Files

491 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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()