@capagents/forgeqe 3.1.8 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/HOW_TO_USE.md +51 -4
  2. package/THIRD_PARTY_NOTICES.md +2 -1
  3. package/dist/docs-site/docs/area-operations/index.html +25 -2
  4. package/dist/docs-site/docs/area-quality/index.html +17 -3
  5. package/dist/docs-site/docs/area-setup/index.html +1 -1
  6. package/dist/docs-site/docs/get-started/index.html +18 -2
  7. package/dist/docs-site/docs/overview/index.html +1 -1
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/forgeqe.js +1972 -1930
  10. package/dist/template.html +12 -12
  11. package/dist/vendor/ibm-ace.js +2 -0
  12. package/dist/web/THIRD_PARTY_NOTICES.md +29 -0
  13. package/dist/web/assets/{3d-force-graph-OeCdKJJ-.js → 3d-force-graph-Bhmgjf_7.js} +1 -1
  14. package/dist/web/assets/Agent-Dx4aOB_h.js +8 -0
  15. package/dist/web/assets/AgentWork-D0MS10up.js +2 -0
  16. package/dist/web/assets/ApiTests-DUoEh0nX.js +10 -0
  17. package/dist/web/assets/Browse-BGgyLuL3.js +1 -0
  18. package/dist/web/assets/Chat-CEHUI2ty.js +3 -0
  19. package/dist/web/assets/{CommandPalette-zRrrp6F_.js → CommandPalette-rY8rp79k.js} +1 -1
  20. package/dist/web/assets/Compare-B_NCvogR.js +1 -0
  21. package/dist/web/assets/Cost-sm-6tWRQ.js +1 -0
  22. package/dist/web/assets/Data-CFyxbwPS.js +6 -0
  23. package/dist/web/assets/Desktop-A_D4LTis.js +1 -0
  24. package/dist/web/assets/DesktopReview-CM7xmpHS.js +2 -0
  25. package/dist/web/assets/Evidence-BlTkmzfE.js +1 -0
  26. package/dist/web/assets/Explore-DyGqAEff.js +2 -0
  27. package/dist/web/assets/Features-BjPR9gCe.js +1 -0
  28. package/dist/web/assets/Flags-C_DneXS9.js +2 -0
  29. package/dist/web/assets/Flaky-l5ugC_ER.js +1 -0
  30. package/dist/web/assets/Impact-7TXQHcsW.js +3 -0
  31. package/dist/web/assets/Jobs-xRLNI-8l.js +5 -0
  32. package/dist/web/assets/KindPage-BZu1Zo4S.js +6 -0
  33. package/dist/web/assets/Migration-DKsyDwDO.js +8 -0
  34. package/dist/web/assets/Observability-CVwKJ-fI.js +1 -0
  35. package/dist/web/assets/PageAgent-C1X5ot6v.js +1 -0
  36. package/dist/web/assets/Product-iHqLyIhD.js +12 -0
  37. package/dist/web/assets/Production-C8eGcwCi.js +1 -0
  38. package/dist/web/assets/Quality-BVsN6u0E.js +1 -0
  39. package/dist/web/assets/Readiness-BWlbiTeu.js +1 -0
  40. package/dist/web/assets/Record-C7qgNFqs.js +1 -0
  41. package/dist/web/assets/Regression-ChleHlqe.js +5 -0
  42. package/dist/web/assets/RelationGraph-CzR_Hs8A.js +1 -0
  43. package/dist/web/assets/Reports-CIcKyoHH.js +2 -0
  44. package/dist/web/assets/Response-D2ZeO8uW.js +9 -0
  45. package/dist/web/assets/Responsive-DCfw-Oz3.js +3 -0
  46. package/dist/web/assets/RunDiff-COaxhvKm.js +1 -0
  47. package/dist/web/assets/Runs-3qx2qf56.js +2 -0
  48. package/dist/web/assets/Settings-DG2k3Lno.js +21 -0
  49. package/dist/web/assets/Steps-CN4n8U1I.js +3 -0
  50. package/dist/web/assets/TestCases-BEfJFp5h.js +1 -0
  51. package/dist/web/assets/TestData-SO2qqaAF.js +2 -0
  52. package/dist/web/assets/TestDebt-DIYhbhjh.js +1 -0
  53. package/dist/web/assets/TestManagement-D7q6G3YN.js +4 -0
  54. package/dist/web/assets/WhatsNew-DqBLhhgk.js +1 -0
  55. package/dist/web/assets/{agents-C0Jg2pN8.js → agents-BUWN-VJv.js} +1 -1
  56. package/dist/web/assets/{coverage-BB9BLjGz.js → coverage-DCtiu73T.js} +4 -4
  57. package/dist/web/assets/dataParts-BdmBLsU9.js +3 -0
  58. package/dist/web/assets/{diff-cbn6NGtL.js → diff-DEgLgw6R.js} +1 -1
  59. package/dist/web/assets/families-CrnKBjis.js +1 -0
  60. package/dist/web/assets/{highlight--Ayfy7Gy.js → highlight-DSLpJ_Dq.js} +1 -1
  61. package/dist/web/assets/index-DAteDsgB.css +2 -0
  62. package/dist/web/assets/index-RJ1kEHuo.js +64 -0
  63. package/dist/web/assets/input-Be3YOEK2.js +1 -0
  64. package/dist/web/assets/logLevel-Dq8s6DZz.js +3 -0
  65. package/dist/web/assets/palette-Dcoz5crU.js +1 -0
  66. package/dist/web/assets/{paletteCommands-ar4wAGok.js → paletteCommands-fwv5XVOS.js} +1 -1
  67. package/dist/web/assets/parts-CkI14hIv.js +1 -0
  68. package/dist/web/assets/productParts-BOUMBM_H.js +1 -0
  69. package/dist/web/assets/qualityParts-8KI3JCY8.js +1 -0
  70. package/dist/web/assets/recordTest-kf2ykEQF.js +1 -0
  71. package/dist/web/assets/route-D8G-pTdk.js +1 -0
  72. package/dist/web/assets/stepper-CQSK6KS0.js +1 -0
  73. package/dist/web/index.html +7 -7
  74. package/docs/OBSERVABILITY.md +233 -0
  75. package/docs/user-guide.html +59 -6
  76. package/forgeqe.example.yaml +5 -1
  77. package/llms.example.json +1 -1
  78. package/package.json +2 -1
  79. package/prompts/browser-persona.md +1 -1
  80. package/py/forgeqe_desktop/handhooks.py +106 -4
  81. package/py/forgeqe_desktop/handrecord.py +77 -2
  82. package/py/forgeqe_desktop/service.py +22 -5
  83. package/py/forgeqe_desktop/workflow.py +47 -2
  84. package/py/forgeqe_engine/copilot_gateway.py +139 -5
  85. package/py/forgeqe_engine/copilot_models.py +186 -0
  86. package/py/forgeqe_engine/diagnostics.py +119 -2
  87. package/py/forgeqe_engine/llm.py +85 -1
  88. package/py/forgeqe_engine/persona.py +3 -2
  89. package/py/forgeqe_engine/service.py +36 -10
  90. package/py/forgeqe_mobile/record.py +95 -5
  91. package/dist/web/assets/Agent-DrdDwck4.js +0 -8
  92. package/dist/web/assets/AgentWork-wNaA-i2T.js +0 -2
  93. package/dist/web/assets/ApiTests-B3X6NIn8.js +0 -10
  94. package/dist/web/assets/Browse-Cd1DEgYR.js +0 -1
  95. package/dist/web/assets/Chat-4GknHS5Z.js +0 -3
  96. package/dist/web/assets/Compare-DJVhkzqO.js +0 -1
  97. package/dist/web/assets/Cost-CbKnuQuB.js +0 -1
  98. package/dist/web/assets/Data-Bt5yqqvq.js +0 -6
  99. package/dist/web/assets/Desktop-CPDo3Ir-.js +0 -1
  100. package/dist/web/assets/DesktopReview-CCaqTSu5.js +0 -1
  101. package/dist/web/assets/Evidence-BAuIgj1h.js +0 -1
  102. package/dist/web/assets/Explore-BqzEPdP7.js +0 -2
  103. package/dist/web/assets/Features-DFuPCW9x.js +0 -1
  104. package/dist/web/assets/Flags-UBakvqIq.js +0 -2
  105. package/dist/web/assets/Flaky-DUzdfQW4.js +0 -1
  106. package/dist/web/assets/Impact-jLZqUzz9.js +0 -3
  107. package/dist/web/assets/Jobs-De3NyY5s.js +0 -5
  108. package/dist/web/assets/KindPage-DWznWcLB.js +0 -6
  109. package/dist/web/assets/Migration-BdOq6RO6.js +0 -2
  110. package/dist/web/assets/PageAgent-dVvZtNoB.js +0 -1
  111. package/dist/web/assets/Product-ByZ8Qr3i.js +0 -12
  112. package/dist/web/assets/Production-D8L2TchK.js +0 -1
  113. package/dist/web/assets/Quality-CSZEuhZo.js +0 -1
  114. package/dist/web/assets/Readiness-bBu_84mx.js +0 -1
  115. package/dist/web/assets/Record-DWJEDj2C.js +0 -1
  116. package/dist/web/assets/Regression-D2VkPIhZ.js +0 -5
  117. package/dist/web/assets/RelationGraph-q5H4bYjq.js +0 -1
  118. package/dist/web/assets/Reports-dF-O5HTI.js +0 -2
  119. package/dist/web/assets/Response-D4JW3pwi.js +0 -9
  120. package/dist/web/assets/Responsive-CLX9S27s.js +0 -3
  121. package/dist/web/assets/RunDiff-BuL_-GwF.js +0 -1
  122. package/dist/web/assets/Runs-DyyaAiyA.js +0 -2
  123. package/dist/web/assets/Settings-DnG6_QQj.js +0 -21
  124. package/dist/web/assets/Steps-C-0zwG7T.js +0 -2
  125. package/dist/web/assets/TestCases-DXk9qsEL.js +0 -1
  126. package/dist/web/assets/TestData-D4al7-3Z.js +0 -2
  127. package/dist/web/assets/TestDebt-BzOVDuS8.js +0 -1
  128. package/dist/web/assets/TestManagement-T-NIlhc9.js +0 -1
  129. package/dist/web/assets/Tosca-D7tqMGK0.js +0 -3
  130. package/dist/web/assets/WhatsNew-DBViE2Qt.js +0 -1
  131. package/dist/web/assets/dataParts-D56_9p6T.js +0 -3
  132. package/dist/web/assets/families-gkpkloLT.js +0 -1
  133. package/dist/web/assets/filters-Culzq1j1.js +0 -1
  134. package/dist/web/assets/fold-UP5ihvz-.js +0 -1
  135. package/dist/web/assets/head-BpR3dGRT.js +0 -1
  136. package/dist/web/assets/index-CljX5dI4.js +0 -64
  137. package/dist/web/assets/index-CwAqcn-z.css +0 -2
  138. package/dist/web/assets/input-D7iHeNXz.js +0 -1
  139. package/dist/web/assets/logos-B4e5nBuL.js +0 -1
  140. package/dist/web/assets/palette-lUno7fso.js +0 -1
  141. package/dist/web/assets/parts-DbdUgAZS.js +0 -1
  142. package/dist/web/assets/productParts-DSrnTFn8.js +0 -1
  143. package/dist/web/assets/qualityParts-D_U5zhKC.js +0 -1
  144. package/dist/web/assets/recordTest-D9zuJ-aG.js +0 -1
  145. package/dist/web/assets/route-Dg53WdFu.js +0 -1
