@capagents/forgeqe 3.2.4 → 3.2.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.
Files changed (152) hide show
  1. package/HOW_TO_USE.md +9 -5
  2. package/dist/docs-site/docs/architecture-reference/index.html +1 -0
  3. package/dist/docs-site/docs/area-api/index.html +17 -4
  4. package/dist/docs-site/docs/area-mobile/index.html +4 -1
  5. package/dist/docs-site/docs/get-started/index.html +7 -4
  6. package/dist/docs-site/docs/mobile/index.html +4 -1
  7. package/dist/docs-site/docs/overview/index.html +1 -1
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/docs-site/docs/web-app/index.html +4 -1
  10. package/dist/forgeqe.js +1911 -1896
  11. package/dist/web/THIRD_PARTY_NOTICES.md +101 -0
  12. package/dist/web/assets/{3d-force-graph-iP39yI0v.js → 3d-force-graph-CNVqakzA.js} +1 -1
  13. package/dist/web/assets/Agent-CAp1dIHx.js +8 -0
  14. package/dist/web/assets/AgentWork-DxO8FN6U.js +2 -0
  15. package/dist/web/assets/ApiTests-XQ8wXCBj.js +14 -0
  16. package/dist/web/assets/Browse-BP1oToo4.js +1 -0
  17. package/dist/web/assets/Chat-DjIdHvHj.js +3 -0
  18. package/dist/web/assets/{CommandPalette-B6QRxOka.js → CommandPalette-rNWxEO_C.js} +1 -1
  19. package/dist/web/assets/{Compare-hz0ft2yP.js → Compare-DwUP21-2.js} +1 -1
  20. package/dist/web/assets/Cost-qZ-gGn2T.js +1 -0
  21. package/dist/web/assets/Data-AlbKk5zW.js +6 -0
  22. package/dist/web/assets/Desktop-yGPlxyBz.js +1 -0
  23. package/dist/web/assets/DesktopReview-BlpxN07L.js +2 -0
  24. package/dist/web/assets/{DeviceScreen-ClPTc5Ot.js → DeviceScreen-BQKsJonx.js} +1 -1
  25. package/dist/web/assets/Evidence-BCodp0GV.js +1 -0
  26. package/dist/web/assets/{Explore-CjowiWJe.js → Explore-Ck5EEDy7.js} +2 -2
  27. package/dist/web/assets/Features-BOQomaU8.js +1 -0
  28. package/dist/web/assets/Flags-DjolLE4S.js +2 -0
  29. package/dist/web/assets/Flaky-D-xnPfil.js +1 -0
  30. package/dist/web/assets/Impact-CoNLaNwy.js +3 -0
  31. package/dist/web/assets/{Jobs-U9kJUVM9.js → Jobs-_kBd2W3F.js} +4 -4
  32. package/dist/web/assets/KindPage-DfnkzpPj.js +6 -0
  33. package/dist/web/assets/LiveDevice-DRAN4Gl4.js +1 -0
  34. package/dist/web/assets/{Migration-BDDE_0TS.js → Migration-PETc1Ckc.js} +5 -5
  35. package/dist/web/assets/Mobile-B193VBXu.js +1 -0
  36. package/dist/web/assets/Observability-CvdV37XD.js +1 -0
  37. package/dist/web/assets/PageAgent-BJguufGW.js +1 -0
  38. package/dist/web/assets/{Product-DkEI-0vu.js → Product-Cmgcj9fr.js} +4 -4
  39. package/dist/web/assets/Production-DM62n03j.js +1 -0
  40. package/dist/web/assets/Quality-DbgAAeel.js +1 -0
  41. package/dist/web/assets/Readiness-CojmD235.js +1 -0
  42. package/dist/web/assets/Record-C4VFM97k.js +1 -0
  43. package/dist/web/assets/Regression-5mma_vyD.js +5 -0
  44. package/dist/web/assets/{RelationGraph-BnhbeI6t.js → RelationGraph-bDvvcead.js} +1 -1
  45. package/dist/web/assets/Reports-BeSrlzKk.js +2 -0
  46. package/dist/web/assets/Responsive-B4CkMBwF.js +3 -0
  47. package/dist/web/assets/RunDiff-DGThx7bk.js +1 -0
  48. package/dist/web/assets/Settings-IjfPYiuf.js +21 -0
  49. package/dist/web/assets/{Steps-C18OGSAM.js → Steps-BPSNI3aY.js} +1 -1
  50. package/dist/web/assets/TestCases-hIuP5BLu.js +1 -0
  51. package/dist/web/assets/TestData-DpAMEMLP.js +2 -0
  52. package/dist/web/assets/TestDebt-D6UjJCpY.js +1 -0
  53. package/dist/web/assets/TestManagement-CTWh-aA8.js +4 -0
  54. package/dist/web/assets/WhatsNew-DMDg1zmv.js +1 -0
  55. package/dist/web/assets/agentSettingsSheet-CUogAKga.js +1 -0
  56. package/dist/web/assets/{dataParts-D08j24QD.js → dataParts-s8iIR3Ad.js} +3 -3
  57. package/dist/web/assets/default-DB4ZMZxa.js +1 -0
  58. package/dist/web/assets/{desktopAppPath-DyQr1aFk.js → desktopAppPath-CnmfVr-s.js} +1 -1
  59. package/dist/web/assets/frame-DNgVKrlp.js +13 -0
  60. package/dist/web/assets/geist-cyrillic-400-normal-DXusLSnH.woff2 +0 -0
  61. package/dist/web/assets/geist-cyrillic-400-normal-DkrqoNl2.woff +0 -0
  62. package/dist/web/assets/geist-cyrillic-500-normal-BboVsk8R.woff +0 -0
  63. package/dist/web/assets/geist-cyrillic-500-normal-NWpm63d5.woff2 +0 -0
  64. package/dist/web/assets/geist-cyrillic-ext-400-normal-ChfpGzr5.woff +0 -0
  65. package/dist/web/assets/geist-cyrillic-ext-500-normal-BXrH8YSv.woff +0 -0
  66. package/dist/web/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  67. package/dist/web/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  68. package/dist/web/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  69. package/dist/web/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  70. package/dist/web/assets/geist-latin-ext-400-normal-Bz1pQMyt.woff +0 -0
  71. package/dist/web/assets/geist-latin-ext-400-normal-CND6cjiG.woff2 +0 -0
  72. package/dist/web/assets/geist-latin-ext-500-normal-BovoTgeE.woff2 +0 -0
  73. package/dist/web/assets/geist-latin-ext-500-normal-C9fx-R30.woff +0 -0
  74. package/dist/web/assets/geist-vietnamese-400-normal-C8xY9-dI.woff +0 -0
  75. package/dist/web/assets/geist-vietnamese-500-normal-_b1ojCbH.woff +0 -0
  76. package/dist/web/assets/{highlight-BpaRxd70.js → highlight-b70fFRUT.js} +1 -1
  77. package/dist/web/assets/index-BBJ_SKdO.js +56 -0
  78. package/dist/web/assets/index-hysPD6U9.css +2 -0
  79. package/dist/web/assets/input-FbzQKk3L.js +1 -0
  80. package/dist/web/assets/markdown-1z66EzBR.js +8 -0
  81. package/dist/web/assets/pageBack-B6bY6ZUl.js +3 -0
  82. package/dist/web/assets/palette-C5Ok5Zd1.js +1 -0
  83. package/dist/web/assets/paletteCommands-CwHwpVqt.js +1 -0
  84. package/dist/web/assets/{parts-eyvIPENF.js → parts-Dqq6noWp.js} +1 -1
  85. package/dist/web/assets/productParts-DNSo4bn5.js +1 -0
  86. package/dist/web/assets/qualityParts-kh6SukEP.js +1 -0
  87. package/dist/web/assets/{recordTest-vps_1X_-.js → recordTest-BCxsm3gC.js} +1 -1
  88. package/dist/web/assets/sectionList-BlwEtA8S.js +1 -0
  89. package/dist/web/assets/{stepper-Cb6rnj2p.js → stepper-ByKrM1LP.js} +1 -1
  90. package/dist/web/assets/when-BuWCTaKm.js +1 -0
  91. package/dist/web/index.html +10 -6
  92. package/docs/ARCHITECTURE_REFERENCE.md +1 -0
  93. package/docs/MOBILE.md +4 -1
  94. package/docs/WEB_APP.md +4 -1
  95. package/docs/user-guide.html +20 -4
  96. package/forgeqe.example.yaml +3 -2
  97. package/llms.example.json +22 -0
  98. package/package.json +1 -1
  99. package/prompts/test-agent.md +0 -2
  100. package/prompts/test-rules.md +3 -8
  101. package/py/forgeqe_desktop/replay.py +46 -1
  102. package/py/forgeqe_desktop/workflow.py +60 -7
  103. package/py/forgeqe_engine/cli.py +6 -2
  104. package/py/forgeqe_engine/copilot_gateway.py +208 -23
  105. package/py/forgeqe_engine/recordsession.py +4 -2
  106. package/py/forgeqe_mobile/maestro.py +3 -0
  107. package/dist/web/assets/Agent-COXI7WgW.js +0 -8
  108. package/dist/web/assets/AgentWork-LD5CQxet.js +0 -2
  109. package/dist/web/assets/ApiTests-Dpwqmpr1.js +0 -14
  110. package/dist/web/assets/Browse-DIcTvI-C.js +0 -1
  111. package/dist/web/assets/Chat-DNw_jYbD.js +0 -3
  112. package/dist/web/assets/Cost-C231Bf_A.js +0 -1
  113. package/dist/web/assets/Data-DODs050c.js +0 -6
  114. package/dist/web/assets/Desktop-CUV43rdi.js +0 -1
  115. package/dist/web/assets/DesktopReview-WEIFBq-L.js +0 -2
  116. package/dist/web/assets/Evidence-DhN_bTZ-.js +0 -1
  117. package/dist/web/assets/Features-BnagyBie.js +0 -1
  118. package/dist/web/assets/Flags-DlkY7U4M.js +0 -2
  119. package/dist/web/assets/Flaky-BkD01mRw.js +0 -1
  120. package/dist/web/assets/Impact-BM4_vIEv.js +0 -3
  121. package/dist/web/assets/KindPage-BkK5AQw0.js +0 -6
  122. package/dist/web/assets/LiveDevice-Bjc2r797.js +0 -1
  123. package/dist/web/assets/Mobile-D2qAF8X5.js +0 -1
  124. package/dist/web/assets/Observability-CLFC0ze7.js +0 -1
  125. package/dist/web/assets/PageAgent-Dz5CuEUe.js +0 -1
  126. package/dist/web/assets/Production-CgfLjbSa.js +0 -1
  127. package/dist/web/assets/Quality-8E667GJi.js +0 -1
  128. package/dist/web/assets/Readiness-Bbkq2lNV.js +0 -1
  129. package/dist/web/assets/Record-JR4HeyTe.js +0 -1
  130. package/dist/web/assets/Regression-_9u6qDMk.js +0 -5
  131. package/dist/web/assets/Reports-DxjHb0vA.js +0 -2
  132. package/dist/web/assets/Response-BvQV20vS.js +0 -9
  133. package/dist/web/assets/Responsive-DNC31nTr.js +0 -3
  134. package/dist/web/assets/RunDiff-BXqh9adv.js +0 -1
  135. package/dist/web/assets/Runs-PsPMVpQl.js +0 -2
  136. package/dist/web/assets/Settings-DEOCWX5o.js +0 -21
  137. package/dist/web/assets/TestCases-MIOqrvt0.js +0 -1
  138. package/dist/web/assets/TestData-DtPsGVwq.js +0 -2
  139. package/dist/web/assets/TestDebt-C8zEVY4j.js +0 -1
  140. package/dist/web/assets/TestManagement-cXbBFksQ.js +0 -4
  141. package/dist/web/assets/WhatsNew-vGPOJXT2.js +0 -1
  142. package/dist/web/assets/agents-DPabR9dS.js +0 -1
  143. package/dist/web/assets/diff-CVufIkRR.js +0 -2
  144. package/dist/web/assets/families-CrnKBjis.js +0 -1
  145. package/dist/web/assets/index-FhirFP-O.css +0 -2
  146. package/dist/web/assets/index-q1r33z9g.js +0 -64
  147. package/dist/web/assets/input-ChhA0xMm.js +0 -1
  148. package/dist/web/assets/pageBack-Dhl5PHZE.js +0 -3
  149. package/dist/web/assets/palette-CpGAHix6.js +0 -1
  150. package/dist/web/assets/paletteCommands-Der7qNEc.js +0 -1
  151. package/dist/web/assets/productParts-2Y8IjOa0.js +0 -1
  152. package/dist/web/assets/qualityParts-CdoLEG3a.js +0 -1
