235 lines
11 KiB
TypeScript
235 lines
11 KiB
TypeScript
// PEP-41: provider, model and effort of the agent per platform → project → story, escalation
|
||
// to a stronger model after failures, a fallback provider when the main one has no login.
|
||
import { m as tr } from "@peppa/shared/i18n";
|
||
import { events, tasks, type Db } from "@peppa/db";
|
||
import { and, desc, eq, inArray } from "drizzle-orm";
|
||
import { PeppaError } from "./errors.ts";
|
||
import { reviewRejections } from "./reviews.ts";
|
||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||
|
||
export const AGENT_PROVIDERS = ["claude", "codex", "opencode"] as const;
|
||
export type AgentProvider = (typeof AGENT_PROVIDERS)[number];
|
||
export const AGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
|
||
export type AgentEffort = (typeof AGENT_EFFORTS)[number];
|
||
export const AGENT_EFFORT_RU: Record<AgentEffort, string> = { low: tr("низкие"), medium: tr("средние"), high: tr("высокие"), xhigh: tr("очень высокие"), max: tr("максимальные") };
|
||
|
||
export interface AgentSettings {
|
||
/** null = the subscription decides (as before PEP-41). */
|
||
provider: AgentProvider | null;
|
||
model: string | null;
|
||
effort: AgentEffort | null;
|
||
escalateModel: string | null;
|
||
escalateEffort: AgentEffort | null;
|
||
/** Failures (red CI attempts + reviewer returns) before escalation; null = never. */
|
||
escalateAfter: number | null;
|
||
fallbackProvider: AgentProvider | null;
|
||
fallbackModel: string | null;
|
||
}
|
||
export type AgentSettingsPatch = { [K in keyof AgentSettings]?: AgentSettings[K] };
|
||
export const AGENT_FIELDS = ["provider", "model", "effort", "escalateModel", "escalateEffort", "escalateAfter", "fallbackProvider", "fallbackModel"] as const satisfies ReadonlyArray<keyof AgentSettings>;
|
||
|
||
export const DEFAULT_AGENT_SETTINGS: AgentSettings = {
|
||
provider: null,
|
||
model: null,
|
||
effort: null,
|
||
escalateModel: null,
|
||
escalateEffort: null,
|
||
escalateAfter: 2,
|
||
fallbackProvider: null,
|
||
fallbackModel: null,
|
||
};
|
||
|
||
const SYSTEM_KEY = "platform.agent";
|
||
const projectKey = (projectId: number) => `project.agent:${projectId}`;
|
||
const taskKey = (taskId: number) => `task.agent:${taskId}`;
|
||
const escalatedKey = (taskId: number) => `agent.escalated:${taskId}`;
|
||
|
||
const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/\[\]-]{0,79}$/;
|
||
|
||
/** Validates one field; returns undefined for "inherit" (empty), throws on a bad value when strict. */
|
||
function parseField(k: keyof AgentSettings, v: unknown, strict: boolean): AgentSettings[keyof AgentSettings] | undefined {
|
||
const bad = () => {
|
||
if (strict) throw new PeppaError(tr("Недопустимое значение {k}: {v}", { k, v: String(v) }));
|
||
return undefined;
|
||
};
|
||
if (v === undefined || v === "") return undefined;
|
||
if (v === null) return k === "escalateAfter" ? null : undefined;
|
||
switch (k) {
|
||
case "provider":
|
||
case "fallbackProvider":
|
||
return AGENT_PROVIDERS.includes(v as AgentProvider) ? (v as AgentProvider) : bad();
|
||
case "effort":
|
||
case "escalateEffort":
|
||
return AGENT_EFFORTS.includes(v as AgentEffort) ? (v as AgentEffort) : bad();
|
||
case "escalateAfter": {
|
||
if (v === "off" || v === "never" || v === 0 || v === "0") return null;
|
||
const n = typeof v === "string" ? Number(v) : v;
|
||
return Number.isInteger(n) && (n as number) >= 1 && (n as number) <= 20 ? (n as number) : bad();
|
||
}
|
||
default:
|
||
return typeof v === "string" && MODEL_RE.test(v.trim()) ? v.trim() : bad();
|
||
}
|
||
}
|
||
|
||
function clean(p: Record<string, unknown> | null, strict = false): AgentSettingsPatch {
|
||
const out: Record<string, unknown> = {};
|
||
if (!p) return out;
|
||
for (const [k, v] of Object.entries(p)) {
|
||
if (!AGENT_FIELDS.includes(k as keyof AgentSettings)) {
|
||
if (strict) throw new PeppaError(tr("Неизвестная настройка агента: {k}", { k }));
|
||
continue;
|
||
}
|
||
const val = parseField(k as keyof AgentSettings, v, strict);
|
||
if (val !== undefined) out[k] = val;
|
||
}
|
||
return out as AgentSettingsPatch;
|
||
}
|
||
|
||
export async function getSystemAgentSettings(db: Db): Promise<AgentSettingsPatch> {
|
||
return clean(await getSetting(db, SYSTEM_KEY));
|
||
}
|
||
export async function getProjectAgentSettings(db: Db, projectId: number): Promise<AgentSettingsPatch> {
|
||
return clean(await getSetting(db, projectKey(projectId)));
|
||
}
|
||
export async function getTaskAgentSettings(db: Db, taskId: number): Promise<AgentSettingsPatch> {
|
||
return clean(await getSetting(db, taskKey(taskId)));
|
||
}
|
||
|
||
/** Effective settings: defaults ← platform ← project ← story. */
|
||
export async function resolveAgentSettings(db: Db, projectId: number, taskId?: number | null): Promise<AgentSettings> {
|
||
return {
|
||
...DEFAULT_AGENT_SETTINGS,
|
||
...(await getSystemAgentSettings(db)),
|
||
...(await getProjectAgentSettings(db, projectId)),
|
||
...(taskId ? await getTaskAgentSettings(db, taskId) : {}),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Replaces the overrides at one level (a full form: fields left out or empty inherit).
|
||
* With `merge`, the patch is applied over the stored overrides; null/"" there removes a field.
|
||
*/
|
||
async function store(db: Db, key: string, patch: Record<string, unknown>, merge: boolean): Promise<AgentSettingsPatch> {
|
||
clean(patch, true); // validation
|
||
let base: Record<string, unknown> = merge ? { ...((await getSetting<Record<string, unknown>>(db, key)) ?? {}) } : {};
|
||
for (const [k, v] of Object.entries(patch)) {
|
||
if (v === undefined) continue;
|
||
if (v === "" || (v === null && k !== "escalateAfter")) delete base[k];
|
||
else base[k] = v;
|
||
}
|
||
const value = clean(base);
|
||
if (Object.keys(value).length) await setSetting(db, key, value);
|
||
else await deleteSetting(db, key);
|
||
return value;
|
||
}
|
||
export const setSystemAgentSettings = (db: Db, patch: Record<string, unknown>, merge = false) => store(db, SYSTEM_KEY, patch, merge);
|
||
export const setProjectAgentSettings = (db: Db, projectId: number, patch: Record<string, unknown>, merge = false) => store(db, projectKey(projectId), patch, merge);
|
||
export const setTaskAgentSettings = (db: Db, taskId: number, patch: Record<string, unknown>, merge = false) => store(db, taskKey(taskId), patch, merge);
|
||
|
||
/** "key=value" pairs (CLI) → a patch; "-" or empty value = inherit. */
|
||
export function parseAgentPairs(pairs: string[]): Record<string, unknown> {
|
||
const out: Record<string, unknown> = {};
|
||
for (const p of pairs) {
|
||
const i = p.indexOf("=");
|
||
if (i < 1) throw new PeppaError(tr("Ожидается ключ=значение: {p}", { p }));
|
||
const k = p.slice(0, i).trim();
|
||
const v = p.slice(i + 1).trim();
|
||
out[k] = v === "-" ? "" : v;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// ── escalation ───────────────────────────────────────────────────────────────
|
||
|
||
export interface Escalation {
|
||
at: string;
|
||
failures: number;
|
||
model: string;
|
||
}
|
||
|
||
/** Failures of a story so far: red CI attempts (distinct commits) + reviewer returns. */
|
||
export async function storyFailures(db: Db, taskId: number): Promise<number> {
|
||
const [t] = await db.select({ ci: tasks.ciAttempts }).from(tasks).where(eq(tasks.id, taskId));
|
||
return (t?.ci ?? 0) + (await reviewRejections(db, taskId));
|
||
}
|
||
|
||
export async function getEscalation(db: Db, taskId: number): Promise<Escalation | null> {
|
||
return getSetting<Escalation>(db, escalatedKey(taskId));
|
||
}
|
||
|
||
/**
|
||
* Sticky escalation: once the story reached `escalateAfter` failures (and an escalation model
|
||
* is set), it is recorded and stays even when a green run resets `ci_attempts`.
|
||
* Returns the escalation and whether it happened just now.
|
||
*/
|
||
export async function checkEscalation(db: Db, projectId: number, taskId: number): Promise<{ escalation: Escalation | null; fresh: boolean }> {
|
||
const cur = await getEscalation(db, taskId);
|
||
if (cur) return { escalation: cur, fresh: false };
|
||
const s = await resolveAgentSettings(db, projectId, taskId);
|
||
if (!s.escalateModel || s.escalateAfter == null) return { escalation: null, fresh: false };
|
||
const failures = await storyFailures(db, taskId);
|
||
if (failures < s.escalateAfter) return { escalation: null, fresh: false };
|
||
const escalation: Escalation = { at: new Date().toISOString(), failures, model: s.escalateModel };
|
||
await setSetting(db, escalatedKey(taskId), escalation);
|
||
return { escalation, fresh: true };
|
||
}
|
||
|
||
export interface LaunchModel {
|
||
model: string | null;
|
||
effort: AgentEffort | null;
|
||
escalated: boolean;
|
||
}
|
||
|
||
/**
|
||
* PEP-241: the CLI a model name belongs to — Claude aliases and `claude-*`, OpenAI `gpt-*`/`o<N>`/`codex-*`,
|
||
* OpenCode `provider/model`; null when the name says nothing.
|
||
*/
|
||
export function modelProvider(model: string): AgentProvider | null {
|
||
const m = model.trim().toLowerCase();
|
||
if (/^(opus|sonnet|haiku|opusplan|claude)([-\[.:]|$)/.test(m)) return "claude";
|
||
if (/^(gpt|codex)([-.]|$)|^o\d/.test(m)) return "codex";
|
||
if (m.includes("/")) return "opencode";
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Does `model` go to `provider`? With the provider set in the settings — only to it; without one
|
||
* (PEP-241) — only to the CLI the name belongs to, an unknown name to the default one (Claude):
|
||
* `-m opus` makes Codex on a ChatGPT account refuse every message.
|
||
*/
|
||
function modelFits(model: string | null, provider: AgentProvider, configured: AgentProvider | null): boolean {
|
||
if (!model) return false;
|
||
if (configured) return configured === provider;
|
||
return (modelProvider(model) ?? "claude") === provider;
|
||
}
|
||
|
||
/**
|
||
* Model and effort for one launch on `provider`: the escalation model once the story is
|
||
* escalated; the fallback model on the fallback provider; the model only on its own provider.
|
||
*/
|
||
export function launchModelFor(s: AgentSettings, provider: AgentProvider, escalated: boolean): LaunchModel {
|
||
const own = s.provider == null || s.provider === provider;
|
||
if (own && escalated && s.escalateModel && modelFits(s.escalateModel, provider, s.provider)) return { model: s.escalateModel, effort: s.escalateEffort ?? s.effort, escalated: true };
|
||
if (own) return { model: modelFits(s.model, provider, s.provider) ? s.model : null, effort: s.effort, escalated: false };
|
||
if (s.fallbackProvider === provider) return { model: s.fallbackModel, effort: null, escalated: false };
|
||
return { model: null, effort: null, escalated: false };
|
||
}
|
||
|
||
/** The model of a session's current launch (from its last started/resumed event). */
|
||
export async function sessionLaunchModel(db: Db, sessionId: number): Promise<string | null> {
|
||
const [row] = await db
|
||
.select({ payload: events.payload })
|
||
.from(events)
|
||
.where(and(eq(events.sessionId, sessionId), inArray(events.type, ["started", "resumed"])))
|
||
.orderBy(desc(events.id))
|
||
.limit(1);
|
||
return ((row?.payload as { model?: string | null } | null)?.model ?? null) || null;
|
||
}
|
||
|
||
/** One line for a card: "opus · усилия высокие" / "как у подписки". */
|
||
export function agentSettingsLabel(s: Pick<AgentSettings, "provider" | "model" | "effort">): string {
|
||
// glossary-ignore: настройки агента показаны только в виде «Инженер»
|
||
const parts = [s.provider, s.model, s.effort ? tr("усилия {effort}", { effort: AGENT_EFFORT_RU[s.effort] }) : null].filter(Boolean);
|
||
return parts.length ? parts.join(" · ") : tr("по умолчанию");
|
||
}
|