@capagents/forgeqe 2.10.4 → 3.0.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 (162) hide show
  1. package/HOW_TO_USE.md +119 -16
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/docs-site/docs/architecture/index.html +1 -0
  5. package/dist/docs-site/docs/cost-architecture/index.html +1 -1
  6. package/dist/docs-site/docs/index.html +158 -19
  7. package/dist/docs-site/docs/mobile/index.html +38 -2
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/forgeqe.js +2121 -1947
  10. package/dist/web/assets/Agent-DISh0THc.js +8 -0
  11. package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
  12. package/dist/web/assets/Browse-WylAQZvD.js +2 -0
  13. package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
  14. package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
  15. package/dist/web/assets/Compare-CgOfZofk.js +1 -0
  16. package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
  17. package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
  18. package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
  19. package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
  20. package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
  21. package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
  22. package/dist/web/assets/Features-DXL_vSjn.js +1 -0
  23. package/dist/web/assets/Flags-B7x2pDud.js +2 -0
  24. package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
  25. package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
  26. package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
  27. package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
  28. package/dist/web/assets/Migration-BOLN1duU.js +2 -0
  29. package/dist/web/assets/Product-C0FeEaJg.js +7 -0
  30. package/dist/web/assets/Production-BSMQyWKd.js +1 -0
  31. package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
  32. package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
  33. package/dist/web/assets/Record-CPx-lK53.js +2 -0
  34. package/dist/web/assets/Regression-BXbX46nO.js +5 -0
  35. package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
  36. package/dist/web/assets/Reports-36YQzVhA.js +2 -0
  37. package/dist/web/assets/Response-DplUOsue.js +4 -0
  38. package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
  39. package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
  40. package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
  41. package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
  42. package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
  43. package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
  44. package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
  45. package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
  46. package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
  47. package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
  48. package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
  49. package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
  50. package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
  51. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  52. package/dist/web/assets/fold-BhRpA0sy.js +1 -0
  53. package/dist/web/assets/frame-D_TPoUTD.js +16 -0
  54. package/dist/web/assets/index-BRB-oAMd.js +67 -0
  55. package/dist/web/assets/index-CIw5WfL8.css +2 -0
  56. package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
  57. package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
  58. package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
  59. package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
  60. package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
  61. package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
  62. package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
  63. package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
  64. package/dist/web/assets/rows-uLoguIo5.js +1 -0
  65. package/dist/web/assets/segmented-DphDskQz.js +1 -0
  66. package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
  67. package/dist/web/index.html +6 -6
  68. package/docs/ARCHITECTURE.md +1 -0
  69. package/docs/COST_ARCHITECTURE.md +1 -1
  70. package/docs/MOBILE.md +40 -0
  71. package/docs/user-guide.html +158 -19
  72. package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
  73. package/forgeqe.example.yaml +11 -1
  74. package/package.json +4 -1
  75. package/prompts/brain.md +4 -0
  76. package/prompts/browser-goal-verification.md +2 -0
  77. package/prompts/refine.md +2 -0
  78. package/prompts/requests-rule.md +1 -1
  79. package/prompts/talk-summary.md +43 -0
  80. package/prompts/talk.md +49 -0
  81. package/prompts/test-agent.md +1 -0
  82. package/prompts/test-reviewer.md +2 -1
  83. package/prompts/test-rules.md +3 -0
  84. package/py/forgeqe_data/__init__.py +1 -0
  85. package/py/forgeqe_data/__main__.py +12 -0
  86. package/py/forgeqe_data/connect.py +290 -0
  87. package/py/forgeqe_data/connstr.py +169 -0
  88. package/py/forgeqe_data/flows.py +603 -0
  89. package/py/forgeqe_data/guard.py +214 -0
  90. package/py/forgeqe_data/mongo.py +219 -0
  91. package/py/forgeqe_data/schema.py +431 -0
  92. package/py/forgeqe_data/service.py +651 -0
  93. package/py/forgeqe_data/streams.py +400 -0
  94. package/py/forgeqe_data/subset.py +299 -0
  95. package/py/forgeqe_data/testdata.py +861 -0
  96. package/py/forgeqe_data/vector.py +113 -0
  97. package/py/forgeqe_desktop/workflow.py +6 -4
  98. package/py/forgeqe_engine/capture.py +5 -4
  99. package/py/forgeqe_engine/diagnostics.py +2 -2
  100. package/py/forgeqe_engine/lenient_json.py +96 -0
  101. package/py/forgeqe_engine/llm.py +4 -0
  102. package/py/forgeqe_engine/network.py +93 -15
  103. package/py/forgeqe_engine/neutral_log.py +16 -1
  104. package/py/forgeqe_engine/recordsession.py +54 -1
  105. package/py/forgeqe_engine/service.py +22 -3
  106. package/py/forgeqe_mobile/appium_driver.py +9 -0
  107. package/py/forgeqe_mobile/apps.py +4 -0
  108. package/py/forgeqe_mobile/maestro.py +3 -0
  109. package/py/forgeqe_mobile/record.py +610 -0
  110. package/py/forgeqe_mobile/service.py +37 -7
  111. package/py/forgeqe_talk/__init__.py +1 -0
  112. package/py/forgeqe_talk/__main__.py +65 -0
  113. package/py/forgeqe_voice/worker.py +141 -0
  114. package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
  115. package/skills/playwright-typescript/SKILL.md +1 -1
  116. package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
  117. package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
  118. package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
  119. package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
  120. package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
  121. package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
  122. package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
  123. package/dist/web/assets/Data-BWTme_Yw.js +0 -6
  124. package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
  125. package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
  126. package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
  127. package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
  128. package/dist/web/assets/Features-DazEWqYu.js +0 -1
  129. package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
  130. package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
  131. package/dist/web/assets/Impact-De87sv5J.js +0 -3
  132. package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
  133. package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
  134. package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
  135. package/dist/web/assets/Product-DpK-PIxV.js +0 -7
  136. package/dist/web/assets/Production-D6A89rZZ.js +0 -1
  137. package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
  138. package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
  139. package/dist/web/assets/Record-DcgBatJJ.js +0 -2
  140. package/dist/web/assets/Regression-BJLYrqST.js +0 -5
  141. package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
  142. package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
  143. package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
  144. package/dist/web/assets/Runs-lb78rvPV.js +0 -2
  145. package/dist/web/assets/Steps-BDSeIznj.js +0 -2
  146. package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
  147. package/dist/web/assets/TestData-DP7cvW48.js +0 -2
  148. package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
  149. package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
  150. package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
  151. package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
  152. package/dist/web/assets/filters-CflRmNDz.js +0 -1
  153. package/dist/web/assets/fold-pOBiaSlF.js +0 -1
  154. package/dist/web/assets/frame-CYYiRu5P.js +0 -4
  155. package/dist/web/assets/index-CNDoTeRV.css +0 -2
  156. package/dist/web/assets/index-D4a0w3Vl.js +0 -67
  157. package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
  158. package/dist/web/assets/parts-C53RxMcR.js +0 -1
  159. package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
  160. package/dist/web/assets/rows-D6rPRkHl.js +0 -1
  161. package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
  162. package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
