UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

378 lines (377 loc) • 15.7 kB
import { randomUUID } from "node:crypto"; import { deliverEngineNotice } from "../engine-notice.js"; import { strayMembersOf } from "../own-property-receipt.js"; import { isPlainRecord } from "./kernel/receive.js"; import { modsInvalid } from "./kernel/registration.js"; import { dispatchClassic, ENGINE_CORE_ANSWER, failedHandlerClause } from "./stations.js"; const EVENT = "classic.MessageDisplay"; export const MESSAGE_DISPLAY_PACE = Object.freeze({ intervalMs: 100, inFlight: 3, windowMs: 10_000 }); const SENTENCES = typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity: "sentence" }) : undefined; export function settledEnd(text, from) { const line = text.lastIndexOf("\n") + 1; let sentence = from; if (SENTENCES !== undefined && text.length > from) { for (const s of SENTENCES.segment(text.slice(from))) sentence = from + s.index; } return Math.max(from, line, sentence); } const DISPLAY_FORM = "classic.MessageDisplay takes { displayContent?: string } (a plain object, no other member)"; const DISPLAY_ANSWER_KEYS = Object.freeze(["displayContent"]); const DISPLAY_ANSWER_WORDS = Object.freeze({ subject: "a classic.MessageDisplay answer", unit: "member", moment: "when the handler answers" }); export function displayAnswerViolation(answer) { if (!isPlainRecord(answer)) return DISPLAY_FORM; const stray = strayMembersOf(answer, DISPLAY_ANSWER_WORDS, DISPLAY_ANSWER_KEYS); if (stray !== undefined) return stray.sentence; const shown = answer["displayContent"]; return shown === undefined || typeof shown === "string" ? undefined : `answered a ${typeof shown} "displayContent"; it is a string`; } function shownBy(answer, delta) { if (answer === ENGINE_CORE_ANSWER || !isPlainRecord(answer)) return delta; const shown = answer.displayContent; return typeof shown === "string" ? shown : delta; } const RANKS = Object.freeze({ of: (a) => (isPlainRecord(a) && a["displayContent"] === "" ? 1 : 0), top: 1 }); export function refuseDisplayWithoutSentences(bus, legEvents, sentencesReadable = SENTENCES !== undefined) { if (legEvents.display === undefined || sentencesReadable || !bus.hasHandlers(EVENT)) return; throw modsInvalid("a classic.MessageDisplay handler is mounted, and this runtime has no Intl.Segmenter: the display's window edge is a sentence end, which needs a node built with ICU (every official build is)"); } const WALL_CLOCK = Object.freeze({ now: () => Date.now(), after: (ms, fn) => { const t = setTimeout(fn, Math.max(0, ms)); return () => clearTimeout(t); }, }); export function openMessageDisplay(input) { if (input.legEvents.display === undefined) return undefined; const clock = input.clock ?? WALL_CLOCK; const mintId = input.mintId ?? randomUUID; const pace = MESSAGE_DISPLAY_PACE; const messages = []; const byEntry = new Map(); let current; const textFrame = (delta) => ({ type: "text_delta", delta, ...input.ident() }); const closeFrame = (content) => ({ type: "text_end", content, ...input.ident() }); const drop = (m) => { if (m.dropped) return; m.dropped = true; m.timer?.(); m.timer = undefined; m.stop.abort(); for (const r of m.runs) r.slot?.fill([]); m.runs.length = 0; m.finalSlot?.fill([]); m.finish(); }; input.runEnd.listen(input.signal, () => { for (const m of [...messages]) drop(m); }); const open = (whole) => { let resolveDone; const done = new Promise((resolve) => (resolveDone = resolve)); const finish = () => { const i = messages.indexOf(m); if (i !== -1) messages.splice(i, 1); resolveDone(); }; const m = { id: mintId(), turn: input.turn(), live: input.bus.hasHandlers(EVENT), whole, stop: new AbortController(), raw: "", blockStart: 0, dispatched: 0, released: 0, index: 0, inFlight: 0, lastRaisedAt: undefined, settled: [], runs: [], finalSlot: undefined, timer: undefined, ended: false, finalRaised: false, dropped: false, chain: Promise.resolve(), segment: "", shown: "", by: [], changed: false, done, finish, }; if (!m.live) { resolveDone(); return m; } messages.push(m); if (input.signal.aborted) drop(m); return m; }; const growing = (m) => { const last = m.runs.at(-1); return last !== undefined && last.to === undefined ? last : undefined; }; const runOf = (m, start, end) => m.runs.find((r) => r.from <= start && (r.to === undefined || start < r.to || (r.from === r.to && start === r.to && end === start))); const windowFrom = (m, from) => { if (m.finalRaised || (m.whole && !m.ended)) return undefined; const close = m.runs.find((r) => r.closes && r.to > from); if (close !== undefined) { const at = close.to; if (at < m.raw.length || m.ended) return { end: at, final: m.ended && at === m.raw.length }; const end = settledEnd(m.raw, from); return end > from && end < at ? { end, final: false } : undefined; } if (m.ended) return { end: m.raw.length, final: true }; const end = settledEnd(m.raw, from); return end > from ? { end, final: false } : undefined; }; const nextWindow = (m) => windowFrom(m, m.dispatched); const noteSettled = (m) => { let to = m.dispatched; for (;;) { const w = windowFrom(m, to); if (w === undefined) break; if (w.final) { to = m.raw.length + 1; break; } if (w.end <= to) break; to = w.end; } if (to > (m.settled.at(-1)?.to ?? m.dispatched)) m.settled.push({ to, at: clock.now() }); }; const deadlineOf = (m, start) => (m.settled.find((s) => s.to > start)?.at ?? clock.now()) + pace.windowMs; const pump = (m) => { while (!m.dropped && m.inFlight < pace.inFlight) { const next = nextWindow(m); if (next === undefined) return; if (!next.final && !m.ended && m.lastRaisedAt !== undefined) { const wait = Math.min(pace.intervalMs - (clock.now() - m.lastRaisedAt), deadlineOf(m, m.dispatched) - clock.now()); if (wait > 0) { m.timer ??= clock.after(wait, () => { m.timer = undefined; pump(m); }); return; } } raise(m, next.end, next.final); } }; const raise = (m, end, final) => { const start = m.dispatched; const delta = m.raw.slice(start, end); const index = m.index++; const deadline = deadlineOf(m, start); m.dispatched = end; m.inFlight += 1; if (final) m.finalRaised = true; const run = runOf(m, start, end); if (run !== undefined && run.to === undefined && end === m.raw.length) run.to = end; while (m.settled.length > 0 && m.settled[0].to <= end) m.settled.shift(); noteSettled(m); const answered = answer(m, { messageId: m.id, turn: m.turn, index, final, delta }, deadline); m.chain = m.chain.then(async () => release(m, await answered, run, end, final)).catch(() => drop(m)); }; const answer = async (m, w, deadline) => { const remaining = deadline - clock.now(); if (remaining <= 0) return shownOf(w, undefined, [{ w, why: "deadline" }]); m.lastRaisedAt = clock.now(); const late = new AbortController(); const cancelTimer = clock.after(remaining, () => late.abort()); const signal = AbortSignal.any([input.signal, m.stop.signal, late.signal]); let outcome; try { outcome = await dispatchClassic(input.bus, EVENT, { ...input.base(), ...w }, { signal, checkAnswer: (a) => displayAnswerViolation(a), ranks: RANKS }).catch(() => "fault"); } finally { cancelTimer(); } if (outcome === undefined) return { text: w.delta, changed: false }; if (outcome === "fault") return shownOf(w, undefined, [{ w, why: "fault" }]); const skipped = outcome.skipped.map((why) => ({ w, why })); if (outcome.kind === "answered") return shownOf(w, outcome, skipped); if (outcome.kind === "failed") return shownOf(w, undefined, [...skipped, { w, why: outcome }]); if (input.signal.aborted || m.stop.signal.aborted) return { text: "", changed: false }; return shownOf(w, outcome.lastAnswer, [...skipped, { w, why: "deadline" }]); }; const shownOf = (w, stood, unapplied) => { const text = stood === undefined ? w.delta : shownBy(stood.answer, w.delta); const said = unapplied.length > 0 ? { unapplied } : {}; return text === w.delta ? { text, changed: false, ...said } : { text, changed: true, ...(stood?.answeredBy !== undefined ? { by: stood.answeredBy } : {}), ...said }; }; const say = (w, why, changed) => { const failed = typeof why === "object" ? why : undefined; const clause = failed !== undefined ? `its message-display handler ${failedHandlerClause(failed)}` : why === "deadline" ? `its handlers had not all answered within ${pace.windowMs / 1000} s of its text settling` : "the engine could not raise it"; deliverEngineNotice(input.onNotice, { code: "mods.display_withheld", message: `a window of the assistant's message (window ${w.index}${w.final ? ", its last" : ""}) was shown ${changed ? "as the handlers that answered left it" : "as the model wrote it"}: ${clause}`, detail: { messageId: w.messageId, turn: w.turn, index: w.index, final: w.final, cause: failed !== undefined ? failed.cause : why, ...(failed !== undefined ? { registration: failed.registration } : {}), sessionId: input.sessionId, }, sessionId: input.sessionId, }); }; const release = (m, shown, run, end, final) => { m.inFlight -= 1; if (m.dropped) return; m.released = end; for (const u of shown.unapplied ?? []) say(u.w, u.why, shown.changed); if (shown.changed) { m.changed = true; if (shown.by !== undefined && !m.by.includes(shown.by)) m.by.push(shown.by); } m.shown += shown.text; m.segment += shown.text; const frames = shown.text !== "" ? [textFrame(shown.text)] : []; if (run === undefined) { m.finalSlot?.fill(frames); } else if (run.to === end && run.closes) { fillClose(m, run, frames); } else if (run.to === end) { run.slot?.fill(frames); forget(m, run); } else { run.slot?.put(frames); } showDueCloses(m); if (final) { m.finish(); return; } pump(m); }; const fillClose = (m, run, before) => { run.slot?.fill(m.segment !== "" ? [...before, closeFrame(m.segment)] : before); m.segment = ""; forget(m, run); }; const forget = (m, run) => { const i = m.runs.indexOf(run); if (i !== -1) m.runs.splice(i, 1); }; const showDueCloses = (m) => { for (const run of [...m.runs]) { if (run.closes && run.from === run.to && m.released >= run.to && m.raw.length > run.to) fillClose(m, run, []); } }; const display = { begin(options) { if (current !== undefined && !current.ended) drop(current); current = open(options?.whole === true); }, text(delta) { const m = current ?? (current = open(false)); if (!m.live) { input.push(textFrame(delta)); return; } if (m.ended || delta === "") return; if (m.dropped) { m.raw += delta; return; } if (growing(m) === undefined) m.runs.push({ from: m.raw.length, to: undefined, closes: false, slot: input.reserve() }); m.raw += delta; showDueCloses(m); noteSettled(m); pump(m); }, blockEnd(content) { const m = current ?? (current = open(false)); if (!m.live) { input.push(closeFrame(content)); return; } if (m.ended) return; const streamed = m.raw.slice(m.blockStart); if (content.length > streamed.length && content.startsWith(streamed)) display.text(content.slice(streamed.length)); if (m.dropped) { m.blockStart = m.raw.length; return; } if (m.raw.length === m.blockStart) return; const run = growing(m); if (run !== undefined) { run.to = m.raw.length; run.closes = true; } else { m.runs.push({ from: m.raw.length, to: m.raw.length, closes: true, slot: input.reserve() }); } m.blockStart = m.raw.length; noteSettled(m); pump(m); }, end(entryId) { const m = current; current = undefined; if (m === undefined || !m.live || m.ended) return; m.ended = true; if (entryId !== undefined) byEntry.set(entryId, m); if (m.dropped) return; if (m.raw === "") { m.finalRaised = true; m.finish(); return; } if (runOf(m, m.dispatched, m.raw.length) === undefined) m.finalSlot = input.reserve(); noteSettled(m); pump(m); }, settled() { if (current !== undefined) display.end(undefined); return messages.length === 0 ? undefined : Promise.all(messages.map((m) => m.done)).then(() => undefined); }, displayedOf(entryIds) { if (entryIds === undefined || entryIds.length === 0) return undefined; const read = entryIds.map((id) => byEntry.get(id)); if (read.some((m) => m === undefined)) return undefined; const shown = read; if (!shown.some((m) => m.changed || m.dropped)) return undefined; const by = []; for (const m of shown) for (const b of m.by) if (!by.includes(b)) by.push(b); return { text: shown.map((m) => m.shown).join(""), by, ...(shown.some((m) => m.dropped && m.raw.slice(m.released).trim() !== "") ? { inPart: true } : {}) }; }, }; return display; }