UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

76 lines (75 loc) • 3.03 kB
import { engineTextFor, shippedReadings } from "../../prompt-assembly/engine-text.js"; import { modelsPrefix } from "./turn-attachments.js"; function replayReadings(say) { return [say, ...shippedReadings()]; } export function listingReplayHeaders(headersOf, say) { const all = replayReadings(say).map(headersOf); return { initial: [...new Set(all.map((h) => h.initial))], delta: [...new Set(all.map((h) => h.delta))], removed: [...new Set(all.map((h) => h.removed))] }; } export function replayAnnouncedListing(texts, headers) { let announced; const namesFrom = (text, from) => { const names = []; for (const raw of text.slice(from).split("\n")) { const line = raw.trimEnd(); if (line === "" && names.length > 0) break; const m = /^- ([^:\n]+?)(?::.*)?$/.exec(line); if (m) names.push(m[1].trim()); else if (line !== "" && names.length > 0) break; } return names; }; const kinds = [ ["initial", headers.initial], ["delta", headers.delta], ["removed", headers.removed], ]; for (const text of texts) { const frames = []; let at = 0; while (at < text.length) { let best; for (const [kind, list] of kinds) for (const h of list) if (h !== "" && text.startsWith(h, at) && (best === undefined || at + h.length > best.end)) best = { end: at + h.length, kind }; if (best !== undefined) frames.push(best); at = text.indexOf("\n", best?.end ?? at) + 1 || text.length; } for (const f of frames) { const names = namesFrom(text, f.end); if (f.kind === "initial") announced = new Set(names); else { announced = announced ?? new Set(); for (const n of names) if (f.kind === "delta") announced.add(n); else announced.delete(n); } } } return announced; } export function replayAnnouncedModels(texts, say = engineTextFor()) { const forms = replayReadings(say).map((r) => ({ prefix: modelsPrefix(r), none: r("core/event.agent-listing.models-none") })); let last; for (const text of texts) { const hits = []; for (const f of forms) for (let at = text.indexOf(f.prefix); at !== -1; at = text.indexOf(f.prefix, at + f.prefix.length)) hits.push({ at, ...f }); for (const { at, prefix, none } of hits.sort((a, b) => a.at - b.at)) { const lineEnd = text.indexOf("\n", at); const value = text.slice(at + prefix.length, lineEnd === -1 ? undefined : lineEnd).trim(); last = value === none ? [] : value.split(",").map((s) => s.trim()).filter((s) => s !== ""); } } return last; }