peppa/packages/core/src/team.ts
Асель 20bb0d25a8 PEP-179: «Погоня за задачей» на странице «Команда»
Над списком агентов — пиксельный мопс бросает задачу, работающие агенты гоняют её по
трассе (CSS offset-path), свободные ждут на скамейке. Данные — core teamChaseView: трасса
= агенты с живым раннером (≤8, остальные «+N»), скамейка — свободные в команде, счётчик —
задачи в «Готово» видимых проектов; «+1» — только при росте счётчика, «Жмите «Принять»» —
только при задачах на приёмке. Живая область team, LiveRefresh pauseHidden. Подсказки,
касание (первое — подсказка, второе — переход), клавиатура, прокрутка к карточке,
«Скрыть» с запоминанием, уменьшенное движение и экономия батареи, < 420 px — строка значков.
PWA: свой шрифт Press Start 2P (OFL), service worker кэширует оболочку и /team, без сети —
последний состав и «Нет связи — данные на ЧЧ:ММ».

Заодно: listAgents и выбор свободного агента считали занятость по id сессии вместо id агента
(drizzle рендерит ${agents.id} в подзапросе голым "id").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:41:46 +05:00

160 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-75: the platform's team of agents — permanent personas with Kazakh names. A runner takes a
// free persona for its story (creating one when everybody is busy) and keeps it across resumes
// and across the story's later runners; the PM gives each a character (markdown) that goes into
// the agent's prompt on top of the shared rules and the project's AGENTS.md.
import { m as tr } from "@peppa/shared/i18n";
import { agents, sessions, type Db } from "@peppa/db";
import { and, asc, desc, eq, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
export type Agent = typeof agents.$inferSelect;
/** Names new personas get, in order; when all are taken — «Айгерим 2», … */
// PEP-96: nicknames, not human names — a product manager must never take an agent for a person.
export const AGENT_NAMES = [
"Шустрик", "Беркут", "Пиксель", "Тулпар", "Байт", "Барыс", "Искра", "Компас", "Бублик", "Маяк", "Радар", "Сокол",
"Енот", "Филин", "Шмель", "Ракета", "Чип", "Пульс", "Кнопка", "Тайфун", "Зубр", "Бобёр", "Сурок", "Хомяк",
"Лис", "Ёжик", "Мотор", "Самрук", "Квант", "Вектор", "Гравити", "Кубик", "Флешка", "Штурман", "Дятел", "Барсук",
"Пингвин", "Турбо", "Нейрончик", "Скаут",
];
export const AGENT_CHARACTER_MAX = 8000;
const FINISHED = ["done", "failed"] as const;
export interface AgentView extends Agent {
/** Live runners of this persona right now. */
busy: number;
/** All runners it has ever worked in. */
runs: number;
}
export async function listAgents(db: Db): Promise<AgentView[]> {
const rows = await db
.select({
a: agents,
// Qualified on purpose: drizzle renders ${agents.id} as a bare "id", which inside the
// subquery is the session's own id (PEP-179 found every card counting the wrong rows).
busy: sql<number>`(select count(*) from sessions s where s.agent_id = "agents"."id" and s.status not in ('done', 'failed'))`,
runs: sql<number>`(select count(*) from sessions s where s.agent_id = "agents"."id")`,
})
.from(agents)
.orderBy(asc(agents.id));
return rows.map((r) => ({ ...r.a, busy: Number(r.busy), runs: Number(r.runs) }));
}
export async function getAgent(db: Db, id: number): Promise<Agent | null> {
const [a] = await db.select().from(agents).where(eq(agents.id, id));
return a ?? null;
}
const cleanName = (name: string) => {
const n = name.trim().replace(/\s+/g, " ");
if (!n || n.length > 40) throw new PeppaError(tr("Имя агента: от 1 до 40 символов"));
return n;
};
function nextName(taken: Set<string>): string {
for (let round = 1; ; round++) {
for (const base of AGENT_NAMES) {
const name = round === 1 ? base : `${base} ${round}`;
if (!taken.has(name.toLowerCase())) return name;
}
}
}
/** A new persona; without a name — the next free one of `AGENT_NAMES`. */
export async function createAgent(db: Db, o: { name?: string; character?: string } = {}): Promise<Agent> {
const character = (o.character ?? "").trim();
if (character.length > AGENT_CHARACTER_MAX) throw new PeppaError(tr("Характер длиннее {n} символов — сократите", { n: AGENT_CHARACTER_MAX }));
return db.transaction((tx) => {
const taken = new Set(tx.select({ name: agents.name }).from(agents).all().map((r) => r.name.toLowerCase()));
const name = o.name?.trim() ? cleanName(o.name) : nextName(taken);
if (taken.has(name.toLowerCase())) throw new PeppaError(tr("Агент «{name}» уже есть", { name }));
return tx.insert(agents).values({ name, character }).returning().get();
});
}
export async function updateAgent(db: Db, id: number, patch: { name?: string; character?: string; disabled?: boolean }): Promise<Agent> {
const set: Partial<Agent> = {};
if (patch.name !== undefined) {
set.name = cleanName(patch.name);
// Compared in JS: SQLite's lower() leaves Cyrillic and Kazakh letters as they are.
const lower = set.name.toLowerCase();
const other = (await db.select({ id: agents.id, name: agents.name }).from(agents)).find((a) => a.name.toLowerCase() === lower);
if (other && other.id !== id) throw new PeppaError(tr("Агент «{name}» уже есть", { name: set.name }));
}
if (patch.character !== undefined) {
set.character = patch.character.replace(/\r\n/g, "\n").trim();
if (set.character.length > AGENT_CHARACTER_MAX) throw new PeppaError(tr("Характер длиннее {n} символов — сократите", { n: AGENT_CHARACTER_MAX }));
}
if (patch.disabled !== undefined) set.disabledAt = patch.disabled ? new Date() : null;
const [row] = Object.keys(set).length ? await db.update(agents).set(set).where(eq(agents.id, id)).returning() : await db.select().from(agents).where(eq(agents.id, id));
if (!row) throw new PeppaError(tr("Агент не найден"));
return row;
}
/**
* The persona of a runner, assigning one on first use: the story's previous persona if it is
* still in the team, else a free one (no live runner), else a new one with the next name.
* One synchronous transaction, so two runners starting together never share a free persona.
*/
export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Agent | null> {
return db.transaction((tx) => {
const s = tx.select().from(sessions).where(eq(sessions.id, sessionId)).get();
if (!s) return null;
if (s.agentId) {
const own = tx.select().from(agents).where(eq(agents.id, s.agentId)).get();
if (own) return own;
}
let agent: Agent | undefined;
if (s.taskId) {
agent = tx
.select({ a: agents })
.from(sessions)
.innerJoin(agents, eq(sessions.agentId, agents.id))
.where(and(eq(sessions.taskId, s.taskId), isNotNull(sessions.agentId), isNull(agents.disabledAt)))
.orderBy(desc(sessions.id))
.limit(1)
.get()?.a;
}
if (!agent) {
const busy = tx.select({ id: sessions.agentId }).from(sessions).where(and(isNotNull(sessions.agentId), notInArray(sessions.status, [...FINISHED]))).all().map((r) => r.id!);
agent = tx
.select()
.from(agents)
.where(and(isNull(agents.disabledAt), busy.length ? notInArray(agents.id, busy) : undefined))
// The one that rested longest goes first, so the team rotates.
.orderBy(sql`(select coalesce(max(s.id), 0) from sessions s where s.agent_id = "agents"."id")`, asc(agents.id))
.limit(1)
.get();
}
if (!agent) {
const taken = new Set(tx.select({ name: agents.name }).from(agents).all().map((r) => r.name.toLowerCase()));
agent = tx.insert(agents).values({ name: nextName(taken) }).returning().get();
}
tx.update(sessions).set({ agentId: agent.id }).where(eq(sessions.id, sessionId)).run();
return agent;
});
}
/** What the persona adds to the agent's system prompt. */
export function agentPrompt(agent: Pick<Agent, "name" | "character">): string {
const lines = [
"## Твой персонаж в команде Пеппы",
`Твоя кличка — **${agent.name}**: ты ИИ-агент команды Пеппы, и PM это знает. Он видит «агент ${agent.name}» на доске и в вопросах; если нужно представиться или подписаться — «агент ${agent.name}». Не выдавай себя за человека.`,
];
if (agent.character.trim()) lines.push("", "Твой характер и специализация (задал PM; правила Пеппы и AGENTS.md проекта важнее, если расходятся):", "", agent.character.trim());
return lines.join("\n");
}
/** Names of the personas working on stories right now: taskId → name (for the board). */
export async function taskAgentNames(db: Db, projectId: number): Promise<Map<number, string>> {
const rows = await db
.select({ taskId: sessions.taskId, name: agents.name })
.from(sessions)
.innerJoin(agents, eq(sessions.agentId, agents.id))
.where(and(eq(sessions.projectId, projectId), isNotNull(sessions.taskId), notInArray(sessions.status, [...FINISHED])))
.orderBy(asc(sessions.id));
return new Map(rows.map((r) => [r.taskId!, r.name]));
}