UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

195 lines (194 loc) • 10.1 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { compactionCutOf } from "../auto-compaction.js"; import { describeThrown } from "../tool-policy.js"; import { foreignLine } from "../protocol-http-auth.js"; import { ENGINE_ORIGIN } from "./kernel/index.js"; import { isPlainRecord } from "./kernel/receive.js"; import { NEXT_IN_FLIGHT, sameModData } from "./kernel/site-rules.js"; import { classicEventBase, failedHandlerClause, seatHears } from "./stations.js"; const FORM = "session.compact takes next(e), the outcome next answered, or { skip: <reason> } / { summary: <text> } in place of next"; const onlyString = (a, key) => { if (!isPlainRecord(a) || Object.keys(a).length !== 1 || !Object.hasOwn(a, key)) return undefined; const v = a[key]; return typeof v === "string" && v.trim() !== "" ? v : undefined; }; const skipOf = (a) => onlyString(a, "skip"); const summaryOf = (a) => onlyString(a, "summary"); const RANKS = Object.freeze({ of: (a) => (skipOf(a) !== undefined ? 1 : 0), top: 1 }); function outcomeView(result, outcome) { return Object.freeze({ outcome, ...(result?.compacted === true && result.tokensBefore !== undefined ? { tokensBefore: result.tokensBefore } : {}), ...(result?.compacted === true && result.freedTokens !== undefined ? { freedTokens: result.freedTokens } : {}), }); } const outcomeOf = (r) => (r.compacted ? "compacted" : r.blocked === true ? "blocked" : r.disabled === true ? "disabled" : "noop"); export function createCompactStation() { let bound; const windows = new AsyncLocalStorage(); const compactBound = async (binding, opts, run, pass) => { let settle; const settled = new Promise((resolve) => (settle = resolve)); let dispatch; let handed; let view; const innerPre = opts.preCompact; const innerPost = opts.postCompact; const preCompact = async (ctx) => { let started; const go = new Promise((resolve) => (started = resolve)); const e = { ...classicEventBase(binding.identity), trigger: ctx.trigger, ...(pass?.instructions !== undefined ? { instructions: pass.instructions } : {}) }; const bottom = async () => { let r; try { r = innerPre !== undefined ? ((await innerPre(ctx)) ?? undefined) : undefined; } finally { started(r); } return settled; }; const checkAnswer = (a, _e, _by, below, ran) => { if (view !== undefined && (a === view || sameModData(a, view))) return undefined; const skip = skipOf(a) !== undefined; const summary = summaryOf(a) !== undefined; if (!skip && !summary) return below.length === 0 ? FORM : "an answer other than the outcome next answered (the answer is the pass's outcome)"; if (below.includes(NEXT_IN_FLIGHT)) return "an answer while its next(e) still runs"; if (ran.bottomStarted || below.some((b) => skipOf(b) === undefined && summaryOf(b) === undefined)) return skip ? "a skip after next() compacted (the compaction happened beneath it; skip before calling next, or hand its outcome up)" : "a summary after next() (hand the summary in place of next)"; return undefined; }; try { dispatch = binding.bus.dispatch("session.compact", e, { bottom, checkAnswer, ranks: RANKS, ...(pass?.call !== undefined ? { frames: pass.call.frames, origin: pass.call.origin, signal: pass.call.signal } : opts.signal !== undefined ? { signal: opts.signal } : {}), }); } catch (err) { return refused(ctx, `the session.compact station could not be raised (${describeThrown(err)})`, true); } const first = await Promise.race([go.then((r) => ({ kind: "go", r })), dispatch.then((o) => ({ kind: "ended", o }))]); if (first.kind === "go") return first.r; const o = first.o; if (o.kind === "aborted") return opts.signal?.aborted === true ? undefined : refused(ctx, "the session.compact dispatch was cancelled before the compaction ran", false); if (o.kind === "failed") return refused(ctx, `a session.compact extension ${failedHandlerClause(o)} before the compaction ran`, o.cause === "violation"); const by = o.answeredBy ?? ENGINE_ORIGIN.plugin; const skip = skipOf(o.answer); if (skip !== undefined) return refused(ctx, `extension "${foreignLine(by, 80)}" skipped this compaction: ${foreignLine(skip, 300)}`, false); const summary = summaryOf(o.answer); if (summary !== undefined) { handed = { summary, by }; return undefined; } return refused(ctx, `extension "${foreignLine(by, 80)}" answered in a form session.compact does not take`, true); }; const refused = async (ctx, why, unsaid) => { if (ctx.trigger !== "forced") { if (unsaid) binding.report(new Error(`session.compact: ${why} — the compaction was blocked (fail-closed)`)); return { block: why }; } binding.report(new Error(`session.compact: ${why} — ignored: a forced compaction (prompt-too-long recovery or trim pressure) is not optional`)); return innerPre !== undefined ? ((await innerPre(ctx)) ?? undefined) : undefined; }; const station = { ...opts, preCompact, summaryProvider: (input) => (handed !== undefined ? handed.summary : (opts.summaryProvider?.(input) ?? undefined)), ...(innerPost !== undefined ? { postCompact: (ctx) => (handed !== undefined ? undefined : innerPost(ctx)) } : {}), }; let result; try { result = await run(station); view = outcomeView(result, outcomeOf(result)); if (handed !== undefined && result.compacted && result.reused !== true) { binding.report(new Error(`session.compact: the summary extension "${foreignLine(handed.by, 80)}" handed was not used — this pass could not take a summary in place of its own (the summary seat's reuse cap), so the model summarized`)); } return result; } catch (err) { view = outcomeView(undefined, compactionCutOf(err) === "failed" ? "failed" : "mooted"); throw err; } finally { settle(view ?? outcomeView(undefined, "failed")); if (dispatch !== undefined) await dispatch.catch(() => undefined); } }; const refuseCall = (by, why) => { const sentence = `${by}: $.session.compact: ${why}`; bound?.report(new Error(sentence)); throw new Error(sentence); }; return { bind: (binding) => { bound = binding; }, compact: (opts, run, pass) => { const binding = bound; return seatHears(binding, "session.compact") ? compactBound(binding, opts, run, pass) : run(opts); }, window: async (pass, raise) => { const w = { pass, open: true, running: undefined }; try { return await windows.run(w, raise); } finally { w.open = false; if (w.running !== undefined) await w.running.catch(() => undefined); } }, call: async (instructions, ctx) => { const by = ctx.origin.plugin; const w = windows.getStore(); const direct = ctx.frames.length >= 2 && ctx.frames.at(-1)?.kind === "dollar" && ctx.frames.slice(0, -1).every((f) => f.kind === "handler"); if (w !== undefined && !w.open) return refuseCall(by, "called after the turn.complete dispatch it was made in had ended; the conversation compacts between turns, so call it from turn.complete or later"); if (w === undefined || !direct) return refuseCall(by, "not called from a turn.complete handler; the conversation compacts between turns, so call it from turn.complete or later"); if (w.running !== undefined) return refuseCall(by, "a compaction is already running at this boundary"); const running = w.pass({ ...(instructions !== undefined ? { instructions } : {}), requestedBy: Object.freeze({ kind: "extension", name: by }), call: ctx }); w.running = running; try { return await running; } finally { w.running = undefined; } }, }; } export function requesterOf(waiters) { for (let i = waiters.length - 1; i >= 0; i--) { const by = waiters[i]?.requestedBy; if (by !== undefined) return { requestedBy: by }; } return {}; } export function createSessionCompactEntry(station) { return async (args, ctx) => { const by = ctx.origin.plugin; const extra = Object.keys(args).find((k) => k !== "instructions"); if (extra !== undefined) throw new TypeError(`${by}: $.session.compact takes { instructions } (a string) or nothing; "${foreignLine(extra, 40)}" is not one`); const instructions = args["instructions"]; if (instructions !== undefined && typeof instructions !== "string") throw new TypeError(`${by}: $.session.compact takes { instructions } (a string) or nothing`); const outcome = await station.call(instructions, ctx); return Object.freeze({ outcome }); }; }