@@ -0,0 +1,113 @@
1
+ """
2
+ DB-GPT's schema index for a database marked ``vector: true``: a summary of every table (its columns, keys and comment)
3
+ embedded and stored in Chroma, and DB-GPT's retriever to find the tables a question is about.
4
+
5
+ The summaries come from the cached catalog (catalog_connector), so building the index sends no query to the database.
6
+ The embedding model is chromadb's all-MiniLM-L6-v2 in ONNX, run on this machine: nothing leaves it, and chromadb checks
7
+ the model's SHA-256 when it downloads it (once, into ~/.forgeqe/data/models).
8
+
9
+ On real schemas this small model ranks tables less well than the word linking in schema.py (measured on an Odoo
10
+ database of 938 tables), so its hits are extra candidates for schema.link, never a replacement.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import shutil
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List, Mapping
19
+
20
+ TOP_K = 10
21
+
22
+
23
+ def _models_dir() -> Path:
24
+ return Path(os.environ.get("FORGEQE_HOME") or Path.home() / ".forgeqe") / "data" / "models" / "all-MiniLM-L6-v2"
25
+
26
+
27
+ class _CatalogConnector:
28
+ """What DB-GPT's table summaries ask of a connector, answered from the catalog: no database round trips."""
29
+
30
+ db_type = "catalog"
31
+
32
+ def __init__(self, catalog: Mapping[str, Any]) -> None:
33
+ self.tables = catalog.get("tables") or {}
34
+
35
+ def get_table_names(self) -> List[str]:
36
+ return list(self.tables)
37
+
38
+ def get_columns(self, table: str) -> List[Dict[str, Any]]:
39
+ return [{"name": c["name"], "type": c["type"], "comment": c.get("comment")} for c in self.tables[table]["columns"]]
40
+
41
+ def get_indexes(self, table: str) -> List[Dict[str, Any]]:
42
+ return [{"name": f"unique_{i}", "column_names": cols} for i, cols in enumerate(self.tables[table].get("unique") or [])]
43
+
44
+ def get_table_comment(self, table: str) -> Dict[str, str]:
45
+ return {"text": self.tables[table].get("comment") or ""}
46
+
47
+ def is_graph_type(self) -> bool:
48
+ return False
49
+
50
+
51
+ def _embeddings() -> Any:
52
+ from chromadb.utils.embedding_functions import ONNXMiniLM_L6_V2
53
+ from dbgpt.core import Embeddings
54
+
55
+ model = ONNXMiniLM_L6_V2()
56
+ model.DOWNLOAD_PATH = _models_dir()
57
+
58
+ class LocalEmbeddings(Embeddings):
59
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
60
+ return [[float(x) for x in v] for v in model(texts)]
61
+
62
+ def embed_query(self, text: str) -> List[float]:
63
+ return self.embed_documents([text])[0]
64
+
65
+ return LocalEmbeddings()
66
+
67
+
68
+ def _stores(folder: Path, embeddings: Any) -> Any:
69
+ from dbgpt_ext.storage.vector_store.chroma_store import ChromaStore, ChromaVectorConfig
70
+
71
+ cfg = ChromaVectorConfig(persist_path=str(folder))
72
+ return ChromaStore(cfg, name="tables", embedding_fn=embeddings), ChromaStore(cfg, name="fields", embedding_fn=embeddings)
73
+
74
+
75
+ def _meta(folder: Path) -> Dict[str, Any]:
76
+ try:
77
+ return json.loads((folder / "index.json").read_text(encoding="utf-8"))
78
+ except (OSError, ValueError):
79
+ return {}
80
+
81
+
82
+ def ensure(catalog: Mapping[str, Any], folder: Path, log: Any = lambda _: None) -> None:
83
+ """The index for this catalog, built when there is none or the catalog was read again since."""
84
+ if _meta(folder).get("catalog_read_at") == catalog.get("read_at") and (folder / "chromadb").exists():
85
+ return
86
+ from dbgpt_ext.rag.assembler.db_schema import DBSchemaAssembler
87
+
88
+ shutil.rmtree(folder, ignore_errors=True)
89
+ folder.mkdir(parents=True, exist_ok=True)
90
+ count = len(catalog.get("tables") or {})
91
+ log(f"Building the schema index of {count} tables (DB-GPT, a local embedding model; once per schema change).")
92
+ embeddings = _embeddings()
93
+ tables, fields = _stores(folder, embeddings)
94
+ DBSchemaAssembler.load_from_connection(
95
+ connector=_CatalogConnector(catalog), table_vector_store_connector=tables, field_vector_store_connector=fields, embeddings=embeddings
96
+ ).persist()
97
+ (folder / "index.json").write_text(json.dumps({"catalog_read_at": catalog.get("read_at"), "tables": count}), encoding="utf-8")
98
+
99
+
100
+ def search(catalog: Mapping[str, Any], folder: Path, question: str, k: int = TOP_K, log: Any = lambda _: None) -> List[str]:
101
+ """The tables DB-GPT's retriever ranks highest for a question, best first."""
102
+ from dbgpt_ext.rag.retriever.db_schema import DBSchemaRetriever
103
+
104
+ ensure(catalog, folder, log)
105
+ tables, fields = _stores(folder, _embeddings())
106
+ retriever = DBSchemaRetriever(table_vector_store_connector=tables, field_vector_store_connector=fields, top_k=k, separator="--table-field-separator--")
107
+ known = catalog.get("tables") or {}
108
+ hits: List[str] = []
109
+ for chunk in retriever.retrieve(question):
110
+ name = (chunk.metadata or {}).get("table_name")
111
+ if name in known and name not in hits:
112
+ hits.append(name)
113
+ return hits
@@ -34,9 +34,9 @@ MAX_DISMISS = 10
34
34
  RETRY_OPS = ("click", "double_click", "type", "select", "keys", "expect", "expect_image")
