UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

355 lines (354 loc) • 20.1 kB
import { sameRouteIdentity } from "../../brain/route-adjudicator.js"; import { engineSeatTier, lowestReasoningSeat } from "../../brain/reasoning-request.js"; import { offSpelling } from "../../brain/reasoning.js"; import { AUTO_MODE_CLASSIFIER_CONTRACT_BROKEN_AFTER, AUTO_MODE_CLASSIFIER_LOW_REASONING_BUDGET_TOKENS, AUTO_MODE_CLASSIFIER_MAX_TOKENS, AUTO_MODE_CLASSIFIER_THINK_BUDGET_TOKENS } from "../auto-mode-defaults.js"; import { AUTO_MODE_RUNG_RATE_LIMITED_CODE, autoModeClassifierFallbackOf, classifierSpendRefusalClause, parseAutoModeResponse } from "../auto-mode.js"; import { CLASSIFIER_REVIEW_SITES, classifierUnavailableDispositionOf } from "../classifier-unavailable-arm.js"; import { catalogModel, DEFAULT_TIER_ORDER, isReceivedCatalog, receiveModelCatalog, receiveRoleMap, resolveTaskModel, roleSpecNamesModel } from "../roles.js"; import { emitTrace } from "../trace.js"; import { deliverEngineNotice } from "../types.js"; export function classifierLadderRungs(knob, classifier, main) { if (autoModeClassifierFallbackOf(knob) === "none") return [classifier]; return sameRouteQuietly(classifier, main) ? [classifier] : [classifier, main]; } function sameRouteQuietly(a, b) { try { return sameRouteIdentity(a, b); } catch { return false; } } export const CLASSIFIER_ROLE_DEFAULT_REASONS = Object.freeze(["tier_below_main", "tier_table", "role_fallback", "main_only", "role_unresolvable"]); export function classifierSeatModel(args) { const { main } = args; const normalized = normalizeSeatDeps(args.deps); const deps = { ...normalized, roles: receiveRoleMap(normalized.roles, "RunnerDeps.roles") }; if (roleSpecNamesModel(deps.roles?.classifier)) { try { return { model: resolveTaskModel({ modelRole: "classifier" }, deps).model }; } catch { return { model: main, defaulted: "role_unresolvable" }; } } const below = tierBelowMain(deps, main); if (below !== undefined) return below; try { const model = resolveTaskModel({ modelRole: "classifier" }, deps).model; if (sameRouteQuietly(model, main)) return { model, defaulted: "main_only" }; return { model, defaulted: deps.tiers !== undefined && Object.keys(deps.tiers).length > 0 ? "tier_table" : "role_fallback" }; } catch { return { model: main, defaulted: "main_only" }; } } export function normalizeSeatDeps(deps) { if (deps.tiers === undefined || isReceivedCatalog(deps.models)) return deps; try { return { ...deps, ...receiveModelCatalog(deps.models, deps.tiers, "RunnerDeps", deps.pricing) }; } catch { return deps; } } function tierModelQuietly(deps, tier) { try { return catalogModel(tier, deps.models, `tiers.${tier}`); } catch { return undefined; } } export function tierIndexOf(deps, model) { if (deps.tiers === undefined || Object.keys(deps.tiers).length === 0 || deps.models === undefined) return undefined; for (let i = DEFAULT_TIER_ORDER.length - 1; i >= 0; i--) { const m = tierModelQuietly(deps, DEFAULT_TIER_ORDER[i]); if (m !== undefined && sameRouteQuietly(m, model)) return i; } return undefined; } function tierBelowMain(deps, main) { const mainTier = tierIndexOf(deps, main); if (mainTier === undefined) return undefined; const bound = DEFAULT_TIER_ORDER.map((tier) => tierModelQuietly(deps, tier)); for (let i = mainTier + 1; i < bound.length; i++) { const m = bound[i]; if (m !== undefined && !sameRouteQuietly(m, main)) return { model: m, defaulted: "tier_below_main" }; } return { model: main, defaulted: "main_only" }; } const OFF_SPELLING_REMEDY = Object.freeze({ "compat.thinkingFormat": "Name a `classifier` role, or declare the model's thinking format (`compat.thinkingFormat`) so the seat can spell off.", "thinkingLevelMap.off": "Name a `classifier` role, or declare the value this endpoint takes for off (`thinkingLevelMap.off`) so the seat can spell off.", none: "No declaration on this model spells off; name a `classifier` role whose model's thinking can be turned off.", }); export function announceClassifierRoleDefaulted(args) { const { seat } = args; if (seat.defaulted === undefined) return; const off = offSpelling(seat.model); deliverEngineNotice(args.onNotice, { code: "classifier.role_defaulted", message: `no classifier role names a model — "${seat.model.id}" classifies this run (${seat.defaulted}); ` + (off.spelled ? "its wire can turn thinking off for the verdict. Name a `classifier` role to classify on another model." : `its wire cannot turn thinking off, so each classification carries a thinking allowance. ${OFF_SPELLING_REMEDY[off.missing]}`), detail: { model: seat.model.id, reason: seat.defaulted, thinkingOffSpelled: off.spelled, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), ...(args.runId !== undefined ? { runId: args.runId } : {}), }, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), }); } export function classifierUnavailableNotice(args) { const whose = args.station === "ancestor" ? "the classifier of the ancestor layer that asked" : "the classifier"; const refusedBySpend = args.site === "call" ? args.refusedBySpend : undefined; const why = refusedBySpend !== undefined ? classifierSpendRefusalClause(refusedBySpend, args.station === "ancestor" ? "the model request of the classifier of the ancestor layer that asked" : "the classifier's model request") : args.cause === "timeout" ? `${whose} did not answer within the deployment's auto-mode time limit for one classification${args.budgetMs !== undefined ? ` (${args.budgetMs} ms)` : ""}` : args.cause === "parse_error" ? args.station === "ancestor" ? `${whose} replied without a verdict` : "the classifier's reply carried no verdict" : `${whose} could not run (error)`; const address = { ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), ...(args.sourceSessionId !== undefined ? { sourceSessionId: args.sourceSessionId } : {}), ...(args.agentId !== undefined ? { agentId: args.agentId } : {}), ...(args.runId !== undefined ? { runId: args.runId } : {}), }; switch (args.site) { case "spawn": case "handback": { const which = `this "${args.toolName}" call${args.subject !== undefined ? ` ("${args.subject}")` : ""}`; const what = args.site === "spawn" ? `auto mode could not review the sub-agent ${which} starts: ${why}, so the sub-agent goes ahead without that review (its own gated calls are still judged one by one).` : `auto mode could not review the work a sub-agent handed back to ${which}: ${why}, so its report was handed to the agent that delegated it, with a note to verify it before acting on it.`; return { code: "classifier.review_skipped", message: `${what} ${DELEGATION_REVIEW_OUTLET[args.cause]}`, detail: { toolName: args.toolName, toolCallId: args.toolCallId, cause: args.cause, site: args.site, disposition: "proceeded", ...address }, }; } case "call": { const seatOwner = args.station === "ancestor" ? "that layer's" : "this run's"; const next = args.route === "live_approver" ? `so the call was handed on to ${seatOwner} live approver rather than refused by the classifier.` : args.route === "policy_seat" ? `so the call was handed on to ${seatOwner} approval policy rather than refused by the classifier.` : args.route === "durable_park" ? `so the call was handed on to ${seatOwner} durable approval park, for a person to answer later, rather than refused by the classifier.` : (args.station === "ancestor" ? "and that layer has no live approver" : "and this run has no approver and no park facility") + ", so the call was refused and did not run." + (args.cause === "timeout" ? " A deployment on a slow gateway raises the budget." : ""); const detail = { toolName: args.toolName, toolCallId: args.toolCallId, cause: args.cause, site: "call", disposition: classifierUnavailableDispositionOf(args.route), ...(refusedBySpend !== undefined ? { refusedBySpend } : {}), ...address }; if (args.route !== "none") return { code: "classifier.unavailable_handed_on", message: `auto mode could not judge "${args.toolName}": ${why}, ${next}`, detail }; return { code: "classifier.unavailable", message: `auto mode could not judge "${args.toolName}": ${why}, ${next}`, detail }; } } } const DELEGATION_REVIEW_OUTLET = { error: "If it keeps happening, the classifier model or its gateway needs checking.", timeout: "The deployment's operator can raise the budget.", parse_error: "If it keeps happening, the classifier model needs to be one that answers in the verdict format.", }; export function classifierUnavailableObserver(args) { const { onNotice, admission, sessionId, sourceSessionId, agentId, runId, station, budgetMs } = args; return (info) => { if (!REVIEW_SITE_SET.has(info.site)) throw new Error(`classifier.unavailable: "${String(info.site)}" is not a classifier site (${CLASSIFIER_REVIEW_SITES.join(" / ")})`); deliverEngineNotice(onNotice, classifierUnavailableNotice({ ...info, station, ...(budgetMs !== undefined ? { budgetMs } : {}), ...(sessionId !== undefined ? { sessionId } : {}), ...(sourceSessionId !== undefined ? { sourceSessionId } : {}), ...(agentId !== undefined ? { agentId } : {}), ...(runId !== undefined ? { runId } : {}) }), admission); }; } const REVIEW_SITE_SET = new Set(CLASSIFIER_REVIEW_SITES); export function delegationReviewSeat(args) { const { decider, legNotice, onNotice, runId } = args; return { decider, unavailable: { onUnavailable: classifierUnavailableObserver({ station: "leg", ...(decider.timeoutMs !== undefined ? { budgetMs: decider.timeoutMs } : {}), onNotice, ...(legNotice.admission !== undefined ? { admission: legNotice.admission } : {}), ...legNotice.route.address, ...(runId !== undefined ? { runId } : {}) }) }, }; } export function classifierUnavailableSeat(args) { const { route, ...observer } = args; return { route, onUnavailable: classifierUnavailableObserver(observer) }; } function classifierFallbackAnnouncer(args) { const announced = new Set(); return (attribution) => { const fallback = attribution?.fallback; if (fallback === undefined) return; const key = `${fallback.from}\u0000${fallback.cause}`; if (announced.has(key)) return; announced.add(key); deliverEngineNotice(args.onNotice, { code: "classifier.fallback", message: `the auto-mode classifier model "${fallback.from}" did not rule (${fallback.cause}) — this run re-asks each gated call on "${fallback.to}". ` + 'Check that the classifier role names a model this deployment\'s gateway serves; set RunnerDeps.autoMode.classifierFallback to "none" to deny instead of falling back.', detail: { from: fallback.from, to: fallback.to, cause: fallback.cause, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), ...(args.runId !== undefined ? { runId: args.runId } : {}), }, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), }); }; } const CONTRACT_MISSES = ["moved_on", "missing", "conflict"]; const CONTRACT_MISS_CLAUSE = { moved_on: (count) => `${count} carried no verdict, and each time the classification moved on to the next classifier model in the ladder`, missing: (count) => `${count} carried no verdict: a gated call it judges goes to the run's approval seat, or is refused where the run has none, and a sub-agent spawn or hand-back it reviews goes ahead without that review`, conflict: (count) => `${count} answered both yes and no: a gated call or a sub-agent spawn it judges is refused, and a hand-back it reviews is flagged`, }; function classifierContractAnnouncer(args) { const streak = new Map(); const announced = new Set(); const noVerdict = (rung, model, miss) => { const key = `${rung}:${model}`; const misses = streak.get(key) ?? { moved_on: 0, missing: 0, conflict: 0 }; misses[miss]++; streak.set(key, misses); const n = CONTRACT_MISSES.reduce((sum, m) => sum + misses[m], 0); if (n < AUTO_MODE_CLASSIFIER_CONTRACT_BROKEN_AFTER || announced.has(key)) return; announced.add(key); const clauses = CONTRACT_MISSES.filter((m) => misses[m] > 0).map((m) => CONTRACT_MISS_CLAUSE[m](misses[m])); deliverEngineNotice(args.onNotice, { code: "classifier.contract_broken", message: `the auto-mode classifier model "${model}" has answered ${n} consecutive classifications without a usable verdict — ${clauses.join("; ")}. ` + "Declare the model's thinking format (`compat.thinkingFormat`) so the seat can turn thinking off, " + "or name a `classifier` role whose model follows the <block> contract.", detail: { model, rung, consecutive: n, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), ...(args.runId !== undefined ? { runId: args.runId } : {}), }, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), }); }; return (info) => { const record = info.classifier; if (record === undefined) return; if (record.fallback?.cause === "parse_error") noVerdict(0, record.fallback.from, "moved_on"); const landed = record.fallback !== undefined ? 1 : 0; if (info.verdict === "parse_error") { if (info.form === undefined) throw new Error("auto_mode.classified: a parse_error record without its form (the decider always states it)"); noVerdict(landed, record.modelUsed, info.form); } else if (info.verdict === "allow" || info.verdict === "block") streak.delete(`${landed}:${record.modelUsed}`); }; } function announceRateLimitBreak(args, brk) { deliverEngineNotice(args.onNotice, { code: "classifier.seat_rate_limited", message: `the auto-mode classifier model "${brk.model}" was rate limited (HTTP 429) on ${brk.consecutive} consecutive classifications — ` + `for the rest of this run it is not asked again, and every gated call is judged on "${brk.to}" without waiting for it. ` + "Raise that model's rate limit at its gateway, or name a different classifier model; the deployment's auto-mode settings decide how many in a row it takes.", detail: { model: brk.model, to: brk.to, rung: brk.rung, consecutive: brk.consecutive, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), ...(args.runId !== undefined ? { runId: args.runId } : {}), }, ...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}), }); } export const CLASSIFIER_OFF_SEAT = { reasoning: "off", maxTokens: AUTO_MODE_CLASSIFIER_MAX_TOKENS }; export const CLASSIFIER_LOW_SEAT = { reasoning: "low", maxTokens: AUTO_MODE_CLASSIFIER_MAX_TOKENS + AUTO_MODE_CLASSIFIER_LOW_REASONING_BUDGET_TOKENS }; export const CLASSIFIER_THINK_SEAT = { reasoning: "low", maxTokens: AUTO_MODE_CLASSIFIER_MAX_TOKENS + AUTO_MODE_CLASSIFIER_THINK_BUDGET_TOKENS }; export function classifierRungSeat(model) { return lowestReasoningSeat(model) === "off" ? CLASSIFIER_OFF_SEAT : CLASSIFIER_LOW_SEAT; } export function classifierSeatOptions(model, seat) { const reasoning = engineSeatTier(model, seat.reasoning); return reasoning === undefined ? { maxTokens: seat.maxTokens } : { reasoning, maxTokens: seat.maxTokens }; } export const CLASSIFIER_ATTEMPT_SUFFIX = { first: '\nErr on the side of blocking. Your ENTIRE response MUST begin with <block>. Do NOT output any analysis, reasoning, or commentary before <block>. No "Looking at..." or similar preamble.', reask: "\nReview the classification process and follow it carefully, making sure you deny actions that should be blocked. As a reminder, explicit (not suggestive or implicit) user confirmation is required to override blocks. Use <thinking> before responding with <block>. Think longer on ambiguous or borderline actions; keep reasoning brief for clear-cut ones.", }; export function classifierReplyText(reply) { return reply.content .filter((c) => c.type === "text") .map((c) => c.text) .join(""); } export function classifierReplyEmptyAtCap(reply) { if (classifierReplyText(reply) !== "") return false; return reply.stopReason === "length" || (reply.stopReason === "error" && reply.errorKind === "length_empty"); } export function classifierReplyTagOnly(reply) { return reply.stopReason === "length" || reply.stopReason === "toolUse" || reply.partialFinalized === true || reply.content.some((c) => c.type === "toolCall"); } export function classifierReplyVerdictText(reply) { const text = classifierReplyText(reply); if (!classifierReplyTagOnly(reply)) return text; const tagged = parseAutoModeResponse(text, { bareAnswer: false }); return tagged.kind === "parse_error" && tagged.form === "missing" ? "" : text; } export function classifierReplyAsksAgain(reply) { if (classifierReplyEmptyAtCap(reply)) return true; const text = classifierReplyVerdictText(reply); if (text === "") return classifierReplyTagOnly(reply) && classifierReplyText(reply) !== ""; const verdict = parseAutoModeResponse(text); return verdict.kind === "parse_error" && verdict.form === "missing"; } export function classifierReplyFailure(reply) { if (reply.stopReason === "aborted") return new Error("the auto-mode classifier request was aborted"); if (reply.stopReason !== "error" || reply.errorKind === "length_empty") return undefined; const failure = new Error(`the auto-mode classifier request failed: ${reply.errorMessage ?? "the model leg reported an error with no message"}`); if (reply.apiErrorStatus === 429) failure.code = AUTO_MODE_RUNG_RATE_LIMITED_CODE; return failure; } export function classifierRoundObserver(args) { const announceFallback = classifierFallbackAnnouncer(args); const countContract = classifierContractAnnouncer(args); return (info) => { emitTrace(args.tracer, () => ({ kind: "auto_mode.classified", version: 1, taskId: args.taskId, toolCallId: info.toolCallId, model: info.classifier?.modelUsed ?? args.seatModelId, ms: info.ms, verdict: info.verdict, ...(info.cause !== undefined ? { cause: info.cause } : {}), ...(info.notAsked !== undefined ? { notAsked: info.notAsked } : {}), ts: Date.now(), })); announceFallback(info.classifier); for (const brk of info.rateLimitBreaks ?? []) announceRateLimitBreak(args, brk); countContract(info); }; }