@screenreader-speech-capture/bridge 0.2.0 → 0.3.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 (223) hide show
  1. package/dist/cli.mjs +1109 -792
  2. package/dist/ui/adapter-node.js +1 -1
  3. package/dist/ui/client/ui/_app/immutable/chunks/BEImj5AP.js +1 -0
  4. package/dist/ui/client/ui/_app/immutable/chunks/BEImj5AP.js.br +0 -0
  5. package/dist/ui/client/ui/_app/immutable/chunks/BEImj5AP.js.gz +0 -0
  6. package/dist/ui/client/ui/_app/immutable/chunks/B__KpOuX.js +3 -0
  7. package/dist/ui/client/ui/_app/immutable/chunks/B__KpOuX.js.br +0 -0
  8. package/dist/ui/client/ui/_app/immutable/chunks/B__KpOuX.js.gz +0 -0
  9. package/dist/ui/client/ui/_app/immutable/chunks/BkoDSEOx.js +1 -0
  10. package/dist/ui/client/ui/_app/immutable/chunks/BkoDSEOx.js.br +0 -0
  11. package/dist/ui/client/ui/_app/immutable/chunks/BkoDSEOx.js.gz +0 -0
  12. package/dist/ui/client/ui/_app/immutable/chunks/BlC5mir6.js +1 -0
  13. package/dist/ui/client/ui/_app/immutable/chunks/BlC5mir6.js.br +2 -0
  14. package/dist/ui/client/ui/_app/immutable/chunks/BlC5mir6.js.gz +0 -0
  15. package/dist/ui/client/ui/_app/immutable/chunks/BquQTeuV.js +1 -0
  16. package/dist/ui/client/ui/_app/immutable/chunks/BquQTeuV.js.br +0 -0
  17. package/dist/ui/client/ui/_app/immutable/chunks/BquQTeuV.js.gz +0 -0
  18. package/dist/ui/client/ui/_app/immutable/chunks/BtnuBvK5.js +1 -0
  19. package/dist/ui/client/ui/_app/immutable/chunks/BtnuBvK5.js.br +1 -0
  20. package/dist/ui/client/ui/_app/immutable/chunks/BtnuBvK5.js.gz +0 -0
  21. package/dist/ui/client/ui/_app/immutable/chunks/{Dk73DTz3.js → BuwZGWCm.js} +21 -21
  22. package/dist/ui/client/ui/_app/immutable/chunks/BuwZGWCm.js.br +0 -0
  23. package/dist/ui/client/ui/_app/immutable/chunks/BuwZGWCm.js.gz +0 -0
  24. package/dist/ui/client/ui/_app/immutable/chunks/Bxh3K0TK.js +1 -0
  25. package/dist/ui/client/ui/_app/immutable/chunks/Bxh3K0TK.js.br +0 -0
  26. package/dist/ui/client/ui/_app/immutable/chunks/Bxh3K0TK.js.gz +0 -0
  27. package/dist/ui/client/ui/_app/immutable/chunks/C06IiL6m.js +1 -0
  28. package/dist/ui/client/ui/_app/immutable/chunks/C06IiL6m.js.br +2 -0
  29. package/dist/ui/client/ui/_app/immutable/chunks/C06IiL6m.js.gz +0 -0
  30. package/dist/ui/client/ui/_app/immutable/chunks/C75l7c5l.js +1 -0
  31. package/dist/ui/client/ui/_app/immutable/chunks/C75l7c5l.js.br +0 -0
  32. package/dist/ui/client/ui/_app/immutable/chunks/C75l7c5l.js.gz +0 -0
  33. package/dist/ui/client/ui/_app/immutable/chunks/{hhZsYtkz.js → CAZ56n62.js} +3 -3
  34. package/dist/ui/client/ui/_app/immutable/chunks/CAZ56n62.js.br +0 -0
  35. package/dist/ui/client/ui/_app/immutable/chunks/CAZ56n62.js.gz +0 -0
  36. package/dist/ui/client/ui/_app/immutable/chunks/Cb63XE4v.js +33 -0
  37. package/dist/ui/client/ui/_app/immutable/chunks/Cb63XE4v.js.br +0 -0
  38. package/dist/ui/client/ui/_app/immutable/chunks/Cb63XE4v.js.gz +0 -0
  39. package/dist/ui/client/ui/_app/immutable/chunks/DRNNJMYk.js +5 -0
  40. package/dist/ui/client/ui/_app/immutable/chunks/DRNNJMYk.js.br +0 -0
  41. package/dist/ui/client/ui/_app/immutable/chunks/DRNNJMYk.js.gz +0 -0
  42. package/dist/ui/client/ui/_app/immutable/chunks/DWjfB3ah.js +1 -0
  43. package/dist/ui/client/ui/_app/immutable/chunks/DWjfB3ah.js.br +0 -0
  44. package/dist/ui/client/ui/_app/immutable/chunks/DWjfB3ah.js.gz +0 -0
  45. package/dist/ui/client/ui/_app/immutable/chunks/JsC3ASJq.js +3 -0
  46. package/dist/ui/client/ui/_app/immutable/chunks/JsC3ASJq.js.br +0 -0
  47. package/dist/ui/client/ui/_app/immutable/chunks/JsC3ASJq.js.gz +0 -0
  48. package/dist/ui/client/ui/_app/immutable/chunks/{DU8ibkb0.js → OAsMjdHF.js} +13 -13
  49. package/dist/ui/client/ui/_app/immutable/chunks/OAsMjdHF.js.br +0 -0
  50. package/dist/ui/client/ui/_app/immutable/chunks/OAsMjdHF.js.gz +0 -0
  51. package/dist/ui/client/ui/_app/immutable/chunks/UKukklIc.js +1 -0
  52. package/dist/ui/client/ui/_app/immutable/chunks/UKukklIc.js.br +2 -0
  53. package/dist/ui/client/ui/_app/immutable/chunks/UKukklIc.js.gz +0 -0
  54. package/dist/ui/client/ui/_app/immutable/chunks/{DoG5cwE3.js → VxDST09k.js} +1 -1
  55. package/dist/ui/client/ui/_app/immutable/chunks/VxDST09k.js.br +0 -0
  56. package/dist/ui/client/ui/_app/immutable/chunks/VxDST09k.js.gz +0 -0
  57. package/dist/ui/client/ui/_app/immutable/chunks/{CEGGem4o.js → vPs9G1oN.js} +36 -36
  58. package/dist/ui/client/ui/_app/immutable/chunks/vPs9G1oN.js.br +0 -0
  59. package/dist/ui/client/ui/_app/immutable/chunks/vPs9G1oN.js.gz +0 -0
  60. package/dist/ui/client/ui/_app/immutable/chunks/{Bq3k_s8n.js → w5i9ZoX_.js} +2 -2
  61. package/dist/ui/client/ui/_app/immutable/chunks/w5i9ZoX_.js.br +0 -0
  62. package/dist/ui/client/ui/_app/immutable/chunks/w5i9ZoX_.js.gz +0 -0
  63. package/dist/ui/client/ui/_app/immutable/entry/app.B2MXuPeH.js +2 -0
  64. package/dist/ui/client/ui/_app/immutable/entry/app.B2MXuPeH.js.br +0 -0
  65. package/dist/ui/client/ui/_app/immutable/entry/app.B2MXuPeH.js.gz +0 -0
  66. package/dist/ui/client/ui/_app/immutable/entry/start.4hiWLKwq.js +2 -0
  67. package/dist/ui/client/ui/_app/immutable/entry/start.4hiWLKwq.js.br +0 -0
  68. package/dist/ui/client/ui/_app/immutable/entry/start.4hiWLKwq.js.gz +0 -0
  69. package/dist/ui/client/ui/_app/immutable/nodes/0.CEfoZ0Mb.js +1 -0
  70. package/dist/ui/client/ui/_app/immutable/nodes/0.CEfoZ0Mb.js.br +0 -0
  71. package/dist/ui/client/ui/_app/immutable/nodes/0.CEfoZ0Mb.js.gz +0 -0
  72. package/dist/ui/client/ui/_app/immutable/nodes/1.BBl7b45u.js +1 -0
  73. package/dist/ui/client/ui/_app/immutable/nodes/1.BBl7b45u.js.br +0 -0
  74. package/dist/ui/client/ui/_app/immutable/nodes/1.BBl7b45u.js.gz +0 -0
  75. package/dist/ui/client/ui/_app/immutable/nodes/2.4VpydhMh.js +1 -0
  76. package/dist/ui/client/ui/_app/immutable/nodes/2.4VpydhMh.js.br +0 -0
  77. package/dist/ui/client/ui/_app/immutable/nodes/2.4VpydhMh.js.gz +0 -0
  78. package/dist/ui/client/ui/_app/immutable/nodes/3.BzIz3rja.js +5 -0
  79. package/dist/ui/client/ui/_app/immutable/nodes/3.BzIz3rja.js.br +0 -0
  80. package/dist/ui/client/ui/_app/immutable/nodes/3.BzIz3rja.js.gz +0 -0
  81. package/dist/ui/client/ui/_app/immutable/nodes/4.B9Ke6ZBV.js +180 -0
  82. package/dist/ui/client/ui/_app/immutable/nodes/4.B9Ke6ZBV.js.br +0 -0
  83. package/dist/ui/client/ui/_app/immutable/nodes/4.B9Ke6ZBV.js.gz +0 -0
  84. package/dist/ui/client/ui/_app/immutable/nodes/5.Cm6I95kb.js +6 -0
  85. package/dist/ui/client/ui/_app/immutable/nodes/5.Cm6I95kb.js.br +0 -0
  86. package/dist/ui/client/ui/_app/immutable/nodes/5.Cm6I95kb.js.gz +0 -0
  87. package/dist/ui/client/ui/_app/immutable/nodes/6.B_1Pts2e.js +6 -0
  88. package/dist/ui/client/ui/_app/immutable/nodes/6.B_1Pts2e.js.br +0 -0
  89. package/dist/ui/client/ui/_app/immutable/nodes/6.B_1Pts2e.js.gz +0 -0
  90. package/dist/ui/client/ui/_app/version.json +1 -1
  91. package/dist/ui/client/ui/_app/version.json.br +0 -0
  92. package/dist/ui/client/ui/_app/version.json.gz +0 -0
  93. package/dist/ui/server/.vite/manifest.json +83 -38
  94. package/dist/ui/server/chunks/{composition.js → app-context.js} +5 -965
  95. package/dist/ui/server/chunks/app-context.js.map +1 -0
  96. package/dist/ui/server/chunks/config2.js +106 -0
  97. package/dist/ui/server/chunks/config2.js.map +1 -0
  98. package/dist/ui/server/chunks/dialog.js +1 -1
  99. package/dist/ui/server/chunks/instance.js +3 -3
  100. package/dist/ui/server/chunks/internal.js +1 -1
  101. package/dist/ui/server/chunks/outlined-button.js +1 -1
  102. package/dist/ui/server/chunks/outlined-text-field.js +1 -1
  103. package/dist/ui/server/chunks/redispatch-event.js +1 -1
  104. package/dist/ui/server/chunks/rolldown-runtime.js +12 -0
  105. package/dist/ui/server/chunks/rules.js +173 -0
  106. package/dist/ui/server/chunks/rules.js.map +1 -0
  107. package/dist/ui/server/chunks/sessions.remote.js +1 -11
  108. package/dist/ui/server/chunks/sessions.remote.js.map +1 -1
  109. package/dist/ui/server/chunks/setup.js +86 -0
  110. package/dist/ui/server/chunks/setup.js.map +1 -0
  111. package/dist/ui/server/chunks/{icon-button.js → speech.js} +42 -3
  112. package/dist/ui/server/chunks/speech.js.map +1 -0
  113. package/dist/ui/server/chunks/src.js +37 -183
  114. package/dist/ui/server/chunks/src.js.map +1 -1
  115. package/dist/ui/server/chunks/static-html.js +1 -1
  116. package/dist/ui/server/chunks/text-button.js +1 -1
  117. package/dist/ui/server/chunks/validate.js +23 -0
  118. package/dist/ui/server/chunks/validate.js.map +1 -0
  119. package/dist/ui/server/chunks/vocabulary.js +19 -0
  120. package/dist/ui/server/chunks/vocabulary.js.map +1 -0
  121. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js +4 -2
  122. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js.map +1 -1
  123. package/dist/ui/server/entries/endpoints/api/input/keys/_server.ts.js +15 -5
  124. package/dist/ui/server/entries/endpoints/api/input/keys/_server.ts.js.map +1 -1
  125. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js +4 -2
  126. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js.map +1 -1
  127. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js +4 -2
  128. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js.map +1 -1
  129. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js +10 -13
  130. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js.map +1 -1
  131. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js +2 -1
  132. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js.map +1 -1
  133. package/dist/ui/server/entries/hooks.server.js +30 -25
  134. package/dist/ui/server/entries/hooks.server.js.map +1 -1
  135. package/dist/ui/server/entries/pages/_layout.svelte.js +750 -3
  136. package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
  137. package/dist/ui/server/entries/pages/_page.svelte.js +34 -25
  138. package/dist/ui/server/entries/pages/_page.svelte.js.map +1 -1
  139. package/dist/ui/server/entries/pages/settings/_page.svelte.js +5 -3
  140. package/dist/ui/server/entries/pages/settings/_page.svelte.js.map +1 -1
  141. package/dist/ui/server/entries/pages/setup/_page.svelte.js +2 -1
  142. package/dist/ui/server/entries/pages/setup/_page.svelte.js.map +1 -1
  143. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js +3 -2
  144. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js.map +1 -1
  145. package/dist/ui/server/manifest-full.js +1 -1
  146. package/dist/ui/server/manifest.js +1 -1
  147. package/dist/ui/server/nodes/0.js +1 -1
  148. package/dist/ui/server/nodes/1.js +1 -1
  149. package/dist/ui/server/nodes/2.js +1 -1
  150. package/dist/ui/server/nodes/3.js +1 -1
  151. package/dist/ui/server/nodes/4.js +1 -1
  152. package/dist/ui/server/nodes/5.js +1 -1
  153. package/dist/ui/server/nodes/6.js +1 -1
  154. package/dist/ui/server/server.js +1 -1
  155. package/package.json +1 -1
  156. package/dist/ui/client/ui/_app/immutable/chunks/0FroJ-XN.js +0 -3
  157. package/dist/ui/client/ui/_app/immutable/chunks/0FroJ-XN.js.br +0 -0
  158. package/dist/ui/client/ui/_app/immutable/chunks/0FroJ-XN.js.gz +0 -0
  159. package/dist/ui/client/ui/_app/immutable/chunks/B_ZElYu_.js +0 -1
  160. package/dist/ui/client/ui/_app/immutable/chunks/B_ZElYu_.js.br +0 -2
  161. package/dist/ui/client/ui/_app/immutable/chunks/B_ZElYu_.js.gz +0 -0
  162. package/dist/ui/client/ui/_app/immutable/chunks/Bq3k_s8n.js.br +0 -0
  163. package/dist/ui/client/ui/_app/immutable/chunks/Bq3k_s8n.js.gz +0 -0
  164. package/dist/ui/client/ui/_app/immutable/chunks/CEGGem4o.js.br +0 -0
  165. package/dist/ui/client/ui/_app/immutable/chunks/CEGGem4o.js.gz +0 -0
  166. package/dist/ui/client/ui/_app/immutable/chunks/CVpgcnu3.js +0 -1
  167. package/dist/ui/client/ui/_app/immutable/chunks/CVpgcnu3.js.br +0 -0
  168. package/dist/ui/client/ui/_app/immutable/chunks/CVpgcnu3.js.gz +0 -0
  169. package/dist/ui/client/ui/_app/immutable/chunks/Cwz551Q0.js +0 -5
  170. package/dist/ui/client/ui/_app/immutable/chunks/Cwz551Q0.js.br +0 -0
  171. package/dist/ui/client/ui/_app/immutable/chunks/Cwz551Q0.js.gz +0 -0
  172. package/dist/ui/client/ui/_app/immutable/chunks/D-2Nx62w.js +0 -1
  173. package/dist/ui/client/ui/_app/immutable/chunks/D-2Nx62w.js.br +0 -4
  174. package/dist/ui/client/ui/_app/immutable/chunks/D-2Nx62w.js.gz +0 -0
  175. package/dist/ui/client/ui/_app/immutable/chunks/DHsTyp2W.js +0 -1
  176. package/dist/ui/client/ui/_app/immutable/chunks/DHsTyp2W.js.br +0 -2
  177. package/dist/ui/client/ui/_app/immutable/chunks/DHsTyp2W.js.gz +0 -0
  178. package/dist/ui/client/ui/_app/immutable/chunks/DJvJc_zO.js +0 -33
  179. package/dist/ui/client/ui/_app/immutable/chunks/DJvJc_zO.js.br +0 -0
  180. package/dist/ui/client/ui/_app/immutable/chunks/DJvJc_zO.js.gz +0 -0
  181. package/dist/ui/client/ui/_app/immutable/chunks/DU8ibkb0.js.br +0 -0
  182. package/dist/ui/client/ui/_app/immutable/chunks/DU8ibkb0.js.gz +0 -0
  183. package/dist/ui/client/ui/_app/immutable/chunks/Dk73DTz3.js.br +0 -0
  184. package/dist/ui/client/ui/_app/immutable/chunks/Dk73DTz3.js.gz +0 -0
  185. package/dist/ui/client/ui/_app/immutable/chunks/DoG5cwE3.js.br +0 -3
  186. package/dist/ui/client/ui/_app/immutable/chunks/DoG5cwE3.js.gz +0 -0
  187. package/dist/ui/client/ui/_app/immutable/chunks/Dvxhfd7j.js +0 -3
  188. package/dist/ui/client/ui/_app/immutable/chunks/Dvxhfd7j.js.br +0 -0
  189. package/dist/ui/client/ui/_app/immutable/chunks/Dvxhfd7j.js.gz +0 -0
  190. package/dist/ui/client/ui/_app/immutable/chunks/DzInmTUe.js +0 -1
  191. package/dist/ui/client/ui/_app/immutable/chunks/DzInmTUe.js.br +0 -1
  192. package/dist/ui/client/ui/_app/immutable/chunks/DzInmTUe.js.gz +0 -0
  193. package/dist/ui/client/ui/_app/immutable/chunks/hhZsYtkz.js.br +0 -0
  194. package/dist/ui/client/ui/_app/immutable/chunks/hhZsYtkz.js.gz +0 -0
  195. package/dist/ui/client/ui/_app/immutable/entry/app.Bic9wlww.js +0 -2
  196. package/dist/ui/client/ui/_app/immutable/entry/app.Bic9wlww.js.br +0 -0
  197. package/dist/ui/client/ui/_app/immutable/entry/app.Bic9wlww.js.gz +0 -0
  198. package/dist/ui/client/ui/_app/immutable/entry/start.DqIv9xYX.js +0 -2
  199. package/dist/ui/client/ui/_app/immutable/entry/start.DqIv9xYX.js.br +0 -0
  200. package/dist/ui/client/ui/_app/immutable/entry/start.DqIv9xYX.js.gz +0 -0
  201. package/dist/ui/client/ui/_app/immutable/nodes/0.IqK6bsxB.js +0 -1
  202. package/dist/ui/client/ui/_app/immutable/nodes/0.IqK6bsxB.js.br +0 -0
  203. package/dist/ui/client/ui/_app/immutable/nodes/0.IqK6bsxB.js.gz +0 -0
  204. package/dist/ui/client/ui/_app/immutable/nodes/1.C81neQJL.js +0 -1
  205. package/dist/ui/client/ui/_app/immutable/nodes/1.C81neQJL.js.br +0 -0
  206. package/dist/ui/client/ui/_app/immutable/nodes/1.C81neQJL.js.gz +0 -0
  207. package/dist/ui/client/ui/_app/immutable/nodes/2.CmlyeAx_.js +0 -1
  208. package/dist/ui/client/ui/_app/immutable/nodes/2.CmlyeAx_.js.br +0 -0
  209. package/dist/ui/client/ui/_app/immutable/nodes/2.CmlyeAx_.js.gz +0 -0
  210. package/dist/ui/client/ui/_app/immutable/nodes/3.DYZ3H5TS.js +0 -5
  211. package/dist/ui/client/ui/_app/immutable/nodes/3.DYZ3H5TS.js.br +0 -0
  212. package/dist/ui/client/ui/_app/immutable/nodes/3.DYZ3H5TS.js.gz +0 -0
  213. package/dist/ui/client/ui/_app/immutable/nodes/4.Lwlmq1AY.js +0 -180
  214. package/dist/ui/client/ui/_app/immutable/nodes/4.Lwlmq1AY.js.br +0 -0
  215. package/dist/ui/client/ui/_app/immutable/nodes/4.Lwlmq1AY.js.gz +0 -0
  216. package/dist/ui/client/ui/_app/immutable/nodes/5.rBMVkFpN.js +0 -6
  217. package/dist/ui/client/ui/_app/immutable/nodes/5.rBMVkFpN.js.br +0 -0
  218. package/dist/ui/client/ui/_app/immutable/nodes/5.rBMVkFpN.js.gz +0 -0
  219. package/dist/ui/client/ui/_app/immutable/nodes/6.nui9awM2.js +0 -6
  220. package/dist/ui/client/ui/_app/immutable/nodes/6.nui9awM2.js.br +0 -0
  221. package/dist/ui/client/ui/_app/immutable/nodes/6.nui9awM2.js.gz +0 -0
  222. package/dist/ui/server/chunks/composition.js.map +0 -1
  223. package/dist/ui/server/chunks/icon-button.js.map +0 -1
