peppa/packages/core/src/team.ts
Асель 5b41e7d779 PEP-75: a team of agents — Kazakh names on the board, a character in the prompt
Also: «Открыть терминал» on live session cards.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 18:49:34 +05:00

156 lines
7.9 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 { 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», … */
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,
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("Имя агента: от 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(`Характер длиннее ${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(`Агент «${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(`Агент «${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(`Характер длиннее ${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("Агент не найден");
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 видит это имя на доске и в вопросах; если нужно представиться или подписаться — используй его.`,
];
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]));
}