@capagents/forgeqe 3.2.5 → 3.2.7

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 (176) hide show
  1. package/HOW_TO_USE.md +12 -5
  2. package/dist/docs-site/CREDITS.md +3 -3
  3. package/dist/docs-site/{LICENSE.dm-sans.txt → LICENSE.geist.txt} +1 -1
  4. package/dist/docs-site/app-look.css +72 -32
  5. package/dist/docs-site/architecture-map/arch-theme.css +31 -40
  6. package/dist/docs-site/docs/app-theme.css +109 -108
  7. package/dist/docs-site/docs/architecture-reference/index.html +1 -0
  8. package/dist/docs-site/docs/area-api/index.html +17 -4
  9. package/dist/docs-site/docs/area-browser/index.html +2 -0
  10. package/dist/docs-site/docs/area-setup/index.html +1 -0
  11. package/dist/docs-site/docs/get-started/index.html +7 -4
  12. package/dist/docs-site/docs/overview/index.html +1 -1
  13. package/dist/docs-site/docs/search.js +1 -1
  14. package/dist/docs-site/docs/web-app/index.html +6 -3
  15. package/dist/docs-site/security/security-theme.css +66 -69
  16. package/dist/forgeqe.js +1890 -1860
  17. package/dist/web/THIRD_PARTY_NOTICES.md +0 -101
  18. package/dist/web/assets/{3d-force-graph-D62h_vvb.js → 3d-force-graph-CUGt_TSW.js} +1 -1
  19. package/dist/web/assets/Agent-DiX8ljlC.js +8 -0
  20. package/dist/web/assets/AgentWork-BpfMY_xu.js +2 -0
  21. package/dist/web/assets/ApiTests-4jfzlfVd.js +15 -0
  22. package/dist/web/assets/Browse-ByDemInL.js +1 -0
  23. package/dist/web/assets/Chat-C3wKV0CI.js +3 -0
  24. package/dist/web/assets/CommandPalette-CKJHtRjo.js +1 -0
  25. package/dist/web/assets/Compare-DtW2g-qb.js +1 -0
  26. package/dist/web/assets/Cost-DW-kVEL8.js +1 -0
  27. package/dist/web/assets/Data--HGneNun.js +6 -0
  28. package/dist/web/assets/Desktop-DQf5gv7D.js +1 -0
  29. package/dist/web/assets/DesktopReview-BaPYt0kl.js +2 -0
  30. package/dist/web/assets/DeviceScreen-DzVNfMwl.js +1 -0
  31. package/dist/web/assets/Evidence-CxRMnZch.js +1 -0
  32. package/dist/web/assets/Explore-ChpAuezG.js +2 -0
  33. package/dist/web/assets/Features-VsLb8QTH.js +1 -0
  34. package/dist/web/assets/Flags-Do-pvmCF.js +2 -0
  35. package/dist/web/assets/Flaky-CyhTszAg.js +1 -0
  36. package/dist/web/assets/Impact-BWBAXRuw.js +3 -0
  37. package/dist/web/assets/Jobs-C_MjXv0_.js +5 -0
  38. package/dist/web/assets/KindPage-Bb3Kp4-q.js +6 -0
  39. package/dist/web/assets/LiveDevice-OyxEiqBt.js +1 -0
  40. package/dist/web/assets/Migration-C80mGA3h.js +8 -0
  41. package/dist/web/assets/Mobile-C4wVBYfr.js +1 -0
  42. package/dist/web/assets/Observability-DdTOLp2C.js +1 -0
  43. package/dist/web/assets/PageAgent-Bi53-H99.js +1 -0
  44. package/dist/web/assets/Product-0LXndvp-.js +12 -0
  45. package/dist/web/assets/Production-oTXhv40a.js +1 -0
  46. package/dist/web/assets/Quality-CY0CJF9e.js +1 -0
  47. package/dist/web/assets/Readiness-Bv9uTTiI.js +1 -0
  48. package/dist/web/assets/Record-C-kyOkYq.js +1 -0
  49. package/dist/web/assets/Regression-CwKxvG1h.js +5 -0
  50. package/dist/web/assets/RelationGraph-BQl3M4zd.js +1 -0
  51. package/dist/web/assets/Reports-Ck8rc3br.js +2 -0
  52. package/dist/web/assets/Responsive-COmV2NXo.js +3 -0
  53. package/dist/web/assets/RunDiff-BBT1sQLh.js +1 -0
  54. package/dist/web/assets/Settings-7aMk9Sqx.js +21 -0
  55. package/dist/web/assets/Steps-C_vL6-8p.js +3 -0
  56. package/dist/web/assets/TestData-KzMy9N9f.js +2 -0
  57. package/dist/web/assets/TestManagement-BCEhOGB9.js +4 -0
  58. package/dist/web/assets/WhatsNew-DTcaqdOJ.js +1 -0
  59. package/dist/web/assets/agentSettingsSheet-DM1aa237.js +1 -0
  60. package/dist/web/assets/choice-B6z9CWyZ.js +1 -0
  61. package/dist/web/assets/code-DzYywAs5.js +1 -0
  62. package/dist/web/assets/{coverage-xSRsKFL6.js → coverage-BhtF065n.js} +4 -4
  63. package/dist/web/assets/dataParts-BNDVxwFb.js +3 -0
  64. package/dist/web/assets/desktopAppPath-D4hHP56R.js +1 -0
  65. package/dist/web/assets/frame-CNYHTG4T.js +13 -0
  66. package/dist/web/assets/index-B1Q2Dlqw.js +56 -0
  67. package/dist/web/assets/index-sxUpjgyw.css +2 -0
  68. package/dist/web/assets/markdown-BhU7ng6c.js +8 -0
  69. package/dist/web/assets/pageBack-BoSbGSU6.js +3 -0
  70. package/dist/web/assets/palette-BsY8OLxd.js +1 -0
  71. package/dist/web/assets/paletteCommands-DflHQ05x.js +1 -0
  72. package/dist/web/assets/parts-C4QMgN_N.js +1 -0
  73. package/dist/web/assets/preload-helper-qorOEK5q.js +1 -0
  74. package/dist/web/assets/productParts-Dxl-TQKY.js +1 -0
  75. package/dist/web/assets/qualityParts-ClGKtjEv.js +1 -0
  76. package/dist/web/assets/radio-DDxnnflQ.js +1 -0
  77. package/dist/web/assets/recordTest-B33rIncn.js +1 -0
  78. package/dist/web/assets/route-D9uPlFWw.js +1 -0
  79. package/dist/web/assets/sectionList-e5mFDaS2.js +1 -0
  80. package/dist/web/assets/stepper-DSDz0uu8.js +1 -0
  81. package/dist/web/index.html +10 -9
  82. package/docs/ARCHITECTURE_REFERENCE.md +1 -0
  83. package/docs/WEB_APP.md +6 -3
  84. package/docs/user-guide.html +26 -7
  85. package/forgeqe.example.yaml +3 -2
  86. package/llms.example.json +22 -0
  87. package/package.json +1 -1
  88. package/prompts/api-scenarios.md +1 -0
  89. package/prompts/brain.md +1 -0
  90. package/prompts/test-agent.md +0 -2
  91. package/prompts/test-rules.md +3 -8
  92. package/py/forgeqe_desktop/replay.py +48 -1
  93. package/py/forgeqe_desktop/workflow.py +79 -7
  94. package/py/forgeqe_engine/capture.py +19 -4
  95. package/py/forgeqe_engine/cli.py +12 -10
  96. package/py/forgeqe_engine/clientcert.py +28 -0
  97. package/py/forgeqe_engine/copilot_gateway.py +208 -23
  98. package/py/forgeqe_engine/d365.py +182 -0
  99. package/py/forgeqe_engine/logins.py +20 -16
  100. package/py/forgeqe_engine/memory.py +9 -3
  101. package/py/forgeqe_engine/recordsession.py +23 -3
  102. package/py/forgeqe_engine/webrecord.py +16 -0
  103. package/py/forgeqe_engine/webrecord_page.py +26 -1
  104. package/py/forgeqe_mobile/appium_driver.py +26 -0
  105. package/py/forgeqe_mobile/maestro.py +5 -1
  106. package/dist/web/assets/Agent-BadQe1GY.js +0 -8
  107. package/dist/web/assets/AgentWork-BGc6uVxB.js +0 -2
  108. package/dist/web/assets/ApiTests-Bo4ds0wk.js +0 -14
  109. package/dist/web/assets/Browse-CmVZJZ72.js +0 -1
  110. package/dist/web/assets/Chat-LTtQQHqr.js +0 -3
  111. package/dist/web/assets/CommandPalette-Dl_DibqU.js +0 -1
  112. package/dist/web/assets/Compare-Dlzg7S1a.js +0 -1
  113. package/dist/web/assets/Cost-DRKVox_i.js +0 -1
  114. package/dist/web/assets/Data-c2c1QLI9.js +0 -6
  115. package/dist/web/assets/Desktop-BMLYLWq1.js +0 -1
  116. package/dist/web/assets/DesktopReview-CO0vz-8o.js +0 -2
  117. package/dist/web/assets/DeviceScreen-CCDj-wqV.js +0 -1
  118. package/dist/web/assets/Evidence-BQmhYE2G.js +0 -1
  119. package/dist/web/assets/Explore-CVurlUoU.js +0 -2
  120. package/dist/web/assets/Features-DPc3_RSA.js +0 -1
  121. package/dist/web/assets/Flags-D4d9STIv.js +0 -2
  122. package/dist/web/assets/Flaky-Dt3iYOZg.js +0 -1
  123. package/dist/web/assets/Impact-CKy2Ezzt.js +0 -3
  124. package/dist/web/assets/Jobs-BZ4zn_7P.js +0 -5
  125. package/dist/web/assets/KindPage-joSX8gyV.js +0 -6
  126. package/dist/web/assets/LiveDevice-DQNdKoh3.js +0 -1
  127. package/dist/web/assets/Migration-EO--lNV1.js +0 -8
  128. package/dist/web/assets/Mobile-DWGNs3HT.js +0 -1
  129. package/dist/web/assets/Observability-DPjKbwcO.js +0 -1
  130. package/dist/web/assets/PageAgent-h70DL1L7.js +0 -1
  131. package/dist/web/assets/Product-ddlw8A_d.js +0 -12
  132. package/dist/web/assets/Production-svTscJhy.js +0 -1
  133. package/dist/web/assets/Quality-CgIo3fM8.js +0 -1
  134. package/dist/web/assets/Readiness-D6s73wXK.js +0 -1
  135. package/dist/web/assets/Record-Cmzr-0-f.js +0 -1
  136. package/dist/web/assets/Regression--3mygZAw.js +0 -5
  137. package/dist/web/assets/RelationGraph-BZYcwCVA.js +0 -1
  138. package/dist/web/assets/Reports-CDv_x9iB.js +0 -2
  139. package/dist/web/assets/Responsive-BhRYdJlZ.js +0 -3
  140. package/dist/web/assets/RunDiff-CO8asgjK.js +0 -1
  141. package/dist/web/assets/Settings-D3zWorNs.js +0 -21
  142. package/dist/web/assets/Steps-Dn12ePte.js +0 -3
  143. package/dist/web/assets/TestCases-CzXHBm5G.js +0 -1
  144. package/dist/web/assets/TestData-CL9bxSAI.js +0 -2
  145. package/dist/web/assets/TestDebt-B1_-OBJe.js +0 -1
  146. package/dist/web/assets/TestManagement-MwMgDuO_.js +0 -4
  147. package/dist/web/assets/WhatsNew-DLE9LimG.js +0 -1
  148. package/dist/web/assets/agents-DPabR9dS.js +0 -1
  149. package/dist/web/assets/dataParts-DAuDeT2W.js +0 -3
  150. package/dist/web/assets/desktopAppPath-C_bB4dWx.js +0 -1
  151. package/dist/web/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  152. package/dist/web/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  153. package/dist/web/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  154. package/dist/web/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  155. package/dist/web/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  156. package/dist/web/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  157. package/dist/web/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  158. package/dist/web/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  159. package/dist/web/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  160. package/dist/web/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  161. package/dist/web/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  162. package/dist/web/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  163. package/dist/web/assets/frame-DBWtBguh.js +0 -13
  164. package/dist/web/assets/index-ByIauY65.css +0 -2
  165. package/dist/web/assets/index-Tsofflw2.js +0 -57
  166. package/dist/web/assets/input-DX7REka8.js +0 -1
  167. package/dist/web/assets/markdown-Cj6qWQq7.js +0 -8
  168. package/dist/web/assets/pageBack-DmmT2q53.js +0 -3
  169. package/dist/web/assets/palette-CtM-T-2Q.js +0 -1
  170. package/dist/web/assets/paletteCommands-BYTeXpSW.js +0 -1
  171. package/dist/web/assets/parts-BQWLwMBf.js +0 -1
  172. package/dist/web/assets/productParts-2Ar8qxlW.js +0 -1
  173. package/dist/web/assets/qualityParts-_Sify8OE.js +0 -1
  174. package/dist/web/assets/recordTest-CL1Z2YWn.js +0 -1
  175. package/dist/web/assets/route-D8G-pTdk.js +0 -1
  176. package/dist/web/assets/stepper-p4Pkqn9_.js +0 -1
