kweo 5.0.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.
kweo/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """kweo — your real, signed-in browser and your own AI, from Python.
2
+
3
+ import kweo
4
+
5
+ k = kweo.connect() # finds kweo on this computer
6
+ tab = k.open("https://news.ycombinator.com")
7
+ print(tab.text()[:500])
8
+ print(tab.ask("What are the top 3 stories about?"))
9
+ rows = tab.extract({"title": str, "points": int}, many=True)
10
+
11
+ run = k.agent.run("Find my last 3 Amazon orders and their totals", url="https://amazon.com")
12
+ print(run.result)
13
+
14
+ Docs: https://kweo.ai/developers
15
+ """
16
+
17
+ from ._http import (
18
+ KweoAmbiguous,
19
+ KweoAuthError,
20
+ KweoError,
21
+ KweoNotFound,
22
+ KweoNotRunning,
23
+ KweoPermissionError,
24
+ KweoTimeout,
25
+ __version__,
26
+ discover,
27
+ )
28
+ from .client import AgentRun, Element, Kweo, Tab, connect
29
+ from .schema import to_json_schema
30
+
31
+ __all__ = [
32
+ "connect", "Kweo", "Tab", "Element", "AgentRun", "discover", "to_json_schema",
33
+ "KweoError", "KweoNotRunning", "KweoAuthError", "KweoPermissionError", "KweoNotFound", "KweoTimeout", "KweoAmbiguous",
34
+ "__version__",
35
+ ]
kweo/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
kweo/_http.py ADDED
@@ -0,0 +1,196 @@
1
+ """HTTP plumbing for the kweo library: finding kweo, requests, errors, Server-Sent Events.
2
+
3
+ Standard library only — `pip install kweo` pulls in nothing else.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import http.client
9
+ import json
10
+ import os
11
+ import socket
12
+ import urllib.parse
13
+ from pathlib import Path
14
+ from typing import Any, Dict, Iterator, Optional, Tuple
15
+
16
+ DEFAULT_URL = "http://127.0.0.1:7333"
17
+ __version__ = "5.0.0"
18
+
19
+
20
+ class KweoError(Exception):
21
+ """Something kweo refused or couldn't do. `status` is the HTTP status, `code` kweo's reason."""
22
+
23
+ def __init__(self, message: str, status: int = 0, code: str = "", details: Optional[Dict[str, Any]] = None):
24
+ super().__init__(message)
25
+ self.message = message
26
+ self.status = status
27
+ self.code = code
28
+ self.details = details or {}
29
+
30
+ def __str__(self) -> str: # pragma: no cover - trivial
31
+ return f"{self.message} ({self.code})" if self.code else self.message
32
+
33
+
34
+ class KweoNotRunning(KweoError):
35
+ """kweo isn't open on this computer (or its API is turned off)."""
36
+
37
+
38
+ class KweoAuthError(KweoError):
39
+ """The API key is missing or wrong."""
40
+
41
+
42
+ class KweoPermissionError(KweoError):
43
+ """The key lacks a permission, the site is blocked, or you declined the action in kweo."""
44
+
45
+
46
+ class KweoNotFound(KweoError):
47
+ """No such tab, element, model, run or workflow."""
48
+
49
+
50
+ class KweoTimeout(KweoError):
51
+ """kweo didn't finish in time."""
52
+
53
+
54
+ class KweoAmbiguous(KweoError):
55
+ """Several elements matched — `details['candidates']` lists them; add role= or nth=."""
56
+
57
+
58
+ def _api_file() -> Path:
59
+ return Path(os.environ.get("KWEO_API_FILE") or (Path.home() / ".kweo" / "api.json"))
60
+
61
+
62
+ def discover(url: Optional[str] = None, key: Optional[str] = None) -> Tuple[str, Optional[str]]:
63
+ """Where kweo listens and the key to use: arguments, then KWEO_URL / KWEO_API_KEY, then
64
+ ~/.kweo/api.json (written by kweo itself), then the default address."""
65
+ info: Dict[str, Any] = {}
66
+ try:
67
+ info = json.loads(_api_file().read_text(encoding="utf-8"))
68
+ except (OSError, ValueError):
69
+ pass
70
+ found_url = url or os.environ.get("KWEO_URL") or info.get("url") or DEFAULT_URL
71
+ found_key = key or os.environ.get("KWEO_API_KEY") or info.get("key")
72
+ return str(found_url).rstrip("/"), found_key
73
+
74
+
75
+ def _error_for(status: int, payload: bytes) -> KweoError:
76
+ message, code, details = "", "", {}
77
+ try:
78
+ body = json.loads(payload.decode("utf-8"))
79
+ err = body.get("error", body) if isinstance(body, dict) else {}
80
+ if isinstance(err, dict):
81
+ message = str(err.get("message") or "")
82
+ code = str(err.get("code") or err.get("type") or "")
83
+ details = {k: v for k, v in err.items() if k not in ("message", "code", "type", "status")}
84
+ except (ValueError, UnicodeDecodeError):
85
+ message = payload.decode("utf-8", "replace")[:500]
86
+ message = message or f"kweo answered HTTP {status}"
87
+ cls: type = KweoError
88
+ if status == 401:
89
+ cls = KweoAuthError
90
+ elif status == 403:
91
+ cls = KweoNotRunning if code == "api_off" else KweoPermissionError
92
+ elif status in (404, 410):
93
+ cls = KweoNotFound
94
+ elif status in (408, 504):
95
+ cls = KweoTimeout
96
+ elif status == 409 and code == "ambiguous":
97
+ cls = KweoAmbiguous
98
+ return cls(message, status, code, details)
99
+
100
+
101
+ class Transport:
102
+ """One kweo server. Thread-safe: every request uses its own connection."""
103
+
104
+ def __init__(self, url: str, key: Optional[str], timeout: float = 120.0):
105
+ parts = urllib.parse.urlsplit(url)
106
+ if parts.scheme != "http":
107
+ raise KweoError(f"kweo listens on plain http on this computer, not {url!r}")
108
+ self.url = url
109
+ self.host = parts.hostname or "127.0.0.1"
110
+ self.port = parts.port or 80
111
+ self.prefix = parts.path.rstrip("/")
112
+ self.key = key
113
+ self.timeout = timeout
114
+
115
+ def _headers(self, extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:
116
+ h = {"Accept": "application/json", "User-Agent": f"kweo-python/{__version__}"}
117
+ if self.key:
118
+ h["Authorization"] = f"Bearer {self.key}"
119
+ if extra:
120
+ h.update(extra)
121
+ return h
122
+
123
+ def _path(self, path: str, query: Optional[Dict[str, Any]] = None) -> str:
124
+ q = {k: ("1" if v is True else "0" if v is False else v) for k, v in (query or {}).items() if v is not None}
125
+ return f"{self.prefix}{path}" + (f"?{urllib.parse.urlencode(q)}" if q else "")
126
+
127
+ def _open(self, method: str, path: str, body: Any, query: Optional[Dict[str, Any]], timeout: Optional[float], accept: str):
128
+ conn = http.client.HTTPConnection(self.host, self.port, timeout=timeout if timeout is not None else self.timeout)
129
+ data = None
130
+ headers = self._headers({"Accept": accept})
131
+ if body is not None:
132
+ data = json.dumps(body).encode("utf-8")
133
+ headers["Content-Type"] = "application/json"
134
+ try:
135
+ conn.request(method, self._path(path, query), body=data, headers=headers)
136
+ return conn, conn.getresponse()
137
+ except (ConnectionRefusedError, ConnectionResetError, socket.gaierror) as e:
138
+ conn.close()
139
+ raise KweoNotRunning(f"kweo isn't running at {self.url} — open the kweo app (its API is on by default; see Settings → Developers).", 0, "not_running") from e
140
+ except socket.timeout as e:
141
+ conn.close()
142
+ raise KweoTimeout(f"kweo didn't answer {method} {path} in time.", 0, "timeout") from e
143
+
144
+ def request(self, method: str, path: str, body: Any = None, query: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Any:
145
+ conn, resp = self._open(method, path, body, query, timeout, "application/json")
146
+ try:
147
+ payload = resp.read()
148
+ except socket.timeout as e:
149
+ raise KweoTimeout(f"kweo didn't finish {method} {path} in time.", 0, "timeout") from e
150
+ finally:
151
+ conn.close()
152
+ if resp.status >= 400:
153
+ raise _error_for(resp.status, payload)
154
+ return json.loads(payload.decode("utf-8")) if payload else {}
155
+
156
+ def raw(self, method: str, path: str, query: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> bytes:
157
+ conn, resp = self._open(method, path, None, query, timeout, "*/*")
158
+ try:
159
+ payload = resp.read()
160
+ finally:
161
+ conn.close()
162
+ if resp.status >= 400:
163
+ raise _error_for(resp.status, payload)
164
+ return payload
165
+
166
+ def stream(self, method: str, path: str, body: Any = None, query: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Iterator[Tuple[str, Any]]:
167
+ """Server-Sent Events as (event, data) pairs; data is parsed JSON when it is JSON."""
168
+ conn, resp = self._open(method, path, body, query, timeout, "text/event-stream")
169
+ try:
170
+ if resp.status >= 400:
171
+ raise _error_for(resp.status, resp.read())
172
+ event, data = "message", []
173
+ while True:
174
+ line = resp.readline()
175
+ if not line:
176
+ break
177
+ text = line.decode("utf-8").rstrip("\r\n")
178
+ if text == "":
179
+ if data:
180
+ joined = "\n".join(data)
181
+ try:
182
+ parsed: Any = json.loads(joined)
183
+ except ValueError:
184
+ parsed = joined
185
+ yield event, parsed
186
+ event, data = "message", []
187
+ elif text.startswith(":"):
188
+ continue
189
+ elif text.startswith("event:"):
190
+ event = text[6:].strip()
191
+ elif text.startswith("data:"):
192
+ data.append(text[5:].lstrip())
193
+ except socket.timeout as e:
194
+ raise KweoTimeout("The event stream went quiet for too long.", 0, "timeout") from e
195
+ finally:
196
+ conn.close()
kweo/aio.py ADDED
@@ -0,0 +1,58 @@
1
+ """Async kweo: the same API, awaitable (each call runs in a worker thread).
2
+
3
+ from kweo.aio import connect
4
+
5
+ async def main():
6
+ k = await connect()
7
+ tab = await k.open("https://example.com")
8
+ print(await tab.text())
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import functools
15
+ from typing import Any, Optional
16
+
17
+ from .client import AgentRun, Element, Kweo, Tab
18
+
19
+ _WRAP = (Kweo, Tab, AgentRun, Element)
20
+
21
+
22
+ def _wrap(v: Any) -> Any:
23
+ if isinstance(v, _WRAP):
24
+ return _Async(v)
25
+ if isinstance(v, list) and v and isinstance(v[0], _WRAP):
26
+ return [_Async(x) for x in v]
27
+ return v
28
+
29
+
30
+ class _Async:
31
+ """Wraps a kweo object: methods become coroutines; attributes and sub-objects pass through."""
32
+
33
+ def __init__(self, obj: Any):
34
+ object.__setattr__(self, "_obj", obj)
35
+
36
+ def __getattr__(self, name: str) -> Any:
37
+ attr = getattr(self._obj, name)
38
+ if name in ("ai", "agent", "workflows", "routines"):
39
+ return _Async(attr)
40
+ if callable(attr):
41
+ @functools.wraps(attr)
42
+ async def call(*a: Any, **kw: Any) -> Any:
43
+ return _wrap(await asyncio.to_thread(attr, *a, **kw))
44
+ return call
45
+ return attr
46
+
47
+ def __repr__(self) -> str:
48
+ return f"<async {self._obj!r}>"
49
+
50
+
51
+ async def connect(url: Optional[str] = None, key: Optional[str] = None, timeout: float = 120.0) -> Any:
52
+ """Connect without blocking the event loop; returns an async view of `kweo.Kweo`."""
53
+ k = await asyncio.to_thread(Kweo, url, key, timeout)
54
+ await asyncio.to_thread(k.status)
55
+ return _Async(k)
56
+
57
+
58
+ AsyncKweo = connect
kweo/cli.py ADDED
@@ -0,0 +1,152 @@
1
+ """The `kweo` command: your browser and your AI from the shell.
2
+
3
+ kweo status what's set up
4
+ kweo tabs your open tabs
5
+ kweo open https://example.com a new tab (prints its id)
6
+ kweo text [TAB|URL] [--find X] a page's text (default: the tab you're looking at)
7
+ kweo links [TAB|URL] [--match X]
8
+ kweo shot [TAB|URL] -o page.png [--full]
9
+ kweo ask "question" [--tab TAB | --url URL] [--model M]
10
+ kweo chat "prompt" [--model M] [--system S] (streams; reads stdin when the prompt is -)
11
+ kweo extract [TAB|URL] (--shape '{"title":"str"}' | --instruction "…") [--many]
12
+ kweo run "goal" [--url URL] [--engine claude|opencode] [--model M]
13
+ kweo models | kweo workflows | kweo workflow NAME [-p key=value …] | kweo events
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import sys
21
+ from typing import Any, List, Optional
22
+
23
+ from . import __version__
24
+ from ._http import KweoError
25
+ from .client import Kweo, Tab, connect
26
+
27
+ _TYPES = {"str": str, "string": str, "int": int, "integer": int, "float": float, "number": float, "bool": bool, "boolean": bool}
28
+
29
+
30
+ def _shape(spec: str) -> Any:
31
+ """'{"title":"str","price":"float","tags":["str"]}' → a shape kweo.extract understands."""
32
+ def conv(v: Any) -> Any:
33
+ if isinstance(v, str):
34
+ return _TYPES.get(v.lower(), str)
35
+ if isinstance(v, list):
36
+ return [conv(v[0])] if v else [str]
37
+ if isinstance(v, dict):
38
+ return v if ("type" in v or "properties" in v) else {k: conv(x) for k, x in v.items()}
39
+ return v
40
+ return conv(json.loads(spec))
41
+
42
+
43
+ def _tab(k: Kweo, ref: Optional[str]) -> Tab:
44
+ if ref and ("://" in ref or ("." in ref and " " not in ref and not ref.startswith("tab"))):
45
+ return k.open(ref)
46
+ if ref:
47
+ return k.tab(ref)
48
+ t = k.active_tab()
49
+ if not t:
50
+ raise KweoError("No tab to use — open one in kweo, or pass a URL.")
51
+ return t
52
+
53
+
54
+ def _print_json(v: Any) -> None:
55
+ print(json.dumps(v, indent=2, ensure_ascii=False, default=str))
56
+
57
+
58
+ def main(argv: Optional[List[str]] = None) -> int:
59
+ p = argparse.ArgumentParser(prog="kweo", description="Your real, signed-in kweo browser and your own AI, from the shell.")
60
+ p.add_argument("--version", action="version", version=f"kweo-python {__version__}")
61
+ sub = p.add_subparsers(dest="cmd", required=True)
62
+ sub.add_parser("status")
63
+ sub.add_parser("tabs")
64
+ sub.add_parser("models")
65
+ sub.add_parser("workflows")
66
+ sub.add_parser("events")
67
+ o = sub.add_parser("open"); o.add_argument("url"); o.add_argument("--front", action="store_true")
68
+ for name in ("text", "links", "elements"):
69
+ s = sub.add_parser(name); s.add_argument("tab", nargs="?")
70
+ if name == "text":
71
+ s.add_argument("--find")
72
+ if name == "links":
73
+ s.add_argument("--match")
74
+ sh = sub.add_parser("shot"); sh.add_argument("tab", nargs="?"); sh.add_argument("-o", "--out", default="kweo-shot.png"); sh.add_argument("--full", action="store_true")
75
+ a = sub.add_parser("ask"); a.add_argument("question"); a.add_argument("--tab"); a.add_argument("--url"); a.add_argument("--model")
76
+ c = sub.add_parser("chat"); c.add_argument("prompt"); c.add_argument("--model", default="default"); c.add_argument("--system")
77
+ e = sub.add_parser("extract"); e.add_argument("tab", nargs="?"); e.add_argument("--shape"); e.add_argument("--instruction"); e.add_argument("--many", action="store_true"); e.add_argument("--model")
78
+ r = sub.add_parser("run"); r.add_argument("goal"); r.add_argument("--url"); r.add_argument("--engine"); r.add_argument("--model"); r.add_argument("--json", action="store_true", help="print the run as JSON")
79
+ w = sub.add_parser("workflow"); w.add_argument("name"); w.add_argument("-p", "--param", action="append", default=[], help="key=value")
80
+ args = p.parse_args(argv)
81
+
82
+ try:
83
+ k = connect()
84
+ if args.cmd == "status":
85
+ _print_json(k.status())
86
+ elif args.cmd == "tabs":
87
+ for t in k.tabs():
88
+ i = t._info
89
+ flags = "".join(["*" if i.get("focused") else " ", "a" if i.get("agent") else " ", "z" if i.get("asleep") else " "])
90
+ print(f"{t.id:>12} {flags} {t.title[:60]:<60} {t.url}")
91
+ elif args.cmd == "models":
92
+ for m in k.ai.models():
93
+ kw = m.get("kweo", {})
94
+ print(f"{m['id']:<40} {kw.get('label', '')}{' (default)' if kw.get('default') else ''}{' on-device' if kw.get('on_device') else ''}")
95
+ elif args.cmd == "workflows":
96
+ for wf in k.workflows.list():
97
+ params = ", ".join(x["name"] for x in wf.get("parameters", []))
98
+ print(f"{wf['id']:<16} {wf['name']}{f' ({params})' if params else ''}")
99
+ elif args.cmd == "events":
100
+ for ev in k.events():
101
+ print(json.dumps(ev, ensure_ascii=False), flush=True)
102
+ elif args.cmd == "open":
103
+ t = k.open(args.url, foreground=args.front)
104
+ print(t.id)
105
+ elif args.cmd == "text":
106
+ print(_tab(k, args.tab).text(find=args.find))
107
+ elif args.cmd == "links":
108
+ for l in _tab(k, args.tab).links(match=args.match):
109
+ print(f"{l['url']}\t{l['text']}")
110
+ elif args.cmd == "elements":
111
+ for el in _tab(k, args.tab).elements(interactive=True):
112
+ print(el)
113
+ elif args.cmd == "shot":
114
+ _tab(k, args.tab).screenshot(args.out, full_page=args.full)
115
+ print(args.out)
116
+ elif args.cmd == "ask":
117
+ if args.tab or args.url:
118
+ print(_tab(k, args.url or args.tab).ask(args.question, model=args.model))
119
+ else:
120
+ print(k.ai.chat(args.question, model=args.model or "default"))
121
+ elif args.cmd == "chat":
122
+ prompt = sys.stdin.read() if args.prompt == "-" else args.prompt
123
+ for piece in k.ai.chat(prompt, model=args.model, system=args.system, stream=True):
124
+ sys.stdout.write(piece); sys.stdout.flush()
125
+ print()
126
+ elif args.cmd == "extract":
127
+ if not args.shape and not args.instruction:
128
+ p.error("extract needs --shape or --instruction")
129
+ t = _tab(k, args.tab)
130
+ _print_json(t.extract(_shape(args.shape) if args.shape else None, many=args.many, instruction=args.instruction, model=args.model))
131
+ elif args.cmd == "run":
132
+ def step(s: Any) -> None:
133
+ print(f" · {s.get('text', '')}", file=sys.stderr, flush=True)
134
+ run = k.agent.run(args.goal, url=args.url, engine=args.engine, model=args.model, on_step=step)
135
+ if args.json:
136
+ _print_json(run._info)
137
+ else:
138
+ print(run.result or run.error or run.status)
139
+ return 0 if run.status == "done" else 1
140
+ elif args.cmd == "workflow":
141
+ params = dict(x.split("=", 1) for x in args.param)
142
+ _print_json(k.workflows.run(args.name, **params))
143
+ return 0
144
+ except KweoError as err:
145
+ print(f"kweo: {err.message}", file=sys.stderr)
146
+ return 2
147
+ except KeyboardInterrupt:
148
+ return 130
149
+
150
+
151
+ if __name__ == "__main__": # pragma: no cover
152
+ raise SystemExit(main())