35
35
  TIMEOUT_OPS = ("launch", *TARGET_OPS, "expect_image", "long_press", "double_tap", "tap", "scroll_to", "drag")
36
36
 
37
- MOBILE_OPS = ("launch", "tap", "double_tap", "long_press", "type", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "back", "hide_keyboard", "keys", "wait", "wait_for", "close")
38
- MOBILE_TARGET_OPS = ("tap", "double_tap", "long_press", "type", "expect", "wait_for", "scroll_to", "drag")
39
- MOBILE_RETRY_OPS = ("tap", "double_tap", "long_press", "type", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "keys")
37
+ MOBILE_OPS = ("launch", "tap", "double_tap", "long_press", "type", "select", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "back", "hide_keyboard", "keys", "wait", "wait_for", "close")
38
+ MOBILE_TARGET_OPS = ("tap", "double_tap", "long_press", "type", "select", "expect", "wait_for", "scroll_to", "drag")
39
+ MOBILE_RETRY_OPS = ("tap", "double_tap", "long_press", "type", "select", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "keys")
40
40
  MOBILE_KEYS = ("enter", "back", "tab", "delete", "search")
41
41
  SWIPE_DIRECTIONS = ("up", "down", "left", "right")
42
42
  _MOBILE_STEP_KEYS = {
@@ -45,6 +45,8 @@ _MOBILE_STEP_KEYS = {
45
45
  "double_tap": {"target"},
46
46
  "long_press": {"target"},
47
47
  "type": {"target", "text"},
48
+ # Opens the target (a drop-down) and picks the item that shows `value`.
49
+ "select": {"target", "value"},
48
50
  "expect": {"target", "text"},
49
51
  "expect_image": {"target", "image", "tolerance", "ignore"},
50
52
  "swipe": {"direction", "target"},
@@ -60,7 +62,7 @@ _MOBILE_STEP_KEYS = {
60
62
  "wait_for": {"target", "text", "gone"},
61
63
  "close": set(),
62
64
  }
63
- _MOBILE_REQUIRED = {"type": {"target", "text"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}, "swipe": {"direction"}, "scroll": {"direction"}, "drag": {"target", "to"}}
65
+ _MOBILE_REQUIRED = {"type": {"target", "text"}, "select": {"target", "value"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}, "swipe": {"direction"}, "scroll": {"direction"}, "drag": {"target", "to"}}
64
66
  IMAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,99}\.png$")
65
67
  MAX_IGNORE = 20
66
68
 
@@ -222,14 +222,14 @@ _VERIFY_FN = r"""function(locs) {
222
222
  const el = this;
223
223
  const norm = (s) => String(s || '').replace(/\s+/g, ' ').trim();
224
224
  const q = (v) => '"' + String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
225
- const visible = (e) => e.getClientRects().length > 0;
226
225
  // The document and its open shadow roots, as Playwright's CSS and text locators search them (web components).
227
226
  const roots = [document];
228
227
  for (let i = 0; i < roots.length && roots.length < 500; i++) for (const x of roots[i].querySelectorAll('*')) if (x.shadowRoot) roots.push(x.shadowRoot);
229
228
  const all = (sel) => roots.flatMap((r) => [...r.querySelectorAll(r === document && sel === '*' ? 'body *' : sel)]);
230
229
  const up = (e) => e.parentElement || (e.parentNode && e.parentNode.nodeType === 11 && e.parentNode.host) || null;
231
230
  const within = (a, b) => { for (let x = b; x; x = up(x)) if (x === a) return true; return false; };
232
- const byText = (t) => all('*').filter((e) => visible(e) && norm(e.textContent) === t && ![...e.children].some((c) => norm(c.textContent) === t));
231
+ // Hidden elements too, as Playwright's text locators find them (and its strict mode counts them); never a script's.
232
+ const byText = (t) => all('*').filter((e) => !['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE'].includes(e.tagName) && norm(e.textContent) === t && ![...e.children].some((c) => norm(c.textContent) === t));
233
233
  const find = (l) => {
234
234
  switch (l.type) {
235
235
  case 'xpath': {
@@ -248,8 +248,9 @@ _VERIFY_FN = r"""function(locs) {
248
248
  try {
249
249
  const all = find(l);
250
250
  if (!all) return null;
251
- const hits = all.filter(visible).length ? all.filter(visible) : all;
252
- return { count: hits.length, target: hits.length === 1 && (hits[0] === el || within(el, hits[0])) };
251
+ // Every match, hidden ones too: Playwright's strict mode counts them, so a locator with a hidden copy (a
252
+ // consent tool's second "Accept all" in a closed menu) throws on click though one match shows.
253
+ return { count: all.length, target: all.length === 1 && (all[0] === el || within(el, all[0])) };
253
254
  } catch (e) { return { count: -1, target: false }; }
254
255
  });
