@sema-agent/core
Version:
Stateless, task-oriented AI agent core
216 lines (215 loc) • 9.75 kB
JavaScript
import { FAST_MODE_BETA, fastModeReadingOf, fastModeRouteOf } from "../../brain/fast-mode.js";
import { deliverEngineNotice } from "../engine-notice.js";
const FAST_MODE_CHANGED = "model.fast_mode_changed";
const MAX_SESSIONS = 4096;
const routeFacts = (facts, route) => {
const known = facts.routes.get(route);
if (known !== undefined)
return known;
const made = { modelsRefused: new Set() };
facts.routes.set(route, made);
return made;
};
const refusedAt = (facts, route, modelId) => {
const at = facts.routes.get(route);
if (at?.beta === "refused")
return "model_not_allowed";
return at?.refused ?? (at?.modelsRefused.has(modelId) === true ? "model_not_allowed" : undefined);
};
const anySent = (facts) => facts !== undefined && [...facts.routes.values()].some((at) => at.beta !== undefined);
export class SessionFastModeSeats {
#facts = new Map();
peek(key) {
const facts = this.#facts.get(key);
if (facts !== undefined) {
this.#facts.delete(key);
this.#facts.set(key, facts);
}
return facts;
}
hold(key) {
const known = this.peek(key);
if (known !== undefined)
return known;
const facts = { routes: new Map(), requested: false };
this.#facts.set(key, facts);
if (this.#facts.size > MAX_SESSIONS)
this.#facts.delete(this.#facts.keys().next().value);
return facts;
}
}
function sentenceOf(change) {
switch (change.kind) {
case "cooldown":
return (`${change.reason === "rate_limit" ? "Fast limit reached and temporarily disabled" : "Fast mode overloaded and is temporarily unavailable"} · ` +
`resets at ${new Date(change.until).toISOString()}: the provider ${change.reason === "rate_limit" ? "rate-limited" : "was overloaded by"} a fast request, ` +
`so requests go at standard speed until then (the request that met it was sent again at standard speed).`);
case "refused": {
const model = `"${change.modelId}"`;
const rest = `Its requests to that endpoint go at standard speed for the rest of this conversation; turning fast mode off and on again asks once more.`;
const reason = change.reason;
switch (reason) {
case "model_not_allowed":
return (`Using standard speed on ${model} · fast mode wasn't available: its endpoint refused the \`speed\` parameter for it, so the catalog ` +
`entry's fast-mode declaration does not match the endpoint — declare fast mode off for this model, or point the entry at an ` +
`endpoint that serves it. ${rest}`);
case "preference":
return `Fast mode has been disabled by your organization: the endpoint answered that fast mode is not enabled when ${model} asked for it. ${rest}`;
case "extra_usage_disabled":
return `Fast mode requires usage credits: the provider refused fast speed for ${model} under the account's usage credits. ${rest}`;
default: {
const _exhaustive = reason;
return _exhaustive;
}
}
}
case "beta_refused":
return (`Using standard speed on "${change.modelId}" · fast mode wasn't available: its endpoint refused the fast-mode beta header ` +
`(\`${FAST_MODE_BETA}\`) itself. Fast mode is not asked of that endpoint again in this conversation, for any model it ` +
`serves: the engine sends it neither that header nor fast speed; turning fast mode off and on again does not ask there again.`);
case "overage":
return (`${change.cause === "out_of_credits" ? "Fast mode disabled · Out of usage credits" : "Fast mode disabled · usage credit limit reached"}: ` +
`the request to "${change.modelId}" that met it was sent again at standard speed; fast speed is asked for again from the next request. Said once per task.`);
case "cooldown_ended":
return `Fast limit reset · now using fast mode.`;
default: {
const _exhaustive = change;
return _exhaustive;
}
}
}
export function createFastModeLeg(input) {
const { seats, key, model, notices } = input;
const now = input.now ?? Date.now;
let requested = input.requested;
let asked = requested;
let overageSaid = false;
let inFlightAsk;
const toggle = (facts, on) => {
if (facts.requested === on)
return;
facts.requested = on;
delete facts.cooldown;
if (on) {
for (const at of facts.routes.values()) {
delete at.refused;
at.modelsRefused.clear();
}
}
};
const factsNow = () => (requested ? seats.hold(key) : seats.peek(key));
if (input.root) {
const facts = factsNow();
if (facts !== undefined)
toggle(facts, requested);
}
const readingFor = (m, facts, ask = requested) => {
const refused = facts === undefined ? undefined : refusedAt(facts, fastModeRouteOf(m), m.id);
return fastModeReadingOf({ model: m, requested: ask, ...(refused !== undefined ? { refused } : {}), ...(facts?.cooldown !== undefined ? { cooldown: facts.cooldown } : {}), now: now() });
};
const announce = (facts, change) => {
const about = change.kind === "cooldown_ended" ? model().id : change.modelId;
const hopRefused = (change.kind === "refused" || change.kind === "beta_refused") && about !== model().id ? refusedAt(facts, change.route, about) : undefined;
const reading = hopRefused !== undefined ? { state: "off", reason: hopRefused } : readingFor(model(), facts);
deliverEngineNotice(notices.onNotice, {
code: FAST_MODE_CHANGED,
message: sentenceOf(change),
detail: { model: about, ...reading, ...(change.kind === "overage" ? { overage: change.cause } : {}), sessionId: notices.sessionId, runId: notices.runId },
});
};
const observe = (facts, observation) => {
try {
switch (observation.kind) {
case "sent": {
const at = routeFacts(facts, observation.route);
if (at.beta === undefined)
at.beta = "latched";
return;
}
case "beta_refused": {
const at = routeFacts(facts, observation.route);
if (at.beta === "refused")
return;
at.beta = "refused";
announce(facts, observation);
return;
}
case "cooldown":
if (facts.cooldown !== undefined && facts.cooldown.until >= observation.until)
return;
facts.cooldown = { until: observation.until, reason: observation.reason };
announce(facts, observation);
return;
case "refused": {
if (refusedAt(facts, observation.route, observation.modelId) === observation.reason)
return;
const at = routeFacts(facts, observation.route);
if (observation.reason === "model_not_allowed")
at.modelsRefused.add(observation.modelId);
else
at.refused = observation.reason;
announce(facts, observation);
return;
}
case "overage":
if (overageSaid)
return;
overageSaid = true;
announce(facts, observation);
return;
}
}
catch {
}
};
const leg = {
get requested() {
return requested;
},
get engaged() {
return asked || anySent(seats.peek(key));
},
callFor() {
const facts = factsNow();
if (facts === undefined)
return undefined;
if (facts.cooldown !== undefined && facts.cooldown.until <= now()) {
delete facts.cooldown;
if (requested)
announce(facts, { kind: "cooldown_ended" });
}
if (!requested && !anySent(facts))
return undefined;
const askedForCall = requested;
return {
get requested() {
return askedForCall && facts.cooldown === undefined;
},
betaLatchedOn: (route) => facts.routes.get(route)?.beta === "latched",
refusedFor: (route, modelId) => refusedAt(facts, route, modelId),
observe: (observation) => observe(facts, observation),
};
},
mainCallFor() {
inFlightAsk = requested;
return leg.callFor();
},
readingOf(m) {
const facts = seats.peek(key);
return readingFor(m ?? model(), facts);
},
inFlightReadingOf(m) {
return readingFor(m, seats.peek(key), inFlightAsk ?? requested);
},
setRequested(on) {
requested = on;
if (on)
asked = true;
const facts = factsNow();
if (facts !== undefined)
toggle(facts, on);
return readingFor(model(), facts);
},
};
return leg;
}