package/dist/cli.mjs CHANGED
@@ -5,7 +5,7 @@ import os, { hostname } from "node:os";
5
5
  import http from "node:http";
6
6
  import net from "node:net";
7
7
  import { finished, pipeline } from "node:stream";
8
- import { setImmediate, setTimeout as setTimeout$1 } from "node:timers/promises";
8
+ import { setImmediate } from "node:timers/promises";
9
9
  import fs, { existsSync, readFileSync } from "node:fs";
10
10
  import { TextDecoder as TextDecoder$1, parseArgs } from "node:util";
11
11
  import fs$1, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
@@ -15,14 +15,14 @@ import { execFile, spawn, spawnSync } from "node:child_process";
15
15
  import readline from "node:readline";
16
16
  import { createInterface } from "node:readline/promises";
17
17
  // package.json
18
- var version = "0.2.0";
18
+ var version = "0.3.0";
19
19
  // ../shared/src/api-version.ts
20
20
  /**
21
21
  * `<major>.<minor>` of the HTTP API. Minor versions only add things, with the exceptions in
22
22
  * docs/usage/http-api.md#versioning. Within a major version the enums of the answers never grow
23
23
  * (`openapi/freeze.test.ts`).
24
24
  */
25
- const API_VERSION = "1.33";
25
+ const API_VERSION = "1.34";
26
26
  /** Path prefix of every API route. */
27
27
  const API_PREFIX = "/api/v1";
28
28
  /**
@@ -832,11 +832,6 @@ const CONFIG_LIMITS = {
832
832
  const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
833
833
  /** A host name without port or scheme, or `*` (`http.allowedHosts`). */
834
834
  const HOST_NAME_PATTERN = /^(\*|[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?)$/;
835
- /** Whether `text` is a usable label: not empty after trimming, at most `max` characters trimmed. */
836
- const isTrimmedLabel = (text, max) => {
837
- const trimmed = text.trim();
838
- return trimmed !== "" && trimmed.length <= max;
839
- };
840
835
  // ../shared/src/rules/vocabulary.ts
841
836
  /** `log.level`, from the least to the most detail. */
842
837
  const LOG_LEVELS = [
@@ -922,6 +917,12 @@ const ERROR_STATUS = {
922
917
  SERVICE_UNAVAILABLE: 503,
923
918
  INTERNAL: 500
924
919
  };
920
+ // ../shared/src/rules/labels.ts
921
+ /** Whether `text` is a usable label: not empty after trimming, at most `max` characters trimmed. */
922
+ const isTrimmedLabel = (text, max) => {
923
+ const trimmed = text.trim();
924
+ return trimmed !== "" && trimmed.length <= max;
925
+ };
925
926
  API_LIMITS.wait.seen, `${API_LIMITS.wait.seen}`;
926
927
  const MarkerRequestSchema = /* @__PURE__ */ strictObject({ label: /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((label) => isTrimmedLabel(label, API_LIMITS.markerLength)), /* @__PURE__ */ description(`Marker text. Trimmed, must not be empty, at most ${API_LIMITS.markerLength} characters.`), /* @__PURE__ */ examples(["step 3"])) });
927
928
  // ../shared/src/input.ts
@@ -934,17 +935,20 @@ const capture = /* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ st
934
935
  timeoutMs: ms(0, CAPTURE.timeoutMs.max, `Longest capture, counted from the input; speech that goes on until then is \`timeout\`. ${CAPTURE.timeoutMs.default} if omitted.`),
935
936
  settleMs: ms(0, CAPTURE.settleMs.max, "Before the input, wait until nothing was spoken for this long (at most `timeoutMs`), so speech still trailing from an earlier step is not captured. The input is sent after `timeoutMs` even if the speech did not pause. 0 (no wait) if omitted.")
936
937
  }), /* @__PURE__ */ description("Records the speech the input causes and answers with it (`InputCapture` instead of `InputResult`). Times are in milliseconds and measured on the bridge, from when it received the speech. Added in API 1.19.")));
938
+ const mark = /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ boolean()), /* @__PURE__ */ description("Put a marker into the speech log right before the input is sent (`keys: Tab`, `click: left 640,12`), `true` if omitted (docs/usage/native-input.md#markers-in-the-speech-log). Added in API 1.34."));
937
939
  CAPTURE.entries, `${CAPTURE.entries}`;
938
940
  const ClickRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
939
941
  x: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen x in physical pixels."), /* @__PURE__ */ examples([640])),
940
942
  y: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen y in physical pixels."), /* @__PURE__ */ examples([12])),
941
943
  button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(MOUSE_BUTTONS)), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
944
+ mark,
942
945
  capture
943
946
  }), /* @__PURE__ */ description("`POST /input/click`: a native mouse click at a screen point, to give a window the focus. Added in API 1.14."));
944
947
  const KeysRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
945
948
  keys: /* @__PURE__ */ pipe(/* @__PURE__ */ union([/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty()), /* @__PURE__ */ pipe(/* @__PURE__ */ array(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty())), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(maxKeys$1))]), /* @__PURE__ */ description(`One chord (\`Insert+T\`) or a sequence of chords (\`["h", "h", "Insert+Down"]\`). Chords join modifiers (\`Control\`, \`Shift\`, \`Alt\`, \`Win\`, \`Insert\`, \`CapsLock\`) and one key with \`+\`. Names are case-insensitive (docs/usage/native-input.md#key-names); the numpad keys (\`numpad7\`, \`numpadEnter\`, …) since API 1.30. At most ${maxKeys$1} chords.`), /* @__PURE__ */ examples(["Insert+T"])),
946
949
  delayMs: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(0), /* @__PURE__ */ maxValue(delayMs$1.max))), /* @__PURE__ */ description(`Pause between the chords of a sequence in milliseconds, ${delayMs$1.default} if omitted.`)),
947
950
  expectedTarget: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(FOCUS_TARGETS)), /* @__PURE__ */ description("Only send the keys while a window of this browser is in front: `mcp` (Playwright MCP) or `playwright` (the Playwright server). Checked before every chord; otherwise, and where the bridge cannot tell, `409 WRONG_WINDOW` and no further chord is sent (docs/usage/native-input.md#requiring-a-target-window). Added in API 1.32.")),
951
+ mark,
948
952
  capture
949
953
  }), /* @__PURE__ */ description("`POST /input/keys`: send key presses to the focused window. Added in API 1.14."));
950
954
  const FocusRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
@@ -957,6 +961,33 @@ const FocusRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
957
961
  * chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
958
962
  * so both use this one copy. Like `text-match.ts`, it belongs to the contract, not to either side.
959
963
  */
964
+ const DIGITS = [
965
+ "0",
966
+ "1",
967
+ "2",
968
+ "3",
969
+ "4",
970
+ "5",
971
+ "6",
972
+ "7",
973
+ "8",
974
+ "9"
975
+ ];
976
+ const FUNCTION_KEYS = [
977
+ "f1",
978
+ "f2",
979
+ "f3",
980
+ "f4",
981
+ "f5",
982
+ "f6",
983
+ "f7",
984
+ "f8",
985
+ "f9",
986
+ "f10",
987
+ "f11",
988
+ "f12"
989
+ ];
990
+ const LETTERS = "abcdefghijklmnopqrstuvwxyz".split("");
960
991
  /** Keys that can be held down while another key is pressed. `Insert` and `CapsLock` are the screen reader keys. */