255
256
  // What Playwright's getByRole reads for the element's role: its tag, href and role attribute.
@@ -276,7 +276,7 @@ def box_for(browser_state: Any, index: Any) -> Optional[Dict[str, float]]:
276
276
 
277
277
 
278
278
  class Diagnostics:
279
- def __init__(self, *, accessibility: bool = True, network: bool = True, axe: Optional[Dict[str, Any]] = None, vitals: bool = True, visual: Optional[Dict[str, Any]] = None) -> None:
279
+ def __init__(self, *, accessibility: bool = True, network: bool = True, axe: Optional[Dict[str, Any]] = None, vitals: bool = True, visual: Optional[Dict[str, Any]] = None, keep_headers: Optional[List[str]] = None) -> None:
280
280
  self.accessibility = accessibility
281
281
  # axe-core: {"script": path to axe.min.js, "tags": ["wcag2a", "wcag2aa"]}; without it, the built-in checks.
282
282
  self.axe_tags: List[str] = [str(t) for t in ((axe or {}).get("tags") or ["wcag2a", "wcag2aa"])]
@@ -292,7 +292,7 @@ class Diagnostics:
292
292
  self.visual: Optional[Dict[str, Any]] = visual
293
293
  self.shots: Dict[str, Dict[str, Any]] = {}
294
294
  self.timeout = CHECK_TIMEOUT * (3 if self._axe_source else 1)
295
- self.network: Optional[NetworkCapture] = NetworkCapture() if network else None
295
+ self.network: Optional[NetworkCapture] = NetworkCapture(keep_headers) if network else None
296
296
  self._net_handlers: Dict[str, Any] = {}
297
297
  self.events: List[Dict[str, Any]] = []
298
298
  self.pages: Dict[str, Dict[str, Any]] = {}
