Files
pipelines/internal/claude/testdata/fake-claude.py
T
alan c810437aa5 Claude Code chats survive server restarts in a detachable host
A pipelines-claude-host process owns each claude -p CLI and its pipes,
spools its stream-json output with offsets and serves a private Unix
socket. The server detaches on shutdown and reattaches on start,
replaying the spool to rebuild turns, approvals, questions, background
tasks and the live model. Explicit close, idle release and CLI exit stop
the host; a crashed host falls back to --resume with a notice.
2026-11-04 16:09:56 +00:00

307 lines
16 KiB
Python

#!/usr/bin/env python3
"""Deterministic stand-in for the Claude Code CLI's SDK stdio protocol.
It implements only what Pipelines' adapter uses: initialize, stream-json turns,
can_use_tool approvals, AskUserQuestion, set_model, set_permission_mode,
interrupt, usage queries and
a session transcript. It never contacts a provider.
"""
import json
import os
import re
import sys
args = sys.argv[1:]
state = {"session": None, "turn": 0, "model": None, "pending": None, "transcript": None}
for index, arg in enumerate(args):
if arg in ("--session-id", "--resume") and index + 1 < len(args):
state["session"] = args[index + 1]
if arg == "--model" and index + 1 < len(args):
state["model"] = args[index + 1]
log_path = os.environ.get("FAKE_CLAUDE_LOG")
if log_path:
with open(log_path, "a", encoding="utf-8") as log:
keys = [k for k in os.environ.get("FAKE_CLAUDE_ENV_KEYS", "").split(",") if k]
env = {k: os.environ.get(k) for k in keys}
if os.environ.get("FAKE_CLAUDE_GIT_EMAIL"):
import subprocess
result = subprocess.run(["git", "config", "user.email"], capture_output=True, text=True)
env["git user.email"] = result.stdout.strip()
log.write(json.dumps({"args": args, "cwd": os.getcwd(), "env": env}) + "\n")
if os.environ.get("FAKE_CLAUDE_FAIL"):
sys.stderr.write("Please run /login to sign in\n")
sys.exit(2)
def send(value):
sys.stdout.write(json.dumps(value, separators=(",", ":")) + "\n")
sys.stdout.flush()
def respond(request_id, response):
send({"type": "control_response", "response": {"subtype": "success", "request_id": request_id, "response": response}})
def slug(cwd):
return re.sub(r"[^A-Za-z0-9]", "-", cwd)
def transcript_path():
base = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude")
directory = os.path.join(base, "projects", slug(os.getcwd()))
os.makedirs(directory, exist_ok=True)
return os.path.join(directory, state["session"] + ".jsonl")
def append(entry):
path = transcript_path()
with open(path, "a", encoding="utf-8") as file:
file.write(json.dumps(entry) + "\n")
def stamp():
return "2026-10-22T12:00:00Z"
def user_message(text):
state["turn"] += 1
append({"type": "user", "uuid": "user-%d" % state["turn"], "timestamp": stamp(),
"message": {"role": "user", "content": [{"type": "text", "text": text}]}})
send({"type": "system", "subtype": "init", "session_id": state["session"],
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd()})
message_id = "msg_fake_%d" % state["turn"]
if "gate" in text:
gated(message_id)
return
if "background" in text:
background(message_id)
return
if "notify" in text:
send({"type": "system", "subtype": "task_notification", "task_id": "b1",
"tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"})
send({"type": "stream_event", "event": {"type": "message_start", "message": {"id": message_id}}})
send({"type": "stream_event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}}})
for delta in ("Hello ", "world"):
send({"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": delta}}})
send({"type": "stream_event", "event": {"type": "content_block_stop", "index": 0}})
send({"type": "stream_event", "event": {"type": "message_stop"}})
append({"type": "assistant", "uuid": "asst-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": "Hello world"}]}})
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": "Hello world"}]}})
if "long" in text:
append({"type": "assistant", "uuid": "asst-long-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": "Hello world"}]}})
state["pending"] = {"kind": "long", "message": message_id, "tool": ""}
return
if "permission" in text:
tool_id = "toolu_fake_%d" % state["turn"]
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "Write",
"input": {"file_path": os.path.join(os.getcwd(), "note.txt"),
"content": "hi"}}]}})
append({"type": "assistant", "uuid": "asst-tool-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "Write",
"input": {"file_path": os.path.join(os.getcwd(), "note.txt"), "content": "hi"}}]}})
state["pending"] = {"kind": "permission", "message": message_id, "tool": tool_id}
send({"type": "control_request", "request_id": "req-permission-%d" % state["turn"],
"request": {"subtype": "can_use_tool", "tool_name": "Write", "display_name": "Write",
"description": "note.txt",
"input": {"file_path": os.path.join(os.getcwd(), "note.txt"), "content": "hi"},
"permission_suggestions": [{"type": "setMode", "mode": "acceptEdits", "destination": "session"}],
"tool_use_id": tool_id}})
return
if "question" in text:
tool_id = "toolu_question_%d" % state["turn"]
questions = {"questions": [{"question": "Pick one?", "header": "Pick one", "multiSelect": False,
"options": [{"label": "Alpha", "description": "First"}, {"label": "Beta", "description": "Second"}]}]}
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "AskUserQuestion", "input": questions}]}})
append({"type": "assistant", "uuid": "asst-question-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "AskUserQuestion", "input": questions}]}})
state["pending"] = {"kind": "question", "message": message_id, "tool": tool_id}
send({"type": "control_request", "request_id": "req-question-%d" % state["turn"],
"request": {"subtype": "can_use_tool", "tool_name": "AskUserQuestion", "display_name": "AskUserQuestion",
"input": questions, "requires_user_interaction": True, "tool_use_id": tool_id}})
return
finish(message_id)
def wait_for(path):
import time
while not os.path.exists(path):
time.sleep(0.02)
def gated(message_id):
"""A turn that streams, then waits for FAKE_CLAUDE_GATE to exist before it
streams the rest and finishes: the test restarts the server in between."""
gate = os.environ["FAKE_CLAUDE_GATE"]
send({"type": "stream_event", "event": {"type": "message_start", "message": {"id": message_id}}})
send({"type": "stream_event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}}})
send({"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": "Working"}}})
wait_for(gate)
send({"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": " after the restart"}}})
send({"type": "stream_event", "event": {"type": "content_block_stop", "index": 0}})
send({"type": "stream_event", "event": {"type": "message_stop"}})
text = "Working after the restart"
append({"type": "assistant", "uuid": "asst-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": text}]}})
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": text}]}})
finish(message_id)
def background(message_id):
"""Starts a background Bash command that a later "notify" turn finishes."""
tool_id = "toolu_bg_fake"
use = {"type": "tool_use", "id": tool_id, "name": "Bash",
"input": {"command": "sleep 600", "run_in_background": True}}
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test", "content": [use]}})
block = {"type": "tool_result", "tool_use_id": tool_id,
"content": "Command running in background with ID: b1. Output is being written to: /tmp/b1.output"}
send({"type": "user", "message": {"role": "user", "content": [block]}})
finish(message_id)
def finish(message_id):
# Shape of SDKRateLimitEvent in Claude Code 2.1.316 (synthetic numbers).
if os.environ.get("FAKE_CLAUDE_RATE_LIMIT"):
send({"type": "rate_limit_event", "uuid": "rate-%d" % state["turn"], "session_id": state["session"],
"rate_limit_info": {"status": "allowed", "resetsAt": 1900000000, "rateLimitType": "five_hour",
"utilization": 0.42, "isUsingOverage": False,
"unifiedWindows": {
"five_hour": {"utilization": 0.42, "resetsAt": 1900000000, "status": "allowed"},
"seven_day": {"utilization": 0.731, "resetsAt": 1900400000}}}})
send({"type": "result", "subtype": "success", "is_error": False, "result": "Hello world",
"session_id": state["session"], "total_cost_usd": 0.25,
"usage": {"input_tokens": 10, "output_tokens": 20}})
def tool_result(text, is_error=False):
pending = state["pending"]
state["pending"] = None
block = {"type": "tool_result", "tool_use_id": pending["tool"], "content": text}
if is_error:
block["is_error"] = True
send({"type": "user", "message": {"role": "user", "content": [block]}})
append({"type": "user", "uuid": "result-%d" % state["turn"], "timestamp": stamp(), "toolUseResult": text,
"message": {"role": "user", "content": [block]}})
finish(pending["message"])
def handle(line):
try:
value = json.loads(line)
except ValueError:
return
kind = value.get("type")
if kind == "control_request":
request = value.get("request") or {}
subtype = request.get("subtype")
if subtype == "initialize":
respond(value.get("request_id"), {
"models": [
{"value": "default", "displayName": "Default", "description": "Default model"},
{"value": "sonnet", "displayName": "Sonnet", "description": "Sonnet model"},
{"value": "haiku", "displayName": "Haiku", "description": "Haiku model"},
],
"commands": [], "agents": [],
"account": {"email": "fixture@example.invalid", "organization": "Fixture Org",
"subscriptionType": "max", "apiProvider": "firstParty"},
})
elif subtype == "set_model":
state["model"] = request.get("model")
respond(value.get("request_id"), {"model": request.get("model")})
elif subtype == "set_permission_mode":
mode_log = os.environ.get("FAKE_CLAUDE_MODE_LOG")
if mode_log:
with open(mode_log, "a", encoding="utf-8") as log:
log.write(request.get("mode", "") + "\n")
respond(value.get("request_id"), {"mode": request.get("mode")})
elif subtype == "interrupt":
respond(value.get("request_id"), {"still_queued": [], "cancelled": []})
if state["pending"]:
state["pending"] = None
send({"type": "result", "subtype": "error_during_execution", "is_error": True,
"result": "Interrupted", "session_id": state["session"]})
elif subtype == "get_usage":
respond(value.get("request_id"), {"session": {
"total_cost_usd": 0.25,
"model_usage": {"claude-test": {"inputTokens": 10, "outputTokens": 20,
"cacheReadInputTokens": 30, "cacheCreationInputTokens": 40,
"costUSD": 0.25, "contextWindow": 200000}}}})
elif subtype == "get_context_usage":
respond(value.get("request_id"), {"totalTokens": 60, "maxTokens": 200000})
else:
send({"type": "control_response", "response": {"subtype": "error",
"request_id": value.get("request_id"),
"error": "unsupported in fixture"}})
return
if kind == "control_response":
response = value.get("response") or {}
pending = state["pending"]
if not pending:
return
if response.get("subtype") == "error":
tool_result("Error: " + str(response.get("error")), True)
return
result = response.get("response") or {}
if result.get("behavior") == "deny":
tool_result("Error: " + str(result.get("message") or "denied"), True)
return
if pending["kind"] == "question":
answers = (result.get("updatedInput") or {}).get("answers") or {}
tool_result("Your questions have been answered: " + json.dumps(answers))
else:
tool_result("File created successfully")
return
if kind == "user":
message = value.get("message") or {}
content = message.get("content")
text = ""
if isinstance(content, list):
text = " ".join(block.get("text", "") for block in content if block.get("type") == "text")
images = [block for block in content if block.get("type") == "image"]
if images and log_path:
with open(log_path + ".content", "a", encoding="utf-8") as log:
log.write(json.dumps(content) + "\n")
pending = state["pending"]
if pending and pending["kind"] == "long":
steer(pending, text)
return
user_message(text)
def steer(pending, text):
"""A message written while a turn runs is read at the turn's next step,
recorded as a queued_command attachment, and the same turn finishes."""
if log_path:
with open(log_path + ".steer", "a", encoding="utf-8") as log:
log.write(text + "\n")
state["pending"] = None
append({"type": "attachment", "uuid": "steer-%d" % state["turn"], "timestamp": stamp(),
"attachment": {"type": "queued_command", "commandMode": "prompt",
"prompt": [{"type": "text", "text": text}]}})
reply = "Noted: " + text
append({"type": "assistant", "uuid": "asst-steer-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": pending["message"] + "_steer", "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": reply}]}})
send({"type": "assistant", "message": {"id": pending["message"] + "_steer", "role": "assistant",
"model": "claude-test", "content": [{"type": "text", "text": reply}]}})
finish(pending["message"])
for line in sys.stdin:
handle(line.strip())