@@ -19,13 +19,22 @@ are not recorded; the result lists them.
19
19
  from __future__ import annotations
20
20
 
21
21
  import re
22
+ import time
22
23
  from dataclasses import dataclass, field
23
24
  from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
24
25
 
25
26
  from .record import _mask, target_of
26
- from .workflow import FORMAT, REFUSED_KEYS, WorkflowError, parse_chord, validate
27
+ from .workflow import FORMAT, REFUSED_KEYS, WorkflowError, merge_variables, parse_chord, validate
27
28
 
28
29
  TEXT_TYPES = ("Edit", "Document")
30
+ # A saved block's steps played in this recording (the gateway's `play`, never one the page sends): nothing that starts or
31
+ # closes the app or compares a picture.
32
+ PLAY_REFUSED_OPS = ("launch", "close", "expect_image", "open_link")
33
+ MAX_PLAY_STEPS = 200
34
+
35
+
36
+ class PlayRefused(ValueError):
37
+ """A block that cannot be played here; the message says why, and nothing was done."""
29
38
  # Keys that move the caret or change the text inside a field: part of typing, not steps of their own.
30
39
  EDIT_KEYS = ("backspace", "delete", "left", "right", "up", "down", "home", "end", "insert")
31
40
  EDIT_CTRL_KEYS = ("a", "c", "v", "x", "z", "y", "backspace", "delete", "left", "right", "home", "end")
