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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated from trimmed zed.proto
|
| 2 |
+
from google.protobuf import descriptor as _descriptor
|
| 3 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 4 |
+
from google.protobuf import runtime_version as _runtime_version
|
| 5 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 6 |
+
from google.protobuf.internal import builder as _builder
|
| 7 |
+
_runtime_version.ValidateProtobufRuntimeVersion(
|
| 8 |
+
_runtime_version.Domain.PUBLIC,
|
| 9 |
+
5,
|
| 10 |
+
29,
|
| 11 |
+
0,
|
| 12 |
+
'',
|
| 13 |
+
'zed.proto'
|
| 14 |
+
)
|
| 15 |
+
# @@protoc_insertion_point(imports)
|
| 16 |
+
|
| 17 |
+
_sym_db = _symbol_database.Default()
|
| 18 |
+
|
| 19 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tzed.proto\x12\x0czed.messages\"&\n\x06PeerId\x12\x10\n\x08owner_id\x18\x01 \x01(\r\x12\n\n\x02id\x18\x02 \x01(\r\"\xe2\x05\n\x08\x45nvelope\x12\n\n\x02id\x18\x01 \x01(\r\x12\x1a\n\rresponding_to\x18\x02 \x01(\rH\x01\x88\x01\x01\x12\x35\n\x12original_sender_id\x18\x03 \x01(\x0b\x32\x14.zed.messages.PeerIdH\x02\x88\x01\x01\x12\x14\n\x06\x61\x63k_id\x18\x8a\x02 \x01(\rH\x03\x88\x01\x01\x12$\n\x05hello\x18\x04 \x01(\x0b\x32\x13.zed.messages.HelloH\x00\x12 \n\x03\x61\x63k\x18\x05 \x01(\x0b\x32\x11.zed.messages.AckH\x00\x12$\n\x05\x65rror\x18\x06 \x01(\x0b\x32\x13.zed.messages.ErrorH\x00\x12\"\n\x04ping\x18\x07 \x01(\x0b\x32\x12.zed.messages.PingH\x00\x12\x46\n\x17\x61\x63\x63\x65pt_terms_of_service\x18\xef\x01 \x01(\x0b\x32".zed.messages.AcceptTermsOfServiceH\x00\x12W\n accept_terms_of_service_response\x18\xf0\x01 \x01(\x0b\x32*.zed.messages.AcceptTermsOfServiceResponseH\x00\x12\x33\n\rget_llm_token\x18\xeb\x01 \x01(\x0b\x32\x19.zed.messages.GetLlmTokenH\x00\x12\x44\n\x16get_llm_token_response\x18\xec\x01 \x01(\x0b\x32!.zed.messages.GetLlmTokenResponseH\x00\x42\t\n\x07payloadB\x10\n\x0e_responding_toB\x15\n\x13_original_sender_idB\t\n\x07_ack_idJ\x04\x08W\x10YJ\x06\x08\x9e\x01\x10\xa2\x01J\x06\x08\xa4\x01\x10\xa5\x01J\x06\x08\xa6\x01\x10\xaa\x01J\x06\x08\xb1\x01\x10\xba\x01J\x06\x08\xbc\x01\x10\xbd\x01J\x06\x08\xc1\x01\x10\xc4\x01J\x06\x08\xc5\x01\x10\xc6\x01J\x06\x08\xc8\x01\x10\xcb\x01J\x06\x08\xcd\x01\x10\xcf\x01J\x06\x08\xdd\x01\x10\xde\x01J\x06\x08\xe0\x01\x10\xe6\x01J\x06\x08\xf6\x01\x10\xf7\x01J\x06\x08\xf7\x01\x10\xff\x01J\x06\x08\xff\x01\x10\x81\x02\".\n\x05Hello\x12%\n\x07peer_id\x18\x01 \x01(\x0b\x32\x14.zed.messages.PeerId\"\x06\n\x04Ping\"\x05\n\x03\x41\x63k\"M\n\x05\x45rror\x12\x0f\n\x07message\x18\x01 \x01(\t\x12%\n\x04\x63ode\x18\x02 \x01(\x0e\x32\x17.zed.messages.ErrorCode\x12\x0c\n\x04tags\x18\x03 \x03(\t\"\x16\n\x14\x41\x63\x63\x65ptTermsOfService\"7\n\x1c\x41\x63\x63\x65ptTermsOfServiceResponse\x12\x17\n\x0f\x61\x63\x63\x65pted_tos_at\x18\x01 \x01(\x04\"\r\n\x0bGetLlmToken\"$\n\x13GetLlmTokenResponse\x12\r\n\x05token\x18\x01 \x01(\t*\xef\x02\n\tErrorCode\x12\x0c\n\x08Internal\x10\x00\x12\x11\n\rNoSuchChannel\x10\x01\x12\x10\n\x0c\x44isconnected\x10\x02\x12\r\n\tSignedOut\x10\x03\x12\x13\n\x0fUpgradeRequired\x10\x04\x12\r\n\tForbidden\x10\x05\x12\x0c\n\x08NeedsCla\x10\x07\x12\x13\n\x0fNotARootChannel\x10\x08\x12\x14\n\x10\x42\x61\x64PublicNesting\x10\t\x12\x13\n\x0f\x43ircularNesting\x10\n\x12\x13\n\x0fWrongMoveTarget\x10\x0b\x12\x10\n\x0cUnsharedItem\x10\x0c\x12\x11\n\rNoSuchProject\x10\r\x12$\n DevServerProjectPathDoesNotExist\x10\x10\x12\x19\n\x15RemoteUpgradeRequired\x10\x11\x12\x15\n\x11RateLimitExceeded\x10\x12\x12\x10\n\x0c\x43ommitFailed\x10\x13\"\x04\x08\x06\x10\x06\"\x04\x08\x0e\x10\x0f\x62\x06proto3')
|
| 20 |
+
|
| 21 |
+
_globals = globals()
|
| 22 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
| 23 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'zed_pb2', _globals)
|
| 24 |
+
if not _descriptor._USE_C_DESCRIPTORS:
|
| 25 |
+
DESCRIPTOR._loaded_options = None
|
| 26 |
+
_globals['_ERRORCODE']._serialized_start=1085
|
| 27 |
+
_globals['_ERRORCODE']._serialized_end=1452
|
| 28 |
+
_globals['_PEERID']._serialized_start=27
|
| 29 |
+
_globals['_PEERID']._serialized_end=65
|
| 30 |
+
_globals['_ENVELOPE']._serialized_start=68
|
| 31 |
+
_globals['_ENVELOPE']._serialized_end=806
|
| 32 |
+
_globals['_HELLO']._serialized_start=808
|
| 33 |
+
_globals['_HELLO']._serialized_end=854
|
| 34 |
+
_globals['_PING']._serialized_start=856
|
| 35 |
+
_globals['_PING']._serialized_end=862
|
| 36 |
+
_globals['_ACK']._serialized_start=864
|
| 37 |
+
_globals['_ACK']._serialized_end=869
|
| 38 |
+
_globals['_ERROR']._serialized_start=871
|
| 39 |
+
_globals['_ERROR']._serialized_end=948
|
| 40 |
+
_globals['_ACCEPTTERMSOFSERVICE']._serialized_start=950
|
| 41 |
+
_globals['_ACCEPTTERMSOFSERVICE']._serialized_end=972
|
| 42 |
+
_globals['_ACCEPTTERMSOFSERVICERESPONSE']._serialized_start=974
|
| 43 |
+
_globals['_ACCEPTTERMSOFSERVICERESPONSE']._serialized_end=1029
|
| 44 |
+
_globals['_GETLLMTOKEN']._serialized_start=1031
|
| 45 |
+
_globals['_GETLLMTOKEN']._serialized_end=1044
|
| 46 |
+
_globals['_GETLLMTOKENRESPONSE']._serialized_start=1046
|
| 47 |
+
_globals['_GETLLMTOKENRESPONSE']._serialized_end=1082
|
| 48 |
+
|
| 49 |
+
# Start of the actual script
|
| 50 |
+
import os
|
| 51 |
+
import random
|
| 52 |
+
import base64
|
| 53 |
+
import json
|
| 54 |
+
import urllib.parse
|
| 55 |
+
import ssl
|
| 56 |
+
import time
|
| 57 |
+
import asyncio
|
| 58 |
+
import logging
|
| 59 |
+
import aiohttp
|
| 60 |
+
from aiohttp import web
|
| 61 |
+
import zstandard as zstd
|
| 62 |
+
from websockets.asyncio.client import connect
|
| 63 |
+
from websockets.exceptions import ConnectionClosed
|
| 64 |
+
|
| 65 |
+
import rsa
|
| 66 |
+
|
| 67 |
+
from google.protobuf.json_format import MessageToDict
|
| 68 |
+
|
| 69 |
+
logging.basicConfig(
|
| 70 |
+
level=logging.INFO,
|
| 71 |
+
format='%(levelname)s: %(message)s'
|
| 72 |
+
)
|
| 73 |
+
logger = logging.getLogger(__name__)
|
| 74 |
+
|
| 75 |
+
BASE_URL = "https://zed.dev"
|
| 76 |
+
BASE_API_URL = "https://collab.zed.dev"
|
| 77 |
+
WS_URL = "wss://collab.zed.dev/rpc"
|
| 78 |
+
LLM_API_URL = "https://llm.zed.dev/completion"
|
| 79 |
+
PROXY_PORT = 9090
|
| 80 |
+
TOKEN_EXPIRY_WARNING_MINUTES = 50
|
| 81 |
+
|
| 82 |
+
highest_message_id = 0
|
| 83 |
+
llm_token = None
|
| 84 |
+
token_timestamp = None
|
| 85 |
+
server_peer_id = None
|
| 86 |
+
active_websocket = None
|
| 87 |
+
proxy_server_running = False
|
| 88 |
+
|
| 89 |
+
def generate_signin_url():
|
| 90 |
+
port = random.randint(30000, 55000)
|
| 91 |
+
(pubkey, privkey) = rsa.newkeys(2048, exponent=65537)
|
| 92 |
+
der_public_key = rsa.PublicKey.save_pkcs1(pubkey, format='DER')
|
| 93 |
+
b64_public_key = base64.urlsafe_b64encode(der_public_key).decode('utf-8')
|
| 94 |
+
signin_url = f"{BASE_URL}/native_app_signin?native_app_port={port}&native_app_public_key={b64_public_key}"
|
| 95 |
+
return signin_url, privkey
|
| 96 |
+
|
| 97 |
+
def decrypt_access_token(access_token_b64, private_key):
|
| 98 |
+
encrypted_token = base64.urlsafe_b64decode(access_token_b64)
|
| 99 |
+
try:
|
| 100 |
+
decrypted = rsa.decrypt(encrypted_token, private_key)
|
| 101 |
+
return decrypted.decode('utf-8')
|
| 102 |
+
except Exception as e:
|
| 103 |
+
try:
|
| 104 |
+
decrypted = rsa.decrypt(encrypted_token, private_key, 'PKCS1_v1_5')
|
| 105 |
+
return decrypted.decode('utf-8')
|
| 106 |
+
except Exception as inner_e:
|
| 107 |
+
raise Exception(f"Decryption failed (OAEP -> PKCS#1): {e}, {inner_e}")
|
| 108 |
+
|
| 109 |
+
def do_auth_flow():
|
| 110 |
+
signin_url, private_key = generate_signin_url()
|
| 111 |
+
print("\n!Sign in with GitHub (wait a few seconds after signing in for the redirect):\n", signin_url)
|
| 112 |
+
print("\nPaste the full callback URL where the browser redirected you here:")
|
| 113 |
+
callback_url = input().strip()
|
| 114 |
+
|
| 115 |
+
parsed_url = urllib.parse.urlparse(callback_url)
|
| 116 |
+
query_params = urllib.parse.parse_qs(parsed_url.query)
|
| 117 |
+
|
| 118 |
+
user_id = query_params.get('user_id', [''])[0]
|
| 119 |
+
access_token_b64 = query_params.get('access_token', [''])[0]
|
| 120 |
+
|
| 121 |
+
if not user_id or not access_token_b64:
|
| 122 |
+
raise Exception("Missing user_id or access_token in callback URL.")
|
| 123 |
+
|
| 124 |
+
decrypted_token = decrypt_access_token(access_token_b64, private_key)
|
| 125 |
+
login_data = {"user_id": user_id, "auth": decrypted_token}
|
| 126 |
+
with open('login.json', 'w') as f:
|
| 127 |
+
json.dump(login_data, f, indent=2)
|
| 128 |
+
logger.info("Success! Authentication data saved to login.json")
|
| 129 |
+
logger.info(f"User ID: {user_id}")
|
| 130 |
+
|
| 131 |
+
def decode_envelope(data):
|
| 132 |
+
try:
|
| 133 |
+
dctx = zstd.ZstdDecompressor()
|
| 134 |
+
decompressed_data = b''
|
| 135 |
+
with dctx.stream_reader(data) as reader:
|
| 136 |
+
while True:
|
| 137 |
+
chunk = reader.read(8192)
|
| 138 |
+
if not chunk:
|
| 139 |
+
break
|
| 140 |
+
decompressed_data += chunk
|
| 141 |
+
envelope = Envelope()
|
| 142 |
+
envelope.ParseFromString(decompressed_data)
|
| 143 |
+
return MessageToDict(envelope, preserving_proto_field_name=True)
|
| 144 |
+
except Exception as e:
|
| 145 |
+
hex_preview = ' '.join(f'{byte:02x}' for byte in data[:20]) + ('...' if len(data) > 20 else '')
|
| 146 |
+
logger.error(f"Unable to decode message: {e}; data preview: {hex_preview}")
|
| 147 |
+
return {"error": f"Unable to decode message: {e}"}
|
| 148 |
+
|
| 149 |
+
def compress_protobuf(data):
|
| 150 |
+
return zstd.ZstdCompressor(level=-7).compress(data)
|
| 151 |
+
|
| 152 |
+
def create_message(message_type):
|
| 153 |
+
global highest_message_id
|
| 154 |
+
highest_message_id += 1
|
| 155 |
+
message_id = highest_message_id
|
| 156 |
+
envelope = Envelope(id=highest_message_id)
|
| 157 |
+
|
| 158 |
+
getattr(envelope, message_type).SetInParent()
|
| 159 |
+
return compress_protobuf(envelope.SerializeToString()), message_id
|
| 160 |
+
|
| 161 |
+
async def ping_periodically(websocket):
|
| 162 |
+
while True:
|
| 163 |
+
try:
|
| 164 |
+
await websocket.ping()
|
| 165 |
+
await asyncio.sleep(1)
|
| 166 |
+
except Exception as e:
|
| 167 |
+
logger.error(f"Error sending ping: {e}")
|
| 168 |
+
break
|
| 169 |
+
|
| 170 |
+
async def handle_messages(websocket):
|
| 171 |
+
global server_peer_id, llm_token, token_timestamp, active_websocket
|
| 172 |
+
active_websocket = websocket
|
| 173 |
+
try:
|
| 174 |
+
async for message in websocket:
|
| 175 |
+
message_bytes = message.encode('utf-8') if isinstance(message, str) else message
|
| 176 |
+
decoded = decode_envelope(message_bytes)
|
| 177 |
+
if "hello" in decoded:
|
| 178 |
+
server_peer_id = decoded.get('hello', {}).get('peer_id')
|
| 179 |
+
elif "accept_terms_of_service_response" in decoded:
|
| 180 |
+
await request_llm_token(websocket)
|
| 181 |
+
elif ("get_llm_token_response" in decoded and
|
| 182 |
+
'token' in decoded.get('get_llm_token_response', {})):
|
| 183 |
+
llm_token = decoded['get_llm_token_response']['token']
|
| 184 |
+
token_timestamp = time.time()
|
| 185 |
+
logger.info(f"LLM token received at {time.ctime(token_timestamp)}")
|
| 186 |
+
if not proxy_server_running:
|
| 187 |
+
asyncio.create_task(start_proxy_server())
|
| 188 |
+
asyncio.create_task(monitor_token_expiration())
|
| 189 |
+
logger.info("Closing WebSocket connection until token refresh is needed")
|
| 190 |
+
await websocket.close()
|
| 191 |
+
active_websocket = None
|
| 192 |
+
return
|
| 193 |
+
except ConnectionClosed:
|
| 194 |
+
logger.info("Connection closed")
|
| 195 |
+
active_websocket = None
|
| 196 |
+
|
| 197 |
+
async def request_llm_token(websocket):
|
| 198 |
+
message, _ = create_message('get_llm_token')
|
| 199 |
+
logger.info("Requesting the LLM token")
|
| 200 |
+
await websocket.send(message)
|
| 201 |
+
|
| 202 |
+
async def request_accept_terms_of_service(websocket):
|
| 203 |
+
message, _ = create_message('accept_terms_of_service')
|
| 204 |
+
logger.info("Sending consent for the Zed Terms of Service")
|
| 205 |
+
await websocket.send(message)
|
| 206 |
+
|
| 207 |
+
def format_content(content):
|
| 208 |
+
if isinstance(content, str):
|
| 209 |
+
return [{"type": "text", "text": content}]
|
| 210 |
+
return content
|
| 211 |
+
|
| 212 |
+
async def handle_message_request(request):
|
| 213 |
+
global llm_token
|
| 214 |
+
if not llm_token:
|
| 215 |
+
return web.json_response({"error": "LLM token not available"}, status=500)
|
| 216 |
+
try:
|
| 217 |
+
body = await request.json()
|
| 218 |
+
# Zed's Anthropic API weirdly doesn't want flat strings for messages
|
| 219 |
+
if "messages" in body:
|
| 220 |
+
for msg in body["messages"]:
|
| 221 |
+
if "content" in msg:
|
| 222 |
+
msg["content"] = format_content(msg["content"])
|
| 223 |
+
# But wants flat strings for system messages
|
| 224 |
+
if "system" in body:
|
| 225 |
+
if isinstance(body["system"], list):
|
| 226 |
+
body["system"] = "\n".join([item["text"] for item in body["system"]])
|
| 227 |
+
|
| 228 |
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {llm_token}"}
|
| 229 |
+
payload = {
|
| 230 |
+
"provider": "anthropic",
|
| 231 |
+
"model": body.get("model", "claude-3-5-sonnet"),
|
| 232 |
+
"provider_request": body
|
| 233 |
+
}
|
| 234 |
+
if body.get("stream", False):
|
| 235 |
+
return await handle_streaming_request(request, headers, payload)
|
| 236 |
+
else:
|
| 237 |
+
return await handle_non_streaming_request(headers, payload)
|
| 238 |
+
except Exception as e:
|
| 239 |
+
logger.error(f"Error processing request: {e}")
|
| 240 |
+
return web.json_response({"error": str(e)}, status=500)
|
| 241 |
+
|
| 242 |
+
async def handle_non_streaming_request(headers, payload):
|
| 243 |
+
async with aiohttp.ClientSession() as session:
|
| 244 |
+
async with session.post(LLM_API_URL, headers=headers, json=payload) as r:
|
| 245 |
+
if r.status != 200:
|
| 246 |
+
text = await r.text()
|
| 247 |
+
logger.error(f"LLM API error: {text}")
|
| 248 |
+
return web.json_response({"error": text}, status=r.status)
|
| 249 |
+
full_content, message_data = "", {}
|
| 250 |
+
async for line in r.content:
|
| 251 |
+
if not line:
|
| 252 |
+
continue
|
| 253 |
+
try:
|
| 254 |
+
event = json.loads(line.decode('utf-8').strip())
|
| 255 |
+
et = event.get('type')
|
| 256 |
+
if et == "message_start":
|
| 257 |
+
message_data = event.get('message', {})
|
| 258 |
+
elif et == "content_block_delta" and event.get('delta', {}).get('type') == "text_delta":
|
| 259 |
+
full_content += event['delta'].get('text', '')
|
| 260 |
+
elif et == "message_delta" and 'usage' in event:
|
| 261 |
+
message_data['usage'] = event.get('usage')
|
| 262 |
+
elif et == "message_stop":
|
| 263 |
+
break
|
| 264 |
+
except Exception as e:
|
| 265 |
+
logger.error(f"Error processing line: {e}")
|
| 266 |
+
message_data['content'] = [{"type": "text", "text": full_content}]
|
| 267 |
+
return web.json_response(message_data)
|
| 268 |
+
|
| 269 |
+
async def handle_streaming_request(request, headers, payload):
|
| 270 |
+
response = web.StreamResponse()
|
| 271 |
+
response.headers['Content-Type'] = 'text/event-stream'
|
| 272 |
+
response.headers['Cache-Control'] = 'no-cache'
|
| 273 |
+
response.headers['Connection'] = 'keep-alive'
|
| 274 |
+
await response.prepare(request)
|
| 275 |
+
async with aiohttp.ClientSession() as session:
|
| 276 |
+
async with session.post(LLM_API_URL, headers=headers, json=payload, timeout=60) as api_response:
|
| 277 |
+
if api_response.status != 200:
|
| 278 |
+
error_text = await api_response.text()
|
| 279 |
+
logger.error(f"LLM API (stream) error: {error_text}")
|
| 280 |
+
await response.write(f"data: {json.dumps({'error': error_text})}\n\n".encode())
|
| 281 |
+
await response.write(b"data: [DONE]\n\n")
|
| 282 |
+
return response
|
| 283 |
+
async for line in api_response.content:
|
| 284 |
+
if line:
|
| 285 |
+
await response.write(f"data: {line.decode('utf-8')}\n\n".encode())
|
| 286 |
+
await response.write(b"data: [DONE]\n\n")
|
| 287 |
+
return response
|
| 288 |
+
|
| 289 |
+
async def start_proxy_server():
|
| 290 |
+
global proxy_server_running
|
| 291 |
+
if proxy_server_running:
|
| 292 |
+
logger.info("Proxy server already running, skipping startup")
|
| 293 |
+
return
|
| 294 |
+
|
| 295 |
+
proxy_server_running = True
|
| 296 |
+
app = web.Application()
|
| 297 |
+
|
| 298 |
+
app.router.add_post('/v1/messages', handle_message_request)
|
| 299 |
+
runner = web.AppRunner(app)
|
| 300 |
+
await runner.setup()
|
| 301 |
+
site = web.TCPSite(runner, 'localhost', PROXY_PORT)
|
| 302 |
+
await site.start()
|
| 303 |
+
logger.info(f"Proxy server started at http://localhost:{PROXY_PORT}")
|
| 304 |
+
|
| 305 |
+
# Start localtunnel
|
| 306 |
+
try:
|
| 307 |
+
import subprocess
|
| 308 |
+
process = subprocess.Popen(
|
| 309 |
+
['lt', '--port', str(PROXY_PORT)],
|
| 310 |
+
stdout=subprocess.PIPE,
|
| 311 |
+
stderr=subprocess.PIPE,
|
| 312 |
+
universal_newlines=True
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
# Wait for the tunnel URL
|
| 316 |
+
while True:
|
| 317 |
+
output = process.stdout.readline()
|
| 318 |
+
if output:
|
| 319 |
+
if 'your url is:' in output.lower():
|
| 320 |
+
url = output.split(':')[-1].strip()
|
| 321 |
+
logger.info(f"\nTunnel established!")
|
| 322 |
+
logger.info(f"Public URL: {url}")
|
| 323 |
+
logger.info("\nKeeping tunnel alive. Press Ctrl+C to stop.")
|
| 324 |
+
break
|
| 325 |
+
|
| 326 |
+
# Check if process failed
|
| 327 |
+
if process.poll() is not None:
|
| 328 |
+
error = process.stderr.read()
|
| 329 |
+
logger.error(f"Error starting tunnel: {error}")
|
| 330 |
+
break
|
| 331 |
+
|
| 332 |
+
await asyncio.sleep(0.1)
|
| 333 |
+
|
| 334 |
+
while True:
|
| 335 |
+
await asyncio.sleep(3600)
|
| 336 |
+
|
| 337 |
+
except Exception as e:
|
| 338 |
+
logger.error(f"Error setting up tunnel: {e}")
|
| 339 |
+
while True:
|
| 340 |
+
await asyncio.sleep(3600)
|
| 341 |
+
|
| 342 |
+
def is_token_expiring():
|
| 343 |
+
if not token_timestamp:
|
| 344 |
+
return False
|
| 345 |
+
return (time.time() - token_timestamp) / 60 >= TOKEN_EXPIRY_WARNING_MINUTES
|
| 346 |
+
|
| 347 |
+
async def monitor_token_expiration():
|
| 348 |
+
while True:
|
| 349 |
+
await asyncio.sleep(60)
|
| 350 |
+
if is_token_expiring():
|
| 351 |
+
elapsed = int((time.time() - token_timestamp) / 60)
|
| 352 |
+
logger.warning(f"LLM token is approaching expiration (received {elapsed} minutes ago)")
|
| 353 |
+
if active_websocket is None:
|
| 354 |
+
logger.info("Reconnecting WebSocket for token refresh")
|
| 355 |
+
asyncio.create_task(reconnect_for_token_refresh())
|
| 356 |
+
return
|
| 357 |
+
|
| 358 |
+
async def reconnect_for_token_refresh():
|
| 359 |
+
try:
|
| 360 |
+
with open("login.json") as f:
|
| 361 |
+
login_data = json.load(f)
|
| 362 |
+
headers = {
|
| 363 |
+
"authorization": login_data["user_id"] + " " + login_data["auth"],
|
| 364 |
+
"x-zed-protocol-version": "68",
|
| 365 |
+
"x-zed-app-version": "0.178.0",
|
| 366 |
+
"x-zed-release-channel": "stable"
|
| 367 |
+
}
|
| 368 |
+
ssl_context = ssl.create_default_context()
|
| 369 |
+
ssl_context.check_hostname = False
|
| 370 |
+
ssl_context.verify_mode = ssl.CERT_NONE
|
| 371 |
+
|
| 372 |
+
async for websocket in connect(WS_URL, additional_headers=headers, ssl=ssl_context):
|
| 373 |
+
try:
|
| 374 |
+
ping_task = asyncio.create_task(ping_periodically(websocket))
|
| 375 |
+
await asyncio.sleep(2)
|
| 376 |
+
await request_accept_terms_of_service(websocket)
|
| 377 |
+
await handle_messages(websocket)
|
| 378 |
+
break
|
| 379 |
+
except ConnectionClosed:
|
| 380 |
+
continue
|
| 381 |
+
except Exception as e:
|
| 382 |
+
logger.error(f"Error during token refresh: {e}")
|
| 383 |
+
await asyncio.sleep(1)
|
| 384 |
+
continue
|
| 385 |
+
finally:
|
| 386 |
+
ping_task.cancel()
|
| 387 |
+
try:
|
| 388 |
+
await ping_task
|
| 389 |
+
except asyncio.CancelledError:
|
| 390 |
+
pass
|
| 391 |
+
except Exception as e:
|
| 392 |
+
logger.error(f"Failed to reconnect for token refresh: {e}")
|
| 393 |
+
|
| 394 |
+
async def async_main():
|
| 395 |
+
with open("login.json") as f:
|
| 396 |
+
login_data = json.load(f)
|
| 397 |
+
headers = {
|
| 398 |
+
"authorization": login_data["user_id"] + " " + login_data["auth"],
|
| 399 |
+
"x-zed-protocol-version": "68",
|
| 400 |
+
"x-zed-app-version": "0.178.0",
|
| 401 |
+
"x-zed-release-channel": "stable"
|
| 402 |
+
}
|
| 403 |
+
ssl_context = ssl.create_default_context()
|
| 404 |
+
ssl_context.check_hostname = False
|
| 405 |
+
ssl_context.verify_mode = ssl.CERT_NONE
|
| 406 |
+
logger.info("Connecting to the WebSocket server")
|
| 407 |
+
async for websocket in connect(WS_URL, additional_headers=headers, ssl=ssl_context):
|
| 408 |
+
try:
|
| 409 |
+
ping_task = asyncio.create_task(ping_periodically(websocket))
|
| 410 |
+
token_request_task = asyncio.create_task(delayed_token_request(websocket, delay=2))
|
| 411 |
+
await handle_messages(websocket)
|
| 412 |
+
break
|
| 413 |
+
except ConnectionClosed:
|
| 414 |
+
continue
|
| 415 |
+
except Exception as e:
|
| 416 |
+
logger.error(f"Unexpected error: {e}")
|
| 417 |
+
await asyncio.sleep(1)
|
| 418 |
+
continue
|
| 419 |
+
finally:
|
| 420 |
+
ping_task.cancel()
|
| 421 |
+
try:
|
| 422 |
+
await ping_task
|
| 423 |
+
except asyncio.CancelledError:
|
| 424 |
+
pass
|
| 425 |
+
token_request_task.cancel()
|
| 426 |
+
try:
|
| 427 |
+
await token_request_task
|
| 428 |
+
except asyncio.CancelledError:
|
| 429 |
+
pass
|
| 430 |
+
|
| 431 |
+
while True:
|
| 432 |
+
await asyncio.sleep(3600)
|
| 433 |
+
|
| 434 |
+
async def delayed_token_request(websocket, delay=2):
|
| 435 |
+
await asyncio.sleep(delay)
|
| 436 |
+
await request_accept_terms_of_service(websocket)
|
| 437 |
+
|
| 438 |
+
def main():
|
| 439 |
+
need_auth = False
|
| 440 |
+
if not os.path.exists("login.json"):
|
| 441 |
+
need_auth = True
|
| 442 |
+
else:
|
| 443 |
+
try:
|
| 444 |
+
with open("login.json") as f:
|
| 445 |
+
data = json.load(f)
|
| 446 |
+
if not data.get("user_id") or not data.get("auth"):
|
| 447 |
+
need_auth = True
|
| 448 |
+
except:
|
| 449 |
+
need_auth = True
|
| 450 |
+
|
| 451 |
+
if need_auth:
|
| 452 |
+
do_auth_flow()
|
| 453 |
+
else:
|
| 454 |
+
logger.info("login.json seems to be present, skipping authentication flow")
|
| 455 |
+
try:
|
| 456 |
+
asyncio.run(async_main())
|
| 457 |
+
except KeyboardInterrupt:
|
| 458 |
+
pass
|
| 459 |
+
|
| 460 |
+
if __name__ == "__main__":
|
| 461 |
+
main()
|