import { getResponseRules, getRulesFormat } from '../config/config-loader.js'; import { getRecordedRules } from './recordings.js'; import { findMatchingRule, ruleFailure, ruleFiles, ruleHasToolCalls, validateResponseRule, type ResponseRule, } from './response-rules.js'; /** * Response rules added while the server runs, through the admin API (see * admin-api.ts). They are held in memory only: the config file is never * written, and a restart starts again with none. * * A runtime rule holds its reply as `text`, or as tool-call `content`. It * can't name a `file` or `contentFile`: the admin API is open to whoever can * reach the server, and a path would let them read files from this machine * through a reply. * * `times` is how many more requests the rule answers. It goes down by one * with each request the rule replies to or fails (not one that chaos fails), * and the rule is removed after the last. A rule without it stays until it is * removed. */ export interface RuntimeRule extends ResponseRule { id: string; times?: number; } const allowedKeys = new Set([ 'match', 'text', 'content', 'in', 'exact', 'stopReason', 'fail', 'times', ]); let runtimeRules: RuntimeRule[] = []; // Never reused, so an id that was removed can't come to mean another rule let nextId = 1; /** * Adds a rule, after the runtime rules already there. Throws a TypeError * describing the problem if it can't be used. */ export const addRuntimeRule = (rule: unknown): RuntimeRule => { if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) { throw new TypeError('rule must be a JSON object'); } if ('file' in rule || 'files' in rule || 'contentFile' in rule) { throw new TypeError( 'rule can not use file, files or contentFile: give the reply as text or content', ); } const unknown = Object.keys(rule).filter((key) => !allowedKeys.has(key)); if (unknown.length > 0) { throw new TypeError(`rule has unknown settings: ${unknown.join(', ')}`); } const { match, text, content, stopReason, fail, times } = rule as RuntimeRule; const scope = (rule as RuntimeRule).in; if (text === undefined && content === undefined && fail === undefined) { throw new TypeError('rule must have text, content or fail'); } if (times !== undefined && !(Number.isInteger(times) && times >= 1)) { throw new TypeError('rule.times must be an integer of 1 or more'); } validateResponseRule(rule, 'rule', getRulesFormat()); const added: RuntimeRule = { id: `r${nextId++}`, match, ...(text !== undefined && { text }), ...(content !== undefined && { content }), ...(scope !== undefined && { in: scope }), ...((rule as RuntimeRule).exact === true && { exact: true }), ...(stopReason !== undefined && { stopReason }), ...(fail !== undefined && { fail }), ...(times !== undefined && { times }), }; runtimeRules.push(added); return added; }; // Removes one rule; false if there is none with that id export const removeRuntimeRule = (id: string): boolean => { const remaining = runtimeRules.filter((rule) => rule.id !== id); const removed = remaining.length < runtimeRules.length; runtimeRules = remaining; return removed; }; export const clearRuntimeRules = (): void => { runtimeRules = []; }; /** * Every rule a request is matched against, in order (first match wins): the * runtime rules, the active preset's own, then the recorded ones (see * recordings.ts), plus the folder their files resolve against. */ export const getActiveRules = (): { rules: ResponseRule[]; baseDir: string; } => { const { rules, baseDir } = getFileRules(); return { rules: [...runtimeRules, ...rules], baseDir }; }; /** * The rules from files: the preset's own, then the recorded ones. A rule's * place in this list is what `/ui-rule-file?rule=` goes by. */ export const getFileRules = (): { rules: ResponseRule[]; recorded: Set; baseDir: string; } => { const { rules, baseDir } = getResponseRules(); const recorded = getRecordedRules(); return { rules: [...rules, ...recorded], recorded: new Set(recorded), baseDir, }; }; /** * The rule that answers this request, with the folder its files resolve * against, or undefined if none matches. Find it once per request and pass it * on: a rule with `times` may be gone the next time. */ export const findRequestRule = ( body: unknown, ): { rule: ResponseRule; baseDir: string } | undefined => { const { rules, baseDir } = getActiveRules(); const rule = findMatchingRule(rules, body); return rule && { rule, baseDir }; }; /** * Counts one request against a rule with `times`, and removes the rule after * its last. Does nothing for any other rule. */ export const countRuleUse = (rule: ResponseRule | undefined): void => { const runtime = runtimeRules.find((entry) => entry === rule); if (runtime?.times === undefined) return; runtime.times -= 1; if (runtime.times === 0) removeRuntimeRule(runtime.id); }; /** * The active rules as the dashboard and the admin API report them: each with * where it came from, every file it can reply with, how its reply ends, how * it fails (null if it replies), and how many more requests it answers (null * if it stays until removed). */ export const describeActiveRules = () => { const { rules, recorded } = getFileRules(); return [...runtimeRules, ...rules].map((rule) => { const runtime = runtimeRules.find((entry) => entry === rule); return { id: runtime?.id ?? null, source: runtime ? 'runtime' : recorded.has(rule) ? 'recorded' : 'config', match: rule.match, in: rule.in ?? 'any', exact: rule.exact === true, text: rule.text ?? null, content: rule.content ?? null, files: ruleFiles(rule), stopReason: rule.stopReason ?? (ruleHasToolCalls(rule) ? 'tool_use' : 'end'), fail: ruleFailure(rule) ?? null, times: runtime?.times ?? null, }; }); };