peppa/packages/testkit/src/mock-agent.ts
Асель 93f38bbcba PEP-22: harden timing-sensitive e2e steps, archive change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 15:00:28 +05:00

393 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Mock Claude Code / Codex CLI. Accepts the same arguments Peppa's runner passes to the
// real CLIs, fires the real hooks (Claude) or notify program (Codex), talks to the real
// peppa MCP server, and reads terminal input the way a TUI does (raw mode, bracketed
// paste, single-key permission dialog). Behaviour comes from a scenario file, so tests can
// drive every customer journey: approvals, questions, permissions, limits, hangs, crashes.
//
// Usage: mock-agent.ts <claude|codex> [cli args...]
// 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 { 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";
const provider = process.argv[2] as Provider;
const argv = process.argv.slice(3);
const cwd = process.cwd();
const LOG = join(cwd, ".peppa", "mock-log.jsonl");
const SCENARIO = join(cwd, ".peppa", "mock-scenario.json");
function log(ev: string, data: Record<string, unknown> = {}) {
appendFileSync(LOG, `${JSON.stringify({ ev, provider, gen: process.env.PEPPA_GENERATION, t: Date.now(), ...data })}\n`);
}
const out = (s: string) => process.stdout.write(s.replace(/\n/g, "\r\n"));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
// ── CLI arguments ────────────────────────────────────────────────────────────────
interface Args {
settings?: string;
rulesFile?: string;
resume?: string;
prompt?: string;
notify?: string[];
developerInstructions?: string;
mcpCommand?: string;
}
function parseArgs(): Args {
const a: Args = {};
for (let i = 0; i < argv.length; i++) {
const x = argv[i]!;
if (x === "--") {
a.prompt = argv.slice(i + 1).join(" ");
break;
}
if (x === "--settings") a.settings = argv[++i];
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 (x === "-c") {
const [k, ...v] = argv[++i]!.split("=");
const val = JSON.parse(v.join("="));
if (k === "notify") a.notify = val;
else if (k === "developer_instructions") a.developerInstructions = val;
else if (k === "mcp_servers.peppa.command") a.mcpCommand = val;
}
}
return a;
}
const args = parseArgs();
const conversationId = args.resume ?? randomUUID();
let lastMessage = "";
// ── hooks / notify ───────────────────────────────────────────────────────────────
interface HookCmd {
command: string;
timeout?: number;
}
function hookFor(event: string, matchQuery?: string): HookCmd | null {
if (!args.settings) return null;
const groups = JSON.parse(readFileSync(args.settings, "utf8")).hooks?.[event] as
| Array<{ matcher?: string; hooks: HookCmd[] }>
| undefined;
const g = groups?.find((g) => !g.matcher || (matchQuery && new RegExp(`^(${g.matcher})$`).test(matchQuery)));
return g?.hooks[0] ?? null;
}
/** Runs a Claude hook like Claude Code does: JSON on stdin, JSON (maybe) on stdout. */
function fireHook(event: string, payload: Record<string, unknown>, matchQuery?: string): Promise<any> {
const h = hookFor(event, matchQuery);
if (!h) return Promise.resolve(null);
const input = { session_id: conversationId, cwd, hook_event_name: event, ...payload };
return new Promise((resolve) => {
const p = spawn("sh", ["-c", h.command], { stdio: ["pipe", "pipe", "inherit"] });
let stdout = "";
const timer = setTimeout(() => p.kill(), (h.timeout ?? 60) * 1000);
p.stdout.on("data", (d) => (stdout += d));
p.on("close", () => {
clearTimeout(timer);
let parsed: unknown = null;
try {
parsed = stdout.trim() ? JSON.parse(stdout) : null;
} catch {}
log("hook", { event, output: parsed });
resolve(parsed);
});
p.stdin.end(JSON.stringify(input));
});
}
function codexNotify(message: string): Promise<void> {
if (!args.notify?.length) return Promise.resolve();
const payload = { type: "agent-turn-complete", "thread-id": conversationId, "turn-id": randomUUID(), cwd, "last-assistant-message": message };
return new Promise((resolve) => {
const [cmd, ...rest] = args.notify!;
const p = spawn(cmd!, [...rest, JSON.stringify(payload)], { stdio: "ignore" });
p.on("close", () => {
log("notify", { message });
resolve();
});
});
}
// ── MCP ──────────────────────────────────────────────────────────────────────────
let mcp: Client | null = null;
function mcpCommand(): string {
if (args.mcpCommand) return args.mcpCommand;
const cfgPath = join(cwd, ".mcp.json");
const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf8")) : {};
return process.env.PEPPA_MOCK_MCP_BIN ?? cfg.mcpServers?.peppa?.command ?? "peppa-mcp";
}
async function callMcp(tool: string, toolArgs: Record<string, unknown>) {
if (!mcp) {
mcp = new Client({ name: `mock-${provider}`, version: "0" });
await mcp.connect(new StdioClientTransport({ command: mcpCommand(), cwd, env: process.env as Record<string, string> }));
}
const r = await mcp.callTool({ name: tool, arguments: toolArgs });
const text = (r.content as Array<{ text: string }>)[0]?.text ?? "";
log("mcp", { tool, args: toolArgs, isError: !!r.isError, text });
out(`⏺ peppa.${tool} → ${text.split("\n")[0]}\n`);
}
// ── terminal input ───────────────────────────────────────────────────────────────
type Mode = "prompt" | "dialog" | "frozen" | "busy";
let mode: Mode = "busy";
let buffer = "";
let inPaste = false;
let dialogResolve: ((key: string) => void) | null = null;
const queue: string[] = [];
let wake: (() => void) | null = null;
function onInput(chunk: string) {
if (mode === "frozen") return;
if (chunk.includes("\x03")) {
log("exit", { code: 130, reason: "ctrl-c" });
process.exit(130);
}
if (mode === "dialog" && dialogResolve) {
const key = chunk.replace(/\x1b\[20[01]~/g, "").trim()[0];
if (key && "123".includes(key)) {
const r = dialogResolve;
dialogResolve = null;
r(key);
}
return;
}
for (let i = 0; i < chunk.length; i++) {
if (chunk.startsWith("\x1b[200~", i)) {
inPaste = true;
i += 5;
} else if (chunk.startsWith("\x1b[201~", i)) {
inPaste = false;
i += 5;
} else if (chunk[i] === "\r" && !inPaste) {
submit(buffer);
buffer = "";
} else if (chunk[i] === "\x7f") {
buffer = buffer.slice(0, -1);
} else {
buffer += chunk[i] === "\r" ? "\n" : chunk[i];
}
}
}
function submit(text: string) {
if (!text.trim()) return;
queue.push(text);
wake?.();
}
async function nextPrompt(): Promise<string> {
while (!queue.length) await new Promise<void>((r) => (wake = r));
wake = null;
return queue.shift()!;
}
function dialog(): Promise<string> {
mode = "dialog";
log("dialog");
return new Promise((r) => (dialogResolve = r));
}
// ── actions ──────────────────────────────────────────────────────────────────────
/** Returns false when the turn must end early (limit) without a normal Stop. */
async function run(action: Action): Promise<boolean> {
log("action", { action });
if ("say" in action) {
lastMessage = action.say;
out(`⏺ ${action.say}\n`);
} else if ("work" in action) {
const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
const end = Date.now() + action.work;
for (let i = 0; Date.now() < end; i++) {
out(`\r${frames[i % frames.length]} Working… ${Math.round((end - Date.now()) / 100) / 10}s `);
await sleep(100);
}
out("\n");
} else if ("sleep" in action) {
await sleep(action.sleep);
} else if ("mcp" in action) {
await callMcp(action.mcp, action.args ?? {});
} else if ("permission" in action) {
if (provider !== "claude") return true;
const { tool, input } = action.permission;
const res = await fireHook("PermissionRequest", { tool_name: tool, tool_input: input, permission_suggestions: [{ type: "addRules", rules: [{ toolName: tool }], behavior: "allow", destination: "localSettings" }] }, tool);
const decision = res?.hookSpecificOutput?.decision;
if (decision) {
log("permission", { tool, via: "hook", behavior: decision.behavior, updatedPermissions: !!decision.updatedPermissions, message: decision.message });
out(`⏺ ${tool} ${decision.behavior === "allow" ? "allowed" : "denied"} by hook\n`);
} else {
out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and don't ask again for ${tool}\n 3. No, and tell Claude what to do differently (esc)\n`);
await fireHook("Notification", { message: `Claude needs your permission to use ${tool}`, notification_type: "permission_prompt" }, "permission_prompt");
const key = await dialog();
mode = "busy";
const behavior = key === "3" ? "deny" : "allow";
log("permission", { tool, via: "terminal", key, behavior });
out(`⏺ ${tool} ${behavior === "allow" ? "allowed" : "denied"} in terminal (${key})\n`);
}
} else if ("ask" in action) {
if (provider !== "claude") return true;
const questions = action.ask.map((q) => ({ question: q.question, header: "Q", options: (q.options ?? []).map((label) => ({ label })), multiSelect: false }));
const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions } }, "AskUserQuestion");
const h = res?.hookSpecificOutput;
if (h?.permissionDecision === "allow" && h.updatedInput?.answers) {
log("ask", { via: "hook", answers: h.updatedInput.answers });
out(`⏺ User answered: ${JSON.stringify(h.updatedInput.answers)}\n`);
} else if (h?.permissionDecision === "deny") {
log("ask", { via: "denied", reason: h.permissionDecisionReason });
out(`⏺ AskUserQuestion denied: ${h.permissionDecisionReason}\n`);
lastMessage = "Жду ответа PM на вопрос.";
} else {
log("ask", { via: "terminal" });
}
} else if ("limit" in action) {
const spec = typeof action.limit === "object" ? action.limit : {};
const at = spec.resetInSec != null ? new Date(Date.now() + spec.resetInSec * 1000).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }) : null;
const when = spec.reset === "unknown" ? "" : at ? ` resets at ${at}` : " resets 5pm";
if (provider === "claude") {
out(`⎿ Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}\n`);
await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: lastMessage }, "rate_limit");
} else {
out(`■ You've hit your usage limit.${spec.reset === "unknown" ? "" : ` Try again at ${at ?? "5:00 PM"}.`}\n`);
}
log("limit");
return false;
} else if ("hang" in action) {
log("hang");
mode = "frozen";
await new Promise(() => {});
} else if ("crash" in action) {
out(`Error: simulated crash (exit ${action.crash})\n`);
log("exit", { code: action.crash, reason: "crash" });
process.exit(action.crash);
} else if ("clear" in action) {
if (provider === "claude") {
await fireHook("SessionEnd", { reason: "clear" }, "clear");
const id = randomUUID();
log("clear", { newConversationId: id });
await fireHook("SessionStart", { source: "clear", session_id: id }, "clear");
}
} else if ("exit" in action) {
log("exit", { code: 0, reason: "exit" });
await fireHook("SessionEnd", { reason: "prompt_input_exit" });
process.exit(0);
}
return true;
}
/**
* One turn. `continuation` = Claude keeps going after a Stop hook blocked the stop (no
* UserPromptSubmit then). Returns the Stop hook's block reason when it asks to continue.
*/
async function turn(prompt: string, actions: Action[] | undefined, continuation = false): Promise<string | null> {
mode = "busy";
if (continuation) {
log("continue", { reason: prompt });
out(`\n⎿ Stop hook: ${prompt}\n`);
} else {
log("prompt", { prompt });
out(`\n> ${prompt.replace(/\n/g, "\n ")}\n`);
await fireHook("UserPromptSubmit", { prompt });
}
lastMessage = "";
let completed = true;
if (prompt.startsWith("!")) {
try {
completed = await run(JSON.parse(prompt.slice(1)) as Action);
} catch (e) {
out(`bad action: ${(e as Error).message}\n`);
}
} else if (actions) {
for (const a of actions) {
if (!(await run(a))) {
completed = false;
break;
}
}
} else {
lastMessage = `Получил: ${prompt.slice(0, 200)}`;
out(`⏺ ${lastMessage}\n`);
}
let next: string | null = null;
if (completed) {
if (provider === "claude") {
const res = await fireHook("Stop", { last_assistant_message: lastMessage || "Готово.", stop_hook_active: continuation });
if (res?.decision === "block" && typeof res.reason === "string") next = res.reason;
} else await codexNotify(lastMessage || "Готово.");
}
log("turn_end", { completed, continued: !!next });
mode = next ? "busy" : "prompt";
if (!next) out("\n> ");
return next;
}
async function main() {
const scenario: Scenario = existsSync(SCENARIO) ? JSON.parse(readFileSync(SCENARIO, "utf8")) : { turns: [] };
const turns = (args.resume && scenario.resumeTurns) || scenario.turns;
const rules = args.rulesFile ? readFileSync(args.rulesFile, "utf8") : (args.developerInstructions ?? "");
log("start", {
argv,
resume: args.resume ?? null,
conversationId,
rulesChars: rules.length,
rulesHead: rules.split("\n")[0],
oauthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN ? `…${process.env.CLAUDE_CODE_OAUTH_TOKEN.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`);
if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup");
let i = 0;
const run = async (prompt: string) => {
let next = await turn(prompt, turns[i++]);
while (next) next = await turn(next, turns[i++], true);
};
if (args.prompt) await run(args.prompt);
else mode = "prompt";
for (;;) await run(await nextPrompt());
}
/**
* `claude setup-token`: prints a sign-in URL, waits for the code. "mock-good-…" codes
* yield a token, anything else fails like an invalid code.
*/
async function setupToken() {
out(" This will guide you through long-lived (1-year) auth token setup for your Claude account.\n");
out(" Browser didn't open? Use the url below to sign in (c to copy)\n\n");
out(`https://claude.com/cai/oauth/authorize?code=true&client_id=mock-client&response_type=code&state=mock-${randomUUID()}\n\n`);
out(" Paste code here if prompted > ");
process.stdin.setEncoding("utf8");
let buf = "";
for await (const chunk of process.stdin) {
buf += String(chunk).replace(/\x1b\[20[01]~/g, "");
if (/[\r\n]/.test(buf)) break;
}
const code = buf.trim();
// Runs in the home dir: log next to Peppa's state, never into a stray ~/.peppa.
if (process.env.PEPPA_HOME) appendFileSync(join(process.env.PEPPA_HOME, "mock-setup-log.jsonl"), `${JSON.stringify({ ev: "setup_token", code, t: Date.now() })}\n`);
if (code.startsWith("mock-good-")) {
out(`\n\n ✓ Long-lived authentication token created successfully!\n\n Your OAuth token (valid for 1 year):\n\n sk-ant-oat01-mock${randomUUID().replace(/-/g, "")}\n\n Store this token securely.\n`);
process.exit(0);
}
out("\n\n OAuth error: Invalid code\n");
process.exit(1);
}
(argv[0] === "setup-token" ? setupToken() : main()).catch((e) => {
log("fatal", { error: String(e?.stack ?? e) });
process.exit(1);
});