@@ -66,9 +66,16 @@ GAVE_UP_AFTER_S = 200.0
66
66
  # The words a failed request's error starts with when the gateway chose a stand-in for the next requests; the agent
67
67
  # runtime lets one retry through when it sees them (src/code/runtime.ts).
68
68
  SWITCHED = "GitHub Copilot switched models"
69
- # WebSockets for Copilot's Responses API are off: every request here is a new session, so a kept connection gains
70
- # nothing, and proxies that break WebSockets left requests unanswered. FORGEQE_COPILOT_WEBSOCKETS=1 turns them on.
69
+ # Copilot's Responses API: WebSockets first, plain HTTPS when they do not work here (many company proxies break
70
+ # WebSockets, which left requests unanswered rather than failing). FORGEQE_COPILOT_WEBSOCKETS=1 keeps WebSockets with
71
+ # no fallback, =0 keeps HTTPS; anything else is auto (websockets_mode).
71
72
  WEBSOCKETS_ENV = "FORGEQE_COPILOT_WEBSOCKETS"
73
+ # Until WebSockets have answered once, how long a request over them may go without a word from Copilot before they are
74
+ # taken for broken and the request is sent again over HTTPS. Copilot says something (the reply starting, its reasoning
75
+ # or its streaming progress) well before this on a working connection.
76
+ WS_PROBE_S = 45.0
77
+ # How long HTTPS is kept after WebSockets failed, in copilot/transport.json, before WebSockets are tried again.
78
+ HTTPS_KEPT_S = 7 * 24 * 3600.0
72
79
  SDK_NO_WEBSOCKETS_ENV = "COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES"