@@ -0,0 +1,96 @@
1
+ """
2
+ A model's structured reply with words around it: some models behind an OpenAI-compatible gateway (GitHub Copilot's
3
+ gpt-6-luna) write a sentence before the JSON the step asked for, and browser_use refuses the whole reply as invalid
4
+ JSON. A real run lost six steps that way and gave up at a sign-in code screen. The step's own model class is given a
5
+ reader that, when the reply is not JSON as it is, takes the JSON object out of it and checks that against the same
6
+ schema; anything else is refused as before.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from typing import Any, Dict, Optional
14
+
15
+ _FENCE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL | re.IGNORECASE)
16
+ _MAX_TEXT = 2_000_000
17
+
18
+
19
+ def json_in(text: Any) -> Optional[str]:
20
+ """
21
+ The JSON object in a reply that is not JSON as it is: a ```json block first, else the longest object found from any
22
+ "{", so braces in the words before it do not count. None when there is none.
23
+ """
24
+ if isinstance(text, (bytes, bytearray)):
25
+ try:
26
+ text = text.decode("utf-8")
27
+ except UnicodeDecodeError:
28
+ return None
29
+ if not isinstance(text, str) or len(text) > _MAX_TEXT:
30
+ return None
31
+ fenced = _FENCE.search(text)
32
+ if fenced:
33
+ try:
34
+ if isinstance(json.loads(fenced.group(1)), dict):
35
+ return fenced.group(1)
36
+ except ValueError:
37
+ pass
38
+ decoder = json.JSONDecoder()
39
+ best: Optional[str] = None
40
+ i = text.find("{")
41
+ while i != -1:
42
+ try:
43
+ obj, end = decoder.raw_decode(text, i)
44
+ except ValueError:
45
+ obj, end = None, i
46
+ if isinstance(obj, dict) and (best is None or end - i > len(best)):
47
+ best = text[i:end]
48
+ i = text.find("{", i + 1)
49
+ return best
50
+
51
+
52
+ _LENIENT: Dict[type, type] = {}
53
+
54
+
55
+ def lenient(output_format: Any) -> Any:
56
+ """
57
+ The step's pydantic model class with a reader that also takes a reply's JSON object out of words around it. The
58
+ schema sent to the model is the same (same name and fields). Anything that is not a pydantic model is given back.
59
+ """
60
+ try:
61
+ from pydantic import BaseModel, ValidationError
62
+ except ImportError: # pragma: no cover - the engine always has pydantic
63
+ return output_format
64
+ if not isinstance(output_format, type) or not issubclass(output_format, BaseModel):
65
+ return output_format
66
+ if output_format in _LENIENT or getattr(output_format, "__forgeqe_lenient__", False):
67
+ return _LENIENT.get(output_format, output_format)
68
+
69
+ base = output_format
70
+
71
+ def model_validate_json(cls: Any, json_data: Any, *args: Any, **kwargs: Any) -> Any:
72
+ try:
73
+ return super(made, cls).model_validate_json(json_data, *args, **kwargs)
74
+ except ValidationError:
75
+ found = json_in(json_data)
76
+ if found is None or found == json_data:
77
+ raise
78
+ try:
79
+ return super(made, cls).model_validate_json(found, *args, **kwargs)
80
+ except ValidationError:
81
+ pass
82
+ raise
83
+
84
+ made = type(
85
+ base.__name__,
86
+ (base,),
87
+ {
88
+ "__module__": base.__module__,
89
+ "__qualname__": base.__qualname__,
90
+ "__doc__": base.__doc__,
91
+ "__forgeqe_lenient__": True,
92
+ "model_validate_json": classmethod(model_validate_json),
93
+ },
94
+ )
95
+ _LENIENT[base] = made
96
+ return made
@@ -164,6 +164,7 @@ def _adaptive(cfg: Dict[str, Any], llm: Any) -> Any:
164
164
  that parameter off and sends the step again.
165
165
  """
166
166
  from .model_params import MAX_ADJUSTMENTS, is_reasoning, refused_parameters
167
+ from .lenient_json import lenient
167
168
 
168
169
  said = cfg.get("reasoning")
169
170
  if said is False:
@@ -173,6 +174,9 @@ def _adaptive(cfg: Dict[str, Any], llm: Any) -> Any:
173
174
  original = llm.ainvoke
174
175
 
175
176
  async def ainvoke(messages: Any, output_format: Any = None, **kwargs: Any) -> Any:
177
+ # A reply with words before its JSON is read for the JSON in it (lenient_json), not refused as a whole.
178
+ if output_format is not None:
179
+ output_format = lenient(output_format)
176
180
  for attempt in range(MAX_ADJUSTMENTS + 1):
177
181
  try:
178
182
  return await original(messages, output_format, **kwargs)
@@ -16,8 +16,8 @@ import logging
16
16
  import re
17
17
  import time
18
18
  from pathlib import Path
19
- from typing import Any, Dict, List, Optional
20
- from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
19
+ from typing import Any, Awaitable, Callable, Dict, Iterable, List, Optional
20
+ from urllib.parse import parse_qsl, quote, quote_plus, urlencode, urlsplit, urlunsplit
21
21
 
22
22
  logger = logging.getLogger(__name__)
23
23
 
@@ -26,10 +26,32 @@ MAX_BODY = 64_000
26
26
  API_TYPES = {"XHR", "Fetch", "EventSource"}
27
27
  TEXT_MIME = re.compile(r"json|xml|text/|graphql|x-www-form-urlencoded|grpc-web-text", re.I)
28
28
  SECRET_NAME = re.compile(
29
- r"pass(word|wd|phrase)?$|secret|token|api[-_]?key|auth|cookie|session|^sid$|otp|^pin$|cvv|cvc|card.?number|^pan$|ssn|private[-_]?key|signature",
29
+ r"pass(word|wd|phrase|code)?$|^pwd$|secret|token|api[-_]?key|auth|cookie|session|^sid$|otp|^pin$|cvv|cvc|card.?number|^pan$|ssn|private[-_]?key|signature|credential",
30
30
  re.I,
31
31
  )
32
32
  KEEP_HEADERS = {"content-type", "accept", "soapaction", "x-requested-with", "grpc-status", "grpc-message", "x-grpc-web", "x-apollo-operation-name"}
33
+ # Headers that carry a credential: never kept, whatever api.keep_headers asks for.
34
+ NEVER_HEADERS = frozenset({"authorization", "proxy-authorization", "cookie", "set-cookie"})
35
+ HEADER_NAME = re.compile(r"^[a-z0-9][a-z0-9-]{0,59}$")
36
+ MAX_EXTRA_HEADERS = 20
37
+
38
+
39
+ def extra_headers(raw: Any) -> frozenset:
40
+ """
41
+ The headers api.keep_headers adds to KEEP_HEADERS (a tenant, a correlation id), read as untrusted: plain header
42
+ names only, lower-cased, at most MAX_EXTRA_HEADERS, and never one that carries a credential (NEVER_HEADERS, or a
43
+ name like a password, token, key or session).
44
+ """
45
+ if not isinstance(raw, (list, tuple)):
46
+ return frozenset()
47
+ out = set()
48
+ for v in raw[:MAX_EXTRA_HEADERS]:
49
+ name = str(v).strip().lower() if isinstance(v, str) else ""
50
+ if HEADER_NAME.match(name) and name not in NEVER_HEADERS and not SECRET_NAME.search(name):
51
+ out.add(name)
52
+ return frozenset(out)
53
+
54
+
33
55
  TRACKERS = re.compile(
34
56
  r"google-analytics|googletagmanager|doubleclick|googlesyndication|facebook\.(com|net)|segment\.(io|com)|hotjar|sentry\.io|"
35
57
  r"newrelic|nr-data|datadoghq|clarity\.ms|mixpanel|amplitude|intercom|fullstory|launchdarkly|optimizely|bugsnag|appdynamics|"
@@ -89,6 +111,41 @@ def redact_body(text: str, mime: str) -> str:
89
111
  return text
90
112
 
91
113
 
114
+ # A CDP call: method ("Network.getResponseBody"), params, session id.
115
+ Send = Callable[[str, Dict[str, Any], Optional[str]], Awaitable[Any]]
116
+
117
+
118
+ def client_send(client: Any) -> Send:
119
+ """A CDP call through a cdp_use client, as NetworkCapture reads bodies with."""
120
+
121
+ async def send(method: str, params: Dict[str, Any], sid: Optional[str]) -> Any:
122
+ domain, name = method.split(".", 1)
123
+ return await getattr(getattr(client.send, domain), name)(params=params, session_id=sid)
124
+
125
+ return send
126
+
127
+
128
+ def value_forms(values: Iterable[str]) -> List[str]:
129
+ """
130
+ Each known secret value as it can appear in a call: as typed, inside a JSON string, and URL-encoded (%20 and +),
131
+ longest first. Values shorter than 4 characters are left out: replacing them would wipe ordinary text.
132
+ """
133
+ forms: set = set()
134
+ for v in values:
135
+ v = str(v or "")
136
+ if len(v) < 4:
137
+ continue
138
+ forms.update({v, json.dumps(v, ensure_ascii=False)[1:-1], json.dumps(v)[1:-1], quote(v, safe=""), quote_plus(v, safe="")})
139
+ return sorted((f for f in forms if f), key=len, reverse=True)
140
+
141
+
142
+ def scrub_text(text: str, forms: List[str]) -> str:
143
+ for f in forms:
144
+ if f in text:
145
+ text = text.replace(f, REDACTED)
146
+ return text
147
+
148
+
92
149
  def auth_kind(headers: Dict[str, Any]) -> Optional[Dict[str, str]]:
93
150
  """How the request authenticated, without the credential: bearer, basic, cookie, or the API key header's name."""
94
151
  low = {str(k).lower(): str(v) for k, v in (headers or {}).items()}
@@ -132,7 +189,9 @@ def _site(host: str) -> str:
132
189
 
133
190
 
134
191
  class NetworkCapture:
135
- def __init__(self) -> None:
192
+ def __init__(self, keep_headers: Any = None) -> None:
193
+ # The headers kept on each call: KEEP_HEADERS and the ones api.keep_headers adds (extra_headers).
194
+ self.keep = KEEP_HEADERS | extra_headers(keep_headers)
136
195
  self.calls: List[Dict[str, Any]] = []
137
196
  self._pending: Dict[str, Dict[str, Any]] = {}
138
197
  self._tasks: List[asyncio.Task[Any]] = []
@@ -183,7 +242,7 @@ class NetworkCapture:
183
242
  "method": str(req.get("method") or "GET"),
184
243
  "url": redact_query(str(req.get("url") or "")),
185
244
  "type": str(params.get("type")),
186
- "request": {"headers": {k: v for k, v in headers.items() if str(k).lower() in KEEP_HEADERS}},
245
+ "request": {"headers": {k: str(v)[:500] for k, v in headers.items() if str(k).lower() in self.keep}},
187
246
  "_ts": float(params.get("timestamp") or 0),
188
247
  "_session": session_id,
189
248
  "_has_post": bool(req.get("hasPostData")),
@@ -226,7 +285,7 @@ class NetworkCapture:
226
285
  if call is None:
227
286
  return
228
287
  res = params.get("response") or {}
229
- headers = {k: v for k, v in (res.get("headers") or {}).items() if str(k).lower() in KEEP_HEADERS}
288
+ headers = {k: str(v)[:500] for k, v in (res.get("headers") or {}).items() if str(k).lower() in self.keep}
230
289
  call["response"] = {"status": int(res.get("status") or 0), "mime": str(res.get("mimeType") or ""), "headers": headers}
231
290
  except Exception:
232
291
  logger.debug("response not recorded", exc_info=True)
@@ -238,7 +297,7 @@ class NetworkCapture:
238
297
  except Exception:
239
298
  logger.debug("cookies not recorded", exc_info=True)
240
299
 
241
- def on_finished(self, params: Any, session_id: Optional[str] = None, client: Any = None) -> None:
300
+ def on_finished(self, params: Any, session_id: Optional[str] = None, client: Any = None, send: Optional[Send] = None) -> None:
242
301
  call = self._pending.pop(str(params.get("requestId")), None)
243
302
  if call is None:
244
303
  return
@@ -247,9 +306,11 @@ class NetworkCapture:
247
306
  call.setdefault("response", {"status": 0, "mime": "", "headers": {}})
248
307
  call["response"]["size"] = int(params.get("encodedDataLength") or 0)
249
308
  self.calls.append(call)
250
- if client is not None:
309
+ if send is None and client is not None:
310
+ send = client_send(client)
311
+ if send is not None:
251
312
  # Bodies are fetched off the event loop: waiting for a reply inside an event handler would block the handler's own reader.
252
- self._tasks.append(asyncio.ensure_future(self._bodies(client, str(params.get("requestId")), call)))
313
+ self._tasks.append(asyncio.ensure_future(self._bodies(send, str(params.get("requestId")), call)))
253
314
 
254
315
  def on_failed(self, params: Any, session_id: Optional[str] = None) -> None:
255
316
  call = self._pending.pop(str(params.get("requestId")), None)
@@ -259,11 +320,11 @@ class NetworkCapture:
259
320
  call.setdefault("response", {"status": 0, "mime": "", "headers": {}})
260
321
  self.calls.append(call)
261
322
 
262
- async def _bodies(self, client: Any, request_id: str, call: Dict[str, Any]) -> None:
323
+ async def _bodies(self, send: Send, request_id: str, call: Dict[str, Any]) -> None:
263
324
  sid = call.get("_session")
264
325
  try:
265
326
  if call["_has_post"] and "body" not in call["request"]:
266
- r = await client.send.Network.getRequestPostData(params={"requestId": request_id}, session_id=sid)
327
+ r = await send("Network.getRequestPostData", {"requestId": request_id}, sid)
267
328
  post = str((r or {}).get("postData") or "")
268
329
  mime = str(call["request"]["headers"].get("Content-Type") or call["request"]["headers"].get("content-type") or "")
269
330
  if post:
@@ -274,7 +335,7 @@ class NetworkCapture:
274
335
  if not TEXT_MIME.search(res.get("mime") or "") or res.get("size", 0) > MAX_BODY * 4:
275
336
  return
276
337
  try:
277
- r = await client.send.Network.getResponseBody(params={"requestId": request_id}, session_id=sid)
338
+ r = await send("Network.getResponseBody", {"requestId": request_id}, sid)
278
339
  if (r or {}).get("base64Encoded"):
279
340
  return
280
341
  body = str((r or {}).get("body") or "")
@@ -289,8 +350,24 @@ class NetworkCapture:
289
350
  if pending:
290
351
  await asyncio.wait(pending, timeout=timeout)
291
352
 
292
- def write(self, out_dir: Path) -> Optional[str]:
293
- if not self.calls and not self.documents:
353
+ def scrub(self, values: Iterable[str]) -> None:
354
+ """Every known secret value (a saved login's), wherever it is in a call: its address, page and both bodies."""
355
+ forms = value_forms(values)
356
+ if not forms:
357
+ return
358
+ for c in self.calls:
359
+ for k in ("url", "page"):
360
+ if isinstance(c.get(k), str):
361
+ c[k] = scrub_text(c[k], forms)
362
+ for part in (c.get("request") or {}, c.get("response") or {}):
363
+ if isinstance(part.get("body"), str):
364
+ part["body"] = scrub_text(part["body"], forms)
365
+ if isinstance(part.get("headers"), dict):
366
+ part["headers"] = {k: scrub_text(str(v), forms) for k, v in part["headers"].items()}
367
+
368
+ def write(self, out_dir: Path, documents: bool = True) -> Optional[str]:
369
+ """network.json in out_dir; without ``documents`` (a recording) the security part is left out."""
370
+ if not self.calls and not (documents and self.documents):
294
371
  return None
295
372
  calls = [{k: v for k, v in c.items() if not k.startswith("_")} for c in sorted(self.calls, key=lambda c: c["t"])]
296
373
  file = out_dir / "network.json"
@@ -300,7 +377,8 @@ class NetworkCapture:
300
377
  "insecure": self.insecure,
301
378
  "cookies": list(self.cookies.values()),
302
379
  }
303
- file.write_text(json.dumps({"version": 1, "calls": calls, **({"dropped": self.dropped} if self.dropped else {}), "security": security}, indent=1, ensure_ascii=False), encoding="utf-8")
380
+ doc = {"version": 1, "calls": calls, **({"dropped": self.dropped} if self.dropped else {}), **({"security": security} if documents else {})}
381
+ file.write_text(json.dumps(doc, indent=1, ensure_ascii=False), encoding="utf-8")
304
382
  return str(file.resolve())
305
383
 
306
384
 
@@ -3,7 +3,8 @@ Log records in ForgeQE's own words: the engine's browser library names itself in
3
3
  and in some messages ("Starting a browser-use agent", links to its project). The engine's log reaches people (the
4
4
  terminal, a failed run's error, the session log), so each record is reworded as it is made: the library's logger
5
5
  names become "engine...", its name in a message becomes "engine", and a message that only points at its project
6
- (an issue tracker, its docs, its cloud) loses that link.
6
+ (an issue tracker, its docs, its cloud) loses that link. A saved browser session the library prints (its
7
+ storage_state, with every cookie and its value: a signed-in session to the person's sites) is never repeated.
7
8
  """
8
9
  from __future__ import annotations
9
10
 
@@ -14,6 +15,9 @@ from typing import Any
14
15
  _LIBRARY = "browser_use"
15
16
  _PROJECT_LINK = re.compile(r"\s*\(?\bhttps?://(?:[\w.-]*\.)?(?:github\.com/browser-use|browser-use\.com)\S*\)?", re.IGNORECASE)
16
17
  _NAME = re.compile(r"\bbrowser[-_ ]?use\b", re.IGNORECASE)
18
+ # A session's contents as the library prints them: storage_state=..., or a cookie's value, to the end of the line.
19
+ _SESSION = re.compile(r"(\bstorage_state\s*[=:]\s*)(?=[{\[(\'\"]).*", re.IGNORECASE)
20
+ _COOKIE_VALUE = re.compile(r"""(['"]value['"]\s*:\s*)(['"]).*?(?<!\\)\2""")
17
21
 
18
22
  _installed = False
19
23
 
@@ -32,6 +36,9 @@ def neutral_name(name: str) -> str:
32
36
 
33
37
 
34
38
  def neutral_text(text: str) -> str:
39
+ text = _SESSION.sub(r"\1<hidden: a saved session>", text)
40
+ if "cookie" in text.lower():
41
+ text = _COOKIE_VALUE.sub(r"\1\2<hidden>\2", text)
35
42
  return _NAME.sub("engine", _PROJECT_LINK.sub("", text))
36
43
 
37
44
 
@@ -56,6 +63,14 @@ def install() -> None:
56
63
  record.args = tuple(_neutral_arg(a) for a in record.args)
57
64
  elif isinstance(record.args, dict):
58
65
  record.args = {k: _neutral_arg(v) for k, v in record.args.items()}
66
+ # A session passed as an argument (a dict, not text) is only seen once the message is made: made here, hidden.
67
+ if record.args:
68
+ try:
69
+ made = record.getMessage()
70
+ except Exception:
71
+ made = ""
72
+ if made and (_SESSION.search(made) or ("cookie" in made.lower() and _COOKIE_VALUE.search(made))):
73
+ record.msg, record.args = neutral_text(made), ()
59
74
  return record
60
75
 
61
76
  logging.setLogRecordFactory(factory)