// PEP-183: specialists get stories of their profile. A specialist is an agent whose «Характер и // специализация» is filled in; the rest are generalists. Whether a story fits a specialist is // decided once by a short model call (runner/team-match.ts) and kept here in `settings` // (`team.match:`); `ensureSessionAgent` (team.ts) and the dispatcher read it. import { asIs, m as tr } from "@peppa/shared/i18n"; import { agents, sessions, settings, type Db, keyPrefix } from "@peppa/db"; import { and, eq, isNull, like, notInArray, sql } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { getSetting, setSetting } from "./settings.ts"; export interface TeamMatch { /** The specialist the story fits; null — nobody. */ agentId: number | null; name: string | null; /** One phrase: why (or why nobody). */ reason: string; at: number; /** The model call failed — treated as «nobody», only the journal knows. */ failed?: boolean; /** First time the dispatcher held the story for a busy specialist (ms). */ waitSince?: number; /** The story really went to this specialist by profile. */ given?: boolean; } export interface TeamSettings { /** How long a story waits for its busy specialist before a generalist takes it. */ waitMin: number; } export const DEFAULT_TEAM_WAIT_MIN = 30; export const matchKey = (taskId: number) => `team.match:${taskId}`; export async function getTeamSettings(db: Db): Promise { const v = await getSetting>(db, "platform.team"); const n = Number(v?.waitMin); return { waitMin: Number.isFinite(n) && n >= 0 ? n : DEFAULT_TEAM_WAIT_MIN }; } export async function setTeamSettings(db: Db, patch: Partial): Promise { const cur = await getTeamSettings(db); const n = patch.waitMin === undefined ? cur.waitMin : Math.round(Number(patch.waitMin)); if (!Number.isFinite(n) || n < 0 || n > 24 * 60) throw new PeppaError(tr("Ожидание: от 0 до 1440 минут")); const next = { waitMin: n }; await setSetting(db, "platform.team", next); return next; } export const isSpecialist = (a: { character: string; disabledAt: Date | null }) => !a.disabledAt && a.character.trim() !== ""; /** Enabled agents with a filled-in specialization. */ export async function listSpecialists(db: Db) { return (await db.select().from(agents).where(isNull(agents.disabledAt))).filter(isSpecialist); } export const getTeamMatch = (db: Db, taskId: number) => getSetting(db, matchKey(taskId)); export const setTeamMatch = (db: Db, taskId: number, v: TeamMatch) => setSetting(db, matchKey(taskId), v); /** Is the agent working in a live runner right now. */ export async function agentIsBusy(db: Db, agentId: number): Promise { const [r] = await db .select({ n: sql`count(*)` }) .from(sessions) .where(and(eq(sessions.agentId, agentId), notInArray(sessions.status, ["done", "failed"]))); return Number(r?.n ?? 0) > 0; } export function matchPrompt(o: { title: string; description: string; epic: string | null; specialists: Array<{ name: string; character: string }> }): string { return [ "Ты распределяешь задачи между агентами команды. Реши, подходит ли задача кому-то из специалистов по его специализации.", "Отвечай одной строкой JSON без пояснений: {\"agent\": \"<кличка специалиста или null>\", \"reason\": \"<одна фраза, почему>\"}.", "Если задача не про профиль ни одного специалиста — agent: null. Не придумывай клички, бери только из списка.", "", "Специалисты:", ...o.specialists.map((s) => `- ${s.name}: ${s.character.trim().replace(/\s+/g, " ").slice(0, 600)}`), "", `Задача: ${o.title}`, o.epic ? `Эпик: ${o.epic}` : "", "Описание:", o.description.slice(0, 4000), ].filter((l) => l !== "").join("\n"); } /** The model's answer → the chosen specialist (by nickname, compared in JS) or nobody. Null — not in the form. */ export function parseMatch(text: string, specialists: Array<{ id: number; name: string }>): Pick | null { const raw = /\{[\s\S]*\}/.exec(text)?.[0]; if (!raw) return null; let j: { agent?: unknown; reason?: unknown }; try { j = JSON.parse(raw); } catch { return null; } const reason = typeof j.reason === "string" ? j.reason.trim().slice(0, 300) : ""; if (j.agent === null || j.agent === undefined || (typeof j.agent === "string" && /^(никто|null|none|)$/i.test(j.agent.trim()))) { return { agentId: null, name: null, reason }; } if (typeof j.agent !== "string") return null; const want = j.agent.trim().toLowerCase(); const hit = specialists.find((s) => s.name.toLowerCase() === want); return hit ? { agentId: hit.id, name: hit.name, reason } : { agentId: null, name: null, reason }; } /** Stories of the profile of this specialist still in the backlog (queue). */ export async function queuedForSpecialist(db: Db, agentId: number): Promise { const rows = await db .select({ key: settings.key, v: settings.value, status: sql`(select status from tasks t where t.id = cast(substr(${settings.key}, 12) as integer))` }) .from(settings) .where(and(keyPrefix(settings.key, "team.match:"), sql`json_extract(${settings.value}, '$.agentId') = ${agentId}`)); return rows.filter((r) => r.status === "backlog").length; } /** How many stories went to the specialist by profile. */ export async function profileTaskCounts(db: Db): Promise> { const rows = await db .select({ id: sql`json_extract(${settings.value}, '$.agentId')`, n: sql`count(*)` }) .from(settings) .where(and(keyPrefix(settings.key, "team.match:"), sql`json_extract(${settings.value}, '$.given') = 1`)) .groupBy(sql`json_extract(${settings.value}, '$.agentId')`); return new Map(rows.map((r) => [Number(r.id), Number(r.n)])); } /** «Отдана специалисту Страж ИБ: …» / «Специалиста не нашлось» — for the story page (engineer). */ export function matchLine(match: TeamMatch | null): string | null { if (!match || match.failed) return match ? tr("Специалиста не нашлось") : null; if (match.agentId === null) return tr("Специалиста не нашлось"); const v = { name: asIs(match.name), reason: asIs(match.reason) }; return match.given ? tr("Отдана специалисту {name}: {reason}", v) : tr("Подходит специалисту {name}: {reason}", v); }