@@ -81,6 +90,8 @@ class HandRecorder:
81
90
  self.skipped: List[Dict[str, Any]] = []
82
91
  self.secrets_used: List[str] = []
83
92
  self.variables: Dict[str, str] = {}
93
+ # Dialog buttons a played block knew to close (its workflow's dismiss), kept with the recording's workflow.
94
+ self.dismiss: List[Dict[str, Any]] = []
84
95
  self._typing: Optional[_Typing] = None
85
96
  self._last_click: Optional[Tuple[Dict[str, Any], float, int]] = None
86
97
  # A click into a text field: dropped when typing into that field follows (the type step focuses it itself).
@@ -182,13 +193,77 @@ class HandRecorder:
182
193
  self._last_click = None
183
194
  return f"check: {target.get('name') or target.get('automation_id')} shows {text!r}"
184
195
 
196
+ # -- a block played --------------------------------------------------------------------------------------------
197
+
198
+ def play(self, cmd: Mapping[str, Any], driver: Any, spec: Any, sleep: Callable[[float], None] = time.sleep) -> Dict[str, Any]:
199
+ """
200
+ A block's steps done in the app now, by the replay's own runner in this session, and kept as steps of the
201
+ recording as they are written (a secret as {{secret:NAME}}, test data as {{name}} with its value among the
202
+ variables). Checked as a workflow first; a secret only of desktop.secrets. Stops at the first step that fails:
203
+ the ones before it stay done and recorded. What was done, as the page is told it (no value, no secret).
204
+ """
205
+ from .replay import replay
206
+
207
+ steps = cmd.get("steps")
208
+ variables = cmd.get("variables") or {}
209
+ label = str(cmd.get("name") or "the block").replace("\n", " ")[:80]
210
+ if not isinstance(steps, list) or not steps or len(steps) > MAX_PLAY_STEPS:
211
+ raise PlayRefused(f"A block plays 1 to {MAX_PLAY_STEPS} steps.")
212
+ if not isinstance(variables, dict):
213
+ raise PlayRefused("The block's values are not a mapping.")
214
+ if any(not isinstance(x, dict) or x.get("op") in PLAY_REFUSED_OPS for x in steps):
215
+ raise PlayRefused("A block played here does not start, close or leave the app.")
216
+ # A value already given under that name (the recording's own, another block's) is never replaced: the block's
217
+ # takes a free name, and its steps read that one.
218
+ steps, variables = merge_variables(self.variables, steps, variables)
219
+ dismiss = cmd.get("dismiss") or []
220
+ if not isinstance(dismiss, list) or len(dismiss) > 10:
221
+ raise PlayRefused("The block's dialog buttons are not a short list.")
222
+ try:
223
+ wf = validate({"format": FORMAT, "name": label, "app": self.app, "variables": {**self.variables, **variables}, **({"dismiss": [*self.dismiss, *dismiss]} if (self.dismiss or dismiss) else {}), "steps": [{"op": "launch"}, *steps]})
224
+ except WorkflowError as e:
225
+ raise PlayRefused(f"The block cannot be played: {e}") from e
226
+ # Typing the tester began before it is read now, before the block types into that field too.
227
+ self._flush()
228
+ own = wf["steps"][1:]
229
+ allowed = [str(n) for n in self.secret_names]
230
+ done: List[int] = []
231
+ try:
232
+ result = replay(
233
+ {**wf, "steps": own},
234
+ driver,
235
+ {self.app: spec},
236
+ allowed_secrets=allowed,
237
+ secret=lambda n: self.secrets.get(n),
238
+ sleep=sleep,
239
+ must_exist=False,
240
+ keep_open=True,
241
+ on_step=lambda r: done.append(r.index) if r.ok else None,
242
+ )
243
+ except WorkflowError as e:
244
+ # Checked before anything is done: a secret desktop.secrets does not list, a step that cannot run.
245
+ raise PlayRefused(f"The block cannot be played: {e}") from e
246
+ for t in wf.get("dismiss") or []:
247
+ if t not in self.dismiss:
248
+ self.dismiss.append(t)
249
+ self.variables.update({str(k): str(v) for k, v in variables.items()})
250
+ for step in own[: len(done)]:
251
+ self.steps.append(dict(step))
252
+ for name in re.findall(r"\{\{\s*secret:([A-Z_][A-Z0-9_]*)\s*\}\}", str(step.get("text", ""))):
253
+ if name not in self.secrets_used:
254
+ self.secrets_used.append(name)
255
+ self._last_click = None
256
+ self._field_click = None
257
+ failed = next((r for r in result.steps if not r.ok), None)
258
+ return {"name": label, "done": len(done), "total": len(own), **({"error": _mask(str(failed.error or ""), self.secrets)[:300]} if failed else {})}
259
+
185
260
  # -- the result ---------------------------------------------------------------------------------------------
