UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

290 lines (289 loc) • 12.5 kB
import { describeRejectedValue } from "./tool-search-setting.js"; const SEATS = new WeakSet(); export function spendAccountOf(seat) { return typeof seat === "object" && seat !== null && SEATS.has(seat) ? seat : undefined; } export function spendNodeMint(parent, member) { const under = spendParentOf(parent, member); return under === undefined ? () => SpendAccount.root() : () => under.account.child(under.link); } export function spendParentOf(parent, member) { if (parent === undefined) return undefined; if (typeof parent !== "object" || parent === null) { throw Object.assign(new Error(`${member} must be a { seat, link } pair or be left out (got ${describeRejectedValue(parent)}).`), { code: "config.invalid_argument", detail: { field: member } }); } const seat = parent.seat; const link = parent.link; const account = spendAccountOf(seat); if (account !== undefined && (link === "task" || link === "session")) return { account, link }; const field = account === undefined ? `${member}.seat` : `${member}.link`; const got = describeRejectedValue(account === undefined ? seat : link); const message = account === undefined ? `${field} must be the spend seat the engine gave a tool of the run this work belongs to (ToolExecuteContext.spendSeat), handed on as it is (got ${got}) — without it the work would spend outside every ceiling of that run.` : `${field} must be "task" (bound to the end of the run that handed the seat) or "session" (outlives it) (got ${got}).`; throw Object.assign(new Error(message), { code: "config.invalid_argument", detail: { field } }); } export const SPEND_OUTPUT_FLOOR_TOKENS = 1024; export const SPEND_DEFAULT_OUTPUT_TOKENS = 4096; const WAIT_CUTS = new WeakSet(); export function cutWaitingForRoom(reason) { return typeof reason === "object" && reason !== null && WAIT_CUTS.has(reason); } export class SpendAccount { parent; link; ceiling = {}; closed = false; own = { tokens: 0, costMicroUsd: 0, turns: 0 }; subtree = { tokens: 0, costMicroUsd: 0, turns: 0 }; reserved = { tokens: 0, costMicroUsd: 0 }; descendants = 0; firstUnpricedBelow; waiters = new Set(); firstStop; lastAsk; inputScale; constructor(parent, link) { this.parent = parent; this.link = link; this.inputScale = new Map(parent?.inputScale); SEATS.add(this); } static root() { return new SpendAccount(undefined, undefined); } child(link) { for (let n = this; n !== undefined; n = n.parent) n.descendants += 1; return new SpendAccount(this, link); } setCeiling(ceiling) { this.ceiling = { ...(ceiling.tokens !== undefined ? { tokens: ceiling.tokens } : {}), ...(ceiling.costMicroUsd !== undefined ? { costMicroUsd: ceiling.costMicroUsd } : {}) }; } get ceilings() { return this.ceiling; } close() { if (this.closed) return; this.closed = true; this.wakeChain(); } get isClosed() { return this.closed; } get stop() { return this.firstStop; } noteStop(stop) { this.firstStop = stop; } noteTurn() { this.own.turns += 1; for (let n = this; n !== undefined; n = n.parent) n.subtree.turns += 1; } get ownSettled() { return this.own; } get subtreeSettled() { return this.subtree; } get inFlight() { return this.reserved; } nested() { if (this.descendants === 0) return undefined; return { tokens: this.subtree.tokens - this.own.tokens, turns: this.subtree.turns - this.own.turns, tasks: this.descendants, costMicroUsd: this.subtree.costMicroUsd - this.own.costMicroUsd, anyUnpriced: this.firstUnpricedBelow !== undefined, }; } get unpricedBelow() { return this.firstUnpricedBelow; } remaining(axis) { const c = axis === "tokens" ? this.ceiling.tokens : this.ceiling.costMicroUsd; if (c === undefined) return undefined; const used = axis === "tokens" ? this.subtree.tokens + this.reserved.tokens : this.subtree.costMicroUsd + this.reserved.costMicroUsd; return Math.max(0, c - used); } fill() { const next = this.lastAsk; if (next === undefined) return undefined; let tightest; for (let n = this; n !== undefined; n = n.parent) { const t = n.ceiling.tokens; if (t !== undefined && t > 0) { const ratio = (n.subtree.tokens + n.reserved.tokens + next.input + next.floor) / t; if (tightest === undefined || ratio > tightest.ratio) tightest = { axis: "tokens", ratio }; } const c = n.ceiling.costMicroUsd; if (c !== undefined && c > 0) { const ratio = (n.subtree.costMicroUsd + n.reserved.costMicroUsd + next.input * next.inPer + next.floor * next.outPer) / c; if (tightest === undefined || ratio > tightest.ratio) tightest = { axis: "cost", ratio }; } } return tightest; } moneyCeilingOnChain() { for (let n = this; n !== undefined; n = n.parent) if (n.ceiling.costMicroUsd !== undefined) return true; return false; } constrained() { for (let n = this; n !== undefined; n = n.parent) if (n.ceiling.tokens !== undefined || n.ceiling.costMicroUsd !== undefined) return true; return false; } closedHolder() { let shielded = false; for (let n = this; n !== undefined; n = n.parent) { if (n.closed && !shielded) return n; if (n.link === "session") shielded = true; } return undefined; } decide(ask) { const closedAt = this.closedHolder(); if (closedAt !== undefined) { const axis = closedAt.ceiling.tokens === undefined && closedAt.ceiling.costMicroUsd !== undefined ? "cost" : "tokens"; const stop = { axis, limit: (axis === "tokens" ? closedAt.ceiling.tokens : closedAt.ceiling.costMicroUsd) ?? 0, observed: axis === "tokens" ? closedAt.subtree.tokens : closedAt.subtree.costMicroUsd, heldBy: closedAt === this ? "own" : "ancestor", reason: "closed" }; return { kind: "refuse", stop }; } const requested = Math.max(1, Math.floor(ask.outputTokens)); const input = Math.max(0, Math.ceil(ask.inputTokens)); let out = requested; let holder; for (let n = this; n !== undefined; n = n.parent) { if (n.ceiling.tokens !== undefined) { const room = n.ceiling.tokens - n.subtree.tokens - n.reserved.tokens - input; if (room < out) { out = room; holder = { node: n, axis: "tokens" }; } } if (n.ceiling.costMicroUsd !== undefined) { const roomMicro = n.ceiling.costMicroUsd - n.subtree.costMicroUsd - n.reserved.costMicroUsd - input * ask.inputMicroUsdPerToken; const byCost = roomMicro < 0 ? -1 : ask.outputMicroUsdPerToken > 0 ? Math.floor(roomMicro / ask.outputMicroUsdPerToken) : Number.POSITIVE_INFINITY; if (byCost < out) { out = byCost; holder = { node: n, axis: "cost" }; } } } const constrained = this.constrained(); const floor = Math.min(SPEND_OUTPUT_FLOOR_TOKENS, requested); const stopAt = (held) => ({ axis: held.axis, limit: (held.axis === "tokens" ? held.node.ceiling.tokens : held.node.ceiling.costMicroUsd), observed: held.axis === "tokens" ? held.node.subtree.tokens : held.node.subtree.costMicroUsd, heldBy: held.node === this ? "own" : "ancestor", reason: "ceiling", }); if (out >= floor) return { kind: "admit", ticket: this.reserve(input, Math.floor(out), holder !== undefined && out < requested ? () => stopAt(holder) : undefined, constrained, ask) }; const held = holder; if (held.node.reserved.tokens > 0 || held.node.reserved.costMicroUsd > 0) return { kind: "wait", on: held.node }; return { kind: "refuse", stop: stopAt(held) }; } admit(ask, signal) { const requested = Math.max(1, Math.floor(ask.outputTokens)); this.lastAsk = { input: Math.max(0, Math.ceil(ask.inputTokens)), floor: Math.min(SPEND_OUTPUT_FLOOR_TOKENS, requested), inPer: ask.inputMicroUsdPerToken, outPer: ask.outputMicroUsdPerToken }; const first = this.decide(ask); if (first.kind !== "wait") return this.recorded(first); return new Promise((resolve) => { let waitingOn = first.on; const onAbort = () => { waitingOn.waiters.delete(retry); const reason = signal?.reason; if (typeof reason === "object" && reason !== null) WAIT_CUTS.add(reason); resolve({ kind: "refuse", stop: { axis: "tokens", limit: waitingOn.ceiling.tokens ?? 0, observed: waitingOn.subtree.tokens, heldBy: waitingOn === this ? "own" : "ancestor", reason: "closed" } }); }; const retry = () => { waitingOn.waiters.delete(retry); if (signal?.aborted === true) return onAbort(); const next = this.decide(ask); if (next.kind === "wait") { waitingOn = next.on; waitingOn.waiters.add(retry); return; } signal?.removeEventListener("abort", onAbort); resolve(this.recorded(next)); }; if (signal?.aborted === true) return onAbort(); signal?.addEventListener("abort", onAbort, { once: true }); waitingOn.waiters.add(retry); }); } recorded(a) { if (a.kind === "refuse") this.noteStop(a.stop); return a; } reserve(input, out, narrowedBy, constrained, ask) { const hold = { tokens: input + out, costMicroUsd: Math.ceil(input * ask.inputMicroUsdPerToken + out * ask.outputMicroUsdPerToken) }; for (let n = this; n !== undefined; n = n.parent) { n.reserved.tokens += hold.tokens; n.reserved.costMicroUsd += hold.costMicroUsd; } let done = false; const book = (actual) => { if (done) return; done = true; this.own.tokens += actual.tokens; this.own.costMicroUsd += actual.costMicroUsd; for (let n = this; n !== undefined; n = n.parent) { n.reserved.tokens -= hold.tokens; n.reserved.costMicroUsd -= hold.costMicroUsd; n.subtree.tokens += actual.tokens; n.subtree.costMicroUsd += actual.costMicroUsd; if (actual.unpriced !== undefined && n !== this) n.firstUnpricedBelow ??= actual.unpriced; } this.wakeChain(); }; return { outputTokens: out, narrowed: narrowedBy !== undefined, constrained, ...(narrowedBy !== undefined ? { narrowedBy } : {}), settle: (actual) => { const last = this.lastAsk; if (actual.inputTokens !== undefined && last !== undefined && actual.inputTokens > last.input) this.lastAsk = { ...last, input: Math.ceil(actual.inputTokens) }; book({ tokens: Math.max(0, actual.tokens), costMicroUsd: Math.max(0, actual.costMicroUsd), ...(actual.unpriced !== undefined ? { unpriced: actual.unpriced } : {}) }); }, settleAtReservation: (unpriced) => book({ tokens: hold.tokens, costMicroUsd: hold.costMicroUsd, ...(unpriced !== undefined ? { unpriced } : {}) }), }; } wakeChain() { for (let n = this; n !== undefined; n = n.parent) { if (n.waiters.size === 0) continue; for (const w of [...n.waiters]) w(); } } }