@capagents/forgeqe 2.6.2 → 2.6.3

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 (87) hide show
  1. package/HOW_TO_USE.md +201 -13
  2. package/README.md +4 -2
  3. package/THIRD_PARTY_NOTICES.md +9 -0
  4. package/dist/docs-site/docs/architecture/index.html +2 -1
  5. package/dist/docs-site/docs/index.html +188 -10
  6. package/dist/docs-site/docs/search.js +1 -1
  7. package/dist/docs-site/docs/web-app/index.html +35 -6
  8. package/dist/forgeqe.js +1316 -1145
  9. package/dist/template.html +64 -64
  10. package/dist/web/assets/Agent-yd1DyMzR.js +4 -0
  11. package/dist/web/assets/ApiTests-BwOGta9J.js +10 -0
  12. package/dist/web/assets/Chat-P8GH_6gl.js +3 -0
  13. package/dist/web/assets/Data-D2iCqk3t.js +3 -0
  14. package/dist/web/assets/Features-Bu38clxs.js +1 -0
  15. package/dist/web/assets/Jobs-DymuaGeN.js +5 -0
  16. package/dist/web/assets/KindPage-zl6TBkEl.js +6 -0
  17. package/dist/web/assets/Migration-Cg_FUqS_.js +2 -0
  18. package/dist/web/assets/Quality-D3bSHP_B.js +1 -0
  19. package/dist/web/assets/Record-DkCLJos6.js +2 -0
  20. package/dist/web/assets/Regression-B2qMKjAE.js +5 -0
  21. package/dist/web/assets/Reports-D_G9yfDa.js +2 -0
  22. package/dist/web/assets/Response-BnPAefP-.js +4 -0
  23. package/dist/web/assets/Runs-DsDj9-LT.js +2 -0
  24. package/dist/web/assets/Shell-DlZHZN0d.js +3 -0
  25. package/dist/web/assets/TestData-qI1R5Q9v.js +2 -0
  26. package/dist/web/assets/WhatsNew-CoCHqSDm.js +1 -0
  27. package/dist/web/assets/accessibility-CH8EpEAV.svg +1 -0
  28. package/dist/web/assets/{arrow-down-BX18RHKM.js → arrow-down-BWCXlJU0.js} +1 -1
  29. package/dist/web/assets/arrow-right-CdxkQBV7.js +1 -0
  30. package/dist/web/assets/{bot-CLgiKzu9.js → bot-D8486kSA.js} +1 -1
  31. package/dist/web/assets/capgemini-mark-D6aZFnD3.png +0 -0
  32. package/dist/web/assets/chevron-up-CQz_ZmIK.js +1 -0
  33. package/dist/web/assets/circle-BqXBUsQS.js +1 -0
  34. package/dist/web/assets/{circle-dashed-CtRp9sew.js → circle-dashed-DlOiCbWD.js} +1 -1
  35. package/dist/web/assets/dataParts-bwNleJYd.js +3 -0
  36. package/dist/web/assets/forgeqe-logo-D3CwM2Jl.png +0 -0
  37. package/dist/web/assets/forgeqe-logo-white-CoE-hF2l.png +0 -0
  38. package/dist/web/assets/forgeqe-mark-ZLd4S3hw.png +0 -0
  39. package/dist/web/assets/index-Bh4NBbEU.js +37 -0
  40. package/dist/web/assets/index-DkgUrjyL.css +2 -0
  41. package/dist/web/assets/keyboard-wpCM6HMa.js +1 -0
  42. package/dist/web/assets/qualityParts-iy-mouSI.js +1 -0
  43. package/dist/web/assets/{thread-Y9TDe1cr.js → thread-BfW2V-2U.js} +1 -1
  44. package/dist/web/assets/upload-CwExsxOd.js +1 -0
  45. package/dist/web/assets/usePageChat-CzWbP_sa.js +1 -0
  46. package/dist/web/index.html +3 -3
  47. package/docs/ARCHITECTURE.md +2 -1
  48. package/docs/WEB_APP.md +36 -6
  49. package/docs/security-data-flow.html +3 -3
  50. package/docs/user-guide.html +188 -10
  51. package/forgeqe.example.yaml +8 -2
  52. package/package.json +5 -3
  53. package/prompts/api-tests.md +1 -1
  54. package/prompts/brain.md +8 -0
  55. package/prompts/browser-persona.md +14 -0
  56. package/prompts/db-agent.md +73 -0
  57. package/prompts/heal.md +1 -1
  58. package/prompts/migrate.md +54 -0
  59. package/prompts/test-agent.md +1 -0
  60. package/py/forgeqe_engine/cli.py +9 -1
  61. package/py/forgeqe_engine/copilot_gateway.py +162 -9
  62. package/py/forgeqe_engine/persona.py +435 -0
  63. package/py/forgeqe_engine/proceed.py +67 -0
  64. package/py/forgeqe_engine/service.py +93 -11
  65. package/skills/test-data/SKILL.md +4 -0
  66. package/dist/web/assets/Agent-CTDTMH3D.js +0 -3
  67. package/dist/web/assets/ApiTests-l1gZ56fZ.js +0 -10
  68. package/dist/web/assets/Chat-Dikg6l8H.js +0 -3
  69. package/dist/web/assets/Data-BwECmGVi.js +0 -4
  70. package/dist/web/assets/Features-B79B8aw4.js +0 -1
  71. package/dist/web/assets/Jobs-B0viFhNH.js +0 -5
  72. package/dist/web/assets/Quality-CjFsnbA2.js +0 -1
  73. package/dist/web/assets/Record-B-Eh1bgA.js +0 -2
  74. package/dist/web/assets/Regression-B7l83v3z.js +0 -5
  75. package/dist/web/assets/Reports-BuUlCohG.js +0 -2
  76. package/dist/web/assets/Response-BS_RT6Qd.js +0 -4
  77. package/dist/web/assets/Runs-C7TPphyI.js +0 -2
  78. package/dist/web/assets/Shell-Vg5t8ZK3.js +0 -3
  79. package/dist/web/assets/accessibility-BSaq_4Me.svg +0 -1
  80. package/dist/web/assets/capgemini-BO8ajcbd.svg +0 -21
  81. package/dist/web/assets/capgemini-white-ByjwPW8N.svg +0 -21
  82. package/dist/web/assets/circle-BF-xM9LZ.js +0 -1
  83. package/dist/web/assets/index-CDCzsK2N.css +0 -2
  84. package/dist/web/assets/index-DR8clS1u.js +0 -26
  85. package/dist/web/assets/markdown-CBbHCXbg.js +0 -10
  86. package/dist/web/assets/trending-up-DMQnalkJ.js +0 -1
  87. package/dist/web/assets/usePageChat-CSLmKGMO.js +0 -1
