629 lines
30 KiB
TypeScript
629 lines
30 KiB
TypeScript
// 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.
|
||
//
|
||
// OpenCode (PEP-67): `opencode <dir> --prompt <p> [--session <id>]` with rules and the MCP
|
||
// server from $OPENCODE_CONFIG; no hooks. Subcommands for subscription sign-in and checks:
|
||
// `claude setup-token`, `claude -p`, `codex login --device-auth|--with-api-key`, `codex exec`,
|
||
// `opencode run`.
|
||
//
|
||
// Usage: mock-agent.ts <claude|codex|opencode> [cli args...]
|
||
// Typing "!{json action}" as a prompt runs that action — handy for manual runs.
|
||
import { execFileSync, spawn } from "node:child_process";
|
||
import { randomUUID } from "node:crypto";
|
||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||
import type { Action, Scenario } from "./scenario.ts";
|
||
|
||
type Provider = "claude" | "codex" | "opencode";
|
||
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 (provider === "opencode" && x === "--session") a.resume = argv[++i];
|
||
else if (provider === "opencode" && x === "--prompt") {
|
||
a.prompt = argv[++i];
|
||
} else if (provider === "opencode" && x === "--model") i++;
|
||
else if (x === "-c") {
|
||
const [k, ...v] = argv[++i]!.split("=");
|
||
const val = JSON.parse(v.join("="));
|
||
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;
|
||
}
|
||
|
||
// PEP-171: Codex 0.169 removed --full-auto — the real CLI refuses it and exits with 2.
|
||
if (provider === "codex" && argv.includes("--full-auto")) {
|
||
process.stderr.write("error: unexpected argument '--full-auto' found\n\n tip: to pass '--full-auto' as a value, use '-- --full-auto'\n\nUsage: codex [OPTIONS] [PROMPT]\n");
|
||
process.exit(2);
|
||
}
|
||
// PEP-188: Codex 0.169 takes only the first positional as PROMPT, a second one is an error;
|
||
// without a trusted folder it shows «Trust this folder?» and waits for a key.
|
||
const codexTrusted = provider !== "codex" || argv[0] === "exec" || argv[0] === "login" || argv.some((a, i) => argv[i - 1] === "-c" && a.startsWith("projects.") && a.endsWith(".trust_level=\"trusted\""));
|
||
if (provider === "codex" && argv[0] !== "exec" && argv[0] !== "login") {
|
||
const positional: string[] = [];
|
||
const withValue = new Set(["--cd", "-c", "--model", "-m", "--sandbox", "-s", "--ask-for-approval", "-a"]);
|
||
for (let i = 0; i < argv.length; i++) {
|
||
const x = argv[i]!;
|
||
if (x === "--") { positional.push(...argv.slice(i + 1, i + 2), ...argv.slice(i + 2).map(() => "!extra")); break; }
|
||
if (x === "resume") { i++; continue; }
|
||
if (withValue.has(x)) i++;
|
||
else if (!x.startsWith("-")) positional.push(x);
|
||
}
|
||
if (positional.length > 1) {
|
||
const bad = positional.find((p) => p !== positional[0]) ?? positional[1];
|
||
process.stderr.write(`error: unexpected argument '${bad === "!extra" ? positional[0] : bad}' found\n\nUsage: codex [OPTIONS] [PROMPT]\n`);
|
||
process.exit(2);
|
||
}
|
||
}
|
||
const args = parseArgs();
|
||
// PEP-241: Codex on a ChatGPT account refuses a Claude model on the first message.
|
||
const codexModel = provider === "codex" ? argv.find((a, i) => argv[i - 1] === "--model" || argv[i - 1] === "-m") : undefined;
|
||
const codexModelRefused = !!codexModel && /^(opus|sonnet|haiku|claude)/i.test(codexModel);
|
||
if (!codexTrusted) {
|
||
process.stdout.write("Do you trust the contents of this directory?\n 1. Yes, continue\n 2. No, quit\nTrust this folder? Press enter to continue\n");
|
||
await new Promise(() => {});
|
||
}
|
||
// OpenCode: rules (instructions) and the peppa MCP server come from the generated config.
|
||
if (provider === "opencode" && process.env.OPENCODE_CONFIG && existsSync(process.env.OPENCODE_CONFIG)) {
|
||
const cfg = JSON.parse(readFileSync(process.env.OPENCODE_CONFIG, "utf8"));
|
||
args.rulesFile = cfg.instructions?.[0];
|
||
args.mcpCommand = cfg.mcp?.peppa?.command?.[0];
|
||
}
|
||
const conversationId = args.resume ?? randomUUID();
|
||
let lastMessage = "";
|
||
// Claude keeps one transcript per conversation; resume appends to it.
|
||
const transcriptPath = join(cwd, ".peppa", `mock-transcript-${conversationId}.jsonl`);
|
||
|
||
// ── 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, transcript_path: transcriptPath, 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));
|
||
});
|
||
}
|
||
|
||
/** Claude's statusLine: the command from settings, JSON on stdin, the first stdout line shown. */
|
||
function fireStatusLine(payload: Record<string, unknown>): Promise<string | null> {
|
||
if (!args.settings) return Promise.resolve(null);
|
||
const cmd = JSON.parse(readFileSync(args.settings, "utf8")).statusLine?.command as string | undefined;
|
||
if (!cmd) return Promise.resolve(null);
|
||
return new Promise((resolve) => {
|
||
const p = spawn("sh", ["-c", cmd], { stdio: ["pipe", "pipe", "inherit"] });
|
||
let stdout = "";
|
||
p.stdout.on("data", (d) => (stdout += d));
|
||
p.on("close", () => {
|
||
const line = stdout.split("\n")[0] ?? "";
|
||
log("statusline", { line });
|
||
resolve(line);
|
||
});
|
||
// Live 2.1.323 (fixtures/claude-live/statusline.json): no hook_event_name.
|
||
p.stdin.end(JSON.stringify({ session_id: conversationId, transcript_path: transcriptPath, cwd, version: "2.1.323-mock", ...payload }));
|
||
});
|
||
}
|
||
|
||
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";
|
||
}
|
||
|
||
// "$TASK" in MCP args = the story the runner started this agent on ("Работай над стори KEY-N"),
|
||
// so one scenario serves every story of a project (PEP-24 dispatcher tests).
|
||
const startTask = /стори ([A-Z][A-Z0-9]*-\d+)/.exec(args.prompt ?? "")?.[1] ?? null;
|
||
const withTask = (v: Record<string, unknown>) =>
|
||
Object.fromEntries(Object.entries(v).map(([k, x]) => [k, x === "$TASK" && startTask ? startTask : x]));
|
||
|
||
async function callMcp(tool: string, rawArgs: Record<string, unknown>) {
|
||
const toolArgs = withTask(rawArgs);
|
||
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 clean = chunk.replace(/\x1b\[20[01]~/g, "");
|
||
// Escape alone cancels the dialog (= No); "1".."4" pick a menu line.
|
||
const key = clean === "\x1b" ? "esc" : clean.trim()[0];
|
||
if (key && ["1", "2", "3", "4", "esc"].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 ("usage" in action) {
|
||
const u = action.usage;
|
||
const model = u.model ?? "claude-sonnet-4-5";
|
||
// Like the live CLI (fixtures/claude-live/transcript.jsonl): one entry per content block,
|
||
// every entry of the message repeats its id and usage.
|
||
const id = `msg_${randomUUID()}`;
|
||
const usage = { input_tokens: u.input ?? 0, output_tokens: u.output ?? 0, cache_read_input_tokens: u.cacheRead ?? 0, cache_creation_input_tokens: u.cacheWrite ?? 0 };
|
||
for (const block of [{ type: "thinking", thinking: "…" }, { type: "text", text: "…" }]) {
|
||
appendFileSync(transcriptPath, `${JSON.stringify({ type: "assistant", sessionId: conversationId, message: { id, model, role: "assistant", type: "message", content: [block], usage } })}\n`);
|
||
}
|
||
if (provider === "claude") {
|
||
const resets = Math.floor(Date.now() / 1000) + (u.resetInSec ?? 3600);
|
||
const rate_limits: Record<string, unknown> = {};
|
||
if (u.fiveHour != null) rate_limits.five_hour = { used_percentage: u.fiveHour, resets_at: resets };
|
||
if (u.sevenDay != null) rate_limits.seven_day = { used_percentage: u.sevenDay, resets_at: resets + 6 * 86400 };
|
||
await fireStatusLine({
|
||
model: { id: model, display_name: model },
|
||
...(u.costUsd != null ? { cost: { total_cost_usd: u.costUsd, total_duration_ms: 1000 } } : {}),
|
||
// total_*_tokens are the last request, not session totals (live 2.1.323).
|
||
...(u.context ? { context_window: { total_input_tokens: u.context.used, total_output_tokens: u.output ?? 0, context_window_size: u.context.size, current_usage: { input_tokens: u.context.used, output_tokens: u.output ?? 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }, used_percentage: Math.round((u.context.used / u.context.size) * 100) } } : {}),
|
||
...(Object.keys(rate_limits).length ? { rate_limits } : {}),
|
||
});
|
||
}
|
||
} 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: "addDirectories", directories: [cwd], destination: "session" }] }, 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 {
|
||
// The menu of Claude Code 2.1.323 (PEP-3, captured live): the "No" line is the 4th.
|
||
out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and always allow access to ${cwd} from this project\n 3. Yes, and switch to auto mode · auto mode handles these prompts for you\n 4. No\n\n Esc to cancel · Tab to amend\n`);
|
||
await fireHook("Notification", { message: "Claude needs your permission", notification_type: "permission_prompt" }, "permission_prompt");
|
||
const key = await dialog();
|
||
mode = "busy";
|
||
const behavior = key === "4" || key === "esc" ? "deny" : "allow";
|
||
log("permission", { tool, via: "terminal", key, behavior, ...(key === "3" ? { mode: "auto" } : {}) });
|
||
if (behavior === "deny") {
|
||
// Live 2.1.323: "No" interrupts the turn — no Stop hook, the prompt waits for the user.
|
||
out(` ⎿ Interrupted · What should Claude do instead?\n`);
|
||
return false;
|
||
}
|
||
out(`⏺ ${tool} allowed 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, description: label })), multiSelect: false }));
|
||
const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions }, tool_use_id: `toolu_${randomUUID()}` }, "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 ("menu" in action) {
|
||
const spec = typeof action.menu === "object" ? action.menu : {};
|
||
if (spec.afterLimit) out("■ You’ve hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro) or try again at 8:47 PM.\n Approaching rate limits\n");
|
||
out(" Switch to gpt-6-luna for lower credit usage?\n› 1. Switch to gpt-6-luna Fast and affordable model for easier tasks.\n 2. Keep current model\n 3. Keep current model (never show again) Hide future rate limit reminders about switching models\n\n enter select · esc back\n");
|
||
const key = await dialog();
|
||
log("menu", { key });
|
||
out(key === "1" ? "• Switched to gpt-6-luna\n" : "• Keeping the current model\n");
|
||
mode = "busy";
|
||
} else if ("trust" in action) {
|
||
const spec = typeof action.trust === "object" ? action.trust : {};
|
||
out(` Folder access\n\n Trust this folder?\n ${spec.path ?? cwd}\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n\n enter select · esc back\n`);
|
||
const key = await dialog();
|
||
log("trust", { key });
|
||
if (key !== "1") {
|
||
log("exit", { code: 0, reason: "trust" });
|
||
process.exit(0);
|
||
}
|
||
mode = "busy";
|
||
} else if ("loginFail" in action) {
|
||
out("› Error: account/read failed: account/read failed: workspace routing discovery timed out (code -32603)\n");
|
||
log("exit", { code: 1, reason: "login" });
|
||
process.exit(1);
|
||
} else if ("warn" in action) {
|
||
out(`⚠ You've used ${action.warn}% of your weekly limit · resets Mon 9am\n`);
|
||
log("warn", { pct: action.warn });
|
||
} else if ("limit" in action) {
|
||
const spec = typeof action.limit === "object" ? action.limit : {};
|
||
if (spec.credential && !(credential() ?? "").includes(spec.credential)) return true;
|
||
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`);
|
||
// Per the hooks docs, last_assistant_message of StopFailure is the API error text, not
|
||
// Claude's output; error_details is optional and its live wording is unverified (PEP-3).
|
||
await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: `API Error: Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}` }, "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 ("commit" in action) {
|
||
const c = action.commit;
|
||
writeFileSync(join(cwd, c.file), c.text ?? "ok\n");
|
||
const git = (...a: string[]) => execFileSync("git", ["-c", "user.name=mock-agent", "-c", "user.email=mock-agent@test", ...a], { cwd, stdio: "ignore" });
|
||
try {
|
||
git("add", "--", c.file);
|
||
git("commit", "-m", c.message ?? `add ${c.file}`, "--", c.file);
|
||
log("commit", { file: c.file });
|
||
out(`⏺ Закоммитил ${c.file}\n`);
|
||
} catch (e) {
|
||
log("commit_failed", { error: (e as Error).message });
|
||
}
|
||
} 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 });
|
||
log("prompt_hooked", {});
|
||
}
|
||
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.providers?.[provider] || 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,
|
||
codexHome: process.env.CODEX_HOME ?? null,
|
||
apiKey: apiKey() ? `…${apiKey()!.slice(-4)}` : null,
|
||
});
|
||
|
||
// PEP-227: the real CLI answers a resume of a conversation it no longer has like this and exits 1.
|
||
if (provider === "claude" && args.resume && scenario.forgetResume) {
|
||
out(`No conversation found with session ID: ${args.resume}\n`);
|
||
log("exit", { code: 1, reason: "no_conversation" });
|
||
process.exit(1);
|
||
}
|
||
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
|
||
if (scenario.echoEnv?.length) {
|
||
const env = Object.fromEntries(scenario.echoEnv.map((k) => [k, process.env[k] ?? null]));
|
||
log("env", { env });
|
||
for (const [k, v] of Object.entries(env)) out(`${k}=${v ?? ""}\n`);
|
||
}
|
||
out(`${provider === "claude" ? "✻ Mock Claude Code" : provider === "opencode" ? "▣ Mock OpenCode" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`);
|
||
|
||
if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup");
|
||
|
||
let i = 0;
|
||
const run = async (prompt: string) => {
|
||
if (codexModelRefused) {
|
||
out(`■ The ${codexModel} model is not supported when using Codex with a ChatGPT account.\n\n> `);
|
||
log("model_refused", { model: codexModel });
|
||
mode = "prompt";
|
||
return;
|
||
}
|
||
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);
|
||
}
|
||
|
||
const apiKey = () => process.env.ANTHROPIC_API_KEY ?? process.env.OPENAI_API_KEY ?? process.env.OPENROUTER_API_KEY;
|
||
|
||
/** The login this run uses: Claude token, Codex auth.json, OpenCode provider key. */
|
||
function credential(): string | undefined {
|
||
if (provider === "claude") return process.env.CLAUDE_CODE_OAUTH_TOKEN ?? "mock-machine-login";
|
||
if (provider === "opencode") return apiKey();
|
||
const auth = join(process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex"), "auth.json");
|
||
return existsSync(auth) ? readFileSync(auth, "utf8") : undefined;
|
||
}
|
||
|
||
/**
|
||
* Trial runs for «Проверить» (`claude -p`, `codex exec`, `opencode run`): the credential's
|
||
* text decides — "bad" → auth error, "limit" → usage limit banner with a reset time, else ok.
|
||
*/
|
||
function probe(): never {
|
||
const fail = (msg: string) => (process.stderr.write(`${msg}\n`), process.exit(1));
|
||
const cred = credential();
|
||
if (!cred) fail(provider === "codex" ? "Not logged in. Run `codex login`." : "Error: no API key configured");
|
||
if (cred!.includes("bad")) fail(provider === "claude" ? "Invalid API key · Please run /login" : "Error: 401 Unauthorized: invalid credentials");
|
||
if (cred!.includes("limit")) fail(provider === "claude" ? "Claude AI usage limit reached. Your limit resets 5pm" : "You've hit your usage limit. Try again at 5:00 PM.");
|
||
process.stdout.write("ok\n");
|
||
process.exit(0);
|
||
}
|
||
|
||
/**
|
||
* `codex login --device-auth`: prints the device URL and a one-time code like the real CLI,
|
||
* then waits until the test "confirms on the device" ($CODEX_HOME/mock-device-approved or
|
||
* …-denied) and writes auth.json. `codex login --with-api-key`: key on stdin.
|
||
*/
|
||
async function codexLogin() {
|
||
const home = process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex");
|
||
mkdirSync(home, { recursive: true });
|
||
if (argv.includes("--with-api-key")) {
|
||
let key = "";
|
||
for await (const chunk of process.stdin) key += chunk;
|
||
key = key.trim();
|
||
if (!key || key.startsWith("mock-bad")) {
|
||
process.stderr.write("Error: invalid API key\n");
|
||
process.exit(1);
|
||
}
|
||
writeFileSync(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: key }));
|
||
process.stdout.write("Successfully logged in\n");
|
||
process.exit(0);
|
||
}
|
||
const code = `MOCK-${randomUUID().slice(0, 4).toUpperCase().replace(/[^A-Z0-9]/g, "Q")}`;
|
||
out("\nWelcome to Codex [mock]\nFollow these steps to sign in with ChatGPT using device code authorization:\n\n");
|
||
out("1. Open this link in your browser and sign in to your account\n https://auth.openai.com/codex/device\n\n");
|
||
out(`2. Enter this one-time code (expires in 15 minutes)\n ${code}\n\n`);
|
||
for (;;) {
|
||
await sleep(200);
|
||
if (existsSync(join(home, "mock-device-denied"))) {
|
||
out("Error logging in with device code: device authorization was denied\n");
|
||
process.exit(1);
|
||
}
|
||
if (existsSync(join(home, "mock-device-approved"))) {
|
||
const extra = readFileSync(join(home, "mock-device-approved"), "utf8");
|
||
writeFileSync(join(home, "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { access_token: `mock-chatgpt-${randomUUID()}${extra.trim()}` } }));
|
||
out("Successfully logged in\n");
|
||
process.exit(0);
|
||
}
|
||
}
|
||
}
|
||
|
||
const sub =
|
||
provider === "claude" && argv[0] === "setup-token"
|
||
? setupToken()
|
||
: (provider === "claude" && argv[0] === "-p") || (provider === "codex" && argv[0] === "exec") || (provider === "opencode" && argv[0] === "run")
|
||
? Promise.resolve(probe())
|
||
: provider === "codex" && argv[0] === "login"
|
||
? codexLogin()
|
||
: main();
|
||
sub.catch((e) => {
|
||
log("fatal", { error: String(e?.stack ?? e) });
|
||
process.exit(1);
|
||
});
|