UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

634 lines (633 loc) • 31.1 kB
import { AUTO_MODE_DEFAULT_TIMEOUT_MS, AUTO_MODE_DENIAL_AUTO_DENY_DEFAULT_MS, AUTO_MODE_DENIAL_LIMIT_DEFAULTS, AUTO_MODE_RATE_LIMIT_BREAK_AFTER_DEFAULT } from "./auto-mode-defaults.js"; import { withStatusSeat } from "../brain/status-sink.js"; import { thrownIs } from "./thrown-value.js"; import { describeRejectedValue } from "./tool-search-setting.js"; import { isPlainRecord } from "./mods/kernel/receive.js"; import { optionKeys, receiptRefusal, receiveMembers, refuseProxy } from "./own-property-receipt.js"; import { callerKey } from "./caller-text.js"; import { foreignLine } from "./protocol-http-auth.js"; import { classifierCategoryOf, isClassifierCategory } from "./classifier-category.js"; import { cutWaitingForRoom } from "./spend-account.js"; export const AUTO_MODE_UNAVAILABLE_CAUSES = Object.freeze(["error", "timeout"]); const AUTO_MODE_UNAVAILABLE_CAUSE_SET = new Set(AUTO_MODE_UNAVAILABLE_CAUSES); export function isAutoModeUnavailableCause(v) { return AUTO_MODE_UNAVAILABLE_CAUSE_SET.has(v); } export const AUTO_MODE_PARSE_FAILURES = Object.freeze(["missing", "conflict"]); const AUTO_MODE_PARSE_FAILURE_SET = new Set(AUTO_MODE_PARSE_FAILURES); export function isAutoModeParseFailure(v) { return AUTO_MODE_PARSE_FAILURE_SET.has(v); } export const AUTO_MODE_FALLBACK_CAUSES = Object.freeze(["error", "timeout", "parse_error"]); const AUTO_MODE_FALLBACK_CAUSE_SET = new Set(AUTO_MODE_FALLBACK_CAUSES); export function isAutoModeFallbackCause(v) { return AUTO_MODE_FALLBACK_CAUSE_SET.has(v); } export const AUTO_MODE_CLASSIFIER_FALLBACKS = Object.freeze(["main", "none"]); const AUTO_MODE_CLASSIFIER_FALLBACK_SET = new Set(AUTO_MODE_CLASSIFIER_FALLBACKS); export function isAutoModeClassifierFallback(v) { return AUTO_MODE_CLASSIFIER_FALLBACK_SET.has(v); } export function autoModeClassifierFallbackOf(v) { if (v === undefined) return "main"; if (isAutoModeClassifierFallback(v)) return v; const e = new Error(`RunnerDeps.autoMode.classifierFallback must be one of ${AUTO_MODE_CLASSIFIER_FALLBACKS.map((x) => `"${x}"`).join(" | ")} ` + `(got ${describeRejectedValue(v)}) — omit it for the default "main"`); e.code = "config.auto_mode_classifier_fallback_invalid"; throw e; } const MAX_TIMER_DELAY_MS = 2_147_483_647; export function isAutoModeTimeoutMs(v) { return typeof v === "number" && Number.isFinite(v) && v >= 1 && v <= MAX_TIMER_DELAY_MS; } export function autoModeTimeoutMsOf(v) { if (v === undefined) return AUTO_MODE_DEFAULT_TIMEOUT_MS; if (isAutoModeTimeoutMs(v)) return v; const e = new Error(`RunnerDeps.autoMode.timeoutMs must be a number of milliseconds between 1 and ${MAX_TIMER_DELAY_MS} ` + `(got ${describeRejectedValue(v)}) — omit it for the default ${AUTO_MODE_DEFAULT_TIMEOUT_MS}`); e.code = "config.auto_mode_timeout_invalid"; throw e; } export function autoModeRateLimitBreakAfterOf(v) { if (v === undefined) return AUTO_MODE_RATE_LIMIT_BREAK_AFTER_DEFAULT; if (typeof v === "number" && Number.isSafeInteger(v) && v >= 1) return v; const e = new Error(`RunnerDeps.autoMode.rateLimitBreakAfter must be a whole number of classifications, at least 1 ` + `(got ${describeRejectedValue(v)}) — omit it for the default ${AUTO_MODE_RATE_LIMIT_BREAK_AFTER_DEFAULT}`); e.code = "config.auto_mode_rate_limit_break_invalid"; throw e; } export const AUTO_MODE_ROUND_NOT_ASKED_CODE = "auto_mode.round_not_asked"; export function autoModeRoundNotAsked(reason) { let detail; try { const m = reason.message; if (typeof m === "string") detail = m.slice(0, 200); } catch { } const e = new Error(`the auto-mode classification could not be assembled: ${detail ?? describeRejectedValue(reason)}`, { cause: reason }); e.code = AUTO_MODE_ROUND_NOT_ASKED_CODE; return e; } function isAutoModeRoundNotAsked(e) { return thrownCarriesCode(e, AUTO_MODE_ROUND_NOT_ASKED_CODE); } export const AUTO_MODE_RUNG_RATE_LIMITED_CODE = "auto_mode.rung_rate_limited"; function isAutoModeRungRateLimited(e) { return thrownCarriesCode(e, AUTO_MODE_RUNG_RATE_LIMITED_CODE); } function thrownCarriesCode(e, code) { try { return typeof e === "object" && e !== null && e.code === code; } catch { return false; } } export function rungDidNotRule(v) { if (v.kind === "unavailable") return v.cause; if (v.kind === "parse_error") return v.form === "conflict" ? undefined : "parse_error"; return undefined; } export function classifierUnavailableDenyMessage(toolName, cause, attribution, refusedBySpend) { if (refusedBySpend !== undefined) { return (`The auto-mode ${classifierSpendRefusalClause(refusedBySpend, "classifier's model request")}, so auto mode cannot determine the safety of ${toolName}. ` + "Trying again will not change that: continue with other tasks that don't require this action. " + "Note: reading files, searching code, and other read-only operations do not require the classifier and can still be used."); } const parenthetical = cause === "timeout" ? " (timed out)" : ""; const fb = attribution?.fallback; const rootCause = fb === undefined ? "" : `The classifier model "${fb.from}" did not answer (${fb.cause}) and neither did the model it fell back to, "${fb.to}" (${cause}). `; return (`The auto-mode classifier is temporarily unavailable${parenthetical}, so auto mode cannot determine the safety of ${toolName} right now. ` + rootCause + "Wait a moment and then try this action again. " + "If it keeps failing, continue with other tasks that don't require this action and come back to it later. " + "Note: reading files, searching code, and other read-only operations do not require the classifier and can still be used."); } export function classifierNoRulingAskMessage(askText, cause, refusedBySpend) { if (refusedBySpend !== undefined) return `${askText}\n\nThe auto-mode ${classifierSpendRefusalClause(refusedBySpend, "classifier's model request")}, so auto mode could not judge this call; it needs an approval instead of the classifier's verdict.`; if (cause === "parse_error") return `${askText}\n\nThe auto-mode classifier replied without a verdict, so auto mode could not judge this call; it needs an approval instead of the classifier's verdict.`; const parenthetical = cause === "timeout" ? " (timed out)" : ""; return `${askText}\n\nThe auto-mode classifier is temporarily unavailable${parenthetical}, so auto mode could not judge this call; it needs an approval instead of the classifier's verdict.`; } export function classifierParseFailureDenyMessage(verdict) { const stem = "Auto mode could not evaluate this action and is blocking it for safety"; const who = verdict.classifier === undefined ? undefined : `the classifier model "${verdict.classifier.modelUsed}"`; if (verdict.form === "conflict") return `${stem} — ${who ?? "the classifier's reply"} answered both yes and no.`; return who === undefined ? `${stem} — the classifier's reply carried no verdict.` : `${stem} — ${who} replied without a verdict.`; } export function classifierSaidOf(verdict) { const reason = verdict.reason ? foreignLine(verdict.reason) : ""; const category = isClassifierCategory(verdict.categoryWord) ? verdict.categoryWord : undefined; return reason === "" && category === undefined ? undefined : { ...(reason !== "" ? { reason } : {}), ...(category !== undefined ? { category } : {}) }; } export function classifierSaidTail(said) { return said?.reason !== undefined ? `: ${said.reason}` : ""; } function stripThinking(text) { return text.replace(/<(thinking|think)>[\s\S]*?<\/\1>/gi, "").replace(/<(thinking|think)>[\s\S]*$/i, ""); } const BARE_ANSWER_WRAPPERS = [ ["**", "**"], ["__", "__"], ["*", "*"], ["_", "_"], ["`", "`"], ['"', '"'], ["'", "'"], ["«", "»"], ]; function unwrapBareAnswer(text) { let s = text; for (;;) { const before = s; s = s.trim().replace(/[.!]+$/, "").trim(); for (const [open, close] of BARE_ANSWER_WRAPPERS) { if (s.length > open.length + close.length && s.startsWith(open) && s.endsWith(close)) { s = s.slice(open.length, s.length - close.length); break; } } if (s === before) return s; } } function bareAnswerOf(text) { const visible = text.replace(/[\u200b-\u200d\ufeff]/g, "").trim(); if (visible.includes("```") || visible.includes("\n")) return undefined; let s = unwrapBareAnswer(visible); const labelled = labelledAnswer(s); if (labelled !== undefined) s = unwrapBareAnswer(labelled); const word = /^(yes|no)$/i.exec(s)?.[1]?.toLowerCase(); return word === "yes" || word === "no" ? word : undefined; } function labelledAnswer(s) { const label = "(?:final[ \\t]+)?(?:block|answer|verdict|decision)"; for (const [open, close] of [["", ""], ...BARE_ANSWER_WRAPPERS]) { const re = new RegExp(`^${escapeRe(open)}${label}${escapeRe(close)}[ \\t]*[:=][ \\t]*(.*)$`, "i"); const m = re.exec(s); if (m !== null) return m[1]; } return undefined; } function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } export function parseAutoModeResponse(text, options) { const rawAnswers = new Set([...text.matchAll(/<block>(yes|no)\b/gi)].map((m) => m[1].toLowerCase())); if (rawAnswers.size > 1) return { kind: "parse_error", raw: text, form: "conflict" }; const stripped = stripThinking(text); const hits = [...stripped.matchAll(/<block>(yes|no)\b(<\/block>)?/gi)]; let answer; if (hits.length > 0) { const answers = new Set(hits.map((m) => m[1].toLowerCase())); if (answers.size !== 1) return { kind: "parse_error", raw: text, form: "conflict" }; answer = answers.has("yes") ? "yes" : "no"; } else { answer = options?.bareAnswer === false ? undefined : bareAnswerOf(stripped); if (answer === undefined) return { kind: "parse_error", raw: text, form: "missing" }; if (rawAnswers.size > 0 && !rawAnswers.has(answer)) return { kind: "parse_error", raw: text, form: "conflict" }; } if (answer === "no") return { kind: "allow" }; const category = /<category>([\s\S]*?)<\/category>/i.exec(stripped)?.[1]?.trim() ?? ""; const reason = /<reason>([\s\S]*?)<\/reason>/.exec(stripped)?.[1]?.trim() ?? ""; const categoryWord = classifierCategoryOf(stripped); return { kind: "block", category, reason, ...(categoryWord !== undefined ? { categoryWord } : {}) }; } export const AUTO_MODE_SPEND_REFUSED_CODE = "auto_mode.spend_refused"; export function classifierSpendRefusalClause(reason, subject = "the classifier's model request") { return `${subject} was not sent (${reason === "closed" ? "the run it was asked for has ended" : "it does not fit what is left of the spend ceiling"})`; } export function autoModeSpendRefused(reason) { return Object.assign(new Error(classifierSpendRefusalClause(reason)), { code: AUTO_MODE_SPEND_REFUSED_CODE, reason }); } export function verdictSpendRefusal(v) { return v.kind === "unavailable" && v.refusedBySpend !== undefined ? { refusedBySpend: v.refusedBySpend } : {}; } function spendRefusedReasonOf(e) { try { if (typeof e !== "object" || e === null || e.code !== AUTO_MODE_SPEND_REFUSED_CODE) return undefined; return e.reason === "closed" ? "closed" : "ceiling"; } catch { return undefined; } } export function heldWhileClassifying(decider, hold) { return { decide: (input, signal) => hold(input.req.toolCallId, () => decider.decide(input, signal)), ...(decider.timeoutMs !== undefined ? { timeoutMs: decider.timeoutMs } : {}), }; } export function createAutoModeDecider(opts) { const timeoutMs = autoModeTimeoutMsOf(opts.timeoutMs); if (opts.candidates !== undefined) { if (opts.candidates.length === 0) { throw new Error("AutoModeDeciderOptions.candidates must name at least one model — omit the member for the leg's own model, never an empty ladder"); } const bad = opts.candidates.findIndex((m) => typeof m !== "string" || m.trim() === ""); if (bad >= 0) throw new Error(`AutoModeDeciderOptions.candidates[${bad}] must be a non-empty model id (got ${describeRejectedValue(opts.candidates[bad])})`); } const ladder = opts.candidates ?? [undefined]; const rateLimitBreakAfter = autoModeRateLimitBreakAfterOf(opts.rateLimitBreakAfter); const rateLimitStreak = new Map(); const retired = new Set(); const decide = async (input, signal) => { const startedAt = performance.now(); const round = { rateLimitBreaks: [] }; const verdict = await decideUnreported(input, round, signal); if (opts.onClassified !== undefined) { try { opts.onClassified({ toolCallId: input.req.toolCallId, ms: Math.max(0, Math.round(performance.now() - startedAt)), verdict: verdict.kind, ...(verdict.kind === "unavailable" ? { cause: verdict.cause } : {}), ...(verdict.kind === "parse_error" ? { form: verdict.form } : {}), ...(round.notAsked !== undefined ? { notAsked: round.notAsked } : {}), ...(verdict.classifier !== undefined ? { classifier: verdict.classifier } : {}), ...(round.rateLimitBreaks.length > 0 ? { rateLimitBreaks: round.rateLimitBreaks } : {}), }); } catch { } } return verdict; }; return { decide, timeoutMs }; async function decideUnreported(input, round, signal) { const causes = []; let verdict = { kind: "unavailable", cause: "error" }; let i = 0; const assembled = await assembleRound(input, round, signal); for (; round.notAsked === undefined && i < ladder.length; i++) { if (i < ladder.length - 1 && retired.has(i)) { causes.push("error"); continue; } const name = ladder[i]; const asked = await askRung(input, signal, name !== undefined ? { index: i, model: name } : undefined, round, assembled); verdict = asked.verdict; noteRungOutcome(i, asked.rateLimited, signal, round); const cause = rungDidNotRule(verdict); if (cause === undefined) break; causes.push(cause); if (round.notAsked !== undefined || signal?.aborted || (verdict.kind === "unavailable" && verdict.refusedBySpend !== undefined)) break; } const landed = round.notAsked !== undefined ? 0 : Math.min(i, ladder.length - 1); const requested = ladder[0]; const used = ladder[landed]; if (requested === undefined || used === undefined) return verdict; const from = landed > 0 ? ladder[landed - 1] : undefined; const movedBy = landed > 0 ? causes[landed - 1] : undefined; return { ...verdict, classifier: Object.freeze({ modelRequested: requested, modelUsed: used, ...(from !== undefined && movedBy !== undefined ? { fallback: Object.freeze({ from, to: used, cause: movedBy }) } : {}), }), }; } async function assembleRound(input, round, signal) { const assemble = opts.assemble; if (assemble === undefined) return undefined; try { return await withDeadline(timeoutMs, signal, (inner) => assemble(input, inner)); } catch (e) { round.notAsked = isAutoModeTimeout(e) ? "timeout" : "failed"; return undefined; } } async function askRung(input, signal, rung, round, assembled) { try { return { verdict: parseAutoModeResponse(await withDeadline(timeoutMs, signal, (inner) => opts.classify(input, inner, rung, assembled), inClassifierLaneFor(input.req.toolCallId))), rateLimited: false }; } catch (e) { if (isAutoModeRoundNotAsked(e)) { round.notAsked = "failed"; return { verdict: { kind: "unavailable", cause: "error" }, rateLimited: false }; } if (signal?.aborted) return { verdict: { kind: "unavailable", cause: "error" }, rateLimited: false }; const refusedBySpend = spendRefusedReasonOf(e); if (refusedBySpend !== undefined) return { verdict: { kind: "unavailable", cause: "error", refusedBySpend }, rateLimited: false }; if (isAutoModeTimeout(e) && cutWaitingForRoom(e)) return { verdict: { kind: "unavailable", cause: "error", refusedBySpend: "ceiling" }, rateLimited: false }; return { verdict: { kind: "unavailable", cause: isAutoModeTimeout(e) ? "timeout" : "error" }, rateLimited: isAutoModeRungRateLimited(e) }; } } function noteRungOutcome(rungIndex, rateLimited, signal, round) { if (signal?.aborted) return; if (!rateLimited) { rateLimitStreak.delete(rungIndex); return; } const streak = (rateLimitStreak.get(rungIndex) ?? 0) + 1; rateLimitStreak.set(rungIndex, streak); if (streak < rateLimitBreakAfter || retired.has(rungIndex)) return; let next = rungIndex + 1; while (next < ladder.length - 1 && retired.has(next)) next++; const model = ladder[rungIndex]; const to = ladder[next]; if (model === undefined || to === undefined) return; retired.add(rungIndex); round.rateLimitBreaks.push({ rung: rungIndex, model, to, consecutive: streak }); } } async function withDeadline(capMs, signal, call, scope = (f) => f()) { if (signal?.aborted === true) throw new Error("the classification was cancelled before it was dispatched"); let timer; let onOuterAbort; const inner = new AbortController(); try { return await new Promise((resolve, reject) => { let settled = false; const settle = (end) => { if (settled) return; settled = true; end(); }; onOuterAbort = () => { scope(() => inner.abort()); settle(() => reject(new Error("the classification was cancelled"))); }; signal?.addEventListener("abort", onOuterAbort, { once: true }); timer = setTimeout(() => { settle(() => { const cut = new AutoModeTimeout(); scope(() => inner.abort(cut)); reject(cut); }); }, capMs); let pending; try { pending = scope(() => call(inner.signal)); } catch (e) { settle(() => reject(e)); return; } pending.then((v) => settle(() => resolve(v)), (e) => settle(() => reject(e))); }); } finally { if (timer !== undefined) clearTimeout(timer); if (signal !== undefined && onOuterAbort !== undefined) signal.removeEventListener("abort", onOuterAbort); } } const inClassifierLaneFor = (toolCallId) => (f) => withStatusSeat("classifier", f, toolCallId); class AutoModeTimeout extends Error { constructor() { super("auto-mode classify timeout"); } } const isAutoModeTimeout = (e) => thrownIs(e, AutoModeTimeout); export const DENIAL_LIMIT_BOUNDS = Object.freeze(["consecutive", "total"]); export function isDenialLimitBound(v) { return DENIAL_LIMIT_BOUNDS.some((bound) => v === bound); } export function readDenialLimitFallback(v) { if (!isPlainRecord(v)) return undefined; const count = (x) => typeof x === "number" && Number.isFinite(x) && x >= 0; const [consecutive, total, limit, autoDenyAfterMs] = [v["consecutive"], v["total"], v["limit"], v["autoDenyAfterMs"]]; if (!count(consecutive) || !count(total) || !count(autoDenyAfterMs) || !isDenialLimitBound(limit)) return undefined; return { consecutive, total, limit, autoDenyAfterMs }; } export function unarmedWindow(fallback) { return { ...countsOf(fallback), autoDenyAfterMs: 0 }; } function countsOf(fallback) { return { consecutive: fallback.consecutive, total: fallback.total, limit: fallback.limit }; } const DENIAL_LIMIT_KEYS = optionKeys()({ maxConsecutive: 0, maxTotal: 0, autoDenyAfterMs: 0 }); function readDenialLimit(v) { const refuse = (what) => { const e = new Error(`RunnerDeps.autoMode.denialLimit${what}`); e.code = "config.auto_mode_denial_limit_invalid"; throw e; }; if (v === undefined) return { resolved: { ...AUTO_MODE_DENIAL_LIMIT_DEFAULTS, autoDenyAfterMs: AUTO_MODE_DENIAL_AUTO_DENY_DEFAULT_MS }, given: undefined }; if (typeof v !== "object" || v === null || Array.isArray(v)) return refuse(` must be a record of bounds (got ${describeRejectedValue(v)}) — omit it for the defaults`); const opts = receiveMembers(v, { subject: "RunnerDeps.autoMode.denialLimit", unit: "member", moment: "when the knob is read" }, DENIAL_LIMIT_KEYS, (_, [stray]) => refuse(` has no member ${callerKey(stray)} — its members are maxConsecutive, maxTotal and autoDenyAfterMs`)); const bound = (name, dflt) => { const b = opts[name]; if (b === undefined) return dflt; return typeof b === "number" && Number.isInteger(b) && b >= 1 ? b : refuse(`.${name} must be a positive integer (got ${describeRejectedValue(b)}) — omit it for the default ${dflt}`); }; const w = opts["autoDenyAfterMs"]; const autoDenyAfterMs = w === undefined ? AUTO_MODE_DENIAL_AUTO_DENY_DEFAULT_MS : typeof w === "number" && Number.isInteger(w) && w >= 0 && w <= MAX_TIMER_DELAY_MS ? w : refuse(`.autoDenyAfterMs must be an integer between 0 and ${MAX_TIMER_DELAY_MS} (got ${describeRejectedValue(w)}) — 0 disarms the window; omit it for the default ${AUTO_MODE_DENIAL_AUTO_DENY_DEFAULT_MS}`); const maxConsecutive = bound("maxConsecutive", AUTO_MODE_DENIAL_LIMIT_DEFAULTS.maxConsecutive); const maxTotal = bound("maxTotal", AUTO_MODE_DENIAL_LIMIT_DEFAULTS.maxTotal); return { resolved: { maxConsecutive, maxTotal, autoDenyAfterMs }, given: Object.freeze({ ...(opts["maxConsecutive"] !== undefined ? { maxConsecutive } : {}), ...(opts["maxTotal"] !== undefined ? { maxTotal } : {}), ...(w !== undefined ? { autoDenyAfterMs } : {}), }), }; } export function autoModeDenialLimitOf(v) { return readDenialLimit(v).resolved; } const AUTO_MODE_FACE_KEYS = optionKeys()({ rules: 0, settingsDenyRules: 0, sessionContext: 0, window: 0, timeoutMs: 0, classifierFallback: 0, rateLimitBreakAfter: 0, denialLimit: 0, persistArming: 0, settingsEpoch: 0, }); const AUTO_MODE_RULES_KEYS = optionKeys()({ allow: 0, softDeny: 0, hardDeny: 0, environment: 0 }); const AUTO_MODE_WINDOW_KEYS = optionKeys()({ maxEntries: 0, maxCharsPerEntry: 0 }); function receiveStringList(v, path) { if (v === undefined) return undefined; if (typeof v === "object" && v !== null) refuseProxy(v, { subject: path, unit: "entry", moment: "when the auto-mode face is received" }); if (!Array.isArray(v)) throw receiptRefusal(`${path} must be a list of strings (got ${describeRejectedValue(v)})`); const out = []; for (let i = 0; i < v.length; i++) { const held = i in v; const item = held ? v[i] : undefined; if (!held || typeof item !== "string") { throw receiptRefusal(`${path}[${i}] must be a string (got ${!held ? "an empty slot" : describeRejectedValue(item)})`); } out.push(item); } return Object.freeze(out); } function receiveAutoModeRules(v, path) { if (v === undefined) return undefined; if (typeof v !== "object" || v === null || Array.isArray(v)) throw receiptRefusal(`${path} must be a plain object of rule lists (got ${describeRejectedValue(v)})`); const copy = receiveMembers(v, { subject: path, unit: "section", moment: "when the auto-mode face is received" }, AUTO_MODE_RULES_KEYS); const out = {}; for (const k of AUTO_MODE_RULES_KEYS) { const list = receiveStringList(copy[k], `${path}.${k}`); if (list !== undefined) out[k] = list; } return Object.freeze(out); } function receiveAutoModeWindow(v, path) { if (v === undefined) return undefined; if (typeof v !== "object" || v === null || Array.isArray(v)) throw receiptRefusal(`${path} must be a plain object of window bounds (got ${describeRejectedValue(v)})`); const copy = receiveMembers(v, { subject: path, unit: "bound", moment: "when the auto-mode face is received" }, AUTO_MODE_WINDOW_KEYS); const out = {}; for (const k of AUTO_MODE_WINDOW_KEYS) { const b = copy[k]; if (b === undefined) continue; if (typeof b !== "number" || !Number.isInteger(b) || b < 0) throw receiptRefusal(`${path}.${k} must be a whole number >= 0 (got ${describeRejectedValue(b)})`); out[k] = b; } return Object.freeze(out); } export function receiveAutoModeFace(given, subject = "RunnerDeps.autoMode") { if (given === undefined) return undefined; if (typeof given !== "object" || given === null || Array.isArray(given)) { throw receiptRefusal(`${subject} must be a plain object (got ${describeRejectedValue(given)}) — omit it to leave auto mode unarmed`); } const copy = receiveMembers(given, { subject, unit: "member", moment: "when the auto-mode face is received" }, AUTO_MODE_FACE_KEYS); const timeoutMs = copy.timeoutMs !== undefined ? autoModeTimeoutMsOf(copy.timeoutMs) : undefined; const classifierFallback = copy.classifierFallback !== undefined ? autoModeClassifierFallbackOf(copy.classifierFallback) : undefined; const rateLimitBreakAfter = copy.rateLimitBreakAfter !== undefined ? autoModeRateLimitBreakAfterOf(copy.rateLimitBreakAfter) : undefined; const denialLimit = readDenialLimit(copy.denialLimit).given; const rules = receiveAutoModeRules(copy.rules, `${subject}.rules`); const settingsDenyRules = receiveStringList(copy.settingsDenyRules, `${subject}.settingsDenyRules`); const sessionContext = receiveStringList(copy.sessionContext, `${subject}.sessionContext`); const window = receiveAutoModeWindow(copy.window, `${subject}.window`); if (copy.persistArming !== undefined && typeof copy.persistArming !== "boolean") { throw receiptRefusal(`${subject}.persistArming must be a boolean (got ${describeRejectedValue(copy.persistArming)}) — omit it for false`); } if (copy.settingsEpoch !== undefined && typeof copy.settingsEpoch !== "string") { throw receiptRefusal(`${subject}.settingsEpoch must be a string (got ${describeRejectedValue(copy.settingsEpoch)}) — omit it when undeclared`); } return Object.freeze({ ...(rules !== undefined ? { rules } : {}), ...(settingsDenyRules !== undefined ? { settingsDenyRules } : {}), ...(sessionContext !== undefined ? { sessionContext } : {}), ...(window !== undefined ? { window } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}), ...(classifierFallback !== undefined ? { classifierFallback } : {}), ...(rateLimitBreakAfter !== undefined ? { rateLimitBreakAfter } : {}), ...(denialLimit !== undefined ? { denialLimit } : {}), ...(copy.persistArming !== undefined ? { persistArming: copy.persistArming } : {}), ...(copy.settingsEpoch !== undefined ? { settingsEpoch: copy.settingsEpoch } : {}), }); } export function screenAutoModeKnobs(face) { void receiveAutoModeFace(face); } export function createAutoModeDenialTracker(opts) { const { maxConsecutive, maxTotal, autoDenyAfterMs } = autoModeDenialLimitOf(opts); let consecutive = 0; let total = 0; let timedFallbackShown = false; let windowArmedAt; let minted = new WeakSet(); return { recordBlock() { consecutive += 1; total += 1; if (consecutive < maxConsecutive && total < maxTotal) return { limitReached: false }; const totalTripped = total >= maxTotal; const fallback = { consecutive, total, limit: totalTripped ? "total" : "consecutive" }; minted.add(fallback); if (totalTripped) { consecutive = 0; total = 0; timedFallbackShown = false; windowArmedAt = undefined; minted = new WeakSet(); minted.add(fallback); } return { limitReached: true, fallback }; }, armTimedWindow(fallback) { if (!minted.delete(fallback) || fallback.limit === "total" || timedFallbackShown || autoDenyAfterMs === 0) return unarmedWindow(fallback); timedFallbackShown = true; windowArmedAt = Date.now(); return { ...countsOf(fallback), autoDenyAfterMs }; }, recordAllow() { consecutive = 0; timedFallbackShown = false; windowArmedAt = undefined; minted = new WeakSet(); }, snapshot: () => ({ consecutive, total, timedFallbackShown, ...(windowArmedAt !== undefined ? { windowArmedAt } : {}) }), }; } export function denialLimitFallbackMessage(fallback, latestBlockedAction) { return `Classifier denial limit exceeded, falling back to prompting: ${denialLimitSentence(fallback)}\n\nLatest blocked action: ${latestBlockedAction}`; } export function denialLimitFallbackAsk(standing, fallback, latestBlockedAction) { const { classifierNoRuling: _why, ...rest } = standing; return { ...rest, message: denialLimitFallbackMessage(fallback, latestBlockedAction), decisionReason: "classifier", requiresRealApproval: true, denialLimitFallback: fallback }; } export function denialLimitSentence(fallback) { return fallback.limit === "total" ? `${fallback.total} actions were blocked this session. Please review the transcript before continuing.` : `${fallback.consecutive} consecutive actions were blocked. Please review the transcript before continuing.`; }