@capagents/forgeqe 2.10.4 → 3.0.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 (162) hide show
  1. package/HOW_TO_USE.md +119 -16
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/docs-site/docs/architecture/index.html +1 -0
  5. package/dist/docs-site/docs/cost-architecture/index.html +1 -1
  6. package/dist/docs-site/docs/index.html +158 -19
  7. package/dist/docs-site/docs/mobile/index.html +38 -2
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/forgeqe.js +2121 -1947
  10. package/dist/web/assets/Agent-DISh0THc.js +8 -0
  11. package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
  12. package/dist/web/assets/Browse-WylAQZvD.js +2 -0
  13. package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
  14. package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
  15. package/dist/web/assets/Compare-CgOfZofk.js +1 -0
  16. package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
  17. package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
  18. package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
  19. package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
  20. package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
  21. package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
  22. package/dist/web/assets/Features-DXL_vSjn.js +1 -0
  23. package/dist/web/assets/Flags-B7x2pDud.js +2 -0
  24. package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
  25. package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
  26. package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
  27. package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
  28. package/dist/web/assets/Migration-BOLN1duU.js +2 -0
  29. package/dist/web/assets/Product-C0FeEaJg.js +7 -0
  30. package/dist/web/assets/Production-BSMQyWKd.js +1 -0
  31. package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
  32. package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
  33. package/dist/web/assets/Record-CPx-lK53.js +2 -0
  34. package/dist/web/assets/Regression-BXbX46nO.js +5 -0
  35. package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
  36. package/dist/web/assets/Reports-36YQzVhA.js +2 -0
  37. package/dist/web/assets/Response-DplUOsue.js +4 -0
  38. package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
  39. package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
  40. package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
  41. package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
  42. package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
  43. package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
  44. package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
  45. package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
  46. package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
  47. package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
  48. package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
  49. package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
  50. package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
  51. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  52. package/dist/web/assets/fold-BhRpA0sy.js +1 -0
  53. package/dist/web/assets/frame-D_TPoUTD.js +16 -0
  54. package/dist/web/assets/index-BRB-oAMd.js +67 -0
  55. package/dist/web/assets/index-CIw5WfL8.css +2 -0
  56. package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
  57. package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
  58. package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
  59. package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
  60. package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
  61. package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
  62. package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
  63. package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
  64. package/dist/web/assets/rows-uLoguIo5.js +1 -0
  65. package/dist/web/assets/segmented-DphDskQz.js +1 -0
  66. package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
  67. package/dist/web/index.html +6 -6
  68. package/docs/ARCHITECTURE.md +1 -0
  69. package/docs/COST_ARCHITECTURE.md +1 -1
  70. package/docs/MOBILE.md +40 -0
  71. package/docs/user-guide.html +158 -19
  72. package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
  73. package/forgeqe.example.yaml +11 -1
  74. package/package.json +4 -1
  75. package/prompts/brain.md +4 -0
  76. package/prompts/browser-goal-verification.md +2 -0
  77. package/prompts/refine.md +2 -0
  78. package/prompts/requests-rule.md +1 -1
  79. package/prompts/talk-summary.md +43 -0
  80. package/prompts/talk.md +49 -0
  81. package/prompts/test-agent.md +1 -0
  82. package/prompts/test-reviewer.md +2 -1
  83. package/prompts/test-rules.md +3 -0
  84. package/py/forgeqe_data/__init__.py +1 -0
  85. package/py/forgeqe_data/__main__.py +12 -0
  86. package/py/forgeqe_data/connect.py +290 -0
  87. package/py/forgeqe_data/connstr.py +169 -0
  88. package/py/forgeqe_data/flows.py +603 -0
  89. package/py/forgeqe_data/guard.py +214 -0
  90. package/py/forgeqe_data/mongo.py +219 -0
  91. package/py/forgeqe_data/schema.py +431 -0
  92. package/py/forgeqe_data/service.py +651 -0
  93. package/py/forgeqe_data/streams.py +400 -0
  94. package/py/forgeqe_data/subset.py +299 -0
  95. package/py/forgeqe_data/testdata.py +861 -0
  96. package/py/forgeqe_data/vector.py +113 -0
  97. package/py/forgeqe_desktop/workflow.py +6 -4
  98. package/py/forgeqe_engine/capture.py +5 -4
  99. package/py/forgeqe_engine/diagnostics.py +2 -2
  100. package/py/forgeqe_engine/lenient_json.py +96 -0
  101. package/py/forgeqe_engine/llm.py +4 -0
  102. package/py/forgeqe_engine/network.py +93 -15
  103. package/py/forgeqe_engine/neutral_log.py +16 -1
  104. package/py/forgeqe_engine/recordsession.py +54 -1
  105. package/py/forgeqe_engine/service.py +22 -3
  106. package/py/forgeqe_mobile/appium_driver.py +9 -0
  107. package/py/forgeqe_mobile/apps.py +4 -0
  108. package/py/forgeqe_mobile/maestro.py +3 -0
  109. package/py/forgeqe_mobile/record.py +610 -0
  110. package/py/forgeqe_mobile/service.py +37 -7
  111. package/py/forgeqe_talk/__init__.py +1 -0
  112. package/py/forgeqe_talk/__main__.py +65 -0
  113. package/py/forgeqe_voice/worker.py +141 -0
  114. package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
  115. package/skills/playwright-typescript/SKILL.md +1 -1
  116. package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
  117. package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
  118. package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
  119. package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
  120. package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
  121. package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
  122. package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
  123. package/dist/web/assets/Data-BWTme_Yw.js +0 -6
  124. package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
  125. package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
  126. package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
  127. package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
  128. package/dist/web/assets/Features-DazEWqYu.js +0 -1
  129. package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
  130. package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
  131. package/dist/web/assets/Impact-De87sv5J.js +0 -3
  132. package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
  133. package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
  134. package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
  135. package/dist/web/assets/Product-DpK-PIxV.js +0 -7
  136. package/dist/web/assets/Production-D6A89rZZ.js +0 -1
  137. package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
  138. package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
  139. package/dist/web/assets/Record-DcgBatJJ.js +0 -2
  140. package/dist/web/assets/Regression-BJLYrqST.js +0 -5
  141. package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
  142. package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
  143. package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
  144. package/dist/web/assets/Runs-lb78rvPV.js +0 -2
  145. package/dist/web/assets/Steps-BDSeIznj.js +0 -2
  146. package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
  147. package/dist/web/assets/TestData-DP7cvW48.js +0 -2
  148. package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
  149. package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
  150. package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
  151. package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
  152. package/dist/web/assets/filters-CflRmNDz.js +0 -1
  153. package/dist/web/assets/fold-pOBiaSlF.js +0 -1
  154. package/dist/web/assets/frame-CYYiRu5P.js +0 -4
  155. package/dist/web/assets/index-CNDoTeRV.css +0 -2
  156. package/dist/web/assets/index-D4a0w3Vl.js +0 -67
  157. package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
  158. package/dist/web/assets/parts-C53RxMcR.js +0 -1
  159. package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
  160. package/dist/web/assets/rows-D6rPRkHl.js +0 -1
  161. package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
  162. package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