961
992
  const MODIFIER_KEYS = [
962
993
  "control",
@@ -971,7 +1002,7 @@ const MODIFIER_KEYS = [
971
1002
  * reading commands. With NumLock off they are those commands, with NumLock on they type.
972
1003
  */
973
1004
  const NUMPAD_KEYS = [
974
- ...Array.from({ length: 10 }, (_, digit) => `numpad${digit}`),
1005
+ ...DIGITS.map((digit) => `numpad${digit}`),
975
1006
  "numpadplus",
976
1007
  "numpadminus",
977
1008
  "numpadmultiply",
@@ -995,7 +1026,7 @@ const NAMED_KEYS = [
995
1026
  "end",
996
1027
  "pageup",
997
1028
  "pagedown",
998
- ...Array.from({ length: 12 }, (_, index) => `f${index + 1}`),
1029
+ ...FUNCTION_KEYS,
999
1030
  ...NUMPAD_KEYS
1000
1031
  ];
1001
1032
  /** Aliases accepted in a chord, by their lower-case spelling. */
@@ -1014,8 +1045,10 @@ const KEY_ALIASES = {
1014
1045
  const KEYS = /* @__PURE__ */ new Set([
1015
1046
  ...MODIFIER_KEYS,
1016
1047
  ...NAMED_KEYS,
1017
- ..."abcdefghijklmnopqrstuvwxyz0123456789"
1048
+ ...LETTERS,
1049
+ ...DIGITS
1018
1050
  ]);
1051
+ const isKeyName = (name) => KEYS.has(name);
1019
1052
  const MODIFIER_SET = new Set(MODIFIER_KEYS);
1020
1053
  /**
1021
1054
  * Parses `Insert+T` or `Control+Shift+Home`: modifiers and one last key, joined with `+`, names
@@ -1027,7 +1060,7 @@ function parseKeyChord$1(chord) {
1027
1060
  for (const part of chord.split("+")) {
1028
1061
  const lower = part.trim().toLowerCase();
1029
1062
  const name = KEY_ALIASES[lower] ?? lower;
1030
- if (!KEYS.has(name)) return {
1063
+ if (!isKeyName(name)) return {
1031
1064
  ok: false,
1032
1065
  message: `unknown key "${part.trim()}" in "${chord}"`
1033
1066
  };
@@ -1051,6 +1084,14 @@ function parseKeyChord$1(chord) {
1051
1084
  }
1052
1085
  };
1053
1086
  }
1087
+ // ../shared/src/rules/run-seq.ts
1088
+ /**
1089
+ * The first `seq` of a bridge run: its start time (`bridge.startedAt`) in milliseconds, so `seq`
1090
+ * keeps rising across restarts and a client can tell a position of an earlier run
1091
+ * (docs/implementation/decisions.md#seq-keeps-rising-across-restarts). The bridge numbers by it,
1092
+ * the client reads by it.
1093
+ */
1094
+ const firstSeqOfRun = (startedAtMs) => startedAtMs;
1054
1095
  // ../shared/src/rules/service-paths.ts
1055
1096
  /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
1056
1097
  const PLAYWRIGHT_PATH = "/playwright";
@@ -1059,8 +1100,8 @@ const PLAYWRIGHT_MCP_PATH = "/playwright-mcp";
1059
1100
  // ../shared/src/rules/text-match.ts
1060
1101
  /**
1061
1102
  * The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
1062
- * `GET /speech/wait`, the client in its own waits, so both must use this one copy. It is the only
1063
- * behaviour in this package: it belongs to the contract, not to either side.
1103
+ * `GET /speech/wait`, the client in its own waits, so both must use this one copy: it belongs to
1104
+ * the contract, not to either side.
1064
1105
  */
1065
1106
  /** Lower case, whitespace runs collapsed to one space, trimmed. */
1066
1107
  function normalizeText(text) {
@@ -1110,6 +1151,20 @@ const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
1110
1151
  * one client ends or replaces another one's session. Optional. API 1.10.
1111
1152
  */
1112
1153
  const CLIENT_HEADER = "x-sr-speech-client";
1154
+ // ../shared/src/ui-host.ts
1155
+ /** The environment variable the UI's BFF reads the bridge's address from. */
1156
+ const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
1157
+ /**
1158
+ * The header that tells the UI its page is opened from the bridge's own machine, where the screen
1159
+ * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
1160
+ * The bridge sets (`1`) or removes it on every request, so a client can't send it.
1161
+ */
1162
+ const LOCAL_HEADER = "x-sr-bridge-local";
1163
+ /**
1164
+ * Where the UI's server code finds the bridge log: a `Symbol.for` key on `globalThis`. Its lines
1165
+ * get the `[web-ui]` prefix, go to the log file and never block on the console.
1166
+ */
1167
+ const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
1113
1168
  // ../shared/src/validate.ts
1114
1169
  /**
1115
1170
  * Checks `value` against `schema`. Unknown keys of an answer don't fail it and are left out of the
@@ -1247,21 +1302,74 @@ var AppError = class extends Error {
1247
1302
  function invalidField(field, message) {
1248
1303
  return new AppError("INVALID_REQUEST", `${field}: ${message}`, { field });
1249
1304
  }
1250
- /**
1251
- * A listener can't use its port: something else listens on it (`EADDRINUSE`), or the system
1252
- * doesn't allow it (`EACCES`, for example a port in a Windows excluded port range). Startup may
1253
- * ask for another TCP port then (docs/implementation/tcp-capture.md#listening-and-connections).
1254
- */
1255
- var PortUnavailableError = class extends Error {
1256
- port;
1257
- reason;
1258
- name = "PortUnavailableError";
1259
- constructor(message, port, reason) {
1305
+ // src/adapters/in/http/response.ts
1306
+ function sendJson(res, status, body) {
1307
+ const data = JSON.stringify(body);
1308
+ res.writeHead(status, {
1309
+ "content-type": "application/json; charset=utf-8",
1310
+ "content-length": Buffer.byteLength(data)
1311
+ });
1312
+ res.end(data);
1313
+ }
1314
+ function sendNoContent(res) {
1315
+ res.writeHead(204).end();
1316
+ }
1317
+ // src/adapters/in/http/errors.ts
1318
+ /** A request refused for where it comes from: `FORBIDDEN`. */
1319
+ var AccessDeniedError = class extends Error {
1320
+ details;
1321
+ name = "AccessDeniedError";
1322
+ code = "FORBIDDEN";
1323
+ constructor(message, details) {
1260
1324
  super(message);
1261
- this.port = port;
1262
- this.reason = reason;
1325
+ this.details = details;
1263
1326
  }
1264
1327
  };
1328
+ /**
1329
+ * The error body every endpoint uses (docs/usage/http-api.md#errors) and its status. An `AppError`
1330
+ * or `AccessDeniedError` keeps its code. Anything else is `INTERNAL`, with the details in the bridge log only.
1331
+ */
1332
+ function errorResponse(error, logger) {
1333
+ let body;
1334
+ if (error instanceof AppError || error instanceof AccessDeniedError) {
1335
+ body = { error: {
1336
+ code: error.code,
1337
+ message: error.message
1338
+ } };
1339
+ if (error.details !== void 0) body.error.details = error.details;
1340
+ } else {
1341
+ logger.error(`internal error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1342
+ body = { error: {
1343
+ code: "INTERNAL",
1344
+ message: "Internal error, see the bridge log"
1345
+ } };
1346
+ }
1347
+ return {
1348
+ status: ERROR_STATUS[body.error.code],
1349
+ body
1350
+ };
1351
+ }
1352
+ /** Sends the error body every endpoint uses (docs/usage/http-api.md#errors). */
1353
+ function sendError(res, error, logger) {
1354
+ const { status, body } = errorResponse(error, logger);
1355
+ if (res.headersSent) {
1356
+ res.destroy();
1357
+ return;
1358
+ }
1359
+ sendJson(res, status, body);
1360
+ }
1361
+ /**
1362
+ * The same answer on the raw socket of a WebSocket upgrade, which has no `ServerResponse`, then
1363
+ * closes it.
1364
+ */
1365
+ function sendSocketError(socket, error, logger) {
1366
+ const { status, body } = errorResponse(error, logger);
1367
+ const data = JSON.stringify(body);
1368
+ socket.end(`HTTP/1.1 ${status} ${http.STATUS_CODES[status] ?? "Error"}\r\ncontent-type: application/json; charset=utf-8\r
1369
+ content-length: ${Buffer.byteLength(data)}\r\nconnection: close\r
1370
+ \r
1371
+ ` + data);
1372
+ }
1265
1373
  // src/adapters/in/http/access.ts
1266
1374
  /** Methods that don't change anything. Other methods with a foreign `Origin` are refused. */
1267
1375
  const SAFE_METHODS = /* @__PURE__ */ new Set([
@@ -1269,20 +1377,23 @@ const SAFE_METHODS = /* @__PURE__ */ new Set([
1269
1377
  "HEAD",
1270
1378
  "OPTIONS"
1271
1379
  ]);
1380
+ /** `Sec-Fetch-Site` values of a request the user made on the bridge's own page or address bar. */
1381
+ const OWN_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
1272
1382
  /**
1273
- * Throws `FORBIDDEN` if the request comes through a foreign host name or from a foreign page.
1274
- * `strictOrigin` refuses a foreign `Origin` for every method: for the proxied services, where a
1275
- * page could open a WebSocket or read an event stream (docs/usage/security.md#host-and-origin).
1383
+ * Throws an `AccessDeniedError` if the request comes through a foreign host name or from a foreign page
1384
+ * (docs/usage/security.md#host-and-origin).
1276
1385
  */
1277
- function checkAccess(req, rules, { strictOrigin = false } = {}) {
1386
+ function checkAccess(req, rules, { strictOrigin = false, crossSite = "allow" } = {}) {
1278
1387
  const host = (req.headers.host ?? "").toLowerCase();
1279
1388
  const hostname = hostnameOf(host);
1280
- if (hostname === void 0) throw new AppError("FORBIDDEN", "The request has no valid Host header");
1281
- if (!hostAllowed(hostname, rules)) throw new AppError("FORBIDDEN", `Host "${hostname}" is not allowed. Use the bridge's IP address, or add the name to http.allowedHosts (--allowed-hosts)`, { host: hostname });
1389
+ if (hostname === void 0) throw new AccessDeniedError("The request has no valid Host header");
1390
+ if (!hostAllowed(hostname, rules)) throw new AccessDeniedError(`Host "${hostname}" is not allowed. Use the bridge's IP address, or add the name to http.allowedHosts (--allowed-hosts)`, { host: hostname });
1391
+ const fetchSite = req.headers["sec-fetch-site"];
1392
+ if (crossSite === "refuse" && fetchSite !== void 0 && !OWN_FETCH_SITES.has(fetchSite)) throw new AccessDeniedError("Requests from another site are not allowed", { fetchSite });
1282
1393
  const origin = req.headers.origin;
1283
1394
  if (origin === void 0) return;
1284
1395
  if (!strictOrigin && SAFE_METHODS.has(req.method ?? "GET")) return;
1285
- if (origin.toLowerCase() !== `http://${host}`) throw new AppError("FORBIDDEN", `Requests from origin "${origin}" are not allowed`, { origin });
1396
+ if (origin.toLowerCase() !== `http://${host}`) throw new AccessDeniedError(`Requests from origin "${origin}" are not allowed`, { origin });
1286
1397
  }
1287
1398
  /** The host name in a `Host` header (`name:port`, `[::1]:port`), `undefined` if it isn't one. */
1288
1399
  function hostnameOf(host) {
@@ -1306,7 +1417,23 @@ function hostAllowed(hostname, { allowedHosts, ownHostnames }) {
1306
1417
  function ownNames(hostnames) {
1307
1418
  return hostnames.flatMap((name) => [name, name.split(".")[0]]).filter((name) => name !== "");
1308
1419
  }
1309
- // src/adapters/shared/net/listen.ts
1420
+ // src/application/ports/out/listener.ts
1421
+ /**
1422
+ * A listener can't use its port: something else listens on it (`EADDRINUSE`), or the system
1423
+ * doesn't allow it (`EACCES`, for example a port in a Windows excluded port range). Startup may
1424
+ * ask for another TCP port then (docs/implementation/tcp-capture.md#listening-and-connections).
1425
+ */
1426
+ var PortUnavailableError = class extends Error {
1427
+ port;
1428
+ reason;
1429
+ name = "PortUnavailableError";
1430
+ constructor(message, port, reason) {
1431
+ super(message);
1432
+ this.port = port;
1433
+ this.reason = reason;
1434
+ }
1435
+ };
1436
+ // src/adapters/common/net/listen.ts
1310
1437
  /**
1311
1438
  * Thrown when a listener can't start for another reason than its port being unavailable (for
1312
1439
  * example `EADDRNOTAVAIL`: an address this machine doesn't have). A port that is in use or not
@@ -1353,7 +1480,7 @@ async function listen(server, host, port) {
1353
1480
  });
1354
1481
  return server.address().port;
1355
1482
  }
1356
- // src/adapters/shared/net/reachable-urls.ts
1483
+ // src/adapters/common/net/reachable-urls.ts
1357
1484
  /** True for a host that means "every interface" (`0.0.0.0`, `::`). */
1358
1485
  const isWildcard = (host) => [
1359
1486
  "0.0.0.0",
@@ -1404,121 +1531,13 @@ function describeListener(scheme, host, port, path = "", interfaces = os.network
1404
1531
  const urls = reachableUrls(scheme, host, port, interfaces).map((url) => `${url}${path}`).join(", ");
1405
1532
  return isWildcard(host) ? `${hostPort(host, port)}, reachable at ${urls}` : urls;
1406
1533
  }
1407
- // src/adapters/in/http/response.ts
1408
- function sendJson(res, status, body) {
1409
- const data = JSON.stringify(body);
1410
- res.writeHead(status, {
1411
- "content-type": "application/json; charset=utf-8",
1412
- "content-length": Buffer.byteLength(data)
1413
- });
1414
- res.end(data);
1415
- }
1416
- function sendNoContent(res) {
1417
- res.writeHead(204).end();
1418
- }
1419
- // src/adapters/in/http/errors.ts
1420
- /**
1421
- * The error body every endpoint uses (docs/usage/http-api.md#errors) and its status. An `AppError`
1422
- * keeps its code. Anything else is `INTERNAL`, with the details in the bridge log only.
1423
- */
1424
- function errorResponse(error, logger) {
1425
- let body;
1426
- if (error instanceof AppError) {
1427
- body = { error: {
1428
- code: error.code,
1429
- message: error.message
1430
- } };
1431
- if (error.details !== void 0) body.error.details = error.details;
1432
- } else {
1433
- logger.error(`internal error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1434
- body = { error: {
1435
- code: "INTERNAL",
1436
- message: "Internal error, see the bridge log"
1437
- } };
1438
- }
1439
- return {
1440
- status: ERROR_STATUS[body.error.code],
1441
- body
1442
- };
1443
- }
1444
- /** Sends the error body every endpoint uses (docs/usage/http-api.md#errors). */
1445
- function sendError(res, error, logger) {
1446
- const { status, body } = errorResponse(error, logger);
1447
- if (res.headersSent) {
1448
- res.destroy();
1449
- return;
1450
- }
1451
- sendJson(res, status, body);
1452
- }
1453
- /**
1454
- * The same answer on the raw socket of a WebSocket upgrade, which has no `ServerResponse`, then
1455
- * closes it.
1456
- */
1457
- function sendSocketError(socket, error, logger) {
1458
- const { status, body } = errorResponse(error, logger);
1459
- const data = JSON.stringify(body);
1460
- socket.end(`HTTP/1.1 ${status} ${http.STATUS_CODES[status] ?? "Error"}\r\ncontent-type: application/json; charset=utf-8\r
1461
- content-length: ${Buffer.byteLength(data)}\r\nconnection: close\r
1462
- \r
1463
- ` + data);
1464
- }
1465
- // src/domain/child-service.ts
1466
- const SERVICE_NAMES = ["playwright", "mcp"];
1467
- /** How the services are named in log lines and errors. */
1468
- const SERVICE_TITLES = {
1469
- playwright: "Playwright server",
1470
- mcp: "Playwright MCP"
1471
- };
1534
+ // src/adapters/common/net/child-host.ts
1472
1535
  /**
1473
1536
  * Where the child services listen: loopback only. Clients reach them through the bridge's HTTP
1474
1537
  * port, which checks Host and Origin for them like for the API
1475
1538
  * (docs/implementation/decisions.md#the-bridge-is-the-single-way-in).
1476
1539
  */
1477
1540
  const CHILD_HOST = "127.0.0.1";
1478
- /** A service's settings from the config: the Playwright server in the configured version, MCP in the bundled one. */
1479
- function serviceSettings(name, config) {
1480
- if (name === "playwright") {
1481
- const { port, version } = config.playwright;
1482
- return {
1483
- host: CHILD_HOST,
1484
- port,
1485
- version
1486
- };
1487
- }
1488
- return {
1489
- host: CHILD_HOST,
1490
- port: config.mcp.port,
1491
- version: null
1492
- };
1493
- }
1494
- function reachability(name, status, enabled) {
1495
- if (status.state === "running") return { port: status.port };
1496
- const title = SERVICE_TITLES[name];
1497
- if (!enabled) return { unavailable: `${title} is disabled` };
1498
- return { unavailable: `${title} is not running (state: ${status.state})` };
1499
- }
1500
- const RESTART_POLICY = {
1501
- baseDelayMs: 1e3,
1502
- maxDelayMs: 3e4,
1503
- stableMs: 6e4,
1504
- maxCrashesInRow: 5
1505
- };
1506
- /**
1507
- * What to do after a crash. `crashesInRow` counts the crashes before this one, `ranForMs` is how
1508
- * long the service ran before it crashed.
1509
- */
1510
- function nextAfterCrash(crashesInRow, ranForMs, policy = RESTART_POLICY) {
1511
- const streak = (ranForMs >= policy.stableMs ? 0 : crashesInRow) + 1;
1512
- if (streak >= policy.maxCrashesInRow) return {
1513
- action: "fail",
1514
- crashesInRow: streak
1515
- };
1516
- return {
1517
- action: "restart",
1518
- crashesInRow: streak,
1519
- delayMs: Math.min(policy.baseDelayMs * 2 ** (streak - 1), policy.maxDelayMs)
1520
- };
1521
- }
1522
1541
  // src/adapters/in/http/proxy/service-proxy.ts
1523
1542
  /** Headers that belong to one connection and are not passed on (RFC 9110, 7.6.1). */
1524
1543
  const HOP_BY_HOP = /* @__PURE__ */ new Set([
@@ -1741,6 +1760,7 @@ function hasType(value, schema) {
1741
1760
  switch (schema.type) {
1742
1761
  case "string": return typeof value === "string";
1743
1762
  case "number": return Number.isFinite(value);
1763
+ case "boolean": return typeof value === "boolean";
1744
1764
  case "picklist": return schema.options.includes(value);
1745
1765
  case "array": return Array.isArray(value) && value.every((item) => hasType(item, schema.item));
1746
1766
  case "union": return schema.options.some((option) => hasType(value, option));
@@ -1958,6 +1978,38 @@ function toWaitResultDto(result) {
1958
1978
  };
1959
1979
  }
1960
1980
  // src/adapters/in/http/dto/input.ts
1981
+ function toFocusRequest({ target, title }) {
1982
+ return {
1983
+ target,
1984
+ title
1985
+ };
1986
+ }
1987
+ function toClickRequest({ x, y, button, mark }) {
1988
+ return {
1989
+ x,
1990
+ y,
1991
+ button,
1992
+ mark
1993
+ };
1994
+ }
1995
+ function toPressKeysRequest(dto) {
1996
+ const { keys, delayMs, expectedTarget, mark } = dto;
1997
+ return {
1998
+ keys,
1999
+ delayMs,
2000
+ expectedTarget,
2001
+ mark
2002
+ };
2003
+ }
2004
+ function toCaptureOptions(dto) {
2005
+ const { quietForMs, firstWithinMs, timeoutMs, settleMs } = dto;
2006
+ return {
2007
+ quietForMs,
2008
+ firstWithinMs,
2009
+ timeoutMs,
2010
+ settleMs
2011
+ };
2012
+ }
1961
2013
  function toInputResultDto({ window }) {
1962
2014
  if (window === void 0) return {};
1963
2015
  return { window: window && {
@@ -2031,7 +2083,7 @@ function answer(exchange, capture, send, record) {
2031
2083
  function inputRoutes(router, deps) {
2032
2084
  const { input, captures, focus, logger } = deps;
2033
2085
  router.add("POST", "/input/focus", { body: FocusRequestSchema }, async ({ req, res, body }) => {
2034
- const request = typedBody(FocusRequestSchema, body);
2086
+ const request = toFocusRequest(typedBody(FocusRequestSchema, body));
2035
2087
  await whileConnected({
2036
2088
  req,
2037
2089
  res,
@@ -2041,23 +2093,25 @@ function inputRoutes(router, deps) {
2041
2093
  signal
2042
2094
  }), (focused) => sendJson(res, 200, toFocusedWindowDto(focused)));
2043
2095
  }).add("POST", "/input/click", { body: ClickRequestSchema }, async ({ req, res, body }) => {
2044
- const { capture, ...request } = typedBody(ClickRequestSchema, body);
2096
+ const dto = typedBody(ClickRequestSchema, body);
2097
+ const request = toClickRequest(dto);
2045
2098
  await answer({
2046
2099
  req,
2047
2100
  res,
2048
2101
  logger
2049
- }, capture, (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
2102
+ }, dto.capture && toCaptureOptions(dto.capture), (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
2050
2103
  ...request,
2051
2104
  capture,
2052
2105
  signal
2053
2106
  }));
2054
2107
  }).add("POST", "/input/keys", { body: KeysRequestSchema }, async ({ req, res, body }) => {
2055
- const { capture, ...request } = typedBody(KeysRequestSchema, body);
2108
+ const dto = typedBody(KeysRequestSchema, body);
2109
+ const request = toPressKeysRequest(dto);
2056
2110
  await answer({
2057
2111
  req,
2058
2112
  res,
2059
2113
  logger
2060
- }, capture, (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
2114
+ }, dto.capture && toCaptureOptions(dto.capture), (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
2061
2115
  ...request,
2062
2116
  capture,
2063
2117
  signal
@@ -2121,6 +2175,14 @@ function sessionRoutes(router, { sessions }) {
2121
2175
  sendJson(res, 200, toSessionListDto(sessions.list()));
2122
2176
  });
2123
2177
  }
2178
+ // src/adapters/in/http/dto/stream.ts
2179
+ function toPositionEventDto() {
2180
+ return {};
2181
+ }
2182
+ /** `sessionId` is left out when everything was cleared. */
2183
+ function toClearEventDto(sessionId) {
2184
+ return sessionId === void 0 ? {} : { sessionId };
2185
+ }
2124
2186
  // src/adapters/in/http/sse/sse-frames.ts
2125
2187
  /**
2126
2188
  * Frames already built, by the entry or session they show. Every open stream gets the same
@@ -2143,9 +2205,9 @@ function sseFrame(event) {
2143
2205
  const data = JSON.stringify(toSpeechEntryDto(event.entry));
2144
2206
  return `id: ${event.entry.seq}\nevent: entry\ndata: ${data}\n\n`;
2145
2207
  });
2146
- case "position": return `id: ${event.seq}\nevent: position\ndata: {}\n\n`;
2208
+ case "position": return `id: ${event.seq}\nevent: position\ndata: ${JSON.stringify(toPositionEventDto())}\n\n`;
2147
2209
  case "session": return cached(event.session, () => `event: session\ndata: ${JSON.stringify(toSessionDto(event.session))}\n\n`);
2148
- case "clear": return event.sessionId === void 0 ? "event: clear\ndata: {}\n\n" : `event: clear\ndata: ${JSON.stringify({ sessionId: event.sessionId })}\n\n`;
2210
+ case "clear": return `event: clear\ndata: ${JSON.stringify(toClearEventDto(event.sessionId))}\n\n`;
2149
2211
  default: return `event: ${event.type}\ndata: {}\n\n`;
2150
2212
  }
2151
2213
  }
@@ -2180,11 +2242,9 @@ function speechRoutes(router, deps) {
2180
2242
  const label = stringParam(url, "label");
2181
2243
  if (label === void 0) throw invalidField("label", "is required");
2182
2244
  sendJson(res, 200, toLatestMarkerDto(speech.latestMarker(label, sessionParam(url))));
2183
- }).add("GET", "/speech/wait", { query: WAIT_QUERY }, async ({ res, url }) => {
2184
- const controller = new AbortController();
2185
- res.on("close", () => {
2186
- if (!res.writableEnded) controller.abort();
2187
- });
2245
+ }).add("GET", "/speech/wait", { query: WAIT_QUERY }, async ({ req, res, url }) => {
2246
+ const signal = hangUpSignal(req, res);
2247
+ signal.addEventListener("abort", () => logger.debug("speech wait: the client hung up before the answer"), { once: true });
2188
2248
  let result;
2189
2249
  try {
2190
2250
  result = await waits.wait({
@@ -2194,10 +2254,10 @@ function speechRoutes(router, deps) {
2194
2254
  since: intParam(url, "since"),
2195
2255
  timeoutMs: intParam(url, "timeoutMs"),
2196
2256
  session: sessionParam(url),
2197
- signal: controller.signal
2257
+ signal
2198
2258
  });
2199
2259
  } catch (error) {
2200
- if (controller.signal.aborted) return;
2260
+ if (signal.aborted) return;
2201
2261
  throw error;
2202
2262
  }
2203
2263
  sendJson(res, 200, toWaitResultDto(result));
@@ -2431,7 +2491,11 @@ var HttpServer = class {
2431
2491
  path = url.pathname;
2432
2492
  if (isApiPath(url.pathname)) res.setHeader(API_VERSION_HEADER, API_VERSION);
2433
2493
  const route = this.proxy.match(url.pathname);
2434
- this.checkAccess(req, route !== void 0);
2494
+ const api = route !== void 0 || isApiPath(url.pathname);
2495
+ this.checkAccess(req, {
2496
+ strictOrigin: route !== void 0,
2497
+ crossSite: api ? "refuse" : "allow"
2498
+ });
2435
2499
  if (route) this.proxy.forward(route, req, res, url);
2436
2500
  else if (this.deps.ui && !isApiPath(url.pathname)) await this.deps.ui(req, res);
2437
2501
  else await this.router.find(method, url.pathname)({
@@ -2454,7 +2518,10 @@ var HttpServer = class {
2454
2518
  const url = parseUrl(req.url);
2455
2519
  const route = this.proxy.match(url.pathname);
2456
2520
  if (route?.scheme !== "ws") throw new AppError("NOT_FOUND", `No WebSocket endpoint at ${url.pathname}`);
2457
- this.checkAccess(req, true);
2521
+ this.checkAccess(req, {
2522
+ strictOrigin: true,
2523
+ crossSite: "refuse"
2524
+ });
2458
2525
  this.deps.logger.debug(`upgrade ${url.pathname} → ${route.name}`);
2459
2526
  this.proxy.upgrade(route, req, socket, head, url);
2460
2527
  } catch (error) {
@@ -2463,13 +2530,14 @@ var HttpServer = class {
2463
2530
  }
2464
2531
  /**
2465
2532
  * Host and origin rules (docs/usage/security.md#host-and-origin). The services refuse a foreign
2466
- * origin for every method: a page could open a WebSocket or read an event stream.
2533
+ * origin for every method: a page could open a WebSocket or read an event stream. The API and
2534
+ * the services refuse what a browser sends for another site's page; the web UI doesn't.
2467
2535
  */
2468
- checkAccess(req, proxied) {
2536
+ checkAccess(req, options) {
2469
2537
  checkAccess(req, {
2470
2538
  allowedHosts: this.allowedHosts,
2471
2539
  ownHostnames: this.deps.hostnames ?? []
2472
- }, { strictOrigin: proxied });
2540
+ }, options);
2473
2541
  }
2474
2542
  };
2475
2543
  /** Whether `pathname` is the API's (`/api/v1`, `/api/v1/…`). An unknown one is an API 404. */
@@ -2485,22 +2553,13 @@ function parseUrl(target) {
2485
2553
  }
2486
2554
  }
2487
2555
  // src/adapters/in/http/ui-mount.ts
2488
- /** The environment variable the UI's BFF reads the bridge's address from. */
2489
- const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
2490
2556
  /** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
2491
2557
  const PROTOCOL_HEADER = "x-sr-bridge-protocol";
2492
2558
  /**
2493
- * The header that tells the UI its page is opened from the bridge's own machine, where the screen
2494
- * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
2495
- * Set (`1`) or removed on every request, so a client can't send it.
2496
- */
2497
- const LOCAL_HEADER = "x-sr-bridge-local";
2498
- /**
2499
- * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
2500
- * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
2501
- * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
2559
+ * The variables {@link UiMount.mount} sets for the UI. Child services don't inherit them
2560
+ * (`adapters/out/process`).
2502
2561
  */
2503
- const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
2562
+ const UI_ENV_NAMES = [BRIDGE_API_URL_ENV, "PROTOCOL_HEADER"];
2504
2563
  /**
2505
2564
  * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
2506
2565
  * none: the bridge runs from source, or the package was built without the UI.
@@ -2705,7 +2764,8 @@ var TcpListener = class {
2705
2764
  line: (text) => this.recordSpeech.record({
2706
2765
  text,
2707
2766
  voice,
2708
- connectionId: id
2767
+ connectionId: id,
2768
+ source: "tcp"
2709
2769
  }),
2710
2770
  lineCut: (max) => this.logger.warn(`connection ${id}: line longer than ${max} bytes, cut it`)
2711
2771
  });
@@ -3148,7 +3208,7 @@ function pipeLines(child, output) {
3148
3208
  crlfDelay: Infinity
3149
3209
  }).on("line", (line) => output.warn(line));
3150
3210
  }
3151
- // src/application/shared/abort.ts
3211
+ // src/application/support/abort.ts
3152
3212
  /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
3153
3213
  function abortReason(signal) {
3154
3214
  const reason = signal.reason;
@@ -3189,20 +3249,24 @@ function linkSignals(...signals) {
3189
3249
  // src/application/services/bridge-lifecycle-service.ts
3190
3250
  /**
3191
3251
  * The bridge's state from `starting` over `ready` to `stopping`, and the order of startup and
3192
- * shutdown.
3252
+ * shutdown. `GET /status` reads the state through {@link state}.
3193
3253
  */
3194
3254
  var BridgeLifecycleService = class {
3195
3255
  deps;
3196
3256
  stopping;
3257
+ #state = "starting";
3197
3258
  constructor(deps) {
3198
3259
  this.deps = deps;
3199
3260
  }
3261
+ state() {
3262
+ return this.#state;
3263
+ }
3200
3264
  async start() {
3201
3265
  const ports = await this.listen();
3202
3266
  await this.deps.httpListening(ports.http);
3203
3267
  this.deps.services.startEnabled().then(() => {
3204
3268
  if (this.stopping !== void 0) return;
3205
- this.deps.state.setState("ready");
3269
+ this.#state = "ready";
3206
3270
  this.deps.logger.info(this.deps.readyMessage(ports));
3207
3271
  });
3208
3272
  return ports;
@@ -3226,8 +3290,8 @@ var BridgeLifecycleService = class {
3226
3290
  }
3227
3291
  }
3228
3292
  async shutdown(reason) {
3229
- const { state, shutdown, tcp, http, services, logger } = this.deps;
3230
- state.setState("stopping");
3293
+ const { shutdown, tcp, http, services, logger } = this.deps;
3294
+ this.#state = "stopping";
3231
3295
  logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
3232
3296
  shutdown.abort(shuttingDown());
3233
3297
  const errors = [];
@@ -3246,17 +3310,52 @@ var BridgeLifecycleService = class {
3246
3310
  logger.info("stopped");
3247
3311
  }
3248
3312
  };
3249
- // src/application/services/child-services-service.ts
3250
- /** Runs the Playwright server and Playwright MCP as the configuration says. */
3251
- var ChildServicesService = class {
3252
- deps;
3253
- constructor(deps) {
3254
- this.deps = deps;
3255
- }
3256
- async startEnabled() {
3257
- const config = this.deps.config();
3258
- const enabled = SERVICE_NAMES.filter((name) => config[name].enabled);
3259
- await Promise.all(enabled.map((name) => this.supervisor(name).start()));
3313
+ // src/domain/child-service.ts
3314
+ const SERVICE_NAMES = ["playwright", "mcp"];
3315
+ /** How the services are named in log lines and errors. */
3316
+ const SERVICE_TITLES = {
3317
+ playwright: "Playwright server",
3318
+ mcp: "Playwright MCP"
3319
+ };
3320
+ function reachability(name, status, enabled) {
3321
+ if (status.state === "running") return { port: status.port };
3322
+ const title = SERVICE_TITLES[name];
3323
+ if (!enabled) return { unavailable: `${title} is disabled` };
3324
+ return { unavailable: `${title} is not running (state: ${status.state})` };
3325
+ }
3326
+ const RESTART_POLICY = {
3327
+ baseDelayMs: 1e3,
3328
+ maxDelayMs: 3e4,
3329
+ stableMs: 6e4,
3330
+ maxCrashesInRow: 5
3331
+ };
3332
+ /**
3333
+ * What to do after a crash. `crashesInRow` counts the crashes before this one, `ranForMs` is how
3334
+ * long the service ran before it crashed.
3335
+ */
3336
+ function nextAfterCrash(crashesInRow, ranForMs, policy = RESTART_POLICY) {
3337
+ const streak = (ranForMs >= policy.stableMs ? 0 : crashesInRow) + 1;
3338
+ if (streak >= policy.maxCrashesInRow) return {
3339
+ action: "fail",
3340
+ crashesInRow: streak
3341
+ };
3342
+ return {
3343
+ action: "restart",
3344
+ crashesInRow: streak,
3345
+ delayMs: Math.min(policy.baseDelayMs * 2 ** (streak - 1), policy.maxDelayMs)
3346
+ };
3347
+ }
3348
+ // src/application/services/child-services-service.ts
3349
+ /** Runs the Playwright server and Playwright MCP as the configuration says. */
3350
+ var ChildServicesService = class {
3351
+ deps;
3352
+ constructor(deps) {
3353
+ this.deps = deps;
3354
+ }
3355
+ async startEnabled() {
3356
+ const config = this.deps.config();
3357
+ const enabled = SERVICE_NAMES.filter((name) => config[name].enabled);
3358
+ await Promise.all(enabled.map((name) => this.supervisor(name).start()));
3260
3359
  }
3261
3360
  async stopAll() {
3262
3361
  const errors = (await Promise.allSettled(SERVICE_NAMES.map((name) => this.supervisor(name).stop()))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
@@ -3430,9 +3529,57 @@ function withUnknownSettings(file, unknown) {
3430
3529
  }
3431
3530
  return Object.fromEntries(result);
3432
3531
  }
3433
- // src/application/services/config-service.ts
3532
+ // src/application/ports/in/load-config.ts
3533
+ /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
3534
+ var ConfigError = class extends Error {
3535
+ name = "ConfigError";
3536
+ };
3537
+ // src/application/services/config-loader.ts
3434
3538
  const show$1 = (value) => JSON.stringify(value);
3435
- const same = (a, b) => show$1(a) === show$1(b);
3539
+ /** `patch` checked, with an error that says where the bad setting came from. */
3540
+ function checked(patch, origin) {
3541
+ try {
3542
+ return validatePatch(patch);
3543
+ } catch (error) {
3544
+ throw new ConfigError(`${origin(error instanceof AppError ? error.details?.field : void 0)}: ${error.message}`, { cause: error });
3545
+ }
3546
+ }
3547
+ /**
3548
+ * The configuration of a start (docs/usage/configuration.md): defaults, then the config file, then
3549
+ * flags and environment variables. `sources` names what sets each of those (`--tcp-port`).
3550
+ * Rejects with a {@link ConfigError}.
3551
+ */
3552
+ async function loadConfig(store, overridesPatch, sources = /* @__PURE__ */ new Map()) {
3553
+ const sourceOf = (field) => sources.get(field) ?? "a flag or environment variable";
3554
+ let loaded;
3555
+ const warnings = [];
3556
+ try {
3557
+ loaded = await store.load((message) => warnings.push(message));
3558
+ } catch (error) {
3559
+ throw new ConfigError(error.message, { cause: error });
3560
+ }
3561
+ const { known, unknown, names } = splitUnknownSettings(loaded);
3562
+ const file = checked(known, () => `Invalid setting in the config file ${store.location}`);
3563
+ const overrides = checked(overridesPatch, (field) => field?.includes(".") ? `Invalid ${sourceOf(field)}` : "Invalid setting");
3564
+ const config = mergeConfig(mergeConfig(DEFAULT_CONFIG, file), overrides);
3565
+ try {
3566
+ assertDistinctPorts(config);
3567
+ } catch (error) {
3568
+ throw new ConfigError(`Invalid setting: ${error.message}`, { cause: error });
3569
+ }
3570
+ for (const name of names) warnings.push(`${name}: unknown setting in ${store.location}, ignored`);
3571
+ for (const { field, file: saved, override } of overriddenFields(file, overrides)) warnings.push(`${field}: the config file sets ${show$1(saved)}, but ${sourceOf(field)} sets ${show$1(override)}, which wins`);
3572
+ return {
3573
+ config,
3574
+ file,
3575
+ unknownSettings: unknown,
3576
+ pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)])),
3577
+ warnings
3578
+ };
3579
+ }
3580
+ // src/application/services/config-service.ts
3581
+ const show = (value) => JSON.stringify(value);
3582
+ const same = (a, b) => show(a) === show(b);
3436
3583
  /**
3437
3584
  * The configuration (`GET` / `PUT /api/v1/config`). The configuration in use never changes while
3438
3585
  * the bridge runs: an update is saved to the config file and takes effect on the next start
@@ -3478,7 +3625,7 @@ var ConfigService = class {
3478
3625
  this.active = mergeConfig(this.active, changes);
3479
3626
  for (const [field, value] of configFields(changes)) {
3480
3627
  if (same(value, before.get(field))) continue;
3481
- this.deps.logger.info(`${field}: ${show$1(before.get(field))} → ${show$1(value)}, saved to ${this.deps.store.location}`);
3628
+ this.deps.logger.info(`${field}: ${show(before.get(field))} → ${show(value)}, saved to ${this.deps.store.location}`);
3482
3629
  }
3483
3630
  return this.active;
3484
3631
  });
@@ -3517,10 +3664,78 @@ var ConfigService = class {
3517
3664
  for (const [field, value] of patched) {
3518
3665
  const source = pinned?.get(field);
3519
3666
  if (source !== void 0) logger.warn(`${field}: saved to ${store.location}, but ${source} overrides it on the next start`);
3520
- else if (!same(value, running.get(field))) logger.info(`${field}: ${show$1(running.get(field))} → ${show$1(value)} on the next start`);
3667
+ else if (!same(value, running.get(field))) logger.info(`${field}: ${show(running.get(field))} → ${show(value)} on the next start`);
3521
3668
  }
3522
3669
  }
3523
3670
  };
3671
+ // src/domain/capture-window.ts
3672
+ /** The speech an input caused, from when it was sent until it pauses, none comes or time runs out. */
3673
+ var CaptureWindow = class {
3674
+ sentAt;
3675
+ timing;
3676
+ maxEntries;
3677
+ #entries = [];
3678
+ #omitted = 0;
3679
+ /** When the newest speech was received. */
3680
+ #last;
3681
+ #end;
3682
+ /** @param maxEntries The first entries kept; later ones are only counted. */
3683
+ constructor(sentAt, timing, maxEntries) {
3684
+ this.sentAt = sentAt;
3685
+ this.timing = timing;
3686
+ this.maxEntries = maxEntries;
3687
+ this.#end = sentAt + timing.timeoutMs;
3688
+ }
3689
+ onSpeech(entry) {
3690
+ this.#last = entry.receivedAt.getTime();
3691
+ if (this.#entries.length < this.maxEntries) this.#entries.push(entry);
3692
+ else this.#omitted++;
3693
+ }
3694
+ /** When the capture ends unless more speech comes. */
3695
+ deadline() {
3696
+ const { firstWithinMs, quietForMs } = this.timing;
3697
+ const due = this.#last === void 0 ? this.sentAt + firstWithinMs : this.#last + quietForMs;
3698
+ return Math.min(due, this.#end);
3699
+ }
3700
+ /**
3701
+ * What the capture holds once its deadline has passed. The status comes from the entries' times,
3702
+ * not from the time now: timers may fire a little early.
3703
+ */
3704
+ result() {
3705
+ return {
3706
+ status: this.#last === void 0 ? "no-speech" : this.#last + this.timing.quietForMs <= this.#end ? "silent" : "timeout",
3707
+ entries: this.#entries,
3708
+ omitted: this.#omitted
3709
+ };
3710
+ }
3711
+ };
3712
+ /**
3713
+ * The wait before an input until the newest speech is `settleMs` old, at most `timeoutMs`: after
3714
+ * that the input is sent anyway, and the trailing speech shows in the capture.
3715
+ */
3716
+ var SettleWindow = class {
3717
+ start;
3718
+ timing;
3719
+ #last;
3720
+ /** @param lastSpeechAt When the newest speech so far was received, if there was any. */
3721
+ constructor(start, timing, lastSpeechAt) {
3722
+ this.start = start;
3723
+ this.timing = timing;
3724
+ this.#last = lastSpeechAt;
3725
+ }
3726
+ /** Whether the speech had already been quiet long enough at the start. */
3727
+ get settled() {
3728
+ return this.#last === void 0 || this.#last + this.timing.settleMs <= this.start;
3729
+ }
3730
+ onSpeech(at) {
3731
+ this.#last = at;
3732
+ }
3733
+ /** When the input may be sent unless more speech comes. */
3734
+ deadline() {
3735
+ if (this.#last === void 0) return this.start;
3736
+ return Math.min(this.#last + this.timing.settleMs, this.start + this.timing.timeoutMs);
3737
+ }
3738
+ };
3524
3739
  // src/application/ports/in/capture-input.ts
3525
3740
  /** Defaults and ranges of the capture options, in milliseconds. */
3526
3741
  const CAPTURE_LIMITS = API_LIMITS.capture;
@@ -3637,7 +3852,65 @@ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, l
3637
3852
  });
3638
3853
  return stop;
3639
3854
  }
3640
- // src/application/shared/int-option.ts
3855
+ /**
3856
+ * {@link followLog} until `onEvent` says `done`, the time runs out (`timeout`) or the signal
3857
+ * aborts. Nothing is listening or running any more once it has settled.
3858
+ */
3859
+ function followUntil(deps, { since, sessionId, signal, pace, timeLeft, startTimer }, onEvent) {
3860
+ if (signal.aborted) return Promise.reject(abortReason(signal));
3861
+ return new Promise((resolve, reject) => {
3862
+ let done = false;
3863
+ let timer;
3864
+ let stop;
3865
+ const finish = () => {
3866
+ done = true;
3867
+ stop?.();
3868
+ timer?.abort();
3869
+ signal.removeEventListener("abort", onAbort);
3870
+ };
3871
+ const succeed = (how) => {
3872
+ if (done) return;
3873
+ finish();
3874
+ resolve(how);
3875
+ };
3876
+ const fail = (error) => {
3877
+ if (done) return;
3878
+ finish();
3879
+ reject(error instanceof Error ? error : new Error(String(error)));
3880
+ };
3881
+ const onAbort = () => fail(abortReason(signal));
3882
+ const arm = () => {
3883
+ if (done) return;
3884
+ timer?.abort();
3885
+ const own = new AbortController();
3886
+ timer = own;
3887
+ deps.clock.sleep(Math.max(0, timeLeft()), own.signal).then(() => {
3888
+ if (timer === own) succeed("timeout");
3889
+ }, () => {});
3890
+ };
3891
+ signal.addEventListener("abort", onAbort, { once: true });
3892
+ if (startTimer === "at once") arm();
3893
+ try {
3894
+ stop = followLog(deps, {
3895
+ since,
3896
+ sessionId
3897
+ }, (event) => {
3898
+ if (done) return;
3899
+ const step = onEvent(event);
3900
+ if (step === "done") succeed("done");
3901
+ else if (step === "rearm") arm();
3902
+ }, {
3903
+ pace,
3904
+ onCaughtUp: startTimer === "caught up" ? arm : void 0,
3905
+ onError: fail
3906
+ });
3907
+ if (done) stop();
3908
+ } catch (error) {
3909
+ fail(error);
3910
+ }
3911
+ });
3912
+ }
3913
+ // src/application/support/int-option.ts
3641
3914
  /**
3642
3915
  * A numeric use-case option: `fallback` if it is missing, otherwise checked to be an integer
3643
3916
  * from `min` to `max` (`INVALID_REQUEST` for `field` if not).
@@ -3662,10 +3935,10 @@ function parseOptions(options) {
3662
3935
  settleMs: ms("settleMs", settleMs)
3663
3936
  };
3664
3937
  }
3665
- const toError = (error) => error instanceof Error ? error : new Error(String(error));
3666
3938
  /**
3667
3939
  * Native input that records the speech it causes (docs/usage/native-input.md#capturing-the-speech-an-input-causes).
3668
- * The start `seq` is read in the input queue right before the input is sent, so no other input
3940
+ * The start `seq` is read in the input queue right before the input is sent (after the input's
3941
+ * marker), so no other input
3669
3942
  * and no speech that came before it gets into the capture; silence is timed from the entries'
3670
3943
  * `receivedAt`, on the bridge's clock, not from when a client got them.
3671
3944
  */
@@ -3693,6 +3966,8 @@ var InputCaptureService = class {
3693
3966
  beforeInject: async () => {
3694
3967
  if (options.settleMs > 0) await this.settle(options, stop.signal);
3695
3968
  if (stop.signal.aborted) throw abortReason(stop.signal);
3969
+ },
3970
+ onSend: () => {
3696
3971
  startSeq = this.deps.log.headSeq;
3697
3972
  }
3698
3973
  }),
@@ -3703,36 +3978,31 @@ var InputCaptureService = class {
3703
3978
  }
3704
3979
  }
3705
3980
  /**
3706
- * Waits until the newest speech is `settleMs` old, at most `timeoutMs`: after that the input
3707
- * is sent anyway, and the trailing speech shows in the capture. Markers and clears don't shorten
3708
- * the wait: it goes by when speech was received, not by what the buffer holds.
3981
+ * Waits for the speech to settle ({@link SettleWindow}). Markers and clears don't shorten the
3982
+ * wait: it goes by when speech was received, not by what the buffer holds.
3709
3983
  */
3710
- async settle({ settleMs, timeoutMs }, signal) {
3711
- const start = this.now();
3712
- let last = this.deps.log.lastSpeechAt?.getTime();
3713
- if (last === void 0 || last + settleMs <= start) return;
3714
- await this.follow(null, signal, () => Math.min(last + settleMs, start + timeoutMs), (event) => {
3715
- if (event.type === "entry" && event.entry.kind === "speech") last = event.entry.receivedAt.getTime();
3984
+ async settle(options, signal) {
3985
+ const window = new SettleWindow(this.now(), options, this.deps.log.lastSpeechAt?.getTime());
3986
+ if (window.settled) return;
3987
+ await this.follow(null, signal, () => window.deadline(), (event) => {
3988
+ if (event.type !== "entry" || event.entry.kind !== "speech") return void 0;
3989
+ window.onSpeech(event.entry.receivedAt.getTime());
3990
+ return "rearm";
3716
3991
  });
3717
3992
  }
3718
- /** Follows the speech after `startSeq` until it paused, none came, or the time ran out. */
3719
- async record(startSeq, { quietForMs, firstWithinMs, timeoutMs }, signal) {
3720
- const sentAt = this.now();
3721
- const end = sentAt + timeoutMs;
3722
- const entries = [];
3723
- let omitted = 0;
3993
+ /** Follows the speech after `startSeq` until its {@link CaptureWindow} has passed. */
3994
+ async record(startSeq, options, signal) {
3995
+ const window = new CaptureWindow(this.now(), options, CAPTURE_LIMITS.entries);
3724
3996
  let truncated = false;
3725
- let last;
3726
- const deadline = () => Math.min(last === void 0 ? sentAt + firstWithinMs : last + quietForMs, end);
3727
- await this.follow(startSeq, signal, deadline, (event) => {
3997
+ await this.follow(startSeq, signal, () => window.deadline(), (event) => {
3728
3998
  if (event.type === "truncated") truncated = true;
3729
- if (event.type !== "entry" || event.entry.kind !== "speech") return;
3730
- last = event.entry.receivedAt.getTime();
3731
- if (entries.length < CAPTURE_LIMITS.entries) entries.push(event.entry);
3732
- else omitted++;
3999
+ if (event.type !== "entry" || event.entry.kind !== "speech") return void 0;
4000
+ window.onSpeech(event.entry);
4001
+ return "rearm";
3733
4002
  });
4003
+ const { status, entries, omitted } = window.result();
3734
4004
  return {
3735
- status: last === void 0 ? "no-speech" : last + quietForMs <= end ? "silent" : "timeout",
4005
+ status,
3736
4006
  startSeq,
3737
4007
  entries,
3738
4008
  omitted,
@@ -3741,61 +4011,35 @@ var InputCaptureService = class {
3741
4011
  }
3742
4012
  /**
3743
4013
  * Hands `onEvent` the log's events after `since` (`null`: only new ones) until `deadline()`
3744
- * (ms, read again after each speech entry) has passed. Rejects when `signal` aborts.
4014
+ * (ms, read again at each `rearm`) has passed. Rejects when `signal` aborts.
3745
4015
  */
3746
- follow(since, signal, deadline, onEvent) {
3747
- if (signal.aborted) return Promise.reject(abortReason(signal));
3748
- return new Promise((resolve, reject) => {
3749
- let done = false;
3750
- let timer;
3751
- let stopFollow;
3752
- const finish = () => {
3753
- done = true;
3754
- stopFollow?.();
3755
- timer?.abort();
3756
- signal.removeEventListener("abort", onAbort);
3757
- };
3758
- const fail = (error) => {
3759
- if (done) return;
3760
- finish();
3761
- reject(error);
3762
- };
3763
- const onAbort = () => fail(abortReason(signal));
3764
- const arm = () => {
3765
- timer?.abort();
3766
- const own = new AbortController();
3767
- timer = own;
3768
- this.deps.clock.sleep(Math.max(0, deadline() - this.now()), own.signal).then(() => {
3769
- if (done || timer !== own) return;
3770
- finish();
3771
- resolve();
3772
- }, () => {});
3773
- };
3774
- signal.addEventListener("abort", onAbort, { once: true });
3775
- arm();
3776
- try {
3777
- stopFollow = followLog(this.deps, {
3778
- since,
3779
- sessionId: void 0
3780
- }, (event) => {
3781
- if (done) return;
3782
- onEvent(event);
3783
- if (event.type === "entry" && event.entry.kind === "speech") arm();
3784
- }, {
3785
- pace: this.deps.pace?.(),
3786
- onError: (error) => fail(toError(error))
3787
- });
3788
- if (done) stopFollow();
3789
- } catch (error) {
3790
- fail(toError(error));
3791
- }
3792
- });
4016
+ async follow(since, signal, deadline, onEvent) {
4017
+ await followUntil(this.deps, {
4018
+ since,
4019
+ sessionId: void 0,
4020
+ signal,
4021
+ pace: this.deps.pace?.(),
4022
+ timeLeft: () => deadline() - this.now(),
4023
+ startTimer: "at once"
4024
+ }, onEvent);
3793
4025
  }
3794
4026
  now() {
3795
4027
  return this.deps.clock.now().getTime();
3796
4028
  }
3797
4029
  };
3798
- // src/application/shared/browser-targets.ts
4030
+ // src/domain/native-input.ts
4031
+ /** Whether the window belongs to the process tree of a target's browser. */
4032
+ function isWindowOfTarget(window, tree) {
4033
+ return tree.has(window.pid);
4034
+ }
4035
+ /**
4036
+ * The window to bring to the front: the first of `windows` (front to back) that belongs to the
4037
+ * target's process tree and has a title, with `title` one that contains it.
4038
+ */
4039
+ function findTargetWindow(windows, tree, title) {
4040
+ return windows.find((window) => isWindowOfTarget(window, tree) && window.title !== "" && (title === void 0 || window.title.includes(title)));
4041
+ }
4042
+ // src/application/support/browser-targets.ts
3799
4043
  /** The service whose process tree holds a target's browser windows, and its name in messages. */
3800
4044
  const BROWSER_TARGETS = {
3801
4045
  mcp: {
@@ -3807,6 +4051,21 @@ const BROWSER_TARGETS = {
3807
4051
  name: "the Playwright server"
3808
4052
  }
3809
4053
  };
4054
+ // src/application/support/input-marker.ts
4055
+ /**
4056
+ * The marker the bridge puts into the speech log for input it sends or a window it focuses
4057
+ * (docs/usage/native-input.md#markers-in-the-speech-log). A label too long for a marker is cut.
4058
+ */
4059
+ function addInputMarker(log, clock, label) {
4060
+ log.append({
4061
+ kind: "marker",
4062
+ text: label.slice(0, API_LIMITS.markerLength),
4063
+ source: "api",
4064
+ voice: null,
4065
+ connectionId: null,
4066
+ receivedAt: clock.now()
4067
+ });
4068
+ }
3810
4069
  // src/application/services/window-focus-service.ts
3811
4070
  /** How long a `title` may take to show up in the window title, and how often it is looked for. */
3812
4071
  const TITLE_WAIT = {
@@ -3835,7 +4094,8 @@ var WindowFocusService = class {
3835
4094
  if (!window) throw notFound(known, title);
3836
4095
  stop.throwIfAborted();
3837
4096
  if (!await this.deps.windows.bringToFront(window)) throw new AppError("FOCUS_FAILED", `Windows did not bring "${window.title}" to the front (is the desktop locked, or does an elevated window have the focus?)`);
3838
- this.deps.logger.info(`focus ${target}: "${window.title}" (pid ${window.pid})`);
4097
+ addInputMarker(this.deps.log, this.deps.clock, `focus: ${target}`);
4098
+ this.deps.logger.debug(`focus ${target}: "${window.title}" (pid ${window.pid})`);
3839
4099
  return {
3840
4100
  title: window.title,
3841
4101
  pid: window.pid
@@ -3853,7 +4113,7 @@ var WindowFocusService = class {
3853
4113
  for (let attempt = 0; attempt < tries; attempt++) {
3854
4114
  if (attempt > 0) await clock.sleep(TITLE_WAIT.pollMs, signal);
3855
4115
  const tree = await windows.processTree(pid);
3856
- const found = (await windows.topLevelWindows()).find((window) => tree.has(window.pid) && window.title !== "" && (title === void 0 || window.title.includes(title)));
4116
+ const found = findTargetWindow(await windows.topLevelWindows(), tree, title);
3857
4117
  if (found) return found;
3858
4118
  }
3859
4119
  }
@@ -3896,36 +4156,41 @@ function parseKeys(keys) {
3896
4156
  *
3897
4157
  * Keys with an `expectedTarget` are checked before every chord and stop at the first one whose
3898
4158
  * window in front isn't of that browser (docs/usage/native-input.md#requiring-a-target-window).
4159
+ *
4160
+ * A request that gets to send its input puts one marker into the speech log first, unless it says
4161
+ * `mark: false` (docs/usage/native-input.md#markers-in-the-speech-log).
3899
4162
  */
3900
4163
  var NativeInputService = class {
3901
4164
  deps;
3902
- queue = Promise.resolve();
3903
4165
  constructor(deps) {
3904
4166
  this.deps = deps;
3905
4167
  }
3906
- async click({ x, y, button = "left" }, hooks = {}) {
4168
+ async click({ x, y, button = "left", mark = true }, hooks = {}) {
3907
4169
  checkCoordinate("x", x);
3908
4170
  checkCoordinate("y", y);
3909
4171
  if (!MOUSE_BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
3910
4172
  let sent = false;
3911
- return this.enqueue(async (signal) => {
4173
+ return this.deps.queue.exclusive(async (signal) => {
3912
4174
  await hooks.beforeInject?.();
3913
4175
  const before = await this.sentTo();
3914
4176
  signal.throwIfAborted();
4177
+ this.announce(mark ? `click: ${button} ${x},${y}` : void 0, hooks);
3915
4178
  await this.deps.injector.click(x, y, button);
3916
4179
  sent = true;
3917
4180
  this.deps.logger.info(`click ${button} at ${x},${y}`);
3918
4181
  return before;
3919
4182
  }, hooks.signal, () => sent ? void 0 : "click not sent");
3920
4183
  }
3921
- async pressKeys({ keys, delayMs: delay = delayMs.default, expectedTarget }, hooks = {}) {
4184
+ async pressKeys({ keys, delayMs: delay = delayMs.default, expectedTarget, mark = true }, hooks = {}) {
3922
4185
  const chords = parseKeys(keys);
3923
4186
  if (!Number.isInteger(delay) || delay < 0 || delay > delayMs.max) throw invalidField("delayMs", `must be an integer from 0 to ${delayMs.max}`);
3924
4187
  if (expectedTarget !== void 0 && !Object.hasOwn(BROWSER_TARGETS, expectedTarget)) throw invalidField("expectedTarget", "must be mcp or playwright");
3925
4188
  this.checkSupported(chords);
3926
- const text = `keys ${typeof keys === "string" ? keys : keys.join(" ")}`;
4189
+ const list = typeof keys === "string" ? [keys] : keys;
4190
+ const text = `keys ${list.join(" ")}`;
4191
+ const label = `keys: ${list.map((chord) => chord.replace(/\s+/g, "")).join(" ")}`;
3927
4192
  let sent = 0;
3928
- return this.enqueue(async (signal) => {
4193
+ return this.deps.queue.exclusive(async (signal) => {
3929
4194
  await hooks.beforeInject?.();
3930
4195
  let before = expectedTarget === void 0 ? await this.sentTo() : {};
3931
4196
  for (const [index, chord] of chords.entries()) {
@@ -3940,6 +4205,7 @@ var NativeInputService = class {
3940
4205
  if (index === 0) before = { window };
3941
4206
  signal.throwIfAborted();
3942
4207
  }
4208
+ if (index === 0) this.announce(mark ? label : void 0, hooks);
3943
4209
  await this.press(chord);
3944
4210
  sent++;
3945
4211
  }
@@ -3948,6 +4214,15 @@ var NativeInputService = class {
3948
4214
  }, hooks.signal, () => sent === chords.length ? void 0 : `${text}: ${sent} of ${chords.length} chords sent`);
3949
4215
  }
3950
4216
  /**
4217
+ * Right before a request's first input: its marker (none without a `label`, or where nothing
4218
+ * can be sent anyway), then `onSend`.
4219
+ */
4220
+ announce(label, { onSend }) {
4221
+ const { injector, log, clock } = this.deps;
4222
+ if (label !== void 0 && injector.availability.available) addInputMarker(log, clock, label);
4223
+ onSend?.();
4224
+ }
4225
+ /**
3951
4226
  * The window in front, read in the input queue right before the input. Only extra information:
3952
4227
  * if it can't be read, the input is sent all the same.
3953
4228
  */
@@ -3990,7 +4265,7 @@ var NativeInputService = class {
3990
4265
  if (error instanceof AppError && error.code === "WRONG_WINDOW") throw error;
3991
4266
  return refuse(`the window in front could not be checked (${error instanceof Error ? error.message : String(error)})`);
3992
4267
  }
3993
- if (!tree.has(window.pid)) return refuse(`the window in front ("${window.title}", pid ${window.pid}) does not belong to the browser of ${name}`, window);
4268
+ if (!isWindowOfTarget(window, tree)) return refuse(`the window in front ("${window.title}", pid ${window.pid}) does not belong to the browser of ${name}`, window);
3994
4269
  return window;
3995
4270
  }
3996
4271
  checkSupported(chords) {
@@ -4031,32 +4306,18 @@ var NativeInputService = class {
4031
4306
  }
4032
4307
  return first;
4033
4308
  }
4034
- exclusive(task, signal) {
4035
- return this.enqueue(task, signal);
4036
- }
4037
- /**
4038
- * Runs `task` after the earlier ones; a failed task doesn't stop the later ones. `task` isn't
4039
- * run if `signal` aborted or the bridge shut down by its turn. `unsent` says what a stopped
4040
- * request leaves unsent, for the log.
4041
- */
4042
- async enqueue(task, signal, unsent = () => void 0) {
4043
- const stop = linkSignals(this.deps.shutdown, signal);
4044
- const run = this.queue.then(() => {
4045
- stop.signal.throwIfAborted();
4046
- return task(stop.signal);
4047
- });
4048
- this.queue = run.catch(() => void 0);
4049
- try {
4050
- return await run;
4051
- } catch (error) {
4052
- const what = stop.signal.aborted ? unsent() : void 0;
4053
- if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
4054
- throw error;
4055
- } finally {
4056
- stop.dispose();
4057
- }
4058
- }
4059
4309
  };
4310
+ // src/domain/label.ts
4311
+ /**
4312
+ * A label as the API takes it: trimmed, not empty, at most `max` characters (`isTrimmedLabel`, the
4313
+ * rule the request schemas check too). `INVALID_REQUEST` naming `field` otherwise.
4314
+ */
4315
+ function trimmedLabel(field, value, max) {
4316
+ if (isTrimmedLabel(value, max)) return value.trim();
4317
+ throw invalidField(field, value.trim() === "" ? "must not be empty" : `must be at most ${max} characters`);
4318
+ }
4319
+ /** A marker's text, which is also the label a marker is found by. */
4320
+ const markerLabel = (label) => trimmedLabel("label", label, API_LIMITS.markerLength);
4060
4321
  // src/domain/session.ts
4061
4322
  const EMPTY_SESSION_STATS = {
4062
4323
  firstSeq: null,
@@ -4074,16 +4335,13 @@ function summarize(session, stats) {
4074
4335
  }
4075
4336
  /** `name` (required) or `run` (optional), trimmed. `INVALID_REQUEST` if empty or too long. */
4076
4337
  function sessionLabel(field, value) {
4077
- const text = value.trim();
4078
- if (text === "") throw invalidField(field, "must not be empty");
4079
- if (text.length > MAX_SESSION_NAME_LENGTH) throw invalidField(field, `must be at most ${MAX_SESSION_NAME_LENGTH} characters`);
4080
- return text;
4338
+ return trimmedLabel(field, value, MAX_SESSION_NAME_LENGTH);
4081
4339
  }
4082
4340
  // src/application/services/session-service.ts
4083
4341
  const describe = (session) => `session ${session.id} "${session.name}" (client ${session.client ?? "unknown"})`;
4084
4342
  /**
4085
- * Starting, ending and listing sessions (docs/usage/speech-capture.md#sessions). Each start and end
4086
- * is published as a `session` event. The speech log gives entries their `sessionId`. One screen
4343
+ * Starting, ending and listing sessions (docs/usage/speech-capture.md#sessions). The speech log
4344
+ * gives entries their `sessionId` and reports each start and end as a `session` event. One screen
4087
4345
  * reader means one current session: a client that ends or replaces another client's session is not
4088
4346
  * refused, but warned about (docs/implementation/decisions.md#sessions-warn-instead-of-locking).
4089
4347
  */
@@ -4093,24 +4351,13 @@ var SessionService = class {
4093
4351
  this.deps = deps;
4094
4352
  }
4095
4353
  start({ name, run, client }) {
4096
- const label = sessionLabel("name", name);
4097
- const group = run === void 0 || run === null ? null : sessionLabel("run", run);
4098
- const owner = clientLabel(client);
4099
4354
  const { ended, started } = this.deps.log.startSession({
4100
- name: label,
4101
- run: group,
4102
- client: owner,
4355
+ name,
4356
+ run: run ?? null,
4357
+ client: client ?? null,
4103
4358
  startedAt: this.deps.clock.now()
4104
4359
  });
4105
- if (ended) this.deps.events.publish({
4106
- type: "session",
4107
- session: ended
4108
- });
4109
- this.deps.events.publish({
4110
- type: "session",
4111
- session: started
4112
- });
4113
- const replaced = ended && ended.client !== owner ? ended : null;
4360
+ const replaced = ended && ended.client !== started.client ? ended : null;
4114
4361
  if (replaced) this.deps.logger.warn(`${describe(started)} replaced ${describe(replaced)}`);
4115
4362
  return {
4116
4363
  session: started,
@@ -4121,10 +4368,6 @@ var SessionService = class {
4121
4368
  const owner = clientLabel(client);
4122
4369
  const ended = this.deps.log.endSession(this.deps.clock.now(), session);
4123
4370
  if (!ended) return null;
4124
- this.deps.events.publish({
4125
- type: "session",
4126
- session: ended
4127
- });
4128
4371
  if (ended.client !== owner) this.deps.logger.warn(`client ${owner ?? "unknown"} ended ${describe(ended)}`);
4129
4372
  return ended;
4130
4373
  }
@@ -4147,10 +4390,9 @@ function clientLabel(client) {
4147
4390
  /** Page size of `list`: the default and the most a caller may ask for. */
4148
4391
  const LIST_LIMIT = API_LIMITS.list;
4149
4392
  // src/application/services/speech-service.ts
4150
- const MAX_MARKER_LENGTH = API_LIMITS.markerLength;
4151
4393
  /**
4152
4394
  * Recording, reading, clearing and marking speech: every entry gets its `seq` and `sessionId`
4153
- * from the speech log and `receivedAt` from the clock, and is published on the event bus
4395
+ * from the speech log and `receivedAt` from the clock
4154
4396
  * (docs/implementation/tcp-capture.md#from-line-to-speech-entry).
4155
4397
  */
4156
4398
  var SpeechService = class {
@@ -4158,11 +4400,11 @@ var SpeechService = class {
4158
4400
  constructor(deps) {
4159
4401
  this.deps = deps;
4160
4402
  }
4161
- record({ text, voice, connectionId }) {
4403
+ record({ text, voice, source, connectionId }) {
4162
4404
  this.add({
4163
4405
  kind: "speech",
4164
4406
  text,
4165
- source: "tcp",
4407
+ source,
4166
4408
  voice,
4167
4409
  connectionId
4168
4410
  });
@@ -4192,66 +4434,39 @@ var SpeechService = class {
4192
4434
  /** Wipes the buffer and the ended sessions, or one scope. The current session stays current. */
4193
4435
  clear(filter) {
4194
4436
  const session = filter === "active" ? this.deps.log.resolveFilter(filter) ?? void 0 : filter;
4195
- if (session === void 0) {
4196
- this.deps.log.clear();
4197
- this.deps.events.publish({ type: "clear" });
4198
- return;
4199
- }
4200
- this.deps.events.publish({
4201
- type: "clear",
4202
- sessionId: this.deps.log.clearScope(session)
4203
- });
4437
+ if (session === void 0) this.deps.log.clear();
4438
+ else this.deps.log.clearScope(session);
4204
4439
  }
4440
+ /** The speech log trims the label and refuses an empty or too long one. */
4205
4441
  addMarker(label) {
4206
- const text = markerLabel(label);
4207
4442
  return this.add({
4208
4443
  kind: "marker",
4209
- text,
4444
+ text: label,
4210
4445
  source: "api",
4211
4446
  voice: null,
4212
4447
  connectionId: null
4213
4448
  });
4214
4449
  }
4215
4450
  latestMarker(label, session) {
4216
- const text = markerLabel(label);
4217
4451
  const sessionId = this.deps.log.resolveFilter(session);
4218
- return this.deps.log.latestMarker(text, sessionId) ?? null;
4452
+ return this.deps.log.latestMarker(label, sessionId) ?? null;
4219
4453
  }
4220
4454
  add(entry) {
4221
- const stored = this.deps.log.append({
4455
+ return this.deps.log.append({
4222
4456
  ...entry,
4223
4457
  receivedAt: this.deps.clock.now()
4224
4458
  });
4225
- this.deps.events.publish({
4226
- type: "entry",
4227
- entry: stored
4228
- });
4229
- return stored;
4230
4459
  }
4231
4460
  };
4232
- /** A marker label: trimmed, not empty, at most `MAX_MARKER_LENGTH` characters. */
4233
- function markerLabel(label) {
4234
- const text = label.trim();
4235
- if (text === "") throw invalidField("label", "must not be empty");
4236
- if (text.length > MAX_MARKER_LENGTH) throw invalidField("label", `must be at most ${MAX_MARKER_LENGTH} characters`);
4237
- return text;
4238
- }
4239
4461
  // src/application/services/status-service.ts
4240
- /**
4241
- * `GET /api/v1/status`. `BridgeLifecycleService` moves the state from `starting` to `ready` and
4242
- * `stopping` through `BridgeStateControl`.
4243
- */
4462
+ /** `GET /api/v1/status`. */
4244
4463
  var StatusService = class {
4245
4464
  deps;
4246
- state = "starting";
4247
4465
  constructor(deps) {
4248
4466
  this.deps = deps;
4249
4467
  }
4250
- setState(state) {
4251
- this.state = state;
4252
- }
4253
4468
  status() {
4254
- const { capture, log, supervisors, config, version, apiVersion, startedAt, injector, windows } = this.deps;
4469
+ const { state, capture, log, supervisors, config, version, apiVersion, startedAt, injector, windows } = this.deps;
4255
4470
  const { listener, connections } = capture.captureStatus();
4256
4471
  const { tcp } = config();
4257
4472
  const listed = log.sessions();
@@ -4260,7 +4475,7 @@ var StatusService = class {
4260
4475
  bridge: {
4261
4476
  version,
4262
4477
  apiVersion,
4263
- state: this.state,
4478
+ state: state(),
4264
4479
  startedAt
4265
4480
  },
4266
4481
  tcp: {
@@ -4284,14 +4499,33 @@ var StatusService = class {
4284
4499
  };
4285
4500
  }
4286
4501
  };
4502
+ // src/application/support/input-queue.ts
4503
+ /** One task at a time, in the order they came. A failed task doesn't stop the later ones. */
4504
+ var SerialInputQueue = class {
4505
+ deps;
4506
+ tail = Promise.resolve();
4507
+ constructor(deps) {
4508
+ this.deps = deps;
4509
+ }
4510
+ async exclusive(task, signal, unsent = () => void 0) {
4511
+ const stop = linkSignals(this.deps.shutdown, signal);
4512
+ const run = this.tail.then(() => {
4513
+ stop.signal.throwIfAborted();
4514
+ return task(stop.signal);
4515
+ });
4516
+ this.tail = run.catch(() => void 0);
4517
+ try {
4518
+ return await run;
4519
+ } catch (error) {
4520
+ const what = stop.signal.aborted ? unsent() : void 0;
4521
+ if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
4522
+ throw error;
4523
+ } finally {
4524
+ stop.dispose();
4525
+ }
4526
+ }
4527
+ };
4287
4528
  // src/application/services/tcp-startup-service.ts
4288
- const VOICE_DOCS = "docs/usage/vm-setup.md#more-voices--other-ports";
4289
- const QUIT = /* @__PURE__ */ new Set([
4290
- "",
4291
- "q",
4292
- "quit",
4293
- "exit"
4294
- ]);
4295
4529
  /**
4296
4530
  * Starts the TCP listener on `tcp.port`. If that port is in use or not allowed, it asks the person
4297
4531
  * at the console for another one, checks it, listens on it and saves it to the config file. It
@@ -4317,29 +4551,24 @@ var TcpStartupService = class {
4317
4551
  return this.deps.listener.stop();
4318
4552
  }
4319
4553
  async choosePort(failure) {
4320
- const { pinnedBy, prompt, logger, configLocation } = this.deps;
4321
- if (pinnedBy !== void 0) throw hinted(failure, `${pinnedBy} sets this port: choose a free one there`);
4322
- const giveUp = hinted(failure, `Start with --tcp-port <port>, or set tcp.port in ${configLocation}`);
4554
+ const { hints, prompt, logger } = this.deps;
4555
+ if (hints.pinned !== void 0) throw hinted(failure, hints.pinned);
4556
+ const giveUp = hinted(failure, hints.choosePort);
4323
4557
  if (prompt === void 0) throw giveUp;
4324
4558
  logger.warn(failure.message);
4325
4559
  for (;;) {
4326
- const text = (await prompt.ask(`TCP port ${failure.port} can't be used. TCP port for the socket voice (Enter to quit): `))?.trim();
4327
- if (text === void 0 || QUIT.has(text.toLowerCase())) throw giveUp;
4328
- const port = await this.tryPort(text);
4560
+ const answer = await prompt.askForPort(failure.port);
4561
+ if (answer === void 0) throw giveUp;
4562
+ const port = await this.tryPort(answer);
4329
4563
  if (port === void 0) continue;
4330
4564
  await this.save(port);
4331
- logger.warn(`speech capture listens on port ${port} instead of ${failure.port}: point the socket voice to it (${VOICE_DOCS})`);
4565
+ logger.warn(`speech capture listens on port ${port} instead of ${failure.port}: ${hints.pointVoice}`);
4332
4566
  return port;
4333
4567
  }
4334
4568
  }
4335
- /** Listens on the port in `answer`, or warns why not and resolves with `undefined`. */
4336
- async tryPort(answer) {
4569
+ /** Listens on `port`, or warns why not and resolves with `undefined`. */
4570
+ async tryPort(port) {
4337
4571
  const { listener, config, logger } = this.deps;
4338
- if (!/^\d+$/.test(answer)) {
4339
- logger.warn(`${JSON.stringify(answer)} is not a port number`);
4340
- return;
4341
- }
4342
- const port = Number(answer);
4343
4572
  if (port === 0) {
4344
4573
  logger.warn("port 0 picks another port on every start, but the voice needs a fixed one");
4345
4574
  return;
@@ -4355,10 +4584,11 @@ var TcpStartupService = class {
4355
4584
  }
4356
4585
  /** Saves `port` as `tcp.port`. The bridge uses it anyway if the file can't be written. */
4357
4586
  async save(port) {
4587
+ const { config, configLocation, hints, logger } = this.deps;
4358
4588
  try {
4359
- await this.deps.config.adopt({ tcp: { port } });
4589
+ await config.adopt({ tcp: { port } });
4360
4590
  } catch (error) {
4361
- this.deps.logger.warn(`tcp.port ${port} could not be saved to ${this.deps.configLocation} (${error instanceof Error ? error.message : String(error)}): start with --tcp-port ${port} next time`);
4591
+ logger.warn(`tcp.port ${port} could not be saved to ${configLocation} (${error instanceof Error ? error.message : String(error)}): ${hints.keepPort(port)}`);
4362
4592
  }
4363
4593
  }
4364
4594
  };
@@ -4387,6 +4617,36 @@ var TranscriptService = class {
4387
4617
  });
4388
4618
  }
4389
4619
  };
4620
+ // src/domain/last-seen.ts
4621
+ /**
4622
+ * The last `limit` entries pushed, and how many came before them: what a wait that timed out
4623
+ * answers with (docs/usage/http-api.md).
4624
+ */
4625
+ var LastSeen = class {
4626
+ limit;
4627
+ #entries = [];
4628
+ #dropped = 0;
4629
+ constructor(limit) {
4630
+ this.limit = limit;
4631
+ }
4632
+ push(entry) {
4633
+ this.#entries.push(entry);
4634
+ if (this.#entries.length >= 2 * this.limit) this.#trim();
4635
+ }
4636
+ result() {
4637
+ this.#trim();
4638
+ return {
4639
+ seen: this.#entries,
4640
+ omitted: this.#dropped
4641
+ };
4642
+ }
4643
+ #trim() {
4644
+ const over = this.#entries.length - this.limit;
4645
+ if (over <= 0) return;
4646
+ this.#entries.splice(0, over);
4647
+ this.#dropped += over;
4648
+ }
4649
+ };
4390
4650
  // src/domain/text-match.ts
4391
4651
  /** Longest `regex` a wait accepts. */
4392
4652
  const MAX_REGEX_LENGTH = API_LIMITS.wait.regexLength;
@@ -4427,28 +4687,6 @@ const WAIT_TIMEOUT_MS = API_LIMITS.wait.timeoutMs;
4427
4687
  /** How many of the entries a wait saw its timeout answer holds at most: the last ones. */
4428
4688
  const WAIT_SEEN_LIMIT = API_LIMITS.wait.seen;
4429
4689
  // src/application/services/wait-for-speech-service.ts
4430
- /** The last {@link WAIT_SEEN_LIMIT} entries pushed, and how many came before them. */
4431
- var LastSeen = class {
4432
- #entries = [];
4433
- #dropped = 0;
4434
- push(entry) {
4435
- this.#entries.push(entry);
4436
- if (this.#entries.length >= 2 * WAIT_SEEN_LIMIT) this.#trim();
4437
- }
4438
- result() {
4439
- this.#trim();
4440
- return {
4441
- seen: this.#entries,
4442
- omitted: this.#dropped
4443
- };
4444
- }
4445
- #trim() {
4446
- const over = this.#entries.length - WAIT_SEEN_LIMIT;
4447
- if (over <= 0) return;
4448
- this.#entries.splice(0, over);
4449
- this.#dropped += over;
4450
- }
4451
- };
4452
4690
  /**
4453
4691
  * Long-poll for a speech entry (`GET /api/v1/speech/wait`): looks through the buffer after
4454
4692
  * `since`, then follows the new entries, with nothing missed or seen twice in between.
@@ -4474,127 +4712,66 @@ var WaitForSpeechService = class {
4474
4712
  const matches = createSpeechMatcher(options);
4475
4713
  const sessionId = this.deps.log.resolveFilter(options.session);
4476
4714
  if (signal?.aborted) throw abortReason(signal);
4477
- return new Promise((resolve, reject) => {
4478
- const seen = new LastSeen();
4479
- let done = false;
4480
- let stop;
4481
- /** The client's signal and the shutdown's. */
4482
- const ended = linkSignals(this.deps.shutdown, signal);
4483
- const finish = () => {
4484
- done = true;
4485
- stop?.();
4486
- timer.abort();
4487
- ended.dispose();
4488
- };
4489
- const fail = (error) => {
4490
- finish();
4491
- reject(error);
4492
- };
4493
- const timer = new AbortController();
4494
- const startTimer = () => {
4495
- if (done) return;
4496
- this.deps.clock.sleep(timeoutMs, timer.signal).then(() => {
4497
- if (done) return;
4498
- finish();
4499
- resolve({
4500
- status: "timeout",
4501
- ...seen.result()
4502
- });
4503
- }, () => {});
4504
- };
4505
- ended.signal.addEventListener("abort", () => fail(abortReason(ended.signal)), { once: true });
4506
- const failed = (error) => fail(error instanceof Error ? error : new Error(String(error)));
4507
- try {
4508
- stop = followLog(this.deps, {
4509
- since,
4510
- sessionId
4511
- }, (event) => {
4512
- if (done || event.type !== "entry") return;
4513
- seen.push(event.entry);
4514
- if (!matches(event.entry)) return;
4515
- finish();
4516
- resolve({
4517
- status: "matched",
4518
- entry: event.entry
4519
- });
4520
- }, {
4521
- pace: this.deps.pace?.(),
4522
- onCaughtUp: startTimer,
4523
- onError: failed
4524
- });
4525
- if (done) stop();
4526
- } catch (error) {
4527
- failed(error);
4528
- }
4529
- });
4715
+ const seen = new LastSeen(WAIT_SEEN_LIMIT);
4716
+ let match;
4717
+ /** The client's signal and the shutdown's. */
4718
+ const ended = linkSignals(this.deps.shutdown, signal);
4719
+ try {
4720
+ await followUntil(this.deps, {
4721
+ since,
4722
+ sessionId,
4723
+ signal: ended.signal,
4724
+ pace: this.deps.pace?.(),
4725
+ timeLeft: () => timeoutMs,
4726
+ startTimer: "caught up"
4727
+ }, (event) => {
4728
+ if (event.type !== "entry") return void 0;
4729
+ seen.push(event.entry);
4730
+ if (!matches(event.entry)) return void 0;
4731
+ match = event.entry;
4732
+ return "done";
4733
+ });
4734
+ } finally {
4735
+ ended.dispose();
4736
+ }
4737
+ return match ? {
4738
+ status: "matched",
4739
+ entry: match
4740
+ } : {
4741
+ status: "timeout",
4742
+ ...seen.result()
4743
+ };
4530
4744
  }
4531
4745
  };
4532
- // src/composition/load-config.ts
4533
- /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
4534
- var ConfigError = class extends Error {
4535
- name = "ConfigError";
4536
- };
4537
- /** `patch` checked, with an error that says where the bad setting came from. */
4538
- function checked(patch, origin) {
4539
- try {
4540
- return validatePatch(patch);
4541
- } catch (error) {
4542
- throw new ConfigError(`${origin(error instanceof AppError ? error.details?.field : void 0)}: ${error.message}`, { cause: error });
4543
- }
4544
- }
4746
+ // src/composition/service-routes.ts
4545
4747
  /**
4546
- * Defaults, then the config file, then flags and environment variables. Settings of the file this
4547
- * bridge doesn't know are left out of `config` and `file` and returned in `unknown`. The store's
4548
- * `warnings` are returned too: there is no log yet, it is built from the result.
4748
+ * The child services' paths on the bridge's HTTP port (docs/usage/playwright-mcp.md): the
4749
+ * Playwright server's WebSocket at `/`, MCP's streamable HTTP at `/mcp`.
4549
4750
  */
4550
- async function loadConfig(store, overridesPatch, sourceOf) {
4551
- let saved;
4552
- const warnings = [];
4553
- try {
4554
- saved = await store.load((message) => warnings.push(message));
4555
- } catch (error) {
4556
- throw new ConfigError(error.message, { cause: error });
4557
- }
4558
- const { known, unknown, names: ignored } = splitUnknownSettings(saved);
4559
- const file = checked(known, () => `Invalid setting in the config file ${store.location}`);
4560
- const overrides = checked(overridesPatch, (field) => field?.includes(".") ? `Invalid ${sourceOf(field)}` : "Invalid setting");
4561
- const config = mergeConfig(mergeConfig(DEFAULT_CONFIG, file), overrides);
4562
- try {
4563
- assertDistinctPorts(config);
4564
- } catch (error) {
4565
- throw new ConfigError(`Invalid setting: ${error.message}`, { cause: error });
4566
- }
4567
- return {
4568
- config,
4569
- file,
4570
- overrides,
4571
- unknown,
4572
- ignored,
4573
- warnings
4574
- };
4575
- }
4576
- // src/composition/summary.ts
4577
- const PATHS = {
4751
+ const SERVICE_ROUTES = {
4578
4752
  playwright: {
4579
4753
  path: PLAYWRIGHT_PATH,
4754
+ upstreamPath: "/",
4580
4755
  scheme: "ws"
4581
4756
  },
4582
4757
  mcp: {
4583
4758
  path: PLAYWRIGHT_MCP_PATH,
4759
+ upstreamPath: "/mcp",
4584
4760
  scheme: "http"
4585
4761
  }
4586
4762
  };
4763
+ // src/composition/summary.ts
4587
4764
  /**
4588
4765
  * The block logged when the bridge is ready: what listens where, and which child services run.
4589
4766
  * It is the one place to look for the URLs to use and for a component that did not start
4590
4767
  * (docs/usage/operations.md#line-format).
4591
4768
  */
4592
4769
  function readySummary(input) {
4593
- const { config, ports, supervisors } = input;
4770
+ const { config, ports, services } = input;
4594
4771
  const rows = [["speech capture", `${describeAddress(config.tcp.host, ports.tcp)} (${config.tcp.encoding})`], [input.webUi ? "HTTP API + web UI" : "HTTP API", reachableUrls("http", config.http.host, ports.http).join(", ")]];
4595
- for (const name of Object.keys(PATHS)) {
4596
- const { path, scheme } = PATHS[name];
4597
- const { state, version } = supervisors[name].status();
4772
+ for (const name of SERVICE_NAMES) {
4773
+ const { path, scheme } = SERVICE_ROUTES[name];
4774
+ const { state, version } = services[name];
4598
4775
  const urls = reachableUrls(scheme, config.http.host, ports.http).map((url) => `${url}${path}`).join(", ");
4599
4776
  let value;
4600
4777
  if (!config[name].enabled) value = "off (disabled in the config)";
@@ -4746,6 +4923,12 @@ function bindExtendedKeyboard(koffi) {
4746
4923
  keyUp: (key) => send(key, KEYEVENTF_KEYUP$1)
4747
4924
  };
4748
4925
  }
4926
+ // src/composition/koffi.ts
4927
+ /** Loads `koffi`, an optional dependency: rejects where it is not installed or can't run. */
4928
+ async function loadKoffi() {
4929
+ const module = await import("koffi");
4930
+ return module.default ?? module;
4931
+ }
4749
4932
  // src/composition/input.ts
4750
4933
  /**
4751
4934
  * Loads `@jitsi/robotjs`, an optional dependency. When it can't be loaded (no prebuilt binary for
@@ -4771,8 +4954,7 @@ async function createInputInjector(logger) {
4771
4954
  async function createExtendedKeyboard(logger) {
4772
4955
  if (process.platform !== "win32") return void 0;
4773
4956
  try {
4774
- const module = await import("koffi");
4775
- return bindExtendedKeyboard(module.default ?? module);
4957
+ return bindExtendedKeyboard(await loadKoffi());
4776
4958
  } catch (error) {
4777
4959
  const reason = `koffi could not be loaded (${error instanceof Error ? error.message : String(error)})`;
4778
4960
  logger.warn(`the keys numpadenter and numpaddivide are off: ${reason}`);
@@ -4854,7 +5036,6 @@ function bindWin32(koffi) {
4854
5036
  const IsWindowVisible = user32.func("int __stdcall IsWindowVisible(intptr_t hWnd)");
4855
5037
  const GetWindow = user32.func("intptr_t __stdcall GetWindow(intptr_t hWnd, uint32_t uCmd)");
4856
5038
  const GetWindowTextW = user32.func("int __stdcall GetWindowTextW(intptr_t hWnd, _Out_ void *lpString, int nMaxCount)");
4857
- const GetClassNameW = user32.func("int __stdcall GetClassNameW(intptr_t hWnd, _Out_ void *lpClassName, int nMaxCount)");
4858
5039
  const IsIconic = user32.func("int __stdcall IsIconic(intptr_t hWnd)");
4859
5040
  const ShowWindow = user32.func("int __stdcall ShowWindow(intptr_t hWnd, int nCmdShow)");
4860
5041
  const keybd_event = user32.func("void __stdcall keybd_event(uint8_t bVk, uint8_t bScan, uint32_t dwFlags, uintptr_t dwExtraInfo)");
@@ -4903,7 +5084,6 @@ function bindWin32(koffi) {
4903
5084
  isVisible: (hwnd) => IsWindowVisible(hwnd) !== 0,
4904
5085
  ownerWindow: (hwnd) => Number(GetWindow(hwnd, GW_OWNER)),
4905
5086
  title: (hwnd) => text(GetWindowTextW, hwnd),
4906
- className: (hwnd) => text(GetClassNameW, hwnd),
4907
5087
  isMinimized: (hwnd) => IsIconic(hwnd) !== 0,
4908
5088
  restore: (hwnd) => void ShowWindow(hwnd, SW_RESTORE),
4909
5089
  tapAlt() {
@@ -4970,8 +5150,7 @@ var Win32WindowSystem = class {
4970
5150
  windows.push({
4971
5151
  handle: hwnd,
4972
5152
  pid: win32.owner(hwnd).pid,
4973
- title: win32.title(hwnd),
4974
- className: win32.className(hwnd)
5153
+ title: win32.title(hwnd)
4975
5154
  });
4976
5155
  }
4977
5156
  return Promise.resolve(windows);
@@ -5015,8 +5194,7 @@ async function createWindowSystem(logger) {
5015
5194
  return new DisabledWindowSystem("only on Windows");
5016
5195
  }
5017
5196
  try {
5018
- const module = await import("koffi");
5019
- const windows = new Win32WindowSystem(bindWin32(module.default ?? module));
5197
+ const windows = new Win32WindowSystem(bindWin32(await loadKoffi()));
5020
5198
  logger.info("bringing windows to the front is available (koffi)");
5021
5199
  return windows;
5022
5200
  } catch (error) {
@@ -5025,6 +5203,18 @@ async function createWindowSystem(logger) {
5025
5203
  return new DisabledWindowSystem(reason);
5026
5204
  }
5027
5205
  }
5206
+ // src/adapters/out/log/terminal-text.ts
5207
+ /**
5208
+ * Escape sequences (CSI such as colours, OSC such as a window title, and the short ones) and the
5209
+ * other control characters, except tab. Text in log lines comes from outside: speech, session and
5210
+ * client names, the voice header, child process output. A terminal would act on what this removes
5211
+ * (docs/usage/operations.md#line-format).
5212
+ */
5213
+ const CONTROL = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-_]?|\u009b[0-?]*[ -/]*[@-~]|[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g;
5214
+ /** `text` without escape sequences and control characters other than tab (one line). */
5215
+ function stripControlChars(text) {
5216
+ return text.replace(CONTROL, "");
5217
+ }
5028
5218
  // src/adapters/out/log/format.ts
5029
5219
  const ESC = "\x1B[";
5030
5220
  const RESET = `${ESC}0m`;
@@ -5052,12 +5242,13 @@ function paint(text, colour, enabled) {
5052
5242
  /**
5053
5243
  * Formats one message as one or more log lines (without line breaks). Every line of a
5054
5244
  * multi-line message gets the full prefix, timestamp and level. Padding is counted without
5055
- * colour codes.
5245
+ * colour codes. Escape sequences and control characters in the message are removed: only the
5246
+ * bridge's own colours reach the terminal.
5056
5247
  */
5057
5248
  function formatLogLines(prefix, level, time, message, colour) {
5058
5249
  const tag = `[${prefix}]`;
5059
5250
  const head = paint(tag, PREFIX_COLOURS[prefix], colour) + " ".repeat(PREFIX_WIDTH - tag.length) + `${time.toISOString()} ` + paint(level.toUpperCase(), LEVEL_COLOURS[level], colour) + " ".repeat(6 - level.length);
5060
- return message.split(/\r?\n/).map((line) => head + line);
5251
+ return message.split(/\r?\n/).map((line) => head + stripControlChars(line));
5061
5252
  }
5062
5253
  // src/adapters/out/log/bridge-log.ts
5063
5254
  const LEVEL_RANK = {
@@ -5240,6 +5431,13 @@ function createLogging(config, options) {
5240
5431
  return log;
5241
5432
  }
5242
5433
  // src/adapters/out/terminal/terminal-prompt.ts
5434
+ /** Answers that quit instead of naming a port. */
5435
+ const QUIT = /* @__PURE__ */ new Set([
5436
+ "",
5437
+ "q",
5438
+ "quit",
5439
+ "exit"
5440
+ ]);
5243
5441
  /**
5244
5442
  * Driven adapter: asks a question on the console and reads one line. Ctrl+C, end of input (Ctrl+D,
5245
5443
  * Ctrl+Z on Windows) and the `signal` cancel it. It lets go of the input after each question, so
@@ -5250,6 +5448,18 @@ var TerminalPrompt = class {
5250
5448
  constructor(options) {
5251
5449
  this.options = options;
5252
5450
  }
5451
+ async askForPort(failedPort) {
5452
+ for (;;) {
5453
+ const answer = await this.ask(`TCP port ${failedPort} can't be used. TCP port for the socket voice (Enter to quit): `);
5454
+ if (answer === void 0 || QUIT.has(answer.toLowerCase())) return void 0;
5455
+ if (/^\d+$/.test(answer)) return Number(answer);
5456
+ this.options.warn(`${JSON.stringify(answer)} is not a port number`);
5457
+ }
5458
+ }
5459
+ /**
5460
+ * Shows `question` and resolves with the trimmed answer, or with `undefined` if the person
5461
+ * cancels (Ctrl+C, end of input) or the start is cancelled.
5462
+ */
5253
5463
  async ask(question) {
5254
5464
  const { input, output, flush, terminal, signal } = this.options;
5255
5465
  if (signal?.aborted === true) return void 0;
@@ -5290,12 +5500,13 @@ var TerminalPrompt = class {
5290
5500
  * The console prompt, or `undefined` when nobody can answer: stdin or stdout is not a terminal
5291
5501
  * (a service, CI, a test, output piped to a file). `cancel` ends a pending question.
5292
5502
  */
5293
- function createOperatorPrompt(cancel) {
5503
+ function createOperatorPrompt(warn, cancel) {
5294
5504
  if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) return void 0;
5295
5505
  return new TerminalPrompt({
5296
5506
  input: process.stdin,
5297
5507
  output: process.stdout,
5298
5508
  flush: flushTerminal,
5509
+ warn,
5299
5510
  terminal: true,
5300
5511
  ...cancel === void 0 ? {} : { signal: cancel }
5301
5512
  });
@@ -5309,27 +5520,30 @@ function yieldEvery(n) {
5309
5520
  let count = 0;
5310
5521
  return () => ++count % n === 0 ? setImmediate() : void 0;
5311
5522
  }
5312
- // src/composition/proxies.ts
5523
+ // src/composition/tcp-startup-hints.ts
5524
+ const VOICE_DOCS = "docs/usage/vm-setup.md#more-voices--other-ports";
5313
5525
  /**
5314
- * The child services' paths on the bridge's HTTP port (docs/usage/playwright-mcp.md): the
5315
- * Playwright server's WebSocket at `/`, MCP's streamable HTTP at `/mcp`.
5526
+ * The ways to set the TCP port by hand, as startup names them. `pinnedBy`: what sets `tcp.port`
5527
+ * if a flag or an environment variable does, for example `--tcp-port`.
5316
5528
  */
5529
+ function tcpStartupHints(configLocation, pinnedBy) {
5530
+ return {
5531
+ ...pinnedBy === void 0 ? {} : { pinned: `${pinnedBy} sets this port: choose a free one there` },
5532
+ choosePort: `Start with --tcp-port <port>, or set tcp.port in ${configLocation}`,
5533
+ pointVoice: `point the socket voice to it (${VOICE_DOCS})`,
5534
+ keepPort: (port) => `start with --tcp-port ${port} next time`
5535
+ };
5536
+ }
5537
+ // src/composition/proxies.ts
5538
+ /** The pass-through of each child service on the bridge's HTTP port. */
5317
5539
  function proxyRoutes(services) {
5318
- return [{
5319
- name: SERVICE_TITLES.playwright,
5320
- path: PLAYWRIGHT_PATH,
5321
- upstreamPath: "/",
5322
- scheme: "ws",
5323
- target: () => services.reachability("playwright")
5324
- }, {
5325
- name: SERVICE_TITLES.mcp,
5326
- path: PLAYWRIGHT_MCP_PATH,
5327
- upstreamPath: "/mcp",
5328
- scheme: "http",
5329
- target: () => services.reachability("mcp")
5330
- }];
5540
+ return SERVICE_NAMES.map((name) => ({
5541
+ name: SERVICE_TITLES[name],
5542
+ ...SERVICE_ROUTES[name],
5543
+ target: () => services.reachability(name)
5544
+ }));
5331
5545
  }
5332
- // src/adapters/shared/net/port-probe.ts
5546
+ // src/adapters/common/net/port-probe.ts
5333
5547
  /** Where to probe a listener on a wildcard host: the loopback address of that family. */
5334
5548
  const WILDCARD_PROBE = {
5335
5549
  "0.0.0.0": "127.0.0.1",
@@ -5351,196 +5565,50 @@ function portOpen(host, port, timeoutMs = 1e3) {
5351
5565
  socket.once("error", () => done(false));
5352
5566
  });
5353
5567
  }
5354
- // src/adapters/out/process/child-process-supervisor.ts
5355
- /** How long the port may take to open after the start, before it counts as a crash. */
5356
- const READY_TIMEOUT_MS = 6e4;
5357
- /**
5358
- * Runs one child service (docs/usage/operations.md#child-service-crashes): prepare, spawn, wait for
5359
- * its port, restart after a crash with a growing delay, give up after too many crashes in a row,
5360
- * and kill the whole process tree on stop.
5361
- */
5362
- var ChildProcessSupervisor = class {
5363
- options;
5364
- settings;
5365
- /** Settings of the current run, until it is stopped. `status()` reports these. */
5366
- active = null;
5367
- state = "stopped";
5368
- restarts = 0;
5369
- exitCode = null;
5370
- lastError = null;
5371
- crashesInRow = 0;
5372
- child = null;
5373
- runningSince = null;
5374
- /** When the current launch began, for the time to `running` in the log. */
5375
- launchedAt = 0;
5376
- restartTimer;
5377
- abort = null;
5378
- /** Bumped by every launch and stop, so callbacks of an older run do nothing. */
5379
- generation = 0;
5380
- waiters = [];
5381
- constructor(options) {
5382
- this.options = options;
5383
- this.settings = options.settings;
5384
- }
5385
- pid() {
5386
- return this.state === "running" ? this.child?.pid ?? null : null;
5387
- }
5388
- status() {
5389
- const { version, port } = this.active ?? this.resolved();
5390
- return {
5391
- state: this.state,
5392
- version,
5393
- port,
5394
- restarts: this.restarts,
5395
- exitCode: this.exitCode,
5396
- lastError: this.lastError
5397
- };
5398
- }
5399
- start() {
5400
- if (this.state === "running") return Promise.resolve();
5401
- const settled = new Promise((resolve) => this.waiters.push(resolve));
5402
- if (this.state === "stopped" || this.state === "failed") {
5403
- this.restarts = 0;
5404
- this.crashesInRow = 0;
5405
- this.exitCode = null;
5406
- this.lastError = null;
5407
- this.launch();
5408
- }
5409
- return settled;
5410
- }
5411
- async stop() {
5412
- this.generation++;
5413
- clearTimeout(this.restartTimer);
5414
- this.abort?.abort();
5415
- this.abort = null;
5416
- const child = this.child;
5417
- this.child = null;
5418
- this.runningSince = null;
5419
- this.active = null;
5420
- const wasStopped = this.state === "stopped";
5421
- this.setState("stopped");
5422
- if (!wasStopped) this.options.logger.info(`${this.options.name} stopped`);
5423
- if (child) await killTree(child);
5424
- }
5425
- resolved() {
5426
- const { host, port, version } = this.settings;
5427
- return {
5428
- host,
5429
- port,
5430
- version: version ?? this.options.defaultVersion
5431
- };
5432
- }
5433
- setState(state) {
5434
- this.state = state;
5435
- if (state === "running" || state === "failed" || state === "stopped") for (const resolve of this.waiters.splice(0)) resolve();
5436
- }
5437
- launch() {
5438
- const generation = ++this.generation;
5439
- const current = () => generation === this.generation;
5440
- const settings = this.resolved();
5441
- this.active = settings;
5442
- const abort = new AbortController();
5443
- this.abort = abort;
5444
- this.setState("starting");
5445
- this.launchedAt = Date.now();
5446
- this.options.logger.info(`starting ${this.options.name} ${settings.version}`);
5447
- const failed = (how, error) => {
5448
- if (!current()) return;
5449
- const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
5450
- this.options.logger.error(`${this.options.name} ${cause}`);
5451
- this.crashed(null, "failed to start", cause);
5452
- };
5453
- this.options.prepare(settings, abort.signal).then(async (command) => {
5454
- if (!current()) return;
5455
- if (await portOpen(settings.host, settings.port)) {
5456
- if (!current()) return;
5457
- const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
5458
- this.options.logger.error(`${this.options.name}: ${cause}`);
5459
- this.crashed(null, "could not start", cause);
5460
- return;
5461
- }
5462
- if (current()) this.spawn(command, settings, generation);
5463
- }, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
5464
- }
5465
- spawn(command, settings, generation) {
5466
- const current = () => generation === this.generation;
5467
- const child = spawn(command.command, [...command.args], {
5468
- ...treeSpawnOptions,
5469
- stdio: [
5470
- "ignore",
5471
- "pipe",
5472
- "pipe"
5473
- ]
5474
- });
5475
- this.child = child;
5476
- trackTree(child);
5477
- pipeLines(child, this.options.output);
5478
- let exited = false;
5479
- let cause;
5480
- const onExit = (code, signal) => {
5481
- if (exited) return;
5482
- exited = true;
5483
- if (!current()) return;
5484
- this.child = null;
5485
- killTree(child);
5486
- const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
5487
- this.crashed(code, what, cause);
5488
- };
5489
- child.once("exit", onExit);
5490
- child.once("error", (error) => {
5491
- const failure = `could not be started: ${error.message}`;
5492
- this.options.logger.error(`${this.options.name} ${failure}`);
5493
- if (child.pid === void 0) {
5494
- cause = failure;
5495
- onExit(null, null);
5496
- }
5497
- });
5498
- this.waitForPort(settings, generation, () => exited).then((open) => {
5499
- if (!current() || exited) return;
5500
- if (open) {
5501
- this.runningSince = Date.now();
5502
- this.setState("running");
5503
- const seconds = ((Date.now() - this.launchedAt) / 1e3).toFixed(1);
5504
- this.options.logger.info(`${this.options.name} running (${seconds}s)`);
5505
- } else {
5506
- cause = `did not open port ${settings.port} in time`;
5507
- this.options.logger.error(`${this.options.name} ${cause}, killing it`);
5508
- killTree(child);
5509
- }
5568
+ // src/adapters/out/process/child-process-runner.ts
5569
+ function run(command, { output, hiddenEnv }) {
5570
+ const env = { ...process.env };
5571
+ for (const name of hiddenEnv ?? []) delete env[name];
5572
+ const child = spawn(command.command, [...command.args], {
5573
+ ...treeSpawnOptions,
5574
+ env,
5575
+ stdio: [
5576
+ "ignore",
5577
+ "pipe",
5578
+ "pipe"
5579
+ ]
5580
+ });
5581
+ trackTree(child);
5582
+ pipeLines(child, output);
5583
+ const exited = new Promise((resolve) => {
5584
+ child.once("exit", (code, signal) => resolve({
5585
+ code,
5586
+ signal
5587
+ }));
5588
+ child.on("error", (error) => {
5589
+ if (child.pid === void 0) resolve({
5590
+ code: null,
5591
+ signal: null,
5592
+ failure: error.message
5593
+ });
5594
+ else output.warn(`process error: ${error.message}`);
5510
5595
  });
5511
- }
5512
- async waitForPort(settings, generation, exited) {
5513
- const deadline = Date.now() + READY_TIMEOUT_MS;
5514
- while (generation === this.generation && !exited() && Date.now() < deadline) {
5515
- if (await portOpen(settings.host, settings.port)) return true;
5516
- await setTimeout$1(this.options.probeIntervalMs ?? 200);
5517
- }
5518
- return false;
5519
- }
5520
- /** `what` goes to the log, `cause` to the status. */
5521
- crashed(code, what, cause = what) {
5522
- const { name, logger } = this.options;
5523
- const ranForMs = this.runningSince === null ? 0 : Date.now() - this.runningSince;
5524
- this.runningSince = null;
5525
- this.exitCode = code;
5526
- this.lastError = cause;
5527
- const decision = nextAfterCrash(this.crashesInRow, ranForMs, this.options.policy);
5528
- this.crashesInRow = decision.crashesInRow;
5529
- if (decision.action === "fail") {
5530
- logger.error(`${name} ${what}, ${decision.crashesInRow} crashes in a row: giving up. Restart the bridge to try again`);
5531
- this.setState("failed");
5532
- return;
5533
- }
5534
- logger.error(`${name} ${what}, restart ${this.restarts + 1} in ${formatDelay(decision.delayMs)}`);
5535
- this.setState("crashed");
5536
- this.restartTimer = setTimeout(() => {
5537
- this.restarts++;
5538
- this.launch();
5539
- }, decision.delayMs);
5540
- }
5541
- };
5542
- function formatDelay(ms) {
5543
- return ms >= 1e3 ? `${ms / 1e3} s` : `${ms} ms`;
5596
+ });
5597
+ return {
5598
+ pid: child.pid ?? null,
5599
+ exited,
5600
+ kill: () => killTree(child)
5601
+ };
5602
+ }
5603
+ /** A child service as processes without a shell, whose whole tree `kill` ends. */
5604
+ function childProcessRunner(options) {
5605
+ return {
5606
+ prepare: async (settings, signal) => {
5607
+ const command = await options.prepare(settings, signal);
5608
+ return () => run(command, options);
5609
+ },
5610
+ portOpen
5611
+ };
5544
5612
  }
5545
5613
  // src/adapters/out/process/quiet-output.ts
5546
5614
  /**
@@ -5635,7 +5703,7 @@ function bundledMcp() {
5635
5703
  };
5636
5704
  }
5637
5705
  /**
5638
- * Supervisor for Playwright MCP in HTTP mode, the bundled version. Each start first runs
5706
+ * Playwright MCP in HTTP mode, the bundled version, as a child service. Each start first runs
5639
5707
  * `cli.js install-browser --no-shell chromium`, which installs the Chromium of MCP's own
5640
5708
  * Playwright and skips a build that is already there. It listens on loopback, and clients reach
5641
5709
  * it through the bridge, which sends a loopback `Host`: MCP's own host check (by default
@@ -5667,17 +5735,16 @@ function playwrightMcp(options) {
5667
5735
  ]
5668
5736
  };
5669
5737
  };
5670
- return new ChildProcessSupervisor({
5671
- name: "mcp",
5672
- settings: options.settings,
5673
- defaultVersion: version,
5674
- prepare: options.launch ?? prepare,
5675
- logger: options.logger,
5676
- output,
5677
- ...options.policy ? { policy: options.policy } : {}
5678
- });
5738
+ return {
5739
+ runner: childProcessRunner({
5740
+ prepare: options.launch ?? prepare,
5741
+ output,
5742
+ hiddenEnv: options.hiddenEnv
5743
+ }),
5744
+ defaultVersion: version
5745
+ };
5679
5746
  }
5680
- // src/domain/version.ts
5747
+ // src/adapters/out/npm/exact-version.ts
5681
5748
  /**
5682
5749
  * An exact npm version (`1.56.1`, `1.57.0-beta-1`). Versions end up on an `npm install` command
5683
5750
  * line (`playwright.version`, `adapters/out/npm`), so nothing else may get through.
@@ -5793,7 +5860,7 @@ async function ensurePlaywright(options) {
5793
5860
  * version (docs/usage/playwright-mcp.md#playwright-server).
5794
5861
  */
5795
5862
  const DEFAULT_PLAYWRIGHT_VERSION = "1.65.1";
5796
- /** Supervisor for `playwright run-server` in the configured version. */
5863
+ /** `playwright run-server` in the configured version, as a child service. */
5797
5864
  function playwrightServer(options) {
5798
5865
  const { cacheRoot } = options;
5799
5866
  const output = quietOutput(options.output, listeningLine);
@@ -5817,34 +5884,236 @@ function playwrightServer(options) {
5817
5884
  ]
5818
5885
  };
5819
5886
  };
5820
- return new ChildProcessSupervisor({
5821
- name: "playwright",
5822
- settings: options.settings,
5823
- defaultVersion: DEFAULT_PLAYWRIGHT_VERSION,
5824
- prepare: options.launch ?? prepare,
5825
- logger: options.logger,
5826
- output,
5827
- ...options.policy ? { policy: options.policy } : {}
5828
- });
5887
+ return {
5888
+ runner: childProcessRunner({
5889
+ prepare: options.launch ?? prepare,
5890
+ output,
5891
+ hiddenEnv: options.hiddenEnv
5892
+ }),
5893
+ defaultVersion: DEFAULT_PLAYWRIGHT_VERSION
5894
+ };
5895
+ }
5896
+ // src/application/services/supervised-service.ts
5897
+ /** How long the port may take to open after the start, before it counts as a crash. */
5898
+ const READY_TIMEOUT_MS = 6e4;
5899
+ /**
5900
+ * Runs one child service (docs/usage/operations.md#child-service-crashes): prepare, spawn, wait for
5901
+ * its port, restart after a crash with a growing delay, give up after too many crashes in a row,
5902
+ * and end the whole process tree on stop.
5903
+ */
5904
+ var SupervisedService = class {
5905
+ deps;
5906
+ /** Settings of the current run, until it is stopped. `status()` reports these. */
5907
+ active = null;
5908
+ state = "stopped";
5909
+ restarts = 0;
5910
+ exitCode = null;
5911
+ lastError = null;
5912
+ crashesInRow = 0;
5913
+ child = null;
5914
+ runningSince = null;
5915
+ /** When the current launch began, for the time to `running` in the log. */
5916
+ launchedAt = 0;
5917
+ /** Of the current launch: aborting it ends its preparation and its waits. */
5918
+ abort = null;
5919
+ /** Bumped by every launch and stop, so callbacks of an older run do nothing. */
5920
+ generation = 0;
5921
+ waiters = [];
5922
+ constructor(deps) {
5923
+ this.deps = deps;
5924
+ }
5925
+ pid() {
5926
+ return this.state === "running" ? this.child?.pid ?? null : null;
5927
+ }
5928
+ status() {
5929
+ const { version, port } = this.active ?? this.resolved();
5930
+ return {
5931
+ state: this.state,
5932
+ version,
5933
+ port,
5934
+ restarts: this.restarts,
5935
+ exitCode: this.exitCode,
5936
+ lastError: this.lastError
5937
+ };
5938
+ }
5939
+ start() {
5940
+ if (this.state === "running") return Promise.resolve();
5941
+ const settled = new Promise((resolve) => this.waiters.push(resolve));
5942
+ if (this.state === "stopped" || this.state === "failed") {
5943
+ this.restarts = 0;
5944
+ this.crashesInRow = 0;
5945
+ this.exitCode = null;
5946
+ this.lastError = null;
5947
+ this.launch();
5948
+ }
5949
+ return settled;
5950
+ }
5951
+ async stop() {
5952
+ this.generation++;
5953
+ this.abort?.abort();
5954
+ this.abort = null;
5955
+ const child = this.child;
5956
+ this.child = null;
5957
+ this.runningSince = null;
5958
+ this.active = null;
5959
+ const wasStopped = this.state === "stopped";
5960
+ this.setState("stopped");
5961
+ if (!wasStopped) this.deps.logger.info(`${this.deps.name} stopped`);
5962
+ if (child) await child.kill();
5963
+ }
5964
+ resolved() {
5965
+ const { host, port, version } = this.deps.settings;
5966
+ return {
5967
+ host,
5968
+ port,
5969
+ version: version ?? this.deps.defaultVersion
5970
+ };
5971
+ }
5972
+ setState(state) {
5973
+ this.state = state;
5974
+ if (state === "running" || state === "failed" || state === "stopped") for (const resolve of this.waiters.splice(0)) resolve();
5975
+ }
5976
+ launch() {
5977
+ const generation = ++this.generation;
5978
+ const current = () => generation === this.generation;
5979
+ const { name, runner, logger } = this.deps;
5980
+ const settings = this.resolved();
5981
+ this.active = settings;
5982
+ const abort = new AbortController();
5983
+ this.abort = abort;
5984
+ this.setState("starting");
5985
+ this.launchedAt = this.now();
5986
+ logger.info(`starting ${name} ${settings.version}`);
5987
+ const failed = (how, error) => {
5988
+ if (!current()) return;
5989
+ const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
5990
+ logger.error(`${name} ${cause}`);
5991
+ this.crashed(null, "failed to start", cause);
5992
+ };
5993
+ runner.prepare(settings, abort.signal).then(async (spawn) => {
5994
+ if (!current()) return;
5995
+ if (await runner.portOpen(settings.host, settings.port)) {
5996
+ if (!current()) return;
5997
+ const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
5998
+ logger.error(`${name}: ${cause}`);
5999
+ this.crashed(null, "could not start", cause);
6000
+ return;
6001
+ }
6002
+ if (current()) this.watch(spawn(), settings, generation, abort.signal);
6003
+ }, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
6004
+ }
6005
+ /** Follows a spawned child: until its port opens, and until it ends. */
6006
+ watch(child, settings, generation, signal) {
6007
+ const current = () => generation === this.generation;
6008
+ const { name, logger } = this.deps;
6009
+ this.child = child;
6010
+ let exited = false;
6011
+ let cause;
6012
+ child.exited.then(({ code, signal, failure }) => {
6013
+ exited = true;
6014
+ if (!current()) return;
6015
+ this.child = null;
6016
+ child.kill();
6017
+ if (failure !== void 0) {
6018
+ cause = `could not be started: ${failure}`;
6019
+ logger.error(`${name} ${cause}`);
6020
+ }
6021
+ const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
6022
+ this.crashed(code, what, cause);
6023
+ });
6024
+ this.waitForPort(settings, signal, () => exited).then((open) => {
6025
+ if (!current() || exited) return;
6026
+ if (open) {
6027
+ this.runningSince = this.now();
6028
+ this.setState("running");
6029
+ const seconds = ((this.now() - this.launchedAt) / 1e3).toFixed(1);
6030
+ logger.info(`${name} running (${seconds}s)`);
6031
+ } else {
6032
+ cause = `did not open port ${settings.port} in time`;
6033
+ logger.error(`${name} ${cause}, killing it`);
6034
+ child.kill();
6035
+ }
6036
+ });
6037
+ }
6038
+ async waitForPort(settings, signal, exited) {
6039
+ const { runner, clock, probeIntervalMs = 200 } = this.deps;
6040
+ const deadline = this.now() + READY_TIMEOUT_MS;
6041
+ while (!signal.aborted && !exited() && this.now() < deadline) {
6042
+ if (await runner.portOpen(settings.host, settings.port)) return true;
6043
+ await clock.sleep(probeIntervalMs, signal).catch(() => void 0);
6044
+ }
6045
+ return false;
6046
+ }
6047
+ /** `what` goes to the log, `cause` to the status. */
6048
+ crashed(code, what, cause = what) {
6049
+ const { name, logger, clock, policy } = this.deps;
6050
+ const ranForMs = this.runningSince === null ? 0 : this.now() - this.runningSince;
6051
+ this.runningSince = null;
6052
+ this.exitCode = code;
6053
+ this.lastError = cause;
6054
+ const decision = nextAfterCrash(this.crashesInRow, ranForMs, policy);
6055
+ this.crashesInRow = decision.crashesInRow;
6056
+ if (decision.action === "fail") {
6057
+ logger.error(`${name} ${what}, ${decision.crashesInRow} crashes in a row: giving up. Restart the bridge to try again`);
6058
+ this.setState("failed");
6059
+ return;
6060
+ }
6061
+ logger.error(`${name} ${what}, restart ${this.restarts + 1} in ${formatDelay(decision.delayMs)}`);
6062
+ this.setState("crashed");
6063
+ clock.sleep(decision.delayMs, this.abort?.signal).then(() => {
6064
+ this.restarts++;
6065
+ this.launch();
6066
+ }, () => void 0);
6067
+ }
6068
+ now() {
6069
+ return this.deps.clock.now().getTime();
6070
+ }
6071
+ };
6072
+ function formatDelay(ms) {
6073
+ return ms >= 1e3 ? `${ms / 1e3} s` : `${ms} ms`;
6074
+ }
6075
+ // src/composition/service-settings.ts
6076
+ /** A service's settings from the config: the Playwright server in the configured version, MCP in the bundled one. */
6077
+ function serviceSettings(name, config) {
6078
+ if (name === "playwright") {
6079
+ const { port, version } = config.playwright;
6080
+ return {
6081
+ host: CHILD_HOST,
6082
+ port,
6083
+ version
6084
+ };
6085
+ }
6086
+ return {
6087
+ host: CHILD_HOST,
6088
+ port: config.mcp.port,
6089
+ version: null
6090
+ };
5829
6091
  }
5830
6092
  // src/composition/services.ts
5831
6093
  /** One supervisor per child service, not started yet (`ChildServicesService` runs them). */
5832
- function createSupervisors(config, options, log) {
6094
+ function createSupervisors(config, options, log, clock) {
5833
6095
  const logger = log.for("bridge");
6096
+ const supervise = (name, program) => new SupervisedService({
6097
+ name,
6098
+ settings: serviceSettings(name, config),
6099
+ ...program,
6100
+ clock,
6101
+ logger
6102
+ });
6103
+ const playwright = playwrightServer({
6104
+ cacheRoot: options.playwrightDir ?? defaultPlaywrightDir(),
6105
+ output: log.for("playwright-server"),
6106
+ hiddenEnv: UI_ENV_NAMES,
6107
+ ...options.playwrightLaunch ? { launch: options.playwrightLaunch } : {}
6108
+ });
6109
+ const mcp = playwrightMcp({
6110
+ output: log.for("playwright-mcp"),
6111
+ hiddenEnv: UI_ENV_NAMES,
6112
+ ...options.mcpLaunch ? { launch: options.mcpLaunch } : {}
6113
+ });
5834
6114
  return {
5835
- playwright: playwrightServer({
5836
- settings: serviceSettings("playwright", config),
5837
- cacheRoot: options.playwrightDir ?? defaultPlaywrightDir(),
5838
- logger,
5839
- output: log.for("playwright-server"),
5840
- ...options.playwrightLaunch ? { launch: options.playwrightLaunch } : {}
5841
- }),
5842
- mcp: playwrightMcp({
5843
- settings: serviceSettings("mcp", config),
5844
- logger,
5845
- output: log.for("playwright-mcp"),
5846
- ...options.mcpLaunch ? { launch: options.mcpLaunch } : {}
5847
- })
6115
+ playwright: supervise("playwright", playwright),
6116
+ mcp: supervise("mcp", mcp)
5848
6117
  };
5849
6118
  }
5850
6119
  // src/domain/capture.ts
@@ -5986,6 +6255,9 @@ var SeqQueue = class {
5986
6255
  * - At most one session is current. The log keeps the current session and the ended ones with
5987
6256
  * entries still in the buffer; an ended session is forgotten once its last entry is dropped or
5988
6257
  * cleared, and `id`s are never given out twice.
6258
+ * - Every change is reported to `onEvent`, once the log is in its new state, so no caller can
6259
+ * forget it. Deleting a session reports nothing
6260
+ * (docs/implementation/decisions.md#deleting-a-session-is-a-400-for-the-current-one-and-sends-no-event).
5989
6261
  *
5990
6262
  * Adding, dropping and the session statistics are O(1), reading after a `seq` is O(log n).
5991
6263
  */
@@ -6007,7 +6279,10 @@ var SpeechLog = class {
6007
6279
  #currentId = null;
6008
6280
  /** The newest session id given out, `runStart - 1` before the first session. */
6009
6281
  #lastSessionId;
6010
- constructor(maxEntries, runStart = 1) {
6282
+ #onEvent;
6283
+ /** @param onEvent Gets every change (the composition root publishes it on the event bus). */
6284
+ constructor(maxEntries, runStart = 1, onEvent = () => {}) {
6285
+ this.#onEvent = onEvent;
6011
6286
  this.#maxEntries = maxEntries;
6012
6287
  this.#runStart = runStart;
6013
6288
  this.#nextSeq = runStart;
@@ -6027,10 +6302,15 @@ var SpeechLog = class {
6027
6302
  get lastSpeechAt() {
6028
6303
  return this.#lastSpeechAt;
6029
6304
  }
6030
- /** Stores an entry in the current session (if any) and returns it with its `seq`. */
6305
+ /**
6306
+ * Stores an entry in the current session (if any) and returns it with its `seq`. A marker's text
6307
+ * is a label (`markerLabel`): trimmed, `INVALID_REQUEST` if empty or too long.
6308
+ */
6031
6309
  append(draft) {
6310
+ const text = draft.kind === "marker" ? markerLabel(draft.text) : draft.text;
6032
6311
  const entry = {
6033
6312
  ...draft,
6313
+ text,
6034
6314
  seq: this.#nextSeq++,
6035
6315
  sessionId: this.#currentId
6036
6316
  };
@@ -6043,6 +6323,10 @@ var SpeechLog = class {
6043
6323
  own.push(entry);
6044
6324
  if (entry.kind === "speech") this.#lastSpeechAt = entry.receivedAt;
6045
6325
  this.#trim();
6326
+ this.#onEvent({
6327
+ type: "entry",
6328
+ entry
6329
+ });
6046
6330
  return entry;
6047
6331
  }
6048
6332
  /**
@@ -6069,7 +6353,8 @@ var SpeechLog = class {
6069
6353
  * session (`null`: outside sessions). `undefined` if there is none (also when it was dropped).
6070
6354
  */
6071
6355
  latestMarker(label, sessionId) {
6072
- return (sessionId === void 0 ? this.#entries : this.#bySession.get(sessionId))?.findLast((entry) => entry.kind === "marker" && entry.text === label);
6356
+ const text = markerLabel(label);
6357
+ return (sessionId === void 0 ? this.#entries : this.#bySession.get(sessionId))?.findLast((entry) => entry.kind === "marker" && entry.text === text);
6073
6358
  }
6074
6359
  /**
6075
6360
  * Removes the entries (and markers) of the current session or of the entries outside sessions
@@ -6084,6 +6369,10 @@ var SpeechLog = class {
6084
6369
  this.#entries.removeWhere((entry) => entry.sessionId === scope);
6085
6370
  this.#bySession.delete(scope);
6086
6371
  this.#droppedBySession.delete(scope);
6372
+ this.#onEvent({
6373
+ type: "clear",
6374
+ sessionId: scope
6375
+ });
6087
6376
  return scope;
6088
6377
  }
6089
6378
  /** Removes all entries and the ended sessions. The current session stays current. */
@@ -6093,6 +6382,7 @@ var SpeechLog = class {
6093
6382
  this.#droppedUpToSeq = 0;
6094
6383
  this.#droppedBySession.clear();
6095
6384
  for (const session of this.#sessions.values()) if (session.endedAt !== null) this.#sessions.delete(session.id);
6385
+ this.#onEvent({ type: "clear" });
6096
6386
  }
6097
6387
  stats() {
6098
6388
  return {
@@ -6102,20 +6392,38 @@ var SpeechLog = class {
6102
6392
  lastSeq: this.#entries.last()?.seq ?? null
6103
6393
  };
6104
6394
  }
6105
- /** Ends the current session, if any, and starts a new current one. */
6395
+ /**
6396
+ * Ends the current session, if any, and starts a new current one. Its `name`, `run` and `client`
6397
+ * are labels (`sessionLabel`): trimmed, `INVALID_REQUEST` if empty or too long.
6398
+ */
6106
6399
  startSession(session) {
6107
- const ended = this.endSession(session.startedAt);
6400
+ const name = sessionLabel("name", session.name);
6401
+ const run = session.run === null ? null : sessionLabel("run", session.run);
6402
+ const client = session.client === null ? null : sessionLabel("client", session.client);
6403
+ const ended = this.#end(session.startedAt);
6108
6404
  const started = {
6109
6405
  ...session,
6406
+ name,
6407
+ run,
6408
+ client,
6110
6409
  id: ++this.#lastSessionId,
6111
6410
  endedAt: null,
6112
6411
  startSeq: this.headSeq
6113
6412
  };
6114
6413
  this.#sessions.set(started.id, started);
6115
6414
  this.#currentId = started.id;
6415
+ const summary = summarize(started, EMPTY_SESSION_STATS);
6416
+ if (ended) this.#onEvent({
6417
+ type: "session",
6418
+ session: ended
6419
+ });
6420
+ this.#onEvent({
6421
+ type: "session",
6422
+ session: summary
6423
+ });
6116
6424
  return {
6117
6425
  ended,
6118
- started: summarize(started, EMPTY_SESSION_STATS)
6426
+ started: summary
6119
6427
  };
6120
6428
  }
6121
6429
  /**
@@ -6124,6 +6432,15 @@ var SpeechLog = class {
6124
6432
  * never gave out.
6125
6433
  */
6126
6434
  endSession(endedAt, id) {
6435
+ const ended = this.#end(endedAt, id);
6436
+ if (ended) this.#onEvent({
6437
+ type: "session",
6438
+ session: ended
6439
+ });
6440
+ return ended;
6441
+ }
6442
+ /** {@link endSession} without reporting it, for a change that isn't complete yet. */
6443
+ #end(endedAt, id) {
6127
6444
  if (id !== void 0) this.#requireIssued(id);
6128
6445
  const current = this.currentSession();
6129
6446
  if (!current || id !== void 0 && current.id !== id) return null;
@@ -6224,7 +6541,6 @@ async function flushOutput() {
6224
6541
  await flushTerminal();
6225
6542
  await flushConsole();
6226
6543
  }
6227
- const show = (value) => JSON.stringify(value);
6228
6544
  /** A busy port needs no stack: the message says what to do. Anything else is unexpected. */
6229
6545
  function describeStartFailure(error) {
6230
6546
  if (error instanceof ListenError || error instanceof PortUnavailableError) return error.message;
@@ -6239,8 +6555,7 @@ async function startBridge(options) {
6239
6555
  const { version } = options;
6240
6556
  const seams = options.testSeams ?? {};
6241
6557
  const store = seams.configStore ?? new FsConfigStore(options.configFile ?? defaultConfigFile());
6242
- const sourceOf = (field) => options.overrideSources?.get(field) ?? "a flag or environment variable";
6243
- const { config, file: savedFile, overrides, unknown: unknownSettings, ignored, warnings } = await loadConfig(store, options.overrides, sourceOf);
6558
+ const { config, file: savedFile, unknownSettings, pinned, warnings } = await loadConfig(store, options.overrides, options.overrideSources);
6244
6559
  const log = createLogging(config, {
6245
6560
  version,
6246
6561
  configLocation: store.location,
@@ -6249,13 +6564,11 @@ async function startBridge(options) {
6249
6564
  const bridgeLogger = log.for("bridge");
6250
6565
  const configLogger = log.for("config");
6251
6566
  for (const warning of warnings) configLogger.warn(warning);
6252
- for (const name of ignored) configLogger.warn(`${name}: unknown setting in ${store.location}, ignored`);
6253
- for (const { field, file: saved, override } of overriddenFields(savedFile, overrides)) configLogger.warn(`${field}: the config file sets ${show(saved)}, but ${sourceOf(field)} sets ${show(override)}, which wins`);
6254
6567
  try {
6255
6568
  const clock = seams.clock ?? new SystemClock();
6256
6569
  const startedAt = clock.now();
6257
- const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
6258
6570
  const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
6571
+ const speechLog = new SpeechLog(config.buffer.maxEntries, firstSeqOfRun(startedAt.getTime()), (event) => events.publish(event));
6259
6572
  new TranscriptService({
6260
6573
  events,
6261
6574
  transcript: log.for("speech-capture", { channel: "speech" })
@@ -6276,20 +6589,24 @@ async function startBridge(options) {
6276
6589
  });
6277
6590
  const sessions = new SessionService({
6278
6591
  log: speechLog,
6279
- events,
6280
6592
  clock,
6281
6593
  logger: log.for("bridge")
6282
6594
  });
6283
6595
  const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
6284
6596
  const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
6285
- const supervisors = createSupervisors(config, seams, log);
6597
+ const supervisors = createSupervisors(config, seams, log, clock);
6598
+ const inputQueue = new SerialInputQueue({
6599
+ shutdown: shutdown.signal,
6600
+ logger: log.for("native-input")
6601
+ });
6286
6602
  const input = new NativeInputService({
6603
+ queue: inputQueue,
6287
6604
  injector,
6288
6605
  windows,
6289
6606
  services: supervisors,
6290
6607
  clock,
6291
- logger: log.for("native-input"),
6292
- shutdown: shutdown.signal
6608
+ log: speechLog,
6609
+ logger: log.for("native-input")
6293
6610
  });
6294
6611
  const captures = new InputCaptureService({
6295
6612
  input,
@@ -6305,23 +6622,23 @@ async function startBridge(options) {
6305
6622
  active: config,
6306
6623
  file: savedFile,
6307
6624
  unknownSettings,
6308
- pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
6625
+ pinned
6309
6626
  });
6310
6627
  const focus = new WindowFocusService({
6311
6628
  windows,
6312
- queue: input,
6629
+ queue: inputQueue,
6313
6630
  services: supervisors,
6314
6631
  clock,
6632
+ log: speechLog,
6315
6633
  logger: log.for("native-input")
6316
6634
  });
6317
6635
  const childServices = new ChildServicesService({
6318
6636
  supervisors,
6319
- config: () => configService.get(),
6320
- logger: bridgeLogger
6637
+ config: () => configService.get()
6321
6638
  });
6322
6639
  const captureState = new CaptureState(() => clock.now());
6323
6640
  const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
6324
- const prompt = seams.prompt === void 0 ? createOperatorPrompt(options.cancelStart) : seams.prompt;
6641
+ const prompt = seams.prompt === void 0 ? createOperatorPrompt((message) => configLogger.warn(message), options.cancelStart) : seams.prompt;
6325
6642
  const tcpStartup = new TcpStartupService({
6326
6643
  listener: {
6327
6644
  start: (port) => tcp.start({
@@ -6331,12 +6648,13 @@ async function startBridge(options) {
6331
6648
  stop: () => tcp.stop()
6332
6649
  },
6333
6650
  config: configService,
6334
- ...configFields(overrides).has("tcp.port") ? { pinnedBy: sourceOf("tcp.port") } : {},
6651
+ hints: tcpStartupHints(store.location, pinned.get("tcp.port")),
6335
6652
  ...prompt === null || prompt === void 0 ? {} : { prompt },
6336
6653
  configLocation: store.location,
6337
6654
  logger: configLogger
6338
6655
  });
6339
6656
  const status = new StatusService({
6657
+ state: () => lifecycle.state(),
6340
6658
  capture: captureState,
6341
6659
  log: speechLog,
6342
6660
  supervisors,
@@ -6364,7 +6682,6 @@ async function startBridge(options) {
6364
6682
  ...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
6365
6683
  });
6366
6684
  const lifecycle = new BridgeLifecycleService({
6367
- state: status,
6368
6685
  tcp: tcpStartup,
6369
6686
  http: {
6370
6687
  start: () => http.start(config.http),
@@ -6376,7 +6693,7 @@ async function startBridge(options) {
6376
6693
  readyMessage: (ports) => readySummary({
6377
6694
  config: configService.get(),
6378
6695
  ports,
6379
- supervisors,
6696
+ services: status.status().services,
6380
6697
  webUi: ui !== void 0,
6381
6698
  nativeInput: injector.availability,
6382
6699
  tookMs: clock.now().getTime() - startedAt.getTime()