diff --git a/openspec/changes/pep-67-subscriptions/design.md b/openspec/changes/pep-67-subscriptions/design.md index 824bce3c..df14cddb 100644 --- a/openspec/changes/pep-67-subscriptions/design.md +++ b/openspec/changes/pep-67-subscriptions/design.md @@ -46,7 +46,7 @@ OpenCode — подписка только по API-ключу провайде ## Вход Общий механизм `runner/subscriptions.ts` поверх tmux (`peppa-auth-sub`), состояние входа — `settings` `subscription.login:` (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` подписки → со страницы diff --git a/openspec/changes/pep-67-subscriptions/proposal.md b/openspec/changes/pep-67-subscriptions/proposal.md index 41b8776b..2fe8d503 100644 --- a/openspec/changes/pep-67-subscriptions/proposal.md +++ b/openspec/changes/pep-67-subscriptions/proposal.md @@ -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`, меню, настройки проекта, форма запуска, «Раннеры», «Настройки». diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 660d5184..a79cf379 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -73,7 +73,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa task set -s peppa q list [KEY] peppa q answer (delivered into the session's terminal) - peppa session start [--provider claude|codex] [-p ] [--mode ] [--model ] + peppa session start [--provider claude|codex|opencode] [-p ] [--mode ] [--model ] peppa session list [--all] peppa session send peppa session attach diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5182e36a..840698bf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ad19e314..6be52088 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.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 { // 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>, + patch: Partial>, ): Promise { 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, }; } diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts new file mode 100644 index 00000000..5b8d8e45 --- /dev/null +++ b/packages/core/src/subscriptions.ts @@ -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 = { 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 = { + 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 | null | undefined): Promise { + if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено"); +} + +// ── subscriptions ──────────────────────────────────────────────────────────────── + +async function activeSessionCounts(db: Db): Promise> { + 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 { + 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 { + 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 { + 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> & { secret?: string | null }, +): Promise { + const { secret, ...rest } = patch; + const set: Partial = { ...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 { + 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): string | null { + return s.secretEnc ? decrypt(s.secretEnc) : null; +} + +/** Active now: `active`, or `limited` whose reset time has passed. */ +export function isUsable(s: Pick, now = new Date()): boolean { + return s.status === "active" || (s.status === "limited" && !!s.limitedUntil && s.limitedUntil <= now); +} + +// ── pools ──────────────────────────────────────────────────────────────────────── + +export async function listPools(db: Db): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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): Promise { + 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 { + 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; +} diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index 3eb7cb18..f23b25a6 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -179,20 +179,6 @@ export async function consumeLoginLink(db: Db, code: string): Promise { - 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): Promise { - 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 { return db.select().from(users).orderBy(asc(users.login)); } diff --git a/packages/db/migrations/0003_subscriptions.sql b/packages/db/migrations/0003_subscriptions.sql new file mode 100644 index 00000000..246d1b12 --- /dev/null +++ b/packages/db/migrations/0003_subscriptions.sql @@ -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 — » +-- (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; \ No newline at end of file diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json new file mode 100644 index 00000000..ac8894f5 --- /dev/null +++ b/packages/db/migrations/meta/0003_snapshot.json @@ -0,0 +1,2570 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "922324fb-4f7c-4dd7-9cb7-7cb03780a882", + "prevId": "8c480919-f0f0-4006-b448-49eff5f43062", + "tables": { + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 5d4b60ba..bee3921a 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1794608096959, "tag": "0002_local_users", "breakpoints": true + }, + { + "idx": 3, + "version": "6", + "when": 1794608984819, + "tag": "0003_subscriptions", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index d2efad7a..a7e88503 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -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/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. diff --git a/packages/runner/src/claude-auth.ts b/packages/runner/src/claude-auth.ts deleted file mode 100644 index 8221df0e..00000000 --- a/packages/runner/src/claude-auth.ts +++ /dev/null @@ -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 { - const s = await getSetting(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 { - 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 { - 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 { - 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 секунд. Начните заново."); -} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index ec96a83e..3112ece5 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -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"; diff --git a/packages/runner/src/providers.ts b/packages/runner/src/providers.ts index 35ce0cce..1219278c 100644 --- a/packages/runner/src/providers.ts +++ b/packages/runner/src/providers.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): Record { + 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, + ]; +} diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 8e999444..7668e4df 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -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 { 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); diff --git a/packages/runner/src/subscription-login.ts b/packages/runner/src/subscription-login.ts new file mode 100644 index 00000000..1ff6a4c6 --- /dev/null +++ b/packages/runner/src/subscription-login.ts @@ -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`); 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 { + const s = await getSetting(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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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(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 { + 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 { + 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 }; diff --git a/packages/runner/src/subscriptions.ts b/packages/runner/src/subscriptions.ts new file mode 100644 index 00000000..54571810 --- /dev/null +++ b/packages/runner/src/subscriptions.ts @@ -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 { + 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 { + 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 { + 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 }; +} diff --git a/packages/runner/src/triage.ts b/packages/runner/src/triage.ts index fe42a8b2..0d804496 100644 --- a/packages/runner/src/triage.ts +++ b/packages/runner/src/triage.ts @@ -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 { const bin = process.env.PEPPA_TRIAGE_BIN ?? "claude"; const TIMEOUT_MS = Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000); diff --git a/packages/testkit/bin/mock-opencode b/packages/testkit/bin/mock-opencode new file mode 100755 index 00000000..065ab78c --- /dev/null +++ b/packages/testkit/bin/mock-opencode @@ -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 "$@" diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index f283efd0..9d19f8e5 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -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 [cli args...] +// OpenCode (PEP-67): `opencode --prompt

[--session ]` 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 [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); }); diff --git a/packages/testkit/test/claude-auth.test.ts b/packages/testkit/test/claude-auth.test.ts deleted file mode 100644 index 83d47458..00000000 --- a/packages/testkit/test/claude-auth.test.ts +++ /dev/null @@ -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>; -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); - }); -}); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 547ae835..d8431cfa 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -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; + start(opts?: { provider?: "claude" | "codex" | "opencode"; subscriptionIds?: number[]; poolId?: number | null }): Promise; log(): MockLogEntry[]; waitLog(label: string, pred: (e: MockLogEntry) => boolean, timeoutMs?: number): Promise; session(id: number): ReturnType; @@ -105,7 +106,7 @@ export async function project(scenario: Scenario): Promise { 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, diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts new file mode 100644 index 00000000..102d1a3c --- /dev/null +++ b/packages/testkit/test/subscriptions.test.ts @@ -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>; +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 — » с тем же токеном, пул у проектов владельца", 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); + }); +});