73
80
  # How long the seat's model list is kept before it is asked again.
74
81
  SEAT_TTL_S = 600.0
@@ -76,6 +83,8 @@ SEAT_TTL_S = 600.0
76
83
  # sometimes never does (github/copilot-sdk#2853), which held a request, and every agent waiting on it, for the full
77
84
  # REQUEST_TIMEOUT_S.
78
85
  TURN_END_GRACE_S = 5.0
86
+ # How long a stopping gateway lets sessions still closing finish.
87
+ CLOSE_WAIT_S = 10.0
79
88
  # A tool name as OpenAI and the Copilot SDK take it.
80
89
  TOOL_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
81
90
  MAX_TOOLS = 256
@@ -89,6 +98,10 @@ class GatewayError(Exception):
89
98
  self.message = message
90
99
 
91
100
 
101
+ class TransportSilent(Exception):
102
+ """Over WebSockets not yet known to work here, Copilot said nothing within WS_PROBE_S."""
103
+
104
+
92
105
  class CallerGone(Exception):
93
106
  """The caller closed the connection (the user pressed Stop): its Copilot session is stopped, nothing is answered."""
94
107
 
@@ -98,6 +111,11 @@ _log = logging.getLogger("forgeqe.copilot_gateway")
98
111
  _log.propagate = False
99
112
 
100
113
 
114
+ def ms(since: float) -> int:
115
+ """Milliseconds since a time.monotonic() reading, for the log."""
116
+ return int((time.monotonic() - since) * 1000)
117
+
118
+
101
119
  def gateway_log(rid: str, text: str) -> None:
102
120
  _log.info("%s %s", rid, text)
103
121
 
@@ -483,8 +501,69 @@ def with_screenshots(req: Dict[str, Any], level: int) -> Dict[str, Any]:
483
501
  return {**req, "attachments": [], "prompt": prompt}
484
502
 
485
503
 
504
+ def websockets_mode(env: Optional[Dict[str, str]] = None) -> str:
505
+ """on: WebSockets only; off: HTTPS only; auto (anything else, unset too): WebSockets first, HTTPS when they fail."""
506
+ value = str((os.environ if env is None else env).get(WEBSOCKETS_ENV, "")).strip().lower()
507
+ if value in ("1", "true", "yes", "on"):
508
+ return "on"
509
+ if value in ("0", "false", "no", "off"):
510
+ return "off"
511
+ return "auto"
512
+
513
+
486
514
  def websockets_on(env: Optional[Dict[str, str]] = None) -> bool:
487
- return str((os.environ if env is None else env).get(WEBSOCKETS_ENV, "")).strip().lower() in ("1", "true", "yes", "on")
515
+ return websockets_mode(env) == "on"
516
+
517
+
518
+ # Copilot's words when a WebSocket could not be opened or was cut: a proxy that refuses the upgrade or drops the stream.
519
+ _WS_FAILED = re.compile(r"web ?socket|\bwss?://|\bupgrade\b|handshake|\b1006\b|socket hang up|econnreset|connection (?:was )?(?:reset|closed|aborted)", re.I)
520
+
521
+
522
+ def websocket_failed(message: str) -> bool:
523
+ """Whether Copilot's error says the WebSocket itself failed (not the model, the sign-in or a limit)."""
524
+ return bool(_WS_FAILED.search(message or ""))
525
+
526
+
527
+ def transport_file() -> str:
528
+ home = os.environ.get("FORGEQE_HOME") or os.path.join(os.path.expanduser("~"), ".forgeqe")
529
+ return os.path.join(home, "copilot", "transport.json")
530
+
531
+
532
+ def https_kept(path: str, now: Optional[float] = None) -> bool:
533
+ """Whether WebSockets failed here recently: transport.json read as untrusted, a time within HTTPS_KEPT_S only."""
534
+ now = time.time() if now is None else now
535
+ try:
536
+ if os.path.islink(path):
537
+ return False
538
+ with open(path, "r", encoding="utf-8") as f:
539
+ raw = json.load(f)
540
+ except (OSError, ValueError):
541
+ return False
542
+ until = raw.get("https_until") if isinstance(raw, dict) else None
543
+ return isinstance(until, (int, float)) and not isinstance(until, bool) and now < until <= now + HTTPS_KEPT_S
544
+
545
+
546
+ def keep_https(path: str, now: Optional[float] = None) -> None:
547
+ """Remembers that WebSockets failed: written through a new file at 0600, never through a link."""
548
+ now = time.time() if now is None else now
549
+ try:
550
+ folder = os.path.dirname(path)
551
+ os.makedirs(folder, exist_ok=True)
552
+ if os.path.islink(path):
553
+ return
554
+ fd, tmp = tempfile.mkstemp(prefix=".transport-", dir=folder)
555
+ try:
556
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
557
+ json.dump({"https_until": now + HTTPS_KEPT_S}, f)
558
+ os.chmod(tmp, 0o600)
559
+ os.replace(tmp, path)
560
+ except Exception:
561
+ try:
562
+ os.unlink(tmp)
563
+ except OSError:
564
+ pass
565
+ except OSError:
566
+ pass
488
567
 
