recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
+257
@@ -0,0 +1,257 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""typegw.py — OpenAI-compatible gateway over type.com account pool (oRPC reverse).
|
||||
Run: python typegw.py [port] (default 8600). Key: TYPE_GW_KEY env or gw_key.txt or 'type-local-2026'.
|
||||
Endpoints: /v1/chat/completions (stream+non-stream), /v1/models, /health, / (dashboard)."""
|
||||
import sys, json, time, os, random, threading, urllib.request, urllib.error
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
POOL_PATH = os.path.join(HERE, 'pool.json')
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8600
|
||||
KEY = os.environ.get('TYPE_GW_KEY')
|
||||
if not KEY:
|
||||
kf = os.path.join(HERE, 'gw_key.txt')
|
||||
KEY = open(kf).read().strip() if os.path.exists(kf) else 'type-local-2026'
|
||||
|
||||
B32 = '0123456789abcdefghjkmnpqrstvwxyz'
|
||||
LOCK = threading.Lock()
|
||||
|
||||
MODELS = [
|
||||
('gpt-6.1-sol', 'openai', 'Codex 6.1 Sol (default)'), ('gpt-6-sol', 'openai', 'Codex 6 Sol'),
|
||||
('gpt-6-luna', 'openai', 'Codex 6 Luna (fast)'), ('gpt-6-astra', 'openai', 'Codex 6 Astra (reasoning)'),
|
||||
('gpt-5.5', 'openai', 'Codex 5.5'), ('gpt-5.6-sol', 'openai', 'Codex 5.6 Sol'),
|
||||
('gpt-5.6-terra', 'openai', 'Codex 5.6 Terra'), ('gpt-5.6-luna', 'openai', 'Codex 5.6 Luna (fast)'),
|
||||
('gpt-5.2-2025-12-11', 'openai', 'GPT-5.2'), ('gpt-5-mini-2025-08-07', 'openai', 'GPT-5 mini'),
|
||||
('claude-opus-5-5', 'anthropic', 'Claude Opus 5.5'), ('claude-fable-5-1', 'anthropic', 'Claude Fable 5.1'),
|
||||
('claude-fable-5', 'anthropic', 'Claude Fable 5'), ('claude-sonnet-5-5', 'anthropic', 'Claude Sonnet 5.5'),
|
||||
('claude-sonnet-5', 'anthropic', 'Claude Sonnet 5'), ('claude-sonnet-4-6', 'anthropic', 'Claude Sonnet 4.6'),
|
||||
('claude-opus-4-5-20251101', 'anthropic', 'Claude Opus 4.5'), ('claude-opus-4-6', 'anthropic', 'Claude Opus 4.6'),
|
||||
('claude-opus-4-8', 'anthropic', 'Claude Opus 4.8'), ('claude-opus-5', 'anthropic', 'Claude Opus 5'),
|
||||
('claude-haiku-5-5', 'anthropic', 'Claude Haiku 5.5'), ('claude-haiku-4-5-20251001', 'anthropic', 'Claude Haiku 4.5'),
|
||||
('gemini-3-flash-preview', 'google', 'Gemini 3 Flash'), ('gemini-3-pro-preview', 'google', 'Gemini 3 Pro'),
|
||||
('gemini-3.1-pro-preview', 'google', 'Gemini 3.1 Pro'),
|
||||
]
|
||||
MODEL_PROVIDER = {m: p for m, p, _ in MODELS}
|
||||
|
||||
def msg_ulid():
|
||||
ts = int(time.time() * 1000)
|
||||
t = ''
|
||||
for _ in range(10):
|
||||
t = B32[ts % 32] + t
|
||||
ts //= 32
|
||||
if t[0] not in '01234567':
|
||||
t = str(int(t[0], 32) % 8) + t[1:]
|
||||
return 'msg_' + t + ''.join(random.choice(B32) for _ in range(16))
|
||||
|
||||
def load_pool():
|
||||
with LOCK:
|
||||
try:
|
||||
return json.load(open(POOL_PATH, encoding='utf-8'))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def save_pool(pool):
|
||||
with LOCK:
|
||||
tmp = POOL_PATH + '.tmp'
|
||||
json.dump(pool, open(tmp, 'w', encoding='utf-8'), indent=1)
|
||||
os.replace(tmp, POOL_PATH)
|
||||
|
||||
def orpc(acc, ep, payload, timeout=40):
|
||||
req = urllib.request.Request('https://api.type.com/api/orpc/' + ep,
|
||||
data=json.dumps({'json': payload}).encode(), headers={
|
||||
'content-type': 'application/json', 'authorization': acc['token'],
|
||||
'origin': 'https://type.com', 'referer': 'https://type.com/',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read().decode('utf-8', 'ignore')
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode('utf-8', 'ignore')
|
||||
except Exception as e:
|
||||
return -1, str(e)[:300]
|
||||
|
||||
def pick_account(pool, provider):
|
||||
now = time.time()
|
||||
cands = [a for a in pool if a.get('token') and a.get('channelId')
|
||||
and a.get('quarantine_until', 0) < now and a.get('fails', 0) < 5]
|
||||
if provider == 'openai':
|
||||
byo = [a for a in cands if a.get('codex')]
|
||||
if byo: cands = byo
|
||||
if not cands: return None
|
||||
cands.sort(key=lambda a: a.get('last_used', 0))
|
||||
return cands[0]
|
||||
|
||||
def quarantine(acc, secs, reason):
|
||||
pool = load_pool()
|
||||
for a in pool:
|
||||
if a['email'] == acc['email']:
|
||||
a['quarantine_until'] = time.time() + secs
|
||||
a['fails'] = a.get('fails', 0) + 1
|
||||
a['last_err'] = reason[:200]
|
||||
save_pool(pool)
|
||||
|
||||
def mark_used(acc):
|
||||
pool = load_pool()
|
||||
for a in pool:
|
||||
if a['email'] == acc['email']:
|
||||
a['last_used'] = time.time(); a['fails'] = 0
|
||||
save_pool(pool)
|
||||
|
||||
def flatten_content(messages):
|
||||
parts = []
|
||||
for m in messages:
|
||||
role = m.get('role', 'user')
|
||||
c = m.get('content')
|
||||
if isinstance(c, list):
|
||||
c = ' '.join(x.get('text', '') for x in c if isinstance(x, dict))
|
||||
if role == 'system':
|
||||
parts.append('[System] ' + str(c))
|
||||
elif role == 'assistant':
|
||||
parts.append('[Assistant history] ' + str(c)[:500])
|
||||
else:
|
||||
parts.append(str(c))
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
def send_and_wait(acc, text, provider, model, deadline=420, on_delta=None):
|
||||
mid = msg_ulid()
|
||||
payload = {
|
||||
'id': mid, 'channelId': acc['channelId'],
|
||||
'parentMessageId': None, 'subchannelId': None, 'replyToId': None,
|
||||
'content': {'version': '1.0', 'blocks': [{'type': 'paragraph', 'children': [{'type': 'text', 'text': text}]}]},
|
||||
'contentSchemaVersion': '1.0', 'textContent': text, 'botName': None,
|
||||
'isBotResponse': False, 'isStreaming': False, 'hasError': False,
|
||||
'fileIds': [], 'timezone': 'Europe/Kyiv', 'aiProvider': provider, 'modelId': model,
|
||||
'triggerTimestamp': int(time.time() * 1000), 'responseIndex': 0,
|
||||
'agentToggleEnabled': True, 'replyMode': 'chat', 'metadata': None,
|
||||
}
|
||||
st, bd = orpc(acc, 'messages/createMessage', payload)
|
||||
if st == 403:
|
||||
quarantine(acc, 3600, bd[:200])
|
||||
return None, '403: ' + bd[:200]
|
||||
if st == 401:
|
||||
quarantine(acc, 7200, '401 token expired')
|
||||
return None, '401 token expired'
|
||||
if st != 200:
|
||||
quarantine(acc, 600, f'{st}: {bd[:150]}')
|
||||
return None, f'createMessage {st}: {bd[:300]}'
|
||||
t0 = time.time()
|
||||
last_len = 0
|
||||
while time.time() - t0 < deadline:
|
||||
st, bd = orpc(acc, 'messages/getMessagesPaginated',
|
||||
{'channelId': acc['channelId'], 'limit': 25, 'direction': 'backward',
|
||||
'parentMessageId': mid}, 60)
|
||||
if st == 200:
|
||||
msgs = json.loads(bd)['json'].get('messages', [])
|
||||
bots = [m for m in msgs if (m.get('isBotResponse') or m.get('botName'))
|
||||
and (m.get('replyToId') == mid or m.get('parentMessageId') == mid
|
||||
or (m.get('triggerTimestamp') or 0) >= payload['triggerTimestamp'] - 5000
|
||||
or m['id'] > mid)]
|
||||
for m in bots:
|
||||
txt = m.get('textContent') or ''
|
||||
if on_delta and len(txt) > last_len:
|
||||
on_delta(txt[last_len:]); last_len = len(txt)
|
||||
if txt and not m.get('isStreaming'):
|
||||
if m.get('hasError'):
|
||||
return None, 'agent error: ' + txt[:300]
|
||||
return txt, None
|
||||
if m.get('hasError'):
|
||||
return None, 'agent error: ' + (txt or json.dumps(m.get('metadata'))[:200])
|
||||
time.sleep(3)
|
||||
return None, 'timeout waiting agent reply'
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a): pass
|
||||
|
||||
def _json(self, code, obj):
|
||||
b = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header('content-type', 'application/json')
|
||||
self.send_header('content-length', str(len(b)))
|
||||
self.end_headers(); self.wfile.write(b)
|
||||
|
||||
def _auth(self):
|
||||
a = self.headers.get('authorization', '')
|
||||
return a in ('Bearer ' + KEY, KEY)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == '/health':
|
||||
return self._json(200, {'ok': True})
|
||||
if self.path == '/v1/models':
|
||||
return self._json(200, {'object': 'list', 'data': [
|
||||
{'id': m, 'object': 'model', 'owned_by': p, 'description': n} for m, p, n in MODELS]})
|
||||
if self.path == '/':
|
||||
pool = load_pool()
|
||||
now = time.time()
|
||||
rows = ''.join(
|
||||
f"<tr><td>{a['email']}</td><td>{'BYO-codex' if a.get('codex') else 'platform'}</td>"
|
||||
f"<td>{a.get('billing_status','?')}</td><td>{str(a.get('trial_end'))[:10]}</td>"
|
||||
f"<td>{'QUAR' if a.get('quarantine_until',0)>now else ('dead' if a.get('fails',0)>=5 else 'ok')}</td>"
|
||||
f"<td>{a.get('last_err','')[:60]}</td></tr>" for a in pool)
|
||||
html = f"<h2>type.com gateway :{PORT}</h2><p>pool: {len(pool)} | models: {len(MODELS)}</p><table border=1 cellpadding=4>{rows}</table>"
|
||||
b = html.encode()
|
||||
self.send_response(200); self.send_header('content-type', 'text/html; charset=utf-8')
|
||||
self.send_header('content-length', str(len(b))); self.end_headers(); self.wfile.write(b)
|
||||
return
|
||||
self._json(404, {'error': 'not found'})
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != '/v1/chat/completions':
|
||||
return self._json(404, {'error': 'not found'})
|
||||
if not self._auth():
|
||||
return self._json(401, {'error': 'invalid key'})
|
||||
ln = int(self.headers.get('content-length', 0))
|
||||
try:
|
||||
req = json.loads(self.rfile.read(ln))
|
||||
except Exception:
|
||||
return self._json(400, {'error': 'bad json'})
|
||||
model = req.get('model', 'gpt-6.1-sol')
|
||||
model = model.split('/')[-1]
|
||||
if model not in MODEL_PROVIDER:
|
||||
model = 'gpt-6.1-sol'
|
||||
provider = MODEL_PROVIDER[model]
|
||||
text = flatten_content(req.get('messages', []))
|
||||
if not text.strip():
|
||||
return self._json(400, {'error': 'empty messages'})
|
||||
stream = bool(req.get('stream'))
|
||||
pool = load_pool()
|
||||
acc = pick_account(pool, provider)
|
||||
if not acc:
|
||||
return self._json(503, {'error': {'message': 'no live accounts in pool', 'type': 'pool_empty'}})
|
||||
cid = 'chatcmpl-' + msg_ulid()[4:]
|
||||
created = int(time.time())
|
||||
if stream:
|
||||
self.send_response(200)
|
||||
self.send_header('content-type', 'text/event-stream')
|
||||
self.send_header('cache-control', 'no-cache')
|
||||
self.end_headers()
|
||||
def emit(delta, finish=None):
|
||||
ch = {'delta': {'content': delta}} if delta else {'delta': {}}
|
||||
if finish: ch['finish_reason'] = finish
|
||||
chunk = {'id': cid, 'object': 'chat.completion.chunk', 'created': created,
|
||||
'model': model, 'choices': [{'index': 0, **ch}]}
|
||||
try:
|
||||
self.wfile.write(f'data: {json.dumps(chunk, ensure_ascii=False)}\n\n'.encode()); self.wfile.flush()
|
||||
except Exception: pass
|
||||
def on_delta(d): emit(d)
|
||||
full, err = send_and_wait(acc, text, provider, model, on_delta=on_delta)
|
||||
if err and not full:
|
||||
emit(f'[gateway error] {err}', 'stop')
|
||||
else:
|
||||
mark_used(acc)
|
||||
try: self.wfile.write(b'data: [DONE]\n\n'); self.wfile.flush()
|
||||
except Exception: pass
|
||||
return
|
||||
full, err = send_and_wait(acc, text, provider, model)
|
||||
if err:
|
||||
return self._json(502, {'error': {'message': err, 'type': 'upstream', 'account': acc['email']}})
|
||||
mark_used(acc)
|
||||
self._json(200, {'id': cid, 'object': 'chat.completion', 'created': created, 'model': model,
|
||||
'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': full}, 'finish_reason': 'stop'}],
|
||||
'usage': {'prompt_tokens': len(text) // 4, 'completion_tokens': len(full) // 4,
|
||||
'total_tokens': (len(text) + len(full)) // 4}})
|
||||
|
||||
if __name__ == '__main__':
|
||||
srv = ThreadingHTTPServer(('0.0.0.0', PORT), H)
|
||||
print(f'typegw on :{PORT} pool={POOL_PATH} models={len(MODELS)}', flush=True)
|
||||
srv.serve_forever()
|
||||
Reference in New Issue
Block a user