optima-ai-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.
- optima/__init__.py +2 -0
- optima/__main__.py +82 -0
- optima/assets/icon-256.png +0 -0
- optima/brand.py +10 -0
- optima/browser.py +287 -0
- optima/config.py +99 -0
- optima/engines.py +348 -0
- optima/i18n.py +214 -0
- optima/macos/AppIcon.icns +0 -0
- optima/macos/Info.plist +31 -0
- optima/macos/build.sh +26 -0
- optima/macos/main.swift +493 -0
- optima/mcp_server.py +157 -0
- optima/notify.py +53 -0
- optima/page_script.js +324 -0
- optima/setup.py +257 -0
- optima/skill/SKILL.md +69 -0
- optima/welcome.html +151 -0
- optima_ai_browser-0.2.0.dist-info/METADATA +264 -0
- optima_ai_browser-0.2.0.dist-info/RECORD +24 -0
- optima_ai_browser-0.2.0.dist-info/WHEEL +5 -0
- optima_ai_browser-0.2.0.dist-info/entry_points.txt +3 -0
- optima_ai_browser-0.2.0.dist-info/licenses/LICENSE +21 -0
- optima_ai_browser-0.2.0.dist-info/top_level.txt +1 -0
optima/__init__.py
ADDED
optima/__main__.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Command line: python -m optima <command>
|
|
2
|
+
|
|
3
|
+
setup first run: language, skill, connect assistants (add --cli for terminal only)
|
|
4
|
+
mcp run the MCP server (what assistants start)
|
|
5
|
+
open URL open the browser yourself, e.g. to log in to your sites
|
|
6
|
+
doctor check the installation
|
|
7
|
+
build-engine compile the native macOS engine (macOS only)
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from . import __version__, brand, config
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def doctor() -> None:
|
|
19
|
+
cfg = config.load()
|
|
20
|
+
engine = config.resolve_engine(cfg)
|
|
21
|
+
print(f"{brand.FULL_NAME} {__version__}")
|
|
22
|
+
print(f" python: {sys.executable} ({sys.version.split()[0]})")
|
|
23
|
+
print(f" config: {config.CONFIG_FILE} ({'found' if config.CONFIG_FILE.exists() else 'missing: run setup'})")
|
|
24
|
+
print(f" language: {cfg.get('language') or '(not chosen yet)'}")
|
|
25
|
+
print(f" engine: {engine}")
|
|
26
|
+
if engine == "webkit":
|
|
27
|
+
app = config.webkit_app_path()
|
|
28
|
+
print(f" app: {app} ({'ok' if app.exists() else 'missing: run optima build-engine'})")
|
|
29
|
+
else:
|
|
30
|
+
try:
|
|
31
|
+
import playwright # noqa: F401
|
|
32
|
+
print(" playwright: ok")
|
|
33
|
+
except ImportError:
|
|
34
|
+
print(" playwright: missing (pip install playwright)")
|
|
35
|
+
from .setup import desktop_config_path, find_claude_cli
|
|
36
|
+
print(f" claude cli: {find_claude_cli() or 'not found'}")
|
|
37
|
+
p = desktop_config_path()
|
|
38
|
+
registered = False
|
|
39
|
+
if p.exists():
|
|
40
|
+
try:
|
|
41
|
+
registered = brand.SLUG in json.loads(p.read_text("utf-8")).get("mcpServers", {})
|
|
42
|
+
except ValueError:
|
|
43
|
+
pass
|
|
44
|
+
print(f" claude desktop: {'registered' if registered else 'not registered'}")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def open_url(url: str) -> None:
|
|
48
|
+
from .browser import Browser
|
|
49
|
+
b = Browser()
|
|
50
|
+
print(b.open(url).split("\n\n", 1)[0])
|
|
51
|
+
print("Close the window when you are done.")
|
|
52
|
+
try:
|
|
53
|
+
while b.engine and b.engine.alive():
|
|
54
|
+
time.sleep(1)
|
|
55
|
+
except KeyboardInterrupt:
|
|
56
|
+
pass
|
|
57
|
+
b.close()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def main() -> None:
|
|
61
|
+
args = sys.argv[1:]
|
|
62
|
+
cmd = args[0] if args else "help"
|
|
63
|
+
if cmd == "mcp":
|
|
64
|
+
from .mcp_server import main as run
|
|
65
|
+
run()
|
|
66
|
+
elif cmd == "setup":
|
|
67
|
+
from .setup import main as run_setup
|
|
68
|
+
run_setup(args[1:])
|
|
69
|
+
elif cmd == "open" and len(args) > 1:
|
|
70
|
+
open_url(args[1])
|
|
71
|
+
elif cmd == "doctor":
|
|
72
|
+
doctor()
|
|
73
|
+
elif cmd == "build-engine":
|
|
74
|
+
print(config.build_macos_engine())
|
|
75
|
+
elif cmd in ("-v", "--version", "version"):
|
|
76
|
+
print(__version__)
|
|
77
|
+
else:
|
|
78
|
+
print(__doc__)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
main()
|
|
Binary file
|
optima/brand.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Every user-visible name lives here. scripts/rename.py rewrites it for you."""
|
|
2
|
+
NAME = "Optima"
|
|
3
|
+
FULL_NAME = "Optima AI Browser"
|
|
4
|
+
SLUG = "optima"
|
|
5
|
+
REPO_URL = "https://github.com/ascaniolocorotondo/optima-ai-browser"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def ua_suffix(version: str) -> str:
|
|
9
|
+
# Honest identification: sites can see this is an AI agent.
|
|
10
|
+
return f"{NAME}/{version} (AI agent; +{REPO_URL})"
|
optima/browser.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""The agent-facing browser: reading, acting, safety rules and human hand-off."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import datetime as _dt
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
|
|
11
|
+
from . import config
|
|
12
|
+
from .engines import Engine, EngineError, make_engine
|
|
13
|
+
from .i18n import t
|
|
14
|
+
from .notify import notify
|
|
15
|
+
|
|
16
|
+
# Words that reveal what a button does, in the six supported languages.
|
|
17
|
+
_CATEGORIES: List[Tuple[str, re.Pattern]] = [
|
|
18
|
+
("purchase", re.compile(r"\b(buy|pay|purchase|checkout|place (your )?order|order now|subscribe|acquista|paga|compra|ordina|"
|
|
19
|
+
r"abbonati|comprar|pagar|suscribirse|acheter|payer|commander|s'abonner|kaufen|bezahlen|"
|
|
20
|
+
r"zahlungspflichtig|bestellen|abonnieren|assinar|finalizar compra)\b", re.I)),
|
|
21
|
+
("delete", re.compile(r"\b(delete|remove|erase|cancel (my )?(account|subscription)|elimina|cancella|rimuovi|borrar|eliminar|"
|
|
22
|
+
r"supprimer|effacer|löschen|entfernen|excluir|apagar)\b", re.I)),
|
|
23
|
+
("send", re.compile(r"\b(send|post|publish|tweet|reply|share|invia|pubblica|rispondi|condividi|enviar|publicar|responder|"
|
|
24
|
+
r"envoyer|publier|répondre|partager|senden|veröffentlichen|antworten|teilen|compartilhar)\b", re.I)),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _now() -> str:
|
|
29
|
+
return _dt.datetime.now().isoformat(timespec="seconds")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ActionRefused(Exception):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Browser:
|
|
37
|
+
def __init__(self) -> None:
|
|
38
|
+
self.cfg = config.load()
|
|
39
|
+
self.engine: Optional[Engine] = None
|
|
40
|
+
self._last_action = 0.0
|
|
41
|
+
|
|
42
|
+
# ---------- lifecycle ----------
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def lang(self) -> str:
|
|
46
|
+
return self.cfg.get("language") or "en"
|
|
47
|
+
|
|
48
|
+
def ensure(self) -> Engine:
|
|
49
|
+
if self.engine is None or not self.engine.alive():
|
|
50
|
+
if self.engine is not None:
|
|
51
|
+
try:
|
|
52
|
+
self.engine.stop()
|
|
53
|
+
except Exception:
|
|
54
|
+
pass
|
|
55
|
+
self.engine = make_engine(self.cfg)
|
|
56
|
+
self.engine.start()
|
|
57
|
+
return self.engine
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
if self.engine is not None:
|
|
61
|
+
try:
|
|
62
|
+
self.engine.stop()
|
|
63
|
+
finally:
|
|
64
|
+
self.engine = None
|
|
65
|
+
|
|
66
|
+
# ---------- helpers ----------
|
|
67
|
+
|
|
68
|
+
def _pace(self) -> None:
|
|
69
|
+
gap = self.cfg.get("min_action_interval_ms", 400) / 1000.0
|
|
70
|
+
wait = self._last_action + gap - time.time()
|
|
71
|
+
if wait > 0:
|
|
72
|
+
time.sleep(wait)
|
|
73
|
+
self._last_action = time.time()
|
|
74
|
+
|
|
75
|
+
def _log(self, tool: str, args: Dict[str, Any], result: str) -> None:
|
|
76
|
+
try:
|
|
77
|
+
config.LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
f = config.LOG_DIR / (_dt.date.today().isoformat() + ".jsonl")
|
|
79
|
+
with f.open("a", encoding="utf-8") as fh:
|
|
80
|
+
fh.write(json.dumps({"ts": _now(), "tool": tool, "args": args, "result": result[:300]},
|
|
81
|
+
ensure_ascii=False) + "\n")
|
|
82
|
+
except OSError:
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
def _after_load(self) -> List[str]:
|
|
86
|
+
"""Runs after every page change: cookie banner, human check, JS dialogs."""
|
|
87
|
+
e = self.ensure()
|
|
88
|
+
notes: List[str] = []
|
|
89
|
+
if self.cfg.get("dismiss_cookie_banners", True):
|
|
90
|
+
try:
|
|
91
|
+
r = e.ab("dismissCookies")
|
|
92
|
+
if r and r.get("clicked"):
|
|
93
|
+
notes.append(f'Cookie banner dismissed with "{r["clicked"]}" (privacy-preserving choice).')
|
|
94
|
+
e.wait_idle(5)
|
|
95
|
+
except Exception:
|
|
96
|
+
pass
|
|
97
|
+
try:
|
|
98
|
+
challenge = e.ab("detectChallenge")
|
|
99
|
+
except Exception:
|
|
100
|
+
challenge = None
|
|
101
|
+
if challenge:
|
|
102
|
+
if self.cfg.get("auto_handoff", True):
|
|
103
|
+
notes.append(self._handoff(challenge=challenge))
|
|
104
|
+
else:
|
|
105
|
+
notes.append(f"This page shows a human check ({challenge}). Call browser_ask_human so the user can complete it.")
|
|
106
|
+
for d in e.dialogs():
|
|
107
|
+
notes.append("Page dialog: " + d)
|
|
108
|
+
return notes
|
|
109
|
+
|
|
110
|
+
def _handoff(self, reason: str = "", challenge: Optional[str] = None) -> str:
|
|
111
|
+
e = self.ensure()
|
|
112
|
+
site = ""
|
|
113
|
+
try:
|
|
114
|
+
site = urlparse(json.loads(e.eval("(function(){return JSON.stringify(location.href)})()"))).netloc
|
|
115
|
+
except Exception:
|
|
116
|
+
pass
|
|
117
|
+
if challenge:
|
|
118
|
+
banner = t(self.lang, "handoff_challenge")
|
|
119
|
+
body = t(self.lang, "notify_challenge", site=site or "?")
|
|
120
|
+
else:
|
|
121
|
+
banner = t(self.lang, "handoff_generic", reason=reason)
|
|
122
|
+
body = t(self.lang, "notify_generic", reason=reason)
|
|
123
|
+
notify(self.cfg, t(self.lang, "notify_title"), body)
|
|
124
|
+
e.handoff_begin(banner, t(self.lang, "done_button"))
|
|
125
|
+
timeout = float(self.cfg.get("handoff_timeout_seconds", 300))
|
|
126
|
+
start = time.time()
|
|
127
|
+
clear_streak = 0
|
|
128
|
+
outcome = "timeout"
|
|
129
|
+
try:
|
|
130
|
+
while time.time() - start < timeout:
|
|
131
|
+
time.sleep(1.0)
|
|
132
|
+
if e.handoff_done():
|
|
133
|
+
outcome = "done"
|
|
134
|
+
break
|
|
135
|
+
if challenge:
|
|
136
|
+
try:
|
|
137
|
+
still = e.ab("detectChallenge")
|
|
138
|
+
except Exception:
|
|
139
|
+
still = challenge
|
|
140
|
+
clear_streak = clear_streak + 1 if not still else 0
|
|
141
|
+
if clear_streak >= 2:
|
|
142
|
+
outcome = "cleared"
|
|
143
|
+
break
|
|
144
|
+
finally:
|
|
145
|
+
try:
|
|
146
|
+
e.handoff_end()
|
|
147
|
+
except EngineError:
|
|
148
|
+
pass
|
|
149
|
+
waited = int(time.time() - start)
|
|
150
|
+
if outcome == "timeout":
|
|
151
|
+
return f"Asked the user for help ({challenge or reason}) but they did not respond within {int(timeout)}s. Tell the user what you need and stop, or try again later."
|
|
152
|
+
if challenge:
|
|
153
|
+
return f"The user completed the human check ({challenge}) in {waited}s. Continuing."
|
|
154
|
+
return f"The user finished ({waited}s): {reason}"
|
|
155
|
+
|
|
156
|
+
def _snapshot(self, max_chars: Optional[int] = None) -> Dict[str, Any]:
|
|
157
|
+
e = self.ensure()
|
|
158
|
+
return e.ab("snapshot", int(max_chars or self.cfg.get("max_read_chars", 12000)))
|
|
159
|
+
|
|
160
|
+
def _render(self, notes: List[str], max_chars: Optional[int] = None) -> str:
|
|
161
|
+
snap = self._snapshot(max_chars)
|
|
162
|
+
head = [f"URL: {snap.get('url', '')}", f"Title: {snap.get('title', '')}", f"Scroll: {snap.get('scroll', '')}"]
|
|
163
|
+
if snap.get("challenge"):
|
|
164
|
+
head.append(f"Human check still on page: {snap['challenge']}")
|
|
165
|
+
out = "\n".join(head)
|
|
166
|
+
if notes:
|
|
167
|
+
out += "\n" + "\n".join("Note: " + n for n in notes)
|
|
168
|
+
out += "\n\n" + (snap.get("text") or "(empty page)")
|
|
169
|
+
if snap.get("truncated"):
|
|
170
|
+
out += "\n\n[truncated: call browser_scroll then browser_read for more, or browser_read with a larger max_chars]"
|
|
171
|
+
return out
|
|
172
|
+
|
|
173
|
+
def _classify(self, info: Dict[str, Any], submitting: bool) -> List[str]:
|
|
174
|
+
text = " ".join([info.get("text", ""), info.get("name", ""), info.get("form_action", "")])
|
|
175
|
+
cats = [name for name, rx in _CATEGORIES if rx.search(text)]
|
|
176
|
+
is_submit = submitting or info.get("type") == "submit" or (
|
|
177
|
+
info.get("tag") == "button" and info.get("type") in ("", "submit") and info.get("in_form"))
|
|
178
|
+
if is_submit:
|
|
179
|
+
cats.append("submit")
|
|
180
|
+
return cats
|
|
181
|
+
|
|
182
|
+
def _check_policy(self, element_id: str, confirmed: bool, submitting: bool = False, typing: bool = False) -> None:
|
|
183
|
+
e = self.ensure()
|
|
184
|
+
info = e.ab("info", element_id)
|
|
185
|
+
if not info:
|
|
186
|
+
raise ActionRefused(f"No element with id {element_id}. Call browser_read to get fresh ids.")
|
|
187
|
+
pol = self.cfg.get("policies", {})
|
|
188
|
+
if typing and pol.get("human_only_fields", True):
|
|
189
|
+
ac = info.get("autocomplete", "")
|
|
190
|
+
if info.get("type") == "password" or ac.startswith("cc-") or "current-password" in ac or "new-password" in ac \
|
|
191
|
+
or re.search(r"card|cvv|cvc|iban", info.get("name", ""), re.I):
|
|
192
|
+
raise ActionRefused("This is a password or payment field. Those are always entered by the human: "
|
|
193
|
+
"call browser_ask_human and ask the user to fill it in.")
|
|
194
|
+
cats = self._classify(info, submitting)
|
|
195
|
+
blocked = [c for c in cats if c in pol.get("block", [])]
|
|
196
|
+
if blocked:
|
|
197
|
+
raise ActionRefused(f"Blocked by the user's rules: this looks like a {blocked[0]} action "
|
|
198
|
+
f"({info.get('text') or info.get('tag')}). Do not try another way.")
|
|
199
|
+
need = [c for c in cats if c in pol.get("confirm_before", [])]
|
|
200
|
+
if need and not confirmed:
|
|
201
|
+
raise ActionRefused(f"This looks like a {need[0]} action (\"{info.get('text') or info.get('tag')}\"). "
|
|
202
|
+
"Ask the user to confirm in the chat, then call again with confirmed=true.")
|
|
203
|
+
|
|
204
|
+
# ---------- tools ----------
|
|
205
|
+
|
|
206
|
+
def open(self, url: str) -> str:
|
|
207
|
+
if not re.match(r"^[a-z][a-z0-9+.-]*:", url, re.I):
|
|
208
|
+
url = "https://" + url
|
|
209
|
+
self._pace()
|
|
210
|
+
e = self.ensure()
|
|
211
|
+
info = e.navigate(url)
|
|
212
|
+
notes = []
|
|
213
|
+
if info.get("error"):
|
|
214
|
+
notes.append("Load error: " + str(info["error"]))
|
|
215
|
+
if info.get("timed_out"):
|
|
216
|
+
notes.append("The page was still loading after 30s; content may be partial.")
|
|
217
|
+
notes += self._after_load()
|
|
218
|
+
return self._render(notes)
|
|
219
|
+
|
|
220
|
+
def read(self, max_chars: Optional[int] = None) -> str:
|
|
221
|
+
self.ensure()
|
|
222
|
+
return self._render([], max_chars)
|
|
223
|
+
|
|
224
|
+
def click(self, element_id: str, confirmed: bool = False) -> str:
|
|
225
|
+
self._check_policy(element_id, confirmed)
|
|
226
|
+
self._pace()
|
|
227
|
+
e = self.ensure()
|
|
228
|
+
r = e.click(element_id)
|
|
229
|
+
if not r.get("ok"):
|
|
230
|
+
raise ActionRefused(r.get("error", "click failed"))
|
|
231
|
+
e.wait_idle(15)
|
|
232
|
+
return self._render(self._after_load())
|
|
233
|
+
|
|
234
|
+
def type(self, element_id: str, text: str, submit: bool = False, confirmed: bool = False) -> str:
|
|
235
|
+
self._check_policy(element_id, confirmed, submitting=submit, typing=True)
|
|
236
|
+
self._pace()
|
|
237
|
+
e = self.ensure()
|
|
238
|
+
r = e.type(element_id, text, submit)
|
|
239
|
+
if not r.get("ok"):
|
|
240
|
+
raise ActionRefused(r.get("error", "typing failed"))
|
|
241
|
+
notes: List[str] = []
|
|
242
|
+
if submit:
|
|
243
|
+
e.wait_idle(15)
|
|
244
|
+
notes = self._after_load()
|
|
245
|
+
return self._render(notes)
|
|
246
|
+
|
|
247
|
+
def select(self, element_id: str, value: str) -> str:
|
|
248
|
+
self._pace()
|
|
249
|
+
r = self.ensure().ab("select", element_id, value)
|
|
250
|
+
if not r.get("ok"):
|
|
251
|
+
raise ActionRefused(r.get("error", "select failed"))
|
|
252
|
+
return self._render([f"Selected \"{r.get('selected')}\"."])
|
|
253
|
+
|
|
254
|
+
def scroll(self, direction: str = "down") -> str:
|
|
255
|
+
self.ensure().ab("scroll", direction)
|
|
256
|
+
time.sleep(0.4)
|
|
257
|
+
return self._render([])
|
|
258
|
+
|
|
259
|
+
def navigate_history(self, action: str) -> str:
|
|
260
|
+
self._pace()
|
|
261
|
+
e = self.ensure()
|
|
262
|
+
e.history(action)
|
|
263
|
+
return self._render(self._after_load())
|
|
264
|
+
|
|
265
|
+
def screenshot(self) -> bytes:
|
|
266
|
+
return self.ensure().screenshot()
|
|
267
|
+
|
|
268
|
+
def ask_human(self, reason: str) -> str:
|
|
269
|
+
return self._handoff(reason=reason) + "\n\n" + self._render([])
|
|
270
|
+
|
|
271
|
+
def wait(self, seconds: float) -> str:
|
|
272
|
+
time.sleep(max(0.0, min(float(seconds), 30.0)))
|
|
273
|
+
return self._render(self._after_load())
|
|
274
|
+
|
|
275
|
+
def recent_actions(self, limit: int = 20) -> str:
|
|
276
|
+
f = config.LOG_DIR / (_dt.date.today().isoformat() + ".jsonl")
|
|
277
|
+
if not f.exists():
|
|
278
|
+
return "No actions logged today."
|
|
279
|
+
lines = f.read_text("utf-8").splitlines()[-int(limit):]
|
|
280
|
+
out = []
|
|
281
|
+
for ln in lines:
|
|
282
|
+
try:
|
|
283
|
+
d = json.loads(ln)
|
|
284
|
+
out.append(f"{d['ts']} {d['tool']} {json.dumps(d['args'], ensure_ascii=False)}")
|
|
285
|
+
except (ValueError, KeyError):
|
|
286
|
+
continue
|
|
287
|
+
return "\n".join(out) or "No actions logged today."
|
optima/config.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Config and data paths. Everything lives in one folder in the user's home."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict
|
|
9
|
+
|
|
10
|
+
from . import brand
|
|
11
|
+
|
|
12
|
+
HOME = Path(os.environ.get("OPTIMA_HOME", Path.home() / f".{brand.SLUG}"))
|
|
13
|
+
CONFIG_FILE = HOME / "config.json"
|
|
14
|
+
LOG_DIR = HOME / "logs"
|
|
15
|
+
PROFILE_DIR = HOME / "profile" # Playwright profile (cookies, logins)
|
|
16
|
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
|
17
|
+
REPO_DIR = PACKAGE_DIR.parent.parent # only meaningful in a source checkout
|
|
18
|
+
MACOS_SRC = PACKAGE_DIR / "macos" # Swift sources of the macOS engine
|
|
19
|
+
|
|
20
|
+
DEFAULTS: Dict[str, Any] = {
|
|
21
|
+
"language": None, # set on first run
|
|
22
|
+
"engine": "auto", # auto | webkit (macOS) | playwright
|
|
23
|
+
"playwright_channel": "auto", # auto | chrome | msedge | chromium
|
|
24
|
+
"headless": False,
|
|
25
|
+
"identify_as_agent": True, # add an honest AI-agent tag to the user agent
|
|
26
|
+
"dismiss_cookie_banners": True, # always picks "reject / only necessary"
|
|
27
|
+
"auto_handoff": True, # call the human when a check page appears
|
|
28
|
+
"handoff_timeout_seconds": 300,
|
|
29
|
+
"min_action_interval_ms": 400, # gentle pace, no hammering sites
|
|
30
|
+
"notify_desktop": True,
|
|
31
|
+
"ntfy_topic": "", # optional: phone push via ntfy.sh
|
|
32
|
+
"ntfy_server": "https://ntfy.sh",
|
|
33
|
+
"policies": {
|
|
34
|
+
# Actions the agent must confirm with the user before doing them.
|
|
35
|
+
"confirm_before": ["purchase", "send", "delete"],
|
|
36
|
+
# Actions that are never allowed.
|
|
37
|
+
"block": [],
|
|
38
|
+
# Password and payment-card fields are always left to the human.
|
|
39
|
+
"human_only_fields": True,
|
|
40
|
+
},
|
|
41
|
+
"max_read_chars": 12000,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _merge(base: Dict[str, Any], over: Dict[str, Any]) -> Dict[str, Any]:
|
|
46
|
+
out = dict(base)
|
|
47
|
+
for k, v in over.items():
|
|
48
|
+
if isinstance(v, dict) and isinstance(out.get(k), dict):
|
|
49
|
+
out[k] = _merge(out[k], v)
|
|
50
|
+
else:
|
|
51
|
+
out[k] = v
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load() -> Dict[str, Any]:
|
|
56
|
+
data: Dict[str, Any] = {}
|
|
57
|
+
if CONFIG_FILE.exists():
|
|
58
|
+
try:
|
|
59
|
+
data = json.loads(CONFIG_FILE.read_text("utf-8"))
|
|
60
|
+
except (OSError, ValueError):
|
|
61
|
+
data = {}
|
|
62
|
+
return _merge(DEFAULTS, data)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def save(cfg: Dict[str, Any]) -> None:
|
|
66
|
+
HOME.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
tmp = CONFIG_FILE.with_suffix(".tmp")
|
|
68
|
+
tmp.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), "utf-8")
|
|
69
|
+
tmp.replace(CONFIG_FILE)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def resolve_engine(cfg: Dict[str, Any]) -> str:
|
|
73
|
+
e = cfg.get("engine", "auto")
|
|
74
|
+
if e == "auto":
|
|
75
|
+
return "webkit" if sys.platform == "darwin" else "playwright"
|
|
76
|
+
return e
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def webkit_app_path() -> Path:
|
|
80
|
+
"""Where the compiled macOS engine lives."""
|
|
81
|
+
installed = HOME / "engine" / "Optima.app"
|
|
82
|
+
if installed.exists():
|
|
83
|
+
return installed
|
|
84
|
+
return MACOS_SRC / "build" / "Optima.app"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def is_source_checkout() -> bool:
|
|
88
|
+
"""True when running from a git clone (src/optima), False when installed with pip."""
|
|
89
|
+
return PACKAGE_DIR.parent.name == "src" and (REPO_DIR / "pyproject.toml").exists()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def build_macos_engine() -> Path:
|
|
93
|
+
"""Compiles the native macOS engine into ~/.optima/engine (needs the Swift compiler)."""
|
|
94
|
+
import subprocess
|
|
95
|
+
out = HOME / "engine"
|
|
96
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
subprocess.run(["sh", str(MACOS_SRC / "build.sh"), str(out)], check=True,
|
|
98
|
+
stdout=subprocess.DEVNULL)
|
|
99
|
+
return out / "Optima.app"
|