feat(chat): add Claude Code chat backend
This commit is contained in:
+211
@@ -0,0 +1,211 @@
|
||||
#!/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, 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:
|
||||
log.write(json.dumps({"args": args, "cwd": os.getcwd()}) + "\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"]
|
||||
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 finish(message_id):
|
||||
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": [],
|
||||
})
|
||||
elif subtype == "set_model":
|
||||
state["model"] = request.get("model")
|
||||
respond(value.get("request_id"), {"model": request.get("model")})
|
||||
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")
|
||||
user_message(text)
|
||||
|
||||
|
||||
for line in sys.stdin:
|
||||
handle(line.strip())
|
||||
Reference in New Issue
Block a user