UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

267 lines (266 loc) • 10.9 kB
import { createHash } from "node:crypto"; import { ZERO_USAGE } from "../../brain/errors.js"; import { projectToolSchema } from "../../brain/tool-schema-projection.js"; import { buildSessionContext, convertToLlm } from "../../internal/harness.js"; export const REGION_CAUSES = Object.freeze({ params: ["request_policy", "model_namespace", "leg_start_inputs"], system: ["compaction", "leg_start_inputs"], tools: ["tool_table", "leg_start_inputs"], messages: ["history_rewrite", "tool_result_clear", "compaction"], }); const HISTORY_REWRITES = REGION_CAUSES.messages; const SEP = "\n<|m|>"; function messageText(m) { if (m.role === "toolResult") return JSON.stringify([m.role, m.toolCallId, m.toolName, m.content, m.isError]); return JSON.stringify([m.role, m.content]); } export function renderRequest(context, options) { const params = `<|params|>${JSON.stringify({ reasoning: options?.reasoning ?? null })}\n`; const system = `<|system|>${context.systemPrompt ?? ""}\n`; const tools = `<|tools|>${JSON.stringify((context.tools ?? []).map((t) => [t.name, t.description, projectToolSchema(t.parameters)]))}`; const head = params + system + tools; const digests = []; const lengths = []; let chars = head.length; for (const m of context.messages) { const text = SEP + messageText(m); digests.push(createHash("sha256").update(text).digest("hex").slice(0, 32)); lengths.push(text.length); chars += text.length; } return { head, systemAt: params.length, toolsAt: params.length + system.length, digests, lengths, chars }; } function lcp(a, b) { const n = Math.min(a.length, b.length); let i = 0; while (i < n && a.charCodeAt(i) === b.charCodeAt(i)) i++; return i; } export function divergenceOf(prev, now) { if (now.head !== prev.head) { const at = lcp(prev.head, now.head); const region = at < Math.max(prev.systemAt, now.systemAt) ? "params" : at < Math.max(prev.toolsAt, now.toolsAt) ? "system" : "tools"; return { at, of: prev.chars, region }; } let at = prev.head.length; for (let k = 0; k < prev.digests.length; k++) { if (now.digests[k] !== prev.digests[k]) return { at, of: prev.chars, region: "messages", message: k }; at += prev.lengths[k]; } return undefined; } const READINGS = new WeakMap(); export function readingOfUsage(usage) { return usage === undefined ? undefined : READINGS.get(usage); } export function observingBrain(brain, observe) { const tag = (msg, reading) => { if (reading !== undefined && msg.usage !== undefined && msg.usage !== ZERO_USAGE) READINGS.set(msg.usage, reading); return msg; }; return { stream: async (model, context, options) => { const reading = observe(model, context, options); const inner = await Promise.resolve(brain.stream(model, context, options)); const tagged = inner.result().then((msg) => tag(msg, reading)); tagged.catch(() => { }); return { [Symbol.asyncIterator]: () => inner[Symbol.asyncIterator](), result: () => tagged }; }, complete: async (model, context, options) => { const reading = observe(model, context, options); const msg = brain.complete !== undefined ? await brain.complete(model, context, options) : await (await Promise.resolve(brain.stream(model, context, options))).result(); return tag(msg, reading); }, ...(brain.adjudicateRoute !== undefined ? { adjudicateRoute: (model, auth) => brain.adjudicateRoute?.(model, auth) } : {}), }; } export class PrefixChangeSeat { #pending = []; #sink; #published = 0; get published() { return this.#published; } emit(change) { this.#published++; if (this.#sink !== undefined) this.#sink(change); else { this.#pending.push(change); if (this.#pending.length > 64) this.#pending.shift(); } } subscribe(sink) { this.#sink = sink; const pending = this.#pending; this.#pending = []; for (const c of pending) sink(c); } unsubscribe() { this.#sink = undefined; } } export function legPrefixObservers(session, detection) { const ledger = sessionPrefixLedgerOf(session); const changes = new PrefixChangeSeat(); let salt; const observer = (main) => (model, context, options) => { if (!detection || salt === undefined) return undefined; const r = ledger.observe({ model, context, options, main, salt }); if (r.change !== undefined) changes.emit(r.change); return r.reading; }; return { ledger, changes, observeMain: observer(true), observeSide: observer(false), seatSalt: (s) => void (salt = s), }; } export function endPrefixLeg(ledger, leg, approach, session) { if (approach.carried !== undefined) ledger.declare("history_rewrite", { from: "tail" }); if (leg === undefined) return; ledger.closeLeg(new Promise((resolve) => resolve(session.getLeafId())), leg); } const LEDGERS = new WeakMap(); export function sessionPrefixLedgerOf(session) { let ledger = LEDGERS.get(session); if (ledger === undefined) LEDGERS.set(session, (ledger = createSessionPrefixLedger())); return ledger; } export async function branchDeclaration(known, branch, pathOf) { if (known === undefined) return undefined; const at = known === null ? -1 : branch.findIndex((e) => e.id === known); if (known === null || at >= 0) { const after = known === null ? branch : branch.slice(at + 1); return after.some((e) => e.type === "compaction") ? { cause: "compaction", from: 0 } : undefined; } let old; try { old = await pathOf(known); } catch { return { cause: "history_rewrite", from: 0 }; } if (old.length === 0 || old[old.length - 1].id !== known) return { cause: "history_rewrite", from: 0 }; let shared = 0; while (shared < branch.length && shared < old.length && branch[shared].id === old[shared].id) shared++; if (branch.slice(shared).some((e) => e.type === "compaction")) return { cause: "compaction", from: 0 }; if (shared === 0 || old.slice(shared).some((e) => e.type === "compaction")) return { cause: "history_rewrite", from: 0 }; return { cause: "history_rewrite", from: convertToLlm(buildSessionContext([...branch.slice(0, shared)]).messages).length }; } export function createSessionPrefixLedger() { const lastMain = new Map(); let pending = []; let segments; let standsOn; let legs = 0; let closing; const declare = (cause, reach) => { let word = pending.find((w) => w.cause === cause); if (word === undefined) pending.push((word = { cause, from: Infinity, tail: false })); if (reach?.from === "tail") word.tail = true; else word.from = Math.min(word.from, reach?.from ?? 0); if (reach?.segments !== undefined && reach.segments.length > 0) segments = reach.segments; }; return { declare, async openLeg(branchOf, pathOf) { let branchRead; const seat = closing; if (seat !== undefined && !seat.settled) { branchRead = new Promise((resolve) => resolve(branchOf())); const answered = branchRead.then(() => undefined, () => undefined); await Promise.race([seat.read, answered]); if (!seat.settled) { standsOn = undefined; if (closing === seat) closing = undefined; } } else if (seat !== undefined) await seat.read; if (standsOn === undefined) return ++legs; let branch; try { branch = await (branchRead ?? branchOf()); } catch { declare("history_rewrite"); standsOn = undefined; return ++legs; } const said = await branchDeclaration(standsOn, branch, pathOf); if (said !== undefined) declare(said.cause, { from: said.from }); standsOn = branch.length > 0 ? branch[branch.length - 1].id : null; return ++legs; }, closeLeg(leafId, leg) { const settle = (id) => { seat.settled = true; if (leg === legs) standsOn = id; }; const seat = { settled: false, read: leafId.then((id) => settle(typeof id === "string" || id === null ? id : undefined), () => settle(undefined)), }; if (leg === legs) closing = seat; }, observe({ model, context, options, main, salt }) { const now = renderRequest(context, options); const key = `${model.provider}:${model.id}`; const prev = lastMain.get(key); const div = prev === undefined ? undefined : divergenceOf(prev, now); const reading = { head: createHash("sha256").update(salt).update(now.head).digest("hex").slice(0, 16), messages: context.messages.length, chars: now.chars, prefix: prev === undefined ? "no-baseline" : (div ?? "extends"), }; if (!main) return { reading }; const words = pending; const causes = words.map((w) => w.cause); const moved = segments; pending = []; segments = undefined; if (causes.some((c) => HISTORY_REWRITES.includes(c))) lastMain.clear(); lastMain.set(key, now); const tail = prev === undefined ? 0 : prev.digests.length - 1; const covered = (region, message) => words.some((w) => REGION_CAUSES[region].includes(w.cause) && (message === undefined || Math.min(w.from, w.tail ? tail : Infinity) <= message)); if (div !== undefined) return { reading, change: { ...div, ...(moved !== undefined ? { segments: moved } : {}), causes, declared: covered(div.region, div.message) } }; if (prev === undefined && moved !== undefined) { const region = moved.every((s) => s === "tools") ? "tools" : "system"; return { reading, change: { region, segments: moved, causes, declared: covered(region) } }; } return { reading }; }, }; }