@capagents/forgeqe 2.8.8 → 2.9.0

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.
Files changed (132) hide show
  1. package/HOW_TO_USE.md +10 -2
  2. package/dist/docs-site/docs/index.html +83 -2
  3. package/dist/docs-site/docs/search.js +1 -1
  4. package/dist/forgeqe.js +2036 -2029
  5. package/dist/template.html +66 -66
  6. package/dist/web/THIRD_PARTY_NOTICES.md +455 -0
  7. package/dist/web/assets/Agent-BGwHbXbc.js +4 -0
  8. package/dist/web/assets/ApiTests-DSnZHRlF.js +10 -0
  9. package/dist/web/assets/Browse-Dx3pHGuG.js +2 -0
  10. package/dist/web/assets/Chat-BcFP0BbA.js +3 -0
  11. package/dist/web/assets/CommandPalette-v6mqHZnU.js +1 -0
  12. package/dist/web/assets/Cost-C9LZdx1p.js +1 -0
  13. package/dist/web/assets/Data-DvbaOc9e.js +6 -0
  14. package/dist/web/assets/Evidence-Y1AeSzh5.js +1 -0
  15. package/dist/web/assets/Explore-Dw8S6DG1.js +2 -0
  16. package/dist/web/assets/Features-CjrVraBE.js +1 -0
  17. package/dist/web/assets/Flags-C_Qm0078.js +2 -0
  18. package/dist/web/assets/Flaky-DYgN586D.js +1 -0
  19. package/dist/web/assets/ForceGraph-CEH86-Z0.js +1 -0
  20. package/dist/web/assets/Impact-dBPp7aM2.js +3 -0
  21. package/dist/web/assets/Jobs-CSyN6YRx.js +5 -0
  22. package/dist/web/assets/KindPage-BQl-5bcd.js +6 -0
  23. package/dist/web/assets/Migration-COly7O-T.js +2 -0
  24. package/dist/web/assets/Product-7mM8tcxH.js +7 -0
  25. package/dist/web/assets/Production-De5CCUoP.js +1 -0
  26. package/dist/web/assets/Quality-Q_iqj3fk.js +1 -0
  27. package/dist/web/assets/Readiness-kU9kum_I.js +1 -0
  28. package/dist/web/assets/Record-CIhINuEz.js +2 -0
  29. package/dist/web/assets/Regression-CMQnH7dN.js +5 -0
  30. package/dist/web/assets/Reports-dUOe6_vN.js +2 -0
  31. package/dist/web/assets/Response-DGl2R0A-.js +4 -0
  32. package/dist/web/assets/RunDiff-BVRRIz3m.js +1 -0
  33. package/dist/web/assets/Runs-CkNWhAhe.js +2 -0
  34. package/dist/web/assets/TestCases-exR7hRWd.js +1 -0
  35. package/dist/web/assets/TestData-yVPMg9kw.js +2 -0
  36. package/dist/web/assets/TestDebt-C3sM6cH0.js +1 -0
  37. package/dist/web/assets/Tosca-Bcalg1JU.js +2 -0
  38. package/dist/web/assets/WhatsNew-EFSt6xx2.js +1 -0
  39. package/dist/web/assets/dataParts-D33u08WR.js +3 -0
  40. package/dist/web/assets/{families-7ZW63NF1.js → families-Btjss8bN.js} +1 -1
  41. package/dist/web/assets/frame-D3IhgCFt.js +4 -0
  42. package/dist/web/assets/index-D5sya6FK.css +2 -0
  43. package/dist/web/assets/index-v-k_CVn7.js +45 -0
  44. package/dist/web/assets/line-icons-CQ-3V8ax.js +1 -0
  45. package/dist/web/assets/logos-CfpaNwbY.js +1 -0
  46. package/dist/web/assets/palette-X7hU78Wy.js +1 -0
  47. package/dist/web/assets/parts-B7YrlR3a.js +1 -0
  48. package/dist/web/assets/productParts-CAxyMnWJ.js +1 -0
  49. package/dist/web/assets/qualityParts-CN9JVKZN.js +1 -0
  50. package/dist/web/assets/rows-IEP4Jvfi.js +1 -0
  51. package/dist/web/assets/{segmented-CCfjZKVa.js → segmented-DBqHvZW3.js} +1 -1
  52. package/dist/web/assets/thread-BeaLQ_f4.js +5 -0
  53. package/dist/web/assets/usePageChat-D_3KsqBU.js +1 -0
  54. package/dist/web/index.html +4 -3
  55. package/docs/user-guide.html +87 -2
  56. package/evals/evidence/build/README.md +20 -0
  57. package/evals/evidence/build/base/package.json +1 -0
  58. package/evals/evidence/build/base/src/index.ts +1 -0
  59. package/evals/evidence/build/base/src/pricing.ts +22 -0
  60. package/evals/evidence/build/base/tests/discount.test.ts +6 -0
  61. package/evals/evidence/build/base/tests/legacy.test.ts +7 -0
  62. package/evals/evidence/build/base/tests/pricing.test.ts +10 -0
  63. package/evals/evidence/build/cases/build-broken/after/src/pricing.ts +22 -0
  64. package/evals/evidence/build/cases/build-broken/case.json +13 -0
  65. package/evals/evidence/build/cases/fixes-legacy/after/src/pricing.ts +22 -0
  66. package/evals/evidence/build/cases/fixes-legacy/case.json +11 -0
  67. package/evals/evidence/build/cases/flaky-test/after/tests/flaky.test.ts +11 -0
  68. package/evals/evidence/build/cases/flaky-test/case.json +11 -0
  69. package/evals/evidence/build/cases/good-feature/after/src/index.ts +1 -0
  70. package/evals/evidence/build/cases/good-feature/after/src/pricing.ts +28 -0
  71. package/evals/evidence/build/cases/good-feature/after/tests/bulk.test.ts +7 -0
  72. package/evals/evidence/build/cases/good-feature/case.json +17 -0
  73. package/evals/evidence/build/cases/new-test-fails/after/src/index.ts +1 -0
  74. package/evals/evidence/build/cases/new-test-fails/after/src/pricing.ts +27 -0
  75. package/evals/evidence/build/cases/new-test-fails/after/tests/coupon.test.ts +6 -0
  76. package/evals/evidence/build/cases/new-test-fails/case.json +19 -0
  77. package/evals/evidence/build/cases/regression/after/src/pricing.ts +23 -0
  78. package/evals/evidence/build/cases/regression/case.json +13 -0
  79. package/evals/evidence/build/cases/test-removed/case.json +14 -0
  80. package/forgeqe.example.yaml +3 -0
  81. package/package.json +2 -1
  82. package/py/forgeqe_engine/browser.py +533 -28
  83. package/py/forgeqe_engine/browserdoctor.py +255 -0
  84. package/py/forgeqe_engine/browserlaunch.py +271 -0
  85. package/py/forgeqe_engine/capture.py +20 -4
  86. package/py/forgeqe_engine/cli.py +26 -0
  87. package/py/forgeqe_engine/logins.py +1 -1
  88. package/py/forgeqe_engine/pwlaunch.mjs +61 -0
  89. package/py/forgeqe_engine/recordsession.py +1 -1
  90. package/py/forgeqe_engine/service.py +1 -1
  91. package/dist/web/assets/Agent-Cp8VlBIz.js +0 -4
  92. package/dist/web/assets/ApiTests-BcZLc09C.js +0 -10
  93. package/dist/web/assets/Browse-C_YjgIEb.js +0 -1
  94. package/dist/web/assets/Chat-BoCGL6_O.js +0 -3
  95. package/dist/web/assets/CommandPalette-BfM5HzzB.js +0 -1
  96. package/dist/web/assets/Cost-TS6CXmoR.js +0 -1
  97. package/dist/web/assets/Data-CBPzLyv3.js +0 -6
  98. package/dist/web/assets/Evidence-BZq0G649.js +0 -1
  99. package/dist/web/assets/Explore-l6Hdu8Sv.js +0 -2
  100. package/dist/web/assets/Features-YYJcXLBf.js +0 -1
  101. package/dist/web/assets/Flags-C60CLbzH.js +0 -2
  102. package/dist/web/assets/Flaky-BkLguGXu.js +0 -1
  103. package/dist/web/assets/ForceGraph-D1krkEJe.js +0 -1
  104. package/dist/web/assets/Impact-640wqe0S.js +0 -3
  105. package/dist/web/assets/Jobs-C97GqHLF.js +0 -5
  106. package/dist/web/assets/KindPage-Bux228tV.js +0 -6
  107. package/dist/web/assets/Migration-VTuXJ3MF.js +0 -2
  108. package/dist/web/assets/Product-BNDHj6KV.js +0 -7
  109. package/dist/web/assets/Production-BC-kcNIt.js +0 -1
  110. package/dist/web/assets/Quality-CuSQTvtJ.js +0 -1
  111. package/dist/web/assets/Readiness-Bh2cynJx.js +0 -1
  112. package/dist/web/assets/Record-DJfuaIqW.js +0 -2
  113. package/dist/web/assets/Regression-oW_4rSE7.js +0 -5
  114. package/dist/web/assets/Reports-CBkl7Abx.js +0 -2
  115. package/dist/web/assets/Response-f5217Gw2.js +0 -4
  116. package/dist/web/assets/RunDiff-B7o9vQBr.js +0 -1
  117. package/dist/web/assets/Runs-CkdASpHU.js +0 -2
  118. package/dist/web/assets/TestCases-BPif-KCg.js +0 -1
  119. package/dist/web/assets/TestData-CQAI8n3o.js +0 -2
  120. package/dist/web/assets/TestDebt-C94phbAj.js +0 -1
  121. package/dist/web/assets/Tosca-CX7hZsNJ.js +0 -2
  122. package/dist/web/assets/WhatsNew-ktL7koKS.js +0 -1
  123. package/dist/web/assets/dataParts-DD_0rviO.js +0 -3
  124. package/dist/web/assets/frame-Ct3Ey3bQ.js +0 -4
  125. package/dist/web/assets/index-DvuGI8X3.css +0 -2
  126. package/dist/web/assets/index-tdO1bZWq.js +0 -45
  127. package/dist/web/assets/logos-Czko8FVx.js +0 -1
  128. package/dist/web/assets/parts-ryIgw8NG.js +0 -1
  129. package/dist/web/assets/productParts-CSw1V5I9.js +0 -1
  130. package/dist/web/assets/qualityParts-Czf68wgs.js +0 -1
  131. package/dist/web/assets/thread-_hyYtCeH.js +0 -5
  132. package/dist/web/assets/usePageChat-Cm84Zkf4.js +0 -1
