waymark-browser 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- waymark_browser/__init__.py +3 -0
- waymark_browser/__main__.py +3 -0
- waymark_browser/app.py +282 -0
- waymark_browser/bridge.py +42 -0
- waymark_browser/cli.py +272 -0
- waymark_browser/client.py +153 -0
- waymark_browser-0.2.0.dist-info/METADATA +100 -0
- waymark_browser-0.2.0.dist-info/RECORD +11 -0
- waymark_browser-0.2.0.dist-info/WHEEL +4 -0
- waymark_browser-0.2.0.dist-info/entry_points.txt +2 -0
- waymark_browser-0.2.0.dist-info/licenses/LICENSE +21 -0
waymark_browser/app.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Install, start and stop the Waymark desktop app (an Electron + Node project)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import signal
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tarfile
|
|
12
|
+
import tempfile
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .client import Client
|
|
20
|
+
|
|
21
|
+
REPO = "guangxiangdebizi/waymark-browser"
|
|
22
|
+
IS_WINDOWS = os.name == "nt"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def home() -> Path:
|
|
26
|
+
return Path(os.environ.get("WAYMARK_HOME") or Path.home() / ".waymark")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def state_file() -> Path:
|
|
30
|
+
return home() / "app.json"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def log_file() -> Path:
|
|
34
|
+
return home() / "logs" / "app.log"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_app_dir(path: Path) -> bool:
|
|
38
|
+
try:
|
|
39
|
+
return json.loads((path / "package.json").read_text(encoding="utf-8-sig")).get("name") == "waymark-browser"
|
|
40
|
+
except (OSError, ValueError):
|
|
41
|
+
return False
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def find_app_dir(explicit: str | None = None) -> Path | None:
|
|
45
|
+
candidates = [explicit, os.environ.get("WAYMARK_APP_DIR"), str(home() / "app"), os.getcwd()]
|
|
46
|
+
for candidate in candidates:
|
|
47
|
+
if candidate and is_app_dir(Path(candidate).expanduser()):
|
|
48
|
+
return Path(candidate).expanduser().resolve()
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def tool(name: str) -> str | None:
|
|
53
|
+
return shutil.which(name + ".cmd") if IS_WINDOWS and shutil.which(name + ".cmd") else shutil.which(name)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def node_version() -> tuple[int, ...] | None:
|
|
57
|
+
node = tool("node")
|
|
58
|
+
if not node:
|
|
59
|
+
return None
|
|
60
|
+
try:
|
|
61
|
+
out = subprocess.run([node, "--version"], capture_output=True, text=True, timeout=20).stdout.strip().lstrip("v")
|
|
62
|
+
return tuple(int(part) for part in out.split(".")[:3])
|
|
63
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def has_ddddocr(python: str = sys.executable) -> bool:
|
|
68
|
+
try:
|
|
69
|
+
return subprocess.run([python, "-c", "import ddddocr"], capture_output=True, timeout=60).returncode == 0
|
|
70
|
+
except (OSError, subprocess.SubprocessError):
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run(command: list[str], cwd: Path, env: dict | None = None) -> None:
|
|
75
|
+
print("$ " + " ".join(command), flush=True)
|
|
76
|
+
result = subprocess.run(command, cwd=cwd, env=env)
|
|
77
|
+
if result.returncode:
|
|
78
|
+
raise SystemExit(f"Command failed with exit code {result.returncode}: {' '.join(command)}")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# ---------------------------------------------------------------- setup
|
|
82
|
+
def download(ref: str) -> bytes:
|
|
83
|
+
urls = [f"https://codeload.github.com/{REPO}/tar.gz/{ref}"]
|
|
84
|
+
last = None
|
|
85
|
+
for url in urls:
|
|
86
|
+
try:
|
|
87
|
+
with urllib.request.urlopen(url, timeout=120) as response:
|
|
88
|
+
return response.read()
|
|
89
|
+
except urllib.error.HTTPError as error:
|
|
90
|
+
last = error
|
|
91
|
+
raise SystemExit(f"Could not download {REPO}@{ref}: {last}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def safe_extract(archive: bytes, target: Path) -> None:
|
|
95
|
+
"""Extract a GitHub tarball, dropping its top-level folder and refusing paths outside target."""
|
|
96
|
+
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
|
|
97
|
+
root = target.resolve()
|
|
98
|
+
for member in tar.getmembers():
|
|
99
|
+
parts = Path(member.name).parts[1:]
|
|
100
|
+
if not parts or member.issym() or member.islnk() or member.isdev():
|
|
101
|
+
continue
|
|
102
|
+
destination = (root / Path(*parts)).resolve()
|
|
103
|
+
if root not in destination.parents and destination != root:
|
|
104
|
+
raise SystemExit(f"Refusing to extract unsafe path: {member.name}")
|
|
105
|
+
if member.isdir():
|
|
106
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
elif member.isfile():
|
|
108
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
source = tar.extractfile(member)
|
|
110
|
+
destination.write_bytes(source.read() if source else b"")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def setup(app_dir: str | None, ref: str | None, skip_install: bool = False) -> Path:
|
|
114
|
+
target = (Path(app_dir).expanduser() if app_dir else home() / "app").resolve()
|
|
115
|
+
if target.exists() and (not target.is_dir() or
|
|
116
|
+
(any(target.iterdir()) and not is_app_dir(target)) or
|
|
117
|
+
(target / ".git").exists()):
|
|
118
|
+
raise SystemExit(f"Refusing to replace {target}: choose an empty directory or a Waymark installation without .git.")
|
|
119
|
+
ref = ref or f"v{__version__}"
|
|
120
|
+
print(f"Downloading {REPO}@{ref} ...", flush=True)
|
|
121
|
+
try:
|
|
122
|
+
archive = download(ref)
|
|
123
|
+
except SystemExit:
|
|
124
|
+
if ref.startswith("v") and ref == f"v{__version__}":
|
|
125
|
+
print(f"Tag {ref} not found; falling back to main.", flush=True)
|
|
126
|
+
ref, archive = "main", download("main")
|
|
127
|
+
else:
|
|
128
|
+
raise
|
|
129
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
with tempfile.TemporaryDirectory() as temp:
|
|
131
|
+
staging = Path(temp) / "src"
|
|
132
|
+
staging.mkdir()
|
|
133
|
+
safe_extract(archive, staging)
|
|
134
|
+
if not is_app_dir(staging):
|
|
135
|
+
raise SystemExit("Downloaded archive is not a Waymark app checkout")
|
|
136
|
+
# Replace code but keep user data (profile, audit ledger, settings) and node_modules.
|
|
137
|
+
for item in target.iterdir():
|
|
138
|
+
if item.name not in {"data", "node_modules", ".venv"}:
|
|
139
|
+
shutil.rmtree(item) if item.is_dir() else item.unlink()
|
|
140
|
+
for item in staging.iterdir():
|
|
141
|
+
shutil.move(str(item), str(target / item.name))
|
|
142
|
+
print(f"App source installed to {target}", flush=True)
|
|
143
|
+
if skip_install:
|
|
144
|
+
return target
|
|
145
|
+
build(target)
|
|
146
|
+
if not has_ddddocr():
|
|
147
|
+
print('Local CAPTCHA OCR is optional. Enable it with: pip install "waymark-browser[ocr]"', flush=True)
|
|
148
|
+
print("Done. Start the browser with: waymark start", flush=True)
|
|
149
|
+
return target
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def build(app_dir: Path) -> None:
|
|
153
|
+
version = node_version()
|
|
154
|
+
if not version:
|
|
155
|
+
raise SystemExit("Node.js 22+ is required: https://nodejs.org/")
|
|
156
|
+
if version < (22,):
|
|
157
|
+
print(f"Warning: Node.js {'.'.join(map(str, version))} found; Waymark is tested on 22+.", flush=True)
|
|
158
|
+
npm = tool("npm")
|
|
159
|
+
if not npm:
|
|
160
|
+
raise SystemExit("npm was not found next to Node.js")
|
|
161
|
+
env = dict(os.environ)
|
|
162
|
+
env.pop("NODE_ENV", None)
|
|
163
|
+
run([npm, "ci", "--include=dev", "--no-audit", "--no-fund"], app_dir, env)
|
|
164
|
+
run([npm, "run", "build"], app_dir, env)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---------------------------------------------------------------- start / stop
|
|
168
|
+
def read_state() -> dict:
|
|
169
|
+
try:
|
|
170
|
+
return json.loads(state_file().read_text(encoding="utf-8"))
|
|
171
|
+
except (OSError, ValueError):
|
|
172
|
+
return {}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def alive(pid: int | None) -> bool:
|
|
176
|
+
if not pid:
|
|
177
|
+
return False
|
|
178
|
+
if IS_WINDOWS:
|
|
179
|
+
out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout
|
|
180
|
+
return str(pid) in out
|
|
181
|
+
try:
|
|
182
|
+
os.kill(pid, 0)
|
|
183
|
+
return True
|
|
184
|
+
except OSError:
|
|
185
|
+
return False
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def start(app_dir: str | None, port: int | None, foreground: bool, timeout: float, url: str | None) -> int:
|
|
189
|
+
directory = find_app_dir(app_dir)
|
|
190
|
+
if not directory:
|
|
191
|
+
raise SystemExit("Waymark app not found. Install it with `waymark setup`, or pass --app-dir / set WAYMARK_APP_DIR.")
|
|
192
|
+
client = Client(url or (f"http://127.0.0.1:{port}" if port else None), timeout=10)
|
|
193
|
+
if client.health():
|
|
194
|
+
print(f"Waymark is already running at {client.url}")
|
|
195
|
+
return 0
|
|
196
|
+
if not (directory / "dist" / "app" / "launcher.js").exists():
|
|
197
|
+
build(directory)
|
|
198
|
+
node = tool("node")
|
|
199
|
+
if not node:
|
|
200
|
+
raise SystemExit("Node.js 22+ is required: https://nodejs.org/")
|
|
201
|
+
env = dict(os.environ)
|
|
202
|
+
if port:
|
|
203
|
+
env["WAYMARK_PORT"] = str(port)
|
|
204
|
+
if "WAYMARK_PYTHON" not in env and has_ddddocr():
|
|
205
|
+
env["WAYMARK_PYTHON"] = sys.executable
|
|
206
|
+
if sys.platform.startswith("linux"):
|
|
207
|
+
if not (env.get("DISPLAY") or env.get("WAYLAND_DISPLAY")):
|
|
208
|
+
raise SystemExit("No display found. Waymark is a desktop app; on a headless server run: xvfb-run -a waymark start --foreground")
|
|
209
|
+
if hasattr(os, "geteuid") and os.geteuid() == 0 and "--no-sandbox" not in env.get("WAYMARK_ELECTRON_ARGS", ""):
|
|
210
|
+
env["WAYMARK_ELECTRON_ARGS"] = (env.get("WAYMARK_ELECTRON_ARGS", "") + " --no-sandbox").strip()
|
|
211
|
+
command = [node, str(Path("dist") / "app" / "launcher.js")]
|
|
212
|
+
if foreground:
|
|
213
|
+
return subprocess.call(command, cwd=directory, env=env)
|
|
214
|
+
log_file().parent.mkdir(parents=True, exist_ok=True)
|
|
215
|
+
log = open(log_file(), "a", encoding="utf-8")
|
|
216
|
+
kwargs: dict = {"cwd": directory, "env": env, "stdout": log, "stderr": subprocess.STDOUT, "stdin": subprocess.DEVNULL}
|
|
217
|
+
if IS_WINDOWS:
|
|
218
|
+
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP | 0x00000008 # DETACHED_PROCESS
|
|
219
|
+
else:
|
|
220
|
+
kwargs["start_new_session"] = True
|
|
221
|
+
process = subprocess.Popen(command, **kwargs)
|
|
222
|
+
state_file().parent.mkdir(parents=True, exist_ok=True)
|
|
223
|
+
state_file().write_text(json.dumps({"pid": process.pid, "app_dir": str(directory), "url": client.url, "started": time.time()}), encoding="utf-8")
|
|
224
|
+
deadline = time.time() + timeout
|
|
225
|
+
while time.time() < deadline:
|
|
226
|
+
if process.poll() is not None:
|
|
227
|
+
raise SystemExit(f"Waymark exited during startup (code {process.returncode}). Log: {log_file()}")
|
|
228
|
+
if client.health():
|
|
229
|
+
print(f"Waymark is running. MCP endpoint: {client.url}/mcp")
|
|
230
|
+
return 0
|
|
231
|
+
time.sleep(1)
|
|
232
|
+
raise SystemExit(f"Waymark did not become ready within {timeout:.0f}s. Log: {log_file()}")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def stop() -> int:
|
|
236
|
+
state = read_state()
|
|
237
|
+
pid = state.get("pid")
|
|
238
|
+
if not alive(pid):
|
|
239
|
+
print("No Waymark process started by this CLI is running.")
|
|
240
|
+
state_file().unlink(missing_ok=True)
|
|
241
|
+
return 0
|
|
242
|
+
if IS_WINDOWS:
|
|
243
|
+
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True)
|
|
244
|
+
else:
|
|
245
|
+
try:
|
|
246
|
+
os.killpg(pid, signal.SIGTERM)
|
|
247
|
+
except OSError:
|
|
248
|
+
os.kill(pid, signal.SIGTERM)
|
|
249
|
+
for _ in range(20):
|
|
250
|
+
if not alive(pid):
|
|
251
|
+
break
|
|
252
|
+
time.sleep(0.25)
|
|
253
|
+
else:
|
|
254
|
+
try:
|
|
255
|
+
os.killpg(pid, signal.SIGKILL)
|
|
256
|
+
except OSError:
|
|
257
|
+
pass
|
|
258
|
+
state_file().unlink(missing_ok=True)
|
|
259
|
+
print("Waymark stopped.")
|
|
260
|
+
return 0
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def doctor(app_dir: str | None, url: str | None) -> int:
|
|
264
|
+
version = node_version()
|
|
265
|
+
directory = find_app_dir(app_dir)
|
|
266
|
+
client = Client(url, timeout=5)
|
|
267
|
+
rows = [
|
|
268
|
+
("Python", f"{sys.version.split()[0]} ({sys.executable})", True),
|
|
269
|
+
("Node.js", ".".join(map(str, version)) if version else "missing - install Node.js 22+", bool(version) and version >= (22,)),
|
|
270
|
+
("npm", tool("npm") or "missing", bool(tool("npm"))),
|
|
271
|
+
("App directory", str(directory) if directory else "not installed - run `waymark setup`", bool(directory)),
|
|
272
|
+
("App built", "yes" if directory and (directory / "dist" / "app" / "launcher.js").exists() else "no", bool(directory and (directory / "dist" / "app" / "launcher.js").exists())),
|
|
273
|
+
("ddddocr (optional)", "installed" if has_ddddocr() else 'not installed - pip install "waymark-browser[ocr]"', True),
|
|
274
|
+
("Running", f"yes at {client.url}" if client.health() else "no", True),
|
|
275
|
+
]
|
|
276
|
+
if sys.platform.startswith("linux"):
|
|
277
|
+
display = os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")
|
|
278
|
+
rows.append(("Display", display or "none - use xvfb-run on servers", bool(display)))
|
|
279
|
+
width = max(len(name) for name, _, _ in rows)
|
|
280
|
+
for name, value, ok in rows:
|
|
281
|
+
print(f"{'OK ' if ok else '!! '} {name.ljust(width)} {value}")
|
|
282
|
+
return 0 if all(ok for _, _, ok in rows) else 1
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""stdio <-> Streamable HTTP bridge so stdio-only MCP clients can drive Waymark.
|
|
2
|
+
|
|
3
|
+
Usage in an MCP client config: {"command": "waymark", "args": ["mcp"]}
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from typing import Callable, TextIO
|
|
10
|
+
|
|
11
|
+
from .client import Client, NotRunningError, WaymarkError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def serve(client: Client, stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout, on_down: Callable[[], bool] | None = None) -> int:
|
|
15
|
+
def emit(message: dict) -> None:
|
|
16
|
+
stdout.write(json.dumps(message, ensure_ascii=False) + "\n")
|
|
17
|
+
stdout.flush()
|
|
18
|
+
|
|
19
|
+
for line in stdin:
|
|
20
|
+
line = line.strip()
|
|
21
|
+
if not line:
|
|
22
|
+
continue
|
|
23
|
+
try:
|
|
24
|
+
message = json.loads(line)
|
|
25
|
+
except json.JSONDecodeError:
|
|
26
|
+
emit({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
|
|
27
|
+
continue
|
|
28
|
+
try:
|
|
29
|
+
try:
|
|
30
|
+
replies = client.post_rpc(message)
|
|
31
|
+
except NotRunningError:
|
|
32
|
+
if not (on_down and on_down()):
|
|
33
|
+
raise
|
|
34
|
+
replies = client.post_rpc(message)
|
|
35
|
+
for reply in replies:
|
|
36
|
+
emit(reply)
|
|
37
|
+
except WaymarkError as error:
|
|
38
|
+
if isinstance(message, dict) and "id" in message:
|
|
39
|
+
emit({"jsonrpc": "2.0", "id": message["id"], "error": {"code": -32000, "message": str(error)}})
|
|
40
|
+
else:
|
|
41
|
+
print(f"waymark mcp: {error}", file=sys.stderr, flush=True)
|
|
42
|
+
return 0
|
waymark_browser/cli.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""`waymark` command line."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from . import __version__, app, bridge
|
|
11
|
+
from .client import Client, WaymarkError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def emit(value: Any, as_json: bool) -> None:
|
|
15
|
+
if as_json or not isinstance(value, str):
|
|
16
|
+
print(json.dumps(value, ensure_ascii=False, indent=2))
|
|
17
|
+
else:
|
|
18
|
+
print(value)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def fmt_time(ts: str) -> str:
|
|
22
|
+
try:
|
|
23
|
+
return datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone().strftime("%m-%d %H:%M:%S")
|
|
24
|
+
except ValueError:
|
|
25
|
+
return ts
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def show_status(status: dict) -> str:
|
|
29
|
+
pending = [job for job in status.get("challenges", []) if job["status"] in ("detected", "ai_recovery_required", "human_required")]
|
|
30
|
+
clipboard = "isolated" if status.get("clipboardProvider", "").endswith("virtual") else "system"
|
|
31
|
+
lines = [
|
|
32
|
+
f"State {'PAUSED by user' if status.get('paused') else ('busy' if status.get('busy') else 'ready')}",
|
|
33
|
+
f"Session {status.get('session')}",
|
|
34
|
+
f"Tabs {status.get('tabs')}",
|
|
35
|
+
f"Clipboard {clipboard}",
|
|
36
|
+
f"Ambient mouse {'on' if status.get('ambientMouse', {}).get('enabled') else 'off'}",
|
|
37
|
+
f"Actions today {status.get('todayActions')}",
|
|
38
|
+
f"Challenges {len(pending)} waiting" + "".join(f"\n - {job['status']} {job['origin']} ({job['id'][:8]})" for job in pending),
|
|
39
|
+
f"MCP {status.get('mcp')}",
|
|
40
|
+
]
|
|
41
|
+
return "\n".join(lines)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def show_tabs(tabs: list) -> str:
|
|
45
|
+
if not tabs:
|
|
46
|
+
return "No tabs."
|
|
47
|
+
return "\n".join(f"{'*' if tab.get('active') else ' '} {tab['id']:>3} {tab.get('title') or '(untitled)'}\n {tab.get('url')}" for tab in tabs)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def collapse_started(events: list) -> list:
|
|
51
|
+
"""Drop "started" rows that already have a matching completion (input is newest first)."""
|
|
52
|
+
completed: dict = {}
|
|
53
|
+
result = []
|
|
54
|
+
for event in events:
|
|
55
|
+
key = (event.get("pageId"), event["action"])
|
|
56
|
+
if event["status"] in ("success", "failure"):
|
|
57
|
+
completed[key] = completed.get(key, 0) + 1
|
|
58
|
+
elif event["status"] == "started" and completed.get(key):
|
|
59
|
+
completed[key] -= 1
|
|
60
|
+
continue
|
|
61
|
+
result.append(event)
|
|
62
|
+
return result
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def show_audit(events: list) -> str:
|
|
66
|
+
rows = []
|
|
67
|
+
for event in reversed(collapse_started([e for e in events if e["action"] != "tabs.list"])):
|
|
68
|
+
where = (event.get("after") or event.get("before") or {}).get("url", "")
|
|
69
|
+
target = event.get("target") or {}
|
|
70
|
+
detail = target.get("ref") or target.get("url") or target.get("key") or ""
|
|
71
|
+
status = {"success": "ok", "failure": "FAIL", "info": "-", "started": "..."}.get(event["status"], event["status"])
|
|
72
|
+
line = f"{fmt_time(event['timestamp'])} {status:<4} {event['action']:<16} {str(detail)[:40]:<40} {where[:70]}"
|
|
73
|
+
if event.get("error"):
|
|
74
|
+
line += f"\n{'':20}{event['error'].splitlines()[0][:120]}"
|
|
75
|
+
rows.append(line)
|
|
76
|
+
return "\n".join(rows) or "No events."
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def parse_fields(values: list[str]) -> list[dict]:
|
|
80
|
+
if len(values) % 2:
|
|
81
|
+
raise SystemExit("fill expects REF VALUE pairs, e.g. waymark fill 3 e4 hello e5 world")
|
|
82
|
+
return [{"ref": values[index], "value": values[index + 1]} for index in range(0, len(values), 2)]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
86
|
+
parser = argparse.ArgumentParser(prog="waymark", description="Drive Waymark, the open-source browser for AI agents, from the terminal.")
|
|
87
|
+
parser.add_argument("--url", help="Waymark base URL (default $WAYMARK_URL or http://127.0.0.1:9510)")
|
|
88
|
+
parser.add_argument("--json", action="store_true", help="print raw JSON")
|
|
89
|
+
parser.add_argument("--version", action="version", version=f"waymark-browser {__version__}")
|
|
90
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
91
|
+
# Accept --json/--url after the subcommand too (`waymark audit --json`); SUPPRESS keeps the global value otherwise.
|
|
92
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
93
|
+
common.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="print raw JSON")
|
|
94
|
+
common.add_argument("--url", default=argparse.SUPPRESS, help="Waymark base URL")
|
|
95
|
+
original_add_parser = sub.add_parser
|
|
96
|
+
sub.add_parser = lambda *a, **k: original_add_parser(*a, parents=[common], **k) # type: ignore[method-assign]
|
|
97
|
+
|
|
98
|
+
p = sub.add_parser("setup", help="download and build the Waymark desktop app")
|
|
99
|
+
p.add_argument("--dir", help="install directory (default ~/.waymark/app)")
|
|
100
|
+
p.add_argument("--ref", help="git tag or branch (default: the tag matching this CLI)")
|
|
101
|
+
p.add_argument("--no-build", action="store_true", help="only download the source")
|
|
102
|
+
|
|
103
|
+
p = sub.add_parser("start", help="start the desktop app")
|
|
104
|
+
p.add_argument("--app-dir")
|
|
105
|
+
p.add_argument("--port", type=int)
|
|
106
|
+
p.add_argument("--foreground", action="store_true", help="stay attached (Ctrl+C to quit)")
|
|
107
|
+
p.add_argument("--timeout", type=float, default=120)
|
|
108
|
+
sub.add_parser("stop", help="stop the app started by `waymark start`")
|
|
109
|
+
p = sub.add_parser("doctor", help="check Node.js, the app install and the connection")
|
|
110
|
+
p.add_argument("--app-dir")
|
|
111
|
+
|
|
112
|
+
sub.add_parser("status", help="show automation state, tabs and pending challenges")
|
|
113
|
+
sub.add_parser("pause", help="pause all agent automation (the user takes the browser)")
|
|
114
|
+
sub.add_parser("resume", help="let agents drive the browser again")
|
|
115
|
+
sub.add_parser("tabs", help="list tabs")
|
|
116
|
+
p = sub.add_parser("open", help="open a URL in a new tab")
|
|
117
|
+
p.add_argument("target", metavar="url")
|
|
118
|
+
p = sub.add_parser("goto", help="navigate a tab")
|
|
119
|
+
p.add_argument("page", type=int)
|
|
120
|
+
p.add_argument("target", metavar="url")
|
|
121
|
+
for name in ("back", "forward", "reload", "close"):
|
|
122
|
+
p = sub.add_parser(name, help=f"{name} a tab")
|
|
123
|
+
p.add_argument("page", type=int)
|
|
124
|
+
p = sub.add_parser("snapshot", help="list interactive elements with refs")
|
|
125
|
+
p.add_argument("page", type=int)
|
|
126
|
+
p = sub.add_parser("read", help="read page text (or rendered HTML)")
|
|
127
|
+
p.add_argument("page", type=int)
|
|
128
|
+
p.add_argument("--html", action="store_true")
|
|
129
|
+
p.add_argument("--limit", type=int)
|
|
130
|
+
p = sub.add_parser("click", help="click an element ref from the last snapshot")
|
|
131
|
+
p.add_argument("page", type=int)
|
|
132
|
+
p.add_argument("ref")
|
|
133
|
+
p = sub.add_parser("hover", help="hover an element ref")
|
|
134
|
+
p.add_argument("page", type=int)
|
|
135
|
+
p.add_argument("ref")
|
|
136
|
+
p = sub.add_parser("fill", help="fill inputs: REF VALUE [REF VALUE ...]")
|
|
137
|
+
p.add_argument("page", type=int)
|
|
138
|
+
p.add_argument("pairs", nargs="+")
|
|
139
|
+
p = sub.add_parser("paste", help="paste text into an element through the clipboard provider")
|
|
140
|
+
p.add_argument("page", type=int)
|
|
141
|
+
p.add_argument("ref")
|
|
142
|
+
p.add_argument("text")
|
|
143
|
+
p = sub.add_parser("press", help="press a key, e.g. Enter or Control+A")
|
|
144
|
+
p.add_argument("page", type=int)
|
|
145
|
+
p.add_argument("key")
|
|
146
|
+
p = sub.add_parser("scroll", help="scroll the page")
|
|
147
|
+
p.add_argument("page", type=int)
|
|
148
|
+
p.add_argument("direction", nargs="?", default="down", choices=["up", "down", "left", "right"])
|
|
149
|
+
p.add_argument("--amount", type=float, default=3)
|
|
150
|
+
p = sub.add_parser("wait", help="wait for text, a CSS selector or a number of milliseconds")
|
|
151
|
+
p.add_argument("page", type=int)
|
|
152
|
+
group = p.add_mutually_exclusive_group(required=True)
|
|
153
|
+
group.add_argument("--text")
|
|
154
|
+
group.add_argument("--selector")
|
|
155
|
+
group.add_argument("--ms", type=int)
|
|
156
|
+
p.add_argument("--timeout", type=int, default=10000)
|
|
157
|
+
p = sub.add_parser("audit", help="show the action ledger")
|
|
158
|
+
p.add_argument("--limit", type=int, default=30)
|
|
159
|
+
p.add_argument("--failures", action="store_true")
|
|
160
|
+
p.add_argument("--ambient", action="store_true", help="include ambient mouse moves")
|
|
161
|
+
p = sub.add_parser("trace", help="show one ledger event with its snapshot basis")
|
|
162
|
+
p.add_argument("id")
|
|
163
|
+
p = sub.add_parser("challenge", help="list or advance CAPTCHA challenge jobs")
|
|
164
|
+
p.add_argument("action", nargs="?", default="list", choices=["list", "status", "ai_failed", "ai_resolved", "human_start", "cancel"])
|
|
165
|
+
p.add_argument("id", nargs="?")
|
|
166
|
+
sub.add_parser("tools", help="list MCP tools exposed by the app")
|
|
167
|
+
p = sub.add_parser("call", help="call any MCP tool with JSON arguments")
|
|
168
|
+
p.add_argument("tool")
|
|
169
|
+
p.add_argument("arguments", nargs="?", default="{}")
|
|
170
|
+
p = sub.add_parser("mcp", help="stdio MCP bridge for clients without HTTP support")
|
|
171
|
+
p.add_argument("--autostart", action="store_true", help="start the app if it is not running")
|
|
172
|
+
return parser
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def run(args: argparse.Namespace) -> int:
|
|
176
|
+
command, as_json = args.command, args.json
|
|
177
|
+
if command == "setup":
|
|
178
|
+
app.setup(args.dir, args.ref, args.no_build)
|
|
179
|
+
return 0
|
|
180
|
+
if command == "start":
|
|
181
|
+
return app.start(args.app_dir, args.port, args.foreground, args.timeout, args.url)
|
|
182
|
+
if command == "stop":
|
|
183
|
+
return app.stop()
|
|
184
|
+
if command == "doctor":
|
|
185
|
+
return app.doctor(args.app_dir, args.url)
|
|
186
|
+
|
|
187
|
+
client = Client(args.url)
|
|
188
|
+
if command == "mcp":
|
|
189
|
+
on_down = (lambda: app.start(None, None, False, 120, args.url) == 0) if args.autostart else None
|
|
190
|
+
return bridge.serve(client, on_down=on_down)
|
|
191
|
+
if command == "status":
|
|
192
|
+
status = client.api("status")
|
|
193
|
+
emit(status if as_json else show_status(status), as_json)
|
|
194
|
+
elif command in ("pause", "resume"):
|
|
195
|
+
result = client.api("control", {"paused": command == "pause"})
|
|
196
|
+
emit(result if as_json else ("Automation paused; agents are refused until `waymark resume`." if result["paused"] else "Automation resumed."), as_json)
|
|
197
|
+
elif command == "tabs":
|
|
198
|
+
tabs = client.call("tabs", {"action": "list"})
|
|
199
|
+
emit(tabs if as_json else show_tabs(tabs), as_json)
|
|
200
|
+
elif command == "open":
|
|
201
|
+
tab = client.call("tabs", {"action": "new", "url": args.target})
|
|
202
|
+
emit(tab if as_json else f"Opened tab {tab['id']}: {tab.get('title')}\n{tab.get('url')}", as_json)
|
|
203
|
+
elif command == "goto":
|
|
204
|
+
emit(client.call("navigate", {"action": "url", "page": args.page, "url": args.target}), True)
|
|
205
|
+
elif command in ("back", "forward", "reload"):
|
|
206
|
+
emit(client.call("navigate", {"action": command, "page": args.page}), True)
|
|
207
|
+
elif command == "close":
|
|
208
|
+
emit(client.call("tabs", {"action": "close", "page": args.page}), True)
|
|
209
|
+
elif command == "snapshot":
|
|
210
|
+
snap = client.call("snapshot", {"page": args.page})
|
|
211
|
+
emit(snap if as_json else snap["text"], as_json)
|
|
212
|
+
elif command == "read":
|
|
213
|
+
arguments = {"page": args.page, "format": "html" if args.html else "text"}
|
|
214
|
+
if args.limit:
|
|
215
|
+
arguments["limit"] = args.limit
|
|
216
|
+
page = client.call("read", arguments)
|
|
217
|
+
emit(page if as_json else page["text"] + ("\n[truncated]" if page.get("truncated") else ""), as_json)
|
|
218
|
+
elif command in ("click", "hover"):
|
|
219
|
+
emit(client.call("act", {"page": args.page, "kind": command, "ref": args.ref}), True)
|
|
220
|
+
elif command == "fill":
|
|
221
|
+
emit(client.call("act", {"page": args.page, "kind": "fill", "fields": parse_fields(args.pairs)}), True)
|
|
222
|
+
elif command == "paste":
|
|
223
|
+
emit(client.call("act", {"page": args.page, "kind": "paste", "ref": args.ref, "value": args.text}), True)
|
|
224
|
+
elif command == "press":
|
|
225
|
+
emit(client.call("act", {"page": args.page, "kind": "press", "key": args.key}), True)
|
|
226
|
+
elif command == "scroll":
|
|
227
|
+
emit(client.call("act", {"page": args.page, "kind": "scroll", "direction": args.direction, "amount": args.amount}), True)
|
|
228
|
+
elif command == "wait":
|
|
229
|
+
kind, value = ("text", args.text) if args.text is not None else ("selector", args.selector) if args.selector is not None else ("time", args.ms)
|
|
230
|
+
result = client.call("wait", {"page": args.page, "for": kind, "value": value, "timeout": args.timeout})
|
|
231
|
+
emit(result, True)
|
|
232
|
+
return 0 if result.get("matched") else 1
|
|
233
|
+
elif command == "audit":
|
|
234
|
+
query = f"audit/events?limit={args.limit}&ambient={1 if args.ambient else 0}" + ("&status=failure" if args.failures else "")
|
|
235
|
+
events = client.api(query)
|
|
236
|
+
emit(events if as_json else show_audit(events), as_json)
|
|
237
|
+
elif command == "trace":
|
|
238
|
+
emit(client.call("audit", {"action": "get", "id": args.id}), True)
|
|
239
|
+
elif command == "challenge":
|
|
240
|
+
arguments = {"action": args.action}
|
|
241
|
+
if args.id:
|
|
242
|
+
arguments["id"] = args.id
|
|
243
|
+
emit(client.call("challenge", arguments), True)
|
|
244
|
+
elif command == "tools":
|
|
245
|
+
tools = client.tools()
|
|
246
|
+
emit(tools if as_json else "\n".join(f"{tool['name']:<14} {tool.get('description', '')}" for tool in tools), as_json)
|
|
247
|
+
elif command == "call":
|
|
248
|
+
try:
|
|
249
|
+
arguments = json.loads(args.arguments)
|
|
250
|
+
except json.JSONDecodeError as error:
|
|
251
|
+
raise SystemExit(f"Arguments must be JSON: {error}")
|
|
252
|
+
emit(client.call(args.tool, arguments), True)
|
|
253
|
+
return 0
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def main(argv: list[str] | None = None) -> int:
|
|
257
|
+
parser = build_parser()
|
|
258
|
+
args = parser.parse_args(argv)
|
|
259
|
+
if not args.command:
|
|
260
|
+
parser.print_help()
|
|
261
|
+
return 0
|
|
262
|
+
for stream in (sys.stdin, sys.stdout, sys.stderr):
|
|
263
|
+
# MCP over stdio is UTF-8 by spec; page titles are often non-ASCII on Windows consoles too.
|
|
264
|
+
if hasattr(stream, "reconfigure"):
|
|
265
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
266
|
+
try:
|
|
267
|
+
return run(args)
|
|
268
|
+
except WaymarkError as error:
|
|
269
|
+
print(f"waymark: {error}", file=sys.stderr)
|
|
270
|
+
return 1
|
|
271
|
+
except KeyboardInterrupt:
|
|
272
|
+
return 130
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Minimal MCP client for the Waymark app, using only the standard library.
|
|
2
|
+
|
|
3
|
+
The app serves stateless Streamable HTTP MCP at ``/mcp`` and a small JSON cockpit
|
|
4
|
+
API under ``/api``. Responses to MCP POSTs may be plain JSON or an SSE stream.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
from typing import Any, Iterable
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
|
|
16
|
+
DEFAULT_URL = "http://127.0.0.1:9510"
|
|
17
|
+
PROTOCOL_VERSION = "2025-03-26"
|
|
18
|
+
END_MARKER = "\n[END_UNTRUSTED_PAGE_CONTENT"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class WaymarkError(RuntimeError):
|
|
22
|
+
"""Raised for connection problems and tool errors reported by the app."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class NotRunningError(WaymarkError):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def base_url(url: str | None = None) -> str:
|
|
30
|
+
value = url or os.environ.get("WAYMARK_URL") or DEFAULT_URL
|
|
31
|
+
value = value.rstrip("/")
|
|
32
|
+
return value[: -len("/mcp")] if value.endswith("/mcp") else value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_messages(body: str, content_type: str) -> list[dict]:
|
|
36
|
+
"""Return JSON-RPC messages from a JSON or text/event-stream response body."""
|
|
37
|
+
if not body.strip():
|
|
38
|
+
return []
|
|
39
|
+
if "text/event-stream" not in content_type:
|
|
40
|
+
data = json.loads(body)
|
|
41
|
+
return data if isinstance(data, list) else [data]
|
|
42
|
+
messages, chunk = [], []
|
|
43
|
+
for line in body.splitlines() + [""]:
|
|
44
|
+
if line.startswith("data:"):
|
|
45
|
+
chunk.append(line[5:].lstrip())
|
|
46
|
+
elif not line.strip() and chunk:
|
|
47
|
+
try:
|
|
48
|
+
messages.append(json.loads("\n".join(chunk)))
|
|
49
|
+
except json.JSONDecodeError:
|
|
50
|
+
pass
|
|
51
|
+
chunk = []
|
|
52
|
+
return messages
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def unwrap(result: dict) -> Any:
|
|
56
|
+
"""Decode a tool result: strip the untrusted-content envelope and parse its JSON body."""
|
|
57
|
+
texts = [item.get("text", "") for item in result.get("content", []) if item.get("type") == "text"]
|
|
58
|
+
text = texts[0] if texts else ""
|
|
59
|
+
start, end = text.find("\n"), text.rfind(END_MARKER)
|
|
60
|
+
body = text[start + 1:end] if text.startswith("[UNTRUSTED_PAGE_CONTENT") and 0 <= start < end else text
|
|
61
|
+
try:
|
|
62
|
+
value = json.loads(body)
|
|
63
|
+
except json.JSONDecodeError:
|
|
64
|
+
value = body
|
|
65
|
+
if result.get("isError"):
|
|
66
|
+
message = value.get("error") if isinstance(value, dict) else value
|
|
67
|
+
raise WaymarkError(str(message))
|
|
68
|
+
return value
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Client:
|
|
72
|
+
def __init__(self, url: str | None = None, timeout: float = 120.0):
|
|
73
|
+
self.url = base_url(url)
|
|
74
|
+
self.timeout = timeout
|
|
75
|
+
self._initialized = False
|
|
76
|
+
self._next_id = 1
|
|
77
|
+
|
|
78
|
+
# ----- transport -----
|
|
79
|
+
def _request(self, method: str, path: str, body: Any = None, headers: dict | None = None) -> tuple[int, str, str]:
|
|
80
|
+
data = None if body is None else json.dumps(body).encode()
|
|
81
|
+
request = urllib.request.Request(self.url + path, data=data, method=method)
|
|
82
|
+
if body is not None:
|
|
83
|
+
request.add_header("Content-Type", "application/json")
|
|
84
|
+
for key, value in (headers or {}).items():
|
|
85
|
+
request.add_header(key, value)
|
|
86
|
+
try:
|
|
87
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
88
|
+
return response.status, response.headers.get("Content-Type", ""), response.read().decode("utf-8")
|
|
89
|
+
except urllib.error.HTTPError as error:
|
|
90
|
+
text = error.read().decode("utf-8", "replace")
|
|
91
|
+
try:
|
|
92
|
+
message = json.loads(text).get("error") or text
|
|
93
|
+
except (json.JSONDecodeError, AttributeError):
|
|
94
|
+
message = text
|
|
95
|
+
raise WaymarkError(f"HTTP {error.code}: {message}") from None
|
|
96
|
+
except (urllib.error.URLError, ConnectionError, TimeoutError) as error:
|
|
97
|
+
raise NotRunningError(f"Waymark is not reachable at {self.url} ({getattr(error, 'reason', error)}). Start it with `waymark start`.") from None
|
|
98
|
+
|
|
99
|
+
def post_rpc(self, message: dict) -> list[dict]:
|
|
100
|
+
"""Send one JSON-RPC message to /mcp and return the messages in the response."""
|
|
101
|
+
status, content_type, body = self._request("POST", "/mcp", message, {
|
|
102
|
+
"Accept": "application/json, text/event-stream",
|
|
103
|
+
"MCP-Protocol-Version": PROTOCOL_VERSION,
|
|
104
|
+
})
|
|
105
|
+
return [] if status == 202 else parse_messages(body, content_type)
|
|
106
|
+
|
|
107
|
+
def rpc(self, method: str, params: dict | None = None) -> Any:
|
|
108
|
+
message_id = self._next_id
|
|
109
|
+
self._next_id += 1
|
|
110
|
+
replies = self.post_rpc({"jsonrpc": "2.0", "id": message_id, "method": method, "params": params or {}})
|
|
111
|
+
reply = next((item for item in replies if item.get("id") == message_id), None)
|
|
112
|
+
if reply is None:
|
|
113
|
+
raise WaymarkError(f"No response to {method}")
|
|
114
|
+
if "error" in reply:
|
|
115
|
+
raise WaymarkError(reply["error"].get("message", str(reply["error"])))
|
|
116
|
+
return reply.get("result")
|
|
117
|
+
|
|
118
|
+
def initialize(self) -> dict:
|
|
119
|
+
result = self.rpc("initialize", {
|
|
120
|
+
"protocolVersion": PROTOCOL_VERSION, "capabilities": {},
|
|
121
|
+
"clientInfo": {"name": "waymark-cli", "version": __version__},
|
|
122
|
+
})
|
|
123
|
+
self.post_rpc({"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
124
|
+
self._initialized = True
|
|
125
|
+
return result
|
|
126
|
+
|
|
127
|
+
# ----- MCP tools -----
|
|
128
|
+
def call(self, tool: str, arguments: dict | None = None) -> Any:
|
|
129
|
+
if not self._initialized:
|
|
130
|
+
self.initialize()
|
|
131
|
+
return unwrap(self.rpc("tools/call", {"name": tool, "arguments": arguments or {}}))
|
|
132
|
+
|
|
133
|
+
def tools(self) -> list[dict]:
|
|
134
|
+
if not self._initialized:
|
|
135
|
+
self.initialize()
|
|
136
|
+
return self.rpc("tools/list").get("tools", [])
|
|
137
|
+
|
|
138
|
+
# ----- cockpit API -----
|
|
139
|
+
def api(self, path: str, body: Any = None) -> Any:
|
|
140
|
+
status, _, text = self._request("GET" if body is None else "POST", "/api/" + path.lstrip("/"), body)
|
|
141
|
+
return json.loads(text) if text else None
|
|
142
|
+
|
|
143
|
+
def health(self) -> bool:
|
|
144
|
+
try:
|
|
145
|
+
_, _, text = self._request("GET", "/health")
|
|
146
|
+
return bool(json.loads(text).get("ok"))
|
|
147
|
+
except (WaymarkError, json.JSONDecodeError):
|
|
148
|
+
return False
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def compact(values: Iterable[str], width: int) -> str:
|
|
152
|
+
text = " ".join(values)
|
|
153
|
+
return text if len(text) <= width else text[: width - 1] + "…"
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: waymark-browser
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: CLI and stdio MCP bridge for Waymark, the open-source desktop browser shared by AI agents and humans.
|
|
5
|
+
Project-URL: Homepage, https://github.com/guangxiangdebizi/waymark-browser
|
|
6
|
+
Project-URL: Source, https://github.com/guangxiangdebizi/waymark-browser
|
|
7
|
+
Project-URL: Issues, https://github.com/guangxiangdebizi/waymark-browser/issues
|
|
8
|
+
Author: guangxiangdebizi
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ai-agent,audit,automation,browser,captcha,electron,mcp,playwright
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
|
|
19
|
+
Classifier: Topic :: Software Development :: Testing
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Provides-Extra: ocr
|
|
22
|
+
Requires-Dist: ddddocr>=1.5; extra == 'ocr'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# waymark-browser
|
|
26
|
+
|
|
27
|
+
Command-line companion for **[Waymark](https://github.com/guangxiangdebizi/waymark-browser)**, an open-source desktop browser that AI agents and people use together. Waymark gives agents an MCP endpoint, keeps their clipboard and pointer isolated from your desktop, routes CAPTCHAs through local OCR → AI → human hand-off, and records every action with the page snapshot it was based on.
|
|
28
|
+
|
|
29
|
+
This package installs and runs the desktop app, drives it from your terminal, and bridges it to MCP clients that only speak stdio. It has no Python dependencies.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install waymark-browser # CLI only
|
|
33
|
+
pip install "waymark-browser[ocr]" # plus local ddddocr for text CAPTCHAs
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Waymark itself is an Electron app, so you also need **Node.js 22+**.
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
waymark setup # download and build the app into ~/.waymark/app
|
|
42
|
+
waymark start # open the browser window; MCP at http://127.0.0.1:9510/mcp
|
|
43
|
+
waymark doctor # check Node.js, the install and the connection
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
On a Linux server without a display, use `xvfb-run -a waymark start --foreground`.
|
|
47
|
+
|
|
48
|
+
## Connect an AI agent
|
|
49
|
+
|
|
50
|
+
Claude Code (HTTP):
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
claude mcp add --transport http waymark http://127.0.0.1:9510/mcp
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Codex (`~/.codex/config.toml`):
|
|
57
|
+
|
|
58
|
+
```toml
|
|
59
|
+
[mcp_servers.waymark]
|
|
60
|
+
url = "http://127.0.0.1:9510/mcp"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Clients that only support stdio:
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{ "mcpServers": { "waymark": { "command": "waymark", "args": ["mcp", "--autostart"] } } }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Drive the browser from the terminal
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
waymark open https://example.com # -> Opened tab 2
|
|
73
|
+
waymark snapshot 2 # interactive elements with refs e1, e2, ...
|
|
74
|
+
waymark fill 2 e4 "noise cancelling headphones"
|
|
75
|
+
waymark press 2 Enter
|
|
76
|
+
waymark read 2 --limit 2000 # visible text (or --html for the rendered DOM)
|
|
77
|
+
waymark audit --limit 20 # what happened, when, on which page
|
|
78
|
+
waymark pause / waymark resume # take the browser back from agents
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
All commands accept `--json` for machine-readable output and `--url` (or `WAYMARK_URL`) to target another instance. `waymark call TOOL '{"json": "args"}'` reaches any MCP tool directly.
|
|
82
|
+
|
|
83
|
+
| Command | What it does |
|
|
84
|
+
|---|---|
|
|
85
|
+
| `setup [--dir] [--ref]` | Download the app source for this CLI's version and build it |
|
|
86
|
+
| `start [--port] [--foreground]` / `stop` | Run the desktop app in the background or attached |
|
|
87
|
+
| `status`, `doctor` | Automation state, pending challenges; environment checks |
|
|
88
|
+
| `tabs`, `open`, `goto`, `back`, `forward`, `reload`, `close` | Tabs and navigation |
|
|
89
|
+
| `snapshot`, `read`, `click`, `hover`, `fill`, `paste`, `press`, `scroll`, `wait` | Page actions by snapshot ref |
|
|
90
|
+
| `audit`, `trace ID` | Action ledger and the snapshot behind one action |
|
|
91
|
+
| `challenge [action] [id]` | Inspect or advance CAPTCHA jobs |
|
|
92
|
+
| `pause`, `resume` | User control lease: agents are refused while paused |
|
|
93
|
+
| `mcp [--autostart]` | stdio MCP bridge |
|
|
94
|
+
| `tools`, `call` | Raw MCP access |
|
|
95
|
+
|
|
96
|
+
## 中文说明
|
|
97
|
+
|
|
98
|
+
`waymark-browser` 是开源 AI 浏览器 Waymark 的命令行工具:一条命令安装并启动浏览器、在终端里打开网页/点击/填写/读取、查看 AI 的每一步操作记录,并为只支持 stdio 的 MCP 客户端提供桥接。安装 `waymark-browser[ocr]` 可启用本地 ddddocr 识别文字验证码。需要 Node.js 22 及以上。
|
|
99
|
+
|
|
100
|
+
License: MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
waymark_browser/__init__.py,sha256=R915vPdgGMDJ9SZFfSaxzKfBTLsfW2ekz12_PU-AbqU,104
|
|
2
|
+
waymark_browser/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
waymark_browser/app.py,sha256=i6dgwT5hvf1wH_T35V21xcvLRdCQJZf4vUY5O3v564E,11576
|
|
4
|
+
waymark_browser/bridge.py,sha256=4_sK4ARj1rxDrXXT89vY5LJz7rSQ05L3h8H1z_q9Dkw,1505
|
|
5
|
+
waymark_browser/cli.py,sha256=lLPhCWGvgKgh-aHWC26iSi5-wSWDZEcP4Xn0YdEDHFA,13614
|
|
6
|
+
waymark_browser/client.py,sha256=viN1mS2_APEZHWmEjuO7-4G37CXQG1Zn-AB2jUdDOyg,6180
|
|
7
|
+
waymark_browser-0.2.0.dist-info/METADATA,sha256=fG7kx9yEkrl6pFpYL-cYWNGprPvk_wmVXWBHejXhb9E,4408
|
|
8
|
+
waymark_browser-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
waymark_browser-0.2.0.dist-info/entry_points.txt,sha256=NzLlBuxYLX8L0xVZU28siWcya2uO8eELZhBggJc1ck0,53
|
|
10
|
+
waymark_browser-0.2.0.dist-info/licenses/LICENSE,sha256=-_3hRLHRs2J2lkBtmawzk3b6wgfDxAXHI2J44zjbg34,1098
|
|
11
|
+
waymark_browser-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 guangxiangdebizi and Waymark contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|