186
261
 
187
262
  def finish(self) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
188
263
  """``(workflow, skipped)``; the workflow is validated."""
189
264
  self._flush()
190
265
  steps = list(self.steps)
191
- workflow = {"format": FORMAT, "name": self.name, "app": self.app, "variables": dict(self.variables), "steps": steps}
266
+ workflow = {"format": FORMAT, "name": self.name, "app": self.app, "variables": dict(self.variables), **({"dismiss": list(self.dismiss)} if self.dismiss else {}), "steps": steps}
192
267
  return validate(workflow), list(self.skipped)
193
268
 
194
269
  @property
@@ -12,8 +12,10 @@ call's time and tokens, never its text), and ``done`` with the result. ``run.jso
12
12
  """
13
13
  from __future__ import annotations
14
14
 
15
+ import inspect
15
16
  import json
16
17
  import os
18
+ import queue
17
19
  import re
18
20
  import sys
19
21
  import threading
@@ -374,7 +376,7 @@ def recording_shots(steps: List[Dict[str, Any]], out: Path) -> List[Dict[str, An
374
376
  return shots
375
377
 
376
378
 
377
- def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: threading.Event, recorder_loop: Optional[Callable[..., str]] = None) -> Dict[str, Any]:
379
+ def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: threading.Event, recorder_loop: Optional[Callable[..., str]] = None, commands: "Optional[queue.Queue[Mapping[str, Any]]]" = None) -> Dict[str, Any]:
378
380
  """Recording by hand: the tester does the steps, their clicks and keys become workflow.yaml. No model."""
379
381
  from .handrecord import HandRecorder
380
382
 
@@ -411,6 +413,10 @@ def run_record(req: Mapping[str, Any], events: Events, driver: Any, stop: thread
411
413
  loop_kwargs: Dict[str, Any] = {"log": events.log, "on_change": lambda e: events.emit({"type": "recorded", **e})}
412
414
  if want_shots:
413
415
  loop_kwargs["on_shot"] = on_shot
416
+ # A saved block the gateway sends while recording (`play`): done in the app, its steps the recording's.
417
+ if commands is not None and "commands" in inspect.signature(recorder_loop).parameters:
418
+ loop_kwargs["commands"] = commands
419
+ loop_kwargs["on_played"] = lambda e: events.emit({"type": "played", **e})
414
420
  reason = recorder_loop(driver, spec, recorder, stop, **loop_kwargs)
415
421
  except Exception as e:
416
422
  error = f"Recording stopped with an error: {type(e).__name__}: {e}"[:2000]
@@ -488,11 +494,21 @@ def _start_screen(req: Mapping[str, Any], events: Events, out: Path, factory: Op
488
494
  return screen
489
495
 
490
496
 
491
- def _watch_stop(stream: IO[str], stop: threading.Event) -> None:
497
+ def _watch_stop(stream: IO[str], stop: threading.Event, commands: "Optional[queue.Queue[Mapping[str, Any]]]" = None) -> None:
498
+ """`stop` ends the run; while recording, a JSON line of `{"cmd": "play", ...}` is queued for the recorder (checked there)."""
492
499
  for line in stream:
493
- if line.strip() == "stop":
500
+ text = line.strip()
501
+ if text == "stop":
494
502
  stop.set()
495
503
  return
504
+ if commands is None or not text.startswith("{") or len(text) > 1_000_000:
505
+ continue
506
+ try:
507
+ cmd = json.loads(text)
508
+ except ValueError:
509
+ continue
510
+ if isinstance(cmd, dict) and cmd.get("cmd") == "play" and commands.qsize() < 5:
511
+ commands.put(cmd)
496
512
 
497
513
 
498
514
  def serve(
@@ -516,7 +532,8 @@ def serve(
516
532
  req = json.loads(line or "{}")
517
533
  if not isinstance(req, dict):
518
534
  raise WorkflowError("the request must be a JSON object")
519
- threading.Thread(target=_watch_stop, args=(stdin, stop), daemon=True).start()
535
+ commands: "queue.Queue[Mapping[str, Any]]" = queue.Queue()
536
+ threading.Thread(target=_watch_stop, args=(stdin, stop, commands if req.get("mode") == "record" else None), daemon=True).start()
520
537
  out = _out_dir(req)
521
538
  mode = req.get("mode")
522
539
  req_mode = str(mode or "")
@@ -529,7 +546,7 @@ def serve(
529
546
  elif mode == "explore":
530
547
  result = run_explore(req, events, driver, runner, model_factory)
531
548
  elif mode == "record":
532
- result = run_record(req, events, driver, stop, recorder_loop)
549
+ result = run_record(req, events, driver, stop, recorder_loop, commands)
533
550
  else:
534
551
  raise WorkflowError(f"mode must be replay, explore or record, not {mode!r}")
535
552
  except Exception as e:
@@ -15,7 +15,7 @@ import os
15
15
  import re
16
16
  import time
17
17
  from pathlib import Path
18
- from typing import Any, Callable, Dict, List, Mapping, Optional
18
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
19
19
 
20
20
  import yaml
21
21
 
@@ -89,6 +89,10 @@ _STEP_KEYS = {
89
89
  _REQUIRED = {"type": {"target", "text"}, "select": {"target", "value"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}}
90
90
 
91
91
  APP_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
92
+ # A step put in from a saved block (src/record/blocks.ts): the block's id and the version it came from, so the review can
93
+ # say when a newer version is saved. Plain data: nothing in a replay reads them.
94
+ BLOCK_ID = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
95
+ BLOCK_KEYS = {"block", "block_version"}
92
96
  _VAR_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
93
97
  # {{name}} or {{secret:NAME}}; anything else between braces is an error, not text to keep.
94
98
  _PLACEHOLDER = re.compile(r"\{\{\s*([^{}]*?)\s*\}\}")
@@ -106,6 +110,38 @@ class WorkflowError(ValueError):
106
110
  """A workflow that cannot run as written; the message says which step and why."""
107
111
 
108
112
 
113
+ def merge_variables(existing: Mapping[str, Any], steps: List[Dict[str, Any]], given: Mapping[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, str]]:
114
+ """
115
+ A played block's test data joined to a recording's: a name the recording already holds with another value (its own
116
+ text_1, an earlier block's user) is given a free one (user_2), and the block's steps read that one instead. Never
117
+ a value replaced under the steps that read it. ``(steps, variables to add)``.
118
+ """
119
+ taken = {str(k) for k in existing}
120
+ renames: Dict[str, str] = {}
121
+ out: Dict[str, str] = {}
122
+ for k, v in given.items():
123
+ name, value = str(k), str(v)
124
+ if name in existing and str(existing[name]) == value:
125
+ continue
126
+ if name in existing or name in out:
127
+ n = 2
128
+ while f"{name}_{n}" in taken or f"{name}_{n}" in out:
129
+ n += 1
130
+ renames[name] = f"{name}_{n}"
131
+ name = renames[str(k)]
132
+ taken.add(name)
133
+ out[name] = value
134
+ if not renames:
135
+ return steps, out
136
+
137
+ def swap(text: Any) -> Any:
138
+ if not isinstance(text, str):
139
+ return text
140
+ return re.sub(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}", lambda m: "{{%s}}" % renames.get(m.group(1), m.group(1)), text)
141
+
142
+ return [{**s, **{k: swap(s[k]) for k in ("text", "value") if k in s}} for s in steps], out
143
+
144
+
109
145
  def parse_chord(chord: str) -> List[str]:
110
146
  """``"ctrl+shift+s"`` as ``["ctrl", "shift", "s"]``: modifiers first, then one named key or one character."""
111
147
  if not isinstance(chord, str) or not chord.strip():
@@ -243,7 +279,7 @@ def validate(doc: Any) -> Dict[str, Any]:
243
279
  op = step.get("op")
244
280
  if op not in ops:
245
281
  raise WorkflowError(f"{where}: op {op!r} is not one of {', '.join(ops)}")
246
- allowed = step_keys[op] | {"op", "note"} | ({"timeout"} if op in TIMEOUT_OPS else set()) | ({"retries"} if op in retry_ops else set())
282
+ allowed = step_keys[op] | {"op", "note"} | BLOCK_KEYS | ({"timeout"} if op in TIMEOUT_OPS else set()) | ({"retries"} if op in retry_ops else set())
247
283
  unknown = set(step) - allowed
248
284
  if unknown:
249
285
  raise WorkflowError(f"{where} ({op}): unknown keys {sorted(unknown)}")
@@ -312,6 +348,15 @@ def validate(doc: Any) -> Dict[str, Any]:
312
348
  clean["retries"] = _retries(f"{where}: retries", step["retries"])
313
349
  if isinstance(step.get("note"), str):
314
350
  clean["note"] = step["note"]
351
+ if "block" in step:
352
+ if not isinstance(step["block"], str) or not BLOCK_ID.match(step["block"]):
353
+ raise WorkflowError(f"{where}: block is a saved block's id (lower case letters, digits and -)")
354
+ clean["block"] = step["block"]
355
+ if "block_version" in step:
356
+ v = step["block_version"]
357
+ if "block" not in step or not isinstance(v, int) or isinstance(v, bool) or not 1 <= v < 1_000_000:
358
+ raise WorkflowError(f"{where}: block_version is the version (a whole number) of the block the step came from")
359
+ clean["block_version"] = v
315
360
  out.append(clean)
316
361
  result: Dict[str, Any] = {"format": fmt, "name": str(doc.get("name") or ""), "app": app, "variables": dict(variables), "steps": out}
317
362
  if "timeout" in doc:
@@ -35,14 +35,32 @@ import uuid
35
35
  from logging.handlers import RotatingFileHandler
36
36
  from typing import Any, Callable, Dict, List, Optional, TextIO, Tuple
37
37
 
38
+ from .copilot_models import AUTO, ModelHealth, client_outdated, model_failed, route, stand_in
38
39
  from .systemcerts import use_system_certificates
39
40
 
40
41
  TOKEN_ENV = "COPILOT_GITHUB_TOKEN"
41
42
  KEY_ENV = "FORGEQE_COPILOT_GATEWAY_KEY"
42
43
 
43
44
  MAX_BODY = 32 * 1024 * 1024
44
- # A screenshot step can take minutes on a slow model; past this the request fails rather than hangs.
45
- REQUEST_TIMEOUT_S = 300.0
45
+ # A screenshot step can take minutes on a slow model; past this the request fails rather than hangs. It stays below the
46
+ # agent runtime's 300s wait for an answer, so the runtime gets the gateway's reason (and the stand-in it chose) rather
47
+ # than its own time-out.
48
+ REQUEST_TIMEOUT_S = 280.0
49
+ # A request whose model failed this quickly is sent again at once to the stand-in; a slower failure is not, as the
50
+ # caller's own time is nearly up, and the stand-in answers its next request.
51
+ RETRY_WITHIN_S = 60.0
52
+ # A caller that hung up after this long with nothing streamed gave up waiting (the browser engine's limit is 240s):
53
+ # the model counts as failing, as a time-out would.
54
+ GAVE_UP_AFTER_S = 200.0
55
+ # The words a failed request's error starts with when the gateway chose a stand-in for the next requests; the agent
56
+ # runtime lets one retry through when it sees them (src/code/runtime.ts).
57
+ SWITCHED = "GitHub Copilot switched models"
58
+ # WebSockets for Copilot's Responses API are off: every request here is a new session, so a kept connection gains
59
+ # nothing, and proxies that break WebSockets left requests unanswered. FORGEQE_COPILOT_WEBSOCKETS=1 turns them on.
60
+ WEBSOCKETS_ENV = "FORGEQE_COPILOT_WEBSOCKETS"
61
+ SDK_NO_WEBSOCKETS_ENV = "COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES"
62
+ # How long the seat's model list is kept before it is asked again.
63
+ SEAT_TTL_S = 600.0
46
64
  # After a turn ends with its reply (or a call of the caller's tools), how long Copilot gets to say it is idle. Copilot
47
65
  # sometimes never does (github/copilot-sdk#2853), which held a request, and every agent waiting on it, for the full
48
66
  # REQUEST_TIMEOUT_S.
@@ -408,6 +426,50 @@ def runtime_load_hint(message: str, probe: Callable[[str], Optional[int]] = prob
408
426
  return f"Windows error {code}. If it persists, {redo}."
409
427
 
410
428
 
429
+ def websockets_on(env: Optional[Dict[str, str]] = None) -> bool:
430
+ return str((os.environ if env is None else env).get(WEBSOCKETS_ENV, "")).strip().lower() in ("1", "true", "yes", "on")
431
+
432
+
433
+ def capi_options(websockets: bool) -> Optional[Any]:
434
+ """The session's Copilot API options: plain HTTPS for the Responses API unless WebSockets are wanted."""
435
+ if websockets:
436
+ return None
437
+ try:
438
+ from copilot.generated.rpc import CapiSessionOptions
439
+ except ImportError:
440
+ return None
441
+ return CapiSessionOptions(enable_web_socket_responses=False)
442
+
443
+
444
+ def pinned_versions() -> str:
445
+ """The SDK and runtime versions this engine runs, as "SDK 1.0.28, runtime 1.0.105"; parts it cannot read are left out."""
446
+ parts = []
447
+ try:
448
+ from importlib.metadata import version
449
+
450
+ parts.append(f"SDK {version('github-copilot-sdk')}")
451
+ except Exception:
452
+ pass
453
+ try:
454
+ from copilot._cli_version import CLI_VERSION
455
+
456
+ if isinstance(CLI_VERSION, str) and re.fullmatch(r"[0-9][0-9A-Za-z.-]{0,40}", CLI_VERSION):
457
+ parts.append(f"runtime {CLI_VERSION}")
458
+ except Exception:
459
+ pass
460
+ return ", ".join(parts)
461
+
462
+
463
+ def outdated_error(message: str) -> "GatewayError":
464
+ """GitHub refusing this version of Copilot's SDK or runtime: no model would do, a newer ForgeQE brings newer ones."""
465
+ pins = pinned_versions()
466
+ return GatewayError(
467
+ 502,
468
+ f"GitHub Copilot no longer accepts the Copilot version this ForgeQE has{f' ({pins})' if pins else ''}: run forgeqe update "
469
+ f"for a newer ForgeQE, then forgeqe setup. {message}"[:2000],
470
+ )
471
+
472
+
411
473
  def client_options(token: Optional[str], home: str, workdir: str) -> Dict[str, Any]:
412
474
  """With a token, that token only; without one, the signed-in user, as the Copilot SDK recommends on a user's machine."""
413
475
  auth: Dict[str, Any] = {"github_token": token, "use_logged_in_user": False} if token else {"use_logged_in_user": True}
@@ -424,7 +486,14 @@ class Copilot:
424
486
  # An empty working folder: the session reads no project files and no custom instructions.
425
487
  self.workdir = tempfile.mkdtemp(prefix="forgeqe-copilot-")
426
488
  self.signed_in_user = not token
489
+ self.websockets = websockets_on()
490
+ if not self.websockets:
491
+ # The runtime the SDK starts reads this too, for every request it makes (the model list included).
492
+ os.environ[SDK_NO_WEBSOCKETS_ENV] = "1"
427
493
  self.client = CopilotClient(**client_options(token, home, self.workdir))
494
+ self.health = ModelHealth()
495
+ self._seat: List[Dict[str, Any]] = []
496
+ self._seat_at = 0.0
428
497
  # Caller tools named like one of Copilot's own: they must say they replace it. Learned from Copilot's answers
429
498
  # (BUILTIN_TOOLS to start with), kept for the gateway's life, so only a first request pays a retry.
430
499
  self.replaces: set = set(BUILTIN_TOOLS)
@@ -443,6 +512,8 @@ class Copilot:
443
512
  limit or a used-up allowance is a 429, so callers wait or stop rather than retry at once."""
444
513
  if limited(message, status):
445
514
  return GatewayError(429, f"GitHub Copilot: {message} ({LIMITED_HINT})"[:2000])
515
+ if client_outdated(message):
516
+ return outdated_error(message)
446
517
  if not signin_refused(message):
447
518
  return GatewayError(502, f"GitHub Copilot: {message}"[:2000])
448
519
  what = "the sign-in" if self.signed_in_user else "the token"
@@ -465,7 +536,25 @@ class Copilot:
465
536
  self._reasoning = set()
466
537
  return model in self._reasoning
467
538
 
539
+ async def seat(self) -> List[Dict[str, Any]]:
540
+ """The seat's models (as models() lists them), kept for SEAT_TTL_S; [] when Copilot cannot list them."""
541
+ if not self._seat or time.monotonic() - self._seat_at > SEAT_TTL_S:
542
+ try:
543
+ self._seat = await self.models()
544
+ self._seat_at = time.monotonic()
545
+ except Exception:
546
+ pass
547
+ return self._seat
548
+
468
549
  async def models(self) -> List[Dict[str, Any]]:
550
+ out = await self._listed()
551
+ if not any(m["id"] == AUTO for m in out):
552
+ # Copilot's own routing, which the SDK takes as a model. A screenshot goes to the seat's best model that takes
553
+ # pictures (copilot_models.route), so it is listed as taking them.
554
+ out.insert(0, {"id": AUTO, "object": "model", "owned_by": "github-copilot", "vision": True, "reasoning_effort": False, "policy": "enabled", "auto": True})
555
+ return out
556
+
557
+ async def _listed(self) -> List[Dict[str, Any]]:
469
558
  out = []
470
559
  for m in await self.client.list_models():
471
560
  caps = getattr(m, "capabilities", None)
@@ -491,9 +580,42 @@ class Copilot:
491
580
  reply, whose code fences are removed once it is whole). `gone` completes when the caller hangs up."""
492
581
  rid = uuid.uuid4().hex[:8]
493
582
  started = time.monotonic()
494
- gateway_log(rid, f"start model={req['model']} tools={len(req['tools'])} schema={req['schema'] is not None} stream={bool(on_text)}")
583
+ asked = req["model"]
584
+ seat = await self.seat()
585
+ needs_vision = bool(req["attachments"])
586
+ model, why = route(asked, seat, self.health, needs_vision, auto_ok=True)
587
+ if why:
588
+ gateway_log(rid, why)
589
+ req = {**req, "model": model}
590
+ # Whether any text went to the caller: once it has, the request cannot be sent again to another model.
591
+ sent = {"text": False}
592
+ if on_text is not None:
593
+ caller_text = on_text
594
+
595
+ def on_text(delta: str) -> None:
596
+ sent["text"] = True
597
+ caller_text(delta)
598
+
599
+ gateway_log(rid, f"start model={model}{'' if model == asked else f' (asked {asked})'} tools={len(req['tools'])} schema={req['schema'] is not None} stream={bool(on_text)}")
495
600
  try:
496
- out = await self._complete(rid, req, on_text, gone)
601
+ try:
602
+ out = await self._complete(rid, req, on_text, gone)
603
+ except GatewayError as e:
604
+ if not model_failed(e.status, e.message):
605
+ raise
606
+ self.health.fail(model)
607
+ other = stand_in(seat, self.health, model, needs_vision, auto_ok=True)
608
+ took = time.monotonic() - started
609
+ if not other:
610
+ raise
611
+ # Text already streamed to the caller cannot be taken back, so that request is not sent again.
612
+ if took >= RETRY_WITHIN_S or sent["text"]:
613
+ gateway_log(rid, f"{model} failed after {took:.0f}s: the next requests go to {other}")
614
+ raise GatewayError(e.status, f"{SWITCHED}: {model} failed, so the next requests go to {other}. {e.message}"[:2000])
615
+ gateway_log(rid, f"{model} failed after {took:.0f}s: sent again to {other}")
616
+ req = {**req, "model": other}
617
+ model = other
618
+ out = await self._complete(rid, req, on_text, gone)
497
619
  # Copilot sometimes ends a turn with no words and no call of the caller's tools. Answered as it is, the
498
620
  # agent runtime takes that for a finished answer and the person's request ends in silence, its plan
499
621
  # half done. It is asked once more; a second empty turn is an error the caller sees.
@@ -506,11 +628,17 @@ class Copilot:
506
628
  raise GatewayError(502, f"{EMPTY_REPLY} ({out.get(SHAPE_KEY) or 'no detail'})")
507
629
  out.pop(SHAPE_KEY, None)
508
630
  except CallerGone:
509
- gateway_log(rid, f"caller gone after {time.monotonic() - started:.1f}s: its Copilot session was stopped")
631
+ took = time.monotonic() - started
632
+ gateway_log(rid, f"caller gone after {took:.1f}s: its Copilot session was stopped")
633
+ if took >= GAVE_UP_AFTER_S:
634
+ # The caller gave up waiting: the model is failing as surely as if it had timed out here.
635
+ self.health.fail(model)
636
+ gateway_log(rid, f"{model} gave no answer in {took:.0f}s: avoided for a while")
510
637
  raise
511
638
  except GatewayError as e:
512
639
  gateway_log(rid, f"error {e.status} after {time.monotonic() - started:.1f}s: {e.message[:300]}")
513
640
  raise
641
+ self.health.recovered(model)
514
642
  calls = out["choices"][0]["message"].get("tool_calls") or []
515
643
  gateway_log(rid, f"done after {time.monotonic() - started:.1f}s" + (f" calls={','.join(c['function']['name'] for c in calls)}" if calls else ""))
516
644
  return out
@@ -621,6 +749,9 @@ class Copilot:
621
749
  **({"reasoning_effort": effort} if effort else {}),
622
750
  **({"streaming": True} if stream["to"] else {}),
623
751
  )
752
+ capi = capi_options(self.websockets)
753
+ if capi is not None:
754
+ options["capi"] = capi
624
755
  failure: Optional[str] = None
625
756
  session = None
626
757
  # A session that did not finish cleanly is stopped before it is detached: detaching alone leaves Copilot
@@ -1071,6 +1202,9 @@ async def serve(out: TextIO, copilot: Any = None) -> int:
1071
1202
  out.write(json.dumps({"error": f"GitHub's Copilot SDK is not installed in the ForgeQE engine ({e}): run forgeqe setup, which installs it from pypi.org."}) + "\n")
1072
1203
  return 1
1073
1204
  except Exception as e:
1205
+ if client_outdated(str(e)):
1206
+ out.write(json.dumps({"error": outdated_error(str(e)).message}) + "\n")
1207
+ return 1
1074
1208
  hint = runtime_load_hint(str(e))
1075
1209
  error = f"GitHub Copilot could not start: {type(e).__name__}: {e}"[:1500]
1076
1210
  out.write(json.dumps({"error": f"{error}\n{hint}" if hint else error}) + "\n")