Files
pipelines/internal/claude/testdata/fake-claude.py
T
alan ed9072b79a Claude accounts: switch a chat refused for usage to another saved account and continue it
When Claude Code refuses an operator chat's turn for a usage limit, the
server marks the refused account until its reset and, if the chat's Claude
home allows it (claude_account_auto_switch / `pipelines claude-account auto
on|off`, on by default, kept in pipelines-accounts/settings.json), switches
the home to the saved account with the most usage left through the
claude_account_use path. Switches of one home are serialized, so chats
refused together switch once. Each refused chat gets one queued prompt,
marked as sent automatically, that asks the agent to check it is on track
before continuing; the app's auto-continue-at-reset prompt for the refusal is
removed (and refused if it arrives later), and the operator gets a
low-priority notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:23:43 +00:00

354 lines
19 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(),
"terminal_slash_commands": ["color"]})
message_id = "msg_fake_%d" % state["turn"]
if "gate" in text:
gated(message_id)
return
if "background" in text:
background(message_id)
return
if "usage-limit" in text:
refused(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 refused(message_id):
"""A turn refused for a usage limit, as Claude Code 2.1 ends one: a rejected
rate_limit_event, a synthetic assistant API-error message and an is_error
result repeating its text."""
text = "You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of usage credits"
send({"type": "rate_limit_event", "uuid": "rate-%d" % state["turn"], "session_id": state["session"],
"rate_limit_info": {"status": "rejected", "resetsAt": 1900000000, "rateLimitType": "five_hour",
"isUsingOverage": False, "overageStatus": "rejected",
"overageDisabledReason": "out_of_credits"}})
refusal_id = "refusal-%d" % state["turn"]
message = {"id": refusal_id, "role": "assistant", "model": "<synthetic>",
"content": [{"type": "text", "text": text}]}
append({"type": "assistant", "uuid": refusal_id, "timestamp": stamp(), "error": "rate_limit",
"isApiErrorMessage": True, "message": message})
send({"type": "assistant", "uuid": refusal_id, "error": "rate_limit", "message": message})
send({"type": "result", "subtype": "success", "is_error": True, "result": text,
"session_id": state["session"]})
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", "resolvedModel": "claude-test", "displayName": "Default", "description": "Default model",
"supportsEffort": True, "supportedEffortLevels": ["low", "medium", "high", "xhigh", "max"]},
{"value": "sonnet", "resolvedModel": "claude-sonnet-test", "displayName": "Sonnet", "description": "Sonnet model",
"supportsEffort": True, "supportedEffortLevels": ["low", "medium", "high", "max"]},
{"value": "haiku", "displayName": "Haiku", "description": "Haiku model"},
],
"commands": [
{"name": "code-review", "description": "Review the current diff", "argumentHint": "[low|high] [<pr#>]"},
{"name": "probe-skill", "description": "Probe skill (user)", "argumentHint": ""},
{"name": "color", "description": "Set the prompt bar color", "argumentHint": "[red|blue]"},
{"name": "__remote-workflow", "description": "internal", "argumentHint": ""},
{"name": "code-review", "description": "duplicate", "argumentHint": ""},
], "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 == "apply_flag_settings":
effort_log = os.environ.get("FAKE_CLAUDE_EFFORT_LOG")
if effort_log:
with open(effort_log, "a", encoding="utf-8") as log:
log.write(json.dumps(request.get("settings"), separators=(",", ":")) + "\n")
respond(value.get("request_id"), {})
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 == "stop_task":
respond(value.get("request_id"), {})
send({"type": "system", "subtype": "task_notification",
"task_id": request.get("task_id"), "tool_use_id": "toolu_bg_fake",
"status": "stopped", "summary": "Background task stopped"})
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":
updated = result.get("updatedInput") or {}
# Like Claude Code: updatedInput must still match the tool's schema.
if not isinstance(updated.get("questions"), list):
tool_result("Error: The parameter `questions` type is expected as `array`", True)
return
answers = updated.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())