@capagents/forgeqe 3.0.5 → 3.0.6
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 +43 -18
- package/dist/docs-site/docs/index.html +32 -1
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +1985 -1973
- package/dist/web/assets/Agent-yYv-sG28.js +8 -0
- package/dist/web/assets/AgentWork-CpY6-7HI.js +2 -0
- package/dist/web/assets/ApiTests-CiIvZiMo.js +10 -0
- package/dist/web/assets/Browse-Be7AuwHt.js +2 -0
- package/dist/web/assets/Chat-BCts4QGa.js +5 -0
- package/dist/web/assets/{CommandPalette-BkNNac9P.js → CommandPalette-8TT9jdZs.js} +1 -1
- package/dist/web/assets/{Compare-Ce214eXq.js → Compare-D736rcq4.js} +1 -1
- package/dist/web/assets/Cost-FNg7VZwi.js +1 -0
- package/dist/web/assets/{Data-BNXAWpvT.js → Data-DcbrW5-J.js} +4 -4
- package/dist/web/assets/Desktop-DP62qPnT.js +1 -0
- package/dist/web/assets/DesktopReview-CvOsaLqf.js +1 -0
- package/dist/web/assets/{Evidence-C6PtAQ6y.js → Evidence-CzgIQH9N.js} +1 -1
- package/dist/web/assets/{Explore-BN8zgzmv.js → Explore-eTri0oMt.js} +2 -2
- package/dist/web/assets/{Features-DRONEGA3.js → Features-DYIzplY5.js} +1 -1
- package/dist/web/assets/{Flags-CF8Zboey.js → Flags-Dhw6rtB2.js} +2 -2
- package/dist/web/assets/{Flaky-B6IYRvE2.js → Flaky-DyKQrSKH.js} +1 -1
- package/dist/web/assets/Impact-BPSNF_Wk.js +3 -0
- package/dist/web/assets/{Jobs-BX-DXp28.js → Jobs-CdZ_9uR8.js} +3 -3
- package/dist/web/assets/KindPage-BX77XCmy.js +6 -0
- package/dist/web/assets/Migration-BsKltBC-.js +2 -0
- package/dist/web/assets/{Product-Bcv7xIYx.js → Product-BjK5mL11.js} +2 -2
- package/dist/web/assets/{Production-DTdUc-ze.js → Production-Fh9Sscxj.js} +1 -1
- package/dist/web/assets/{Quality-B0MRg6wI.js → Quality-Ld82j0hy.js} +1 -1
- package/dist/web/assets/{Readiness-XpGisxdv.js → Readiness-BBQxbCqC.js} +1 -1
- package/dist/web/assets/Record-C5cEwqy-.js +1 -0
- package/dist/web/assets/Regression-gjrSoFfx.js +5 -0
- package/dist/web/assets/{RelationGraph-MHWsIy8b.js → RelationGraph-DVWg7aQv.js} +1 -1
- package/dist/web/assets/{Reports-Cy1MvUqg.js → Reports-DP1a7XJS.js} +2 -2
- package/dist/web/assets/Response-D2kQxq_Y.js +4 -0
- package/dist/web/assets/{RunDiff-BQH6Wacd.js → RunDiff-D6mEdE9S.js} +1 -1
- package/dist/web/assets/{Runs-IwZWhlyu.js → Runs-Q10bNJEL.js} +2 -2
- package/dist/web/assets/{Steps-DKCrz0ed.js → Steps-De_8K9c1.js} +1 -1
- package/dist/web/assets/{TestCases-Bt81xr3X.js → TestCases-Dt8B7TOf.js} +1 -1
- package/dist/web/assets/{TestData-CXRhxaD8.js → TestData-CaGz4HQ1.js} +2 -2
- package/dist/web/assets/{TestDebt-DM5VeTwn.js → TestDebt-DCJ_GT7n.js} +1 -1
- package/dist/web/assets/TestManagement-uO9AjV8t.js +1 -0
- package/dist/web/assets/Tosca-CNvp2_fr.js +3 -0
- package/dist/web/assets/{WhatsNew-D3yHnxgW.js → WhatsNew-BsvPslDU.js} +1 -1
- package/dist/web/assets/agentLink-DZqDlz5a.js +1 -0
- package/dist/web/assets/{dataParts-B0tYVMhQ.js → dataParts-DDONrWlN.js} +1 -1
- package/dist/web/assets/{families-DGOQO6Mu.js → families-dexkG1XJ.js} +1 -1
- package/dist/web/assets/filters-C4y29lln.js +1 -0
- package/dist/web/assets/{fold-B_G_xXZM.js → fold-B0BRJaD-.js} +1 -1
- package/dist/web/assets/frame-DsEMaf7r.js +18 -0
- package/dist/web/assets/index-DFHl9AbL.css +2 -0
- package/dist/web/assets/index-Do1FSXo9.js +68 -0
- package/dist/web/assets/{logos-DpiYLP3H.js → logos-Bf_yvAjX.js} +1 -1
- package/dist/web/assets/{markdown-Dn8IZFhS.js → markdown-DerN4WZw.js} +1 -1
- package/dist/web/assets/{paletteCommands-DKcFFV7I.js → paletteCommands-BHKI8Ajf.js} +1 -1
- package/dist/web/assets/{parts-Ct3kXHNO.js → parts-CD8Iib6m.js} +1 -1
- package/dist/web/assets/poll-CHpac9Fb.js +1 -0
- package/dist/web/assets/{productParts-IDyVJAgM.js → productParts-ua-02OtT.js} +1 -1
- package/dist/web/assets/{qualityParts-Db6YfFIY.js → qualityParts-BGB8bK0j.js} +1 -1
- package/dist/web/assets/{recordTest-_r_cdTC6.js → recordTest-cdImm3Tn.js} +1 -1
- package/dist/web/assets/{rows-De2l3NFN.js → rows-HJE6LrRs.js} +1 -1
- package/dist/web/assets/{segmented-CHGzMxbS.js → segmented-C9eCOTSg.js} +1 -1
- package/dist/web/assets/usePageChat-fVgsHXcu.js +1 -0
- package/dist/web/index.html +5 -5
- package/docs/RELIABILITY.md +62 -0
- package/docs/TEST_MANAGEMENT_PLAN.md +95 -0
- package/docs/user-guide.html +32 -1
- package/forgeqe.example.yaml +5 -0
- package/package.json +1 -1
- package/prompts/README.md +1 -0
- package/prompts/suite-builder.md +44 -0
- package/py/forgeqe_engine/brand.py +49 -12
- package/py/forgeqe_engine/copilot_gateway.py +131 -3
- package/py/forgeqe_engine/diagnostics.py +5 -2
- package/py/forgeqe_engine/memory.py +12 -0
- package/py/forgeqe_engine/recordsession.py +68 -7
- package/py/forgeqe_engine/service.py +8 -1
- package/py/forgeqe_engine/video.py +14 -0
- package/dist/web/assets/Agent-BF6goYbq.js +0 -8
- package/dist/web/assets/ApiTests-08El24XV.js +0 -10
- package/dist/web/assets/Browse-DB7lNo6R.js +0 -2
- package/dist/web/assets/Chat-Co7EJfA9.js +0 -5
- package/dist/web/assets/Cost-B_oVlEve.js +0 -1
- package/dist/web/assets/Desktop-Dnsmc_L-.js +0 -1
- package/dist/web/assets/DesktopReview-C7SG_gBt.js +0 -1
- package/dist/web/assets/Impact-DglYEuEY.js +0 -3
- package/dist/web/assets/KindPage-ByaxfUiE.js +0 -6
- package/dist/web/assets/Migration-wVEuZ3zr.js +0 -2
- package/dist/web/assets/Record-C0vcXk-u.js +0 -2
- package/dist/web/assets/Regression-CthpK77C.js +0 -5
- package/dist/web/assets/Response-53IPohSg.js +0 -4
- package/dist/web/assets/Tosca-B42EZ5YF.js +0 -3
- package/dist/web/assets/agentLink-BlI6CU6m.js +0 -1
- package/dist/web/assets/filters-Btr3PTRn.js +0 -1
- package/dist/web/assets/frame-CU0pSxTD.js +0 -18
- package/dist/web/assets/index-CCNq91up.js +0 -68
- package/dist/web/assets/index-D6jp6pDW.css +0 -2
- package/dist/web/assets/usePageChat-CpAYTNqJ.js +0 -1
|
@@ -494,6 +494,17 @@ class Copilot:
|
|
|
494
494
|
gateway_log(rid, f"start model={req['model']} tools={len(req['tools'])} schema={req['schema'] is not None} stream={bool(on_text)}")
|
|
495
495
|
try:
|
|
496
496
|
out = await self._complete(rid, req, on_text, gone)
|
|
497
|
+
# Copilot sometimes ends a turn with no words and no call of the caller's tools. Answered as it is, the
|
|
498
|
+
# agent runtime takes that for a finished answer and the person's request ends in silence, its plan
|
|
499
|
+
# half done. It is asked once more; a second empty turn is an error the caller sees.
|
|
500
|
+
if empty_reply(req, out):
|
|
501
|
+
gateway_log(rid, "Copilot ended its turn with no reply and no call of the caller's tools: asked once more")
|
|
502
|
+
out = await self._complete(rid, req, on_text, gone)
|
|
503
|
+
if empty_reply(req, out):
|
|
504
|
+
# The turn's shape, never its text, goes to the caller: ForgeQE's own session log then says what
|
|
505
|
+
# Copilot sent, without the gateway's log.
|
|
506
|
+
raise GatewayError(502, f"{EMPTY_REPLY} ({out.get(SHAPE_KEY) or 'no detail'})")
|
|
507
|
+
out.pop(SHAPE_KEY, None)
|
|
497
508
|
except CallerGone:
|
|
498
509
|
gateway_log(rid, f"caller gone after {time.monotonic() - started:.1f}s: its Copilot session was stopped")
|
|
499
510
|
raise
|
|
@@ -527,7 +538,7 @@ class Copilot:
|
|
|
527
538
|
statuses: List[Optional[int]] = []
|
|
528
539
|
calls: List[Dict[str, Any]] = []
|
|
529
540
|
# The last root reply without tool requests, and the timer that ends the wait when a turn ends without idle.
|
|
530
|
-
turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event()}
|
|
541
|
+
turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event(), "messages": []}
|
|
531
542
|
|
|
532
543
|
def on_loop(fn: Callable[[], None]) -> None:
|
|
533
544
|
"""The SDK may call on_event from a thread of its own; timers and events belong to the server's loop."""
|
|
@@ -555,6 +566,7 @@ class Copilot:
|
|
|
555
566
|
usage["output"] += data.output_tokens or 0
|
|
556
567
|
usage["cached"] += data.cache_read_tokens or 0
|
|
557
568
|
usage["premium"] += float(getattr(data, "cost", None) or 0)
|
|
569
|
+
usage["reasoning"] = usage.get("reasoning", 0) + (getattr(data, "reasoning_tokens", None) or 0)
|
|
558
570
|
if not getattr(data, "parent_tool_call_id", None):
|
|
559
571
|
finish["reason"] = "content_filter" if getattr(data, "content_filter_triggered", False) else getattr(data, "finish_reason", None)
|
|
560
572
|
elif isinstance(data, SessionErrorData):
|
|
@@ -566,6 +578,9 @@ class Copilot:
|
|
|
566
578
|
stream["to"](data.delta_content)
|
|
567
579
|
elif isinstance(data, AssistantMessageData) and not data.parent_tool_call_id:
|
|
568
580
|
turn["final"] = None if data.tool_requests else event
|
|
581
|
+
# Every root message of the turn: a reply split into chunks or phases, and tool requests Copilot never
|
|
582
|
+
# handed to the relay, are read from them (reply_of, requested_calls).
|
|
583
|
+
turn["messages"].append(data)
|
|
569
584
|
elif isinstance(data, AssistantTurnStartData) and not data.parent_tool_call_id:
|
|
570
585
|
on_loop(unsettle)
|
|
571
586
|
elif isinstance(data, AssistantTurnEndData) and not data.parent_tool_call_id:
|
|
@@ -584,6 +599,7 @@ class Copilot:
|
|
|
584
599
|
calls.clear()
|
|
585
600
|
on_loop(unsettle)
|
|
586
601
|
turn["final"] = None
|
|
602
|
+
turn["messages"] = []
|
|
587
603
|
turn["settled"] = asyncio.Event()
|
|
588
604
|
names = {t["name"] for t in req["tools"]}
|
|
589
605
|
tools = relay_tools(req["tools"], calls, replaces=self.replaces & names)
|
|
@@ -655,14 +671,32 @@ class Copilot:
|
|
|
655
671
|
raise self.refusal(errors[-1], statuses[-1] if statuses else None)
|
|
656
672
|
gateway_log(rid, cache_note(req, usage))
|
|
657
673
|
data = getattr(reply, "data", None)
|
|
674
|
+
messages = list(turn["messages"]) or ([data] if isinstance(data, AssistantMessageData) else [])
|
|
658
675
|
content = (data.content or "") if isinstance(data, AssistantMessageData) else ""
|
|
659
676
|
if calls:
|
|
660
677
|
return completion(req["model"], content, usage, calls)
|
|
661
|
-
|
|
678
|
+
caller = {t["name"] for t in req["tools"]}
|
|
679
|
+
# A call of the caller's tools Copilot asked for but never handed to the relay (a call it failed itself leaves
|
|
680
|
+
# its loop running): the call goes back to the caller all the same, instead of an empty answer.
|
|
681
|
+
recovered = requested_calls(messages, caller)
|
|
682
|
+
if recovered:
|
|
683
|
+
gateway_log(rid, f"Copilot asked for {','.join(c['name'] for c in recovered)} without handing the call over: passed on as tool calls")
|
|
684
|
+
return completion(req["model"], "", usage, recovered)
|
|
685
|
+
if not isinstance(data, AssistantMessageData) and not messages:
|
|
662
686
|
raise GatewayError(502, "GitHub Copilot sent no reply.")
|
|
687
|
+
if not content.strip():
|
|
688
|
+
# A reply sent in chunks or phases, whose last message holds none of it.
|
|
689
|
+
content = reply_of(messages)
|
|
690
|
+
if content.strip():
|
|
691
|
+
gateway_log(rid, "the reply's last message was empty: its text was taken from the turn's earlier messages")
|
|
663
692
|
if req["schema"] is not None or req["json_only"]:
|
|
664
693
|
content = strip_fences(content)
|
|
665
|
-
|
|
694
|
+
out = completion(req["model"], content, usage, finish=finish["reason"])
|
|
695
|
+
if not content.strip():
|
|
696
|
+
shape = turn_shape(messages, usage, finish["reason"], caller)
|
|
697
|
+
gateway_log(rid, f"empty turn: {shape}")
|
|
698
|
+
out[SHAPE_KEY] = shape
|
|
699
|
+
return out
|
|
666
700
|
|
|
667
701
|
|
|
668
702
|
async def _wait(self, rid: str, session: Any, req: Dict[str, Any], turn: Dict[str, Any], gone: Optional["asyncio.Future[Any]"]) -> Tuple[Any, bool]:
|
|
@@ -708,6 +742,100 @@ _LIMITED = re.compile(r"rate.?limit|too many requests|quota|premium request|allo
|
|
|
708
742
|
LIMITED_HINT = "the seat's rate limit or premium request allowance; wait, or pick a model with a lower multiplier: forgeqe models --copilot"
|
|
709
743
|
|
|
710
744
|
|
|
745
|
+
EMPTY_REPLY = "GitHub Copilot ended its turn twice with no reply and no tool call."
|
|
746
|
+
# Where an empty answer carries its turn's shape inside the gateway; removed before anything is sent.
|
|
747
|
+
SHAPE_KEY = "_forgeqe_turn_shape"
|
|
748
|
+
_PLAIN = re.compile(r"^[A-Za-z0-9_.-]{1,40}$")
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def reply_of(messages: List[Any]) -> str:
|
|
752
|
+
"""
|
|
753
|
+
The reply's text from a turn's root messages: after the last one that asked for a tool, the last message with words,
|
|
754
|
+
its chunks joined in order (one per chunk_index, the latest kept). Copilot can send a reply in chunks, or a final
|
|
755
|
+
message with no words after one that had them; the last message alone then loses the reply.
|
|
756
|
+
"""
|
|
757
|
+
after: List[Any] = []
|
|
758
|
+
for m in messages:
|
|
759
|
+
if getattr(m, "tool_requests", None):
|
|
760
|
+
after = []
|
|
761
|
+
else:
|
|
762
|
+
after.append(m)
|
|
763
|
+
groups: Dict[str, List[Any]] = {}
|
|
764
|
+
order: List[str] = []
|
|
765
|
+
for i, m in enumerate(after):
|
|
766
|
+
key = str(getattr(m, "message_id", "") or f"#{i}")
|
|
767
|
+
if key not in groups:
|
|
768
|
+
groups[key] = []
|
|
769
|
+
order.append(key)
|
|
770
|
+
groups[key].append(m)
|
|
771
|
+
for key in reversed(order):
|
|
772
|
+
parts = groups[key]
|
|
773
|
+
if any(isinstance(getattr(p, "chunk_index", None), int) for p in parts):
|
|
774
|
+
by_index: Dict[int, str] = {}
|
|
775
|
+
for p in parts:
|
|
776
|
+
idx = getattr(p, "chunk_index", None)
|
|
777
|
+
by_index[idx if isinstance(idx, int) else -1] = str(getattr(p, "content", "") or "")
|
|
778
|
+
text = "".join(by_index[k] for k in sorted(by_index))
|
|
779
|
+
else:
|
|
780
|
+
text = str(getattr(parts[-1], "content", "") or "")
|
|
781
|
+
if text.strip():
|
|
782
|
+
return text
|
|
783
|
+
return ""
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def requested_calls(messages: List[Any], caller: set) -> List[Dict[str, Any]]:
|
|
787
|
+
"""
|
|
788
|
+
The calls of the caller's tools the turn's last root message asked for, as the relay records them; none when it
|
|
789
|
+
asked for another tool too (Copilot's own, or one nobody has), since the caller could not answer that one.
|
|
790
|
+
"""
|
|
791
|
+
if not messages:
|
|
792
|
+
return []
|
|
793
|
+
asked = list(getattr(messages[-1], "tool_requests", None) or [])
|
|
794
|
+
if not asked or any(str(getattr(t, "name", "") or "") not in caller for t in asked):
|
|
795
|
+
return []
|
|
796
|
+
out = []
|
|
797
|
+
for t in asked[:16]:
|
|
798
|
+
args = getattr(t, "arguments", None)
|
|
799
|
+
out.append({
|
|
800
|
+
"id": str(getattr(t, "tool_call_id", "") or f"call_{uuid.uuid4().hex[:24]}")[:64],
|
|
801
|
+
"name": str(t.name),
|
|
802
|
+
"arguments": args if isinstance(args, str) else json.dumps(args if args is not None else {}),
|
|
803
|
+
})
|
|
804
|
+
return out
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def turn_shape(messages: List[Any], usage: Dict[str, Any], finish: Optional[str], caller: set) -> str:
|
|
808
|
+
"""
|
|
809
|
+
What an empty turn was made of, for the log and the caller's error: counts, phases, the finish reason and the tools
|
|
810
|
+
asked for. Never the turn's text; a name the model wrote only when it is one of the caller's or Copilot's own tools.
|
|
811
|
+
"""
|
|
812
|
+
phases = sorted({str(getattr(m, "phase", "") or "") for m in messages} - {""})
|
|
813
|
+
asked = [str(getattr(t, "name", "") or "") for m in messages for t in (getattr(m, "tool_requests", None) or [])]
|
|
814
|
+
known = sorted({n for n in asked if n in caller or n in BUILTIN_TOOLS})
|
|
815
|
+
other = len([n for n in asked if n not in caller and n not in BUILTIN_TOOLS])
|
|
816
|
+
reasoning_only = any(str(getattr(m, "reasoning_text", "") or "").strip() for m in messages) and not any(str(getattr(m, "content", "") or "").strip() for m in messages)
|
|
817
|
+
bits = [
|
|
818
|
+
f"messages {len(messages)}",
|
|
819
|
+
f"phases {'/'.join(p for p in phases if _PLAIN.match(p)) or 'none'}",
|
|
820
|
+
f"finish {finish if finish and _PLAIN.match(str(finish)) else 'none'}",
|
|
821
|
+
f"output tokens {int(usage.get('output') or 0)}",
|
|
822
|
+
f"reasoning tokens {int(usage.get('reasoning') or 0)}",
|
|
823
|
+
f"tools asked {', '.join(known) or 'none'}{f' and {other} other' if other else ''}",
|
|
824
|
+
]
|
|
825
|
+
if reasoning_only:
|
|
826
|
+
bits.append("reasoning without a reply")
|
|
827
|
+
return "; ".join(bits)
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def empty_reply(req: Dict[str, Any], out: Dict[str, Any]) -> bool:
|
|
831
|
+
"""A plain-text answer with no words and no tool calls that Copilot did not cut short: nothing the caller can use."""
|
|
832
|
+
if req.get("schema") is not None or req.get("json_only"):
|
|
833
|
+
return False
|
|
834
|
+
choice = (out.get("choices") or [{}])[0]
|
|
835
|
+
message = choice.get("message") or {}
|
|
836
|
+
return not message.get("tool_calls") and not str(message.get("content") or "").strip() and choice.get("finish_reason") == "stop"
|
|
837
|
+
|
|
838
|
+
|
|
711
839
|
def limited(message: str, status: Optional[int] = None) -> bool:
|
|
712
840
|
"""Whether Copilot's error is a rate limit or a used-up premium request allowance."""
|
|
713
841
|
return status == 429 or bool(_LIMITED.search(message or ""))
|
|
@@ -15,6 +15,7 @@ from pathlib import Path
|
|
|
15
15
|
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
16
16
|
from urllib.parse import urlsplit
|
|
17
17
|
|
|
18
|
+
from .brand import clean_capture
|
|
18
19
|
from .network import NetworkCapture, hook
|
|
19
20
|
|
|
20
21
|
logger = logging.getLogger(__name__)
|
|
@@ -463,7 +464,8 @@ class Diagnostics:
|
|
|
463
464
|
continue
|
|
464
465
|
await asyncio.sleep(0.1)
|
|
465
466
|
entry[mode] = await self._eval(session, L10N_MEASURE % "false") or {}
|
|
466
|
-
|
|
467
|
+
with clean_capture():
|
|
468
|
+
shot = await session.cdp_client.send.Page.captureScreenshot(params={"format": "jpeg", "quality": 60, "fromSurface": True}, session_id=session.session_id)
|
|
467
469
|
if (shot or {}).get("data"):
|
|
468
470
|
entry.setdefault("_shots", {})[mode] = base64.b64decode(shot["data"])
|
|
469
471
|
except Exception:
|
|
@@ -514,7 +516,8 @@ class Diagnostics:
|
|
|
514
516
|
width, height = int(size.get("width") or 0), min(int(size.get("height") or 0), MAX_FULL_HEIGHT)
|
|
515
517
|
if width and height:
|
|
516
518
|
params.update({"captureBeyondViewport": True, "clip": {"x": 0, "y": 0, "width": width, "height": height, "scale": 1}})
|
|
517
|
-
|
|
519
|
+
with clean_capture():
|
|
520
|
+
shot = await send.Page.captureScreenshot(params=params, session_id=session.session_id)
|
|
518
521
|
data = (shot or {}).get("data")
|
|
519
522
|
if data:
|
|
520
523
|
title = str(await self._eval(session, "document.title") or "")
|
|
@@ -1223,6 +1223,18 @@ def _present_first(target: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
|
1223
1223
|
return [l for l in locs if (l["type"], l["value"]) in current] + [l for l in locs if (l["type"], l["value"]) not in current]
|
|
1224
1224
|
|
|
1225
1225
|
|
|
1226
|
+
UNSAVED_SECRET = (
|
|
1227
|
+
"typed into a password field a value that is not a saved secret, so replays stop there and the model signs in "
|
|
1228
|
+
"again on every run. Make the password a secret: in env.yaml, a variable whose value is only $NAME of an "
|
|
1229
|
+
"environment variable (the browser model then types <secret>…</secret>), or a login in forgeqe.yaml"
|
|
1230
|
+
)
|
|
1231
|
+
|
|
1232
|
+
|
|
1233
|
+
def unsaved_secret_steps(steps: List[Dict[str, Any]]) -> List[int]:
|
|
1234
|
+
"""The 1-based numbers of the flow's steps that typed into a password field without a saved secret (never replayable)."""
|
|
1235
|
+
return [n for n, s in enumerate(steps or [], 1) if isinstance(s, dict) and s.get("secret")]
|
|
1236
|
+
|
|
1237
|
+
|
|
1226
1238
|
def flow_step(action: str, params: Dict[str, Any], target: Optional[Dict[str, Any]], line: str) -> Dict[str, Any]:
|
|
1227
1239
|
"""One replayable action. Element actions keep the element's ranked locators and fingerprint, never its index."""
|
|
1228
1240
|
step: Dict[str, Any] = {"action": action, "params": {k: v for k, v in (params or {}).items() if k != "index"}, "line": line}
|
|
@@ -58,6 +58,28 @@ MAX_SHOTS = 400
|
|
|
58
58
|
MAX_STEP_TIMES = 1000
|
|
59
59
|
SHOT_QUALITY = 55
|
|
60
60
|
# The tester's tab as a video (browser.video): the page's own screencast, on the recorder's connection (video.py).
|
|
61
|
+
# How often, and how long apart, a tab's history is asked for when it cannot answer yet (a back-forward cache restore).
|
|
62
|
+
HISTORY_TRIES = 6
|
|
63
|
+
HISTORY_RETRY_S = 0.1
|
|
64
|
+
# The tab's history addresses kept to tell back from forward when its history cannot be read.
|
|
65
|
+
MAX_HISTORY = 200
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def history_step(prev: Any, urls: Any, url: str) -> str:
|
|
69
|
+
"""
|
|
70
|
+
Back or forward from the address alone, when the tab's history cannot be read: the entry just before the one the tab
|
|
71
|
+
was on is back, the one just after forward; anything else is a new page. Read as untrusted (only the shapes kept).
|
|
72
|
+
"""
|
|
73
|
+
if not (isinstance(prev, tuple) and len(prev) == 3 and isinstance(prev[0], int) and isinstance(urls, list) and url):
|
|
74
|
+
return "new"
|
|
75
|
+
cur = prev[0]
|
|
76
|
+
if 1 <= cur <= len(urls) and urls[cur - 1] == url:
|
|
77
|
+
return "back"
|
|
78
|
+
if 0 <= cur + 1 < len(urls) and urls[cur + 1] == url:
|
|
79
|
+
return "forward"
|
|
80
|
+
return "new"
|
|
81
|
+
|
|
82
|
+
|
|
61
83
|
VIDEO_SCREENCAST = {"format": "jpeg", "quality": 60, "maxWidth": 1920, "maxHeight": 1200, "everyNthFrame": 1}
|
|
62
84
|
|
|
63
85
|
# What the page shows after a step, for the review to suggest checks from and to pick an element on the screenshot:
|
|
@@ -387,6 +409,8 @@ class RecordSession:
|
|
|
387
409
|
with contextlib.suppress(Exception):
|
|
388
410
|
await self.network.settle(3.0)
|
|
389
411
|
sid, self._video_sid = self._video_sid, None
|
|
412
|
+
# The browser is about to close: the last picture is taken now, while its tab is there (_finish_video comes after).
|
|
413
|
+
await self._last_picture(self.video, sid)
|
|
390
414
|
if self.video is not None and sid and sid in self.pages:
|
|
391
415
|
with contextlib.suppress(Exception):
|
|
392
416
|
await self.send("Page.stopScreencast", {}, sid)
|
|
@@ -772,7 +796,7 @@ class RecordSession:
|
|
|
772
796
|
await self.send("Page.startScreencast", dict(VIDEO_SCREENCAST), sid)
|
|
773
797
|
except Exception as ex:
|
|
774
798
|
logger.debug("record: no screencast of the page: %s", ex)
|
|
775
|
-
how = await self._how(sid, page)
|
|
799
|
+
how = await self._how(sid, page, url)
|
|
776
800
|
renderer = page.pop("renderer", False)
|
|
777
801
|
started = page.pop("started", None)
|
|
778
802
|
if page.pop("initial", False) or (page.get("opener") and not page.get("seen")):
|
|
@@ -789,16 +813,34 @@ class RecordSession:
|
|
|
789
813
|
if msg:
|
|
790
814
|
self._changed(msg)
|
|
791
815
|
|
|
792
|
-
async def _how(self, sid: str, page: Dict[str, Any]) -> str:
|
|
793
|
-
"""
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
816
|
+
async def _how(self, sid: str, page: Dict[str, Any], url: str = "") -> str:
|
|
817
|
+
"""
|
|
818
|
+
How the tab got to its page, from its history: "back", "forward", "reload", or "new". A page restored from the
|
|
819
|
+
back-forward cache answers "Not attached to an active page" for a moment: the history is asked again, and if it
|
|
820
|
+
still cannot be read, the address tells back from forward (the entry before or after the one it was on).
|
|
821
|
+
"""
|
|
822
|
+
h: Optional[Dict[str, Any]] = None
|
|
823
|
+
for attempt in range(HISTORY_TRIES):
|
|
824
|
+
try:
|
|
825
|
+
h = await self.send("Page.getNavigationHistory", None, sid)
|
|
826
|
+
break
|
|
827
|
+
except Exception as ex:
|
|
828
|
+
if attempt + 1 < HISTORY_TRIES:
|
|
829
|
+
await asyncio.sleep(HISTORY_RETRY_S)
|
|
830
|
+
else:
|
|
831
|
+
logger.debug("record: no history of the tab: %s", ex)
|
|
832
|
+
if h is None:
|
|
833
|
+
how = history_step(page.get("history"), page.get("history_urls"), url)
|
|
834
|
+
# Where the tab now is in its history, so the next navigation is judged from here.
|
|
835
|
+
if how in ("back", "forward"):
|
|
836
|
+
cur, length, _ = page["history"]
|
|
837
|
+
page["history"] = (cur - 1 if how == "back" else cur + 1, length, None)
|
|
838
|
+
return how
|
|
798
839
|
entries = h.get("entries") or []
|
|
799
840
|
cur = int(h.get("currentIndex") or 0)
|
|
800
841
|
entry = entries[cur]["id"] if 0 <= cur < len(entries) else None
|
|
801
842
|
prev, page["history"] = page.get("history"), (cur, len(entries), entry)
|
|
843
|
+
page["history_urls"] = [str(e.get("url") or "") for e in entries][:MAX_HISTORY]
|
|
802
844
|
if not prev:
|
|
803
845
|
return "new"
|
|
804
846
|
p_cur, p_len, p_entry = prev
|
|
@@ -1741,11 +1783,30 @@ class RecordSession:
|
|
|
1741
1783
|
except Exception as ex:
|
|
1742
1784
|
logger.debug("record: no screencast of the page: %s", ex)
|
|
1743
1785
|
|
|
1786
|
+
async def _last_picture(self, video: Any, sid: Optional[str]) -> None:
|
|
1787
|
+
"""
|
|
1788
|
+
Chrome sends a screencast picture only when the page repaints: a short recording of a still page can end with
|
|
1789
|
+
none. Its screen as it is now is taken once, while the tab is still there, so the recording keeps its video
|
|
1790
|
+
(never while paused, never when a picture came).
|
|
1791
|
+
"""
|
|
1792
|
+
if video is None or not sid or sid not in self.pages or self.paused or getattr(video, "pictured", True):
|
|
1793
|
+
return
|
|
1794
|
+
try:
|
|
1795
|
+
shot = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": VIDEO_SCREENCAST["quality"]}, sid)
|
|
1796
|
+
data = shot.get("data") if isinstance(shot, dict) else None
|
|
1797
|
+
if isinstance(data, str):
|
|
1798
|
+
import base64
|
|
1799
|
+
|
|
1800
|
+
video.frame(base64.b64decode(data, validate=True))
|
|
1801
|
+
except Exception as ex:
|
|
1802
|
+
logger.debug("record: no last picture for the video: %s", ex)
|
|
1803
|
+
|
|
1744
1804
|
async def _finish_video(self) -> Optional[str]:
|
|
1745
1805
|
video, self.video = self.video, None
|
|
1746
1806
|
if video is None:
|
|
1747
1807
|
return None
|
|
1748
1808
|
sid, self._video_sid = self._video_sid, None
|
|
1809
|
+
await self._last_picture(video, sid)
|
|
1749
1810
|
if sid and sid in self.pages:
|
|
1750
1811
|
try:
|
|
1751
1812
|
await self.send("Page.stopScreencast", {}, sid)
|
|
@@ -23,7 +23,7 @@ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
|
|
23
23
|
from . import brand, userlike
|
|
24
24
|
from .diagnostics import Diagnostics, box_for
|
|
25
25
|
from .logins import _host_matches, can_sign_in, code_logins, guard_secrets, load_sessions, parse_logins, passkey_logins, prompt_block, push_logins, register_code_action, register_mfa_actions, save_sessions, use_env_secrets, use_logins
|
|
26
|
-
from .memory import READ_ONLY_ACTIONS, MemoryStore, compact_step, flow_step, page_id
|
|
26
|
+
from .memory import READ_ONLY_ACTIONS, UNSAVED_SECRET, MemoryStore, compact_step, flow_step, page_id, unsaved_secret_steps
|
|
27
27
|
from .prompts import CONVENTIONS, text as prompt_text, use_prompts
|
|
28
28
|
from .report import CASE_REPORT_INSTRUCTION, CaseReport, build_timeline, case_report_from_history
|
|
29
29
|
from .replay import ReplayOutcome, handoff_task, replay_flow
|
|
@@ -1436,6 +1436,8 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
|
|
|
1436
1436
|
extra_parts.append(saved_logins)
|
|
1437
1437
|
if req.case_steps > 0:
|
|
1438
1438
|
extra_parts.append(prompt_text("browser-case-report", CASE_REPORT_INSTRUCTION).replace("{n}", str(req.case_steps)))
|
|
1439
|
+
if overlay is not None:
|
|
1440
|
+
extra_parts.append(brand.AGENT_NOTE)
|
|
1439
1441
|
if (req.extend_system_message or "").strip():
|
|
1440
1442
|
extra_parts.append((req.extend_system_message or "").strip())
|
|
1441
1443
|
if req.skills:
|
|
@@ -1920,6 +1922,11 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
|
|
|
1920
1922
|
_save(out, "history", history=history, shot=shot)
|
|
1921
1923
|
return out
|
|
1922
1924
|
finally:
|
|
1925
|
+
if mem is not None:
|
|
1926
|
+
unsaved = unsaved_secret_steps(mem.steps)
|
|
1927
|
+
if unsaved:
|
|
1928
|
+
# Said in every run it happens: a sign-in the replay cannot do costs model steps on each run after.
|
|
1929
|
+
emit({"type": "log", "level": "warn", "text": f"Step {', '.join(map(str, unsaved[:5]))} {UNSAVED_SECRET}"})
|
|
1923
1930
|
if mem is not None and not mem.finished:
|
|
1924
1931
|
with contextlib.suppress(Exception):
|
|
1925
1932
|
mem.store.flush()
|
|
@@ -280,11 +280,25 @@ class FrameVideo:
|
|
|
280
280
|
return
|
|
281
281
|
self._stop.wait(step)
|
|
282
282
|
|
|
283
|
+
@property
|
|
284
|
+
def pictured(self) -> bool:
|
|
285
|
+
"""Whether a picture has come: a recording of a page that never repainted has none until one is taken."""
|
|
286
|
+
with self._lock:
|
|
287
|
+
return self._latest is not None
|
|
288
|
+
|
|
283
289
|
def close(self, timeout: float = FINISH_SECONDS) -> Optional[Path]:
|
|
284
290
|
"""Finish the file: its path, or None (nothing removed is left behind) when no video was made."""
|
|
285
291
|
self._stop.set()
|
|
286
292
|
if self._thread is not None:
|
|
287
293
|
self._thread.join(timeout=10)
|
|
294
|
+
# A picture that came after the writer's last turn (the only one, on a short recording of a still page): written
|
|
295
|
+
# once, so the video shows it rather than nothing at all.
|
|
296
|
+
if self.written == 0 and not self._held and not self.error:
|
|
297
|
+
with self._lock:
|
|
298
|
+
self._fresh = self._latest is not None
|
|
299
|
+
pixels = self._pixels_now()
|
|
300
|
+
if pixels is not None and self.exe and (self._proc is not None or self._open()):
|
|
301
|
+
self._write(pixels)
|
|
288
302
|
proc = self._proc
|
|
289
303
|
if proc is None:
|
|
290
304
|
return None
|