@@ -14,6 +14,7 @@ from __future__ import annotations
14
14
 
15
15
  import json
16
16
  import os
17
+ import queue
17
18
  import sys
18
19
  import threading
19
20
  import time
@@ -189,7 +190,7 @@ def _maestro_steps(wf: Mapping[str, Any], commands: List[Mapping[str, Any]], ok:
189
190
  """Each workflow step's result from Maestro's command results, as to_flow writes them: a type step is three Maestro
190
191
  commands, and a launch is launchApp then an optional tap for each dismiss target (which never fails the launch)."""
191
192
  dismiss = len(wf.get("dismiss") or [])
192
- per_step = [3 if s["op"] == "type" else 1 + dismiss if s["op"] == "launch" else 1 for s in wf["steps"]]
193
+ per_step = [3 if s["op"] == "type" else 2 if s["op"] == "select" else 1 + dismiss if s["op"] == "launch" else 1 for s in wf["steps"]]
193
194
  if not commands and not ok:
194
195
  # No step's result is known (Maestro wrote none, or the job's results did not come back): the run's error says
195
196
  # what failed, rather than a step that may have passed.
@@ -294,6 +295,16 @@ def _remember(memory: Any, goal: str, app: str, workflow: Optional[Mapping[str,
294
295
  return {"dir": str(memory.root), "kind": outcome.get("memory") or "", "replayed": int(outcome.get("replayed") or 0), "flow": flow}
295
296
 
296
297
 
298
+ def run_record_mode(req: Mapping[str, Any], events: Events, stop: threading.Event, commands: "queue.Queue[Mapping[str, Any]]", driver_factory: Optional[Callable[[], Any]] = None) -> Dict[str, Any]:
299
+ """A recording by hand (record.py): the page's commands come on stdin, the screen and steps go out as events."""
300
+ from .record import run_record
301
+
302
+ out = _out_dir(req)
303
+ mobile = _mobile(req)
304
+ apps = load_mobile_apps(mobile)
305
+ return run_record(req, events, stop, commands, driver_factory or (lambda: appium_driver(mobile)), apps, _secret_names(mobile), out)
306
+
307
+
297
308
  def run_flows(req: Mapping[str, Any], events: Events, maestro_run: Optional[Callable[..., Any]] = None, cloud_run: Optional[Callable[..., Any]] = None) -> Dict[str, Any]:
298
309
  """The team's own Maestro flows: each checked against the allowlist, then run together."""
299
310
  out = _out_dir(req)
@@ -360,11 +371,27 @@ def _app_of_flows(flows: List[str], apps: Mapping[str, Any]) -> Any:
360
371
  raise WorkflowError(f"no mobile app with app_id {app_id} is configured; add it (with its app build or lt:// id) to env.yaml or mobile.apps")
361
372
 
362
373
 
363
- def _watch_stop(stream: IO[str], stop: threading.Event) -> None:
374
+ MAX_COMMAND_LINE = 10_000
375
+
376
+
377
+ def _watch_stop(stream: IO[str], stop: threading.Event, commands: "Optional[queue.Queue[Mapping[str, Any]]]" = None) -> None:
378
+ """``stop`` on a line of its own stops the run. A recording's commands come as JSON objects, one per line, and go
379
+ to ``commands``; any other line is ignored."""
364
380
  for line in stream:
365
- if line.strip() == "stop":
381
+ text = line.strip()
382
+ if text == "stop":
366
383
  stop.set()
384
+ if commands is not None:
385
+ commands.put({"cmd": "stop"})
367
386
  return
387
+ if commands is None or not text.startswith("{") or len(text) > MAX_COMMAND_LINE:
388
+ continue
389
+ try:
390
+ cmd = json.loads(text)
391
+ except ValueError:
392
+ continue
393
+ if isinstance(cmd, dict):
394
+ commands.put(cmd)
368
395
 
369
396
 
370
397
  def serve(
@@ -382,17 +409,20 @@ def serve(
382
409
  req = json.loads(stdin.readline() or "{}")
383
410
  if not isinstance(req, dict):
384
411
  raise WorkflowError("the request must be a JSON object")
385
- threading.Thread(target=_watch_stop, args=(stdin, stop), daemon=True).start()
386
- out = _out_dir(req)
387
412
  mode = req.get("mode")
388
- if mode == "replay":
413
+ commands: "Optional[queue.Queue[Mapping[str, Any]]]" = queue.Queue() if mode == "record" else None
414
+ threading.Thread(target=_watch_stop, args=(stdin, stop, commands), daemon=True).start()
415
+ out = _out_dir(req)
416
+ if mode == "record" and commands is not None:
417
+ result = run_record_mode(req, events, stop, commands, driver_factory)
418
+ elif mode == "replay":
389
419
  result = run_replay(req, events, stop, driver_factory, model_factory, maestro_run, cloud_run)
390
420
  elif mode == "explore":
391
421
  result = run_explore(req, events, stop, driver_factory, model_factory)
392
422
  elif mode == "maestro":
393
423
  result = run_flows(req, events, maestro_run, cloud_run)
394
424
  else:
395
- raise WorkflowError(f"mode must be replay, explore or maestro, not {mode!r}")
425
+ raise WorkflowError(f"mode must be replay, explore, maestro or record, not {mode!r}")
396
426
  except Exception as e:
397
427
  result = {"ok": False, "error": f"{type(e).__name__}: {e}" if not isinstance(e, (WorkflowError, ValueError)) else str(e)}
398
428
  result.setdefault("format", MOBILE_FORMAT)
@@ -0,0 +1 @@
1
+ """Talk's voice agent's model calls (src/talk/agent.ts): one warm client for quick turns."""
@@ -0,0 +1,65 @@
1
+ """
2
+ ``python -m forgeqe_talk serve``: Talk's voice agent's model, kept warm for quick turns (src/talk/agent.ts).
3
+
4
+ The first line on stdin is ``{"llm": <profile>}`` (llms.json's, as the engine takes it); each line after it is one
5
+ call, ``{"id": "<id>", "messages": [...], "max_tokens": n}``, answered on stdout as ``{"id", "ok", "text"}`` or
6
+ ``{"id", "ok": false, "error"}``, in the order asked. The model is asked for JSON (the voice agent's answer, which the
7
+ gateway checks). Each call's time and tokens go out as ``{"type": "call", ...}``; never a prompt or a reply.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ import sys
14
+ from typing import Any, Dict, IO
15
+
16
+ MAX_LINE = 400_000
17
+ _ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
18
+
19
+
20
+ def _emit(out: IO[str], event: Dict[str, Any]) -> None:
21
+ out.write(json.dumps(event, ensure_ascii=False) + "\n")
22
+ out.flush()
23
+
24
+
25
+ def serve(stdin: IO[str] = sys.stdin, stdout: IO[str] = sys.stdout, model_factory: Any = None) -> int:
26
+ first = stdin.readline()
27
+ try:
28
+ req = json.loads(first or "{}")
29
+ profile = req.get("llm") if isinstance(req, dict) else None
30
+ if not isinstance(profile, dict):
31
+ raise ValueError("the first line must be {\"llm\": <profile>}")
32
+ if model_factory is None:
33
+ from forgeqe_desktop.models import DesktopModel
34
+
35
+ model_factory = DesktopModel
36
+ model = model_factory(profile, on_call=lambda c: _emit(stdout, {"type": "call", **c}), timeout=60.0)
37
+ except Exception as e: # noqa: BLE001 - said to the gateway, which says it to the page
38
+ _emit(stdout, {"type": "fatal", "error": f"{type(e).__name__}: {e}"[:500]})
39
+ return 1
40
+ _emit(stdout, {"type": "ready"})
41
+ for line in stdin:
42
+ if len(line) > MAX_LINE:
43
+ continue
44
+ try:
45
+ call = json.loads(line)
46
+ except ValueError:
47
+ continue
48
+ cid = call.get("id") if isinstance(call, dict) else None
49
+ messages = call.get("messages") if isinstance(call, dict) else None
50
+ if not isinstance(cid, str) or not _ID.match(cid) or not isinstance(messages, list):
51
+ continue
52
+ max_tokens = call.get("max_tokens") if isinstance(call.get("max_tokens"), int) else 400
53
+ try:
54
+ text = model.complete(messages, max_tokens=max(50, min(max_tokens, 1000)), json_mode=True)
55
+ _emit(stdout, {"id": cid, "ok": True, "text": text[:20_000]})
56
+ except Exception as e: # noqa: BLE001 - one failed call; the next may work
57
+ _emit(stdout, {"id": cid, "ok": False, "error": f"{type(e).__name__}: {e}"[:500]})
58
+ return 0
59
+
60
+
61
+ if __name__ == "__main__":
62
+ if sys.argv[1:] != ["serve"]:
63
+ sys.stderr.write("usage: python -m forgeqe_talk serve\n")
64
+ sys.exit(2)
65
+ sys.exit(serve())
@@ -0,0 +1,141 @@
1
+ """Speech to text and text to speech for the web app's Talk mode (src/voice/worker.ts), on this computer only.
2
+
3
+ Run by ForgeQE as ``python -I worker.py <models folder>`` in its own environment (~/.forgeqe/voice/.venv), with no shell,
4
+ an environment of system settings only (src/voice/setup.ts, ``voiceEnv``) and Hugging Face kept offline: the models are
5
+ the files ForgeQE downloaded and checked by SHA-256, read from the folder given, and nothing is fetched here.
6
+
7
+ It reads one JSON request per line on stdin and writes one JSON answer per line on stdout:
8
+
9
+ - ``{"id": 1, "op": "transcribe", "pcm": "<base64>", "language": "en"}``: 16 kHz mono 16-bit PCM, at most
10
+ ``MAX_SECONDS``, to ``{"id": 1, "ok": true, "text": "..."}`` (faster-whisper, its Silero voice filter on).
11
+ - ``{"id": 2, "op": "speak", "text": "...", "voice": "af_heart"}``: at most ``MAX_TEXT`` characters to
12
+ ``{"id": 2, "ok": true, "wav": "<base64>"}`` (Kokoro), a 24 kHz mono 16-bit WAV.
13
+
14
+ Everything a request carries is checked again here (sizes, the voice's shape and that Kokoro has it, the language
15
+ of a fixed list). An error is ``{"id": n, "ok": false, "error": "..."}`` on one line, never a traceback.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import io
22
+ import json
23
+ import re
24
+ import sys
25
+ import wave
26
+ from pathlib import Path
27
+
28
+ FORMAT = 1
29
+ RATE_IN = 16_000
30
+ MAX_SECONDS = 30
31
+ MAX_TEXT = 600
32
+ VOICE = re.compile(r"^[abh][fm]_[a-z]{2,12}$")
33
+ LANGUAGES = {"en", "de", "es", "fr", "it", "nl", "pt", "pl", "hi", "ja", "zh"}
34
+ # Words ForgeQE's people say often, so Whisper spells them as they are written.
35
+ # The words people say to ForgeQE that Whisper does not know ("ADO" heard as "a do", "TestMu" as "Tasmo"): a fixed list,
36
+ # never what anyone typed, so it only leans what is heard toward these spellings.
37
+ PROMPT = (
38
+ "ForgeQE, ADO, Azure DevOps, Jira, ACs, acceptance criteria, work item, user story, test case, test plan, "
39
+ "TestMu, BrowserStack, Playwright, Cypress, Selenium, Appium, Maestro, Tosca, regression pack, staging, Record, runs."
40
+ )
41
+ # Hindi as people say it to ForgeQE: Hindi with its English terms ("मॉडल सेटिंग्स खोलो", "ADO से 256 के ACs"). Fixed.
42
+ HI_PROMPT = "ForgeQE, ADO, Azure DevOps, Jira, ACs, TestMu, Playwright. मॉडल सेटिंग्स खोलो। मेरे फेल हुए रन दिखाओ। टेस्ट केस।"
43
+
44
+
45
+ def _say(msg: dict) -> None:
46
+ sys.stdout.write(json.dumps(msg) + "\n")
47
+ sys.stdout.flush()
48
+
49
+
50
+ class Voice:
51
+ def __init__(self, models: Path) -> None:
52
+ from faster_whisper import WhisperModel
53
+ from kokoro_onnx import Kokoro
54
+
55
+ self.models = models
56
+ self.whisper = WhisperModel(str(models / "whisper-base"), device="cpu", compute_type="int8")
57
+ # Hindi's listening model (whisper-small), loaded the first time Hindi is heard, when it was downloaded.
58
+ self.whisper_hi = None
59
+ self.kokoro = Kokoro(str(models / "kokoro" / "kokoro-v1.0.int8.onnx"), str(models / "kokoro" / "voices-v1.0.bin"))
60
+ self.voices = set(self.kokoro.get_voices())
61
+
62
+ def transcribe(self, req: dict) -> dict:
63
+ import numpy as np
64
+
65
+ raw = base64.b64decode(str(req.get("pcm", "")), validate=True)
66
+ if not raw or len(raw) % 2 or len(raw) > RATE_IN * 2 * MAX_SECONDS:
67
+ raise ValueError("The recording is empty, cut, or longer than ForgeQE takes.")
68
+ language = req.get("language") or "en"
69
+ if language not in LANGUAGES:
70
+ raise ValueError("That language is not one Talk offers.")
71
+ audio = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
72
+ model, prompt = self.whisper, PROMPT
73
+ if language == "hi":
74
+ small = self.models / "whisper-small"
75
+ if self.whisper_hi is None and (small / "model.bin").is_file():
76
+ from faster_whisper import WhisperModel
77
+
78
+ self.whisper_hi = WhisperModel(str(small), device="cpu", compute_type="int8")
79
+ if self.whisper_hi is not None:
80
+ model, prompt = self.whisper_hi, HI_PROMPT
81
+ segments, _ = model.transcribe(audio, language=language, beam_size=1, vad_filter=True, initial_prompt=prompt, condition_on_previous_text=False)
82
+ return {"text": " ".join(s.text.strip() for s in segments).strip()}
83
+
84
+ def speak(self, req: dict) -> dict:
85
+ import numpy as np
86
+
87
+ text = req.get("text")
88
+ voice = req.get("voice")
89
+ if not isinstance(text, str) or not text.strip() or len(text) > MAX_TEXT:
90
+ raise ValueError("Nothing to say, or too much.")
91
+ if not isinstance(voice, str) or not VOICE.match(voice) or voice not in self.voices:
92
+ raise ValueError("That voice is not one Talk offers.")
93
+ lang = "hi" if voice.startswith("h") else "en-gb" if voice.startswith("b") else "en-us"
94
+ samples, rate = self.kokoro.create(text, voice=voice, speed=1.0, lang=lang)
95
+ pcm = (np.clip(samples, -1.0, 1.0) * 32767).astype("<i2").tobytes()
96
+ out = io.BytesIO()
97
+ with wave.open(out, "wb") as w:
98
+ w.setnchannels(1)
99
+ w.setsampwidth(2)
100
+ w.setframerate(int(rate))
101
+ w.writeframes(pcm)
102
+ return {"wav": base64.b64encode(out.getvalue()).decode("ascii")}
103
+
104
+
105
+ def main() -> int:
106
+ if len(sys.argv) != 2:
107
+ _say({"ready": False, "error": "usage: worker.py <models folder>"})
108
+ return 2
109
+ try:
110
+ voice = Voice(Path(sys.argv[1]))
111
+ except Exception as e: # noqa: BLE001 - one line for ForgeQE, never a traceback
112
+ _say({"ready": False, "error": f"The speech models do not load: {type(e).__name__}"})
113
+ return 1
114
+ _say({"ready": True, "format": FORMAT})
115
+ for line in sys.stdin:
116
+ try:
117
+ req = json.loads(line)
118
+ except ValueError:
119
+ continue
120
+ if not isinstance(req, dict):
121
+ continue
122
+ rid = req.get("id")
123
+ if not isinstance(rid, int):
124
+ continue
125
+ op = req.get("op")
126
+ try:
127
+ if op == "transcribe":
128
+ _say({"id": rid, "ok": True, **voice.transcribe(req)})
129
+ elif op == "speak":
130
+ _say({"id": rid, "ok": True, **voice.speak(req)})
131
+ else:
132
+ _say({"id": rid, "ok": False, "error": "Unknown request."})
133
+ except ValueError as e:
134
+ _say({"id": rid, "ok": False, "error": str(e)[:200]})
135
+ except Exception as e: # noqa: BLE001
136
+ _say({"id": rid, "ok": False, "error": f"Speech failed: {type(e).__name__}"})
137
+ return 0
138
+
139
+
140
+ if __name__ == "__main__":
141
+ sys.exit(main())
@@ -27,6 +27,7 @@ agents: [scribe]
27
27
  - Assert page state with retrying assertions: `await Expect(locator).ToBeVisibleAsync()`, `ToHaveTextAsync`, `ToHaveValueAsync`, and `await Expect(Page).ToHaveURLAsync(...)`. Use NUnit's `Assert.That` for plain values only, never on `await locator.IsVisibleAsync()`.
28
28
  - Wait for outcomes with `Page.WaitForURLAsync`, `Page.RunAndWaitForResponseAsync`, or an assertion.
29
29
  - One overlay that appears at random (a cookie banner, a survey): register `Page.AddLocatorHandlerAsync(...)` in `[SetUp]` of the base class (Playwright 1.42 and later) rather than clicking it inside a test.
30
+ - Find an overlay's close button inside the overlay's own container (`banner.GetByRole(AriaRole.Button, new() { Name = "Accept all", Exact = true })`): consent tools often render a second "Accept all" elsewhere, and strict mode then throws. After the click, `await Expect(banner).ToBeHiddenAsync()`. A helper that closes it "if present" catches only the `TimeoutException` of it not showing, never a `PlaywrightException`.
30
31
  - Two or more that can show at once: write one helper that closes each visible one, top first, as the test rules describe. A handler's click is blocked while another overlay covers it.
31
32
 
32
33
  ## Data, secrets, attributes
@@ -27,7 +27,7 @@ agents: [scribe]
27
27
  - Wait for outcomes, never time: no `page.waitForTimeout`. Use an assertion, `page.waitForURL`, or a `page.waitForResponse(...)` promise created before the click that triggers the request.
28
28
 
29
29
  ## Overlays that come and go
30
- - One cookie banner, chat prompt, or survey that appears at random: register `page.addLocatorHandler(page.getByRole('button', { name: 'Accept all' }), async (button) => { await button.click() })` in a fixture or `beforeEach` (Playwright 1.42 and later), instead of clicking it inside the test.
30
+ - One cookie banner, chat prompt, or survey that appears at random: register `page.addLocatorHandler(banner, async () => { await banner.getByRole('button', { name: 'Accept all', exact: true }).click(); await expect(banner).toBeHidden() })`, where `banner` is the overlay's own container (`page.locator('#cookie-banner')`) in a fixture or `beforeEach` (Playwright 1.42 and later), instead of clicking it inside the test.
31
31
  - Two or more that can show at once: write one helper that closes each visible one, top first, as the test rules describe. A handler's click is blocked while another overlay covers it.
32
32
 
33
33
  ## Data and secrets