@@ -0,0 +1,54 @@
1
+ ---
2
+ name: migrate
3
+ description: "Migrates a repository's automated tests to another framework or language, one file at a time, keeping what each test checks."
4
+ used_by: "migrate_tests, forgeqe migrate"
5
+ kind: agent
6
+ ---
7
+ {{> conventions}}
8
+
9
+ ## Role
10
+ You are a senior test automation engineer who moves a test suite from one framework or language to another.
11
+
12
+ ## Objective
13
+ Write the target version of one source file at a time, in the target folder. The new file does what the source did, and checks what the source checked. Use the idiomatic style of the target framework.
14
+
15
+ ## Execution contract
16
+ **Preconditions**: ForgeQE gives you the plan: the source and target stacks, and the target folder. For this step, it gives the source file, the target path, and the files that are already migrated. You MUST read the source file before you write. You MUST read the source files that it uses.
17
+ **Tools**: your own tools to read files, edit files, and run commands.
18
+ **Procedure**:
19
+ 1. The setup step: make the target folder a project of its own for the target framework. Write the files that the step names. Add the dependencies that the tests need, and install them inside the target folder. Take the base URL, browsers, timeouts and environment variables from the configuration of the source. Run no test yet.
20
+ 2. A support file is a page object, a fixture, or a helper. Write its target version at the given path. Keep the same public methods, in the naming style of the target. Use the waits and locators of the target.
21
+ 3. A test file: write its target version at the given path. Keep every test of the file, with its name, steps, data, and assertions. Import the migrated support files from their new paths.
22
+ 4. Run the test with the command that ForgeQE gives you. Fix your code until the test passes, or until you know why it cannot pass.
23
+ **Stop when**: you wrote the file and, for a test, it passes with the command of ForgeQE. Also stop when you know why it cannot pass.
24
+ **On failure**: the application or the environment can fail the test (the site is down, a login is missing). Then say so in the reason. Do not change the test to hide it.
25
+ **Evidence**: ForgeQE checks the result itself. It runs each migrated test with its own command. It checks that the file is at the path of the plan. It checks that no test is skipped, and that the assertions are all there. Only the run of ForgeQE counts.
26
+
27
+ ## Rules
28
+ - You MUST write only inside the target folder.
29
+ - You MUST NOT change the source tests, other files of the repository, or the files of ForgeQE. ForgeQE puts back each change outside the target folder, and fails the step.
30
+ - You MUST write each file at the path that the plan gives, so the runner of the target finds it.
31
+ - You MUST keep the intent of each test.
32
+ - You MUST NOT drop a test, skip it, or mark it as fixme or only.
33
+ - You MUST NOT make an assertion weaker, remove an assertion, or make a timeout longer to get a pass.
34
+ - The plan can name limits: things the target cannot do as the source did. Then you MUST keep the test and write the nearest equivalent. Say what changed in the reason.
35
+ - You MUST NOT create symbolic links.
36
+ - You MUST NOT put secrets in the code. You MUST read them from the environment variables that the source tests use.
37
+ - The instructions of the user in the plan tell you about style and conventions. When they conflict with these rules, these rules win.
38
+
39
+ Skills:
40
+ - {{> skill-rule}}
41
+
42
+ {{> domain-rule}}
43
+ - You MUST keep each assertion that checks a domain risk or an obligation, such as an audit entry or an approval.
44
+
45
+ ## Code standards
46
+ - You MUST write the code with the current best practice of the target framework. Do this also when the source tests use an older style.
47
+ - Locators, in this order of preference: role with accessible name, label, placeholder, text, test id, then CSS. Keep the locator of the source when it is the best one that the page has. You MUST NOT turn a CSS or id locator into XPath or a position (nth, index).
48
+ - You MUST assert with the retrying assertions of the target framework.
49
+ - You MUST wait for outcomes (an assertion, a URL, a response), never for time. A sleep in the source becomes a wait for the thing that it waited for.
50
+ - You MUST NOT use deprecated APIs.
51
+ - Put browser settings (headless, browser, viewport, locale) in the configuration of the target, never in a test or a page object.
52
+
53
+ ## Output
54
+ The structured result for the step. Give its status: done, or blocked with the reason. Give the files that you wrote. Give a reason in one or two sentences. Say what you changed from the source, and what the target does differently.
@@ -59,6 +59,7 @@ Steps and checks:
59
59
  Code:
