286 lines
9.3 KiB
Python
286 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Approval-card scaffolding: /connect WebSocket double that pushes a permission.
|
|
|
|
Two sessions: `ses_perm` hands out a pending `chat_permission` after a prompt so
|
|
the approval card can be answered (once/always/reject), and `ses_resolved` pushes
|
|
a frame the server already settled so the card must show the outcome with no
|
|
actions. Same wire shapes as the other stubs; test scaffolding only, never part
|
|
of the app.
|
|
"""
|
|
import base64
|
|
import hashlib
|
|
import itertools
|
|
import json
|
|
import socket
|
|
import struct
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
|
|
# Every prompt gets a fresh request id, so a new prompt is a new request rather
|
|
# than a re-push of an already-answered one.
|
|
REQUEST_SEQ = itertools.count(1)
|
|
|
|
PENDING_SESSION = "ses_perm"
|
|
RESOLVED_SESSION = "ses_resolved"
|
|
|
|
SESSIONS = [
|
|
{
|
|
"id": PENDING_SESSION,
|
|
"title": "Answer an approval",
|
|
"agent": "build",
|
|
"model": "deepseek-v4.1",
|
|
"directory": "/home/user/project",
|
|
"created_at": 1760620000000,
|
|
"updated_at": 1760620600000,
|
|
"busy": False,
|
|
},
|
|
{
|
|
"id": RESOLVED_SESSION,
|
|
"title": "Already resolved",
|
|
"agent": "build",
|
|
"model": "deepseek-v4.1",
|
|
"directory": "/home/user/project",
|
|
"created_at": 1760620000000,
|
|
"updated_at": 1760620600000,
|
|
"busy": False,
|
|
},
|
|
]
|
|
|
|
MESSAGES = {
|
|
PENDING_SESSION: [
|
|
{"id": "m1", "session_id": PENDING_SESSION, "role": "user",
|
|
"parts": [{"type": "text", "id": "m1t", "text": "Refactor the layout constants."}]},
|
|
{"id": "m2", "session_id": PENDING_SESSION, "role": "assistant",
|
|
"parts": [{"type": "text", "id": "m2t",
|
|
"text": "I need to edit `src/layout.kt`; approve the change to continue."}]},
|
|
],
|
|
RESOLVED_SESSION: [
|
|
{"id": "r1", "session_id": RESOLVED_SESSION, "role": "user",
|
|
"parts": [{"type": "text", "id": "r1t", "text": "Run the tests."}]},
|
|
{"id": "r2", "session_id": RESOLVED_SESSION, "role": "assistant",
|
|
"parts": [{"type": "text", "id": "r2t",
|
|
"text": "The shell command was approved from another client."}]},
|
|
],
|
|
}
|
|
|
|
|
|
def _recv_exact(conn, n):
|
|
buf = b""
|
|
while len(buf) < n:
|
|
chunk = conn.recv(n - len(buf))
|
|
if not chunk:
|
|
raise EOFError
|
|
buf += chunk
|
|
return buf
|
|
|
|
|
|
def _handshake(conn):
|
|
data = b""
|
|
while b"\r\n\r\n" not in data:
|
|
chunk = conn.recv(4096)
|
|
if not chunk:
|
|
return False
|
|
data += chunk
|
|
headers = {}
|
|
for line in data.split(b"\r\n")[1:]:
|
|
if b":" in line:
|
|
k, v = line.split(b":", 1)
|
|
headers[k.strip().lower()] = v.strip()
|
|
key = headers.get(b"sec-websocket-key")
|
|
if not key:
|
|
return False
|
|
accept = base64.b64encode(hashlib.sha1(key + GUID.encode()).digest()).decode()
|
|
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
|
|
"Connection: Upgrade\r\n"
|
|
f"Sec-WebSocket-Accept: {accept}\r\n\r\n").encode())
|
|
return True
|
|
|
|
|
|
def _read_frame(conn):
|
|
b1, b2 = _recv_exact(conn, 2)
|
|
opcode = b1 & 0x0F
|
|
masked = b2 & 0x80
|
|
length = b2 & 0x7F
|
|
if length == 126:
|
|
length = struct.unpack(">H", _recv_exact(conn, 2))[0]
|
|
elif length == 127:
|
|
length = struct.unpack(">Q", _recv_exact(conn, 8))[0]
|
|
mask = _recv_exact(conn, 4) if masked else b""
|
|
payload = _recv_exact(conn, length) if length else b""
|
|
if masked:
|
|
payload = bytes(payload[i] ^ mask[i % 4] for i in range(len(payload)))
|
|
return opcode, payload
|
|
|
|
|
|
def _frame_text(text):
|
|
payload = text.encode()
|
|
header = bytearray([0x81])
|
|
n = len(payload)
|
|
if n < 126:
|
|
header.append(n)
|
|
elif n < 65536:
|
|
header.append(126)
|
|
header += struct.pack(">H", n)
|
|
else:
|
|
header.append(127)
|
|
header += struct.pack(">Q", n)
|
|
return bytes(header) + payload
|
|
|
|
|
|
def _frame_pong(payload):
|
|
"""Answer a client ping frame (opcode 0x9) with a pong (0xA).
|
|
|
|
OkHttp pings on its own schedule and drops the socket when no pong comes
|
|
back, so without this the app reconnects mid-drive.
|
|
"""
|
|
header = bytearray([0x8A])
|
|
n = len(payload)
|
|
if n < 126:
|
|
header.append(n)
|
|
elif n < 65536:
|
|
header.append(126)
|
|
header += struct.pack(">H", n)
|
|
else:
|
|
header.append(127)
|
|
header += struct.pack(">Q", n)
|
|
return bytes(header) + payload
|
|
|
|
|
|
class Session:
|
|
def __init__(self, conn):
|
|
self.conn = conn
|
|
self.lock = threading.Lock()
|
|
|
|
def send(self, message):
|
|
with self.lock:
|
|
self.conn.sendall(_frame_text(json.dumps(message)))
|
|
|
|
def send_event(self, session_id, kind, **fields):
|
|
frame = {"session_id": session_id, "kind": kind}
|
|
frame.update(fields)
|
|
self.send({"type": "chat_event", "chat_event": frame})
|
|
|
|
def push_permission(self, session_id, request_id, action, resources, message,
|
|
resolved=False, decision=""):
|
|
self.send({
|
|
"type": "chat_permission",
|
|
"chat_permission": {
|
|
"session_id": session_id,
|
|
"request_id": request_id,
|
|
"action": action,
|
|
"resources": resources,
|
|
"message": message,
|
|
"resolved": resolved,
|
|
"decision": decision,
|
|
"source": {"type": "tool", "message_id": "m2", "id": "call_1"},
|
|
},
|
|
})
|
|
|
|
def open_approval(self, session_id, request_id):
|
|
self.send_event(session_id, "step", step={"status": "started", "index": 1})
|
|
self.send_event(
|
|
session_id,
|
|
"text",
|
|
message_id="m3",
|
|
delta="Editing src/layout.kt — I need your approval before I write it.\n",
|
|
part={"type": "text", "id": "m3t"},
|
|
)
|
|
self.push_permission(
|
|
session_id,
|
|
request_id,
|
|
action="edit",
|
|
resources=["src/layout.kt"],
|
|
message="This rewrites src/layout.kt in your workspace. Review the change before allowing it.",
|
|
)
|
|
|
|
|
|
def _respond(session, request):
|
|
kind = request.get("type")
|
|
print(f"<- {kind}", flush=True)
|
|
rid = request.get("id")
|
|
if kind == "ping":
|
|
session.send({"id": rid, "type": "pong", "time": "2026-10-16T15:00:00Z"})
|
|
elif kind == "chat_sessions":
|
|
session.send({"id": rid, "type": "chat_sessions", "chat_sessions": SESSIONS})
|
|
elif kind == "chat_messages":
|
|
body = request.get("chat_messages") or request.get("chat_query") or {}
|
|
session_id = body.get("session_id") or PENDING_SESSION
|
|
session.send({"id": rid, "type": "chat_messages",
|
|
"chat_messages": MESSAGES.get(session_id, [])})
|
|
if session_id == RESOLVED_SESSION:
|
|
# The server reports a request it has already settled: the card must
|
|
# state the outcome instead of offering once/always/reject.
|
|
session.push_permission(
|
|
session_id,
|
|
"req_resolved",
|
|
action="shell",
|
|
resources=["go test ./..."],
|
|
message="Another client already rejected this command.",
|
|
resolved=True,
|
|
decision="reject",
|
|
)
|
|
elif kind == "chat_prompt":
|
|
body = request.get("chat_prompt") or {}
|
|
session_id = body.get("session_id") or PENDING_SESSION
|
|
session.send({"id": rid, "type": "chat_prompt"})
|
|
threading.Thread(
|
|
target=session.open_approval,
|
|
args=(session_id, f"req_pending_{next(REQUEST_SEQ)}"),
|
|
daemon=True,
|
|
).start()
|
|
elif kind == "chat_reply":
|
|
body = request.get("chat_reply") or {}
|
|
print(f" decision={body.get('decision')} request={body.get('request_id')}", flush=True)
|
|
session.send({"id": rid, "type": "chat_reply"})
|
|
elif kind == "chat_interrupt":
|
|
session.send({"id": rid, "type": "chat_interrupt"})
|
|
else:
|
|
# Benign echo for pipelines/runs/status so the app's background loads do
|
|
# not surface an error while the chat is being driven.
|
|
session.send({"id": rid, "type": kind})
|
|
|
|
|
|
def _serve(conn):
|
|
session = Session(conn)
|
|
try:
|
|
if not _handshake(conn):
|
|
return
|
|
while True:
|
|
opcode, payload = _read_frame(conn)
|
|
if opcode == 0x8:
|
|
break
|
|
if opcode == 0x9:
|
|
with session.lock:
|
|
conn.sendall(_frame_pong(payload))
|
|
continue
|
|
if opcode != 0x1:
|
|
continue
|
|
try:
|
|
request = json.loads(payload.decode())
|
|
except Exception:
|
|
continue
|
|
_respond(session, request)
|
|
except (EOFError, OSError):
|
|
pass
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def main():
|
|
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8799
|
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
server.bind(("0.0.0.0", port))
|
|
server.listen(8)
|
|
print(f"chat_stub_approval listening on 0.0.0.0:{port}", flush=True)
|
|
while True:
|
|
conn, _ = server.accept()
|
|
threading.Thread(target=_serve, args=(conn,), daemon=True).start()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|