Add runner: tmux sessions, Claude hook ingestion and watchdog
- startSession: trusts the workspace in ~/.claude.json, runs interactive claude in tmux with PEPPA_SESSION_ID, remain-on-exit for crash status - answerAndDeliver: PM answers go into the terminal (permission menu keys, approval -> task status + instruction, free text via bracketed paste) - peppa-hook: session-start/prompt/notification/stop/session-end update session status and raise PM questions; never fails the Claude session - watchdog: detects dead panes, vanished sessions, stalls, usage limits; launchd agent under caffeinate (scripts/install-launchd.sh) - CLI: peppa session start|list|send|attach|stop, peppa watchdog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9824ce4c18
commit
967f70ac09
@ -11,15 +11,18 @@
|
||||
- `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-hook`, вачдог
|
||||
- `packages/runner` — запуск claude в tmux (`peppa-<task>-s<id>`, env `PEPPA_SESSION_ID`), доставка ответов PM в терминал, `peppa-hook` (хуки Claude Code → БД), вачдог (смерть/зависание/лимит)
|
||||
- `template/` — содержимое репо `peppa/template` (AGENTS.md и т.д.), копируется в каждый проект
|
||||
- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin)
|
||||
- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate)
|
||||
|
||||
## Команды
|
||||
- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
|
||||
- `pnpm typecheck`
|
||||
- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера
|
||||
- `pnpm dev:web`
|
||||
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>`
|
||||
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
|
||||
- Тест раннера без настоящего claude: `PEPPA_CLAUDE_BIN=<fake script>`, `PEPPA_CLAUDE_CONFIG=<tmp claude.json>`
|
||||
|
||||
TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`.
|
||||
Сама Пеппа тоже ведётся по OpenSpec (`openspec/`).
|
||||
|
||||
@ -3,11 +3,17 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": { "peppa": "./bin/peppa" },
|
||||
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
|
||||
"bin": {
|
||||
"peppa": "./bin/peppa"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "tsx src/index.ts",
|
||||
"typecheck": "tsc -p ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*"
|
||||
"@peppa/shared": "workspace:*",
|
||||
"@peppa/runner": "workspace:*"
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,13 +2,14 @@
|
||||
import { parseArgs } from "node:util";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
createGoal,
|
||||
createProject,
|
||||
createTask,
|
||||
findProjectFile,
|
||||
getProject,
|
||||
getSession,
|
||||
getTaskDetails,
|
||||
listSessions,
|
||||
listGoals,
|
||||
listProjects,
|
||||
listTasks,
|
||||
@ -20,6 +21,8 @@ import {
|
||||
type TaskStatus,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { answerAndDeliver, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
|
||||
const USAGE = `peppa — Peppa software factory CLI
|
||||
@ -33,7 +36,13 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa task show <PEP-42|42>
|
||||
peppa task set <PEP-42|42> -s <status>
|
||||
peppa q list [KEY]
|
||||
peppa q answer <id> <answer>
|
||||
peppa q answer <id> <answer> (delivered into the session's terminal)
|
||||
peppa session start <PEP-42|42> [-p <extra prompt>] [--mode <permission-mode>] [--model <m>]
|
||||
peppa session list [--all]
|
||||
peppa session send <id> <text>
|
||||
peppa session attach <id>
|
||||
peppa session stop <id>
|
||||
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
||||
|
||||
KEY defaults to the project of the current directory (.peppa/project.json).
|
||||
Statuses: ${TASK_STATUSES.join(", ")}`;
|
||||
@ -48,6 +57,13 @@ const { values: opts, positionals } = parseArgs({
|
||||
goal: { type: "string", short: "g" },
|
||||
status: { type: "string", short: "s" },
|
||||
help: { type: "boolean", short: "h" },
|
||||
prompt: { type: "string", short: "p" },
|
||||
mode: { type: "string" },
|
||||
model: { type: "string" },
|
||||
all: { type: "boolean" },
|
||||
once: { type: "boolean" },
|
||||
interval: { type: "string", default: "30" },
|
||||
stall: { type: "string", default: "15" },
|
||||
},
|
||||
});
|
||||
|
||||
@ -140,8 +156,42 @@ async function main(): Promise<void> {
|
||||
}
|
||||
case "q answer": {
|
||||
const [id, ...answer] = args;
|
||||
const q = await answerQuestion(db, Number(id), answer.join(" "), "terminal");
|
||||
console.log(`Answered #${q.id}`);
|
||||
const { delivered, question } = await answerAndDeliver(db, Number(id), answer.join(" "), "terminal");
|
||||
console.log(`Answered #${question.id}${delivered ? " (sent to session)" : ""}`);
|
||||
break;
|
||||
}
|
||||
case "session start": {
|
||||
const s = await startSession(db, args[0] ?? "", { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model, defaultProjectKey: here });
|
||||
console.log(`Session #${s.id} for ${s.taskKey} → tmux attach -t ${s.tmuxName}`);
|
||||
break;
|
||||
}
|
||||
case "session list":
|
||||
for (const s of await listSessions(db, { active: !opts.all })) {
|
||||
const ago = s.lastActivityAt ? `${Math.round((Date.now() - s.lastActivityAt.getTime()) / 60000)}m ago` : "-";
|
||||
console.log(`#${String(s.id).padEnd(4)} ${(s.taskKey ?? "-").padEnd(10)} ${s.status.padEnd(14)} ${ago.padEnd(9)} ${s.tmuxName}`);
|
||||
}
|
||||
break;
|
||||
case "session send":
|
||||
await sendToSession(db, Number(args[0]), args.slice(1).join(" "));
|
||||
console.log("sent");
|
||||
break;
|
||||
case "session attach": {
|
||||
const s = await getSession(db, Number(args[0]));
|
||||
spawnSync("tmux", ["attach", "-t", s.tmuxName], { stdio: "inherit" });
|
||||
break;
|
||||
}
|
||||
case "session stop":
|
||||
await stopSession(db, Number(args[0]));
|
||||
console.log("stopped");
|
||||
break;
|
||||
case "watchdog": {
|
||||
const wopts = {
|
||||
intervalMs: Number(opts.interval) * 1000,
|
||||
stallMs: Number(opts.stall) * 60000,
|
||||
log: (m: string) => console.log(`${new Date().toISOString()} ${m}`),
|
||||
};
|
||||
if (opts.once) await tick(db, wopts);
|
||||
else await runWatchdog(db, wopts);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
|
||||
@ -3,3 +3,4 @@ export * from "./notify.ts";
|
||||
export * from "./project-file.ts";
|
||||
export * from "./projects.ts";
|
||||
export * from "./tasks.ts";
|
||||
export * from "./sessions.ts";
|
||||
|
||||
@ -7,7 +7,8 @@ export type PeppaNotification =
|
||||
| { type: "question"; questionId: number }
|
||||
| { type: "question_answered"; questionId: number }
|
||||
| { type: "task_updated"; taskId: number }
|
||||
| { type: "progress"; eventId: number };
|
||||
| { type: "progress"; eventId: number }
|
||||
| { type: "session_updated"; sessionId: number };
|
||||
|
||||
/** Broadcasts via Postgres NOTIFY; the bot and web listen on EVENTS_CHANNEL. */
|
||||
export async function notify(db: Db, n: PeppaNotification): Promise<void> {
|
||||
|
||||
103
packages/core/src/sessions.ts
Normal file
103
packages/core/src/sessions.ts
Normal file
@ -0,0 +1,103 @@
|
||||
import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, desc, eq, isNull, notInArray } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import type { Question, QuestionKind } from "./tasks.ts";
|
||||
|
||||
export type Session = typeof sessions.$inferSelect;
|
||||
export type SessionStatus = (typeof sessionStatus.enumValues)[number];
|
||||
export const FINISHED_SESSION_STATUSES: SessionStatus[] = ["done", "failed"];
|
||||
|
||||
export interface SessionView extends Session {
|
||||
projectKey: string;
|
||||
taskKey: string | null;
|
||||
taskTitle: string | null;
|
||||
}
|
||||
|
||||
export async function createSession(db: Db, s: { projectId: number; taskId?: number }): Promise<Session> {
|
||||
// tmux name needs the id, so insert with a unique placeholder first.
|
||||
const [row] = await db
|
||||
.insert(sessions)
|
||||
.values({ ...s, tmuxName: `pending-${crypto.randomUUID()}` })
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export async function getSession(db: Db, id: number): Promise<SessionView> {
|
||||
const [row] = await sessionQuery(db).where(eq(sessions.id, id));
|
||||
if (!row) throw new PeppaError(`Session #${id} not found`);
|
||||
return toView(row);
|
||||
}
|
||||
|
||||
export async function listSessions(db: Db, opts: { active?: boolean; taskId?: number } = {}): Promise<SessionView[]> {
|
||||
const rows = await sessionQuery(db)
|
||||
.where(
|
||||
and(
|
||||
opts.active ? notInArray(sessions.status, FINISHED_SESSION_STATUSES) : undefined,
|
||||
opts.taskId != null ? eq(sessions.taskId, opts.taskId) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(sessions.id));
|
||||
return rows.map(toView);
|
||||
}
|
||||
|
||||
export async function updateSession(
|
||||
db: Db,
|
||||
id: number,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "claudeSessionId" | "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`);
|
||||
if (patch.status) await notify(db, { type: "session_updated", sessionId: id });
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function logSessionEvent(db: Db, s: Session, type: string, payload?: unknown) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type, payload })
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
/** Unanswered questions raised by a session (ask_pm, approvals, hook/watchdog alerts). */
|
||||
export async function pendingSessionQuestions(db: Db, sessionId: number): Promise<Question[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(questions)
|
||||
.where(and(eq(questions.sessionId, sessionId), isNull(questions.answeredAt)));
|
||||
}
|
||||
|
||||
/** Raises a session-level alert for the PM (permission prompt, idle, stall, crash). */
|
||||
export async function raiseSessionQuestion(
|
||||
db: Db,
|
||||
s: Session,
|
||||
kind: QuestionKind,
|
||||
text: string,
|
||||
options?: string[],
|
||||
): Promise<Question> {
|
||||
const [row] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options })
|
||||
.returning();
|
||||
await notify(db, { type: "question", questionId: row!.id });
|
||||
return row!;
|
||||
}
|
||||
|
||||
function sessionQuery(db: Db) {
|
||||
return db
|
||||
.select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title })
|
||||
.from(sessions)
|
||||
.innerJoin(projects, eq(sessions.projectId, projects.id))
|
||||
.leftJoin(tasks, eq(sessions.taskId, tasks.id));
|
||||
}
|
||||
|
||||
function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView {
|
||||
return {
|
||||
...r.session,
|
||||
projectKey: r.projectKey,
|
||||
taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null,
|
||||
taskTitle: r.taskTitle,
|
||||
};
|
||||
}
|
||||
7
packages/runner/bin/peppa-hook
Executable file
7
packages/runner/bin/peppa-hook
Executable file
@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
# Not a Peppa session: nothing to do, skip node startup.
|
||||
[ -z "${PEPPA_SESSION_ID:-}" ] && { cat >/dev/null; exit 0; }
|
||||
[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a
|
||||
mkdir -p "$HOME/.peppa"
|
||||
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@"
|
||||
@ -3,6 +3,19 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": { "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*" }
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"bin": {
|
||||
"peppa-hook": "./bin/peppa-hook"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"drizzle-orm": "0.45.4"
|
||||
}
|
||||
}
|
||||
|
||||
22
packages/runner/src/claude-config.ts
Normal file
22
packages/runner/src/claude-config.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
const CONFIG = process.env.PEPPA_CLAUDE_CONFIG ?? join(homedir(), ".claude.json");
|
||||
|
||||
/**
|
||||
* Marks a workspace as trusted in ~/.claude.json. Without it Claude Code ignores the
|
||||
* project's .claude/settings.json (permissions, hooks) and .mcp.json servers.
|
||||
*/
|
||||
export function trustWorkspace(dir: string): void {
|
||||
const cfg = existsSync(CONFIG) ? (JSON.parse(readFileSync(CONFIG, "utf8")) as Record<string, any>) : {};
|
||||
cfg.projects ??= {};
|
||||
const p = (cfg.projects[dir] ??= {});
|
||||
if (p.hasTrustDialogAccepted && p.hasCompletedProjectOnboarding) return;
|
||||
p.hasTrustDialogAccepted = true;
|
||||
p.hasCompletedProjectOnboarding = true;
|
||||
p.enabledMcpjsonServers = Array.from(new Set([...(p.enabledMcpjsonServers ?? []), "peppa"]));
|
||||
const tmp = `${CONFIG}.peppa-${process.pid}`;
|
||||
writeFileSync(tmp, JSON.stringify(cfg, null, 2));
|
||||
renameSync(tmp, CONFIG);
|
||||
}
|
||||
124
packages/runner/src/hook.ts
Normal file
124
packages/runner/src/hook.ts
Normal file
@ -0,0 +1,124 @@
|
||||
// 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.
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
getSession,
|
||||
logSessionEvent,
|
||||
pendingSessionQuestions,
|
||||
raiseSessionQuestion,
|
||||
updateSession,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
|
||||
interface HookInput {
|
||||
session_id?: string;
|
||||
transcript_path?: string;
|
||||
hook_event_name?: string;
|
||||
message?: string;
|
||||
notification_type?: string;
|
||||
prompt?: string;
|
||||
reason?: string;
|
||||
source?: string;
|
||||
last_assistant_message?: string;
|
||||
}
|
||||
|
||||
const LOG = join(homedir(), ".peppa", "hook.log");
|
||||
const log = (msg: string) => {
|
||||
try {
|
||||
appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
/** Last assistant text from the transcript JSONL — what the PM needs to see. */
|
||||
export function lastAssistantText(transcriptPath?: string): string | null {
|
||||
if (!transcriptPath) return null;
|
||||
try {
|
||||
const lines = readFileSync(transcriptPath, "utf8").trimEnd().split("\n");
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const entry = JSON.parse(lines[i]!);
|
||||
if (entry.type !== "assistant") continue;
|
||||
const content = entry.message?.content;
|
||||
const text = Array.isArray(content)
|
||||
? content.filter((c: { type: string }) => c.type === "text").map((c: { text: string }) => c.text).join("\n")
|
||||
: typeof content === "string"
|
||||
? content
|
||||
: "";
|
||||
if (text.trim()) return text.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
log(`transcript read failed: ${(e as Error).message}`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const clip = (s: string, n = 1500) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
|
||||
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);
|
||||
const now = new Date();
|
||||
|
||||
switch (event) {
|
||||
case "session-start":
|
||||
await updateSession(db, s.id, { claudeSessionId: input.session_id ?? null, status: "running", lastActivityAt: now });
|
||||
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)) {
|
||||
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"]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "stop": {
|
||||
const text = input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path);
|
||||
await logSessionEvent(db, s, "turn_end", { text });
|
||||
// If the agent already asked via ask_pm/request_approval, the PM has the question.
|
||||
if ((await pendingSessionQuestions(db, s.id)).length === 0) {
|
||||
await raiseSessionQuestion(db, s, "attention", clip(text ?? "Сессия закончила ход и ждёт ввода."));
|
||||
}
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now });
|
||||
break;
|
||||
}
|
||||
|
||||
case "session-end":
|
||||
await updateSession(db, s.id, { status: "done", endedAt: now });
|
||||
await logSessionEvent(db, s, "session_end", { reason: input.reason });
|
||||
break;
|
||||
|
||||
default:
|
||||
log(`unknown event ${event}`);
|
||||
}
|
||||
}
|
||||
|
||||
const event = process.argv[2] ?? "";
|
||||
let raw = "";
|
||||
try {
|
||||
raw = readFileSync(0, "utf8");
|
||||
} catch {}
|
||||
try {
|
||||
await handle(event, raw ? (JSON.parse(raw) as HookInput) : {});
|
||||
} catch (e) {
|
||||
log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`);
|
||||
}
|
||||
process.exit(0);
|
||||
@ -1,2 +1,4 @@
|
||||
// Runner + watchdog (stage 3): starts claude in tmux, ingests hook events, detects stalls.
|
||||
console.log("@peppa/runner: not implemented yet");
|
||||
export * from "./claude-config.ts";
|
||||
export * from "./sessions.ts";
|
||||
export * as tmux from "./tmux.ts";
|
||||
export * from "./watchdog.ts";
|
||||
|
||||
130
packages/runner/src/sessions.ts
Normal file
130
packages/runner/src/sessions.ts
Normal file
@ -0,0 +1,130 @@
|
||||
import { existsSync, realpathSync } from "node:fs";
|
||||
import {
|
||||
answerQuestion,
|
||||
createSession,
|
||||
getSession,
|
||||
PeppaError,
|
||||
resolveTask,
|
||||
updateSession,
|
||||
updateTask,
|
||||
logSessionEvent,
|
||||
type Question,
|
||||
type SessionView,
|
||||
} from "@peppa/core";
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { trustWorkspace } from "./claude-config.ts";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
export interface StartOptions {
|
||||
/** Extra instructions appended to the default "work on <task>" prompt. */
|
||||
prompt?: string;
|
||||
permissionMode?: string;
|
||||
model?: string;
|
||||
/** Project for a bare task number ("42"). */
|
||||
defaultProjectKey?: string;
|
||||
}
|
||||
|
||||
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
/** Starts an interactive Claude Code session for a task in a detached tmux session. */
|
||||
export async function startSession(db: Db, taskInput: string, opts: StartOptions = {}): Promise<SessionView> {
|
||||
const ref = await resolveTask(db, taskInput, opts.defaultProjectKey);
|
||||
const dir = ref.project.workspacePath;
|
||||
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
|
||||
const cwd = realpathSync(dir);
|
||||
trustWorkspace(cwd);
|
||||
|
||||
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");
|
||||
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),
|
||||
];
|
||||
try {
|
||||
await tmux.newSession({
|
||||
name: tmuxName,
|
||||
cwd,
|
||||
command: `${claude} ${args.filter(Boolean).join(" ")}`,
|
||||
env: { PEPPA_SESSION_ID: String(session.id), PEPPA_PROJECT_DIR: cwd },
|
||||
});
|
||||
} catch (e) {
|
||||
await updateSession(db, session.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);
|
||||
}
|
||||
|
||||
export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> {
|
||||
const s = await getSession(db, sessionId);
|
||||
if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`);
|
||||
await tmux.sendText(s.tmuxName, text);
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
|
||||
}
|
||||
|
||||
export async function stopSession(db: Db, sessionId: number): Promise<void> {
|
||||
const s = await getSession(db, sessionId);
|
||||
if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
|
||||
await updateSession(db, s.id, { status: "done", endedAt: new Date() });
|
||||
await logSessionEvent(db, s, "stopped");
|
||||
}
|
||||
|
||||
const APPROVE_RE = /^\s*(ok|ок|да|yes|approve|approved|одобр|lgtm|go|погнали|делай)/i;
|
||||
// Claude Code permission prompt: 1 = yes, 2 = yes and don't ask again, 3 = no.
|
||||
const PERMISSION_KEYS: Record<string, string> = { allow: "1", always: "2", deny: "3" };
|
||||
|
||||
/**
|
||||
* Records the PM's answer and delivers it into the session's terminal:
|
||||
* permission → menu choice; approval → status change + message; otherwise the text.
|
||||
*/
|
||||
export async function answerAndDeliver(
|
||||
db: Db,
|
||||
questionId: number,
|
||||
answer: string,
|
||||
via: NonNullable<Question["answeredVia"]>,
|
||||
): Promise<{ delivered: boolean; question: Question }> {
|
||||
const q = await answerQuestion(db, questionId, answer, via);
|
||||
let message = answer;
|
||||
|
||||
if (q.kind === "approval" && q.taskId) {
|
||||
const approved = APPROVE_RE.test(answer);
|
||||
const ref = await resolveTaskById(db, q.taskId);
|
||||
await updateTask(db, ref, { status: approved ? "in_progress" : "proposing" }, q.sessionId ?? undefined);
|
||||
message = approved
|
||||
? `PM одобрил proposal ${ref.key}. Статус in_progress — переходи к Apply.${answer.trim().length > 4 ? `\n\nКомментарий PM: ${answer}` : ""}`
|
||||
: `PM не одобрил proposal ${ref.key}. Доработай proposal по комментарию и снова запроси одобрение.\n\nКомментарий PM: ${answer}`;
|
||||
} else if (q.kind === "question") {
|
||||
message = `Ответ PM на вопрос #${q.id}: ${answer}`;
|
||||
}
|
||||
|
||||
if (!q.sessionId) return { delivered: false, question: q };
|
||||
const s = await getSession(db, q.sessionId);
|
||||
if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q };
|
||||
|
||||
if (q.kind === "permission") {
|
||||
const key = PERMISSION_KEYS[answer.trim().toLowerCase()];
|
||||
if (key) await tmux.sendKeys(s.tmuxName, key);
|
||||
else await tmux.sendText(s.tmuxName, answer);
|
||||
} else {
|
||||
await tmux.sendText(s.tmuxName, message);
|
||||
}
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
|
||||
return { delivered: true, question: q };
|
||||
}
|
||||
|
||||
async function resolveTaskById(db: Db, taskId: number) {
|
||||
const [row] = await db
|
||||
.select({ key: projects.key, number: tasks.number })
|
||||
.from(tasks)
|
||||
.innerJoin(projects, eq(tasks.projectId, projects.id))
|
||||
.where(eq(tasks.id, taskId));
|
||||
if (!row) throw new PeppaError(`Task #${taskId} not found`);
|
||||
return resolveTask(db, `${row.key}-${row.number}`);
|
||||
}
|
||||
81
packages/runner/src/tmux.ts
Normal file
81
packages/runner/src/tmux.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const TMUX = process.env.PEPPA_TMUX_BIN ?? "tmux";
|
||||
|
||||
async function tmux(...args: string[]): Promise<string> {
|
||||
const { stdout } = await run(TMUX, args);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
export interface NewTmuxSession {
|
||||
name: string;
|
||||
cwd: string;
|
||||
command: string;
|
||||
env: Record<string, string>;
|
||||
}
|
||||
|
||||
export async function newSession(s: NewTmuxSession): Promise<void> {
|
||||
const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
|
||||
await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", "220", "-y", "50", ...envArgs, s.command);
|
||||
// Keep the pane after claude exits so the watchdog can read the exit status.
|
||||
await tmux("set-option", "-t", s.name, "remain-on-exit", "on");
|
||||
await tmux("set-option", "-t", s.name, "history-limit", "20000");
|
||||
}
|
||||
|
||||
export async function hasSession(name: string): Promise<boolean> {
|
||||
try {
|
||||
await tmux("has-session", "-t", `=${name}`);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface PaneState {
|
||||
dead: boolean;
|
||||
exitStatus: number | null;
|
||||
}
|
||||
|
||||
export async function paneState(name: string): Promise<PaneState> {
|
||||
const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status}")).trim();
|
||||
const [dead, status] = out.split(" ");
|
||||
return { dead: dead === "1", exitStatus: status ? Number(status) : null };
|
||||
}
|
||||
|
||||
/** Visible screen (plus `history` lines of scrollback) as plain text. */
|
||||
export async function capturePane(name: string, history = 0): Promise<string> {
|
||||
return tmux("capture-pane", "-p", "-J", "-t", `=${name}:`, "-S", String(-history));
|
||||
}
|
||||
|
||||
/**
|
||||
* Types text into the pane and submits it. Uses a bracketed paste so multi-line text
|
||||
* lands as one prompt instead of being submitted line by line.
|
||||
*/
|
||||
export async function sendText(name: string, text: string, submit = true): Promise<void> {
|
||||
const buffer = `peppa-${process.pid}-${Date.now()}`;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const p = spawn(TMUX, ["load-buffer", "-b", buffer, "-"], { stdio: ["pipe", "ignore", "pipe"] });
|
||||
let err = "";
|
||||
p.stderr.on("data", (d) => (err += d));
|
||||
p.on("error", reject);
|
||||
p.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`tmux load-buffer failed: ${err}`))));
|
||||
p.stdin.end(text);
|
||||
});
|
||||
await tmux("paste-buffer", "-p", "-d", "-b", buffer, "-t", `=${name}:`);
|
||||
if (submit) {
|
||||
// Give the TUI a moment to finish handling the paste before Enter.
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
await tmux("send-keys", "-t", `=${name}:`, "Enter");
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends tmux key names (e.g. "1", "Enter", "Escape", "C-c"). */
|
||||
export async function sendKeys(name: string, ...keys: string[]): Promise<void> {
|
||||
await tmux("send-keys", "-t", `=${name}:`, ...keys);
|
||||
}
|
||||
|
||||
export async function killSession(name: string): Promise<void> {
|
||||
await tmux("kill-session", "-t", `=${name}`);
|
||||
}
|
||||
110
packages/runner/src/watchdog.ts
Normal file
110
packages/runner/src/watchdog.ts
Normal file
@ -0,0 +1,110 @@
|
||||
// Watchdog: polls Peppa's tmux sessions, tracks activity, and alerts the PM when a
|
||||
// session dies, stalls, or hits a usage limit. Run under launchd with caffeinate.
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
listSessions,
|
||||
logSessionEvent,
|
||||
pendingSessionQuestions,
|
||||
raiseSessionQuestion,
|
||||
updateSession,
|
||||
type SessionView,
|
||||
} from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
export interface WatchdogOptions {
|
||||
intervalMs: number;
|
||||
/** A running session with an unchanged screen for this long is "stalled". */
|
||||
stallMs: number;
|
||||
log?: (msg: string) => void;
|
||||
}
|
||||
|
||||
// Claude Code's limit banners ("…usage limit reached… resets 3pm", "You've hit your limit").
|
||||
const LIMIT_RE = /(usage limit reached|limit reached.{0,40}reset|you've hit your (usage )?limit|out of extra usage)/i;
|
||||
|
||||
// Screen hash per session, kept across ticks.
|
||||
const lastScreen = new Map<number, string>();
|
||||
const limitAlerted = new Set<number>();
|
||||
|
||||
export async function tick(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
const log = opts.log ?? (() => {});
|
||||
for (const s of await listSessions(db, { active: true })) {
|
||||
try {
|
||||
await checkSession(db, s, opts, log);
|
||||
} catch (e) {
|
||||
log(`session #${s.id}: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) {
|
||||
if (s.tmuxName.startsWith("pending-")) return;
|
||||
const label = `#${s.id} ${s.taskKey ?? ""} (${s.tmuxName})`;
|
||||
|
||||
if (!(await tmux.hasSession(s.tmuxName))) {
|
||||
log(`${label}: tmux session gone`);
|
||||
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
|
||||
await logSessionEvent(db, s, "tmux_gone");
|
||||
await raiseSessionQuestion(db, s, "attention", `Сессия ${s.taskKey ?? s.id} пропала (tmux-сессии больше нет).`);
|
||||
return;
|
||||
}
|
||||
|
||||
const pane = await tmux.paneState(s.tmuxName);
|
||||
if (pane.dead) {
|
||||
const ok = pane.exitStatus === 0;
|
||||
log(`${label}: claude exited with ${pane.exitStatus}`);
|
||||
const tail = (await tmux.capturePane(s.tmuxName, 30)).trimEnd().split("\n").slice(-15).join("\n");
|
||||
await updateSession(db, s.id, { status: ok ? "done" : "failed", endedAt: new Date() });
|
||||
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
|
||||
if (!ok) {
|
||||
await raiseSessionQuestion(db, s, "attention", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`);
|
||||
}
|
||||
await tmux.killSession(s.tmuxName).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
const screen = await tmux.capturePane(s.tmuxName);
|
||||
const hash = createHash("sha1").update(screen).digest("hex");
|
||||
const now = Date.now();
|
||||
let last = s.lastActivityAt?.getTime() ?? now;
|
||||
if (lastScreen.get(s.id) !== hash) {
|
||||
last = now;
|
||||
lastScreen.set(s.id, hash);
|
||||
await updateSession(db, s.id, {
|
||||
lastActivityAt: new Date(now),
|
||||
...(s.status === "stalled" ? { status: "running" as const } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (LIMIT_RE.test(screen) && !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 logSessionEvent(db, s, "usage_limit", { line });
|
||||
await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Сессия ${s.id}`} упёрлась в лимит: ${line}`);
|
||||
}
|
||||
|
||||
if (s.status === "running" && now - last > opts.stallMs) {
|
||||
log(`${label}: stalled`);
|
||||
await updateSession(db, s.id, { status: "stalled" });
|
||||
await logSessionEvent(db, s, "stalled", { idleMinutes: Math.round((now - last) / 60000) });
|
||||
if ((await pendingSessionQuestions(db, s.id)).length === 0) {
|
||||
const tail = screen.trimEnd().split("\n").slice(-12).join("\n");
|
||||
await raiseSessionQuestion(
|
||||
db,
|
||||
s,
|
||||
"attention",
|
||||
`${s.taskKey ?? `Сессия ${s.id}`}: экран не меняется ${Math.round((now - last) / 60000)} мин — похоже, зависла.\n\n${tail}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise<void> {
|
||||
const log = opts.log ?? (() => {});
|
||||
log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`);
|
||||
while (!signal?.aborted) {
|
||||
await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`));
|
||||
await new Promise((r) => setTimeout(r, opts.intervalMs));
|
||||
}
|
||||
}
|
||||
9
pnpm-lock.yaml
generated
9
pnpm-lock.yaml
generated
@ -218,6 +218,9 @@ importers:
|
||||
'@peppa/db':
|
||||
specifier: workspace:*
|
||||
version: link:../db
|
||||
'@peppa/runner':
|
||||
specifier: workspace:*
|
||||
version: link:../runner
|
||||
'@peppa/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
@ -270,12 +273,18 @@ importers:
|
||||
|
||||
packages/runner:
|
||||
dependencies:
|
||||
'@peppa/core':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
'@peppa/db':
|
||||
specifier: workspace:*
|
||||
version: link:../db
|
||||
'@peppa/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
drizzle-orm:
|
||||
specifier: 0.45.4
|
||||
version: 0.45.4(postgres@4.1.1)
|
||||
|
||||
packages/shared:
|
||||
dependencies:
|
||||
|
||||
32
scripts/install-launchd.sh
Executable file
32
scripts/install-launchd.sh
Executable file
@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs the Peppa watchdog as a launchd agent (starts at login, restarts on crash).
|
||||
# caffeinate -i keeps the Mac from idle-sleeping while the watchdog runs.
|
||||
# Remove: launchctl bootout gui/$(id -u)/quest.telecom.peppa.watchdog && rm the plist.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
LABEL=quest.telecom.peppa.watchdog
|
||||
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
|
||||
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa"
|
||||
cat > "$PLIST" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key><string>$LABEL</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/usr/bin/caffeinate</string><string>-i</string>
|
||||
<string>$ROOT/packages/cli/bin/peppa</string><string>watchdog</string>
|
||||
</array>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict><key>PATH</key><string>$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string></dict>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>KeepAlive</key><true/>
|
||||
<key>StandardOutPath</key><string>$HOME/.peppa/watchdog.log</string>
|
||||
<key>StandardErrorPath</key><string>$HOME/.peppa/watchdog.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
|
||||
launchctl bootstrap "gui/$(id -u)" "$PLIST"
|
||||
echo "watchdog installed: $PLIST (log: ~/.peppa/watchdog.log)"
|
||||
Loading…
Reference in New Issue
Block a user