60
60
  - You MUST write the test in the language and framework of the repository. A C# NUnit repository gets a C# NUnit test.
61
61
  - You MUST use and extend the page objects, fixtures, helpers, test data, and configuration of the repository, in its style.
62
+ - When you have the data_* tools and the test needs rows in a database (a customer, an order), you MUST ask the DB agent with data_request_test_data before you run the test. Use the values it returns, and give its replay command in your summary. You MUST NOT invent the values.
62
63
  - When the repository has no test setup, you MUST add Playwright Test with TypeScript in the standard layout.
63
64
  - You MUST NOT put secrets in the code. You MUST read them from the environment variables that the handoff names.
64
65
  - A public demo login is the one exception: a user name and password that the application itself shows to anyone, such as the logins on the sign-in page of a demo site (saucedemo.com). Such a login MAY follow the convention of the repository for test data. The page snapshots of the run show whether the application publishes it.
@@ -2,7 +2,7 @@
2
2
  Engine process protocol, used by the Bun CLI:
3
3
 
4
4
  stdin line 1 run request JSON
5
- stdin later "stop" aborts the run
5
+ stdin later "stop" aborts the run; "continue <id> yes|no" answers a {"type": "continue?"} event (proceed.py)
6
6
  stdout one JSON event per line (log, memory, step, result, usage, done);