@@ -0,0 +1,255 @@
1
+ """
2
+ forgeqe doctor browser: start each local browser each way ForgeQE can (directly, through Playwright, a browser the
3
+ person started), one at a time, and report what happened with everything that explains it: each start's own log, the
4
+ browser's own log when it was started directly, the browser policies that stop automation, the security software that
5
+ runs, and on Windows the AppLocker and code integrity events about browsers. Read only: it changes no setting, and
6
+ every program it asks is started with a fixed argument list.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ import os
14
+ import platform
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Callable, Dict, List, Optional
22
+
23
+ from .browser import (
24
+ _shutdown_browser_instance,
25
+ browser_name,
26
+ devtools_wait_seconds,
27
+ local_browser_launch_kwargs,
28
+ local_launch_candidates,
29
+ start_local_browser,
30
+ start_logger,
31
+ )
32
+ from .browserlaunch import attach_command, attach_port, launch_method, playwright_runtime
33
+
34
+ # Browser policies that decide whether ForgeQE can drive a browser it starts.
35
+ _POLICY_KEYS = {
36
+ "Google Chrome": (r"HKLM\SOFTWARE\Policies\Google\Chrome", r"HKCU\SOFTWARE\Policies\Google\Chrome"),
37
+ "Microsoft Edge": (r"HKLM\SOFTWARE\Policies\Microsoft\Edge", r"HKCU\SOFTWARE\Policies\Microsoft\Edge"),
38
+ }
39
+ _POLICY_NAMES = ("RemoteDebuggingAllowed", "UserDataDir", "DeveloperToolsAvailability", "BrowserSignin", "CommandLineFlagSecurityWarningsEnabled")
40
+ _LINUX_POLICY_DIRS = {
41
+ "Google Chrome": ("/etc/opt/chrome/policies/managed",),
42
+ "Chromium": ("/etc/chromium/policies/managed",),
43
+ "Microsoft Edge": ("/etc/opt/edge/policies/managed",),
44
+ }
45
+
46
+ # Process names of security software that is known to stop or restart programs (named, never its settings).
47
+ _SECURITY = {
48
+ "csfalconservice": "CrowdStrike Falcon",
49
+ "mssense": "Microsoft Defender for Endpoint",
50
+ "msmpeng": "Microsoft Defender Antivirus",
51
+ "defendpointservice": "BeyondTrust Privilege Management",
52
+ "pgsystemtray": "BeyondTrust Privilege Management",
53
+ "threatlockerservice": "ThreatLocker",
54
+ "sentinelagent": "SentinelOne",
55
+ "cylancesvc": "Cylance",
56
+ "cbdefense": "Carbon Black",
57
+ "repmgr": "Carbon Black",
58
+ "taniumclient": "Tanium",
59
+ "zsatunnel": "Zscaler",
60
+ "ccsvchst": "Symantec Endpoint Protection",
61
+ "mcshield": "McAfee",
62
+ "ntrtscan": "Trend Micro",
63
+ "appidsvc": "AppLocker (Application Identity)",
64
+ "cyserver": "Cortex XDR",
65
+ "xagt": "Trellix (FireEye) Endpoint",
66
+ "elastic-endpoint": "Elastic Endpoint",
67
+ "netskope": "Netskope",
68
+ "epsecurityservice": "Bitdefender",
69
+ }
70
+
71
+ # Windows event logs that record a program being blocked.
72
+ _EVENT_LOGS = ("Microsoft-Windows-AppLocker/EXE and DLL", "Microsoft-Windows-CodeIntegrity/Operational")
73
+ _EVENT_WORDS = ("chrome.exe", "msedge.exe", "chromium", "python.exe", "node.exe", "bun.exe", "forgeqe")
74
+
75
+
76
+ def _run(args: List[str], timeout: float = 15) -> str:
77
+ try:
78
+ r = subprocess.run(args, capture_output=True, text=True, timeout=timeout, errors="replace")
79
+ except Exception:
80
+ return ""
81
+ return r.stdout or ""
82
+
83
+
84
+ def browser_policies() -> List[Dict[str, str]]:
85
+ """The policies of _POLICY_NAMES that are set, for Chrome and Edge, and where."""
86
+ found: List[Dict[str, str]] = []
87
+ if sys.platform == "win32":
88
+ for browser, keys in _POLICY_KEYS.items():
89
+ for key in keys:
90
+ for name in _POLICY_NAMES:
91
+ for line in _run(["reg", "query", key, "/v", name], timeout=10).splitlines():
92
+ parts = line.split()
93
+ if len(parts) >= 3 and parts[0] == name:
94
+ found.append({"browser": browser, "where": key, "name": name, "value": " ".join(parts[2:])[:200]})
95
+ return found
96
+ import json
97
+
98
+ for browser, dirs in _LINUX_POLICY_DIRS.items():
99
+ for d in dirs:
100
+ try:
101
+ files = sorted(Path(d).glob("*.json"))
102
+ except Exception:
103
+ continue
104
+ for f in files:
105
+ try:
106
+ data = json.loads(f.read_text(encoding="utf-8"))
107
+ except Exception:
108
+ continue
109
+ if isinstance(data, dict):
110
+ for name in _POLICY_NAMES:
111
+ if name in data:
112
+ found.append({"browser": browser, "where": str(f), "name": name, "value": str(data[name])[:200]})
113
+ return found
114
+
115
+
116
+ def security_software() -> List[str]:
117
+ try:
118
+ import psutil
119
+ except ImportError:
120
+ return []
121
+ seen = set()
122
+ for proc in psutil.process_iter(["name"]):
123
+ name = str(proc.info.get("name") or "").lower()
124
+ stem = name[:-4] if name.endswith(".exe") else name
125
+ if stem in _SECURITY:
126
+ seen.add(_SECURITY[stem])
127
+ return sorted(seen)
128
+
129
+
130
+ def blocked_events(limit: int = 10) -> List[str]:
131
+ """Recent AppLocker and code integrity events about browsers, Python, Node or ForgeQE (Windows only)."""
132
+ if sys.platform != "win32":
133
+ return []
134
+ out: List[str] = []
135
+ for log in _EVENT_LOGS:
136
+ text = _run(["wevtutil", "qe", log, "/c:50", "/rd:true", "/f:text"], timeout=20)
137
+ for event in text.split("Event["):
138
+ if any(w in event.lower() for w in _EVENT_WORDS):
139
+ lines = [ln.strip() for ln in event.splitlines() if ln.strip()]
140
+ keep = [ln for ln in lines if ln.split(":", 1)[0] in ("Date", "Event ID", "Level")] + [ln for ln in lines if any(w in ln.lower() for w in _EVENT_WORDS)][:2]
141
+ out.append(f"{log}: " + " | ".join(keep)[:400])
142
+ if len(out) >= limit:
143
+ return out
144
+ return out
145
+
146
+
147
+ class _Collect(logging.Handler):
148
+ def __init__(self) -> None:
149
+ super().__init__(logging.INFO)
150
+ self.lines: List[str] = []
151
+
152
+ def emit(self, record: logging.LogRecord) -> None:
153
+ if len(self.lines) < 200:
154
+ self.lines.append(f"{record.levelname} {record.getMessage()}"[:600])
155
+
156
+
157
+ def _tail(file: Path, lines: int = 60) -> List[str]:
158
+ try:
159
+ text = file.read_text(encoding="utf-8", errors="replace")
160
+ except Exception:
161
+ return []
162
+ return [ln[:400] for ln in text.splitlines()[-lines:]]
163
+
164
+
165
+ async def _try(launch: Dict[str, Any], log_dir: Optional[Path]) -> Dict[str, Any]:
166
+ """Start one way, note what happened, close it."""
167
+ from browser_use import Browser
168
+
169
+ collect = _Collect()
170
+ start_logger.addHandler(collect)
171
+ started = time.monotonic()
172
+ result: Dict[str, Any] = {"how": browser_name(launch), "via": launch.get("_via") or "direct"}
173
+ if log_dir is not None and launch.get("_via") == "direct" and sys.platform == "win32":
174
+ # The browser's own log of its start, only for this check. Windows only: elsewhere Chrome writes it to its
175
+ # output, which nothing reads while it starts, and a full pipe stops the browser.
176
+ launch = {**launch, "args": [*list(launch.get("args") or []), "--enable-logging", "--v=0", f"--log-file={log_dir / 'browser.log'}"]}
177
+ try:
178
+ b, _ = await start_local_browser([launch], make=lambda kw: Browser(**kw))
179
+ result["ok"] = True
180
+ try:
181
+ await b._cdp_navigate("about:blank")
182
+ result["drove_a_page"] = True
183
+ except Exception as ex:
184
+ result["drove_a_page"] = False
185
+ result["error"] = f"started, but a page could not be opened: {str(ex).splitlines()[0][:300]}"
186
+ await _shutdown_browser_instance(b)
187
+ except Exception as ex:
188
+ result["ok"] = False
189
+ result["error"] = str(ex).strip()[:1200]
190
+ if log_dir is not None:
191
+ result["browser_log"] = _tail(log_dir / "browser.log")
192
+ finally:
193
+ start_logger.removeHandler(collect)
194
+ result["seconds"] = round(time.monotonic() - started, 1)
195
+ result["log"] = collect.lines
196
+ return result
197
+
198
+
199
+ async def check_browsers(payload: Dict[str, Any], emit: Callable[[Dict[str, Any]], None]) -> Dict[str, Any]:
200
+ headless = payload.get("headless") is True
201
+ choice = payload.get("local_browser")
202
+ facts: Dict[str, Any] = {
203
+ "system": f"{platform.system()} {platform.release()} ({platform.machine()})",
204
+ "python": sys.version.split()[0],
205
+ "start_wait_seconds": int(devtools_wait_seconds()),
206
+ "headless": headless,
207
+ "playwright": "installed" if playwright_runtime() is not None else "not installed",
208
+ "browser": local_browser_launch_kwargs(headless=headless).get("executable_path") or "",
209
+ # How a person starts a browser ForgeQE can connect to (browser.launch: attach).
210
+ "attach_command": attach_command(attach_port(payload.get("attach_port")) or 9222),
211
+ }
212
+ try:
213
+ from importlib.metadata import version
214
+
215
+ facts["engine_library"] = version("browser-use")
216
+ except Exception:
217
+ facts["engine_library"] = "not known"
218
+ emit({"type": "log", "level": "info", "text": "Reading browser policies and security software"})
219
+ facts["policies"] = browser_policies()
220
+ facts["security_software"] = security_software()
221
+ facts["blocked_events"] = blocked_events()
222
+
223
+ ways: List[Dict[str, Any]] = []
224
+ for how in ("direct", "playwright"):
225
+ try:
226
+ ways += local_launch_candidates(headless=headless, choice=choice, method=how)
227
+ except Exception as ex:
228
+ ways.append({"_skip": f"{how}: {str(ex).splitlines()[0][:300]}"})
229
+ if launch_method(payload.get("launch")) == "attach" or attach_port(payload.get("attach_port")) is not None:
230
+ try:
231
+ ways += local_launch_candidates(headless=headless, method="attach", port=payload.get("attach_port"))
232
+ except Exception as ex:
233
+ ways.append({"_skip": f"attach: {str(ex).splitlines()[0][:300]}"})
234
+
235
+ attempts: List[Dict[str, Any]] = []
236
+ for launch in ways:
237
+ if "_skip" in launch:
238
+ attempts.append({"how": launch["_skip"].split(":", 1)[0], "ok": False, "skipped": True, "error": launch["_skip"]})
239
+ continue
240
+ emit({"type": "log", "level": "info", "progress": True, "text": f"Starting {browser_name(launch)}"})
241
+ log_dir = Path(tempfile.mkdtemp(prefix="forgeqe-doctor-"))
242
+ try:
243
+ attempt = await _try(launch, log_dir)
244
+ finally:
245
+ shutil.rmtree(log_dir, ignore_errors=True)
246
+ attempts.append(attempt)
247
+ emit({"type": "log", "level": "info" if attempt["ok"] else "warn", "text": f"{attempt['how']}: {'started' if attempt['ok'] else 'did not start'} ({attempt['seconds']}s)"})
248
+
249
+ worked = next((a for a in attempts if a.get("ok") and a.get("drove_a_page", True)), None)
250
+ return {"success": True, "facts": facts, "attempts": attempts, "worked": worked["how"] if worked else None, "worked_via": worked["via"] if worked else None}
251
+
252
+
253
+ def main_payload(payload: Dict[str, Any], emit: Callable[[Dict[str, Any]], None]) -> Dict[str, Any]:
254
+ os.environ.setdefault("BROWSER_USE_LOGGING_LEVEL", "info")
255
+ return asyncio.run(check_browsers(payload, emit))
@@ -0,0 +1,271 @@
1
+ """
2
+ The ways ForgeQE starts or reaches the local browser, besides the library starting it directly:
3
+
4
+ - through Playwright (`launch_with_playwright`): ForgeQE's playwright-core, run by Node (or Bun), starts the browser and
5
+ the engine connects to its DevTools port. On some company PCs a browser started directly is stopped while one Playwright
6
+ starts is not.
7
+ - a browser the person started by hand (`attach_url`): only on this computer (127.0.0.1), on a port they chose; ForgeQE
8
+ connects and never closes it.
9
+
10
+ What started last time is remembered (`remembered`, `remember`) so the next start tries it first.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import contextlib
17
+ import json
18
+ import os
19
+ import shutil
20
+ import sys
21
+ import tempfile
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+ from urllib.parse import urlparse
26
+
27
+ from .browser import browser_key, devtools_wait_seconds, start_logger, wait_for_devtools
28
+
29
+ LAUNCH_METHODS = ("auto", "direct", "playwright", "attach")
30
+
31
+ PLAYWRIGHT_ENV = "FORGEQE_ENGINE_PLAYWRIGHT"
32
+ PLAYWRIGHT_RUNTIME_ENV = "FORGEQE_ENGINE_PLAYWRIGHT_RUNTIME"
33
+ _RUNTIMES = ("node", "node.exe", "bun", "bun.exe")
34
+
35
+ # The environment the Playwright launcher gets: what starting a browser needs, never a model key or a login's values.
36
+ _LAUNCH_ENV = (
37
+ "PATH", "SYSTEMROOT", "SYSTEMDRIVE", "WINDIR", "COMSPEC", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "USERNAME",
38
+ "LOCALAPPDATA", "APPDATA", "PROGRAMDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", "COMMONPROGRAMFILES",
39
+ "PLAYWRIGHT_BROWSERS_PATH", "LANG", "LC_ALL", "DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "XAUTHORITY",
40
+ "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", "NODE_EXTRA_CA_CERTS",
41
+ )
42
+
43
+
44
+ def launch_method(value: Any) -> str:
45
+ """browser.launch of forgeqe.yaml: auto (the default), direct, playwright or attach; anything else is auto."""
46
+ v = str(value or "").strip().lower()
47
+ return v if v in LAUNCH_METHODS else "auto"
48
+
49
+
50
+ def attach_port(value: Any) -> Optional[int]:
51
+ """browser.attach_port: a port number from 1024 to 65535, else None. Never a host: attaching is to this computer."""
52
+ if isinstance(value, bool):
53
+ return None
54
+ try:
55
+ port = int(str(value).strip())
56
+ except (TypeError, ValueError):
57
+ return None
58
+ return port if 1024 <= port <= 65535 and str(value).strip().isdigit() else None
59
+
60
+
61
+ def launch_env() -> Dict[str, str]:
62
+ keep = {n.upper() for n in _LAUNCH_ENV}
63
+ return {k: v for k, v in os.environ.items() if k.upper() in keep}
64
+
65
+
66
+ def playwright_runtime() -> Optional[Tuple[str, str]]:
67
+ """
68
+ (runtime, playwright-core entry) ForgeQE handed the engine (FORGEQE_ENGINE_PLAYWRIGHT_RUNTIME, FORGEQE_ENGINE_PLAYWRIGHT),
69
+ or None when either is missing or not what ForgeQE sets: an absolute path to node or bun, and playwright-core's
70
+ index.mjs.
71
+ """
72
+ runtime = (os.getenv(PLAYWRIGHT_RUNTIME_ENV) or "").strip()
73
+ entry = (os.getenv(PLAYWRIGHT_ENV) or "").strip()
74
+ if not runtime or not entry:
75
+ return None
76
+ rt, en = Path(runtime), Path(entry)
77
+ if not (rt.is_absolute() and rt.is_file() and rt.name.lower() in _RUNTIMES):
78
+ return None
79
+ if not (en.is_absolute() and en.is_file() and en.name == "index.mjs" and en.parent.name == "playwright-core"):
80
+ return None
81
+ return str(rt), str(en)
82
+
83
+
84
+ def launcher_script() -> Path:
85
+ return Path(__file__).with_name("pwlaunch.mjs")
86
+
87
+
88
+ # Launchers by the browser they started (id of the library's Browser), closed with it (`close_launcher`).
89
+ _LAUNCHERS: Dict[int, Tuple[Any, str]] = {}
90
+
91
+
92
+ async def _drain(stream: Any, label: str) -> None:
93
+ """Read a launcher's stderr into the run's log so it never fills its pipe; lines capped."""
94
+ if stream is None:
95
+ return
96
+ count = 0
97
+ while True:
98
+ line = await stream.readline()
99
+ if not line:
100
+ return
101
+ count += 1
102
+ if count <= 40:
103
+ start_logger.info("browser start: %s: %s", label, line.decode("utf-8", "replace").rstrip()[:300])
104
+
105
+
106
+ async def launch_with_playwright(launch: Dict[str, Any], *, name: str) -> Tuple[str, Any, str]:
107
+ """
108
+ Start the browser of `launch` (its executable_path, else its channel) through Playwright, with a DevTools port;
109
+ returns (DevTools address, launcher process, profile folder). A failure says "Failed to start browser" so the next
110
+ browser is tried.
111
+ """
112
+ found = playwright_runtime()
113
+ if found is None:
114
+ raise RuntimeError(f"Failed to start browser: {name}: ForgeQE's Playwright is not installed here.")
115
+ runtime, entry = found
116
+ profile = tempfile.mkdtemp(prefix="forgeqe-pw-")
117
+ args: List[str] = []
118
+ size = launch.get("window_size")
119
+ if isinstance(size, dict) and size.get("width") and size.get("height"):
120
+ args.append(f"--window-size={int(size['width'])},{int(size['height'])}")
121
+ request: Dict[str, Any] = {"headless": launch.get("headless") is True, "args": args, "userDataDir": profile, "timeoutMs": int(devtools_wait_seconds() * 1000)}
122
+ if launch.get("executable_path"):
123
+ request["executablePath"] = str(launch["executable_path"])
124
+ elif launch.get("channel") in ("chrome", "msedge"):
125
+ request["channel"] = str(launch["channel"])
126
+ else:
127
+ shutil.rmtree(profile, ignore_errors=True)
128
+ raise RuntimeError(f"Failed to start browser: {name}: no browser to start.")
129
+ start_logger.info("browser start: %s (%s %s)", name, Path(runtime).name, request.get("executablePath") or f"channel {request.get('channel')}")
130
+ proc = await asyncio.create_subprocess_exec(
131
+ runtime, str(launcher_script()), entry,
132
+ stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=launch_env(),
133
+ )
134
+ drain = asyncio.ensure_future(_drain(proc.stderr, "playwright"))
135
+ try:
136
+ assert proc.stdin is not None and proc.stdout is not None
137
+ proc.stdin.write((json.dumps(request) + "\n").encode("utf-8"))
138
+ await proc.stdin.drain()
139
+ line = await asyncio.wait_for(proc.stdout.readline(), timeout=devtools_wait_seconds() + 30)
140
+ try:
141
+ answer = json.loads(line.decode("utf-8", "replace") or "{}")
142
+ except ValueError:
143
+ answer = {}
144
+ if not isinstance(answer, dict):
145
+ answer = {}
146
+ port = answer.get("port")
147
+ if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
148
+ error = str(answer.get("error") or f"no answer (exit code {proc.returncode})")[:500]
149
+ raise RuntimeError(f"Failed to start browser: {name}: {error}")
150
+ start_logger.info("browser start: Playwright started %s (launcher PID %s), DevTools port %d", name, proc.pid, port)
151
+ url = await wait_for_devtools(port, timeout=30, process=None)
152
+ return url, proc, profile
153
+ except BaseException:
154
+ await _stop_launcher(proc, profile)
155
+ drain.cancel()
156
+ raise
157
+
158
+
159
+ async def _stop_launcher(proc: Any, profile: str) -> None:
160
+ """Close the launcher, which closes its browser; a browser still on its profile folder after that (the launcher was
161
+ stopped before it could close it) is closed by that folder, and the folder removed."""
162
+ from .browser import end_left_browsers, own_profile
163
+
164
+ with contextlib.suppress(Exception):
165
+ if proc.stdin is not None:
166
+ proc.stdin.close()
167
+ try:
168
+ await asyncio.wait_for(proc.wait(), timeout=15)
169
+ except Exception:
170
+ with contextlib.suppress(Exception):
171
+ proc.kill()
172
+ with contextlib.suppress(Exception):
173
+ await asyncio.wait_for(proc.wait(), timeout=5)
174
+ name = own_profile(profile)
175
+ if name:
176
+ with contextlib.suppress(Exception):
177
+ await asyncio.to_thread(end_left_browsers, {name})
178
+ shutil.rmtree(profile, ignore_errors=True)
179
+
180
+
181
+ def keep_launcher(browser: Any, proc: Any, profile: str) -> None:
182
+ _LAUNCHERS[id(browser)] = (proc, profile)
183
+
184
+
185
+ async def close_launcher(browser: Any) -> None:
186
+ """Close the Playwright launcher that started this browser, which closes the browser; nothing for other browsers."""
187
+ found = _LAUNCHERS.pop(id(browser), None)
188
+ if found is not None:
189
+ await _stop_launcher(*found)
190
+
191
+
192
+ def attach_command(port: int) -> str:
193
+ """How a person starts Chrome for ForgeQE to connect to: its own profile folder (Chrome refuses a debugging port on
194
+ the everyday profile) and the port, on this computer only."""
195
+ from .browser import find_edge_executable, resolve_chrome_executable_path
196
+
197
+ exe = resolve_chrome_executable_path("chrome") or find_edge_executable() or "chrome"
198
+ if sys.platform == "win32":
199
+ folder = os.path.join(os.environ.get("LOCALAPPDATA") or "%LOCALAPPDATA%", "ForgeQE", "attach-profile")
200
+ else:
201
+ folder = os.path.join(os.path.expanduser("~"), ".forgeqe", "attach-profile")
202
+ return f'"{exe}" --remote-debugging-port={port} --user-data-dir="{folder}"'
203
+
204
+
205
+ async def attach_url(port: Any) -> str:
206
+ """
207
+ The DevTools address of a browser the person started on this computer with --remote-debugging-port=<port>. Only
208
+ 127.0.0.1, only a port of browser.attach_port's range, no redirect followed, and its own WebSocket address must be
209
+ on this computer and that port.
210
+ """
211
+ import aiohttp
212
+
213
+ p = attach_port(port)
214
+ if p is None:
215
+ raise RuntimeError(f"browser.attach_port must be a port from 1024 to 65535, not {str(port)[:40]!r}.")
216
+ start_logger.info("browser start: connecting to the browser on 127.0.0.1:%d", p)
217
+ problem = "no browser answers there"
218
+ try:
219
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
220
+ async with session.get(f"http://127.0.0.1:{p}/json/version", allow_redirects=False) as resp:
221
+ if resp.status == 200:
222
+ data = await resp.json(content_type=None)
223
+ ws = urlparse(str((data or {}).get("webSocketDebuggerUrl") or ""))
224
+ if ws.scheme == "ws" and ws.hostname in ("127.0.0.1", "localhost") and ws.port == p:
225
+ start_logger.info("browser start: connected to %s on port %d", str((data or {}).get("Browser") or "a browser")[:80], p)
226
+ return f"http://127.0.0.1:{p}/"
227
+ problem = "what answers there is not a browser's DevTools on this computer"
228
+ else:
229
+ problem = f"it answered HTTP {resp.status}"
230
+ except Exception as ex:
231
+ problem = f"no browser answers there ({type(ex).__name__})"
232
+ raise RuntimeError(
233
+ f"browser.launch is attach, but {problem} (127.0.0.1:{p}). Start the browser first, for example:\n {attach_command(p)}"
234
+ )
235
+
236
+
237
+ def _state_file() -> Path:
238
+ home = os.environ.get("FORGEQE_HOME") or os.path.join(os.path.expanduser("~"), ".forgeqe")
239
+ return Path(home) / "engine" / "browser-start.json"
240
+
241
+
242
+ def remembered() -> Optional[Tuple[str, str]]:
243
+ """(browser, method) that started last time on this computer, read as untrusted: each only one of its known values."""
244
+ try:
245
+ data = json.loads(_state_file().read_text(encoding="utf-8"))
246
+ except Exception:
247
+ return None
248
+ if not isinstance(data, dict):
249
+ return None
250
+ b, m = data.get("browser"), data.get("via")
251
+ if b in ("chrome", "edge", "chromium") and m in ("direct", "playwright"):
252
+ return str(b), str(m)
253
+ return None
254
+
255
+
256
+ def remember(launch: Dict[str, Any]) -> None:
257
+ via = launch.get("_via") or "direct"
258
+ if via not in ("direct", "playwright"):
259
+ return
260
+ file = _state_file()
261
+ with contextlib.suppress(Exception):
262
+ file.parent.mkdir(parents=True, exist_ok=True)
263
+ file.write_text(
264
+ json.dumps({"browser": browser_key(launch), "via": via, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")}) + "\n",
265
+ encoding="utf-8",
266
+ )
267
+
268
+
269
+ def forget() -> None:
270
+ with contextlib.suppress(Exception):
271
+ _state_file().unlink()
@@ -256,11 +256,27 @@ async def _object_for(cdp: Any, backend_node_id: int) -> Optional[str]:
256
256
  return ((res or {}).get("object") or {}).get("objectId")
257
257
 
258
258
 
259
+ _AX_GROUP = "forgeqe-ax"
260
+
261
+
259
262
  async def _ax_matches(cdp: Any, role: str, name: str) -> List[int]:
260
- """backend node ids of the elements Chrome's accessibility tree names `name` with `role`."""
261
- doc = await _send(cdp, "DOM", "getDocument", {"depth": 0})
262
- root = ((doc or {}).get("root") or {}).get("backendNodeId")
263
- res = await _send(cdp, "Accessibility", "queryAXTree", {"backendNodeId": root, "accessibleName": name, "role": role})
263
+ """
264
+ backend node ids of the elements Chrome's accessibility tree names `name` with `role`, searched from the page's
265
+ document as its own script sees it. Not from DOM.getDocument: asked while the page is being replaced (the step just
266
+ taken submitted a form, followed a link), that one crashes Chrome's renderer now and then (Chrome 153), and the page
267
+ with it.
268
+ """
269
+ doc = await _send(cdp, "Runtime", "evaluate", {"expression": "document", "objectGroup": _AX_GROUP})
270
+ found = (doc or {}).get("result") or {}
271
+ try:
272
+ if not found.get("objectId") or found.get("subtype") != "node":
273
+ return []
274
+ res = await _send(cdp, "Accessibility", "queryAXTree", {"objectId": found["objectId"], "accessibleName": name, "role": role})
275
+ finally:
276
+ try:
277
+ await _send(cdp, "Runtime", "releaseObjectGroup", {"objectGroup": _AX_GROUP})
278
+ except Exception:
279
+ pass
264
280
  return [n["backendDOMNodeId"] for n in (res or {}).get("nodes") or [] if n.get("backendDOMNodeId") and not n.get("ignored")]
265
281
 
266
282
 
@@ -290,6 +290,30 @@ def _utf8_stdio() -> None:
290
290
  pass
291
291
 
292
292
 
293
+ def _doctor_browser(out: TextIO) -> int:
294
+ """stdin line 1: {headless, local_browser, launch, attach_port}; each way of starting the local browser, tried."""
295
+ from .browserdoctor import main_payload
296
+
297
+ line = sys.stdin.readline()
298
+ try:
299
+ payload = json.loads(line) if line.strip() else {}
300
+ except ValueError:
301
+ payload = {}
302
+ if not isinstance(payload, dict):
303
+ payload = {}
304
+
305
+ def emit(event: Dict[str, Any]) -> None:
306
+ out.write(json.dumps(event, ensure_ascii=False, default=str) + "\n")
307
+ out.flush()
308
+
309
+ try:
310
+ result = main_payload(payload, emit)
311
+ except Exception as e:
312
+ result = {"success": False, "error": str(e)}
313
+ emit({"type": "done", "result": result})
314
+ return 0 if result.get("success") else 1
315
+
316
+
293
317
  def main(argv: list[str] | None = None) -> int:
294
318
  args = list(sys.argv[1:] if argv is None else argv)
295
319
  _utf8_stdio()
@@ -298,6 +322,8 @@ def main(argv: list[str] | None = None) -> int:
298
322
  cmd = args[0] if args else "run"
299
323
  if cmd == "doctor":
300
324
  return _doctor(out)
325
+ if cmd == "doctor-browser":
326
+ return _doctor_browser(out)
301
327
  if cmd == "run":
302
328
  return _run(out)
303
329
  if cmd == "login":
@@ -308,7 +308,7 @@ async def interactive_login(payload: Dict[str, Any], emit: Any, finished: Any) -
308
308
  return {"success": False, "error": "A login with a url is required."}
309
309
  brand.install()
310
310
  stored = load_sessions(logins)
311
- candidates = [{**c, "storage_state": stored} if stored else c for c in local_launch_candidates(headless=False)]
311
+ candidates = [{**c, "storage_state": stored} if stored else c for c in local_launch_candidates(headless=False, choice=payload.get("local_browser"), method=payload.get("launch"), port=payload.get("attach_port"))]
312
312
 
313
313
  def fell_back(failed: Dict[str, Any], nxt: Dict[str, Any], reason: str) -> None:
314
314
  emit({"type": "log", "level": "warn", "text": f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}"})
@@ -0,0 +1,61 @@
1
+ // Starts a browser through Playwright for the ForgeQE engine (browser.launch: playwright, or auto after a direct start
2
+ // failed). The engine runs it with an argument list: <node or bun> pwlaunch.mjs <playwright-core index.mjs>.
3
+ // stdin, one JSON line: {executablePath?, channel?, headless, args, userDataDir, timeoutMs}.
4
+ // stdout, one JSON line: {port} once the browser's DevTools port is known, or {error}.
5
+ // The browser is closed when stdin ends (the engine closes it, or the engine has gone).
6
+ import { existsSync, readFileSync } from "node:fs"
7
+ import path from "node:path"
8
+ import readline from "node:readline"
9
+ import { pathToFileURL } from "node:url"
10
+
11
+ const entry = process.argv[2]
12
+ const say = (o) => process.stdout.write(`${JSON.stringify(o)}\n`)
13
+ let context = null
14
+ let closing = false
15
+
16
+ async function close(code) {
17
+ if (closing) return
18
+ closing = true
19
+ try {
20
+ await context?.close()
21
+ } catch {}
22
+ process.exit(code)
23
+ }
24
+
25
+ async function start(line) {
26
+ const req = JSON.parse(line)
27
+ const { chromium } = await import(pathToFileURL(entry).href)
28
+ const where = req.executablePath ? { executablePath: String(req.executablePath) } : req.channel ? { channel: String(req.channel) } : {}
29
+ context = await chromium.launchPersistentContext(String(req.userDataDir), {
30
+ ...where,
31
+ headless: req.headless === true,
32
+ // The same browser as a direct start, as a site sees it: no --enable-automation (navigator.webdriver true and the
33
+ // "controlled by automated test software" bar), and Chrome's sandbox kept on, which Playwright turns off unless
34
+ // told; on Linux as root Chrome cannot start with it, as a direct start finds too.
35
+ ignoreDefaultArgs: ["--enable-automation"],
36
+ chromiumSandbox: !(process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0),
37
+ // Port 0: the browser picks a free one and writes it to DevToolsActivePort in its profile folder.
38
+ // Playwright drives the browser over --remote-debugging-pipe, which makes Chrome report itself automated
39
+ // (navigator.webdriver true) as a direct start does not: AutomationControlled off keeps the two alike to a site,
40
+ // at the cost of Chrome's "unsupported command-line flag" bar in a visible window.
41
+ args: ["--remote-debugging-port=0", "--disable-blink-features=AutomationControlled", ...(Array.isArray(req.args) ? req.args.map(String) : [])],
42
+ // The engine sizes the page; Playwright's own 1280x720 emulation would fight it.
43
+ viewport: null,
44
+ timeout: Number(req.timeoutMs) || 90000,
45
+ })
46
+ const file = path.join(String(req.userDataDir), "DevToolsActivePort")
47
+ const until = Date.now() + 30000
48
+ while (!existsSync(file) && Date.now() < until) await new Promise((r) => setTimeout(r, 100))
49
+ const port = existsSync(file) ? Number(readFileSync(file, "utf8").split(/\r?\n/)[0]) : NaN
50
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("the browser started but wrote no DevTools port")
51
+ say({ port })
52
+ }
53
+
54
+ const lines = readline.createInterface({ input: process.stdin })
55
+ lines.once("line", (line) => {
56
+ start(line).catch((e) => {
57
+ say({ error: String((e && e.message) || e).split("\n")[0].slice(0, 500) })
58
+ void close(1)
59
+ })
60
+ })
61
+ lines.on("close", () => void close(0))