@sema-agent/core
Version:
Stateless, task-oriented AI agent core
162 lines (161 loc) • 10.1 kB
JavaScript
import { runWithStatusSink } from "../../brain/status-sink.js";
import { malformedPricingField, priceTableOf } from "../pricing.js";
import { refusalAbout } from "../config-refusal-input.js";
import { emitTrace } from "../trace.js";
import { billsOf, priceReply } from "./reply-pricing.js";
import { bookCacheOperands, cacheTraceMembersOf } from "./cache-hit-account.js";
import { cacheFamilyOf } from "./usage-accounting.js";
import { remainingBudgetMicroUsd } from "../checkpoint-store.js";
import { readingOfUsage } from "./prefix-ledger.js";
export const SIDE_CALL_LANE_TOTAL = {
compaction: "compactionMicroUsd",
classifier: "sideCallMicroUsd",
mod: "sideCallMicroUsd",
advisor: "sideCallMicroUsd",
manager: "sideCallMicroUsd",
};
const LANE_MODEL_SEAT = {
compaction: ["the compaction pass's model (the task's main model)", "price the task's main model"],
classifier: ["the permission classifier's model (roles.classifier)", "bind a priced classifier model"],
mod: ["the model of a mod's model call", "have the mod call a priced model"],
advisor: ["the advisor tool's model", "name a priced advisor model"],
manager: ["the manager's model, judging a worker's card (the manager run's main model)", "price the manager run's main model"],
};
export function unpricedCallCause(modelId, tableExists, via) {
const id = JSON.stringify(modelId);
if (via === "below")
return `a run this run started called model ${id}, which ${tableExists ? "was served at fast speed and its price table declares no fast tier with whole rates" : "has no price table (neither a RunnerDeps.pricing entry nor a Model.cost declaration)"}, and that call settled with no cost figure — price it, or keep the runs under this ceiling off it`;
if (tableExists) {
return `model ${id} was served at fast speed and its price table declares no fast tier with whole rates (an empty or partial \`fast\` prices nothing) — declare the tier's rates as \`fast\` on that table (RunnerDeps.pricing[${id}] when the deployment prices the model, else its Model.cost), or declare fast mode off for it`;
}
const none = "has no price table (neither a RunnerDeps.pricing entry nor a Model.cost declaration)";
if (typeof via === "object")
return `model ${id}, a hop of model ${JSON.stringify(via.fallbackOf)}'s fallback chain, ${none} — price it, or take it off that chain (\`fallbacks\`)`;
if (via === "degrade")
return `model ${id}, the near-budget degrade target (TaskSpec.limits.degrade.to), ${none} — price it, or name a priced target`;
if (via === "main")
return `model ${id}, the run's own model, ${none} — price it`;
const [what, fix] = LANE_MODEL_SEAT[via];
return `model ${id}, ${what}, ${none} — price it, or ${fix}`;
}
export function noteUnpricedSpend(telemetry, cause) {
telemetry.unpricedSpend = true;
telemetry.unpricedCause ??= cause;
}
export function ownMoneyCeiling(spec, ledger) {
const total = ledger !== undefined ? remainingBudgetMicroUsd(ledger) !== undefined : spec.resourceSuspend?.totalBudgetUsd !== undefined;
const own = spec.limits?.maxCostUsd !== undefined ? "limits.maxCostUsd" : total ? "resourceSuspend.totalBudgetUsd" : undefined;
return own === undefined ? undefined : `TaskSpec.${own} is a money ceiling`;
}
export function enclosingMoneyCeiling(under) {
return under?.moneyCeilingOnChain() === true ? "An enclosing run's money ceiling holds what this run spends" : undefined;
}
export function moneyCeilingOver(spec, ledger, under) {
return ownMoneyCeiling(spec, ledger) ?? enclosingMoneyCeiling(under);
}
export function unpricedModelRefusal(held, model, pricing, modelInput) {
if (held === undefined)
return undefined;
const priced = priceTableOf(model, pricing);
if (!priced.exists)
return refusalAbout(priceTableInput(priced, modelInput), uncountedSpendRefusal(held, unpricedCallCause(model.id, false, "main"), "start"));
const bad = malformedPricingField(priced.table);
if (bad === undefined)
return undefined;
const why = `the price table for model ${JSON.stringify(model.id)} declares an unevaluable ${bad} — every rate must be a finite, non-negative number of USD per 1M tokens`;
return refusalAbout(priceTableInput(priced, modelInput), Object.assign(new Error(`${held}, but ${why}. A table like this prices every turn at zero (or below), so the ceiling would never trip: refused rather than enforced in name only.`), { code: "config.limit_invalid" }));
}
export function priceTableInput(table, modelInput) {
return table.from === "deployment" ? "deps" : modelInput;
}
export function uncountedSpendRefusal(held, why, when) {
const tail = when === "start" ? "so the run is refused before its first request rather than spend past it" : "so the run stops at this turn's end rather than spend past it; the work done so far is kept";
return Object.assign(new Error(`${held}, but ${why}. The ceiling can no longer count what the run spends, ${tail}.`), { code: "config.limit_invalid" });
}
export function costFigureOf(telemetry, costMicroUsd) {
return telemetry.unpricedSpend ? { unpricedBecause: telemetry.unpricedCause ?? "a call this run made settled with no cost figure" } : costMicroUsd;
}
export function recordSideCallUsage(stats, usage, lane, call) {
if (usage === undefined || call.usageMissing === true)
stats.usageMissing = true;
const { account } = call;
if (usage === undefined) {
const { modelId, price, priced, tableExists } = priceReply({}, call.model, account.pricing(), true);
if (!priced)
noteUnpricedSpend(account.telemetry, unpricedCallCause(modelId, tableExists, lane));
account.noteUnevaluablePriceTable(price);
bookCacheOperands(stats, lane, undefined, true, 0);
return;
}
const { modelId, served, price, priced, tableExists, totalInputTokens, uncachedInputTokens, costMicroUsd } = priceReply(usage, call.model, account.pricing(), call.usageMissing === true);
if (!priced)
noteUnpricedSpend(account.telemetry, unpricedCallCause(modelId, tableExists, lane));
account.noteUnevaluablePriceTable(price);
stats.tokens += usage.totalTokens || 0;
stats.promptTokens += uncachedInputTokens;
stats.totalInputTokens += totalInputTokens;
stats.cachedTokens += usage.cacheRead ?? 0;
stats.cacheWriteTokens += usage.cacheWrite ?? 0;
stats.cacheWriteTokensLong += usage.cacheWriteLong ?? 0;
bookCacheOperands(stats, lane, { family: cacheFamilyOf(call.model), usage }, call.usageMissing === true, totalInputTokens);
stats.outputTokens += usage.output || 0;
stats.costMicroUsd += costMicroUsd;
const total = SIDE_CALL_LANE_TOTAL[lane];
stats[total] = (stats[total] ?? 0) + costMicroUsd;
emitSideCallRow(account.telemetry, lane, usage, { modelId, provider: served.provider, uncachedInputTokens, totalInputTokens, ...(priced ? { costMicroUsd } : {}), ...(call.stopReason !== undefined ? { stopReason: call.stopReason } : {}) });
}
function emitSideCallRow(telemetry, lane, usage, priced) {
const request = readingOfUsage(usage);
emitTrace(telemetry.tracer, () => ({
kind: "brain.call", version: 1, taskId: telemetry.taskId, model: priced.modelId, lane, provider: priced.provider,
promptTokens: priced.uncachedInputTokens, totalInputTokens: priced.totalInputTokens, completionTokens: usage.output || 0,
...cacheTraceMembersOf(usage),
latencyMs: 0, ...(priced.costMicroUsd !== undefined ? { costMicroUsd: priced.costMicroUsd } : {}), ...(priced.stopReason !== undefined ? { stopReason: priced.stopReason } : {}),
...(request !== undefined ? { request } : {}),
ts: Date.now(),
}));
}
export function emitSuggestionsRow(telemetry, reply, model, pricing) {
const priced = priceReply(reply.usage, model, pricing, false);
emitSideCallRow(telemetry, "suggestions", reply.usage, { modelId: priced.modelId, provider: priced.served.provider, uncachedInputTokens: priced.uncachedInputTokens, totalInputTokens: priced.totalInputTokens, ...(priced.priced ? { costMicroUsd: priced.costMicroUsd } : {}), ...(typeof reply.stopReason === "string" ? { stopReason: reply.stopReason } : {}) });
}
export function derivedLegBrain(brainOf, lane, book, fastModeOf) {
const shielded = (fn) => runWithStatusSink(() => { }, fn);
const withFastMode = (o) => {
const fastMode = fastModeOf?.();
return fastMode === undefined ? o : { ...o, fastMode };
};
return {
stream: (m, c, o) => shielded(async () => {
const inner = await Promise.resolve(brainOf().stream(m, c, withFastMode(o)));
const booked = inner.result().then((msg) => {
book(lane, m, msg);
return msg;
});
booked.catch(() => { });
return { [Symbol.asyncIterator]: () => inner[Symbol.asyncIterator](), result: () => booked };
}),
complete: async (m, c, o0) => {
const brain = brainOf();
const o = withFastMode(o0);
const msg = await shielded(async () => (brain.complete ? await brain.complete(m, c, o) : await (await Promise.resolve(brain.stream(m, c, o))).result()));
book(lane, m, msg);
return msg;
},
};
}
export function sideCallBookOf(stats, account) {
return (lane, model, reply) => {
const { reading, bills } = billsOf(model, reply);
const entries = reply?.usage === undefined ? [...bills, { model: reading.served }] : bills;
entries.forEach((entry, i) => {
recordSideCallUsage(stats, entry.usage, lane, {
model: entry.model,
account,
...(entry.usageMissing === true ? { usageMissing: true } : {}),
...(i === entries.length - 1 && typeof reply?.stopReason === "string" ? { stopReason: reply.stopReason } : {}),
});
});
account.noteFallback?.(lane, model, reading, reply);
};
}