7
7
  steps replayed from page memory carry "source": "memory"
8
8
  stderr engine logs
@@ -101,6 +101,7 @@ def _doctor(out: TextIO) -> int:
101
101
 
102
102
 
103
103
  def _run(out: TextIO) -> int:
104
+ from .proceed import ANSWERS
104
105
  from .service import RunRequest, run_with_events
105
106
 
106
107
  line = sys.stdin.readline()
@@ -124,6 +125,9 @@ def _run(out: TextIO) -> int:
124
125
  if cmd.strip().lower() == "stop":
125
126
  loop.call_soon_threadsafe(cancel.set)
126
127
  return
128
+ if cmd.strip().lower().startswith("continue "):
129
+ # An answer to "carry on past the limit?" (proceed.py); anything else on the pipe is ignored.
130
+ loop.call_soon_threadsafe(ANSWERS.receive, cmd)
127
131
  loop.call_soon_threadsafe(cancel.set)
128
132
 
129
133
  threading.Thread(target=watch_stdin, daemon=True).start()
@@ -285,5 +289,9 @@ def main(argv: list[str] | None = None) -> int:
285
289
  from .copilot_gateway import main as copilot_gateway
286
290
 
287
291
  return copilot_gateway(out)
292
+ if cmd == "copilot-logout":
293
+ from .copilot_gateway import sign_out_main
294
+
295
+ return sign_out_main(out)
288
296
  out.write(json.dumps({"type": "done", "result": {"success": False, "error": f"Unknown command {cmd}"}}) + "\n")
289
297
  return 2
@@ -224,6 +224,7 @@ def translate(body: Dict[str, Any]) -> Dict[str, Any]:
224
224
  prompt += "\n\nReply with a single JSON object and nothing else."
225
225
  return {
226
226
  "model": model,
227
+ "reasoning_effort": reasoning_effort(body.get("reasoning_effort")),
227
228
  "system": "\n\n".join(s for s in system if s),
228
229
  "prompt": prompt,
229
230
  "attachments": attachments,
@@ -234,8 +235,25 @@ def translate(body: Dict[str, Any]) -> Dict[str, Any]:
234
235
  }
235
236
 
236
237
 