489
568
 
490
569
  def capi_options(websockets: bool) -> Optional[Dict[str, Any]]:
@@ -616,10 +695,17 @@ class Copilot:
616
695
  # An empty working folder: the session reads no project files and no custom instructions.
617
696
  self.workdir = tempfile.mkdtemp(prefix="forgeqe-copilot-")
618
697
  self.signed_in_user = not token
619
- self.websockets = websockets_on()
698
+ self.ws_mode = websockets_mode()
699
+ self.transport_path = transport_file()
700
+ kept = self.ws_mode == "auto" and https_kept(self.transport_path)
701
+ self.websockets = self.ws_mode == "on" or (self.ws_mode == "auto" and not kept)
702
+ # Forced on, there is nothing to fall back to: no watchdog.
703
+ self.ws_proven = self.ws_mode == "on"
620
704
  if not self.websockets:
621
705
  # The runtime the SDK starts reads this too, for every request it makes (the model list included).
622
706
  os.environ[SDK_NO_WEBSOCKETS_ENV] = "1"
707
+ if kept:
708
+ gateway_log("gateway", "Copilot's responses go over HTTPS: WebSockets failed on this computer recently (copilot/transport.json)")
623
709
  # Before the client: it looks for (and downloads) its runtime as it is made.
624
710
  self.runtime = runtime_fallback()
625
711
  if self.runtime:
@@ -631,6 +717,8 @@ class Copilot:
631
717
  # Caller tools named like one of Copilot's own: they must say they replace it. Learned from Copilot's answers
632
718
  # (BUILTIN_TOOLS to start with), kept for the gateway's life, so only a first request pays a retry.
633
719
  self.replaces: set = set(BUILTIN_TOOLS)
720
+ # Sessions being closed after their answer went out (close_later), kept so they finish before the gateway stops.
721
+ self._closing: set = set()
634
722
 
635
723
  async def start(self) -> None:
636
724
  await self.client.start()
@@ -655,6 +743,9 @@ class Copilot:
655
743
  return GatewayError(401, f"GitHub Copilot refused {what}{who}: {message}"[:2000])
656
744
 
657
745
  async def stop(self) -> None:
746
+ closing = getattr(self, "_closing", None)
747
+ if closing:
748
+ await asyncio.wait(list(closing), timeout=CLOSE_WAIT_S)
658
749
  try:
659
750
  await self.client.stop()
660
751
  except Exception:
@@ -757,7 +848,8 @@ class Copilot:
757
848
  f"GitHub Copilot's server could not be reached from this computer: check the network or proxy for "
758
849
  f"api.business.githubcopilot.com. {e.message}"[:2000],
759
850
  )
760
- if not model_failed(e.status, e.message):
851
+ # A broken WebSocket is the network's, never the model's.
852
+ if not model_failed(e.status, e.message) or websocket_failed(e.message):
761
853
  raise
762
854
  self.health.fail(model)
763
855
  other = stand_in(seat, self.health, model, needs_vision, auto_ok=True)
@@ -799,8 +891,44 @@ class Copilot:
799
891
  gateway_log(rid, f"done after {time.monotonic() - started:.1f}s" + (f" calls={','.join(c['function']['name'] for c in calls)}" if calls else ""))
800
892
  return out
801
893
 
894
+ def use_https(self, rid: str, why: str) -> None:
895
+ """Leaves WebSockets for plain HTTPS, for this gateway and, kept in transport.json, for HTTPS_KEPT_S."""
896
+ self.websockets = False
897
+ keep_https(getattr(self, "transport_path", None) or transport_file())
898
+ gateway_log(rid, f"WebSockets did not work ({why}): this request and the next ones go over HTTPS, kept for {int(HTTPS_KEPT_S // 86400)} days before WebSockets are tried again")
899
+
900
+ def falls_back(self) -> bool:
901
+ """Whether a failure over WebSockets can still move to HTTPS (auto, and the request went over WebSockets)."""
902
+ return bool(self.websockets) and getattr(self, "ws_mode", "auto") == "auto"
903
+
904
+ def close_later(self, rid: str, session: Any, clean: bool) -> None:
905
+ """
906
+ Closes a request's session after its answer has gone out: a session that did not finish cleanly is stopped
907
+ first (detaching alone leaves Copilot working on it). Closing used to happen before the answer was sent, so every
908
+ call waited for it, and on Windows that is often a noticeable part of the call.
909
+ """
910
+
911
+ async def close() -> None:
912
+ began = time.monotonic()
913
+ if not clean:
914
+ try:
915
+ await session.abort()
916
+ except Exception:
917
+ pass
918
+ try:
919
+ await session.disconnect()
920
+ except Exception:
921
+ pass
922
+ gateway_log(rid, f"session closed in {ms(began)}ms" + ("" if clean else " (stopped first)"))
923
+
924
+ closing = self.__dict__.setdefault("_closing", set())
925
+ task = asyncio.ensure_future(close())
926
+ closing.add(task)
927
+ task.add_done_callback(closing.discard)
928
+
802
929
  async def _complete(self, rid: str, req: Dict[str, Any], on_text: Optional[Callable[[str], None]], gone: Optional["asyncio.Future[Any]"]) -> Dict[str, Any]:
