PEP-67: subscriptions and pools in core/db, sign-in and checks in runner, OpenCode provider, mocks, tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
11778d98bd
commit
9054774f96
@ -46,7 +46,7 @@ OpenCode — подписка только по API-ключу провайде
|
||||
## Вход
|
||||
Общий механизм `runner/subscriptions.ts` поверх tmux (`peppa-auth-sub<id>`), состояние
|
||||
входа — `settings` `subscription.login:<id>` (10 мин):
|
||||
- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` переписан на подписку):
|
||||
- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` → `subscription-login.ts`, на подписку):
|
||||
ссылка → код в форму → токен из вывода → `secret_enc`, статус `active`, tmux убивается
|
||||
(стирает токен из буфера). Либо вставить готовый токен `sk-ant-oat…` руками.
|
||||
- Codex device auth: `codex login --device-auth` с `CODEX_HOME` подписки → со страницы
|
||||
|
||||
@ -46,5 +46,5 @@
|
||||
`projects.subscription_pool_id`, `sessions.subscription_id`, провайдер `opencode`.
|
||||
Миграция данных токенов Claude. **На живой базе нужна `peppa db backup && peppa db migrate`.**
|
||||
- runner: `subscriptions.ts` (вход, проверка, выбор), `providers.ts` (OpenCode),
|
||||
`sessions.ts`; `claude-auth.ts` теперь работает на подписку, а не на пользователя.
|
||||
`sessions.ts`; `claude-auth.ts` → `subscription-login.ts`: вход на подписку, а не на пользователя.
|
||||
- web: `/subscriptions`, меню, настройки проекта, форма запуска, «Раннеры», «Настройки».
|
||||
|
||||
@ -73,7 +73,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa task set <PEP-42|42> -s <status>
|
||||
peppa q list [KEY]
|
||||
peppa q answer <id> <answer> (delivered into the session's terminal)
|
||||
peppa session start <PEP-42|42> [--provider claude|codex] [-p <extra prompt>] [--mode <permission-mode>] [--model <m>]
|
||||
peppa session start <PEP-42|42> [--provider claude|codex|opencode] [-p <extra prompt>] [--mode <permission-mode>] [--model <m>]
|
||||
peppa session list [--all]
|
||||
peppa session send <id> <text>
|
||||
peppa session attach <id>
|
||||
|
||||
@ -20,3 +20,4 @@ export * from "./ci.ts";
|
||||
export * from "./egov.ts";
|
||||
export * from "./local-users.ts";
|
||||
export * from "./specs.ts";
|
||||
export * from "./subscriptions.ts";
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
|
||||
import { events, projects, questions, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
@ -14,11 +14,13 @@ export interface SessionView extends Session {
|
||||
projectKey: string;
|
||||
taskKey: string | null;
|
||||
taskTitle: string | null;
|
||||
/** PEP-67: name of the subscription the session runs on. */
|
||||
subscriptionName: string | null;
|
||||
}
|
||||
|
||||
export async function createSession(
|
||||
db: Db,
|
||||
s: { projectId: number; taskId?: number; provider?: Session["provider"] },
|
||||
s: { projectId: number; taskId?: number; provider?: Session["provider"]; subscriptionId?: number | null },
|
||||
): Promise<Session> {
|
||||
// tmux name needs the id, so insert with a unique placeholder first.
|
||||
const [row] = await db
|
||||
@ -69,7 +71,7 @@ export async function listUserSessions(db: Db, userId: number, opts: { filter?:
|
||||
export async function updateSession(
|
||||
db: Db,
|
||||
id: number,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt" | "resumeAt" | "limitProbeMin" | "limitResumes" | "limitResumesDay" | "limitResumedAt">>,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt" | "resumeAt" | "limitProbeMin" | "limitResumes" | "limitResumesDay" | "limitResumedAt" | "subscriptionId">>,
|
||||
): Promise<Session> {
|
||||
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
|
||||
if (!row) throw new PeppaError(`Session #${id} not found`);
|
||||
@ -160,18 +162,20 @@ export async function raiseSessionQuestion(
|
||||
|
||||
function sessionQuery(db: Db) {
|
||||
return db
|
||||
.select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title })
|
||||
.select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, subscriptionName: subscriptions.name })
|
||||
.from(sessions)
|
||||
.innerJoin(projects, eq(sessions.projectId, projects.id))
|
||||
.leftJoin(tasks, eq(sessions.taskId, tasks.id));
|
||||
.leftJoin(tasks, eq(sessions.taskId, tasks.id))
|
||||
.leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id));
|
||||
}
|
||||
|
||||
function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView {
|
||||
function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; subscriptionName: string | null }): SessionView {
|
||||
return {
|
||||
...r.session,
|
||||
projectKey: r.projectKey,
|
||||
taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null,
|
||||
taskTitle: r.taskTitle,
|
||||
subscriptionName: r.subscriptionName,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
270
packages/core/src/subscriptions.ts
Normal file
270
packages/core/src/subscriptions.ts
Normal file
@ -0,0 +1,270 @@
|
||||
// Agent subscriptions and pools (PEP-67): superadmins keep the accounts agents run on
|
||||
// (Claude Code, Codex, OpenCode) and group them into pools; a runner takes the first free
|
||||
// active subscription of the chosen set. Rotation on limits and fairness — PEP-39.
|
||||
import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
|
||||
import { and, asc, count, eq, inArray, notInArray } from "drizzle-orm";
|
||||
import { decrypt, encrypt } from "./crypto.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { isSuperadmin } from "./monitor.ts";
|
||||
import type { Project } from "./projects.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
export type Subscription = typeof subscriptions.$inferSelect;
|
||||
export type SubscriptionProvider = Subscription["provider"];
|
||||
export type SubscriptionStatus = Subscription["status"];
|
||||
export type SubscriptionPool = typeof subscriptionPools.$inferSelect;
|
||||
|
||||
export const PROVIDER_NAMES: Record<SubscriptionProvider, string> = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" };
|
||||
/** OpenCode model providers a key can belong to, and the env variable it goes into. */
|
||||
export const OPENCODE_KEY_ENV: Record<string, string> = {
|
||||
anthropic: "ANTHROPIC_API_KEY",
|
||||
openai: "OPENAI_API_KEY",
|
||||
openrouter: "OPENROUTER_API_KEY",
|
||||
};
|
||||
|
||||
export interface SubscriptionView extends Subscription {
|
||||
createdByLogin: string | null;
|
||||
activeSessions: number;
|
||||
poolIds: number[];
|
||||
}
|
||||
|
||||
export interface PoolView extends SubscriptionPool {
|
||||
subscriptionIds: number[];
|
||||
projectKeys: string[];
|
||||
}
|
||||
|
||||
/** Throws "not found" unless the user is a superadmin: the section doesn't exist for others. */
|
||||
export async function requireSuperadmin(db: Db, user: Pick<User, "login"> | null | undefined): Promise<void> {
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
|
||||
}
|
||||
|
||||
// ── subscriptions ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function activeSessionCounts(db: Db): Promise<Map<number, number>> {
|
||||
const rows = await db
|
||||
.select({ id: sessions.subscriptionId, n: count() })
|
||||
.from(sessions)
|
||||
.where(notInArray(sessions.status, FINISHED_SESSION_STATUSES))
|
||||
.groupBy(sessions.subscriptionId);
|
||||
return new Map(rows.filter((r) => r.id != null).map((r) => [r.id!, r.n]));
|
||||
}
|
||||
|
||||
export async function listSubscriptions(db: Db): Promise<SubscriptionView[]> {
|
||||
const rows = await db
|
||||
.select({ s: subscriptions, login: users.login })
|
||||
.from(subscriptions)
|
||||
.leftJoin(users, eq(subscriptions.createdBy, users.id))
|
||||
.orderBy(asc(subscriptions.id));
|
||||
const counts = await activeSessionCounts(db);
|
||||
const members = await db.select().from(subscriptionPoolMembers);
|
||||
return rows.map((r) => ({
|
||||
...r.s,
|
||||
createdByLogin: r.login,
|
||||
activeSessions: counts.get(r.s.id) ?? 0,
|
||||
poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getSubscription(db: Db, id: number): Promise<Subscription> {
|
||||
const [row] = await db.select().from(subscriptions).where(eq(subscriptions.id, id));
|
||||
if (!row) throw new PeppaError(`Подписка #${id} не найдена`);
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function createSubscription(
|
||||
db: Db,
|
||||
s: { provider: SubscriptionProvider; name: string; authKind: Subscription["authKind"]; secret?: string | null; keyProvider?: string | null; createdBy?: number | null },
|
||||
): Promise<Subscription> {
|
||||
const name = s.name.trim();
|
||||
if (!name) throw new PeppaError("Нужно название подписки");
|
||||
if (s.provider === "opencode" && !(s.keyProvider && s.keyProvider in OPENCODE_KEY_ENV)) throw new PeppaError("Выберите провайдера ключа OpenCode");
|
||||
const [row] = await db
|
||||
.insert(subscriptions)
|
||||
.values({
|
||||
provider: s.provider,
|
||||
name,
|
||||
authKind: s.authKind,
|
||||
secretEnc: s.secret ? encrypt(s.secret) : null,
|
||||
keyProvider: s.keyProvider ?? null,
|
||||
createdBy: s.createdBy ?? null,
|
||||
})
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export async function updateSubscription(
|
||||
db: Db,
|
||||
id: number,
|
||||
patch: Partial<Pick<Subscription, "name" | "status" | "limitedUntil" | "lastError" | "checkedAt" | "authKind">> & { secret?: string | null },
|
||||
): Promise<Subscription> {
|
||||
const { secret, ...rest } = patch;
|
||||
const set: Partial<Subscription> = { ...rest };
|
||||
if (secret !== undefined) set.secretEnc = secret ? encrypt(secret) : null;
|
||||
if (patch.status === "active") {
|
||||
set.limitedUntil = null;
|
||||
set.lastError = null;
|
||||
const cur = await getSubscription(db, id);
|
||||
if (!cur.activatedAt) set.activatedAt = new Date();
|
||||
}
|
||||
const [row] = await db.update(subscriptions).set(set).where(eq(subscriptions.id, id)).returning();
|
||||
if (!row) throw new PeppaError(`Подписка #${id} не найдена`);
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Removes a subscription; its sessions keep running but forget it. The runner wipes its login dir. */
|
||||
export async function deleteSubscription(db: Db, id: number): Promise<void> {
|
||||
db.transaction((tx) => {
|
||||
tx.update(sessions).set({ subscriptionId: null }).where(eq(sessions.subscriptionId, id)).run();
|
||||
tx.delete(subscriptions).where(eq(subscriptions.id, id)).run();
|
||||
});
|
||||
}
|
||||
|
||||
/** The decrypted secret (Claude token / OpenCode key); null if the subscription has none. */
|
||||
export function subscriptionSecret(s: Pick<Subscription, "secretEnc">): string | null {
|
||||
return s.secretEnc ? decrypt(s.secretEnc) : null;
|
||||
}
|
||||
|
||||
/** Active now: `active`, or `limited` whose reset time has passed. */
|
||||
export function isUsable(s: Pick<Subscription, "status" | "limitedUntil">, now = new Date()): boolean {
|
||||
return s.status === "active" || (s.status === "limited" && !!s.limitedUntil && s.limitedUntil <= now);
|
||||
}
|
||||
|
||||
// ── pools ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listPools(db: Db): Promise<PoolView[]> {
|
||||
const pools = await db.select().from(subscriptionPools).orderBy(asc(subscriptionPools.name));
|
||||
const members = await db.select().from(subscriptionPoolMembers);
|
||||
const used = await db.select({ key: projects.key, poolId: projects.subscriptionPoolId }).from(projects);
|
||||
return pools.map((p) => ({
|
||||
...p,
|
||||
subscriptionIds: members.filter((m) => m.poolId === p.id).map((m) => m.subscriptionId).sort((a, b) => a - b),
|
||||
projectKeys: used.filter((u) => u.poolId === p.id).map((u) => u.key),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getPool(db: Db, id: number): Promise<SubscriptionPool> {
|
||||
const [row] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id));
|
||||
if (!row) throw new PeppaError(`Пул #${id} не найден`);
|
||||
return row;
|
||||
}
|
||||
|
||||
async function checkSubscriptionIds(db: Db, ids: number[]): Promise<number[]> {
|
||||
const uniq = [...new Set(ids.filter((n) => Number.isInteger(n) && n > 0))];
|
||||
if (!uniq.length) return [];
|
||||
const found = await db.select({ id: subscriptions.id }).from(subscriptions).where(inArray(subscriptions.id, uniq));
|
||||
if (found.length !== uniq.length) throw new PeppaError("Некоторых подписок уже нет");
|
||||
return uniq;
|
||||
}
|
||||
|
||||
export async function createPool(db: Db, p: { name: string; subscriptionIds: number[]; createdBy?: number | null }): Promise<SubscriptionPool> {
|
||||
const name = p.name.trim();
|
||||
if (!name) throw new PeppaError("Нужно название пула");
|
||||
const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
|
||||
if (dup) throw new PeppaError(`Пул «${name}» уже есть`);
|
||||
const ids = await checkSubscriptionIds(db, p.subscriptionIds);
|
||||
return db.transaction((tx) => {
|
||||
const row = tx.insert(subscriptionPools).values({ name, createdBy: p.createdBy ?? null }).returning().get();
|
||||
for (const id of ids) tx.insert(subscriptionPoolMembers).values({ poolId: row.id, subscriptionId: id }).run();
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updatePool(db: Db, id: number, p: { name?: string; subscriptionIds?: number[] }): Promise<void> {
|
||||
await getPool(db, id);
|
||||
const ids = p.subscriptionIds ? await checkSubscriptionIds(db, p.subscriptionIds) : null;
|
||||
const name = p.name?.trim();
|
||||
if (name) {
|
||||
const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
|
||||
if (dup && dup.id !== id) throw new PeppaError(`Пул «${name}» уже есть`);
|
||||
}
|
||||
db.transaction((tx) => {
|
||||
if (name) tx.update(subscriptionPools).set({ name }).where(eq(subscriptionPools.id, id)).run();
|
||||
if (ids) {
|
||||
tx.delete(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.poolId, id)).run();
|
||||
for (const sid of ids) tx.insert(subscriptionPoolMembers).values({ poolId: id, subscriptionId: sid }).run();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Deletes a pool; projects that used it as default go back to "no pool". */
|
||||
export async function deletePool(db: Db, id: number): Promise<void> {
|
||||
db.transaction((tx) => {
|
||||
tx.update(projects).set({ subscriptionPoolId: null }).where(eq(projects.subscriptionPoolId, id)).run();
|
||||
tx.delete(subscriptionPools).where(eq(subscriptionPools.id, id)).run();
|
||||
});
|
||||
}
|
||||
|
||||
export async function setProjectPool(db: Db, projectId: number, poolId: number | null): Promise<void> {
|
||||
if (poolId != null) await getPool(db, poolId);
|
||||
await db.update(projects).set({ subscriptionPoolId: poolId }).where(eq(projects.id, projectId));
|
||||
}
|
||||
|
||||
async function poolSubscriptions(db: Db, poolId: number): Promise<Subscription[]> {
|
||||
const rows = await db
|
||||
.select({ s: subscriptions })
|
||||
.from(subscriptionPoolMembers)
|
||||
.innerJoin(subscriptions, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
|
||||
.where(eq(subscriptionPoolMembers.poolId, poolId))
|
||||
.orderBy(asc(subscriptions.id));
|
||||
return rows.map((r) => r.s);
|
||||
}
|
||||
|
||||
// ── choosing a subscription for a runner ─────────────────────────────────────────
|
||||
|
||||
export interface PickOptions {
|
||||
projectId: number;
|
||||
/** Subscriptions ticked in the launch form (multiple choice). */
|
||||
subscriptionIds?: number[];
|
||||
/** A pool chosen in the launch form instead of the project's default. */
|
||||
poolId?: number | null;
|
||||
provider?: SubscriptionProvider;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subscription a new runner starts on: the first free usable one of the chosen set
|
||||
* (ticked subscriptions, else the chosen pool, else the project's pool), by id; if all are
|
||||
* busy — the least busy one (the runner never waits; fairness is PEP-39). Null when nothing
|
||||
* is chosen and the project has no pool: the agent runs on this machine's own login.
|
||||
*/
|
||||
export async function pickSubscription(db: Db, o: PickOptions): Promise<Subscription | null> {
|
||||
let candidates: Subscription[];
|
||||
let source: string;
|
||||
if (o.subscriptionIds?.length) {
|
||||
candidates = await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)).orderBy(asc(subscriptions.id));
|
||||
source = "отмеченных";
|
||||
} else {
|
||||
const poolId = o.poolId ?? (await db.select({ id: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, o.projectId)))[0]?.id;
|
||||
if (poolId == null) return null;
|
||||
const pool = await getPool(db, poolId);
|
||||
candidates = await poolSubscriptions(db, poolId);
|
||||
source = `пула «${pool.name}»`;
|
||||
}
|
||||
if (o.provider) {
|
||||
candidates = candidates.filter((s) => s.provider === o.provider);
|
||||
if (!candidates.length) throw new PeppaError(`Среди ${source} подписок нет подписок ${PROVIDER_NAMES[o.provider]}`);
|
||||
}
|
||||
const usable = candidates.filter((s) => isUsable(s, o.now));
|
||||
if (!usable.length) throw new PeppaError(`Нет активных подписок среди ${source}${candidates.length ? "" : " (пул пуст)"} — проверьте их в «Подписках»`);
|
||||
const counts = await activeSessionCounts(db);
|
||||
return usable.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best));
|
||||
}
|
||||
|
||||
/** Claude token for one-off calls on behalf of a project (incident triage): the project's pool. */
|
||||
export async function claudeTokenForProject(db: Db, project: Pick<Project, "id">): Promise<string | null> {
|
||||
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, project.id));
|
||||
if (p?.poolId == null) return null;
|
||||
const s = (await poolSubscriptions(db, p.poolId)).find((x) => x.provider === "claude" && isUsable(x) && x.secretEnc);
|
||||
return s ? subscriptionSecret(s) : null;
|
||||
}
|
||||
|
||||
/** Pool name of a project (for the project settings), or null. */
|
||||
export async function projectPool(db: Db, projectId: number): Promise<SubscriptionPool | null> {
|
||||
const [row] = await db
|
||||
.select({ pool: subscriptionPools })
|
||||
.from(projects)
|
||||
.innerJoin(subscriptionPools, eq(projects.subscriptionPoolId, subscriptionPools.id))
|
||||
.where(and(eq(projects.id, projectId)));
|
||||
return row?.pool ?? null;
|
||||
}
|
||||
@ -179,20 +179,6 @@ export async function consumeLoginLink(db: Db, code: string): Promise<number | n
|
||||
return Date.now() < saved.expiresAt ? saved.userId : null;
|
||||
}
|
||||
|
||||
export async function setClaudeToken(db: Db, userId: number, token: string | null): Promise<void> {
|
||||
await db
|
||||
.update(users)
|
||||
.set({ claudeTokenEnc: token ? encrypt(token) : null, claudeTokenSetAt: token ? new Date() : null })
|
||||
.where(eq(users.id, userId));
|
||||
}
|
||||
|
||||
/** The decrypted Claude token of a project's owner, if they connected Claude. */
|
||||
export async function claudeTokenForProject(db: Db, project: Pick<Project, "ownerId">): Promise<string | null> {
|
||||
if (!project.ownerId) return null;
|
||||
const u = await getUser(db, project.ownerId);
|
||||
return u?.claudeTokenEnc ? decrypt(u.claudeTokenEnc) : null;
|
||||
}
|
||||
|
||||
export async function listUsers(db: Db): Promise<User[]> {
|
||||
return db.select().from(users).orderBy(asc(users.login));
|
||||
}
|
||||
|
||||
54
packages/db/migrations/0003_subscriptions.sql
Normal file
54
packages/db/migrations/0003_subscriptions.sql
Normal file
@ -0,0 +1,54 @@
|
||||
CREATE TABLE `subscription_pool_members` (
|
||||
`pool_id` integer NOT NULL,
|
||||
`subscription_id` integer NOT NULL,
|
||||
PRIMARY KEY(`pool_id`, `subscription_id`),
|
||||
FOREIGN KEY (`pool_id`) REFERENCES `subscription_pools`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `subscription_pools` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`created_by` integer,
|
||||
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
|
||||
FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `subscription_pools_name_unique` ON `subscription_pools` (`name`);--> statement-breakpoint
|
||||
CREATE TABLE `subscriptions` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`provider` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`auth_kind` text NOT NULL,
|
||||
`secret_enc` text,
|
||||
`key_provider` text,
|
||||
`status` text DEFAULT 'pending' NOT NULL,
|
||||
`limited_until` integer,
|
||||
`last_error` text,
|
||||
`checked_at` integer,
|
||||
`activated_at` integer,
|
||||
`created_by` integer,
|
||||
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
|
||||
FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `projects` ADD `subscription_pool_id` integer REFERENCES subscription_pools(id) ON DELETE set null;--> statement-breakpoint
|
||||
ALTER TABLE `sessions` ADD `subscription_id` integer REFERENCES subscriptions(id) ON DELETE set null;--> statement-breakpoint
|
||||
-- PEP-67 data: the PEP-13 Claude token of every user becomes a subscription «Claude — <login>»
|
||||
-- (same ciphertext: same PEPPA_SECRET key), a pool of the same name, and the default pool of the
|
||||
-- projects that user owns — sessions keep running on the same account. Then the token is cleared.
|
||||
INSERT INTO `subscriptions` (`provider`, `name`, `auth_kind`, `secret_enc`, `status`, `activated_at`, `created_by`)
|
||||
SELECT 'claude', 'Claude — ' || `login`, 'oauth', `claude_token_enc`, 'active', coalesce(`claude_token_set_at`, cast(unixepoch('subsec') * 1000 as integer)), `id`
|
||||
FROM `users` WHERE `claude_token_enc` IS NOT NULL;--> statement-breakpoint
|
||||
INSERT OR IGNORE INTO `subscription_pools` (`name`, `created_by`)
|
||||
SELECT 'Claude — ' || `login`, `id` FROM `users` WHERE `claude_token_enc` IS NOT NULL;--> statement-breakpoint
|
||||
INSERT OR IGNORE INTO `subscription_pool_members` (`pool_id`, `subscription_id`)
|
||||
SELECT p.`id`, s.`id` FROM `users` u
|
||||
JOIN `subscription_pools` p ON p.`name` = 'Claude — ' || u.`login`
|
||||
JOIN `subscriptions` s ON s.`name` = 'Claude — ' || u.`login` AND s.`created_by` = u.`id` AND s.`provider` = 'claude'
|
||||
WHERE u.`claude_token_enc` IS NOT NULL;--> statement-breakpoint
|
||||
UPDATE `projects` SET `subscription_pool_id` = (
|
||||
SELECT p.`id` FROM `users` u JOIN `subscription_pools` p ON p.`name` = 'Claude — ' || u.`login`
|
||||
WHERE u.`id` = `projects`.`owner_id` AND u.`claude_token_enc` IS NOT NULL
|
||||
) WHERE `subscription_pool_id` IS NULL AND `owner_id` IN (SELECT `id` FROM `users` WHERE `claude_token_enc` IS NOT NULL);--> statement-breakpoint
|
||||
UPDATE `users` SET `claude_token_enc` = NULL, `claude_token_set_at` = NULL WHERE `claude_token_enc` IS NOT NULL;
|
||||
2570
packages/db/migrations/meta/0003_snapshot.json
Normal file
2570
packages/db/migrations/meta/0003_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -22,6 +22,13 @@
|
||||
"when": 1794608096959,
|
||||
"tag": "0002_local_users",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "6",
|
||||
"when": 1794608984819,
|
||||
"tag": "0003_subscriptions",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
||||
import { integer, primaryKey, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
|
||||
|
||||
// SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is
|
||||
// text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only.
|
||||
@ -22,8 +22,8 @@ export const users = sqliteTable("users", {
|
||||
accessTokenEnc: text("access_token_enc"),
|
||||
refreshTokenEnc: text("refresh_token_enc"),
|
||||
tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
|
||||
// Long-lived Claude Code token from `claude setup-token` (encrypted); used for the
|
||||
// Claude sessions of this user's projects.
|
||||
// Deprecated (PEP-67): the PEP-13 Claude token moved to `subscriptions`; the migration
|
||||
// copies it there and clears these columns. Not read by the code any more.
|
||||
claudeTokenEnc: text("claude_token_enc"),
|
||||
claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }),
|
||||
// Telegram chat paired from Settings; agent questions of this user's projects go there.
|
||||
@ -58,6 +58,8 @@ export const projects = sqliteTable("projects", {
|
||||
ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }),
|
||||
// Next task number to hand out; bumped atomically on task creation.
|
||||
nextTaskNumber: integer("next_task_number").notNull().default(1),
|
||||
// PEP-67: default subscription pool for the project's runners (set by a superadmin).
|
||||
subscriptionPoolId: integer("subscription_pool_id").references((): AnySQLiteColumn => subscriptionPools.id, { onDelete: "set null" }),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
@ -187,13 +189,58 @@ export const sessionStatus = { enumValues: [
|
||||
"failed",
|
||||
] as const };
|
||||
|
||||
/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
|
||||
export const agentProviders = { enumValues: ["claude", "codex", "opencode"] as const };
|
||||
|
||||
/**
|
||||
* PEP-67: an agent subscription (Claude Code / Codex / OpenCode) managed by superadmins.
|
||||
* Claude: OAuth token from `claude setup-token` in `secret_enc`; Codex: the login lives in
|
||||
* its own CODEX_HOME ($PEPPA_HOME/subscriptions/s<id>/codex); OpenCode: a model provider
|
||||
* API key in `secret_enc`. Secrets are AES-256-GCM encrypted with PEPPA_SECRET.
|
||||
*/
|
||||
export const subscriptions = sqliteTable("subscriptions", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
provider: text("provider", { enum: agentProviders.enumValues }).notNull(),
|
||||
name: text("name").notNull(),
|
||||
authKind: text("auth_kind", { enum: ["oauth", "api_key", "device"] }).notNull(),
|
||||
secretEnc: text("secret_enc"),
|
||||
// OpenCode: which model provider the key belongs to (anthropic | openai | openrouter).
|
||||
keyProvider: text("key_provider"),
|
||||
status: text("status", { enum: ["pending", "active", "limited", "auth_error"] }).notNull().default("pending"),
|
||||
limitedUntil: integer("limited_until", { mode: "timestamp_ms" }),
|
||||
lastError: text("last_error"),
|
||||
checkedAt: integer("checked_at", { mode: "timestamp_ms" }),
|
||||
// Became active at least once (a cancelled first login deletes the row).
|
||||
activatedAt: integer("activated_at", { mode: "timestamp_ms" }),
|
||||
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/** PEP-67: a named set of subscriptions runners take from (rotation within it — PEP-39). */
|
||||
export const subscriptionPools = sqliteTable("subscription_pools", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
name: text("name").notNull().unique(),
|
||||
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
export const subscriptionPoolMembers = sqliteTable(
|
||||
"subscription_pool_members",
|
||||
{
|
||||
poolId: integer("pool_id").notNull().references(() => subscriptionPools.id, { onDelete: "cascade" }),
|
||||
subscriptionId: integer("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }),
|
||||
},
|
||||
(t) => [primaryKey({ columns: [t.poolId, t.subscriptionId] })],
|
||||
);
|
||||
|
||||
/** An agent CLI session (Claude Code, Codex or OpenCode) running in tmux on this machine. */
|
||||
export const sessions = sqliteTable("sessions", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
||||
tmuxName: text("tmux_name").notNull().unique(),
|
||||
provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"),
|
||||
provider: text("provider", { enum: agentProviders.enumValues }).notNull().default("claude"),
|
||||
// PEP-67: the subscription the session runs on (null = this machine's own login).
|
||||
subscriptionId: integer("subscription_id").references(() => subscriptions.id, { onDelete: "set null" }),
|
||||
// Claude session id or Codex thread id — the resume target.
|
||||
conversationId: text("claude_session_id"),
|
||||
// Bumped on every launch/resume; hooks from an older generation are ignored.
|
||||
|
||||
@ -1,90 +0,0 @@
|
||||
// "Connect Claude" from the web: runs `claude setup-token` on this machine in a tmux
|
||||
// session, hands the sign-in URL to the user, types back the code they paste into the
|
||||
// web form, and stores the resulting long-lived token (encrypted) on the user.
|
||||
import { homedir } from "node:os";
|
||||
import { deleteSetting, getSetting, PeppaError, setClaudeToken, setSetting } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
const SETUP_TTL_MS = 10 * 60_000;
|
||||
const URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/;
|
||||
const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/;
|
||||
const ERROR_RE = /(error|invalid|failed|expired)/i;
|
||||
|
||||
const sessionName = (userId: number) => `peppa-auth-u${userId}`;
|
||||
const settingKey = (userId: number) => `claude.setup.u${userId}`;
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
export interface ClaudeSetup {
|
||||
url: string;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
/** Pending setup of this user (null if none or expired). */
|
||||
export async function pendingClaudeSetup(db: Db, userId: number): Promise<ClaudeSetup | null> {
|
||||
const s = await getSetting<ClaudeSetup>(db, settingKey(userId));
|
||||
if (!s) return null;
|
||||
if (Date.now() - s.startedAt > SETUP_TTL_MS || !(await tmux.hasSession(sessionName(userId)))) {
|
||||
await cancelClaudeSetup(db, userId);
|
||||
return null;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export async function cancelClaudeSetup(db: Db, userId: number): Promise<void> {
|
||||
await deleteSetting(db, settingKey(userId));
|
||||
if (await tmux.hasSession(sessionName(userId))) await tmux.killSession(sessionName(userId)).catch(() => {});
|
||||
}
|
||||
|
||||
/** Starts `claude setup-token` and returns the sign-in URL to show the user. */
|
||||
export async function startClaudeSetup(db: Db, userId: number): Promise<ClaudeSetup> {
|
||||
await cancelClaudeSetup(db, userId);
|
||||
await tmux.newSession({
|
||||
name: sessionName(userId),
|
||||
cwd: homedir(),
|
||||
command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`,
|
||||
env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine
|
||||
width: 1000,
|
||||
});
|
||||
for (let i = 0; i < 60; i++) {
|
||||
await sleep(500);
|
||||
const url = URL_RE.exec(await tmux.capturePane(sessionName(userId)))?.[0];
|
||||
if (url) {
|
||||
const setup = { url, startedAt: Date.now() };
|
||||
await setSetting(db, settingKey(userId), setup);
|
||||
return setup;
|
||||
}
|
||||
}
|
||||
const tail = await tmux.capturePane(sessionName(userId)).catch(() => "");
|
||||
await cancelClaudeSetup(db, userId);
|
||||
throw new PeppaError(`claude setup-token не показал ссылку входа${tail.trim() ? `: ${tail.trim().split("\n").slice(-3).join(" ")}` : ""}`);
|
||||
}
|
||||
|
||||
/** Types the user's code into setup-token and stores the token it prints. */
|
||||
export async function finishClaudeSetup(db: Db, userId: number, code: string): Promise<void> {
|
||||
const c = code.trim();
|
||||
if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов");
|
||||
if (!(await pendingClaudeSetup(db, userId))) throw new PeppaError("Подключение не начато или истекло — нажмите «Подключить Claude» ещё раз");
|
||||
const name = sessionName(userId);
|
||||
const before = await tmux.capturePane(name);
|
||||
await tmux.sendText(name, c);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
await sleep(500);
|
||||
const screen = await tmux.capturePane(name, 200);
|
||||
const token = TOKEN_RE.exec(screen)?.[0];
|
||||
if (token) {
|
||||
await setClaudeToken(db, userId, token);
|
||||
await cancelClaudeSetup(db, userId); // also wipes the token from the tmux scrollback
|
||||
return;
|
||||
}
|
||||
const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length);
|
||||
const dead = (await tmux.paneState(name)).dead;
|
||||
if (dead || ERROR_RE.test(after)) {
|
||||
const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" ");
|
||||
await cancelClaudeSetup(db, userId);
|
||||
throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`);
|
||||
}
|
||||
}
|
||||
await cancelClaudeSetup(db, userId);
|
||||
throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново.");
|
||||
}
|
||||
@ -6,7 +6,8 @@ export * from "./run-settings.ts";
|
||||
export * from "./providers.ts";
|
||||
export * from "./provision.ts";
|
||||
export * from "./flow.ts";
|
||||
export * from "./claude-auth.ts";
|
||||
export * from "./subscription-login.ts";
|
||||
export * from "./subscriptions.ts";
|
||||
export * from "./share.ts";
|
||||
export * from "./limits.ts";
|
||||
export * from "./monitor.ts";
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Session } from "@peppa/core";
|
||||
import { peppaRoot } from "@peppa/shared";
|
||||
import { writeRunRules, writeRunSettings } from "./run-settings.ts";
|
||||
import { runDir, writeRunRules, writeRunSettings } from "./run-settings.ts";
|
||||
|
||||
export type Provider = Session["provider"];
|
||||
export const PROVIDERS: Provider[] = ["claude", "codex"];
|
||||
export const PROVIDERS: Provider[] = ["claude", "codex", "opencode"];
|
||||
|
||||
// PEPPA_ROOT first: inside a Next.js build import.meta.url points into .next/.
|
||||
const ROOT = () => peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."));
|
||||
@ -25,7 +26,12 @@ export interface LaunchContext {
|
||||
|
||||
/** argv for one run of the agent CLI (executable first). */
|
||||
export function buildCommand(provider: Provider, c: LaunchContext): string[] {
|
||||
return provider === "codex" ? codexCommand(c) : claudeCommand(c);
|
||||
return provider === "codex" ? codexCommand(c) : provider === "opencode" ? opencodeCommand(c) : claudeCommand(c);
|
||||
}
|
||||
|
||||
/** Extra environment the provider's CLI needs for this run (OpenCode reads its config from a file). */
|
||||
export function providerEnv(provider: Provider, c: Pick<LaunchContext, "sessionId" | "generation">): Record<string, string> {
|
||||
return provider === "opencode" ? { OPENCODE_CONFIG: join(runDir(c.sessionId, c.generation), "opencode.json") } : {};
|
||||
}
|
||||
|
||||
function claudeCommand(c: LaunchContext): string[] {
|
||||
@ -69,3 +75,32 @@ function codexCommand(c: LaunchContext): string[] {
|
||||
c.prompt,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenCode (PEP-67): TUI in tmux; rules and the peppa MCP server come from a generated
|
||||
* opencode.json (OPENCODE_CONFIG, see providerEnv). It has no Claude-style hooks — the
|
||||
* watchdog follows the process (alive, dead, stalled); hooks via an OpenCode plugin later.
|
||||
*/
|
||||
function opencodeCommand(c: LaunchContext): string[] {
|
||||
const dir = runDir(c.sessionId, c.generation);
|
||||
writeFileSync(
|
||||
join(dir, "opencode.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
instructions: [writeRunRules(c.sessionId, c.generation, c.rules)],
|
||||
mcp: { peppa: { type: "local", command: [MCP_BIN()], enabled: true } },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return [
|
||||
process.env.PEPPA_OPENCODE_BIN ?? "opencode",
|
||||
c.cwd,
|
||||
...(c.model ? ["--model", c.model] : []),
|
||||
...(c.resume ? ["--session", c.resume] : []),
|
||||
"--prompt",
|
||||
c.prompt,
|
||||
];
|
||||
}
|
||||
|
||||
@ -2,7 +2,8 @@ import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
claudeTokenForProject,
|
||||
getSubscription,
|
||||
pickSubscription,
|
||||
createSession,
|
||||
expireSessionQuestions,
|
||||
getSession,
|
||||
@ -20,7 +21,8 @@ import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { trustWorkspace } from "./claude-config.ts";
|
||||
import { buildCommand, type Provider } from "./providers.ts";
|
||||
import { buildCommand, providerEnv, type Provider } from "./providers.ts";
|
||||
import { subscriptionEnv } from "./subscriptions.ts";
|
||||
import { runDir } from "./run-settings.ts";
|
||||
import * as tmux from "./tmux.ts";
|
||||
import { onReleaseAnswer } from "./deploy.ts";
|
||||
@ -33,6 +35,9 @@ export interface StartOptions {
|
||||
/** Project for a bare task number ("42"). */
|
||||
defaultProjectKey?: string;
|
||||
provider?: Provider;
|
||||
/** PEP-67: subscriptions ticked at launch (multiple choice); else `poolId`; else the project's pool. */
|
||||
subscriptionIds?: number[];
|
||||
poolId?: number | null;
|
||||
}
|
||||
|
||||
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
|
||||
@ -44,9 +49,11 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions
|
||||
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
|
||||
const cwd = realpathSync(dir);
|
||||
|
||||
const provider = opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
|
||||
// PEP-67: the first free active subscription of the chosen set decides the provider.
|
||||
const sub = await pickSubscription(db, { projectId: ref.project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider: opts.provider });
|
||||
const provider = sub?.provider ?? opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
|
||||
if (provider === "claude") trustWorkspace(cwd);
|
||||
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider });
|
||||
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider, subscriptionId: sub?.id ?? null });
|
||||
const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`;
|
||||
await updateSession(db, session.id, { tmuxName });
|
||||
const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n");
|
||||
@ -84,8 +91,8 @@ async function launch(
|
||||
): Promise<SessionView> {
|
||||
const generation = s.generation + 1;
|
||||
const rules = await loadSharedRules();
|
||||
const [owner] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, s.projectId));
|
||||
const claudeToken = s.provider === "claude" && owner ? await claudeTokenForProject(db, owner) : null;
|
||||
// The session's subscription (no rotation on resume — PEP-39); none = this machine's login.
|
||||
const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
|
||||
const argv = buildCommand(s.provider, {
|
||||
sessionId: s.id,
|
||||
generation,
|
||||
@ -98,6 +105,7 @@ async function launch(
|
||||
});
|
||||
// tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux
|
||||
// command line, and leaves a record of exactly what was started.
|
||||
const ctx = { sessionId: s.id, generation };
|
||||
const launchScript = join(runDir(s.id, generation), "launch.sh");
|
||||
writeFileSync(launchScript, `#!/bin/bash\nexec ${argv.map(shq).join(" ")}\n`);
|
||||
chmodSync(launchScript, 0o700);
|
||||
@ -114,8 +122,9 @@ async function launch(
|
||||
// Hooks and the MCP server must talk to the same DB / state dir as the runner.
|
||||
PEPPA_DB: loadEnv().PEPPA_DB,
|
||||
...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}),
|
||||
// The project owner's own Claude subscription, if they connected it (PEP-13).
|
||||
...(claudeToken ? { CLAUDE_CODE_OAUTH_TOKEN: claudeToken } : {}),
|
||||
...providerEnv(s.provider, ctx),
|
||||
// The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
|
||||
...(sub ? subscriptionEnv(sub) : {}),
|
||||
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
|
||||
},
|
||||
});
|
||||
@ -129,6 +138,7 @@ async function launch(
|
||||
tmuxName: s.tmuxName,
|
||||
prompt: opts.prompt,
|
||||
provider: s.provider,
|
||||
subscriptionId: sub?.id ?? null,
|
||||
rulesSource: rules.source,
|
||||
});
|
||||
return getSession(db, s.id);
|
||||
|
||||
242
packages/runner/src/subscription-login.ts
Normal file
242
packages/runner/src/subscription-login.ts
Normal file
@ -0,0 +1,242 @@
|
||||
// Sign-in of agent subscriptions from the web (PEP-13 → PEP-67): the agent CLI's own login
|
||||
// runs on this machine in a tmux session (`peppa-auth-sub<id>`); the superadmin opens the
|
||||
// link on their device and, for Claude, pastes the code back into the web form.
|
||||
// Claude — `claude setup-token`: URL → code → long-lived token, stored encrypted.
|
||||
// Codex — `codex login --device-auth` with the subscription's own CODEX_HOME: URL + one-time
|
||||
// code; Codex itself writes auth.json there when the user confirms on their device.
|
||||
import { execFile } from "node:child_process";
|
||||
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
deleteSetting,
|
||||
deleteSubscription,
|
||||
getSetting,
|
||||
getSubscription,
|
||||
PeppaError,
|
||||
setSetting,
|
||||
updateSubscription,
|
||||
type Subscription,
|
||||
} from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { peppaHome } from "@peppa/shared";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
const LOGIN_TTL_MS = 10 * 60_000;
|
||||
const CLAUDE_URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/;
|
||||
const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/;
|
||||
const ERROR_RE = /(error|invalid|failed|expired)/i;
|
||||
const CODEX_URL_RE = /https:\/\/\S+/;
|
||||
const CODEX_CODE_RE = /\b[A-Z0-9]{4,5}-[A-Z0-9]{4,5}\b/;
|
||||
|
||||
const sessionName = (id: number) => `peppa-auth-sub${id}`;
|
||||
const settingKey = (id: number) => `subscription.login:${id}`;
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/** Login dir of a subscription (Codex: CODEX_HOME). Private: the CLI keeps credentials there. */
|
||||
export function subscriptionDir(id: number): string {
|
||||
return join(peppaHome(), "subscriptions", `s${id}`);
|
||||
}
|
||||
export function codexHome(id: number): string {
|
||||
const dir = join(subscriptionDir(id), "codex");
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
return dir;
|
||||
}
|
||||
|
||||
export interface PendingLogin {
|
||||
kind: "claude" | "codex";
|
||||
url: string;
|
||||
/** Codex device auth: the one-time code to enter on the device. */
|
||||
code?: string;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
/** Pending sign-in of a subscription (null if none or expired). */
|
||||
export async function pendingLogin(db: Db, id: number): Promise<PendingLogin | null> {
|
||||
const s = await getSetting<PendingLogin>(db, settingKey(id));
|
||||
if (!s) return null;
|
||||
if (Date.now() - s.startedAt > LOGIN_TTL_MS || !(await tmux.hasSession(sessionName(id)))) {
|
||||
await endLogin(db, id);
|
||||
return null;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
async function endLogin(db: Db, id: number): Promise<void> {
|
||||
await deleteSetting(db, settingKey(id));
|
||||
if (await tmux.hasSession(sessionName(id))) await tmux.killSession(sessionName(id)).catch(() => {});
|
||||
}
|
||||
|
||||
/** Cancels a sign-in; a subscription that was never active disappears with it. */
|
||||
export async function cancelLogin(db: Db, id: number): Promise<void> {
|
||||
await endLogin(db, id);
|
||||
const s = await getSubscription(db, id).catch(() => null);
|
||||
if (s && !s.activatedAt) await removeSubscription(db, id);
|
||||
}
|
||||
|
||||
/** Deletes a subscription with its login dir (and any sign-in in progress). */
|
||||
export async function removeSubscription(db: Db, id: number): Promise<void> {
|
||||
await endLogin(db, id);
|
||||
await deleteSubscription(db, id);
|
||||
rmSync(subscriptionDir(id), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function waitForScreen(id: number, re: RegExp, what: string): Promise<string> {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
await sleep(500);
|
||||
const screen = await tmux.capturePane(sessionName(id), 200).catch(() => "");
|
||||
if (re.test(screen)) return screen;
|
||||
if ((await tmux.paneState(sessionName(id)).catch(() => ({ dead: true }))).dead) break;
|
||||
}
|
||||
const tail = (await tmux.capturePane(sessionName(id)).catch(() => "")).trim();
|
||||
throw new PeppaError(`${what} не показал ссылку входа${tail ? `: ${tail.split("\n").slice(-3).join(" ").slice(0, 200)}` : ""}`);
|
||||
}
|
||||
|
||||
// ── Claude ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Starts `claude setup-token` for a Claude subscription and returns the sign-in URL. */
|
||||
export async function startClaudeLogin(db: Db, id: number): Promise<PendingLogin> {
|
||||
const sub = await getSubscription(db, id);
|
||||
if (sub.provider !== "claude") throw new PeppaError("Это не подписка Claude");
|
||||
await endLogin(db, id);
|
||||
await tmux.newSession({
|
||||
name: sessionName(id),
|
||||
cwd: homedir(),
|
||||
command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`,
|
||||
env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine
|
||||
width: 1000,
|
||||
});
|
||||
try {
|
||||
const url = CLAUDE_URL_RE.exec(await waitForScreen(id, CLAUDE_URL_RE, "claude setup-token"))![0];
|
||||
const login: PendingLogin = { kind: "claude", url, startedAt: Date.now() };
|
||||
await setSetting(db, settingKey(id), login);
|
||||
return login;
|
||||
} catch (e) {
|
||||
await endLogin(db, id);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Types the code into setup-token and stores the token it prints on the subscription. */
|
||||
export async function finishClaudeLogin(db: Db, id: number, code: string): Promise<void> {
|
||||
const c = code.trim();
|
||||
if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов");
|
||||
const login = await pendingLogin(db, id);
|
||||
if (login?.kind !== "claude") throw new PeppaError("Вход не начат или истёк — начните заново");
|
||||
const name = sessionName(id);
|
||||
const before = await tmux.capturePane(name);
|
||||
await tmux.sendText(name, c);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
await sleep(500);
|
||||
const screen = await tmux.capturePane(name, 200);
|
||||
const token = TOKEN_RE.exec(screen)?.[0];
|
||||
if (token) {
|
||||
await updateSubscription(db, id, { secret: token, authKind: "oauth", status: "active", checkedAt: new Date() });
|
||||
await endLogin(db, id); // also wipes the token from the tmux scrollback
|
||||
return;
|
||||
}
|
||||
const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length);
|
||||
const dead = (await tmux.paneState(name)).dead;
|
||||
if (dead || ERROR_RE.test(after)) {
|
||||
const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" ");
|
||||
await endLogin(db, id);
|
||||
throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`);
|
||||
}
|
||||
}
|
||||
await endLogin(db, id);
|
||||
throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново.");
|
||||
}
|
||||
|
||||
/** A ready token pasted by hand (from `claude setup-token` run elsewhere). */
|
||||
export async function setClaudeSubscriptionToken(db: Db, id: number, token: string): Promise<void> {
|
||||
const t = token.trim();
|
||||
if (!TOKEN_RE.test(t) || TOKEN_RE.exec(t)![0] !== t) throw new PeppaError("Это не похоже на токен Claude (sk-ant-oat…)");
|
||||
await endLogin(db, id);
|
||||
await updateSubscription(db, id, { secret: t, authKind: "oauth", status: "active", checkedAt: new Date() });
|
||||
}
|
||||
|
||||
// ── Codex ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Starts `codex login --device-auth` with the subscription's CODEX_HOME: URL + one-time code. */
|
||||
export async function startCodexLogin(db: Db, id: number): Promise<PendingLogin> {
|
||||
const sub = await getSubscription(db, id);
|
||||
if (sub.provider !== "codex") throw new PeppaError("Это не подписка Codex");
|
||||
await endLogin(db, id);
|
||||
await tmux.newSession({
|
||||
name: sessionName(id),
|
||||
cwd: homedir(),
|
||||
command: `${process.env.PEPPA_CODEX_BIN ?? "codex"} login --device-auth`,
|
||||
env: { CODEX_HOME: codexHome(id), BROWSER: "/usr/bin/true" },
|
||||
width: 300,
|
||||
});
|
||||
try {
|
||||
const screen = await waitForScreen(id, CODEX_CODE_RE, "codex login");
|
||||
const url = CODEX_URL_RE.exec(screen)?.[0];
|
||||
if (!url) throw new PeppaError("codex login не показал ссылку входа");
|
||||
const login: PendingLogin = { kind: "codex", url, code: CODEX_CODE_RE.exec(screen)![0], startedAt: Date.now() };
|
||||
await setSetting(db, settingKey(id), login);
|
||||
await updateSubscription(db, id, { authKind: "device" });
|
||||
return login;
|
||||
} catch (e) {
|
||||
await endLogin(db, id);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a Codex device sign-in stands: still waiting for the user, done (auth.json written,
|
||||
* subscription active) or failed. Called by the page while it shows the code.
|
||||
*/
|
||||
export async function pollCodexLogin(db: Db, id: number): Promise<"pending" | "active" | "failed" | "none"> {
|
||||
const login = await getSetting<PendingLogin>(db, settingKey(id));
|
||||
if (login?.kind !== "codex") return "none";
|
||||
const name = sessionName(id);
|
||||
const state = (await tmux.hasSession(name)) ? await tmux.paneState(name) : { dead: true, exitStatus: null };
|
||||
if (!state.dead) {
|
||||
if (Date.now() - login.startedAt > LOGIN_TTL_MS) {
|
||||
await endLogin(db, id);
|
||||
await updateSubscription(db, id, { status: "auth_error", lastError: "вход не подтверждён за 10 минут" });
|
||||
return "failed";
|
||||
}
|
||||
return "pending";
|
||||
}
|
||||
const screen = await tmux.capturePane(name, 200).catch(() => "");
|
||||
await endLogin(db, id);
|
||||
if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) {
|
||||
await updateSubscription(db, id, { status: "active", checkedAt: new Date() });
|
||||
return "active";
|
||||
}
|
||||
const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200);
|
||||
await updateSubscription(db, id, { status: "auth_error", lastError: msg || `codex login завершился с кодом ${state.exitStatus}` });
|
||||
return "failed";
|
||||
}
|
||||
|
||||
/** API key for Codex: `codex login --with-api-key` (key on stdin, never in argv or logs). */
|
||||
export async function setCodexApiKey(db: Db, id: number, key: string): Promise<void> {
|
||||
const k = key.trim();
|
||||
if (!k || /\s/.test(k)) throw new PeppaError("Вставьте ключ целиком, без пробелов");
|
||||
await endLogin(db, id);
|
||||
const out = await new Promise<{ code: number | null; text: string }>((resolve) => {
|
||||
const child = execFile(
|
||||
process.env.PEPPA_CODEX_BIN ?? "codex",
|
||||
["login", "--with-api-key"],
|
||||
{ env: { ...process.env, CODEX_HOME: codexHome(id) }, timeout: 60_000 },
|
||||
(err, stdout, stderr) => resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, text: `${stdout}${stderr}` }),
|
||||
);
|
||||
child.stdin?.end(`${k}\n`);
|
||||
});
|
||||
if (out.code !== 0) {
|
||||
await updateSubscription(db, id, { status: "auth_error", authKind: "api_key", lastError: mask(out.text, [k]).trim().slice(-200) });
|
||||
throw new PeppaError(`Codex не принял ключ: ${mask(out.text, [k]).trim().split("\n").slice(-1)[0]?.slice(0, 200) ?? ""}`);
|
||||
}
|
||||
await updateSubscription(db, id, { status: "active", authKind: "api_key", checkedAt: new Date() });
|
||||
}
|
||||
|
||||
/** Removes secrets from CLI output before it is stored or shown. */
|
||||
export function mask(text: string, secrets: Array<string | null | undefined>): string {
|
||||
let t = text.replace(TOKEN_RE, "sk-ant-…").replace(/\bsk-[A-Za-z0-9_-]{16,}/g, "sk-…");
|
||||
for (const s of secrets) if (s && s.length > 6) t = t.split(s).join("…");
|
||||
return t;
|
||||
}
|
||||
|
||||
export type { Subscription };
|
||||
128
packages/runner/src/subscriptions.ts
Normal file
128
packages/runner/src/subscriptions.ts
Normal file
@ -0,0 +1,128 @@
|
||||
// Agent subscriptions on this machine (PEP-67): the environment an agent CLI gets for a
|
||||
// subscription, and «Проверить» — a short trial run that updates the subscription's status.
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createSubscription, getSubscription, OPENCODE_KEY_ENV, PeppaError, subscriptionSecret, updateSubscription, type Subscription } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { parseResetTime } from "./limits.ts";
|
||||
import { codexHome, mask, removeSubscription, setClaudeSubscriptionToken, setCodexApiKey, startClaudeLogin, startCodexLogin } from "./subscription-login.ts";
|
||||
|
||||
/** Environment for the agent CLI running on this subscription. */
|
||||
export function subscriptionEnv(s: Subscription): Record<string, string> {
|
||||
switch (s.provider) {
|
||||
case "claude": {
|
||||
const token = subscriptionSecret(s);
|
||||
return token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {};
|
||||
}
|
||||
case "codex":
|
||||
return { CODEX_HOME: codexHome(s.id) };
|
||||
case "opencode": {
|
||||
const key = subscriptionSecret(s);
|
||||
const env = s.keyProvider ? OPENCODE_KEY_ENV[s.keyProvider] : undefined;
|
||||
return key && env ? { [env]: key } : {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface NewSubscription {
|
||||
provider: Subscription["provider"];
|
||||
name: string;
|
||||
/** claude: "login" (setup-token) | "token"; codex: "device" | "api_key"; opencode: key. */
|
||||
method: string;
|
||||
secret?: string;
|
||||
keyProvider?: string;
|
||||
createdBy: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a subscription the way the superadmin chose: Claude/Codex sign-in starts right away
|
||||
* (the page then shows the link), a pasted token or key makes it active at once.
|
||||
*/
|
||||
export async function addSubscription(db: Db, n: NewSubscription): Promise<Subscription> {
|
||||
if (n.provider === "opencode") {
|
||||
if (!n.secret?.trim()) throw new PeppaError("Вставьте ключ провайдера");
|
||||
const s = await createSubscription(db, { provider: "opencode", name: n.name, authKind: "api_key", secret: n.secret.trim(), keyProvider: n.keyProvider, createdBy: n.createdBy });
|
||||
return updateSubscription(db, s.id, { status: "active" });
|
||||
}
|
||||
const authKind = n.method === "api_key" ? "api_key" : n.method === "device" ? "device" : "oauth";
|
||||
const s = await createSubscription(db, { provider: n.provider, name: n.name, authKind, createdBy: n.createdBy });
|
||||
try {
|
||||
if (n.provider === "claude" && n.method === "token") await setClaudeSubscriptionToken(db, s.id, n.secret ?? "");
|
||||
else if (n.provider === "claude") await startClaudeLogin(db, s.id);
|
||||
else if (n.method === "api_key") await setCodexApiKey(db, s.id, n.secret ?? "");
|
||||
else await startCodexLogin(db, s.id);
|
||||
} catch (e) {
|
||||
await removeSubscription(db, s.id);
|
||||
throw e;
|
||||
}
|
||||
return getSubscription(db, s.id);
|
||||
}
|
||||
|
||||
const LIMIT_RE = /(usage limit|rate limit|limit reached|hit your limit|limit will reset|quota exceeded|too many requests|\b429\b)/i;
|
||||
const PROBE_PROMPT = "Ответь одним словом: ok";
|
||||
|
||||
function probeArgs(s: Subscription): { bin: string; args: string[] } {
|
||||
switch (s.provider) {
|
||||
case "claude":
|
||||
return { bin: process.env.PEPPA_CLAUDE_BIN ?? "claude", args: ["-p", PROBE_PROMPT, "--max-turns", "1"] };
|
||||
case "codex":
|
||||
return { bin: process.env.PEPPA_CODEX_BIN ?? "codex", args: ["exec", "--skip-git-repo-check", PROBE_PROMPT] };
|
||||
case "opencode":
|
||||
return { bin: process.env.PEPPA_OPENCODE_BIN ?? "opencode", args: ["run", PROBE_PROMPT] };
|
||||
}
|
||||
}
|
||||
|
||||
export interface CheckResult {
|
||||
status: Subscription["status"];
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* «Проверить»: a short non-interactive run of the CLI on this subscription in an empty dir.
|
||||
* Exit 0 → active; a limit message → limited (until the reset time, else for an hour);
|
||||
* anything else → auth error with the CLI's last lines (secrets masked).
|
||||
*/
|
||||
export async function checkSubscription(db: Db, id: number, now = new Date()): Promise<CheckResult> {
|
||||
const s = await getSubscription(db, id);
|
||||
if (s.status === "pending") throw new PeppaError("Сначала завершите вход");
|
||||
const { bin, args } = probeArgs(s);
|
||||
const env = subscriptionEnv(s);
|
||||
const timeoutMs = Number(process.env.PEPPA_SUBSCRIPTION_CHECK_TIMEOUT_MS ?? 60_000);
|
||||
const cwd = mkdtempSync(join(tmpdir(), "peppa-sub-check-"));
|
||||
let out: { code: number | null; text: string };
|
||||
try {
|
||||
out = await new Promise((resolve) => {
|
||||
const child = spawn(bin, args, { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
||||
let text = "";
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
process.kill(-child.pid!, "SIGKILL");
|
||||
} catch {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
resolve({ code: null, text: `${text}\nне ответил за ${Math.round(timeoutMs / 1000)} с` });
|
||||
}, timeoutMs);
|
||||
child.stdout.on("data", (d) => (text += d));
|
||||
child.stderr.on("data", (d) => (text += d));
|
||||
child.on("error", (e) => (clearTimeout(timer), resolve({ code: 127, text: e.message })));
|
||||
child.on("close", (code) => (clearTimeout(timer), resolve({ code, text })));
|
||||
});
|
||||
} finally {
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
const text = mask(out.text, Object.values(env)).trim();
|
||||
const tail = text.split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 300);
|
||||
if (LIMIT_RE.test(out.text)) {
|
||||
const until = parseResetTime(out.text, now) ?? new Date(now.getTime() + 60 * 60_000);
|
||||
await updateSubscription(db, id, { status: "limited", limitedUntil: until, lastError: tail, checkedAt: now });
|
||||
return { status: "limited", message: tail };
|
||||
}
|
||||
if (out.code === 0) {
|
||||
await updateSubscription(db, id, { status: "active", checkedAt: now });
|
||||
return { status: "active", message: tail };
|
||||
}
|
||||
await updateSubscription(db, id, { status: "auth_error", lastError: tail || `код ${out.code}`, checkedAt: now });
|
||||
return { status: "auth_error", message: tail };
|
||||
}
|
||||
@ -65,7 +65,7 @@ export function parseTriageOutput(stdout: string): TriageDecision | null {
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs `$PEPPA_TRIAGE_BIN -p` (default `claude`) on the project owner's Claude subscription. */
|
||||
/** Runs `$PEPPA_TRIAGE_BIN -p` (default `claude`) on a Claude subscription of the project's pool (PEP-67). */
|
||||
export async function runTriage(db: Db, project: Project, i: Incident, pmPrompt: string): Promise<TriageResult> {
|
||||
const bin = process.env.PEPPA_TRIAGE_BIN ?? "claude";
|
||||
const TIMEOUT_MS = Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000);
|
||||
|
||||
4
packages/testkit/bin/mock-opencode
Executable file
4
packages/testkit/bin/mock-opencode
Executable file
@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Mock opencode CLI for Peppa tests and manual runs (see packages/testkit/src/mock-agent.ts).
|
||||
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" opencode "$@"
|
||||
@ -4,17 +4,22 @@
|
||||
// paste, single-key permission dialog). Behaviour comes from a scenario file, so tests can
|
||||
// drive every customer journey: approvals, questions, permissions, limits, hangs, crashes.
|
||||
//
|
||||
// Usage: mock-agent.ts <claude|codex> [cli args...]
|
||||
// OpenCode (PEP-67): `opencode <dir> --prompt <p> [--session <id>]` with rules and the MCP
|
||||
// server from $OPENCODE_CONFIG; no hooks. Subcommands for subscription sign-in and checks:
|
||||
// `claude setup-token`, `claude -p`, `codex login --device-auth|--with-api-key`, `codex exec`,
|
||||
// `opencode run`.
|
||||
//
|
||||
// Usage: mock-agent.ts <claude|codex|opencode> [cli args...]
|
||||
// Typing "!{json action}" as a prompt runs that action — handy for manual runs.
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import type { Action, Scenario } from "./scenario.ts";
|
||||
|
||||
type Provider = "claude" | "codex";
|
||||
type Provider = "claude" | "codex" | "opencode";
|
||||
const provider = process.argv[2] as Provider;
|
||||
const argv = process.argv.slice(3);
|
||||
const cwd = process.cwd();
|
||||
@ -50,6 +55,10 @@ function parseArgs(): Args {
|
||||
else if (x === "--append-system-prompt-file") a.rulesFile = argv[++i];
|
||||
else if (x === "--resume") a.resume = argv[++i];
|
||||
else if (x === "resume") a.resume = argv[++i];
|
||||
else if (provider === "opencode" && x === "--session") a.resume = argv[++i];
|
||||
else if (provider === "opencode" && x === "--prompt") {
|
||||
a.prompt = argv[++i];
|
||||
} else if (provider === "opencode" && x === "--model") i++;
|
||||
else if (x === "-c") {
|
||||
const [k, ...v] = argv[++i]!.split("=");
|
||||
const val = JSON.parse(v.join("="));
|
||||
@ -62,6 +71,12 @@ function parseArgs(): Args {
|
||||
}
|
||||
|
||||
const args = parseArgs();
|
||||
// OpenCode: rules (instructions) and the peppa MCP server come from the generated config.
|
||||
if (provider === "opencode" && process.env.OPENCODE_CONFIG && existsSync(process.env.OPENCODE_CONFIG)) {
|
||||
const cfg = JSON.parse(readFileSync(process.env.OPENCODE_CONFIG, "utf8"));
|
||||
args.rulesFile = cfg.instructions?.[0];
|
||||
args.mcpCommand = cfg.mcp?.peppa?.command?.[0];
|
||||
}
|
||||
const conversationId = args.resume ?? randomUUID();
|
||||
let lastMessage = "";
|
||||
|
||||
@ -340,13 +355,15 @@ async function main() {
|
||||
rulesChars: rules.length,
|
||||
rulesHead: rules.split("\n")[0],
|
||||
oauthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN ? `…${process.env.CLAUDE_CODE_OAUTH_TOKEN.slice(-4)}` : null,
|
||||
codexHome: process.env.CODEX_HOME ?? null,
|
||||
apiKey: apiKey() ? `…${apiKey()!.slice(-4)}` : null,
|
||||
});
|
||||
|
||||
if (process.stdin.isTTY) process.stdin.setRawMode(true);
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", onInput);
|
||||
process.stdout.write("\x1b[?2004h"); // ask the terminal for bracketed paste
|
||||
out(`${provider === "claude" ? "✻ Mock Claude Code" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`);
|
||||
out(`${provider === "claude" ? "✻ Mock Claude Code" : provider === "opencode" ? "▣ Mock OpenCode" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`);
|
||||
|
||||
if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup");
|
||||
|
||||
@ -386,7 +403,76 @@ async function setupToken() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
(argv[0] === "setup-token" ? setupToken() : main()).catch((e) => {
|
||||
const apiKey = () => process.env.ANTHROPIC_API_KEY ?? process.env.OPENAI_API_KEY ?? process.env.OPENROUTER_API_KEY;
|
||||
|
||||
/**
|
||||
* Trial runs for «Проверить» (`claude -p`, `codex exec`, `opencode run`): the credential's
|
||||
* text decides — "bad" → auth error, "limit" → usage limit banner with a reset time, else ok.
|
||||
*/
|
||||
function probe(): never {
|
||||
const fail = (msg: string) => (process.stderr.write(`${msg}\n`), process.exit(1));
|
||||
let cred: string | undefined;
|
||||
if (provider === "claude") cred = process.env.CLAUDE_CODE_OAUTH_TOKEN ?? "mock-machine-login";
|
||||
else if (provider === "opencode") cred = apiKey();
|
||||
else {
|
||||
const auth = join(process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex"), "auth.json");
|
||||
cred = existsSync(auth) ? readFileSync(auth, "utf8") : undefined;
|
||||
}
|
||||
if (!cred) fail(provider === "codex" ? "Not logged in. Run `codex login`." : "Error: no API key configured");
|
||||
if (cred!.includes("bad")) fail(provider === "claude" ? "Invalid API key · Please run /login" : "Error: 401 Unauthorized: invalid credentials");
|
||||
if (cred!.includes("limit")) fail(provider === "claude" ? "Claude AI usage limit reached. Your limit resets 5pm" : "You've hit your usage limit. Try again at 5:00 PM.");
|
||||
process.stdout.write("ok\n");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* `codex login --device-auth`: prints the device URL and a one-time code like the real CLI,
|
||||
* then waits until the test "confirms on the device" ($CODEX_HOME/mock-device-approved or
|
||||
* …-denied) and writes auth.json. `codex login --with-api-key`: key on stdin.
|
||||
*/
|
||||
async function codexLogin() {
|
||||
const home = process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex");
|
||||
mkdirSync(home, { recursive: true });
|
||||
if (argv.includes("--with-api-key")) {
|
||||
let key = "";
|
||||
for await (const chunk of process.stdin) key += chunk;
|
||||
key = key.trim();
|
||||
if (!key || key.startsWith("mock-bad")) {
|
||||
process.stderr.write("Error: invalid API key\n");
|
||||
process.exit(1);
|
||||
}
|
||||
writeFileSync(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: key }));
|
||||
process.stdout.write("Successfully logged in\n");
|
||||
process.exit(0);
|
||||
}
|
||||
const code = `MOCK-${randomUUID().slice(0, 4).toUpperCase().replace(/[^A-Z0-9]/g, "Q")}`;
|
||||
out("\nWelcome to Codex [mock]\nFollow these steps to sign in with ChatGPT using device code authorization:\n\n");
|
||||
out("1. Open this link in your browser and sign in to your account\n https://auth.openai.com/codex/device\n\n");
|
||||
out(`2. Enter this one-time code (expires in 15 minutes)\n ${code}\n\n`);
|
||||
for (;;) {
|
||||
await sleep(200);
|
||||
if (existsSync(join(home, "mock-device-denied"))) {
|
||||
out("Error logging in with device code: device authorization was denied\n");
|
||||
process.exit(1);
|
||||
}
|
||||
if (existsSync(join(home, "mock-device-approved"))) {
|
||||
const extra = readFileSync(join(home, "mock-device-approved"), "utf8");
|
||||
writeFileSync(join(home, "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { access_token: `mock-chatgpt-${randomUUID()}${extra.trim()}` } }));
|
||||
out("Successfully logged in\n");
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sub =
|
||||
provider === "claude" && argv[0] === "setup-token"
|
||||
? setupToken()
|
||||
: (provider === "claude" && argv[0] === "-p") || (provider === "codex" && argv[0] === "exec") || (provider === "opencode" && argv[0] === "run")
|
||||
? Promise.resolve(probe())
|
||||
: provider === "codex" && argv[0] === "login"
|
||||
? codexLogin()
|
||||
: main();
|
||||
sub.catch((e) => {
|
||||
log("fatal", { error: String(e?.stack ?? e) });
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@ -1,54 +0,0 @@
|
||||
// PEP-13: connect Claude from the web (setup-token in tmux) and use the token in sessions.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
|
||||
let user: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
before(async () => {
|
||||
user = await core.upsertUserFromGitea(db, { id: 31, login: "mock-claude-user" }, { access_token: "x" });
|
||||
});
|
||||
after(teardown);
|
||||
|
||||
describe("connect Claude", () => {
|
||||
test("wrong code → error, nothing stored; right code → encrypted token", async () => {
|
||||
const s1 = await runner.startClaudeSetup(db, user.id);
|
||||
assert.match(s1.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/);
|
||||
assert.deepEqual((await runner.pendingClaudeSetup(db, user.id))?.url, s1.url);
|
||||
await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-bad-code"), /не принял код/);
|
||||
assert.equal((await core.getUser(db, user.id))?.claudeTokenEnc, null);
|
||||
assert.equal(await runner.pendingClaudeSetup(db, user.id), null, "failed setup is cleaned up");
|
||||
await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-good-1"), /не начато/);
|
||||
|
||||
await runner.startClaudeSetup(db, user.id);
|
||||
await runner.finishClaudeSetup(db, user.id, "mock-good-1");
|
||||
const u = (await core.getUser(db, user.id))!;
|
||||
assert.ok(u.claudeTokenEnc && !u.claudeTokenEnc.includes("sk-ant"), "stored encrypted");
|
||||
assert.match(core.decrypt(u.claudeTokenEnc), /^sk-ant-oat01-mock/);
|
||||
assert.ok(u.claudeTokenSetAt);
|
||||
assert.equal(await runner.pendingClaudeSetup(db, user.id), null);
|
||||
});
|
||||
|
||||
test("sessions of the owner's projects get the token; other projects and disconnect don't", async () => {
|
||||
const token = core.decrypt((await core.getUser(db, user.id))!.claudeTokenEnc!);
|
||||
const mine = await project({ turns: [[{ say: "ok" }]] });
|
||||
await core.setProjectOwner(db, (await core.getProject(db, mine.key)).id, user.id);
|
||||
const sid = await mine.start();
|
||||
const start = await mine.waitLog("started", (e) => e.ev === "start");
|
||||
assert.equal(start.oauthToken, `…${token.slice(-4)}`);
|
||||
await runner.stopSession(db, sid);
|
||||
|
||||
const other = await project({ turns: [[{ say: "ok" }]] });
|
||||
const sid2 = await other.start();
|
||||
assert.equal((await other.waitLog("started", (e) => e.ev === "start")).oauthToken, null);
|
||||
await runner.stopSession(db, sid2);
|
||||
|
||||
await core.setClaudeToken(db, user.id, null);
|
||||
const again = await project({ turns: [[{ say: "ok" }]] });
|
||||
await core.setProjectOwner(db, (await core.getProject(db, again.key)).id, user.id);
|
||||
const sid3 = await again.start();
|
||||
assert.equal((await again.waitLog("started", (e) => e.ev === "start")).oauthToken, null);
|
||||
await runner.stopSession(db, sid3);
|
||||
});
|
||||
});
|
||||
@ -20,6 +20,7 @@ Object.assign(process.env, {
|
||||
PEPPA_TMUX_SOCKET: `peppa-test-${process.pid}`,
|
||||
PEPPA_CLAUDE_BIN: join(ROOT, "packages/testkit/bin/mock-claude"),
|
||||
PEPPA_CODEX_BIN: join(ROOT, "packages/testkit/bin/mock-codex"),
|
||||
PEPPA_OPENCODE_BIN: join(ROOT, "packages/testkit/bin/mock-opencode"),
|
||||
PEPPA_MOCK_MCP_BIN: join(ROOT, "packages/mcp/bin/peppa-mcp"),
|
||||
PEPPA_CLAUDE_CONFIG: join(TMP, "claude.json"),
|
||||
PEPPA_HOOK_WAIT_SEC: "4",
|
||||
@ -74,7 +75,7 @@ export interface TestProject {
|
||||
key: string;
|
||||
dir: string;
|
||||
taskKey: string;
|
||||
start(opts?: { provider?: "claude" | "codex" }): Promise<number>;
|
||||
start(opts?: { provider?: "claude" | "codex" | "opencode"; subscriptionIds?: number[]; poolId?: number | null }): Promise<number>;
|
||||
log(): MockLogEntry[];
|
||||
waitLog(label: string, pred: (e: MockLogEntry) => boolean, timeoutMs?: number): Promise<MockLogEntry>;
|
||||
session(id: number): ReturnType<typeof core.getSession>;
|
||||
@ -105,7 +106,7 @@ export async function project(scenario: Scenario): Promise<TestProject> {
|
||||
dir,
|
||||
taskKey: ref.key,
|
||||
async start(opts = {}) {
|
||||
const s = await runner.startSession(db, ref.key, { provider: opts.provider });
|
||||
const s = await runner.startSession(db, ref.key, opts);
|
||||
return s.id;
|
||||
},
|
||||
log,
|
||||
|
||||
253
packages/testkit/test/subscriptions.test.ts
Normal file
253
packages/testkit/test/subscriptions.test.ts
Normal file
@ -0,0 +1,253 @@
|
||||
// PEP-67: agent subscriptions (Claude Code / Codex / OpenCode), pools and the subscription a
|
||||
// runner starts on. Sign-in and trial runs go through the mock CLIs (mock-claude, mock-codex,
|
||||
// mock-opencode) with the real contracts: setup-token, device auth, --with-api-key, -p/exec/run.
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
|
||||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let asel: User;
|
||||
let dana: User;
|
||||
before(async () => {
|
||||
asel = await core.upsertUserFromGitea(db, { id: 41, login: "asel" }, { access_token: "x" });
|
||||
dana = await core.upsertUserFromGitea(db, { id: 42, login: "mock-dana" }, { access_token: "x" });
|
||||
await core.setPlatformAdmins(db, ["asel", "admin"]);
|
||||
});
|
||||
after(teardown);
|
||||
|
||||
const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag.replace(/[^A-Za-z0-9]/g, "")}`;
|
||||
const claudeSub = (name: string, tag = name) =>
|
||||
runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: asel.id });
|
||||
const sub = (id: number) => core.getSubscription(db, id);
|
||||
|
||||
describe("Раздел «Подписки» только для суперадмина", () => {
|
||||
test("суперадмин — логин из platform.admins, остальным раздела нет", async () => {
|
||||
assert.equal(await core.isSuperadmin(db, asel), true);
|
||||
assert.equal(await core.isSuperadmin(db, { login: "ADMIN" }), true);
|
||||
assert.equal(await core.isSuperadmin(db, dana), false);
|
||||
assert.equal(await core.isSuperadmin(db, null), false);
|
||||
await assert.rejects(core.requireSuperadmin(db, dana), /Не найдено/);
|
||||
await core.requireSuperadmin(db, asel);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Подписка агента", () => {
|
||||
test("суперадмин добавляет подписку Claude: ссылка → код → активна, токен зашифрован", async () => {
|
||||
const s = await runner.addSubscription(db, { provider: "claude", name: "Claude Max — asel", method: "login", createdBy: asel.id });
|
||||
assert.equal(s.status, "pending");
|
||||
const login = await runner.pendingLogin(db, s.id);
|
||||
assert.match(login!.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/);
|
||||
await runner.finishClaudeLogin(db, s.id, "mock-good-1");
|
||||
const got = await sub(s.id);
|
||||
assert.equal(got.status, "active");
|
||||
assert.ok(got.secretEnc && !got.secretEnc.includes("sk-ant"), "stored encrypted");
|
||||
assert.match(core.decrypt(got.secretEnc), /^sk-ant-oat01-mock/);
|
||||
assert.equal(await runner.pendingLogin(db, s.id), null);
|
||||
const listed = (await core.listSubscriptions(db)).find((x) => x.id === s.id)!;
|
||||
assert.equal(listed.createdByLogin, "asel");
|
||||
assert.equal(listed.activeSessions, 0);
|
||||
});
|
||||
|
||||
test("неверный код Claude: ошибка, подписка не активна; отмена удаляет новую подписку", async () => {
|
||||
const s = await runner.addSubscription(db, { provider: "claude", name: "Claude bad", method: "login", createdBy: asel.id });
|
||||
await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-bad-code"), /не принял код/);
|
||||
assert.equal((await sub(s.id)).status, "pending");
|
||||
assert.equal((await sub(s.id)).secretEnc, null);
|
||||
await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-good-1"), /не начат/);
|
||||
await runner.cancelLogin(db, s.id);
|
||||
await assert.rejects(sub(s.id), /не найдена/);
|
||||
});
|
||||
|
||||
test("Codex через ChatGPT: ссылка и одноразовый код, вход в собственном CODEX_HOME", async () => {
|
||||
const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT Pro", method: "device", createdBy: asel.id });
|
||||
const login = (await runner.pendingLogin(db, s.id))!;
|
||||
assert.equal(login.url, "https://auth.openai.com/codex/device");
|
||||
assert.match(login.code!, /^MOCK-[A-Z0-9]{4}$/);
|
||||
assert.equal(await runner.pollCodexLogin(db, s.id), "pending");
|
||||
writeFileSync(join(runner.codexHome(s.id), "mock-device-approved"), "");
|
||||
await waitFor("codex login done", async () => (await runner.pollCodexLogin(db, s.id)) === "active");
|
||||
assert.equal((await sub(s.id)).status, "active");
|
||||
assert.ok(existsSync(join(runner.codexHome(s.id), "auth.json")));
|
||||
assert.ok(runner.codexHome(s.id).startsWith(process.env.PEPPA_HOME!));
|
||||
});
|
||||
|
||||
test("Codex: отказ на устройстве → ошибка входа", async () => {
|
||||
const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT denied", method: "device", createdBy: asel.id });
|
||||
writeFileSync(join(runner.codexHome(s.id), "mock-device-denied"), "");
|
||||
await waitFor("codex login failed", async () => (await runner.pollCodexLogin(db, s.id)) === "failed");
|
||||
const got = await sub(s.id);
|
||||
assert.equal(got.status, "auth_error");
|
||||
assert.match(got.lastError!, /denied/);
|
||||
});
|
||||
|
||||
test("Codex по API-ключу: неверный ключ отклонён, верный — активна, ключа нет в БД", async () => {
|
||||
await assert.rejects(
|
||||
runner.addSubscription(db, { provider: "codex", name: "Codex bad key", method: "api_key", secret: "mock-bad-key-123", createdBy: asel.id }),
|
||||
/не принял ключ/,
|
||||
);
|
||||
assert.equal((await core.listSubscriptions(db)).some((x) => x.name === "Codex bad key"), false);
|
||||
const s = await runner.addSubscription(db, { provider: "codex", name: "Codex key", method: "api_key", secret: "mock-openai-key-123", createdBy: asel.id });
|
||||
assert.equal(s.status, "active");
|
||||
assert.equal(s.secretEnc, null);
|
||||
assert.match(readFileSync(join(runner.codexHome(s.id), "auth.json"), "utf8"), /mock-openai-key-123/);
|
||||
});
|
||||
|
||||
test("OpenCode по ключу провайдера: активна, ключ зашифрован", async () => {
|
||||
await assert.rejects(runner.addSubscription(db, { provider: "opencode", name: "OC", method: "api_key", secret: "k", keyProvider: "nope", createdBy: asel.id }), /провайдера/);
|
||||
const s = await runner.addSubscription(db, { provider: "opencode", name: "OpenCode Anthropic", method: "api_key", secret: "mock-anthropic-key-1", keyProvider: "anthropic", createdBy: asel.id });
|
||||
assert.equal(s.status, "active");
|
||||
assert.equal(core.subscriptionSecret(s), "mock-anthropic-key-1");
|
||||
assert.ok(!s.secretEnc!.includes("mock-anthropic"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Проверка подписки", () => {
|
||||
test("лимит → «лимит до …», отозванный вход → «ошибка входа» без секрета, рабочая → активна", async () => {
|
||||
const now = new Date("2026-11-14T10:00:00");
|
||||
const limited = await claudeSub("Claude limited", "limit");
|
||||
const r1 = await runner.checkSubscription(db, limited.id, now);
|
||||
assert.equal(r1.status, "limited");
|
||||
const l = await sub(limited.id);
|
||||
assert.equal(l.status, "limited");
|
||||
assert.equal(l.limitedUntil!.getHours(), 17, "reset time from the banner (5pm)");
|
||||
|
||||
const bad = await claudeSub("Claude revoked", "bad");
|
||||
assert.equal((await runner.checkSubscription(db, bad.id, now)).status, "auth_error");
|
||||
const b = await sub(bad.id);
|
||||
assert.match(b.lastError!, /Invalid API key/);
|
||||
assert.ok(!b.lastError!.includes(TOKEN("bad")));
|
||||
|
||||
const ok = await claudeSub("Claude ok", "fine");
|
||||
assert.equal((await runner.checkSubscription(db, ok.id, now)).status, "active");
|
||||
|
||||
const codexLimited = await runner.addSubscription(db, { provider: "codex", name: "Codex limited", method: "api_key", secret: "mock-limit-key-1", createdBy: asel.id });
|
||||
assert.equal((await runner.checkSubscription(db, codexLimited.id, now)).status, "limited");
|
||||
const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC bad", method: "api_key", secret: "mock-bad-oc-key", keyProvider: "openai", createdBy: asel.id });
|
||||
assert.equal((await runner.checkSubscription(db, oc.id, now)).status, "auth_error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Пулы и подписка сессии", () => {
|
||||
test("пул для ротации: раннеры проекта стартуют на свободной подписке пула", async () => {
|
||||
const a = await claudeSub("Claude A");
|
||||
const b = await claudeSub("Claude B");
|
||||
const c = await runner.addSubscription(db, { provider: "codex", name: "Codex C", method: "api_key", secret: "mock-openai-key-c", createdBy: asel.id });
|
||||
const pool = await core.createPool(db, { name: "Основной", subscriptionIds: [a.id, b.id, c.id], createdBy: asel.id });
|
||||
assert.deepEqual((await core.listPools(db)).find((p) => p.id === pool.id)!.subscriptionIds, [a.id, b.id, c.id]);
|
||||
|
||||
const p1 = await project({ turns: [[{ say: "ok" }]] });
|
||||
const p2 = await project({ turns: [[{ say: "ok" }]] });
|
||||
for (const p of [p1, p2]) await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||||
|
||||
const s1 = await p1.start();
|
||||
assert.equal((await p1.session(s1)).subscriptionId, a.id);
|
||||
assert.equal((await p1.session(s1)).subscriptionName, "Claude A");
|
||||
assert.equal((await p1.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${TOKEN("Claude A").slice(-4)}`);
|
||||
const s2 = await p2.start();
|
||||
assert.equal((await p2.session(s2)).subscriptionId, b.id, "A is busy → B");
|
||||
assert.equal((await core.listSubscriptions(db)).find((x) => x.id === a.id)!.activeSessions, 1);
|
||||
|
||||
// Provider asked explicitly: only the pool's Codex subscription, with its CODEX_HOME.
|
||||
const p3 = await project({ turns: [[{ say: "ok" }]] });
|
||||
await core.setProjectPool(db, (await core.getProject(db, p3.key)).id, pool.id);
|
||||
const s3 = await p3.start({ provider: "codex" });
|
||||
assert.equal((await p3.session(s3)).provider, "codex");
|
||||
assert.equal((await p3.waitLog("started", (e) => e.ev === "start")).codexHome, runner.codexHome(c.id));
|
||||
|
||||
// Resume stays on the session's subscription.
|
||||
await runner.stopSession(db, s1);
|
||||
await runner.resumeSession(db, s1);
|
||||
await waitFor("resumed run", async () => p1.log().filter((e) => e.ev === "start").length === 2);
|
||||
assert.equal(p1.log().filter((e) => e.ev === "start")[1]!.oauthToken, `…${TOKEN("Claude A").slice(-4)}`);
|
||||
for (const id of [s1, s2, s3]) await runner.stopSession(db, id);
|
||||
});
|
||||
|
||||
test("выбор при запуске: раннер стартует на одной из отмеченных подписок", async () => {
|
||||
const [x, y] = [await claudeSub("Pick X"), await claudeSub("Pick Y")];
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const s = await p.start({ subscriptionIds: [y.id, x.id] });
|
||||
assert.equal((await p.session(s)).subscriptionId, x.id, "first free by id among the ticked");
|
||||
await runner.stopSession(db, s);
|
||||
});
|
||||
|
||||
test("нет активных подписок → запуск отклонён; без пула — вход машины", async () => {
|
||||
const bad = await claudeSub("Only bad", "bad");
|
||||
await runner.checkSubscription(db, bad.id);
|
||||
const pool = await core.createPool(db, { name: "Сломанный", subscriptionIds: [bad.id] });
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||||
await assert.rejects(p.start(), /Нет активных подписок/);
|
||||
await assert.rejects(p.start({ subscriptionIds: [bad.id] }), /Нет активных подписок/);
|
||||
await assert.rejects(core.createPool(db, { name: "Сломанный", subscriptionIds: [] }), /уже есть/);
|
||||
|
||||
const free = await project({ turns: [[{ say: "ok" }]] });
|
||||
const s = await free.start();
|
||||
assert.equal((await free.session(s)).subscriptionId, null);
|
||||
assert.equal((await free.waitLog("started", (e) => e.ev === "start")).oauthToken, null);
|
||||
await runner.stopSession(db, s);
|
||||
});
|
||||
|
||||
test("OpenCode: сессия в tmux с правилами из opencode.json и ключом подписки", async () => {
|
||||
const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC session", method: "api_key", secret: "mock-or-key-777", keyProvider: "openrouter", createdBy: asel.id });
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const s = await p.start({ subscriptionIds: [oc.id] });
|
||||
const start = await p.waitLog("started", (e) => e.ev === "start");
|
||||
assert.equal(start.provider, "opencode");
|
||||
assert.equal(start.apiKey, "…-777");
|
||||
assert.ok((start.rulesChars as number) > 100, "rules from opencode.json instructions");
|
||||
assert.equal((await p.session(s)).provider, "opencode");
|
||||
await runner.stopSession(db, s);
|
||||
});
|
||||
|
||||
test("удаление подписки и пула: сессии и проекты их забывают, каталог входа удалён", async () => {
|
||||
const c = await runner.addSubscription(db, { provider: "codex", name: "To delete", method: "api_key", secret: "mock-openai-del", createdBy: asel.id });
|
||||
const pool = await core.createPool(db, { name: "Временный", subscriptionIds: [c.id] });
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const pid = (await core.getProject(db, p.key)).id;
|
||||
await core.setProjectPool(db, pid, pool.id);
|
||||
const s = await p.start();
|
||||
assert.equal((await core.projectPool(db, pid))?.name, "Временный");
|
||||
await runner.removeSubscription(db, c.id);
|
||||
assert.equal((await p.session(s)).subscriptionId, null);
|
||||
assert.ok(!existsSync(runner.subscriptionDir(c.id)));
|
||||
assert.deepEqual((await core.listPools(db)).find((x) => x.id === pool.id)!.subscriptionIds, []);
|
||||
await core.deletePool(db, pool.id);
|
||||
assert.equal(await core.projectPool(db, pid), null);
|
||||
await runner.stopSession(db, s);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Перенос токена Claude из настроек", () => {
|
||||
test("миграция: подписка «Claude — <login>» с тем же токеном, пул у проектов владельца", async () => {
|
||||
const legacy = TOKEN("legacy");
|
||||
const u = await core.upsertUserFromGitea(db, { id: 43, login: "mock-legacy" }, { access_token: "x" });
|
||||
db.$client.prepare("UPDATE users SET claude_token_enc = ?, claude_token_set_at = ? WHERE id = ?").run(core.encrypt(legacy), Date.now(), u.id);
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const pid = (await core.getProject(db, p.key)).id;
|
||||
await core.setProjectOwner(db, pid, u.id);
|
||||
|
||||
// Re-run the data part of migration 0003 on this database.
|
||||
const sql = readFileSync(join(ROOT, "packages/db/migrations/0003_subscriptions.sql"), "utf8");
|
||||
const data = sql.split("--> statement-breakpoint").map((x) => x.trim()).filter((x) => /^(--.*\n)*\s*(INSERT|UPDATE)/.test(x));
|
||||
assert.equal(data.length, 5);
|
||||
for (const stmt of data) db.$client.exec(stmt);
|
||||
|
||||
const s = (await core.listSubscriptions(db)).find((x) => x.name === "Claude — mock-legacy")!;
|
||||
assert.equal(s.status, "active");
|
||||
assert.equal(s.provider, "claude");
|
||||
assert.equal(core.subscriptionSecret(s), legacy);
|
||||
assert.equal((await core.projectPool(db, pid))?.name, "Claude — mock-legacy");
|
||||
assert.equal((await core.getUser(db, u.id))!.claudeTokenEnc, null);
|
||||
assert.equal(await core.claudeTokenForProject(db, { id: pid }), legacy);
|
||||
|
||||
const sid = await p.start();
|
||||
assert.equal((await p.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${legacy.slice(-4)}`);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user