237
- def completion(model: str, content: str, usage: Dict[str, int], tool_calls: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
238
- """An OpenAI chat.completion object; with tool_calls, the calls the model made and finish_reason tool_calls."""
238
+ # OpenAI's reasoning_effort values as Copilot names them; "none" and anything unknown leave the model's default.
239
+ _EFFORTS = {"minimal": "low", "low": "low", "medium": "medium", "high": "high", "xhigh": "xhigh", "max": "max"}
240
+
241
+
242
+ def reasoning_effort(value: Any) -> Optional[str]:
243
+ """The Copilot reasoning effort for OpenAI's reasoning_effort, or None for the model's default."""
244
+ return _EFFORTS.get(str(value).strip().lower()) if isinstance(value, str) else None
245
+
246
+
247
+ _EFFORT_PATH = re.compile(r"^/effort/([a-z]{1,8})(/.*)?$")
248
+
249
+
250
+ # Copilot's finish reasons that mean the reply is not the whole answer, as OpenAI names them.
251
+ _FINISH = {"length": "length", "max_tokens": "length", "content_filter": "content_filter"}
252
+
253
+
254
+ def completion(model: str, content: str, usage: Dict[str, Any], tool_calls: Optional[List[Dict[str, Any]]] = None, finish: Optional[str] = None) -> Dict[str, Any]:
255
+ """An OpenAI chat.completion object; with tool_calls, the calls the model made and finish_reason tool_calls. `finish`
256
+ is Copilot's reason a reply stopped: one cut at the length limit or by the content filter says so."""
239
257
  prompt_tokens = int(usage.get("input", 0))
240
258
  completion_tokens = int(usage.get("output", 0))
241
259
  message: Dict[str, Any] = {"role": "assistant", "content": content}
@@ -246,11 +264,14 @@ def completion(model: str, content: str, usage: Dict[str, int], tool_calls: Opti
246
264
  "object": "chat.completion",
247
265
  "created": int(time.time()),
248
266
  "model": model,
249
- "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if tool_calls else "stop"}],
267
+ "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if tool_calls else _FINISH.get(str(finish or "").lower(), "stop")}],
250
268
  "usage": {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": prompt_tokens + completion_tokens},
251
269
  }
252
270
  if usage.get("cached"):
253
271
  out["usage"]["prompt_tokens_details"] = {"cached_tokens": int(usage["cached"])}
272
+ if usage.get("premium"):
273
+ # Copilot's own count of premium requests this call used; not an OpenAI field, so callers that do not know it skip it.
274
+ out["usage"]["copilot_premium_requests"] = round(float(usage["premium"]), 4)
254
275
  return out
255
276
 
256
277
 
@@ -307,6 +328,56 @@ def copilot_home() -> str:
307
328
  return os.path.join(os.environ.get("FORGEQE_HOME") or os.path.join(os.path.expanduser("~"), ".forgeqe"), "copilot")
308
329
 
309
330
 
331
+ # The SDK's runtime wrapper says only this when Windows refuses its native library, without Windows' reason.
332
+ _RUNTIME_LOAD = re.compile(r"failed to load runtime cdylib (.+?runtime\.node)\b", re.IGNORECASE)
333
+ # Loads the library in a child, so Windows' error code is seen without loading it into the gateway.
334
+ _LOAD_PROBE = "import ctypes,sys\ntry:\n ctypes.WinDLL(sys.argv[1])\n print(0)\nexcept OSError as e:\n print(getattr(e, 'winerror', None) or -1)\n"
335
+ # DirectX 12, which the runtime imports; missing on Windows Server without the desktop experience and some VDI images.
336
+ _DIRECTX = ("d3d12.dll", "dxgi.dll")
337
+
338
+
339
+ def probe_runtime_load(path: str) -> Optional[int]:
340
+ """Windows' error code for loading `path` in a separate Python (0: it loads), or None when it cannot be learned."""
341
+ import subprocess
342
+
343
+ env = {k: v for k, v in os.environ.items() if k not in (TOKEN_ENV, KEY_ENV)}
344
+ try:
345
+ r = subprocess.run([sys.executable, "-I", "-c", _LOAD_PROBE, path], capture_output=True, text=True, timeout=120, env=env)
346
+ return int(r.stdout.strip().splitlines()[-1])
347
+ except Exception:
348
+ return None
349
+
350
+
351
+ def runtime_load_hint(message: str, probe: Callable[[str], Optional[int]] = probe_runtime_load, system32: Optional[str] = None) -> str:
352
+ """What to do when Windows refused the Copilot runtime's library, from Windows' own reason; "" for other errors."""
353
+ m = _RUNTIME_LOAD.search(message)
354
+ if not m or sys.platform != "win32" and probe is probe_runtime_load:
355
+ return ""
356
+ path = m.group(1).strip()
357
+ if os.path.basename(path).lower() != "runtime.node" or not os.path.isfile(path):
358
+ return ""
359
+ folder = os.path.dirname(os.path.dirname(os.path.dirname(path)))
360
+ redo = f"delete {folder} and run forgeqe auth login copilot again, which downloads it afresh"
361
+ code = probe(path)
362
+ sys32 = system32 or os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32")
363
+ if code == 126:
364
+ missing = [d for d in _DIRECTX if not os.path.isfile(os.path.join(sys32, d))]
365
+ if missing:
366
+ return f"Windows lacks {', '.join(missing)} (DirectX 12), which Copilot's runtime needs: use Windows 10 or 11, or Windows Server with the Desktop Experience, or sign in with a token on a machine that has it."
367
+ return f"A Windows library Copilot's runtime needs could not be found (Windows error 126). Install the latest Windows updates; if it persists, {redo}."
368
+ if code in (5, 1260, 4551):
369
+ return f"Your organisation's application control (AppLocker or Windows Defender Application Control) blocks Copilot's runtime (Windows error {code}). Ask IT to allow GitHub-signed files in {folder}."
370
+ if code in (225, 226):
371
+ return f"Antivirus blocked Copilot's runtime (Windows error {code}). Ask IT to allow {path}, or {redo}."
372
+ if code in (193, 216, 1392):
373
+ return f"Copilot's runtime is damaged or incomplete (Windows error {code}): {redo}."
374
+ if code == 0:
375
+ return f"It loads when tried again, so something held it the first time (often antivirus scanning it): run forgeqe auth login copilot again. If it fails again, {redo}."
376
+ if code is None:
377
+ return f"If it persists, {redo}."
378
+ return f"Windows error {code}. If it persists, {redo}."
379
+
380
+
310
381
  def client_options(token: Optional[str], home: str, workdir: str) -> Dict[str, Any]:
311
382
  """With a token, that token only; without one, the signed-in user, as the Copilot SDK recommends on a user's machine."""
312
383
  auth: Dict[str, Any] = {"github_token": token, "use_logged_in_user": False} if token else {"use_logged_in_user": True}
@@ -337,8 +408,11 @@ class Copilot:
337
408
  raise GatewayError(401, "GitHub Copilot is not signed in: run forgeqe auth login copilot, which opens GitHub in your browser.")
338
409
  raise GatewayError(401, "GitHub Copilot did not accept the token: use a fine-grained token with the Copilot Requests permission, for an account with a Copilot seat.")
339
410
 
340
- def refusal(self, message: str) -> "GatewayError":
341
- """Copilot's error as the gateway reports it. A refused sign-in says whose, and whether it was a token."""
411
+ def refusal(self, message: str, status: Optional[int] = None) -> "GatewayError":
412
+ """Copilot's error as the gateway reports it. A refused sign-in says whose, and whether it was a token; a rate
413
+ limit or a used-up allowance is a 429, so callers wait or stop rather than retry at once."""
414
+ if limited(message, status):
415
+ return GatewayError(429, f"GitHub Copilot: {message} ({LIMITED_HINT})"[:2000])
342
416
  if not signin_refused(message):
343
417
  return GatewayError(502, f"GitHub Copilot: {message}"[:2000])
344
418
  what = "the sign-in" if self.signed_in_user else "the token"
@@ -351,6 +425,16 @@ class Copilot:
351
425
  except Exception:
352
426
  pass
353
427
 
428
+ async def reasons(self, model: str) -> bool:
429
+ """Whether `model` takes a reasoning effort on this seat; asked once. A model that does not is sent none."""
430
+ if getattr(self, "_reasoning", None) is None:
431
+ try:
432
+ found = await self.client.list_models()
433
+ self._reasoning = {m.id for m in found if getattr(getattr(getattr(m, "capabilities", None), "supports", None), "reasoning_effort", False)}
434
+ except Exception:
435
+ self._reasoning = set()
436
+ return model in self._reasoning
437
+
354
438
  async def models(self) -> List[Dict[str, Any]]:
355
439
  out = []
356
440
  for m in await self.client.list_models():
@@ -364,6 +448,7 @@ class Copilot:
364
448
  "object": "model",
365
449
  "owned_by": "github-copilot",
366
450
  "vision": bool(getattr(supports, "vision", False)),
451
+ "reasoning_effort": bool(getattr(supports, "reasoning_effort", False)),
367
452
  # enabled, disabled (the seat's policy turns it off) or unconfigured (enable it in GitHub's Copilot settings).
368
453
  "policy": str(policy) if policy else "enabled",
369
454
  **({"multiplier": float(multiplier)} if isinstance(multiplier, (int, float)) else {}),
@@ -406,8 +491,10 @@ class Copilot:
406
491
  # The text callback while this request streams; None once it is asked for again without streaming.
407
492
  stream: Dict[str, Any] = {"to": None if req["schema"] is not None or req["json_only"] else on_text, "sent": False}
408
493
 
409
- usage = {"input": 0, "output": 0, "cached": 0}
494
+ usage: Dict[str, Any] = {"input": 0, "output": 0, "cached": 0, "premium": 0.0}
495
+ finish: Dict[str, Optional[str]] = {"reason": None}
410
496
  errors: List[str] = []
497
+ statuses: List[Optional[int]] = []
411
498
  calls: List[Dict[str, Any]] = []
412
499
  # The last root reply without tool requests, and the timer that ends the wait when a turn ends without idle.
413
500
  turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event()}
@@ -437,8 +524,12 @@ class Copilot:
437
524
  usage["input"] += data.input_tokens or 0
438
525
  usage["output"] += data.output_tokens or 0
439
526
  usage["cached"] += data.cache_read_tokens or 0
527
+ usage["premium"] += float(getattr(data, "cost", None) or 0)
528
+ if not getattr(data, "parent_tool_call_id", None):
529
+ finish["reason"] = "content_filter" if getattr(data, "content_filter_triggered", False) else getattr(data, "finish_reason", None)
440
530
  elif isinstance(data, SessionErrorData):
441
531
  errors.append(data.message or data.error_type or "error")
532
+ statuses.append(getattr(data, "status_code", None))
442
533
  # A sub-agent's text is not the reply.
443
534
  elif stream["to"] and isinstance(data, AssistantMessageDeltaData) and data.delta_content and not data.parent_tool_call_id:
444
535
  stream["sent"] = True
@@ -456,8 +547,10 @@ class Copilot:
456
547
 
457
548
  tried: set = set()
458
549
  reply: Any = None
550
+ effort = req.get("reasoning_effort") if await self.reasons(req["model"]) else None
459
551
  for _ in range(MAX_TOOL_RETRIES + 2):
460
552
  errors.clear()
553
+ statuses.clear()
461
554
  calls.clear()
462
555
  on_loop(unsettle)
463
556
  turn["final"] = None
@@ -476,7 +569,10 @@ class Copilot:
476
569
  enable_config_discovery=False,
477
570
  enable_skills=False,
478
571
  enable_session_store=False,
572
+ # GitHub's session telemetry is on by default for a signed-in user: off, like every telemetry ForgeQE starts.
573
+ enable_session_telemetry=False,
479
574
  on_event=on_event,
575
+ **({"reasoning_effort": effort} if effort else {}),
480
576
  **({"streaming": True} if stream["to"] else {}),
481
577
  )