803
930
  from copilot.generated.rpc import PermissionDecisionReject
931
+ from copilot import session_events as _events
804
932
  from copilot.session_events import (
805
933
  AssistantMessageData,
806
934
  AssistantMessageDeltaData,
@@ -811,6 +939,16 @@ class Copilot:
811
939
  SessionIdleData,
812
940
  )
813
941
 
942
+ # What only Copilot's server sends: any of these says the connection carries its answer.
943
+ heard = tuple(
944
+ c
945
+ for c in (getattr(_events, n, None) for n in (
946
+ "AssistantMessageStartData", "AssistantReasoningDeltaData", "AssistantReasoningData", "AssistantStreamingDeltaData",
947
+ "AssistantToolCallDeltaData", "AssistantTurnRetryData", "AssistantIntentData",
948
+ ))
949
+ if isinstance(c, type)
950
+ ) + (AssistantMessageData, AssistantMessageDeltaData, AssistantUsageData, SessionErrorData)
951
+
814
952
  loop = asyncio.get_running_loop()
815
953
 
816
954
  # The text callback while this request streams; None once it is asked for again without streaming.
@@ -822,7 +960,7 @@ class Copilot:
822
960
  statuses: List[Optional[int]] = []
823
961
  calls: List[Dict[str, Any]] = []
824
962
  # The last root reply without tool requests, and the timer that ends the wait when a turn ends without idle.
825
- turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event(), "messages": []}
963
+ turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event(), "messages": [], "sent": time.monotonic(), "heard": asyncio.Event()}
826
964
 
827
965
  def on_loop(fn: Callable[[], None]) -> None:
828
966
  """The SDK may call on_event from a thread of its own; timers and events belong to the server's loop."""
@@ -845,6 +983,8 @@ class Copilot:
845
983
 
846
984
  def on_event(event: Any) -> None:
847
985
  data = getattr(event, "data", None)
986
+ if isinstance(data, heard) and not turn["heard"].is_set():
987
+ on_loop(turn["heard"].set)
848
988
  if isinstance(data, AssistantUsageData):
849
989
  usage["input"] += data.input_tokens or 0
850
990
  usage["output"] += data.output_tokens or 0
@@ -868,11 +1008,11 @@ class Copilot:
868
1008
  elif isinstance(data, AssistantTurnStartData) and not data.parent_tool_call_id:
869
1009
  on_loop(unsettle)
870
1010
  elif isinstance(data, AssistantTurnEndData) and not data.parent_tool_call_id:
871
- gateway_log(rid, "turn ended" + (" with a call of the caller's tools" if calls else " with a reply" if turn["final"] is not None else ""))
1011
+ gateway_log(rid, "turn ended" + (" with a call of the caller's tools" if calls else " with a reply" if turn["final"] is not None else "") + f" after {time.monotonic() - turn['sent']:.1f}s")
872
1012
  if calls or turn["final"] is not None:
873
1013
  on_loop(settle_soon)
874
1014
  elif isinstance(data, SessionIdleData):
875
- gateway_log(rid, "idle")
1015
+ gateway_log(rid, f"idle after {time.monotonic() - turn['sent']:.1f}s")
876
1016
 
877
1017
  tried: set = set()
878
1018
  reply: Any = None
@@ -885,6 +1025,7 @@ class Copilot:
885
1025
  turn["final"] = None
886
1026
  turn["messages"] = []
887
1027
  turn["settled"] = asyncio.Event()
1028
+ turn["heard"] = asyncio.Event()
888
1029
  names = {t["name"] for t in req["tools"]}
889
1030
  tools = relay_tools(req["tools"], calls, replaces=self.replaces & names)
890
1031
  options: Dict[str, Any] = dict(
@@ -905,18 +1046,26 @@ class Copilot:
905
1046
  **({"reasoning_effort": effort} if effort else {}),
906
1047
  **({"streaming": True} if stream["to"] else {}),
907
1048
  )
908
- capi = capi_options(self.websockets)
1049
+ over_ws = bool(self.websockets)
1050
+ capi = capi_options(over_ws)
909
1051
  if capi is not None:
910
1052
  options["capi"] = capi
1053
+ # Until WebSockets have answered here once, a silent request over them is taken for a broken connection.
1054
+ probe = WS_PROBE_S if over_ws and self.falls_back() and not getattr(self, "ws_proven", False) else None
911
1055
  failure: Optional[str] = None
1056
+ silent = False
912
1057
  session = None
913
1058
  # A session that did not finish cleanly is stopped before it is detached: detaching alone leaves Copilot
914
1059
  # working on it in the background.
915
1060
  clean = False
916
1061
  try:
1062
+ opening = time.monotonic()
917
1063
  session = await self.client.create_session(**options)
918
- gateway_log(rid, f"session {getattr(session, 'session_id', '?')}")
919
- reply, clean = await self._wait(rid, session, req, turn, gone)
1064
+ gateway_log(rid, f"session {getattr(session, 'session_id', '?')} opened in {ms(opening)}ms")
1065
+ turn["sent"] = time.monotonic()
1066
+ reply, clean = await self._wait(rid, session, req, turn, gone, probe)
1067
+ except TransportSilent:
1068
+ silent = True
920
1069
  except TimeoutError:
921
1070
  raise GatewayError(504, f"GitHub Copilot did not answer within {int(REQUEST_TIMEOUT_S)} seconds.")
922
1071
  except CallerGone:
@@ -926,15 +1075,19 @@ class Copilot:
926
1075
  finally:
927
1076
  on_loop(unsettle)
928
1077
  if session is not None:
929
- if not clean:
930
- try:
931
- await session.abort()
932
- except Exception:
933
- pass
934
- try:
935
- await session.disconnect()
936
- except Exception:
937
- pass
1078
+ self.close_later(rid, session, clean)
1079
+ # WebSockets that do not work here: the same request again over HTTPS, if nothing reached the caller yet.
1080
+ problem = failure or (errors[-1] if errors and not calls else "")
1081
+ if over_ws and self.falls_back() and not stream["sent"] and (
1082
+ silent or (problem and (websocket_failed(problem) or (not getattr(self, "ws_proven", False) and network_failed(problem))))
1083
+ ):
1084
+ self.use_https(rid, f"no word from Copilot within {int(WS_PROBE_S)}s" if silent else "the connection failed")
1085
+ continue
1086
+ if silent:
1087
+ raise GatewayError(504, f"GitHub Copilot did not answer within {int(WS_PROBE_S)} seconds.")
1088
+ if over_ws and not getattr(self, "ws_proven", False) and turn["heard"].is_set() and not problem:
1089
+ self.ws_proven = True
1090
+ gateway_log(rid, "WebSockets work: Copilot's responses go over them")
938
1091
  # Copilot reports a clash with its own tools when the session starts or when the turn starts.
939
1092
  fix = tool_conflict(failure or (errors[-1] if errors and not calls else ""), names)
940
1093
  if fix and fix not in tried:
@@ -986,22 +1139,43 @@ class Copilot:
986
1139
  return out
987
1140
 
988
1141
 
989
- async def _wait(self, rid: str, session: Any, req: Dict[str, Any], turn: Dict[str, Any], gone: Optional["asyncio.Future[Any]"]) -> Tuple[Any, bool]:
1142
+ async def _wait(
1143
+ self, rid: str, session: Any, req: Dict[str, Any], turn: Dict[str, Any], gone: Optional["asyncio.Future[Any]"], probe: Optional[float] = None
1144
+ ) -> Tuple[Any, bool]:
990
1145
  """
991
1146
  The reply, and whether Copilot finished cleanly. Copilot normally says it is idle; when a turn has ended with a
992
1147
  reply or a call of the caller's tools and it does not, the reply is taken TURN_END_GRACE_S later. A caller that
993
- hangs up ends the wait at once.
1148
+ hangs up ends the wait at once. With `probe`, Copilot saying nothing at all for that long raises TransportSilent.
994
1149
  """
1150
+ loop = asyncio.get_running_loop()
995
1151
  waiter = asyncio.ensure_future(
996
1152
  session.send_and_wait(req["prompt"], attachments=req["attachments"] or None, response_schema=req["schema"], timeout=REQUEST_TIMEOUT_S)
997
1153
  )
998
1154
  waiter.add_done_callback(lambda t: t.cancelled() or t.exception())
999
1155
  settled = asyncio.ensure_future(turn["settled"].wait())
1000
1156
  watch = {waiter, settled} | ({gone} if gone is not None else set())
1157
+ quiet: Optional["asyncio.Future[bool]"] = asyncio.ensure_future(_silent_for(turn["heard"], probe)) if probe else None
1158
+ if quiet is not None:
1159
+ watch.add(quiet)
1160
+ deadline = loop.time() + REQUEST_TIMEOUT_S + 5
1161
+ done: set = set()
1001
1162
  try:
1002
- done, _ = await asyncio.wait(watch, timeout=REQUEST_TIMEOUT_S + 5, return_when=asyncio.FIRST_COMPLETED)
1163
+ while True:
1164
+ left = deadline - loop.time()
1165
+ if left <= 0:
1166
+ done = set()
1167
+ break
1168
+ done, _ = await asyncio.wait(watch, timeout=left, return_when=asyncio.FIRST_COMPLETED)
1169
+ if quiet is not None and done == {quiet} and not quiet.result():
1170
+ # Copilot spoke: no more watching for silence.
1171
+ watch.discard(quiet)
1172
+ quiet = None
1173
+ continue
1174
+ break
1003
1175
  finally:
1004
1176
  settled.cancel()
1177
+ if quiet is not None:
1178
+ quiet.cancel()
1005
1179
  if waiter in done:
1006
1180
  return waiter.result(), True
1007
1181
  waiter.cancel()
@@ -1010,9 +1184,20 @@ class Copilot:
1010
1184
  if settled in done:
1011
1185
  gateway_log(rid, f"the turn ended but Copilot did not say it was idle within {TURN_END_GRACE_S:.0f}s: answered anyway")
1012
1186
  return turn["final"], False
1187
+ if quiet is not None and quiet in done and quiet.result():
1188
+ raise TransportSilent()
1013
1189
  raise TimeoutError()
1014
1190
 
1015
1191
 
1192
+ async def _silent_for(heard: asyncio.Event, seconds: float) -> bool:
1193
+ """True when `heard` stayed unset for `seconds`; False as soon as it is set."""
1194
+ try:
1195
+ await asyncio.wait_for(heard.wait(), seconds)
1196
+ return False
1197
+ except asyncio.TimeoutError:
1198
+ return True
1199
+
1200
+
1016
1201
  # Copilot's own tools that the agent runtime's tools are named like (bash, glob, grep, edit, …). A caller tool with one
1017
1202
  # of these names says it replaces Copilot's: the caller's tool is the one offered, and it runs nothing here.
1018
1203
  BUILTIN_TOOLS = frozenset({"bash", "powershell", "glob", "grep", "view", "edit", "create", "task", "skill", "web_fetch", "think", "update_todo", "report_intent"})
