# -*- 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"
pool: {len(pool)} | models: {len(MODELS)}