feat: pc-agent bridge (minara engine + local PC tools, streaming tool calls), domain probe, tunnel keeper
This commit is contained in:
@@ -83,4 +83,41 @@ python domain_score.py 0.4 1
|
||||
## Этика
|
||||
|
||||
Код писался для собственного пула аккаунтов и тестов нативности моделей.
|
||||
Массовая регистрация нарушает ToS сервиса — используйте на свой риск.
|
||||
Массовая регистрация нарушает ToS сервиса — используйте на свой риск.
|
||||
|
||||
## Обратный реверс: их агент как движок, твой ПК как руки
|
||||
|
||||
`pc_agent.py` — OpenAI-совместимый сервер (порт 48200), который делает из Minara
|
||||
настоящего агента с доступом к твоей машине.
|
||||
|
||||
Что вскрыто:
|
||||
|
||||
```
|
||||
POST /v1/chat агентский стрим: f:{messageId} 0:"дельта" 9:{toolCall,tool_args}
|
||||
a:{result} e:{finishReason} d:{finishReason}
|
||||
GET /v1/tools 128 серверных инструментов (searchToken, polymarket*, swap …)
|
||||
GET /v1/chat/resume докрутка по offset
|
||||
POST /v1/chat/tool-call/status отчёт клиента об исполнении инструмента
|
||||
```
|
||||
|
||||
Их инструменты исполняет их сервер, свои `tools` в теле запроса игнорируются
|
||||
(модель прямо отвечает, что доступа к компьютеру нет). Поэтому движком взята их
|
||||
обычная `/v1/chat/completions` с нативным `tool_calls`, а инструменты исполняются
|
||||
локально: `pc_screenshot`, `pc_windows`, `pc_click`, `pc_type`, `pc_key`,
|
||||
`pc_exec`, `pc_read`, `pc_write`.
|
||||
|
||||
Цикл: модель → tool_calls → локальное исполнение → результат обратно модели,
|
||||
скриншот уходит картинкой base64. Всё стримится в OpenAI-формате, включая
|
||||
кадры `tool_calls` и `pc_tool_result` — клиент видит каждый шаг.
|
||||
|
||||
```bash
|
||||
python pc_agent.py --port=48200 --model=anthropic/claude-opus-5
|
||||
curl -N http://127.0.0.1:48200/v1/chat/completions -H "Authorization: Bearer $PC_AGENT_TOKEN" -d '{"model":"pc-agent","stream":true,"messages":[{"role":"user","content":"что у меня на экране?"}]}'
|
||||
```
|
||||
|
||||
`tunnel_keep.py` держит reverse-туннель `прод:48200 -> локальный агент`, чтобы
|
||||
шлюз new-api мог звать модель `pc-agent`.
|
||||
|
||||
`domain_probe.py` — бесплатная проверка домена: с `captchaToken:"x"` сервер
|
||||
отвечает `Invalid captcha` (домен жив) или `not a valid domain` (в чёрном списке),
|
||||
капча не тратится.
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Бесплатная проверка: какие домены minara ещё принимает.
|
||||
|
||||
Хитрость: с заведомо неверным captchaToken сервер отвечает
|
||||
"Invalid captcha" -> домен ПРОШЁЛ фильтр (капчу решаем отдельно)
|
||||
"not a valid domain" -> домен в чёрном списке (регистрация невозможна)
|
||||
Капча при этом не тратится: до 2captcha дело не доходит.
|
||||
|
||||
usage: python domain_probe.py [--limit=N] [--workers=8] [--pool=pool_mix.jsonl]
|
||||
out: domains_ok.jsonl / domains_dead.jsonl
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import requests
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
API = "https://api.minara.ai"
|
||||
H = {"Origin": "https://minara.ai", "Referer": "https://minara.ai/",
|
||||
"Content-Type": "application/json", "User-Agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"}
|
||||
LOCK = threading.Lock()
|
||||
PROXIES = [p.strip() for p in os.environ.get("MINARA_PROXIES", "").split(",") if p.strip()]
|
||||
_PI = [0]
|
||||
|
||||
|
||||
def next_proxy():
|
||||
if not PROXIES:
|
||||
return None
|
||||
with LOCK:
|
||||
p = PROXIES[_PI[0] % len(PROXIES)]
|
||||
_PI[0] += 1
|
||||
return {"http": p, "https": p}
|
||||
|
||||
|
||||
def probe(domain):
|
||||
try:
|
||||
r = requests.post(API + "/auth/email/code",
|
||||
json={"email": "probe1@" + domain, "captchaToken": "x"},
|
||||
headers=H, timeout=25, proxies=next_proxy())
|
||||
body = (r.text or "").lower()
|
||||
if "not a valid domain" in body:
|
||||
return domain, "dead", r.status_code
|
||||
if "invalid captcha" in body or "captcha" in body:
|
||||
return domain, "ok", r.status_code
|
||||
if r.status_code == 429:
|
||||
return domain, "ratelimit", r.status_code
|
||||
return domain, "other:" + (r.text or "")[:60], r.status_code
|
||||
except Exception as e:
|
||||
return domain, "err:" + str(e)[:40], 0
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--limit", type=int, default=0)
|
||||
ap.add_argument("--workers", type=int, default=8)
|
||||
ap.add_argument("--pool", default=os.path.join(HERE, "pool_mix.jsonl"))
|
||||
a = ap.parse_args()
|
||||
|
||||
doms = []
|
||||
with io.open(a.pool, encoding="utf8", errors="ignore") as fh:
|
||||
for l in fh:
|
||||
l = l.strip()
|
||||
if not l:
|
||||
continue
|
||||
try:
|
||||
d = json.loads(l).get("dom")
|
||||
except Exception:
|
||||
continue
|
||||
if d and d not in doms:
|
||||
doms.append(d)
|
||||
if a.limit:
|
||||
doms = doms[:a.limit]
|
||||
print("доменов на пробу:", len(doms), flush=True)
|
||||
|
||||
c = collections.Counter()
|
||||
ok, dead, other = [], [], []
|
||||
lock = threading.Lock()
|
||||
queue = list(doms)
|
||||
queue.reverse()
|
||||
|
||||
def work():
|
||||
while True:
|
||||
with lock:
|
||||
if not queue:
|
||||
return
|
||||
d = queue.pop()
|
||||
dom, verdict, code = probe(d)
|
||||
with lock:
|
||||
c[verdict.split(":")[0]] += 1
|
||||
if verdict == "ok":
|
||||
ok.append(dom)
|
||||
print("OK ", dom, flush=True)
|
||||
elif verdict == "dead":
|
||||
dead.append(dom)
|
||||
else:
|
||||
other.append((dom, verdict))
|
||||
print("??? ", dom, verdict, flush=True)
|
||||
|
||||
ths = [threading.Thread(target=work) for _ in range(a.workers)]
|
||||
for t in ths:
|
||||
t.start()
|
||||
for t in ths:
|
||||
t.join()
|
||||
|
||||
with io.open(os.path.join(HERE, "domains_ok.jsonl"), "w", encoding="utf8", newline="\n") as fh:
|
||||
for d in ok:
|
||||
fh.write(json.dumps({"dom": d}, ensure_ascii=False) + "\n")
|
||||
with io.open(os.path.join(HERE, "domains_dead.jsonl"), "w", encoding="utf8", newline="\n") as fh:
|
||||
for d in dead:
|
||||
fh.write(json.dumps({"dom": d}, ensure_ascii=False) + "\n")
|
||||
print("итог: ok=%d dead=%d other=%d" % (len(ok), len(dead), len(other)), flush=True)
|
||||
print("ok-домены:", ", ".join(ok[:40]), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+491
@@ -0,0 +1,491 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PC-агент на движке Minara: OpenAI-совместимый сервер, который реально видит твой компьютер.
|
||||
|
||||
Схема:
|
||||
клиент (curl/любой SDK) -> POST /v1/chat/completions
|
||||
-> модель Minara (/v1/chat/completions, нативный tool_calls)
|
||||
-> вызов инструмента ПК (скриншот / мышь / клавиатура / shell / файлы)
|
||||
-> результат возвращается модели, скриншот уходит картинкой (base64)
|
||||
-> цикл до MAX_STEPS, всё стримится в OpenAI-формате
|
||||
|
||||
Отличие от их агента: /v1/chat исполняет инструменты на СВОЁМ сервере (128 сервисов,
|
||||
свои tools в теле запроса игнорируются). Здесь инструменты исполняются на твоей машине.
|
||||
|
||||
usage: python pc_agent.py [--port=48200] [--engine=https://api.minara.ai] [--token-file=bank.jsonl]
|
||||
env: MINARA_TOKEN (готовый JWT) | MINARA_BANK (jsonl с токенами)
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import ctypes
|
||||
import ctypes.wintypes as wt
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import requests
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SHOTS = os.path.join(HERE, "shots")
|
||||
MAX_STEPS = int(os.environ.get("PC_AGENT_MAX_STEPS", "8"))
|
||||
ENGINE = os.environ.get("PC_AGENT_ENGINE", "https://api.minara.ai")
|
||||
MODEL = os.environ.get("PC_AGENT_MODEL", "anthropic/claude-opus-5")
|
||||
LOCK = threading.Lock()
|
||||
_TOK = {"v": None}
|
||||
TOKEN_FILE = os.environ.get("MINARA_BANK", os.path.join(HERE, "bank.jsonl"))
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
try:
|
||||
ctypes.windll.shcore.SetProcessDpiAwareness(2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ---------------------------------------------------------------- инструменты ПК
|
||||
|
||||
TOOLS = [
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_screenshot",
|
||||
"description": "Сделать скриншот экрана пользователя. Возвращает путь к файлу; изображение "
|
||||
"автоматически прикладывается к следующему сообщению, так что ты его видишь.",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"monitor": {"type": "integer", "description": "0 = все экраны"}}, "required": []}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_windows", "description": "Список открытых окон (заголовок, координаты, размер).",
|
||||
"parameters": {"type": "object", "properties": {}, "required": []}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_click", "description": "Клик мышью в экранных координатах.",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"x": {"type": "integer"}, "y": {"type": "integer"},
|
||||
"button": {"type": "string", "enum": ["left", "right", "middle"]},
|
||||
"double": {"type": "boolean"}}, "required": ["x", "y"]}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_type", "description": "Напечатать текст в активное окно (юникод, посимвольно).",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"text": {"type": "string"}}, "required": ["text"]}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_key", "description": "Нажать клавиши, например 'enter', 'ctrl+c', 'alt+tab', 'win+r'.",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"keys": {"type": "string"}}, "required": ["keys"]}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_exec", "description": "Выполнить команду в bash на машине пользователя, вернуть stdout+stderr.",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"cmd": {"type": "string"}, "timeout": {"type": "integer"}}, "required": ["cmd"]}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_read", "description": "Прочитать текстовый файл с машины пользователя.",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}}},
|
||||
{"type": "function", "function": {
|
||||
"name": "pc_write", "description": "Записать текст в файл на машине пользователя.",
|
||||
"parameters": {"type": "object", "properties": {
|
||||
"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}},
|
||||
]
|
||||
|
||||
KEYMAP = {"enter": 0x0D, "tab": 0x09, "esc": 0x1B, "space": 0x20, "backspace": 0x08, "delete": 0x2E,
|
||||
"up": 0x26, "down": 0x28, "left": 0x25, "right": 0x27, "home": 0x24, "end": 0x23,
|
||||
"f1": 0x70, "f2": 0x71, "f3": 0x72, "f4": 0x73, "f5": 0x74, "f6": 0x75}
|
||||
|
||||
|
||||
def tool_screenshot(monitor=0):
|
||||
from PIL import ImageGrab
|
||||
os.makedirs(SHOTS, exist_ok=True)
|
||||
img = ImageGrab.grab(all_screens=True)
|
||||
path = os.path.join(SHOTS, "shot_%s.png" % time.strftime("%H%M%S"))
|
||||
img.save(path)
|
||||
return {"path": path, "size": list(img.size), "image_path": path}
|
||||
|
||||
|
||||
def tool_windows():
|
||||
out = []
|
||||
EnumProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wt.HWND, wt.LPARAM)
|
||||
|
||||
def cb(hwnd, _):
|
||||
if not user32.IsWindowVisible(hwnd):
|
||||
return True
|
||||
n = user32.GetWindowTextLengthW(hwnd)
|
||||
if n == 0:
|
||||
return True
|
||||
buf = ctypes.create_unicode_buffer(n + 1)
|
||||
user32.GetWindowTextW(hwnd, buf, n + 1)
|
||||
r = wt.RECT()
|
||||
user32.GetWindowRect(hwnd, ctypes.byref(r))
|
||||
out.append({"title": buf.value[:120], "x": r.left, "y": r.top,
|
||||
"w": r.right - r.left, "h": r.bottom - r.top})
|
||||
return True
|
||||
|
||||
user32.EnumWindows(EnumProc(cb), 0)
|
||||
return {"count": len(out), "windows": out[:40]}
|
||||
|
||||
|
||||
def tool_click(x, y, button="left", double=False):
|
||||
user32.SetCursorPos(int(x), int(y))
|
||||
time.sleep(0.08)
|
||||
down = {"left": 0x0002, "right": 0x0008, "middle": 0x0020}[button]
|
||||
up = {"left": 0x0004, "right": 0x0010, "middle": 0x0040}[button]
|
||||
user32.mouse_event(down, 0, 0, 0, 0)
|
||||
user32.mouse_event(up, 0, 0, 0, 0)
|
||||
if double:
|
||||
time.sleep(0.05)
|
||||
user32.mouse_event(down, 0, 0, 0, 0)
|
||||
user32.mouse_event(up, 0, 0, 0, 0)
|
||||
return {"ok": True, "x": x, "y": y, "button": button}
|
||||
|
||||
|
||||
def tool_type(text):
|
||||
# KEYEVENTF_UNICODE: печатает юникод в обход раскладки
|
||||
for ch in str(text):
|
||||
code = ord(ch)
|
||||
user32.keybd_event(0, code, 0x0004, 0)
|
||||
user32.keybd_event(0, code, 0x0004 | 0x0002, 0)
|
||||
time.sleep(0.002)
|
||||
return {"ok": True, "chars": len(str(text))}
|
||||
|
||||
|
||||
def tool_key(keys):
|
||||
parts = [p.strip().lower() for p in str(keys).split("+")]
|
||||
mods = {"ctrl": 0x11, "alt": 0x12, "shift": 0x10, "win": 0x5B}
|
||||
codes = [mods[p] for p in parts[:-1] if p in mods]
|
||||
last = parts[-1]
|
||||
vk = KEYMAP.get(last) or (ord(last.upper()) if len(last) == 1 else None)
|
||||
if vk is None:
|
||||
return {"error": "unknown key " + last}
|
||||
for c in codes:
|
||||
user32.keybd_event(c, 0, 0, 0)
|
||||
user32.keybd_event(vk, 0, 0, 0)
|
||||
user32.keybd_event(vk, 0, 0x0002, 0)
|
||||
for c in reversed(codes):
|
||||
user32.keybd_event(c, 0, 0x0002, 0)
|
||||
return {"ok": True, "keys": keys}
|
||||
|
||||
|
||||
def tool_exec(cmd, timeout=60):
|
||||
try:
|
||||
p = subprocess.run(["bash", "-lc", cmd], capture_output=True, text=True,
|
||||
timeout=int(timeout), errors="replace")
|
||||
return {"exit": p.returncode, "stdout": p.stdout[-4000:], "stderr": p.stderr[-2000:]}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"error": "timeout"}
|
||||
except Exception as e:
|
||||
return {"error": str(e)[:200]}
|
||||
|
||||
|
||||
def tool_read(path, limit=200000):
|
||||
try:
|
||||
with io.open(path, encoding="utf8", errors="replace") as fh:
|
||||
return {"path": path, "content": fh.read(int(limit))}
|
||||
except Exception as e:
|
||||
return {"error": str(e)[:200]}
|
||||
|
||||
|
||||
def tool_write(path, content):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
with io.open(path, "w", encoding="utf8", newline="\n") as fh:
|
||||
fh.write(content)
|
||||
return {"ok": True, "path": path, "bytes": len(content)}
|
||||
except Exception as e:
|
||||
return {"error": str(e)[:200]}
|
||||
|
||||
|
||||
EXECUTORS = {"pc_screenshot": tool_screenshot, "pc_windows": tool_windows, "pc_click": tool_click,
|
||||
"pc_type": tool_type, "pc_key": tool_key, "pc_exec": tool_exec,
|
||||
"pc_read": tool_read, "pc_write": tool_write}
|
||||
|
||||
|
||||
def run_tool(name, args):
|
||||
fn = EXECUTORS.get(name)
|
||||
if not fn:
|
||||
return {"error": "unknown tool " + name}
|
||||
try:
|
||||
return fn(**args)
|
||||
except Exception as e:
|
||||
return {"error": type(e).__name__ + ": " + str(e)[:200]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- движок Minara
|
||||
|
||||
def token():
|
||||
with LOCK:
|
||||
if _TOK["v"]:
|
||||
return _TOK["v"]
|
||||
t = os.environ.get("MINARA_TOKEN")
|
||||
if not t and os.path.exists(TOKEN_FILE):
|
||||
last = None
|
||||
with io.open(TOKEN_FILE, encoding="utf8", errors="ignore") as fh:
|
||||
for l in fh:
|
||||
l = l.strip()
|
||||
if not l:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(l)
|
||||
except Exception:
|
||||
continue
|
||||
if r.get("token"):
|
||||
last = r["token"]
|
||||
t = last
|
||||
if not t:
|
||||
raise RuntimeError("нет токена: задай MINARA_TOKEN или положи bank.jsonl")
|
||||
with LOCK:
|
||||
_TOK["v"] = t
|
||||
return t
|
||||
|
||||
|
||||
HDR = {"Origin": "https://minara.ai", "Referer": "https://minara.ai/app/ide"}
|
||||
|
||||
|
||||
def call_engine(messages, stream=False, tools=True):
|
||||
body = {"model": MODEL, "messages": messages, "max_tokens": 3000}
|
||||
if tools:
|
||||
body["tools"] = TOOLS
|
||||
body["tool_choice"] = "auto"
|
||||
h = dict(HDR, Authorization="Bearer " + token(), **{"Content-Type": "application/json"})
|
||||
if stream:
|
||||
h["Accept"] = "text/event-stream"
|
||||
r = requests.post(ENGINE + "/v1/chat/completions", headers=h, json=body,
|
||||
stream=stream, timeout=180)
|
||||
if r.status_code in (401, 402, 403):
|
||||
with LOCK:
|
||||
_TOK["v"] = None
|
||||
return r
|
||||
|
||||
|
||||
def parse_json_once(resp):
|
||||
"""Миnara отвечает обычным JSON, даже когда просишь stream=true — разбираем и его."""
|
||||
try:
|
||||
j = resp.json()
|
||||
except Exception:
|
||||
yield "text", resp.text[:300]
|
||||
yield "finish", "error"
|
||||
return
|
||||
ch = (j.get("choices") or [{}])[0]
|
||||
msg = ch.get("message") or {}
|
||||
if msg.get("content"):
|
||||
yield "text", msg["content"]
|
||||
calls = []
|
||||
for tc in (msg.get("tool_calls") or []):
|
||||
fn = tc.get("function") or {}
|
||||
calls.append({"id": tc.get("id") or "call_" + uuid.uuid4().hex[:8],
|
||||
"name": fn.get("name", ""), "args": fn.get("arguments") or "{}"})
|
||||
if calls:
|
||||
yield "tool", calls
|
||||
yield "finish", ch.get("finish_reason") or ("tool_calls" if calls else "stop")
|
||||
|
||||
|
||||
def parse_sse(resp):
|
||||
"""Отдаёт (kind, payload): 'text' | 'tool' | 'finish'."""
|
||||
ctype = (resp.headers.get("content-type") or "").lower()
|
||||
if "event-stream" not in ctype:
|
||||
for ev in parse_json_once(resp):
|
||||
yield ev
|
||||
return
|
||||
calls = {}
|
||||
for line in resp.iter_lines(decode_unicode=True):
|
||||
if not line or not line.startswith("data:"):
|
||||
continue
|
||||
data = line[5:].strip()
|
||||
if data == "[DONE]":
|
||||
break
|
||||
try:
|
||||
j = json.loads(data)
|
||||
except Exception:
|
||||
continue
|
||||
ch = (j.get("choices") or [{}])[0]
|
||||
delta = ch.get("delta") or {}
|
||||
if delta.get("content"):
|
||||
yield "text", delta["content"]
|
||||
for tc in (delta.get("tool_calls") or []):
|
||||
idx = tc.get("index", 0)
|
||||
slot = calls.setdefault(idx, {"id": tc.get("id") or "call_" + uuid.uuid4().hex[:8],
|
||||
"name": "", "args": ""})
|
||||
fn = tc.get("function") or {}
|
||||
if fn.get("name"):
|
||||
slot["name"] += fn["name"]
|
||||
if fn.get("arguments"):
|
||||
slot["args"] += fn["arguments"]
|
||||
if ch.get("finish_reason"):
|
||||
yield "finish", ch["finish_reason"]
|
||||
if calls:
|
||||
yield "tool", [calls[k] for k in sorted(calls)]
|
||||
|
||||
|
||||
def agent_stream(messages):
|
||||
"""Гоняет цикл модель↔инструменты, отдаёт события ('text'|'tool_call'|'tool_result'|'finish')."""
|
||||
msgs = list(messages)
|
||||
for step in range(MAX_STEPS):
|
||||
r = call_engine(msgs, stream=True)
|
||||
if r.status_code != 200:
|
||||
yield "text", "[engine %d] %s" % (r.status_code, r.text[:200])
|
||||
yield "finish", "error"
|
||||
return
|
||||
pending_tools = []
|
||||
finish = None
|
||||
for kind, payload in parse_sse(r):
|
||||
if kind == "text":
|
||||
yield "text", payload
|
||||
elif kind == "tool":
|
||||
pending_tools = payload
|
||||
elif kind == "finish":
|
||||
finish = payload
|
||||
if not pending_tools:
|
||||
yield "finish", finish or "stop"
|
||||
return
|
||||
msgs.append({"role": "assistant", "content": None,
|
||||
"tool_calls": [{"id": t["id"], "type": "function",
|
||||
"function": {"name": t["name"], "arguments": t["args"] or "{}"}}
|
||||
for t in pending_tools]})
|
||||
shot = None
|
||||
for t in pending_tools:
|
||||
try:
|
||||
args = json.loads(t["args"] or "{}")
|
||||
except Exception:
|
||||
args = {}
|
||||
yield "tool_call", {"id": t["id"], "name": t["name"], "args": args}
|
||||
res = run_tool(t["name"], args)
|
||||
if res.get("image_path"):
|
||||
shot = res.pop("image_path")
|
||||
yield "tool_result", {"id": t["id"], "name": t["name"], "result": res}
|
||||
msgs.append({"role": "tool", "tool_call_id": t["id"],
|
||||
"content": json.dumps(res, ensure_ascii=False)[:6000]})
|
||||
if shot:
|
||||
try:
|
||||
with open(shot, "rb") as fh:
|
||||
b64 = base64.b64encode(fh.read()).decode()
|
||||
msgs.append({"role": "user", "content": [
|
||||
{"type": "text", "text": "Скриншот экрана, который ты только что снял:"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}}]})
|
||||
except Exception:
|
||||
pass
|
||||
yield "finish", "max_steps"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTTP API
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
def _json(self, code, obj):
|
||||
raw = 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(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _auth_ok(self):
|
||||
want = os.environ.get("PC_AGENT_TOKEN", "").strip()
|
||||
if not want:
|
||||
return True
|
||||
got = (self.headers.get("Authorization") or "").replace("Bearer ", "").strip()
|
||||
return got == want
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/health"):
|
||||
return self._json(200, {"ok": True, "model": MODEL, "engine": ENGINE,
|
||||
"tools": [t["function"]["name"] for t in TOOLS]})
|
||||
if self.path.startswith("/v1/models"):
|
||||
return self._json(200, {"object": "list", "data": [
|
||||
{"id": "pc-agent", "object": "model", "created": 0, "owned_by": "eni"}]})
|
||||
self._json(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
if not self.path.startswith("/v1/chat/completions"):
|
||||
return self._json(404, {"error": "not found"})
|
||||
if not self._auth_ok():
|
||||
return self._json(401, {"error": {"message": "bad token", "type": "auth"}})
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
try:
|
||||
req = json.loads(self.rfile.read(n) or b"{}")
|
||||
except Exception:
|
||||
return self._json(400, {"error": "bad json"})
|
||||
messages = req.get("messages") or []
|
||||
stream = bool(req.get("stream"))
|
||||
cid = "chatcmpl-" + uuid.uuid4().hex[:10]
|
||||
ts = int(time.time())
|
||||
model = req.get("model") or "pc-agent"
|
||||
|
||||
def chunk(delta, finish=None):
|
||||
return {"id": cid, "object": "chat.completion.chunk", "created": ts, "model": model,
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
|
||||
|
||||
if not stream:
|
||||
parts, tools_used = [], []
|
||||
for kind, payload in agent_stream(messages):
|
||||
if kind == "text":
|
||||
parts.append(payload)
|
||||
elif kind == "tool_call":
|
||||
tools_used.append({"id": payload["id"], "type": "function",
|
||||
"function": {"name": payload["name"],
|
||||
"arguments": json.dumps(payload["args"], ensure_ascii=False)}})
|
||||
elif kind == "tool_result":
|
||||
tools_used[-1]["result"] = payload["result"]
|
||||
msg = {"role": "assistant", "content": "".join(parts)}
|
||||
if tools_used:
|
||||
msg["tool_calls"] = [{"id": t["id"], "type": "function", "function": t["function"]}
|
||||
for t in tools_used]
|
||||
msg["pc_tool_results"] = [{"id": t["id"], "name": t["function"]["name"],
|
||||
"result": t.get("result")} for t in tools_used]
|
||||
return self._json(200, {"id": cid, "object": "chat.completion", "created": ts, "model": model,
|
||||
"choices": [{"index": 0, "message": msg, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}})
|
||||
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.send_header("Connection", "keep-alive")
|
||||
self.end_headers()
|
||||
|
||||
def emit(obj):
|
||||
self.wfile.write(("data: " + json.dumps(obj, ensure_ascii=False) + "\n\n").encode())
|
||||
self.wfile.flush()
|
||||
|
||||
emit(chunk({"role": "assistant", "content": ""}))
|
||||
tidx = [0]
|
||||
try:
|
||||
for kind, payload in agent_stream(messages):
|
||||
if kind == "text":
|
||||
emit(chunk({"content": payload}))
|
||||
elif kind == "tool_call":
|
||||
emit(chunk({"tool_calls": [{
|
||||
"index": tidx[0], "id": payload["id"], "type": "function",
|
||||
"function": {"name": payload["name"],
|
||||
"arguments": json.dumps(payload["args"], ensure_ascii=False)}}]}))
|
||||
tidx[0] += 1
|
||||
elif kind == "tool_result":
|
||||
emit(chunk({"pc_tool_result": payload}))
|
||||
elif kind == "finish":
|
||||
emit(chunk({}, payload))
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
except Exception as e:
|
||||
try:
|
||||
emit(chunk({"content": "\n[ошибка агента] " + str(e)[:200]}))
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
global ENGINE, MODEL
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=int(os.environ.get("PC_AGENT_PORT", "48200")))
|
||||
ap.add_argument("--engine", default=ENGINE)
|
||||
ap.add_argument("--model", default=MODEL)
|
||||
a = ap.parse_args()
|
||||
ENGINE, MODEL = a.engine, a.model
|
||||
os.makedirs(SHOTS, exist_ok=True)
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
|
||||
print("pc-agent on http://127.0.0.1:%d engine=%s model=%s tools=%d" %
|
||||
(a.port, ENGINE, MODEL, len(TOOLS)), flush=True)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Поднимает detached SSH-socks туннели (переживают выход из bash) и прогоняет domain_probe.
|
||||
|
||||
Windows-специфика: ssh -D из background-bash умирает вместе с оболочкой,
|
||||
поэтому запускаем через subprocess с DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
HOSTS = [("2.152.87.13", 1101), ("31.77.251.109", 1102), ("2.27.98.2", 1103),
|
||||
("2.27.98.7", 1104), ("31.77.251.116", 1105)]
|
||||
DETACH = 0x00000008 | 0x00000200
|
||||
|
||||
|
||||
def port_open(p):
|
||||
s = socket.socket()
|
||||
try:
|
||||
return s.connect_ex(("127.0.0.1", p)) == 0
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def main():
|
||||
started = []
|
||||
for host, port in HOSTS:
|
||||
if port_open(port):
|
||||
print("tunnel %s:%d уже жив" % (host, port))
|
||||
started.append(port)
|
||||
continue
|
||||
p = subprocess.Popen(["ssh", "-N", "-D", str(port), "-o", "BatchMode=yes",
|
||||
"-o", "ExitOnForwardFailure=yes", "-o", "StrictHostKeyChecking=no",
|
||||
"-o", "ServerAliveInterval=30", "root@" + host],
|
||||
creationflags=DETACH, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
for _ in range(12):
|
||||
time.sleep(1)
|
||||
if port_open(port):
|
||||
started.append(port)
|
||||
print("tunnel %s:%d up (pid %d)" % (host, port, p.pid))
|
||||
break
|
||||
else:
|
||||
print("tunnel %s:%d FAIL" % (host, port))
|
||||
if not started:
|
||||
print("нет туннелей")
|
||||
return 1
|
||||
proxies = ",".join("socks5h://127.0.0.1:%d" % p for p in started)
|
||||
env = dict(os.environ)
|
||||
env.update({"MINARA_PROXIES": proxies, "PYTHONIOENCODING": "utf-8"})
|
||||
env.pop("PYTHONPATH", None)
|
||||
cmd = [sys.executable, "-u", os.path.join(HERE, "domain_probe.py"),
|
||||
"--pool=pool_mix.jsonl", "--workers=%d" % len(started)]
|
||||
print("probe:", " ".join(cmd))
|
||||
subprocess.call(cmd, env=env, cwd=HERE)
|
||||
print("tunnels:", started)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Держит reverse-туннель прод:48200 -> локальный pc_agent.
|
||||
|
||||
Зачем: ssh -R, запущенный из background-bash, умирает вместе с оболочкой,
|
||||
а pc_agent должен быть доступен new-api постоянно.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ARGS = ["ssh", "-N", "-R", "48200:127.0.0.1:48200", "-o", "BatchMode=yes",
|
||||
"-o", "ExitOnForwardFailure=yes", "-o", "StrictHostKeyChecking=no",
|
||||
"-o", "ServerAliveInterval=20", "-o", "ServerAliveCountMax=3",
|
||||
"root@2.27.98.196"]
|
||||
DETACH = 0x00000008 | 0x00000200
|
||||
|
||||
|
||||
def main():
|
||||
child = None
|
||||
while True:
|
||||
if child is None or child.poll() is not None:
|
||||
if child is not None:
|
||||
print("tunnel died rc=%s, restart" % child.returncode, flush=True)
|
||||
child = subprocess.Popen(ARGS, creationflags=DETACH,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
print("tunnel up pid=%d" % child.pid, flush=True)
|
||||
time.sleep(15)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(0)
|
||||
Reference in New Issue
Block a user