@@ -0,0 +1,182 @@
1
+ """
2
+ Dynamics 365 / Power Apps model-driven apps, as the recorder sees them (ADO 3529).
3
+
4
+ The browser agent reads the `dynamics-365` skill and the coding agent `dynamics-365-automation`, whose catalogue
5
+ (`skills/dynamics-365-automation/references/elements.md`, from Microsoft's EasyRepro) says how D365 names its
6
+ controls: by its own attributes (`data-id`, `data-lp-id`, `data-type`, `data-control-name`), never by a generated id.
7
+ A hand recording has no model to read a skill, so the same rules are code here, and `tests/engine/test_d365.py`
8
+ checks that every selector shape below is one the skill's catalogue holds.
9
+
10
+ D365 renders ids from where a control sits (`AppModuleTileSec_1_Item_1`: the first tile of the first section of the
11
+ app picker's results; `id-6a1c…-12`, `quickFind_text_1`). They look steady and match on the page they were read from,
12
+ so the recorder ranked them first, and a replay with other results, another order or another session found nothing.
13
+
14
+ What the page gives is untrusted: an attribute is kept only by a name of `ATTRS`, and a value only when it is plain
15
+ (`plain`), so a selector built from it is one attribute test and nothing else.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import Any, Dict, List
21
+
22
+ SITE = "d365"
23
+
24
+ # Hosts of Dynamics 365 / Dataverse model-driven apps: commercial (crm, crm2…crm21), China, Germany, US government.
25
+ # An app on another host (on-premises) is told by the page itself: `#ApplicationShell`, the UCI's root (elements.md
26
+ # "App shell"); `HOST_JS` and `SHELL_ID` go to the page scripts so both sides decide alike.
27
+ HOST = re.compile(r"(?:^|\.)crm\d*\.(?:dynamics\.com|dynamics\.cn|microsoftdynamics\.de|microsoftdynamics\.us|appsplatform\.us)$", re.I)
28
+ HOST_JS = r"(?:^|\.)crm\d*\.(?:dynamics\.com|dynamics\.cn|microsoftdynamics\.de|microsoftdynamics\.us|appsplatform\.us)$"
29
+ SHELL_ID = "ApplicationShell"
30
+
31
+ # D365's own attributes that name a control (elements.md). Read only on a D365 page.
32
+ ATTRS = ("data-id", "data-lp-id", "data-type", "data-control-name")
33
+ # The only data-type value that names a thing: an app tile on the app landing page (elements.md Nav_UCIAppTile).
34
+ APP_TILE = "app-title"
35
+
36
+ # A D365 id or attribute value made from where the control sits or from a record: a number standing alone between
37
+ # separators (a section, an item, a row index), a GUID, or the Fluent UI ids D365 renders (`id__123`, `id-…`).
38
+ # `emailaddress1`, `address1_line1` keep their digits inside a word, so they stay.
39
+ GENERATED = re.compile(r"(?:^|[_\-.:])\d+(?:$|[_\-.:])|[0-9a-f]{8}-[0-9a-f]{4}-|^id(?:__|-)|^AppModuleTile", re.I)
40
+ GENERATED_JS = r"(?:^|[_\-.:])\d+(?:$|[_\-.:])|[0-9a-f]{8}-[0-9a-f]{4}-|^id(?:__|-)|^AppModuleTile"
41
+
42
+ # Above an id (memory.BASE["id"] 0.90) and a test id: the catalogue's attributes are what D365 keeps across sessions
43
+ # and releases, where its ids are not.
44
+ BASE = 0.95
45
+ MAX_VALUE = 120
46
+ # How far up from the element the recorder looks for the D365 control it belongs to (a tile, a command, a row).
47
+ MAX_UP = 4
48
+ FORM_TAGS = frozenset({"input", "textarea", "select"})
49
+ _TAG = re.compile(r"^[a-z][a-z0-9-]{0,30}$")
50
+
51
+
52
+ def is_d365_url(url: str) -> bool:
53
+ from urllib.parse import urlparse
54
+
55
+ try:
56
+ host = urlparse(url or "").hostname or ""
57
+ except Exception:
58
+ return False
59
+ return bool(host and HOST.search(host))
60
+
61
+
62
+ def plain(value: Any) -> bool:
63
+ """A value that goes into a selector as it is: one line, short, no quote, backslash or angle bracket."""
64
+ return isinstance(value, str) and 0 < len(value) <= MAX_VALUE and not re.search(r"[\"'\\<>\x00-\x1f\x7f]", value)
65
+
66
+
67
+ def generated(value: str) -> bool:
68
+ """A D365 id or attribute made from where the control sits or from a record: it changes on another run."""
69
+ return bool(GENERATED.search(value or ""))
70
+
71
+
72
+ def generated_path(xpath: str) -> bool:
73
+ """A relative XPath the page script built on an id or name D365 renders from position (`//div[@id='AppModuleTileSec_1_Item_1']`)."""
74
+ return any(generated(v) for v in re.findall(r"@(?:id|name)\s*=\s*['\"]([^'\"]*)['\"]", xpath or ""))
75
+
76
+
77
+ def page_config() -> Dict[str, Any]:
78
+ """What the page scripts need to tell a D365 page and read its attributes (webrecord_page.py, capture.py)."""
79
+ return {"host": HOST_JS, "shell": SHELL_ID, "attrs": list(ATTRS), "gen": GENERATED_JS, "up": MAX_UP}
80
+
81
+
82
+ def _attrs(raw: Any) -> Dict[str, str]:
83
+ if not isinstance(raw, dict):
84
+ return {}
85
+ out = {k: raw[k] for k in ATTRS if plain(raw.get(k))}
86
+ if plain(raw.get("title")):
87
+ out["title"] = raw["title"]
88
+ return out
89
+
90
+
91
+ def clean_facts(facts: Dict[str, Any]) -> Dict[str, Any]:
92
+ """
93
+ An element's facts as the page script read them, with D365's parts kept only in their shapes: `site` only "d365",
94
+ its attributes only by a name of `ATTRS` with a plain value, the control it belongs to (`d365_up`) only a tag and
95
+ such attributes. Anything else the page sent is dropped. On a page that is not D365, none of it is kept.
96
+ """
97
+ out = dict(facts)
98
+ attrs = dict(out.get("attributes") or {})
99
+ up = out.pop("d365_up", None)
100
+ if out.get("site") != SITE:
101
+ out.pop("site", None)
102
+ for k in ATTRS:
103
+ attrs.pop(k, None)
104
+ out["attributes"] = attrs
105
+ return out
106
+ for k in ATTRS:
107
+ if k in attrs and not plain(attrs[k]):
108
+ attrs.pop(k)
109
+ out["attributes"] = attrs
110
+ if isinstance(up, dict) and isinstance(up.get("tag"), str) and _TAG.match(up["tag"]):
111
+ a = _attrs(up.get("attributes"))
112
+ if any(k in a for k in ATTRS):
113
+ out["d365_up"] = {"tag": up["tag"], "attributes": a}
114
+ return out
115
+
116
+
117
+ def _q(v: str) -> str:
118
+ return '"' + v + '"'
119
+
120
+
121
+ def _selectors(tag: str, a: Dict[str, str]) -> List[Dict[str, str]]:
122
+ """The catalogue's selector shapes for one element's attributes, steadiest first, each with the attribute it counts by."""
123
+ out: List[Dict[str, str]] = []
124
+ title = a.get("title") or ""
125
+ # App tile: `div[data-type="app-title"][title="<app name>"]` (elements.md Nav_UCIAppTile).
126
+ if a.get("data-type") == APP_TILE and plain(title):
127
+ out.append({"css": f"{tag}[data-type={_q(APP_TILE)}][title={_q(title)}]", "attr": "title", "value": title})
128
+ # `[data-id="<field>.fieldControl-…"]`, `button[data-id*="Mscrm.Form.account.Save"]`, `a[data-id="appBreadCrumb"]`.
129
+ for k in ("data-id", "data-lp-id", "data-control-name"):
130
+ v = a.get(k) or ""
131
+ if plain(v) and not generated(v):
132
+ out.append({"css": f"{tag}[{k}={_q(v)}]", "attr": k, "value": v})
133
+ return out
134
+
135
+
136
+ def locators(f: Dict[str, Any]) -> List[Dict[str, Any]]:
137
+ """
138
+ Locators the D365 catalogue gives for an element: on the element itself, then on the D365 control it is inside (a
139
+ click on an app tile's name is a click on the tile), never for a field's input by its container. Each is a `css`
140
+ locator a replay builds as `page.locator(css)`, marked `site: d365`; `up` when it finds the control around it.
141
+ """
142
+ if f.get("site") != SITE:
143
+ return []
144
+ tag = str(f.get("tag") or "")
145
+ if not _TAG.match(tag):
146
+ return []
147
+ out: List[Dict[str, Any]] = []
148
+ seen = set()
149
+
150
+ def add(sel: Dict[str, str], up: bool) -> None:
151
+ if sel["css"] in seen:
152
+ return
153
+ seen.add(sel["css"])
154
+ css = sel["css"]
155
+ loc: Dict[str, Any] = {
156
+ "type": "css", "value": css, "css": css, "playwright": f"page.locator({_js(css)})", "base": BASE, "site": SITE,
157
+ # Counted by the page script at the event through this attribute (recordsession._count): an upper bound, as
158
+ # the selector is narrower than the attribute alone.
159
+ **({"count_attr": sel["attr"]} if not up else {}),
160
+ }
161
+ if up:
162
+ loc["up"] = True
163
+ out.append(loc)
164
+
165
+ for sel in _selectors(tag, f.get("attributes") or {}):
166
+ add(sel, False)
167
+ up = f.get("d365_up")
168
+ if tag not in FORM_TAGS and isinstance(up, dict) and _TAG.match(str(up.get("tag") or "")):
169
+ for sel in _selectors(str(up["tag"]), up.get("attributes") or {}):
170
+ add(sel, True)
171
+ return out
172
+
173
+
174
+ def _js(s: str) -> str:
175
+ import json
176
+
177
+ return json.dumps(s)
178
+
179
+
180
+ def note() -> str:
181
+ """One line for the recording's log, said once when the recorder first sees a D365 page."""
182
+ return "Dynamics 365 page: elements are found by D365's own attributes (data-id, app tiles by name), as the dynamics-365 skill says, never by the ids D365 renders from position."
@@ -318,10 +318,11 @@ def write_session(file: str, state: Dict[str, Any]) -> None:
318
318
  os.replace(tmp, path)
319
319
 
320
320
 
321
- async def interactive_login(payload: Dict[str, Any], emit: Any, finished: Any) -> Dict[str, Any]:
321
+ async def interactive_login(payload: Dict[str, Any], emit: Any, next_command: Any) -> Dict[str, Any]:
322
322
  """
323
323
  Open a visible browser on the login's page with any saved session, let a person sign in, and save the session
324
- when `finished` is set by a "save" line on stdin.
324
+ when `next_command()` gives "save" ("stop" cancels). A "save" pressed before the person signed in (nothing of the
325
+ login's sites to keep yet) leaves the browser open and says so (`not_signed_in`), so it is never closed under them.
325
326
  """
326
327
  from browser_use import Browser
327
328
 
@@ -352,21 +353,24 @@ async def interactive_login(payload: Dict[str, Any], emit: Any, finished: Any) -
352
353
  enroll = (enroll_cdp, await add_authenticator(enroll_cdp))
353
354
  await browser._cdp_navigate(url)
354
355
  if overlay is not None:
355
- await overlay.waiting(f"Sign in to {logins[0].name} here, then press Enter in the terminal to save the session")
356
+ await overlay.waiting(f"Sign in to {logins[0].name} here, then confirm in ForgeQE to save the session")
356
357
  emit({"type": "log", "level": "info", "text": f"Browser open at {url}"})
357
- await finished.wait()
358
- if payload.get("cancelled"):
359
- return {"success": False, "error": "cancelled"}
360
- saved = await save_sessions(browser, logins, {})
361
- if enroll is not None:
362
- from .passkey import read_credentials
363
-
364
- creds = await read_credentials(*enroll)
365
- # The credential is a secret: it goes back to ForgeQE on this pipe only, which keeps it in the credential store.
366
- return {"success": True, "saved": saved, "passkey": creds, "summary": f"{len(creds)} security key{'' if len(creds) == 1 else 's'} registered"}
367
- if not saved:
368
- return {"success": False, "error": f"No cookies or local storage for {', '.join(logins[0].domains)} were found; nothing was saved."}
369
- return {"success": True, "saved": saved, "summary": f"Session saved for {', '.join(saved)}"}
358
+ while True:
359
+ if await next_command() != "save":
360
+ return {"success": False, "error": "cancelled"}
361
+ if enroll is not None:
362
+ from .passkey import read_credentials
363
+
364
+ saved = await save_sessions(browser, logins, {})
365
+ creds = await read_credentials(*enroll)
366
+ # The credential is a secret: it goes back to ForgeQE on this pipe only, which keeps it in the credential store.
367
+ return {"success": True, "saved": saved, "passkey": creds, "summary": f"{len(creds)} security key{'' if len(creds) == 1 else 's'} registered"}
368
+ saved = await save_sessions(browser, logins, {})
369
+ if saved:
370
+ return {"success": True, "saved": saved, "summary": f"Session saved for {', '.join(saved)}"}
371
+ # Nothing to keep yet: the person has not finished signing in (an account picker, a code still open). The
372
+ # browser stays open and ForgeQE asks again.
373
+ emit({"type": "not_signed_in", "text": f"No cookies or local storage for {', '.join(logins[0].domains)} yet: finish signing in in the browser window."})
370
374
  finally:
371
375
  await _shutdown_browser_instance(browser)
372
376