@@ -44,8 +44,8 @@ _MOBILE_STEP_KEYS = {
44
44
  # The newest magic link the login's site sent to its mailbox, opened on the device (forgeqe_mobile/magiclink.py).
45
45
  "open_link": {"login"},
46
46
  # at: [x, y] inside the target in thousandths of its width and height, for what the app draws with no control.
47
- "tap": {"target", "at"},
48
- "double_tap": {"target", "at"},
47
+ "tap": {"target", "at", "choice"},
48
+ "double_tap": {"target", "at", "choice"},
49
49
  "long_press": {"target", "at"},
50
50
  "type": {"target", "text"},
51
51
  # Opens the target (a drop-down) and picks the item that shows `value`.
@@ -75,8 +75,8 @@ MAX_IGNORE = 20
75
75
  LOCATOR_KEYS = ("automation_id", "name", "control_type", "class_name", "index", "path")
76
76
  _STEP_KEYS = {
77
77
  "launch": set(),
78
- "click": {"target"},
79
- "double_click": {"target"},
78
+ "click": {"target", "choice"},
79
+ "double_click": {"target", "choice"},
80
80
  "type": {"target", "text"},
81
81
  "select": {"target", "value"},
82
82
  "keys": {"keys"},
@@ -106,6 +106,37 @@ NAMED_KEYS = (
106
106
  REFUSED_KEYS = ("win", "lwin", "rwin", "windows", "super", "meta", "cmd", "apps", "menu")
107
107
 
108
108
 
109
+ # A click (a tap) the review made data (src/web/desktop.ts dataChanges; the web's src/record/choice.ts): its target's
110
+ # name is test data ({{keep}}) or a date from today ({{$date:+N:FORMAT}}), or "any" clicks the first enabled control of
111
+ # its type inside its parent. The replay keeps what it clicked as {{keep}}; `was` is the target as recorded.
112
+ CHOICE_HOWS = ("data", "date", "any")
113
+ # Controls "any" looks through at most.
114
+ MAX_PICK = 50
115
+ # {{$date:+N:FORMAT}}: N days from the day of the run, in a format of the tokens below (never strftime's, which differ
116
+ # between systems and read the locale).
117
+ _DATE_REF = re.compile(r"^\$date:([+-])(\d{1,4}):([^{}\n]{1,80})$")
118
+ _MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
119
+ _DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
120
+
121
+
122
+ def date_text(days: int, fmt: str, today: Optional["date"] = None) -> str:
123
+ """The date ``days`` from ``today`` in ``fmt``: %Y %m %d, %e the day without a zero, %o its ending, month and day names."""
124
+ from datetime import date, timedelta
125
+
126
+ d = (today or date.today()) + timedelta(days=days)
127
+
128
+ def one(m: "re.Match[str]") -> str:
129
+ k = m.group(1)
130
+ n = d.day
131
+ return {
132
+ "Y": str(d.year), "m": f"{d.month:02d}", "d": f"{n:02d}", "e": str(n),
133
+ "o": "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th"),
134
+ "B": _MONTHS[d.month - 1], "b": _MONTHS[d.month - 1][:3], "A": _DAYS[d.weekday()], "a": _DAYS[d.weekday()][:3],
135
+ }[k]
136
+
137
+ return re.sub(r"%([YmdeoBbAa])", one, fmt)
138
+
139
+
109
140
  class WorkflowError(ValueError):
110
141
  """A workflow that cannot run as written; the message says which step and why."""
111
142
 
@@ -171,7 +202,7 @@ MAX_FALLBACKS = 4
171
202
  _ANCHOR_KEYS = ("automation_id", "name")
172
203
 
173
204
 
174
- def _check_target(where: str, target: Any, mobile: bool = False, fallback: bool = False) -> Dict[str, Any]:
205
+ def _check_target(where: str, target: Any, mobile: bool = False, fallback: bool = False, pick: bool = False) -> Dict[str, Any]:
175
206
  if not isinstance(target, dict):
176
207
  raise WorkflowError(f"{where}: target must be a mapping of UIA properties")
177
208
  allowed = set(LOCATOR_KEYS) | ({"within", "web"} | (set() if fallback else {"fallbacks"}) if mobile else set())
@@ -203,7 +234,13 @@ def _check_target(where: str, target: Any, mobile: bool = False, fallback: bool
203
234
  target = {k: v for k, v in target.items() if k not in MOBILE_LOCATOR_KEYS}
204
235
  if "web" in out_extra:
205
236
  return {**target, **out_extra}
206
- if not str(target.get("automation_id") or "").strip() and not str(target.get("name") or "").strip():
237
+ if pick:
238
+ # Any of a kind: by its control type inside its parent (a path, or the ancestor it is within), never one by name.
239
+ if target.get("automation_id") or target.get("name") or "index" in target:
240
+ raise WorkflowError(f"{where}: a choice of any one names no automation_id, name or index: it takes the first enabled one")
241
+ if not str(target.get("control_type") or "").strip() or not (target.get("path") or out_extra.get("within")):
242
+ raise WorkflowError(f"{where}: a choice of any one needs a control_type, inside a path or within its parent")
243
+ elif not str(target.get("automation_id") or "").strip() and not str(target.get("name") or "").strip():
207
244
  raise WorkflowError(f"{where}: target needs an automation_id or a name")
208
245
  for k in ("automation_id", "name", "control_type", "class_name"):
209
246
  if k in target and not isinstance(target[k], str):
@@ -287,8 +324,19 @@ def validate(doc: Any) -> Dict[str, Any]:
287
324
  if missing:
288
325
  raise WorkflowError(f"{where} ({op}) needs {', '.join(sorted(missing))}")
289
326
  clean: Dict[str, Any] = {"op": op}
327
+ choice = step.get("choice")
328
+ if "choice" in step:
329
+ if not isinstance(choice, dict) or set(choice) - {"how", "keep", "was"} or choice.get("how") not in CHOICE_HOWS:
330
+ raise WorkflowError(f"{where}: choice is {{how: data | date | any, keep: a variable's name, was: the target as recorded}}")
331
+ if not isinstance(choice.get("keep"), str) or not _VAR_NAME.match(choice["keep"]):
332
+ raise WorkflowError(f"{where}: choice.keep is a variable's name (letters, digits and _)")
333
+ if "at" in step:
334
+ raise WorkflowError(f"{where}: a choice clicks a control, not a point in it")
335
+ clean["choice"] = {"how": choice["how"], "keep": choice["keep"], **({"was": _check_target(f"{where} (choice.was)", choice["was"], mobile)} if "was" in choice else {})}
290
336
  if "target" in step:
291
- clean["target"] = _check_target(where, step["target"], mobile)
337
+ clean["target"] = _check_target(where, step["target"], mobile, pick=isinstance(choice, dict) and choice.get("how") == "any")
338
+ if isinstance(choice, dict) and choice.get("how") in ("data", "date") and "{{" not in str(clean["target"].get("name") or ""):
339
+ raise WorkflowError(f"{where}: a choice of test data or a date names its control by {{{{…}}}}")
292
340
  if "to" in step:
293
341
  clean["to"] = _check_target(f"{where} (to)", step["to"], mobile)
294
342
  for k in ("text", "value"):
@@ -396,6 +444,11 @@ def fill(text: str, variables: Mapping[str, Any], secret: Callable[[str], Option
396
444
 
397
445
  def one(m: "re.Match[str]") -> str:
398
446
  ref = m.group(1)
447
+ if ref.startswith("$date:"):
448
+ when = _DATE_REF.match(ref)
449
+ if not when:
450
+ raise WorkflowError(f"{{{{{ref}}}}} is not a date: {{{{$date:+N:FORMAT}}}}")
451
+ return date_text(int(when.group(2)) * (-1 if when.group(1) == "-" else 1), when.group(3))
399
452
  if ref.startswith("secret:") or ref.startswith("totp:"):
400
453
  kind, name = ref.split(":", 1)
401
454
  name = name.strip()
@@ -271,8 +271,12 @@ def _probe(out: TextIO) -> int:
271
271
  from .probe import probe
272
272
 
273
273
  line = sys.stdin.readline()
274
- cfg = json.loads(line) if line.strip() else {}
275
- result = asyncio.run(probe(cfg))
274
+ try:
275
+ cfg = json.loads(line) if line.strip() else {}
276
+ result = asyncio.run(probe(cfg))
277
+ except Exception as e:
278
+ # A failure outside the calls (the client's import) is the check's answer too, never a silent exit.
279
+ result = {"ok": False, "error": " ".join(f"{type(e).__name__}: {e}".split())[:300]}
276
280
  out.write(json.dumps(result) + "\n")
277
281
  return 0 if result.get("ok") else 1
278
282
 
@@ -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"})
@@ -129,9 +129,11 @@ SNAPSHOT_FN = r"""function (dx, dy, f, VW, VH) {
129
129
  const type = (el.tagName === 'INPUT' ? (el.type || 'text') : el.tagName).toLowerCase();
130
130
  if (/^(hidden|submit|button|image|reset|file)$/.test(type)) continue;
131
131
  const box = seen(el); if (!box) continue;
132
- const label = (el.getAttribute('aria-label') || (el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute('placeholder') || el.name || '').replace(/\s+/g, ' ').trim().slice(0, 80);
132
+ // by: what the name came from, so a check finds the field again the same way (a placeholder or a name is no label).
133
+ const named = [['label', el.getAttribute('aria-label')], ['label', el.labels && el.labels[0] && el.labels[0].innerText], ['placeholder', el.getAttribute('placeholder')], ['name', el.name]].find(([, v]) => v && String(v).trim()) || ['', ''];
134
+ const label = String(named[1]).replace(/\s+/g, ' ').trim().slice(0, 80), by = named[0];
133
135
  const value = type === 'password' ? '' : (type === 'checkbox' || type === 'radio') ? (el.checked ? 'checked' : 'not checked') : el.tagName === 'SELECT' ? (el.selectedOptions[0] ? el.selectedOptions[0].text : '') : String(el.value || '');
134
- out.fields.push(where(el, { label, value: value.slice(0, 120), type, ...box }));
136
+ out.fields.push(where(el, { label, by, value: value.slice(0, 120), type, ...box }));
135
137
  }
136
138
  return out;
137
139
  }"""
@@ -125,6 +125,9 @@ def to_flow(workflow: Mapping[str, Any], app_id: str, variables: Optional[Mappin
125
125
  cmds.append({"tapOn": {**_selector(d), "optional": True}})
126
126
  elif op == "close":
127
127
  cmds.append("stopApp")
128
+ elif op in ("tap", "double_tap") and (step.get("choice") or {}).get("how") == "any":
129
+ # Maestro runs a whole flow it was given: it cannot look through the controls for the first free one.
130
+ raise WorkflowError(f"step {i}: choosing any free control has no Maestro form; replay this workflow with Appium")
128
131
  elif op == "open_link":
129
132
  # Maestro's openLink takes the link as written, and a magic link is read when the step runs.
130
133
  raise WorkflowError(f"step {i}: a magic link read from the mailbox has no Maestro form; replay this workflow with Appium")