482
578
  failure: Optional[str] = None
@@ -521,11 +617,12 @@ class Copilot:
521
617
  continue
522
618
  if failure:
523
619
  raise self.refusal(failure)
620
+ # A rate limit or a used-up allowance is not asked again here: the caller waits, or stops.
524
621
  break
525
622
  else:
526
623
  raise GatewayError(502, "GitHub Copilot kept refusing the names of the caller's tools.")
527
624
  if errors and not calls:
528
- raise self.refusal(errors[-1])
625
+ raise self.refusal(errors[-1], statuses[-1] if statuses else None)
529
626
  data = getattr(reply, "data", None)
530
627
  content = (data.content or "") if isinstance(data, AssistantMessageData) else ""
531
628
  if calls:
@@ -534,7 +631,7 @@ class Copilot:
534
631
  raise GatewayError(502, "GitHub Copilot sent no reply.")
535
632
  if req["schema"] is not None or req["json_only"]:
536
633
  content = strip_fences(content)
537
- return completion(req["model"], content, usage)
634
+ return completion(req["model"], content, usage, finish=finish["reason"])
538
635
 
539
636
 
540
637
  async def _wait(self, rid: str, session: Any, req: Dict[str, Any], turn: Dict[str, Any], gone: Optional["asyncio.Future[Any]"]) -> Tuple[Any, bool]:
@@ -576,6 +673,15 @@ _NO_BUILTIN = re.compile(r'tool "([A-Za-z0-9_-]{1,64})"[^"\n]{0,80}(?:does not|d
576
673
  _SIGNIN_REFUSED = re.compile(r"authori[sz]ation error|credentials may be expired|bad credentials|unauthori[sz]ed|not authenticated|no github oauth token|\b401\b", re.I)
577
674
 
578
675
 
676
+ _LIMITED = re.compile(r"rate.?limit|too many requests|quota|premium request|allowance|exceeded your|usage limit|\b429\b", re.I)
677
+ LIMITED_HINT = "the seat's rate limit or premium request allowance; wait, or pick a model with a lower multiplier: forgeqe models --copilot"
678
+
679
+
680
+ def limited(message: str, status: Optional[int] = None) -> bool:
681
+ """Whether Copilot's error is a rate limit or a used-up premium request allowance."""
682
+ return status == 429 or bool(_LIMITED.search(message or ""))
683
+
684
+
579
685
  def signin_refused(message: str) -> bool:
580
686
  """Whether Copilot's error says it would not take the sign-in or token (as opposed to the model or the request)."""
581
687
  return bool(_SIGNIN_REFUSED.search(message or ""))
@@ -726,6 +832,11 @@ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, cop
726
832
  writer.write(_error(401, "Unauthorized"))
727
833
  return
728
834
  path = path.split("?", 1)[0].rstrip("/")
835
+ # /effort/<level>/v1/...: a profile's reasoning effort (llms.json), for callers that send none of their own.
836
+ effort = None
837
+ m = _EFFORT_PATH.match(path)
838
+ if m:
839
+ effort, path = reasoning_effort(m.group(1)), m.group(2) or "/"
729
840
  if path.startswith("/v1/"):
730
841
  path = path[3:]
731
842
  if method == "GET" and path == "/models":
@@ -748,6 +859,8 @@ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, cop
748
859
  writer.write(_error(400, "The request body is not JSON."))
749
860
  return
750
861
  req = translate(body)
862
+ if effort and not req["reasoning_effort"]:
863
+ req["reasoning_effort"] = effort
751
864
  gone = asyncio.ensure_future(caller_gone(reader))
752
865
  try:
753
866
  if req["stream"]:
@@ -799,7 +912,9 @@ async def serve(out: TextIO, copilot: Any = None) -> int:
799
912
  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")
800
913
  return 1
801
914
  except Exception as e:
802
- out.write(json.dumps({"error": f"GitHub Copilot could not start: {type(e).__name__}: {e}"[:1500]}) + "\n")
915
+ hint = runtime_load_hint(str(e))
916
+ error = f"GitHub Copilot could not start: {type(e).__name__}: {e}"[:1500]
917
+ out.write(json.dumps({"error": f"{error}\n{hint}" if hint else error}) + "\n")
803
918
  return 1
804
919
  server = await asyncio.start_server(lambda r, w: handle(r, w, copilot, key), host="127.0.0.1", port=0, limit=64 * 1024)
805
920
  port = server.sockets[0].getsockname()[1]
@@ -814,6 +929,44 @@ async def serve(out: TextIO, copilot: Any = None) -> int:
814
929
  return 0
815
930
 
816
931
 
932
+ async def sign_out(out: TextIO, client: Any = None) -> int:
933
+ """
934
+ Removes the browser sign-in (forgeqe auth logout copilot): every account Copilot keeps in ForgeQE's Copilot home is
935
+ logged out, from the system's credential store and Copilot's own state. Prints {"removed": n} or {"error": ...}.
936
+ """
937
+ try:
938
+ if client is None:
939
+ from copilot import CopilotClient
940
+
941
+ home = copilot_home()
942
+ os.makedirs(home, exist_ok=True)
943
+ client = CopilotClient(**client_options(None, home, tempfile.mkdtemp(prefix="forgeqe-copilot-")))
944
+ await client.start()
945
+ from copilot.generated.rpc import AccountLogoutRequest
946
+
947
+ removed = 0
948
+ for user in await client.rpc.account.get_all_users():
949
+ sel = user.get("selectionId") if isinstance(user, dict) else getattr(user, "selection_id", None)
950
+ if isinstance(sel, str) and sel:
951
+ await client.rpc.account.logout(AccountLogoutRequest(selection_id=sel))
952
+ removed += 1
953
+ out.write(json.dumps({"removed": removed}) + "\n")
954
+ return 0
955
+ except Exception as e:
956
+ out.write(json.dumps({"error": f"{type(e).__name__}: {e}"[:500]}) + "\n")
957
+ return 1
958
+ finally:
959
+ try:
960
+ await client.stop()
961
+ except Exception:
962
+ pass
963
+
964
+
965
+ def sign_out_main(out: TextIO) -> int:
966
+ use_system_certificates()
967
+ return asyncio.run(sign_out(out))
968
+
969
+
817
970
  def main(out: TextIO) -> int:
818
971
  use_system_certificates()
819
972
  return asyncio.run(serve(out))