Adopt Cowork harness lessons: blocking hooks, generations, resume
- hooks move from the project template to a per-run --settings file - PermissionRequest / AskUserQuestion hooks wait for the PM's answer in the DB and return the decision to Claude; fall back to the terminal dialog after PEPPA_HOOK_WAIT_SEC (awaiting_hook prevents double delivery) - sessions.generation + PEPPA_GENERATION: stale hooks are ignored; peppa session resume relaunches with claude --resume - SessionEnd no longer marks the process done (/clear, /resume) - StopFailure rate_limit -> rate_limited status - MCP: agents cannot set done or approve their own proposal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
967f70ac09
commit
5184fc214c
@ -11,7 +11,13 @@
|
||||
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё
|
||||
- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd
|
||||
- `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба
|
||||
- `packages/runner` — запуск claude в tmux (`peppa-<task>-s<id>`, env `PEPPA_SESSION_ID`), доставка ответов PM в терминал, `peppa-hook` (хуки Claude Code → БД), вачдог (смерть/зависание/лимит)
|
||||
- `packages/runner` — запуск claude в tmux (`peppa-<task>-s<id>`), вачдог, `peppa-hook`
|
||||
- хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s<id>-g<gen>/settings.json` (`claude --settings`)
|
||||
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
|
||||
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
|
||||
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
|
||||
- StopFailure `rate_limit` → `rate_limited`; `peppa session resume <id>` → `claude --resume`
|
||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||
- `template/` — содержимое репо `peppa/template` (AGENTS.md и т.д.), копируется в каждый проект
|
||||
- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate)
|
||||
|
||||
|
||||
@ -21,7 +21,7 @@ import {
|
||||
type TaskStatus,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { answerAndDeliver, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { answerAndDeliver, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
|
||||
@ -42,6 +42,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa session send <id> <text>
|
||||
peppa session attach <id>
|
||||
peppa session stop <id>
|
||||
peppa session resume <id> [-p <extra prompt>] (new generation, claude --resume)
|
||||
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
||||
|
||||
KEY defaults to the project of the current directory (.peppa/project.json).
|
||||
@ -180,6 +181,11 @@ async function main(): Promise<void> {
|
||||
spawnSync("tmux", ["attach", "-t", s.tmuxName], { stdio: "inherit" });
|
||||
break;
|
||||
}
|
||||
case "session resume": {
|
||||
const s = await resumeSession(db, Number(args[0]), { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model });
|
||||
console.log(`Session #${s.id} resumed (generation ${s.generation}) → tmux attach -t ${s.tmuxName}`);
|
||||
break;
|
||||
}
|
||||
case "session stop":
|
||||
await stopSession(db, Number(args[0]));
|
||||
console.log("stopped");
|
||||
|
||||
@ -45,7 +45,7 @@ export async function listSessions(db: Db, opts: { active?: boolean; taskId?: nu
|
||||
export async function updateSession(
|
||||
db: Db,
|
||||
id: number,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "claudeSessionId" | "lastActivityAt" | "endedAt">>,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "claudeSessionId" | "generation" | "lastActivityAt" | "endedAt">>,
|
||||
): Promise<Session> {
|
||||
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
|
||||
if (!row) throw new PeppaError(`Session #${id} not found`);
|
||||
@ -62,11 +62,41 @@ export async function logSessionEvent(db: Db, s: Session, type: string, payload?
|
||||
}
|
||||
|
||||
/** Unanswered questions raised by a session (ask_pm, approvals, hook/watchdog alerts). */
|
||||
export async function pendingSessionQuestions(db: Db, sessionId: number): Promise<Question[]> {
|
||||
export async function pendingSessionQuestions(
|
||||
db: Db,
|
||||
sessionId: number,
|
||||
opts: { excludeHook?: boolean } = {},
|
||||
): Promise<Question[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(questions)
|
||||
.where(and(eq(questions.sessionId, sessionId), isNull(questions.answeredAt)));
|
||||
.where(
|
||||
and(
|
||||
eq(questions.sessionId, sessionId),
|
||||
isNull(questions.answeredAt),
|
||||
opts.excludeHook ? eq(questions.awaitingHook, false) : undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getQuestion(db: Db, id: number): Promise<Question> {
|
||||
const [row] = await db.select().from(questions).where(eq(questions.id, id));
|
||||
if (!row) throw new PeppaError(`Question #${id} not found`);
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* A blocking hook gives up waiting: from now on the answer goes to the terminal.
|
||||
* Returns the question if it got answered in the meantime (the race is settled by
|
||||
* Postgres row locking against answerQuestion).
|
||||
*/
|
||||
export async function releaseHookQuestion(db: Db, id: number): Promise<Question | null> {
|
||||
const [released] = await db
|
||||
.update(questions)
|
||||
.set({ awaitingHook: false })
|
||||
.where(and(eq(questions.id, id), isNull(questions.answeredAt)))
|
||||
.returning();
|
||||
return released ? null : getQuestion(db, id);
|
||||
}
|
||||
|
||||
/** Raises a session-level alert for the PM (permission prompt, idle, stall, crash). */
|
||||
@ -76,10 +106,11 @@ export async function raiseSessionQuestion(
|
||||
kind: QuestionKind,
|
||||
text: string,
|
||||
options?: string[],
|
||||
awaitingHook = false,
|
||||
): Promise<Question> {
|
||||
const [row] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options })
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook })
|
||||
.returning();
|
||||
await notify(db, { type: "question", questionId: row!.id });
|
||||
return row!;
|
||||
|
||||
3
packages/db/migrations/0001_chunky_dreadnoughts.sql
Normal file
3
packages/db/migrations/0001_chunky_dreadnoughts.sql
Normal file
@ -0,0 +1,3 @@
|
||||
ALTER TYPE "public"."session_status" ADD VALUE 'rate_limited' BEFORE 'done';--> statement-breakpoint
|
||||
ALTER TABLE "questions" ADD COLUMN "awaiting_hook" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "sessions" ADD COLUMN "generation" integer DEFAULT 0 NOT NULL;
|
||||
706
packages/db/migrations/meta/0001_snapshot.json
Normal file
706
packages/db/migrations/meta/0001_snapshot.json
Normal file
@ -0,0 +1,706 @@
|
||||
{
|
||||
"id": "7e63ed2b-721c-4506-a2ab-21922112a126",
|
||||
"prevId": "2281ab22-b150-4664-9ffc-a0bb54103d9c",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.events": {
|
||||
"name": "events",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"task_id": {
|
||||
"name": "task_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"session_id": {
|
||||
"name": "session_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"payload": {
|
||||
"name": "payload",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"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": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.goals": {
|
||||
"name": "goals",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "goal_status",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'open'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"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": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.projects": {
|
||||
"name": "projects",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"slug": {
|
||||
"name": "slug",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"gitea_owner": {
|
||||
"name": "gitea_owner",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"gitea_repo": {
|
||||
"name": "gitea_repo",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"default_branch": {
|
||||
"name": "default_branch",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'main'"
|
||||
},
|
||||
"workspace_path": {
|
||||
"name": "workspace_path",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"next_task_number": {
|
||||
"name": "next_task_number",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 1
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"projects_slug_unique": {
|
||||
"name": "projects_slug_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"slug"
|
||||
]
|
||||
},
|
||||
"projects_key_unique": {
|
||||
"name": "projects_key_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"key"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.questions": {
|
||||
"name": "questions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"task_id": {
|
||||
"name": "task_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"session_id": {
|
||||
"name": "session_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"kind": {
|
||||
"name": "kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"text": {
|
||||
"name": "text",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"options": {
|
||||
"name": "options",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"answer": {
|
||||
"name": "answer",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"answered_via": {
|
||||
"name": "answered_via",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"telegram_message_id": {
|
||||
"name": "telegram_message_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"awaiting_hook": {
|
||||
"name": "awaiting_hook",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"answered_at": {
|
||||
"name": "answered_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": 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": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.sessions": {
|
||||
"name": "sessions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"task_id": {
|
||||
"name": "task_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"tmux_name": {
|
||||
"name": "tmux_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"claude_session_id": {
|
||||
"name": "claude_session_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"generation": {
|
||||
"name": "generation",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "session_status",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'starting'"
|
||||
},
|
||||
"last_activity_at": {
|
||||
"name": "last_activity_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"ended_at": {
|
||||
"name": "ended_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"sessions_tmux_name_unique": {
|
||||
"name": "sessions_tmux_name_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"tmux_name"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.tasks": {
|
||||
"name": "tasks",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"goal_id": {
|
||||
"name": "goal_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"number": {
|
||||
"name": "number",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "task_status",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'backlog'"
|
||||
},
|
||||
"openspec_change": {
|
||||
"name": "openspec_change",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"pr_url": {
|
||||
"name": "pr_url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"tasks_project_number": {
|
||||
"name": "tasks_project_number",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "project_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "number",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"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": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
"enums": {
|
||||
"public.goal_status": {
|
||||
"name": "goal_status",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"open",
|
||||
"done",
|
||||
"archived"
|
||||
]
|
||||
},
|
||||
"public.session_status": {
|
||||
"name": "session_status",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"starting",
|
||||
"running",
|
||||
"waiting_input",
|
||||
"idle",
|
||||
"stalled",
|
||||
"rate_limited",
|
||||
"done",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"public.task_status": {
|
||||
"name": "task_status",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"backlog",
|
||||
"proposing",
|
||||
"awaiting_approval",
|
||||
"in_progress",
|
||||
"review",
|
||||
"done",
|
||||
"blocked"
|
||||
]
|
||||
}
|
||||
},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"roles": {},
|
||||
"policies": {},
|
||||
"views": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@ -8,6 +8,13 @@
|
||||
"when": 1794492884912,
|
||||
"tag": "0000_safe_shiver_man",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1794493804069,
|
||||
"tag": "0001_chunky_dreadnoughts",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { integer, jsonb, pgEnum, pgTable, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
||||
import { boolean, integer, jsonb, pgEnum, pgTable, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
||||
|
||||
const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
|
||||
const updatedAt = () =>
|
||||
@ -70,6 +70,7 @@ export const sessionStatus = pgEnum("session_status", [
|
||||
"waiting_input", // Claude asked something / needs permission
|
||||
"idle", // turn finished, nothing pending
|
||||
"stalled", // watchdog saw no activity
|
||||
"rate_limited", // StopFailure with error=rate_limit, or limit banner on screen
|
||||
"done",
|
||||
"failed",
|
||||
]);
|
||||
@ -81,6 +82,8 @@ export const sessions = pgTable("sessions", {
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
||||
tmuxName: text("tmux_name").notNull().unique(),
|
||||
claudeSessionId: text("claude_session_id"),
|
||||
// Bumped on every launch/resume; hooks from an older generation are ignored.
|
||||
generation: integer("generation").notNull().default(0),
|
||||
status: sessionStatus("status").notNull().default("starting"),
|
||||
lastActivityAt: timestamp("last_activity_at", { withTimezone: true }),
|
||||
startedAt: createdAt(),
|
||||
@ -100,6 +103,9 @@ export const questions = pgTable("questions", {
|
||||
answer: text("answer"),
|
||||
answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal"] }),
|
||||
telegramMessageId: integer("telegram_message_id"),
|
||||
// A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer,
|
||||
// so it must not also be typed into the terminal.
|
||||
awaitingHook: boolean("awaiting_hook").notNull().default(false),
|
||||
createdAt: createdAt(),
|
||||
answeredAt: timestamp("answered_at", { withTimezone: true }),
|
||||
});
|
||||
|
||||
@ -112,6 +112,11 @@ tool(
|
||||
},
|
||||
async ({ task, status, openspec_change, pr_url, title, description }) => {
|
||||
const ref = await resolveTask(db, task, defaultKey);
|
||||
// Acceptance stays with the PM: agents can't mark work done or approve themselves.
|
||||
if (status === "done") throw new PeppaError("Only the PM marks a task done. Open a PR and set status: review.");
|
||||
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
|
||||
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
|
||||
}
|
||||
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
|
||||
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
|
||||
},
|
||||
|
||||
@ -1,18 +1,25 @@
|
||||
// peppa-hook <event>: called by Claude Code hooks (see template/.claude/settings.json).
|
||||
// Reads the hook JSON from stdin and updates the Peppa session that PEPPA_SESSION_ID
|
||||
// points to. Must never break the Claude session: always exits 0, errors go to a log.
|
||||
// peppa-hook <event>: called by the Claude Code hooks in the per-run settings file
|
||||
// (run-settings.ts). Reads the hook JSON from stdin and updates the Peppa session that
|
||||
// PEPPA_SESSION_ID / PEPPA_GENERATION point to. Must never break the Claude session:
|
||||
// always exits 0, errors go to ~/.peppa/hook.log, and blocking hooks fall back to
|
||||
// Claude's own terminal dialog when the PM doesn't answer in time.
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
getQuestion,
|
||||
getSession,
|
||||
logSessionEvent,
|
||||
pendingSessionQuestions,
|
||||
raiseSessionQuestion,
|
||||
releaseHookQuestion,
|
||||
updateSession,
|
||||
type Question,
|
||||
type SessionView,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { createDb, type Db } from "@peppa/db";
|
||||
import { HOOK_WAIT_SEC } from "./run-settings.ts";
|
||||
|
||||
interface HookInput {
|
||||
session_id?: string;
|
||||
@ -23,7 +30,19 @@ interface HookInput {
|
||||
prompt?: string;
|
||||
reason?: string;
|
||||
source?: string;
|
||||
error?: string;
|
||||
error_details?: string;
|
||||
last_assistant_message?: string;
|
||||
tool_name?: string;
|
||||
tool_input?: Record<string, unknown>;
|
||||
permission_suggestions?: unknown[];
|
||||
}
|
||||
|
||||
interface AskQuestionItem {
|
||||
question: string;
|
||||
header?: string;
|
||||
options?: Array<{ label: string; description?: string }>;
|
||||
multiSelect?: boolean;
|
||||
}
|
||||
|
||||
const LOG = join(homedir(), ".peppa", "hook.log");
|
||||
@ -32,8 +51,10 @@ const log = (msg: string) => {
|
||||
appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`);
|
||||
} catch {}
|
||||
};
|
||||
const clip = (s: string, n = 1500) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
const output = (o: unknown) => process.stdout.write(JSON.stringify(o));
|
||||
|
||||
/** Last assistant text from the transcript JSONL — what the PM needs to see. */
|
||||
/** Last assistant text from the transcript JSONL — fallback when the hook omits it. */
|
||||
export function lastAssistantText(transcriptPath?: string): string | null {
|
||||
if (!transcriptPath) return null;
|
||||
try {
|
||||
@ -55,40 +76,127 @@ export function lastAssistantText(transcriptPath?: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const clip = (s: string, n = 1500) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
/** Polls until every question is answered, or returns null after HOOK_WAIT_SEC. */
|
||||
async function waitForAnswers(db: Db, ids: number[]): Promise<Question[] | null> {
|
||||
const deadline = Date.now() + HOOK_WAIT_SEC * 1000;
|
||||
while (Date.now() < deadline) {
|
||||
const qs = await Promise.all(ids.map((id) => getQuestion(db, id)));
|
||||
if (qs.every((q) => q.answeredAt)) return qs;
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
}
|
||||
// Give up: answers that still arrive go to the terminal instead.
|
||||
const settled = await Promise.all(ids.map((id) => releaseHookQuestion(db, id)));
|
||||
return settled.every(Boolean) ? (settled as Question[]) : null;
|
||||
}
|
||||
|
||||
function describeTool(name = "?", input: Record<string, unknown> = {}): string {
|
||||
const main = input.command ?? input.file_path ?? input.url ?? input.pattern ?? input.prompt;
|
||||
const detail = typeof main === "string" ? main : JSON.stringify(input);
|
||||
return `${name}: ${clip(detail, 600)}${typeof input.description === "string" ? `\n(${input.description})` : ""}`;
|
||||
}
|
||||
|
||||
async function permissionRequest(db: Db, s: SessionView, input: HookInput) {
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||||
const q = await raiseSessionQuestion(
|
||||
db,
|
||||
s,
|
||||
"permission",
|
||||
`Разрешить ${describeTool(input.tool_name, input.tool_input)}`,
|
||||
["allow", "always", "deny"],
|
||||
true,
|
||||
);
|
||||
const [answered] = (await waitForAnswers(db, [q.id])) ?? [];
|
||||
if (!answered) return log(`permission #${q.id}: no answer in ${HOOK_WAIT_SEC}s, falling back to terminal`);
|
||||
const a = answered.answer!.trim().toLowerCase();
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
|
||||
if (a === "allow" || a === "always") {
|
||||
output({
|
||||
hookSpecificOutput: {
|
||||
hookEventName: "PermissionRequest",
|
||||
decision: {
|
||||
behavior: "allow",
|
||||
...(a === "always" && input.permission_suggestions?.length ? { updatedPermissions: input.permission_suggestions } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const reason = a === "deny" ? "PM запретил это действие." : `PM запретил это действие: ${answered.answer}`;
|
||||
output({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "deny", message: reason } } });
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes Claude's built-in AskUserQuestion to the PM and fills in the answers. */
|
||||
async function askQuestion(db: Db, s: SessionView, input: HookInput) {
|
||||
const items = (input.tool_input?.questions as AskQuestionItem[] | undefined) ?? [];
|
||||
if (!items.length) return;
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||||
const qs: Question[] = [];
|
||||
for (const item of items) {
|
||||
const opts = item.options?.map((o) => o.label);
|
||||
const text = [item.question, ...(item.options ?? []).map((o) => `• ${o.label}${o.description ? ` — ${o.description}` : ""}`)].join("\n");
|
||||
qs.push(await raiseSessionQuestion(db, s, "question", text, opts, true));
|
||||
}
|
||||
const answered = await waitForAnswers(db, qs.map((q) => q.id));
|
||||
if (!answered) {
|
||||
// The questions stay pending; the PM's answer will be typed into the terminal.
|
||||
output({
|
||||
hookSpecificOutput: {
|
||||
hookEventName: "PreToolUse",
|
||||
permissionDecision: "deny",
|
||||
permissionDecisionReason: `Вопрос переслан PM через Пеппу (${qs.map((q) => `#${q.id}`).join(", ")}). Закончи ход — ответ придёт следующим сообщением.`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
|
||||
const answers = Object.fromEntries(items.map((item, i) => [item.question, answered[i]!.answer ?? ""]));
|
||||
output({
|
||||
hookSpecificOutput: {
|
||||
hookEventName: "PreToolUse",
|
||||
permissionDecision: "allow",
|
||||
updatedInput: { ...input.tool_input, answers },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function handle(event: string, input: HookInput): Promise<void> {
|
||||
const sessionId = Number(process.env.PEPPA_SESSION_ID);
|
||||
if (!sessionId) return; // manual `claude`, not started by Peppa
|
||||
const db = createDb();
|
||||
const s = await getSession(db, sessionId);
|
||||
// A hook from an earlier run of this session (before a resume) is stale.
|
||||
if (Number(process.env.PEPPA_GENERATION) !== s.generation) {
|
||||
return log(`${event}: stale generation ${process.env.PEPPA_GENERATION} != ${s.generation} for session #${s.id}`);
|
||||
}
|
||||
const now = new Date();
|
||||
|
||||
switch (event) {
|
||||
case "session-start":
|
||||
// Also fires after /clear and /resume, with a new Claude session id.
|
||||
await updateSession(db, s.id, { claudeSessionId: input.session_id ?? null, status: "running", lastActivityAt: now });
|
||||
await logSessionEvent(db, s, "claude_session", { source: input.source, claudeSessionId: input.session_id });
|
||||
break;
|
||||
|
||||
case "prompt": {
|
||||
// Someone typed into the terminal (or the bot pasted an answer): anything still
|
||||
// pending for this session is now answered.
|
||||
for (const q of await pendingSessionQuestions(db, s.id)) {
|
||||
case "prompt":
|
||||
// Someone typed into the terminal (or Peppa pasted an answer): anything still
|
||||
// pending for this session is now answered — except hook-held questions.
|
||||
for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true })) {
|
||||
await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {});
|
||||
}
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: now });
|
||||
break;
|
||||
}
|
||||
|
||||
case "notification": {
|
||||
const msg = input.message ?? "Claude Code ждёт внимания";
|
||||
const isPermission = input.notification_type === "permission_prompt" || /permission/i.test(msg);
|
||||
// Idle notifications duplicate the Stop alert; only permissions need their own.
|
||||
if (isPermission) {
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now });
|
||||
await raiseSessionQuestion(db, s, "permission", msg, ["allow", "always", "deny"]);
|
||||
}
|
||||
case "permission-request":
|
||||
await permissionRequest(db, s, input);
|
||||
break;
|
||||
|
||||
case "ask-question":
|
||||
await askQuestion(db, s, input);
|
||||
break;
|
||||
|
||||
case "notification":
|
||||
await logSessionEvent(db, s, "notification", { type: input.notification_type, message: input.message });
|
||||
break;
|
||||
}
|
||||
|
||||
case "stop": {
|
||||
const text = input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path);
|
||||
@ -101,9 +209,25 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
break;
|
||||
}
|
||||
|
||||
case "stop-failure": {
|
||||
const limited = input.error === "rate_limit";
|
||||
await updateSession(db, s.id, { status: limited ? "rate_limited" : "waiting_input", lastActivityAt: now });
|
||||
await logSessionEvent(db, s, "stop_failure", { error: input.error, details: input.error_details });
|
||||
await raiseSessionQuestion(
|
||||
db,
|
||||
s,
|
||||
"attention",
|
||||
limited
|
||||
? `${s.taskKey ?? `Сессия ${s.id}`} упёрлась в лимит Claude.${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`
|
||||
: `${s.taskKey ?? `Сессия ${s.id}`}: ход оборвался с ошибкой ${input.error ?? "unknown"}.${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case "session-end":
|
||||
await updateSession(db, s.id, { status: "done", endedAt: now });
|
||||
await logSessionEvent(db, s, "session_end", { reason: input.reason });
|
||||
// /clear and /resume end a Claude session inside a live process, so this is not
|
||||
// the process exiting; the watchdog decides that from the tmux pane.
|
||||
await logSessionEvent(db, s, "claude_session_end", { reason: input.reason });
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
@ -2,3 +2,4 @@ export * from "./claude-config.ts";
|
||||
export * from "./sessions.ts";
|
||||
export * as tmux from "./tmux.ts";
|
||||
export * from "./watchdog.ts";
|
||||
export * from "./run-settings.ts";
|
||||
|
||||
35
packages/runner/src/run-settings.ts
Normal file
35
packages/runner/src/run-settings.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HOOK_BIN = resolve(dirname(fileURLToPath(import.meta.url)), "../bin/peppa-hook");
|
||||
/** Blocking hooks wait for the PM this long before falling back to the terminal. */
|
||||
export const HOOK_WAIT_SEC = Number(process.env.PEPPA_HOOK_WAIT_SEC ?? 540);
|
||||
|
||||
export const RUNS_DIR = join(homedir(), ".peppa", "runs");
|
||||
|
||||
/**
|
||||
* Claude settings for one session run, passed with --settings. Hooks live here rather
|
||||
* than in each project repo, so they are versioned with Peppa and only fire for
|
||||
* sessions Peppa launched.
|
||||
*/
|
||||
export function writeRunSettings(sessionId: number, generation: number): string {
|
||||
const hook = (event: string, timeout = 30) => ({ type: "command", command: `${HOOK_BIN} ${event}`, timeout });
|
||||
const settings = {
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [hook("session-start")] }],
|
||||
UserPromptSubmit: [{ hooks: [hook("prompt")] }],
|
||||
PermissionRequest: [{ hooks: [hook("permission-request", HOOK_WAIT_SEC + 30)] }],
|
||||
PreToolUse: [{ matcher: "AskUserQuestion", hooks: [hook("ask-question", HOOK_WAIT_SEC + 30)] }],
|
||||
Notification: [{ hooks: [hook("notification")] }],
|
||||
Stop: [{ hooks: [hook("stop")] }],
|
||||
StopFailure: [{ hooks: [hook("stop-failure")] }],
|
||||
SessionEnd: [{ hooks: [hook("session-end")] }],
|
||||
},
|
||||
};
|
||||
const path = join(RUNS_DIR, `s${sessionId}-g${generation}`, "settings.json");
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify(settings, null, 2));
|
||||
return path;
|
||||
}
|
||||
@ -14,6 +14,7 @@ import {
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { trustWorkspace } from "./claude-config.ts";
|
||||
import { writeRunSettings } from "./run-settings.ts";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
export interface StartOptions {
|
||||
@ -38,28 +39,71 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions
|
||||
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id });
|
||||
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");
|
||||
return launch(db, await getSession(db, session.id), cwd, { ...opts, prompt });
|
||||
}
|
||||
|
||||
/**
|
||||
* Relaunches a finished/failed/rate-limited session in a new generation, continuing
|
||||
* the same Claude conversation (claude --resume) when its id is known.
|
||||
*/
|
||||
export async function resumeSession(db: Db, sessionId: number, opts: StartOptions = {}): Promise<SessionView> {
|
||||
const s = await getSession(db, sessionId);
|
||||
if (await tmux.hasSession(s.tmuxName)) {
|
||||
if (!(await tmux.paneState(s.tmuxName)).dead) throw new PeppaError(`Session #${s.id} is still running`);
|
||||
await tmux.killSession(s.tmuxName);
|
||||
}
|
||||
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
|
||||
const cwd = realpathSync(project!.workspacePath);
|
||||
trustWorkspace(cwd);
|
||||
const prompt = [
|
||||
`Продолжай работу${s.taskKey ? ` над задачей ${s.taskKey}` : ""}: сессия была прервана. Сверься с peppa.get_task и tasks.md.`,
|
||||
opts.prompt,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
return launch(db, s, cwd, { ...opts, prompt, resume: s.claudeSessionId ?? undefined });
|
||||
}
|
||||
|
||||
async function launch(
|
||||
db: Db,
|
||||
s: SessionView,
|
||||
cwd: string,
|
||||
opts: StartOptions & { prompt: string; resume?: string },
|
||||
): Promise<SessionView> {
|
||||
const generation = s.generation + 1;
|
||||
const settings = writeRunSettings(s.id, generation);
|
||||
const claude = process.env.PEPPA_CLAUDE_BIN ?? "claude";
|
||||
const args = [
|
||||
`--permission-mode ${shq(opts.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits")}`,
|
||||
opts.model ? `--model ${shq(opts.model)}` : "",
|
||||
shq(prompt),
|
||||
"--settings",
|
||||
settings,
|
||||
"--permission-mode",
|
||||
opts.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits",
|
||||
...(opts.model ? ["--model", opts.model] : []),
|
||||
...(opts.resume ? ["--resume", opts.resume] : []),
|
||||
"--",
|
||||
opts.prompt,
|
||||
];
|
||||
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });
|
||||
try {
|
||||
await tmux.newSession({
|
||||
name: tmuxName,
|
||||
name: s.tmuxName,
|
||||
cwd,
|
||||
command: `${claude} ${args.filter(Boolean).join(" ")}`,
|
||||
env: { PEPPA_SESSION_ID: String(session.id), PEPPA_PROJECT_DIR: cwd },
|
||||
command: [claude, ...args].map(shq).join(" "),
|
||||
env: {
|
||||
PEPPA_SESSION_ID: String(s.id),
|
||||
PEPPA_GENERATION: String(generation),
|
||||
PEPPA_PROJECT_DIR: cwd,
|
||||
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
await updateSession(db, session.id, { status: "failed", endedAt: new Date() });
|
||||
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
|
||||
throw new PeppaError(`tmux failed to start: ${(e as Error).message}`);
|
||||
}
|
||||
await updateSession(db, session.id, { status: "running", lastActivityAt: new Date() });
|
||||
await logSessionEvent(db, session, "started", { tmuxName, prompt });
|
||||
return getSession(db, session.id);
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
|
||||
await logSessionEvent(db, s, opts.resume ? "resumed" : "started", { generation, tmuxName: s.tmuxName, prompt: opts.prompt });
|
||||
return getSession(db, s.id);
|
||||
}
|
||||
|
||||
export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> {
|
||||
@ -91,6 +135,8 @@ export async function answerAndDeliver(
|
||||
via: NonNullable<Question["answeredVia"]>,
|
||||
): Promise<{ delivered: boolean; question: Question }> {
|
||||
const q = await answerQuestion(db, questionId, answer, via);
|
||||
// A blocking hook is polling for this answer and hands it to Claude itself.
|
||||
if (q.awaitingHook) return { delivered: true, question: q };
|
||||
let message = answer;
|
||||
|
||||
if (q.kind === "approval" && q.taskId) {
|
||||
|
||||
@ -76,10 +76,12 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
|
||||
});
|
||||
}
|
||||
|
||||
if (LIMIT_RE.test(screen) && !limitAlerted.has(s.id)) {
|
||||
// Fallback for limits that don't come through the StopFailure hook.
|
||||
if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && !limitAlerted.has(s.id)) {
|
||||
limitAlerted.add(s.id);
|
||||
const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? "";
|
||||
log(`${label}: usage limit`);
|
||||
await updateSession(db, s.id, { status: "rate_limited" });
|
||||
await logSessionEvent(db, s, "usage_limit", { line });
|
||||
await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Сессия ${s.id}`} упёрлась в лимит: ${line}`);
|
||||
}
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
{
|
||||
"enabledMcpjsonServers": ["peppa"],
|
||||
"enabledMcpjsonServers": [
|
||||
"peppa"
|
||||
],
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__peppa",
|
||||
@ -12,22 +14,5 @@
|
||||
"Bash(git checkout -b:*)",
|
||||
"Bash(git switch:*)"
|
||||
]
|
||||
},
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{ "hooks": [{ "type": "command", "command": "command -v peppa-hook >/dev/null && peppa-hook session-start || true" }] }
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{ "hooks": [{ "type": "command", "command": "command -v peppa-hook >/dev/null && peppa-hook prompt || true" }] }
|
||||
],
|
||||
"Notification": [
|
||||
{ "hooks": [{ "type": "command", "command": "command -v peppa-hook >/dev/null && peppa-hook notification || true" }] }
|
||||
],
|
||||
"Stop": [
|
||||
{ "hooks": [{ "type": "command", "command": "command -v peppa-hook >/dev/null && peppa-hook stop || true" }] }
|
||||
],
|
||||
"SessionEnd": [
|
||||
{ "hooks": [{ "type": "command", "command": "command -v peppa-hook >/dev/null && peppa-hook session-end || true" }] }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user