qw_agent: bash shell (not cmd), SSE streaming in serve mode, docs

This commit is contained in:
ENI
2026-11-21 00:24:17 +02:00
parent 029931fb73
commit 3fde9c5635
2 changed files with 80 additions and 6 deletions
+13 -1
View File
@@ -27,7 +27,7 @@ So the desktop harness cannot be repointed at an arbitrary endpoint.
| `fs_list` | directory listing with sizes |
| `fs_glob` | find files by glob (`**/*.py`) |
| `fs_grep` | regex search inside files, `file:line:text` |
| `shell` | run any command on the host (git-bash), returns exit/stdout/stderr |
| `shell` | run any command on the host in **git-bash** (auto-detected; `QW_SHELL_BIN` overrides), returns exit/stdout/stderr/shell |
| `http_get` | fetch a URL, status + first 20k chars |
| `todo_write` | keep a plan checklist |
| `task_done` | finish and return the final answer |
@@ -50,6 +50,8 @@ curl -s localhost:48970/v1/chat/completions -H 'Content-Type: application/json'
Backends: `--provider qw` (qwenwork shim, `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 ...` for anything OpenAI-compatible.
`serve` supports `"stream": true` (SSE chunks + `x_qw_tools` trailer + `[DONE]`), so any OpenAI SDK,
bot or gateway can call it unchanged.
Safety: destructive shell commands (`rm -rf`, `mkfs`, `diskpart`, ...) ask for confirmation unless
`--yolo`; `--root DIR` confines all file tools to one directory.
@@ -74,6 +76,16 @@ Serve proof:
GET /healthz {"ok": true, "model": "deepseek-v4.1-flash-1017", "tools": 10}
GET /v1/models {"data": [{"id": "deepseek-v4.1-flash-1017-agent"}]}
POST /v1/chat/completions {"choices": [...content "world qw"...], "x_qw_tools": ["fs_read","task_done"]}
POST +"stream":true 5 SSE chunks, content "1795213381" (real `date +%s` from the PC), [DONE]
```
Bash proof (`shell` goes through real git-bash, not cmd.exe) — 3 calls in parallel, 4.5 s, 2 turns:
```
[tool] shell {"command": "date +%s"} -> 1795213351 (exit 0)
[tool] shell {"command": "ls C:/Users/User/tmp/qwrepo | wc -l"} -> 12 (exit 0)
[tool] fs_grep {"path": "C:/Users/User/tmp/qwrepo", "pattern": "BASH = ", "glob": "*.py"}
-> qw_agent.py:240 "BASH = _find_bash()"
```
## Registration
+65 -3
View File
@@ -20,9 +20,11 @@ Safety: destructive shell commands ask for confirmation unless --yolo; --root co
"""
import argparse
import fnmatch
import glob as globmod
import json
import os
import re
import shutil
import subprocess
import sys
import time
@@ -211,6 +213,33 @@ def t_fs_grep(st, path, pattern, glob=None, max_hits=40):
return {"hits": hits, "truncated": False}
def _find_bash():
"""Prefer a real POSIX bash: subprocess(shell=True) on Windows is cmd.exe, where `date`, `wc`,
`grep` and friends do not exist."""
for env in ("QW_SHELL_BIN", "SHELL"):
cand = os.environ.get(env)
if cand and os.path.isfile(cand):
return cand
cand = shutil.which("bash")
if cand:
return cand
patterns = [
"C:/Users/User/AppData/Local/hermes/tools/git-*/usr/bin/bash.exe",
"C:/Users/User/AppData/Local/hermes/tools/git-*/bin/bash.exe",
"C:/Program Files/Git/bin/bash.exe",
"C:/Program Files (x86)/Git/bin/bash.exe",
"C:/ProgramData/mingw64/mingw64/usr/bin/bash.exe",
]
for pat in patterns:
hits = sorted(globmod.glob(pat))
if hits:
return hits[0].replace("\\", "/")
return None
BASH = _find_bash()
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):
@@ -218,9 +247,14 @@ def t_shell(st, command, cwd=None, timeout=180):
if cwd:
cwd = st.guard(cwd)
try:
if BASH:
p = subprocess.run([BASH, "-lc", command], cwd=cwd, capture_output=True, text=True,
timeout=timeout, encoding="utf-8", errors="replace")
else:
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:]}
return {"exit": p.returncode, "stdout": (p.stdout or "")[-20000:], "stderr": (p.stderr or "")[-4000:],
"shell": BASH or "cmd"}
except subprocess.TimeoutExpired:
return {"exit": -1, "stdout": "", "stderr": "timeout after %ss" % timeout}
@@ -387,9 +421,37 @@ class ServeHandler(BaseHTTPRequestHandler):
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)
cid = "chatcmpl-" + uuid.uuid4().hex[:24]
created = int(time.time())
if req.get("stream"):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
def chunk(delta, finish=None):
payload = {"id": cid, "object": "chat.completion.chunk", "created": created,
"model": be.model, "choices": [{"index": 0, "delta": delta,
"finish_reason": finish}]}
self.wfile.write(("data: " + json.dumps(payload, ensure_ascii=False) + "\n\n").encode())
self.wfile.flush()
try:
chunk({"role": "assistant", "content": ""})
ans = r["answer"] or ""
for i in range(0, len(ans), 400):
chunk({"content": ans[i:i + 400]})
chunk({}, "stop")
self.wfile.write(("data: " + json.dumps({"id": cid, "x_qw_tools": [t["tool"] for t in r["trace"]]},
ensure_ascii=False) + "\n\n").encode())
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
self.close_connection = True
return
return self._json(200, {
"id": "chatcmpl-" + uuid.uuid4().hex[:24], "object": "chat.completion",
"created": int(time.time()), "model": be.model,
"id": cid, "object": "chat.completion",
"created": created, "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,