@capagents/forgeqe 2.10.3 → 2.10.5
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.
- package/HOW_TO_USE.md +36 -7
- package/README.md +1 -1
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/dist/docs-site/docs/architecture/index.html +1 -0
- package/dist/docs-site/docs/cost-architecture/index.html +1 -1
- package/dist/docs-site/docs/index.html +91 -14
- package/dist/docs-site/docs/mobile/index.html +38 -2
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +1966 -1808
- package/dist/web/assets/Agent-bSVNDlcU.js +8 -0
- package/dist/web/assets/ApiTests-DOxGgoZC.js +10 -0
- package/dist/web/assets/Browse-CG8jzqR1.js +2 -0
- package/dist/web/assets/Chat-DzufzeGg.js +5 -0
- package/dist/web/assets/CommandPalette-D7ufvlUN.js +1 -0
- package/dist/web/assets/Compare-6vHuAaKv.js +1 -0
- package/dist/web/assets/Cost-DGZ5t-Q_.js +1 -0
- package/dist/web/assets/Data-DqGA1ZtQ.js +6 -0
- package/dist/web/assets/Desktop-CSOFE8cN.js +1 -0
- package/dist/web/assets/DesktopReview-BWtionFH.js +1 -0
- package/dist/web/assets/Evidence-D8pLFcbr.js +1 -0
- package/dist/web/assets/Explore-TtfTWmGW.js +2 -0
- package/dist/web/assets/Features-DazoSiEi.js +1 -0
- package/dist/web/assets/Flags-Brja-ZXF.js +2 -0
- package/dist/web/assets/Flaky-jJlHFFCa.js +1 -0
- package/dist/web/assets/Impact-b60dmhJK.js +3 -0
- package/dist/web/assets/Jobs-Y9W9nBgx.js +5 -0
- package/dist/web/assets/KindPage-Y72w2UwG.js +6 -0
- package/dist/web/assets/Migration-CvIeTB9p.js +2 -0
- package/dist/web/assets/Product-BEe2GyO6.js +7 -0
- package/dist/web/assets/Production-D2qmPFYy.js +1 -0
- package/dist/web/assets/Quality-C4Aak_hw.js +1 -0
- package/dist/web/assets/Readiness-ClXnnmLo.js +1 -0
- package/dist/web/assets/Record-LaLYhQgk.js +2 -0
- package/dist/web/assets/Regression-DKz05MC_.js +5 -0
- package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-DLeEarQd.js} +1 -1
- package/dist/web/assets/Reports-ClSAzQOh.js +2 -0
- package/dist/web/assets/Response-De60pk_7.js +10 -0
- package/dist/web/assets/RunDiff-0ibEcmI5.js +1 -0
- package/dist/web/assets/Runs-T8yF8Hi0.js +2 -0
- package/dist/web/assets/Steps-CB30w6BA.js +2 -0
- package/dist/web/assets/TestCases-Ba6bUE4i.js +1 -0
- package/dist/web/assets/TestData-DefDzeMW.js +2 -0
- package/dist/web/assets/TestDebt-zohltDHp.js +1 -0
- package/dist/web/assets/Tosca-jAtdiG28.js +3 -0
- package/dist/web/assets/WhatsNew-D7n48IsG.js +1 -0
- package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
- package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
- package/dist/web/assets/dataParts-CZAcb4L_.js +3 -0
- package/dist/web/assets/{families-zlLgApNV.js → families-D2ygriY6.js} +1 -1
- package/dist/web/assets/filters-CYaF2RvC.js +1 -0
- package/dist/web/assets/fold-BhYvId2X.js +1 -0
- package/dist/web/assets/frame-DeJBYtBX.js +11 -0
- package/dist/web/assets/index-CYlacOTX.css +2 -0
- package/dist/web/assets/index-DXpBYobT.js +67 -0
- package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
- package/dist/web/assets/{logos-CMkTgBD8.js → logos-DmK40tlV.js} +1 -1
- package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-Bej6qyls.js} +7 -7
- package/dist/web/assets/paletteCommands-CKBMmhb4.js +1 -0
- package/dist/web/assets/parts-BOpbd90H.js +1 -0
- package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-B3_FGd-T.js} +1 -1
- package/dist/web/assets/qualityParts-B8yJRVpP.js +1 -0
- package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-CZUrGm8I.js} +1 -1
- package/dist/web/assets/rows-BcG6gFCy.js +1 -0
- package/dist/web/assets/segmented-ffWUfF8N.js +1 -0
- package/dist/web/assets/{usePageChat-DWmmQrbC.js → usePageChat-T6vQY_1C.js} +1 -1
- package/dist/web/index.html +6 -6
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/COST_ARCHITECTURE.md +1 -1
- package/docs/MOBILE.md +40 -0
- package/docs/user-guide.html +91 -14
- package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
- package/forgeqe.example.yaml +11 -1
- package/package.json +2 -1
- package/prompts/brain.md +4 -0
- package/prompts/browser-goal-verification.md +2 -0
- package/prompts/refine.md +2 -0
- package/prompts/test-reviewer.md +2 -1
- package/prompts/test-rules.md +3 -0
- package/py/forgeqe_desktop/workflow.py +6 -4
- package/py/forgeqe_engine/capture.py +5 -4
- package/py/forgeqe_engine/diagnostics.py +2 -2
- package/py/forgeqe_engine/lenient_json.py +96 -0
- package/py/forgeqe_engine/llm.py +4 -0
- package/py/forgeqe_engine/network.py +93 -15
- package/py/forgeqe_engine/neutral_log.py +16 -1
- package/py/forgeqe_engine/recordsession.py +79 -1
- package/py/forgeqe_engine/service.py +22 -3
- package/py/forgeqe_mobile/appium_driver.py +9 -0
- package/py/forgeqe_mobile/apps.py +4 -0
- package/py/forgeqe_mobile/maestro.py +3 -0
- package/py/forgeqe_mobile/record.py +610 -0
- package/py/forgeqe_mobile/service.py +37 -7
- package/py/forgeqe_voice/worker.py +121 -0
- package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
- package/skills/playwright-typescript/SKILL.md +1 -1
- package/dist/web/assets/Agent-DyyAZPKr.js +0 -8
- package/dist/web/assets/ApiTests-p_cbulD4.js +0 -10
- package/dist/web/assets/Browse-DOAlK-ox.js +0 -2
- package/dist/web/assets/Chat-BCV5OsEz.js +0 -3
- package/dist/web/assets/CommandPalette-o9PuLas2.js +0 -1
- package/dist/web/assets/Compare-Bf1LhXmj.js +0 -1
- package/dist/web/assets/Cost-r7D19VSG.js +0 -1
- package/dist/web/assets/Data-CRttp4iM.js +0 -6
- package/dist/web/assets/Desktop-DcaKyfKA.js +0 -1
- package/dist/web/assets/DesktopReview-BjplTYfH.js +0 -1
- package/dist/web/assets/Evidence-BAAKcK0h.js +0 -1
- package/dist/web/assets/Explore-D_RZhVAc.js +0 -2
- package/dist/web/assets/Features-B6azjGtN.js +0 -1
- package/dist/web/assets/Flags-BQR4dRaK.js +0 -2
- package/dist/web/assets/Flaky-Ci1bvglt.js +0 -1
- package/dist/web/assets/Impact-CPB7NjQF.js +0 -3
- package/dist/web/assets/Jobs-CR8SxpWA.js +0 -5
- package/dist/web/assets/KindPage-Bl7q-2b8.js +0 -6
- package/dist/web/assets/Migration-BecNlszU.js +0 -2
- package/dist/web/assets/Product-AMUC5arL.js +0 -7
- package/dist/web/assets/Production-CZ-EG3t2.js +0 -1
- package/dist/web/assets/Quality-k2U9v2Dn.js +0 -1
- package/dist/web/assets/Readiness-D3_S6lDT.js +0 -1
- package/dist/web/assets/Record-Ba6XRn7c.js +0 -2
- package/dist/web/assets/Regression-jpkQRkt_.js +0 -5
- package/dist/web/assets/Reports-BHKtb9Oi.js +0 -2
- package/dist/web/assets/Response-CVNWGdun.js +0 -4
- package/dist/web/assets/RunDiff-dbcFibiJ.js +0 -1
- package/dist/web/assets/Runs-ij-80l3A.js +0 -2
- package/dist/web/assets/Steps-BDSeIznj.js +0 -2
- package/dist/web/assets/TestCases-BW8laQ_8.js +0 -1
- package/dist/web/assets/TestData-0f1XzLdc.js +0 -2
- package/dist/web/assets/TestDebt-C-2y3RTV.js +0 -1
- package/dist/web/assets/Tosca-DnfpS6Zf.js +0 -3
- package/dist/web/assets/WhatsNew-C1HUalPw.js +0 -1
- package/dist/web/assets/dataParts-DWD2uUxL.js +0 -3
- package/dist/web/assets/filters-CflRmNDz.js +0 -1
- package/dist/web/assets/fold-o_l3hXTU.js +0 -1
- package/dist/web/assets/frame-CdUL-UeQ.js +0 -4
- package/dist/web/assets/index-BmJOj6t1.js +0 -67
- package/dist/web/assets/index-DP3riJZe.css +0 -2
- package/dist/web/assets/palette-D-wSuihi.js +0 -1
- package/dist/web/assets/parts-C53RxMcR.js +0 -1
- package/dist/web/assets/qualityParts-DS83Q0nG.js +0 -1
- package/dist/web/assets/rows-DYYObxPx.js +0 -1
- package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
- package/dist/web/assets/thread-Cnjdo5ve.js +0 -5
package/forgeqe.example.yaml
CHANGED
|
@@ -242,6 +242,10 @@ prompts:
|
|
|
242
242
|
# # a colour such as "#7c3aed": the flat icons' lines, made darker or lighter
|
|
243
243
|
# # where they would not show; phosphor's and solar's second tone (grey in
|
|
244
244
|
# # black) takes the colour's palest shade
|
|
245
|
+
# mascot: visor # visor (the default: a pastel robot with an LED face showing the agent's symbol) |
|
|
246
|
+
# # classic (a character in its job's outfit) | icons (the icons above): how each
|
|
247
|
+
# # agent is drawn from 22px up, in chat, on the Agents pages and on Home
|
|
248
|
+
# mascot_colours: soft # soft (the default: pastels) | original (each agent's own colour)
|
|
245
249
|
# logo_size: auto # auto (the default: fitted to the logo's shape) | standard | large (a wide logo
|
|
246
250
|
# # across the sidebar's top, for one with small words)
|
|
247
251
|
# primary: "#0b1f3a" # the sidebar in light mode; dark mode uses the dark sidebar
|
|
@@ -404,7 +408,10 @@ sources:
|
|
|
404
408
|
# # priority: 2 # 1 (highest) to 4; the agent may give a case its own
|
|
405
409
|
# # tags: [forgeqe] # added to the case's own tags
|
|
406
410
|
# # state: Design # e.g. Design, so a person reviews a case before it is Ready
|
|
407
|
-
# # retire_state: Closed # retire_test_case's state (nothing is deleted)
|
|
411
|
+
# # retire_state: Closed # retire_test_case's state (nothing is deleted); default: a state the project itself calls done
|
|
412
|
+
# # states: # only where the project categorises its own states wrongly:
|
|
413
|
+
# # done: [Verified, Shipped] # states that mean the work is over, whatever the team calls them
|
|
414
|
+
# # removed: [Dropped] # states that mean the item was taken out
|
|
408
415
|
# # shared_steps: [345, 346] # Shared Steps work items new cases refer to instead of copying their steps
|
|
409
416
|
# jira:
|
|
410
417
|
# url: https://acme.atlassian.net # or JIRA_URL; Server/Data Center URLs work too
|
|
@@ -419,6 +426,7 @@ sources:
|
|
|
419
426
|
# # priority: Medium # a priority name; the agent may give a case its own
|
|
420
427
|
# # tags: [forgeqe] # labels (no spaces), added to the case's own
|
|
421
428
|
# # retire_label: obsolete # retire_test_case's label (Jira workflows differ, so no status is set)
|
|
429
|
+
# # done_statuses: [Verified, Shipped] # only where the site categorises its own statuses wrongly; otherwise Jira's status category says
|
|
422
430
|
# xray: # no MCP server: ForgeQE's API tools cover Xray
|
|
423
431
|
# url: https://xray.cloud.getxray.app # Xray Cloud; Server/DC uses the jira: settings above
|
|
424
432
|
# client_id_env: XRAY_CLIENT_ID
|
|
@@ -602,6 +610,8 @@ suite:
|
|
|
602
610
|
# headers:
|
|
603
611
|
# Authorization: Bearer ${API_TOKEN}
|
|
604
612
|
# third_party: false # keep calls to other sites than the page's
|
|
613
|
+
# keep_headers: [X-Tenant, X-Correlation-Id] # more headers to keep on captured calls (never one that carries a credential)
|
|
614
|
+
# browser_fallback: true # a read-only call the site's bot protection blocks is sent again from a browser page
|
|
605
615
|
# timeout_seconds: 30
|
|
606
616
|
# oauth2: # a bearer token fetched with the client-credentials grant (sent unless a call has its own Authorization)
|
|
607
617
|
# token_url: https://login.shop.example/oauth2/token
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capagents/forgeqe",
|
|
3
|
-
"version": "2.10.
|
|
3
|
+
"version": "2.10.5",
|
|
4
4
|
"description": "ForgeQE: a browser agent CLI that runs goals and test cases in local Chrome or Chromium, or BrowserStack and TestMu AI/LambdaTest when configured, and turns passing runs into tests in your repo",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"repository": {
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"py/forgeqe_desktop/*.py",
|
|
22
22
|
"py/forgeqe_mobile/*.py",
|
|
23
23
|
"py/forgeqe_knowledge/*.py",
|
|
24
|
+
"py/forgeqe_voice/*.py",
|
|
24
25
|
"py/forgeqe_tosca/*.py",
|
|
25
26
|
"py/forgeqe_tosca/vendor/toscatsu/",
|
|
26
27
|
"guardrails/",
|
package/prompts/brain.md
CHANGED
|
@@ -198,6 +198,7 @@ For a Confluence page, a Jira or Azure DevOps story, a specification file, or a
|
|
|
198
198
|
- When linked_case has in_scope_not_linked, you MUST pass the story to update_test_case. When its also_tests names other stories, you MUST name them, say that changing the case changes it for them too, and offer to copy it instead: save your case again with its title in force_new, leaving the existing case as it is.
|
|
199
199
|
- In the reply, you MUST list each saved case as a markdown link to its work item, with its title and its status, and without its full steps.
|
|
200
200
|
- When ForgeQE does not save cases there, or the user says not to, you MUST show them as a short markdown list with numbered titles, steps, and expected results.
|
|
201
|
+
- When you write cases to a file, every place that names a case (a coverage table, a link, another case) MUST use exactly the id in its heading, such as DOC-002, never another form of it such as TC-DOC-002.
|
|
201
202
|
- You MUST then run them with run_test_cases, unless the user asked only for the cases.
|
|
202
203
|
- You MUST run saved Azure DevOps cases by their ids (save_test_cases gives run_with), so that the results go back. Run other cases as text sources, one entry for each case.
|
|
203
204
|
- You MUST save cases from other requirements into a test management system only when the user asks. Use save_test_cases with the story when there is one to link them to; with no story, give the area path (Azure DevOps) or project (Jira, Zephyr Scale) the user names. Give the new ids as links.
|
|
@@ -226,12 +227,14 @@ For "an end-to-end test for story 1234", "combine these cases into one flow", or
|
|
|
226
227
|
- A browser_run goal is the complete instruction that the browser agent follows. It MUST give each value and each setting that the user named (dates, places, filters, sort order), and what to check.
|
|
227
228
|
- The goal MUST NOT have your questions, alternatives, or reasoning. You MUST remove all doubt before you call it.
|
|
228
229
|
- The goal MUST NOT add values that the user did not give, such as a number of guests or rooms. Leave the site's default.
|
|
230
|
+
- For items that meet a condition (under £700, 4 stars), the goal SHOULD tell the agent to apply the site's filter for it, or the sort for "cheapest" or "best rated". The goal MUST NOT tell it to keep the default order unless the user said so. "Top 5" is the first 5 after the filter: you MUST NOT ask which order.
|
|
229
231
|
- The goal MUST ask only for what the page can show. It MUST NOT make the run prove what a page cannot show, such as how an account's data was set up. When the user gives a limit per unit (per night, per item, per month) and the site can show the total for the whole stay or order, give both in the goal: the limit per unit and the total that it means (5 nights under £100 a night is a total under £500). The agent then uses the one that the page shows.
|
|
230
232
|
- A run with outcome assertion_failed did all the steps and found an expected result that is not true. failed_expectations gives what was expected and what the page shows.
|
|
231
233
|
- That is a correct result: a failed test case. You MUST report it as a failed test, with the expected and the actual result.
|
|
232
234
|
- You MUST NOT run it again, look for the value in other places, or change the expectation. Run again only the runs that could not do their steps.
|
|
233
235
|
- When a browser_run fails and gives resume steps, you MUST run the same task again with resume_from and that run_dir. ForgeQE replays the steps that worked without the model.
|
|
234
236
|
- You MUST read why the run failed, and say in the new goal what to do differently at that point.
|
|
237
|
+
- When a run stopped while it looked through many results, the new goal MUST tell the agent to use the site's filter or sort.
|
|
235
238
|
- You MAY start again from the beginning only when those steps were wrong, such as the wrong site or wrong values.
|
|
236
239
|
- After a browser run or a suite, you MUST report what passed, what failed, and why, in plain words.
|
|
237
240
|
- You MUST name the files that it made: report.html in the run folder, and the test that write_test wrote. Say if the run of that test passed. When ForgeQE wrote no test, say so and why.
|
|
@@ -321,6 +324,7 @@ When the user asks, or when the setup below says that passed runs become tests:
|
|
|
321
324
|
You MUST NOT write a new test file for a journey that an existing test covers in part. After extend or sibling, write_test does what you chose. You MUST NOT give it a mode.
|
|
322
325
|
- Cases that run_test_cases ran in a session that writes tests already have their test. You MUST call write_test only for a case that has none, when the user asks.
|
|
323
326
|
- You MUST NOT write that test yourself. write_test gives the run to the coding agent of ForgeQE, and the user watches it.
|
|
327
|
+
- When write_test is not in your tools, you MUST add it with use_capabilities (write-tests), not write the test with your file tools.
|
|
324
328
|
- Reuse before you rebuild, and extend before you duplicate. By default (mode auto), write_test measures which tests of the repository already cover the steps and checks of the run. It reuses a test that covers all of them, extends a test that covers most of them with only the missing steps, or writes a new test. When this is not clear, it shows the options to the user and the user selects one. You MUST NOT ask the user the same question again.
|
|
325
329
|
- When the user says how ("extend the login test", "write a separate test", "update it"), you MUST give that mode, and the test_file when the user names one.
|
|
326
330
|
- When the repository's tests are BDD (.feature files with Reqnroll, SpecFlow, Cucumber, behave or pytest-bdd), you MUST follow the bdd-scenario-design skill: ask the user how the scenarios are shaped (a Scenario Outline with Examples or not, Background, Rule) before write_test, and give the answers as bdd.
|
|
@@ -9,7 +9,9 @@ You MUST call done with success=true only when all parts of the goal are true on
|
|
|
9
9
|
- Each field MUST show exactly what the goal tells you. Sites fill in some fields before you start, and keep earlier selections. You MUST remove each value that the goal does not ask for.
|
|
10
10
|
- You MUST apply each setting that the goal names (sort order, filters, dates, options) through the controls of the page. The page MUST show the setting. To look through results that are not sorted is not the same as to apply the sort.
|
|
11
11
|
- You MUST read from the page all that the goal tells you to find or check. Your final answer MUST say what you saw.
|
|
12
|
+
- For items that meet a condition (a price limit, a rating), you SHOULD first apply the page's filter for it, or else sort by it. You SHOULD NOT look through many pages of results.
|
|
12
13
|
- You SHOULD read the items that the page lists (result cards, rows, prices, scores) from that list in one step. Open an item only when the goal needs data that the list does not show.
|
|
14
|
+
- When a script (evaluate) does not read a list in two tries, you MUST use extract.
|
|
13
15
|
- A tab can look empty immediately after it opens because it is loading. You MUST wait for it one time before you think that it is empty.
|
|
14
16
|
|
|
15
17
|
When a part is not true and you cannot make it true, you MUST call done with success=false, and name that part.
|
package/prompts/refine.md
CHANGED
|
@@ -33,6 +33,8 @@ Meaning:
|
|
|
33
33
|
|
|
34
34
|
Facts:
|
|
35
35
|
- You MUST NOT invent an id, a URL, a project, or a file.
|
|
36
|
+
- You MUST keep each file name that starts with @ as the user wrote it, for example @login.spec.ts or @"test plan.xlsx". Put it in the objective or the context.
|
|
37
|
+
- You MUST keep each persona command that starts with / as the user wrote it, for example /sam. Keep it in the part of the request that it applies to.
|
|
36
38
|
- You SHOULD check facts with your tools. Check that an item exists, its name, and how many cases it has.
|
|
37
39
|
- You MUST give names, not internal ids such as GUIDs. Give an id only when people use it as the name, for example a work item or build number.
|
|
38
40
|
- You MUST put a list of items of the same type on one line, for example "Projects: Autothon, CQube.AI".
|
package/prompts/test-reviewer.md
CHANGED
|
@@ -42,7 +42,8 @@ Scope:
|
|
|
42
42
|
- For each changed file that existed before the job, you MUST check its diff (git diff). An existing test that the job removed or rewrote, also one that was commented out, is a correctness problem.
|
|
43
43
|
|
|
44
44
|
Locators and values:
|
|
45
|
-
- You MUST NOT ask to replace locators and texts that the handoff took from its replay script and checks. They matched the live site.
|
|
45
|
+
- You MUST NOT ask to replace locators and texts that the handoff took from its replay script and checks. They matched the live site. A step that the handoff marks ✗ is the exception: its locator did not work in the replay.
|
|
46
|
+
- A cookie banner or other overlay is a correctness problem when its close locator can match more than one element, when its helper catches all errors, or when the test does not assert that the overlay is hidden after the click.
|
|
46
47
|
- When the message lists what the code graph of ForgeQE found, you MUST check each point in the changed files. A new member that locates an element an existing member already locates is a standards problem: the correction is to reuse the existing member. A brittle locator is a standards problem when the handoff gives a ✓ semantic locator for the same element.
|
|
47
48
|
- You MUST accept a value that the test case names, such as a user name. Credentials MUST still come from the environment.
|
|
48
49
|
- A public demo login is the one exception: a user name and password that the application itself shows to anyone, such as the logins on the sign-in page of a demo site (saucedemo.com). Such a login MAY follow the convention of the repository for test data. The page snapshots of the run show whether the application publishes it. You MUST NOT report it. You MUST report any other credential in code or test data.
|
package/prompts/test-rules.md
CHANGED
|
@@ -47,6 +47,9 @@ kind: fragment
|
|
|
47
47
|
- When the handoff lists one overlay that the run closed, and the framework has an overlay handler (Playwright 1.42 and later: page.addLocatorHandler, Page.AddLocatorHandlerAsync), you MUST register the handler once, in the fixture or the base class setup, with the close control of the handoff.
|
|
48
48
|
- When the handoff lists two or more overlays, or the framework has no overlay handler, you MUST write one helper that closes each visible overlay, in the sequence of the handoff, top one first.
|
|
49
49
|
- For each overlay, the helper MUST check its close control with a plain visibility check, click it, and wait until the overlay is hidden.
|
|
50
|
+
- A close control's locator MUST match one element on the whole page: find it inside the overlay's container, not with .first(). Cookie tools often have a second "Accept all".
|
|
51
|
+
- A helper that closes an overlay "if present" MAY ignore only the timeout of an overlay that did not show. Other errors MUST fail the test. After the click, the test MUST assert that the overlay is hidden.
|
|
52
|
+
- For a step marked ✗ in the handoff, you MUST use the locator that the handoff gives in its place.
|
|
50
53
|
- You MUST call the helper after each navigation, and immediately before each step that opens a thing, such as a date picker or a menu.
|
|
51
54
|
- You MUST NOT use overlay handlers or a combined locator (locator.or) for two or more overlays. They can show at the same time: the click of one handler is blocked by the other overlay, handlers do not run inside a handler, and strict mode fails on a combined locator.
|
|
52
55
|
- You MUST do the flow again, not the tries of the agent.
|
|
@@ -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
|
-
|
|
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
|
-
|
|
252
|
-
|
|
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
|
package/py/forgeqe_engine/llm.py
CHANGED
|
@@ -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)
|
|
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
|
|
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
|
|
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(
|
|
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,
|
|
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
|
|
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
|
|
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
|
|
293
|
-
|
|
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
|
-
|
|
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)
|