484 lines
20 KiB
Python
484 lines
20 KiB
Python
"""qw_agent — full local tool-use harness (OpenAI-compatible backend, real PC access).
|
|
|
|
Why: QwenWork's desktop CLI (resources/agent-sdk/components/qwencode/*/qwen-code, ACP mode) does
|
|
have native tools, but its provider is pinned to DashScope inside the build, so it cannot be pointed
|
|
at another endpoint. This harness gives the same capability with any OpenAI-compatible backend.
|
|
|
|
Modes:
|
|
run one-shot task: python qw_agent.py run -p "count lines in ..."
|
|
chat interactive REPL: python qw_agent.py chat
|
|
serve OpenAI-like server: python qw_agent.py serve --port 48970
|
|
tools print tool names
|
|
|
|
Backends:
|
|
--provider qw qwenwork pool shim (default http://127.0.0.1:48981/v1, qw-flash)
|
|
--provider router local dashscope rotator (http://127.0.0.1:16432/v1)
|
|
--provider any --base ... --model ... --key ...
|
|
|
|
Tools: fs_read, fs_write, fs_edit, fs_list, fs_glob, fs_grep, shell, http_get, todo_write, task_done.
|
|
Safety: destructive shell commands ask for confirmation unless --yolo; --root confines file tools.
|
|
"""
|
|
import argparse
|
|
import fnmatch
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
TOOLS = [
|
|
{"type": "function", "function": {
|
|
"name": "fs_read",
|
|
"description": "Read a UTF-8 text file with line numbers. Use offset/limit for big files.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string"},
|
|
"offset": {"type": "integer", "description": "1-based first line"},
|
|
"limit": {"type": "integer", "description": "max lines, default 400"}},
|
|
"required": ["path"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "fs_write",
|
|
"description": "Write or overwrite a text file. Creates parent dirs.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string"}, "content": {"type": "string"}},
|
|
"required": ["path", "content"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "fs_edit",
|
|
"description": "Replace an exact substring inside a file (first match unless replace_all).",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"},
|
|
"replace_all": {"type": "boolean"}},
|
|
"required": ["path", "old", "new"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "fs_list",
|
|
"description": "List a directory: names, dir flag, size.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string"}, "limit": {"type": "integer"}},
|
|
"required": ["path"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "fs_glob",
|
|
"description": "Find files by glob under a directory, e.g. **/*.py or *.md.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string"}, "pattern": {"type": "string"}, "limit": {"type": "integer"}},
|
|
"required": ["path", "pattern"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "fs_grep",
|
|
"description": "Regex search inside files; returns file, line, text.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string"}, "pattern": {"type": "string"},
|
|
"glob": {"type": "string"}, "max_hits": {"type": "integer"}},
|
|
"required": ["path", "pattern"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "shell",
|
|
"description": "Run a shell command on this Windows host (git-bash). Returns exit/stdout/stderr.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"command": {"type": "string"}, "cwd": {"type": "string"}, "timeout": {"type": "integer"}},
|
|
"required": ["command"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "http_get",
|
|
"description": "Fetch a URL, return status and the first 20k characters.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"url": {"type": "string"}, "max_chars": {"type": "integer"}},
|
|
"required": ["url"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "todo_write",
|
|
"description": "Store or replace the task plan as a checklist (kept by the harness).",
|
|
"parameters": {"type": "object", "properties": {
|
|
"items": {"type": "array", "items": {"type": "string"}}},
|
|
"required": ["items"]}}},
|
|
{"type": "function", "function": {
|
|
"name": "task_done",
|
|
"description": "Mark the task finished and return the final answer.",
|
|
"parameters": {"type": "object", "properties": {"answer": {"type": "string"}},
|
|
"required": ["answer"]}}},
|
|
]
|
|
|
|
DANGER = re.compile(r"(\brm\s+-rf\b|\bmkfs\b|diskpart|\bshutdown\b|\breg\s+delete\b|"
|
|
r"\bdel\s+/[sfq]\b|\brd\s+/s\b|remove-item.*-recurse)", re.I)
|
|
SKIP_DIRS = {".git", "__pycache__", "node_modules", ".venv", "venv", ".idea", ".mypy_cache", "dist", "build"}
|
|
|
|
SYSTEM = """You are qw_agent, a local agent with full access to this Windows machine (git-bash shell).
|
|
Rules:
|
|
- Act, don't ask. Inspect real state with tools instead of guessing.
|
|
- Paths use forward slashes: C:/Users/<user>/...
|
|
- Prefer fs_read / fs_grep / fs_glob over shell for reading and searching; use shell for builds, tests, git, network.
|
|
- After edits, verify by reading the changed region or running the check.
|
|
- Never paste huge files back, summarise; report only what you actually observed (counts, exit codes, HTTP statuses).
|
|
- When finished, call task_done with the final answer."""
|
|
|
|
|
|
class State:
|
|
def __init__(self, root=None, yolo=False, confirm=None):
|
|
self.root = os.path.abspath(root).replace("\\", "/") if root else None
|
|
self.yolo = yolo
|
|
self.confirm = confirm or (lambda prompt: True)
|
|
self.todos = []
|
|
self.answer = None
|
|
self.trace = []
|
|
|
|
def guard(self, path):
|
|
p = os.path.abspath(path).replace("\\", "/")
|
|
if self.root and not p.lower().startswith(self.root.lower()):
|
|
raise PermissionError("path outside --root: %s" % p)
|
|
return p
|
|
|
|
|
|
def _numbered(text, offset):
|
|
return "\n".join("%d|%s" % (i, line) for i, line in enumerate(text.splitlines(), offset))
|
|
|
|
|
|
def t_fs_read(st, path, offset=1, limit=400):
|
|
p = st.guard(path)
|
|
with open(p, encoding="utf-8", errors="replace") as f:
|
|
lines = f.readlines()
|
|
chunk = "".join(lines[offset - 1: offset - 1 + limit])
|
|
return {"path": p, "total_lines": len(lines), "offset": offset,
|
|
"content": _numbered(chunk, offset)[:60000]}
|
|
|
|
|
|
def t_fs_write(st, path, content):
|
|
p = st.guard(path)
|
|
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
with open(p, "w", encoding="utf-8", newline="\n") as f:
|
|
f.write(content)
|
|
return {"path": p, "bytes": len(content.encode())}
|
|
|
|
|
|
def t_fs_edit(st, path, old, new, replace_all=False):
|
|
p = st.guard(path)
|
|
with open(p, encoding="utf-8") as f:
|
|
src = f.read()
|
|
n = src.count(old)
|
|
if n == 0:
|
|
return {"error": "old string not found", "path": p}
|
|
src = src.replace(old, new) if replace_all else src.replace(old, new, 1)
|
|
with open(p, "w", encoding="utf-8", newline="\n") as f:
|
|
f.write(src)
|
|
return {"path": p, "occurrences": n, "replaced": n if replace_all else 1, "bytes": len(src.encode())}
|
|
|
|
|
|
def t_fs_list(st, path, limit=300):
|
|
p = st.guard(path)
|
|
out = []
|
|
for name in sorted(os.listdir(p))[:limit]:
|
|
fp = os.path.join(p, name)
|
|
try:
|
|
out.append({"name": name, "dir": os.path.isdir(fp), "size": os.path.getsize(fp)})
|
|
except OSError:
|
|
out.append({"name": name, "dir": os.path.isdir(fp)})
|
|
return {"path": p, "entries": out}
|
|
|
|
|
|
def t_fs_glob(st, path, pattern, limit=200):
|
|
p = st.guard(path)
|
|
hits = []
|
|
for root, dirs, files in os.walk(p):
|
|
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
|
for fn in files:
|
|
full = os.path.join(root, fn).replace("\\", "/")
|
|
if fnmatch.fnmatch(full, pattern) or fnmatch.fnmatch(fn, pattern):
|
|
hits.append(full)
|
|
if len(hits) >= limit:
|
|
return {"hits": hits, "truncated": True}
|
|
return {"hits": hits, "truncated": False}
|
|
|
|
|
|
def t_fs_grep(st, path, pattern, glob=None, max_hits=40):
|
|
rx = re.compile(pattern)
|
|
hits = []
|
|
base = st.guard(path)
|
|
for root, dirs, files in os.walk(base):
|
|
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
|
for fn in files:
|
|
if glob and not fnmatch.fnmatch(fn, glob):
|
|
continue
|
|
fp = os.path.join(root, fn)
|
|
try:
|
|
if os.path.getsize(fp) > 3_000_000:
|
|
continue
|
|
with open(fp, encoding="utf-8", errors="replace") as f:
|
|
for i, line in enumerate(f, 1):
|
|
if rx.search(line):
|
|
hits.append({"file": fp.replace("\\", "/"), "line": i, "text": line.rstrip()[:300]})
|
|
if len(hits) >= max_hits:
|
|
return {"hits": hits, "truncated": True}
|
|
except OSError:
|
|
continue
|
|
return {"hits": hits, "truncated": False}
|
|
|
|
|
|
def t_shell(st, command, cwd=None, timeout=180):
|
|
if DANGER.search(command) and not st.yolo:
|
|
if not st.confirm("dangerous command, run? %s" % command):
|
|
return {"exit": -1, "stdout": "", "stderr": "blocked by user"}
|
|
if cwd:
|
|
cwd = st.guard(cwd)
|
|
try:
|
|
p = subprocess.run(command, shell=True, cwd=cwd, capture_output=True, text=True,
|
|
timeout=timeout, encoding="utf-8", errors="replace")
|
|
return {"exit": p.returncode, "stdout": (p.stdout or "")[-20000:], "stderr": (p.stderr or "")[-4000:]}
|
|
except subprocess.TimeoutExpired:
|
|
return {"exit": -1, "stdout": "", "stderr": "timeout after %ss" % timeout}
|
|
|
|
|
|
def t_http_get(st, url, max_chars=20000):
|
|
req = urllib.request.Request(url, headers={"User-Agent": "qw-agent/2.0"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=40) as r:
|
|
return {"status": r.status, "content_type": r.headers.get("content-type"),
|
|
"body": r.read().decode("utf-8", "replace")[:max_chars]}
|
|
except urllib.error.HTTPError as e:
|
|
return {"status": e.code, "body": e.read().decode("utf-8", "replace")[:2000]}
|
|
except Exception as e:
|
|
return {"error": "%s: %s" % (type(e).__name__, e)}
|
|
|
|
|
|
def t_todo_write(st, items):
|
|
st.todos = list(items)
|
|
return {"todos": st.todos}
|
|
|
|
|
|
def t_task_done(st, answer):
|
|
st.answer = answer
|
|
return {"ok": True}
|
|
|
|
|
|
DISPATCH = {
|
|
"fs_read": t_fs_read, "fs_write": t_fs_write, "fs_edit": t_fs_edit, "fs_list": t_fs_list,
|
|
"fs_glob": t_fs_glob, "fs_grep": t_fs_grep, "shell": t_shell, "http_get": t_http_get,
|
|
"todo_write": t_todo_write, "task_done": t_task_done,
|
|
}
|
|
|
|
|
|
def call_tool(st, name, args):
|
|
fn = DISPATCH.get(name)
|
|
if not fn:
|
|
return {"error": "unknown tool %s" % name}
|
|
try:
|
|
return fn(st, **args)
|
|
except Exception as e:
|
|
return {"error": "%s: %s" % (type(e).__name__, e)}
|
|
|
|
|
|
class Backend:
|
|
def __init__(self, base, model, key="sk-local", timeout=240):
|
|
self.base = (base or "").rstrip("/")
|
|
self.model = model
|
|
self.key = key
|
|
self.timeout = timeout
|
|
|
|
def chat(self, messages, tools=True, temperature=0):
|
|
body = {"model": self.model, "messages": messages, "temperature": temperature}
|
|
if tools:
|
|
body["tools"] = TOOLS
|
|
body["tool_choice"] = "auto"
|
|
req = urllib.request.Request(self.base + "/chat/completions",
|
|
data=json.dumps(body).encode(),
|
|
headers={"Content-Type": "application/json",
|
|
"Authorization": "Bearer " + self.key})
|
|
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
return json.loads(r.read().decode())
|
|
|
|
|
|
def trim(messages, keep_tail=14, cap=60000):
|
|
for m in messages:
|
|
c = m.get("content")
|
|
if m.get("role") == "tool" and isinstance(c, str) and len(c) > cap:
|
|
m["content"] = c[:cap] + "\n...[trimmed]"
|
|
if len(messages) <= keep_tail + 1:
|
|
return messages
|
|
return [messages[0]] + messages[-keep_tail:]
|
|
|
|
|
|
def run_task(be, prompt, st, max_turns=20, verbose=True, system=SYSTEM, history=None):
|
|
messages = [{"role": "system", "content": system}]
|
|
if history:
|
|
messages.extend(history[-20:])
|
|
messages.append({"role": "user", "content": prompt})
|
|
t0 = time.time()
|
|
for turn in range(max_turns):
|
|
try:
|
|
resp = be.chat(trim(messages))
|
|
except urllib.error.HTTPError as e:
|
|
return {"answer": "[http %s] %s" % (e.code, e.read().decode("utf-8", "replace")[:400]),
|
|
"turns": turn, "trace": st.trace, "error": True}
|
|
except Exception as e:
|
|
return {"answer": "[%s] %s" % (type(e).__name__, e), "turns": turn, "trace": st.trace, "error": True}
|
|
msg = ((resp.get("choices") or [{}])[0].get("message") or {})
|
|
calls = msg.get("tool_calls") or []
|
|
text = (msg.get("content") or "").strip()
|
|
if verbose and text:
|
|
print("\n[assistant] " + text[:2000], flush=True)
|
|
am = {"role": "assistant", "content": text}
|
|
if calls:
|
|
am["tool_calls"] = calls
|
|
messages.append(am)
|
|
if not calls:
|
|
return {"answer": st.answer or text, "turns": turn + 1, "trace": st.trace,
|
|
"seconds": round(time.time() - t0, 1)}
|
|
for c in calls:
|
|
name = c["function"]["name"]
|
|
try:
|
|
args = json.loads(c["function"].get("arguments") or "{}")
|
|
except Exception:
|
|
args = {}
|
|
res = call_tool(st, name, args)
|
|
st.trace.append({"tool": name, "args": {k: str(v)[:120] for k, v in args.items()},
|
|
"ok": "error" not in res})
|
|
if verbose:
|
|
err = "" if "error" not in res else " ERR"
|
|
print("[tool] %s %s%s" % (name, json.dumps(args, ensure_ascii=False)[:160], err), flush=True)
|
|
messages.append({"role": "tool", "tool_call_id": c.get("id") or name,
|
|
"content": json.dumps(res, ensure_ascii=False)[:40000]})
|
|
if name == "task_done":
|
|
return {"answer": st.answer, "turns": turn + 1, "trace": st.trace,
|
|
"seconds": round(time.time() - t0, 1)}
|
|
return {"answer": "(max turns reached)", "turns": max_turns, "trace": st.trace}
|
|
|
|
|
|
class ServeHandler(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
backend = None
|
|
yolo = True
|
|
|
|
def log_message(self, format, *args):
|
|
sys.stderr.write("[serve] " + (format % args) + "\n")
|
|
|
|
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 _be(self):
|
|
be = type(self).backend
|
|
assert be is not None, "backend not configured"
|
|
return be
|
|
|
|
def do_GET(self):
|
|
if self.path.startswith("/healthz"):
|
|
return self._json(200, {"ok": True, "model": self._be().model, "tools": len(TOOLS)})
|
|
if self.path.startswith("/v1/models"):
|
|
return self._json(200, {"object": "list", "data": [
|
|
{"id": self._be().model + "-agent", "object": "model", "owned_by": "qw_agent"}]})
|
|
return 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"})
|
|
ln = int(self.headers.get("Content-Length") or 0)
|
|
try:
|
|
req = json.loads(self.rfile.read(ln) or b"{}")
|
|
except Exception:
|
|
return self._json(400, {"error": {"message": "bad json"}})
|
|
msgs = req.get("messages") or []
|
|
sys_msg = next((m.get("content") for m in msgs if m.get("role") == "system"), None) or SYSTEM
|
|
user = "\n\n".join((m.get("content") or "") for m in msgs if m.get("role") == "user").strip()
|
|
if not user:
|
|
return self._json(400, {"error": {"message": "empty prompt"}})
|
|
st = State(yolo=self.yolo)
|
|
be = self._be()
|
|
if req.get("model"):
|
|
be.model = req["model"]
|
|
r = run_task(be, user, st, max_turns=int(req.get("max_turns") or 20), verbose=False, system=sys_msg)
|
|
return self._json(200, {
|
|
"id": "chatcmpl-" + uuid.uuid4().hex[:24], "object": "chat.completion",
|
|
"created": int(time.time()), "model": be.model,
|
|
"choices": [{"index": 0, "message": {"role": "assistant", "content": r["answer"]},
|
|
"finish_reason": "stop"}],
|
|
"usage": {"prompt_tokens": len(user) // 4, "completion_tokens": len(r["answer"]) // 4,
|
|
"total_tokens": (len(user) + len(r["answer"])) // 4},
|
|
"x_qw_tools": [t["tool"] for t in r["trace"]],
|
|
})
|
|
|
|
|
|
def build_backend(a):
|
|
if a.provider == "qw":
|
|
return Backend(a.base or "http://127.0.0.1:48981/v1", a.model or "qw-flash", a.key or "sk-local")
|
|
if a.provider == "router":
|
|
return Backend(a.base or "http://127.0.0.1:16432/v1",
|
|
a.model or "deepseek-v4.1-flash-1017", a.key or "sk-local")
|
|
if not a.base:
|
|
raise SystemExit("--base required with --provider any")
|
|
return Backend(a.base, a.model or "gpt-4o", a.key or "sk-local")
|
|
|
|
|
|
def confirm(prompt):
|
|
try:
|
|
return input(prompt + " [y/N] ").strip().lower().startswith("y")
|
|
except EOFError:
|
|
return False
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="qw_agent — local tool-use harness")
|
|
ap.add_argument("mode", nargs="?", default="run", choices=["run", "chat", "serve", "tools"])
|
|
ap.add_argument("--provider", default=os.environ.get("QW_AGENT_PROVIDER", "qw"),
|
|
choices=["qw", "router", "any"])
|
|
ap.add_argument("--base", default=os.environ.get("QW_AGENT_BASE"))
|
|
ap.add_argument("--model", default=os.environ.get("QW_AGENT_MODEL"))
|
|
ap.add_argument("--key", default=os.environ.get("QW_AGENT_KEY"))
|
|
ap.add_argument("-p", "--prompt")
|
|
ap.add_argument("--root", help="confine file tools to this directory")
|
|
ap.add_argument("--yolo", action="store_true", help="auto-approve destructive commands")
|
|
ap.add_argument("--max-turns", type=int, default=20)
|
|
ap.add_argument("--port", type=int, default=48970)
|
|
ap.add_argument("--session", help="session json file to keep chat history")
|
|
a = ap.parse_args()
|
|
|
|
if a.mode == "tools":
|
|
print(json.dumps([t["function"]["name"] for t in TOOLS]))
|
|
return
|
|
|
|
if a.mode == "serve":
|
|
ServeHandler.backend = build_backend(a)
|
|
ServeHandler.yolo = a.yolo
|
|
print("[serve] %s model=%s port=%d tools=%d" % (ServeHandler.backend.base,
|
|
ServeHandler.backend.model, a.port, len(TOOLS)), flush=True)
|
|
srv = ThreadingHTTPServer(("127.0.0.1", a.port), ServeHandler)
|
|
srv.daemon_threads = True
|
|
srv.serve_forever()
|
|
return
|
|
|
|
be = build_backend(a)
|
|
st = State(root=a.root, yolo=a.yolo, confirm=confirm)
|
|
history = []
|
|
if a.session and os.path.exists(a.session):
|
|
try:
|
|
history = json.load(open(a.session, encoding="utf-8"))
|
|
except Exception:
|
|
history = []
|
|
|
|
if a.mode == "chat":
|
|
while True:
|
|
try:
|
|
q = input("\n> ").strip()
|
|
except (EOFError, KeyboardInterrupt):
|
|
return
|
|
if not q or q in ("exit", "quit"):
|
|
return
|
|
st.answer = None
|
|
r = run_task(be, q, st, a.max_turns, history=history)
|
|
history += [{"role": "user", "content": q}, {"role": "assistant", "content": r["answer"]}]
|
|
if a.session:
|
|
json.dump(history[-40:], open(a.session, "w", encoding="utf-8"), ensure_ascii=False)
|
|
return
|
|
|
|
if not a.prompt:
|
|
ap.print_help()
|
|
return
|
|
r = run_task(be, a.prompt, st, a.max_turns)
|
|
print("\n--- result ---")
|
|
print(json.dumps({"answer": r["answer"], "turns": r["turns"],
|
|
"tools_used": [t["tool"] for t in r["trace"]],
|
|
"seconds": r.get("seconds")}, ensure_ascii=False, indent=1))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |