@screenreader-speech-capture/bridge 0.1.0 → 0.2.1

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 (236) hide show
  1. package/dist/cli.mjs +1292 -791
  2. package/dist/ui/adapter-node.js +1 -1
  3. package/dist/ui/client/ui/_app/immutable/assets/{4.DyY1vjRV.css → 4.DEk4yqpA.css} +1 -1
  4. package/dist/ui/client/ui/_app/immutable/assets/4.DEk4yqpA.css.br +0 -0
  5. package/dist/ui/client/ui/_app/immutable/assets/4.DEk4yqpA.css.gz +0 -0
  6. package/dist/ui/client/ui/_app/immutable/chunks/BEImj5AP.js +1 -0
  7. package/dist/ui/client/ui/_app/immutable/chunks/BEImj5AP.js.br +0 -0
  8. package/dist/ui/client/ui/_app/immutable/chunks/BEImj5AP.js.gz +0 -0
  9. package/dist/ui/client/ui/_app/immutable/chunks/BLbj0ykL.js +1 -0
  10. package/dist/ui/client/ui/_app/immutable/chunks/BLbj0ykL.js.br +0 -0
  11. package/dist/ui/client/ui/_app/immutable/chunks/BLbj0ykL.js.gz +0 -0
  12. package/dist/ui/client/ui/_app/immutable/chunks/B__KpOuX.js +3 -0
  13. package/dist/ui/client/ui/_app/immutable/chunks/B__KpOuX.js.br +0 -0
  14. package/dist/ui/client/ui/_app/immutable/chunks/B__KpOuX.js.gz +0 -0
  15. package/dist/ui/client/ui/_app/immutable/chunks/BkoDSEOx.js +1 -0
  16. package/dist/ui/client/ui/_app/immutable/chunks/BkoDSEOx.js.br +0 -0
  17. package/dist/ui/client/ui/_app/immutable/chunks/BkoDSEOx.js.gz +0 -0
  18. package/dist/ui/client/ui/_app/immutable/chunks/BlC5mir6.js +1 -0
  19. package/dist/ui/client/ui/_app/immutable/chunks/BlC5mir6.js.br +2 -0
  20. package/dist/ui/client/ui/_app/immutable/chunks/BlC5mir6.js.gz +0 -0
  21. package/dist/ui/client/ui/_app/immutable/chunks/BquQTeuV.js +1 -0
  22. package/dist/ui/client/ui/_app/immutable/chunks/BquQTeuV.js.br +0 -0
  23. package/dist/ui/client/ui/_app/immutable/chunks/BquQTeuV.js.gz +0 -0
  24. package/dist/ui/client/ui/_app/immutable/chunks/BtnuBvK5.js +1 -0
  25. package/dist/ui/client/ui/_app/immutable/chunks/BtnuBvK5.js.br +1 -0
  26. package/dist/ui/client/ui/_app/immutable/chunks/BtnuBvK5.js.gz +0 -0
  27. package/dist/ui/client/ui/_app/immutable/chunks/{BrPqgVT6.js → BuwZGWCm.js} +21 -21
  28. package/dist/ui/client/ui/_app/immutable/chunks/BuwZGWCm.js.br +0 -0
  29. package/dist/ui/client/ui/_app/immutable/chunks/BuwZGWCm.js.gz +0 -0
  30. package/dist/ui/client/ui/_app/immutable/chunks/Bxh3K0TK.js +1 -0
  31. package/dist/ui/client/ui/_app/immutable/chunks/Bxh3K0TK.js.br +0 -0
  32. package/dist/ui/client/ui/_app/immutable/chunks/Bxh3K0TK.js.gz +0 -0
  33. package/dist/ui/client/ui/_app/immutable/chunks/C06IiL6m.js +1 -0
  34. package/dist/ui/client/ui/_app/immutable/chunks/C06IiL6m.js.br +2 -0
  35. package/dist/ui/client/ui/_app/immutable/chunks/C06IiL6m.js.gz +0 -0
  36. package/dist/ui/client/ui/_app/immutable/chunks/CAZ56n62.js +3 -0
  37. package/dist/ui/client/ui/_app/immutable/chunks/CAZ56n62.js.br +0 -0
  38. package/dist/ui/client/ui/_app/immutable/chunks/CAZ56n62.js.gz +0 -0
  39. package/dist/ui/client/ui/_app/immutable/chunks/CTnnxqUD.js +1 -0
  40. package/dist/ui/client/ui/_app/immutable/chunks/CTnnxqUD.js.br +0 -0
  41. package/dist/ui/client/ui/_app/immutable/chunks/CTnnxqUD.js.gz +0 -0
  42. package/dist/ui/client/ui/_app/immutable/chunks/DRNNJMYk.js +5 -0
  43. package/dist/ui/client/ui/_app/immutable/chunks/DRNNJMYk.js.br +0 -0
  44. package/dist/ui/client/ui/_app/immutable/chunks/DRNNJMYk.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/{C7D7xLuA.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/R_4U_-zb.js +33 -0
  52. package/dist/ui/client/ui/_app/immutable/chunks/R_4U_-zb.js.br +0 -0
  53. package/dist/ui/client/ui/_app/immutable/chunks/R_4U_-zb.js.gz +0 -0
  54. package/dist/ui/client/ui/_app/immutable/chunks/UKukklIc.js +1 -0
  55. package/dist/ui/client/ui/_app/immutable/chunks/UKukklIc.js.br +2 -0
  56. package/dist/ui/client/ui/_app/immutable/chunks/UKukklIc.js.gz +0 -0
  57. package/dist/ui/client/ui/_app/immutable/chunks/{KD5R77Wj.js → VxDST09k.js} +1 -1
  58. package/dist/ui/client/ui/_app/immutable/chunks/VxDST09k.js.br +0 -0
  59. package/dist/ui/client/ui/_app/immutable/chunks/VxDST09k.js.gz +0 -0
  60. package/dist/ui/client/ui/_app/immutable/chunks/{D9JU-e3z.js → vPs9G1oN.js} +36 -36
  61. package/dist/ui/client/ui/_app/immutable/chunks/vPs9G1oN.js.br +0 -0
  62. package/dist/ui/client/ui/_app/immutable/chunks/vPs9G1oN.js.gz +0 -0
  63. package/dist/ui/client/ui/_app/immutable/chunks/{Cc902J0D.js → w5i9ZoX_.js} +2 -2
  64. package/dist/ui/client/ui/_app/immutable/chunks/w5i9ZoX_.js.br +0 -0
  65. package/dist/ui/client/ui/_app/immutable/chunks/w5i9ZoX_.js.gz +0 -0
  66. package/dist/ui/client/ui/_app/immutable/entry/app.CHExvln1.js +2 -0
  67. package/dist/ui/client/ui/_app/immutable/entry/app.CHExvln1.js.br +0 -0
  68. package/dist/ui/client/ui/_app/immutable/entry/app.CHExvln1.js.gz +0 -0
  69. package/dist/ui/client/ui/_app/immutable/entry/start.4hiWLKwq.js +2 -0
  70. package/dist/ui/client/ui/_app/immutable/entry/start.4hiWLKwq.js.br +0 -0
  71. package/dist/ui/client/ui/_app/immutable/entry/start.4hiWLKwq.js.gz +0 -0
  72. package/dist/ui/client/ui/_app/immutable/nodes/0.DENUQERM.js +1 -0
  73. package/dist/ui/client/ui/_app/immutable/nodes/0.DENUQERM.js.br +0 -0
  74. package/dist/ui/client/ui/_app/immutable/nodes/0.DENUQERM.js.gz +0 -0
  75. package/dist/ui/client/ui/_app/immutable/nodes/1.BBl7b45u.js +1 -0
  76. package/dist/ui/client/ui/_app/immutable/nodes/1.BBl7b45u.js.br +0 -0
  77. package/dist/ui/client/ui/_app/immutable/nodes/1.BBl7b45u.js.gz +0 -0
  78. package/dist/ui/client/ui/_app/immutable/nodes/2.4VpydhMh.js +1 -0
  79. package/dist/ui/client/ui/_app/immutable/nodes/2.4VpydhMh.js.br +0 -0
  80. package/dist/ui/client/ui/_app/immutable/nodes/2.4VpydhMh.js.gz +0 -0
  81. package/dist/ui/client/ui/_app/immutable/nodes/3.D9AmPYb5.js +5 -0
  82. package/dist/ui/client/ui/_app/immutable/nodes/3.D9AmPYb5.js.br +0 -0
  83. package/dist/ui/client/ui/_app/immutable/nodes/3.D9AmPYb5.js.gz +0 -0
  84. package/dist/ui/client/ui/_app/immutable/nodes/4.DxNIrNp_.js +180 -0
  85. package/dist/ui/client/ui/_app/immutable/nodes/4.DxNIrNp_.js.br +0 -0
  86. package/dist/ui/client/ui/_app/immutable/nodes/4.DxNIrNp_.js.gz +0 -0
  87. package/dist/ui/client/ui/_app/immutable/nodes/5.Cm6I95kb.js +6 -0
  88. package/dist/ui/client/ui/_app/immutable/nodes/5.Cm6I95kb.js.br +0 -0
  89. package/dist/ui/client/ui/_app/immutable/nodes/5.Cm6I95kb.js.gz +0 -0
  90. package/dist/ui/client/ui/_app/immutable/nodes/6.D9jpgBJB.js +6 -0
  91. package/dist/ui/client/ui/_app/immutable/nodes/6.D9jpgBJB.js.br +0 -0
  92. package/dist/ui/client/ui/_app/immutable/nodes/6.D9jpgBJB.js.gz +0 -0
  93. package/dist/ui/client/ui/_app/version.json +1 -1
  94. package/dist/ui/client/ui/_app/version.json.br +0 -0
  95. package/dist/ui/client/ui/_app/version.json.gz +0 -0
  96. package/dist/ui/server/.vite/manifest.json +80 -59
  97. package/dist/ui/server/_app/immutable/assets/{_page.DyY1vjRV.css → _page.DEk4yqpA.css} +1 -1
  98. package/dist/ui/server/chunks/{composition.js → app-context.js} +50 -958
  99. package/dist/ui/server/chunks/app-context.js.map +1 -0
  100. package/dist/ui/server/chunks/config2.js +106 -0
  101. package/dist/ui/server/chunks/config2.js.map +1 -0
  102. package/dist/ui/server/chunks/dialog.js +1 -1
  103. package/dist/ui/server/chunks/instance.js +3 -3
  104. package/dist/ui/server/chunks/internal.js +1 -1
  105. package/dist/ui/server/chunks/outlined-button.js +116 -0
  106. package/dist/ui/server/chunks/outlined-button.js.map +1 -0
  107. package/dist/ui/server/chunks/outlined-text-field.js +1 -1
  108. package/dist/ui/server/chunks/redispatch-event.js +1 -1
  109. package/dist/ui/server/chunks/rolldown-runtime.js +12 -0
  110. package/dist/ui/server/chunks/rules.js +178 -0
  111. package/dist/ui/server/chunks/rules.js.map +1 -0
  112. package/dist/ui/server/chunks/sessions.remote.js +1 -11
  113. package/dist/ui/server/chunks/sessions.remote.js.map +1 -1
  114. package/dist/ui/server/chunks/setup.js +86 -0
  115. package/dist/ui/server/chunks/setup.js.map +1 -0
  116. package/dist/ui/server/chunks/{icon-button.js → speech.js} +42 -3
  117. package/dist/ui/server/chunks/speech.js.map +1 -0
  118. package/dist/ui/server/chunks/src.js +20 -155
  119. package/dist/ui/server/chunks/src.js.map +1 -1
  120. package/dist/ui/server/chunks/static-html.js +1 -1
  121. package/dist/ui/server/chunks/text-button.js +1 -1
  122. package/dist/ui/server/chunks/vocabulary.js +19 -0
  123. package/dist/ui/server/chunks/vocabulary.js.map +1 -0
  124. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js +3 -2
  125. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js.map +1 -1
  126. package/dist/ui/server/entries/endpoints/api/input/keys/_server.ts.js +14 -5
  127. package/dist/ui/server/entries/endpoints/api/input/keys/_server.ts.js.map +1 -1
  128. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js +3 -2
  129. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js.map +1 -1
  130. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js +2 -1
  131. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js.map +1 -1
  132. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js +10 -13
  133. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js.map +1 -1
  134. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js +2 -1
  135. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js.map +1 -1
  136. package/dist/ui/server/entries/hooks.server.js +29 -25
  137. package/dist/ui/server/entries/hooks.server.js.map +1 -1
  138. package/dist/ui/server/entries/pages/_layout.svelte.js +749 -4
  139. package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
  140. package/dist/ui/server/entries/pages/_page.svelte.js +34 -26
  141. package/dist/ui/server/entries/pages/_page.svelte.js.map +1 -1
  142. package/dist/ui/server/entries/pages/settings/_page.svelte.js +143 -15
  143. package/dist/ui/server/entries/pages/settings/_page.svelte.js.map +1 -1
  144. package/dist/ui/server/entries/pages/setup/_page.svelte.js +3 -3
  145. package/dist/ui/server/entries/pages/setup/_page.svelte.js.map +1 -1
  146. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js +16 -10
  147. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js.map +1 -1
  148. package/dist/ui/server/manifest-full.js +1 -1
  149. package/dist/ui/server/manifest.js +1 -1
  150. package/dist/ui/server/nodes/0.js +1 -1
  151. package/dist/ui/server/nodes/1.js +1 -1
  152. package/dist/ui/server/nodes/2.js +1 -1
  153. package/dist/ui/server/nodes/3.js +1 -1
  154. package/dist/ui/server/nodes/4.js +2 -2
  155. package/dist/ui/server/nodes/5.js +1 -1
  156. package/dist/ui/server/nodes/6.js +1 -1
  157. package/dist/ui/server/server.js +1 -1
  158. package/package.json +1 -1
  159. package/dist/ui/client/ui/_app/immutable/assets/4.DyY1vjRV.css.br +0 -0
  160. package/dist/ui/client/ui/_app/immutable/assets/4.DyY1vjRV.css.gz +0 -0
  161. package/dist/ui/client/ui/_app/immutable/chunks/0FroJ-XN.js +0 -3
  162. package/dist/ui/client/ui/_app/immutable/chunks/0FroJ-XN.js.br +0 -0
  163. package/dist/ui/client/ui/_app/immutable/chunks/0FroJ-XN.js.gz +0 -0
  164. package/dist/ui/client/ui/_app/immutable/chunks/B_ZElYu_.js +0 -1
  165. package/dist/ui/client/ui/_app/immutable/chunks/B_ZElYu_.js.br +0 -2
  166. package/dist/ui/client/ui/_app/immutable/chunks/B_ZElYu_.js.gz +0 -0
  167. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js +0 -2
  168. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js.br +0 -0
  169. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js.gz +0 -0
  170. package/dist/ui/client/ui/_app/immutable/chunks/BrPqgVT6.js.br +0 -0
  171. package/dist/ui/client/ui/_app/immutable/chunks/BrPqgVT6.js.gz +0 -0
  172. package/dist/ui/client/ui/_app/immutable/chunks/C7D7xLuA.js.br +0 -0
  173. package/dist/ui/client/ui/_app/immutable/chunks/C7D7xLuA.js.gz +0 -0
  174. package/dist/ui/client/ui/_app/immutable/chunks/CVpgcnu3.js +0 -1
  175. package/dist/ui/client/ui/_app/immutable/chunks/CVpgcnu3.js.br +0 -0
  176. package/dist/ui/client/ui/_app/immutable/chunks/CVpgcnu3.js.gz +0 -0
  177. package/dist/ui/client/ui/_app/immutable/chunks/Cc902J0D.js.br +0 -0
  178. package/dist/ui/client/ui/_app/immutable/chunks/Cc902J0D.js.gz +0 -0
  179. package/dist/ui/client/ui/_app/immutable/chunks/D-2Nx62w.js +0 -1
  180. package/dist/ui/client/ui/_app/immutable/chunks/D-2Nx62w.js.br +0 -4
  181. package/dist/ui/client/ui/_app/immutable/chunks/D-2Nx62w.js.gz +0 -0
  182. package/dist/ui/client/ui/_app/immutable/chunks/D9JU-e3z.js.br +0 -0
  183. package/dist/ui/client/ui/_app/immutable/chunks/D9JU-e3z.js.gz +0 -0
  184. package/dist/ui/client/ui/_app/immutable/chunks/DHsTyp2W.js +0 -1
  185. package/dist/ui/client/ui/_app/immutable/chunks/DHsTyp2W.js.br +0 -2
  186. package/dist/ui/client/ui/_app/immutable/chunks/DHsTyp2W.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/KD5R77Wj.js.br +0 -0
  194. package/dist/ui/client/ui/_app/immutable/chunks/KD5R77Wj.js.gz +0 -0
  195. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js +0 -3
  196. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js.br +0 -0
  197. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js.gz +0 -0
  198. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js +0 -33
  199. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js.br +0 -0
  200. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js.gz +0 -0
  201. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js +0 -4
  202. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js.br +0 -0
  203. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js.gz +0 -0
  204. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js +0 -2
  205. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js.br +0 -0
  206. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js.gz +0 -0
  207. package/dist/ui/client/ui/_app/immutable/entry/start.DqIv9xYX.js +0 -2
  208. package/dist/ui/client/ui/_app/immutable/entry/start.DqIv9xYX.js.br +0 -0
  209. package/dist/ui/client/ui/_app/immutable/entry/start.DqIv9xYX.js.gz +0 -0
  210. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js +0 -1
  211. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js.br +0 -0
  212. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js.gz +0 -0
  213. package/dist/ui/client/ui/_app/immutable/nodes/1.C81neQJL.js +0 -1
  214. package/dist/ui/client/ui/_app/immutable/nodes/1.C81neQJL.js.br +0 -0
  215. package/dist/ui/client/ui/_app/immutable/nodes/1.C81neQJL.js.gz +0 -0
  216. package/dist/ui/client/ui/_app/immutable/nodes/2.CmlyeAx_.js +0 -1
  217. package/dist/ui/client/ui/_app/immutable/nodes/2.CmlyeAx_.js.br +0 -0
  218. package/dist/ui/client/ui/_app/immutable/nodes/2.CmlyeAx_.js.gz +0 -0
  219. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js +0 -5
  220. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js.br +0 -0
  221. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js.gz +0 -0
  222. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js +0 -160
  223. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js.br +0 -0
  224. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js.gz +0 -0
  225. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js +0 -6
  226. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js.br +0 -0
  227. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js.gz +0 -0
  228. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js +0 -6
  229. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js.br +0 -0
  230. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js.gz +0 -0
  231. package/dist/ui/server/chunks/composition.js.map +0 -1
  232. package/dist/ui/server/chunks/filled-button.js +0 -116
  233. package/dist/ui/server/chunks/filled-button.js.map +0 -1
  234. package/dist/ui/server/chunks/icon-button.js.map +0 -1
  235. package/dist/ui/server/chunks/icon.js +0 -49
  236. package/dist/ui/server/chunks/icon.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";
@@ -13,8 +13,9 @@ import path from "node:path";
13
13
  import { Worker } from "node:worker_threads";
14
14
  import { execFile, spawn, spawnSync } from "node:child_process";
15
15
  import readline from "node:readline";
16
+ import { createInterface } from "node:readline/promises";
16
17
  // package.json
17
- var version = "0.1.0";
18
+ var version = "0.2.1";
18
19
  // ../shared/src/api-version.ts
19
20
  /**
20
21
  * `<major>.<minor>` of the HTTP API. Minor versions only add things, with the exceptions in
@@ -956,6 +957,33 @@ const FocusRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
956
957
  * chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
957
958
  * so both use this one copy. Like `text-match.ts`, it belongs to the contract, not to either side.
958
959
  */
960
+ const DIGITS = [
961
+ "0",
962
+ "1",
963
+ "2",
964
+ "3",
965
+ "4",
966
+ "5",
967
+ "6",
968
+ "7",
969
+ "8",
970
+ "9"
971
+ ];
972
+ const FUNCTION_KEYS = [
973
+ "f1",
974
+ "f2",
975
+ "f3",
976
+ "f4",
977
+ "f5",
978
+ "f6",
979
+ "f7",
980
+ "f8",
981
+ "f9",
982
+ "f10",
983
+ "f11",
984
+ "f12"
985
+ ];
986
+ const LETTERS = "abcdefghijklmnopqrstuvwxyz".split("");
959
987
  /** Keys that can be held down while another key is pressed. `Insert` and `CapsLock` are the screen reader keys. */
960
988
  const MODIFIER_KEYS = [
961
989
  "control",
@@ -970,7 +998,7 @@ const MODIFIER_KEYS = [
970
998
  * reading commands. With NumLock off they are those commands, with NumLock on they type.
971
999
  */
972
1000
  const NUMPAD_KEYS = [
973
- ...Array.from({ length: 10 }, (_, digit) => `numpad${digit}`),
1001
+ ...DIGITS.map((digit) => `numpad${digit}`),
974
1002
  "numpadplus",
975
1003
  "numpadminus",
976
1004
  "numpadmultiply",
@@ -994,7 +1022,7 @@ const NAMED_KEYS = [
994
1022
  "end",
995
1023
  "pageup",
996
1024
  "pagedown",
997
- ...Array.from({ length: 12 }, (_, index) => `f${index + 1}`),
1025
+ ...FUNCTION_KEYS,
998
1026
  ...NUMPAD_KEYS
999
1027
  ];
1000
1028
  /** Aliases accepted in a chord, by their lower-case spelling. */
@@ -1013,8 +1041,10 @@ const KEY_ALIASES = {
1013
1041
  const KEYS = /* @__PURE__ */ new Set([
1014
1042
  ...MODIFIER_KEYS,
1015
1043
  ...NAMED_KEYS,
1016
- ..."abcdefghijklmnopqrstuvwxyz0123456789"
1044
+ ...LETTERS,
1045
+ ...DIGITS
1017
1046
  ]);
1047
+ const isKeyName = (name) => KEYS.has(name);
1018
1048
  const MODIFIER_SET = new Set(MODIFIER_KEYS);
1019
1049
  /**
1020
1050
  * Parses `Insert+T` or `Control+Shift+Home`: modifiers and one last key, joined with `+`, names
@@ -1026,7 +1056,7 @@ function parseKeyChord$1(chord) {
1026
1056
  for (const part of chord.split("+")) {
1027
1057
  const lower = part.trim().toLowerCase();
1028
1058
  const name = KEY_ALIASES[lower] ?? lower;
1029
- if (!KEYS.has(name)) return {
1059
+ if (!isKeyName(name)) return {
1030
1060
  ok: false,
1031
1061
  message: `unknown key "${part.trim()}" in "${chord}"`
1032
1062
  };
@@ -1050,6 +1080,14 @@ function parseKeyChord$1(chord) {
1050
1080
  }
1051
1081
  };
1052
1082
  }
1083
+ // ../shared/src/rules/run-seq.ts
1084
+ /**
1085
+ * The first `seq` of a bridge run: its start time (`bridge.startedAt`) in milliseconds, so `seq`
1086
+ * keeps rising across restarts and a client can tell a position of an earlier run
1087
+ * (docs/implementation/decisions.md#seq-keeps-rising-across-restarts). The bridge numbers by it,
1088
+ * the client reads by it.
1089
+ */
1090
+ const firstSeqOfRun = (startedAtMs) => startedAtMs;
1053
1091
  // ../shared/src/rules/service-paths.ts
1054
1092
  /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
1055
1093
  const PLAYWRIGHT_PATH = "/playwright";
@@ -1109,6 +1147,20 @@ const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
1109
1147
  * one client ends or replaces another one's session. Optional. API 1.10.
1110
1148
  */
1111
1149
  const CLIENT_HEADER = "x-sr-speech-client";
1150
+ // ../shared/src/ui-host.ts
1151
+ /** The environment variable the UI's BFF reads the bridge's address from. */
1152
+ const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
1153
+ /**
1154
+ * The header that tells the UI its page is opened from the bridge's own machine, where the screen
1155
+ * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
1156
+ * The bridge sets (`1`) or removes it on every request, so a client can't send it.
1157
+ */
1158
+ const LOCAL_HEADER = "x-sr-bridge-local";
1159
+ /**
1160
+ * Where the UI's server code finds the bridge log: a `Symbol.for` key on `globalThis`. Its lines
1161
+ * get the `[web-ui]` prefix, go to the log file and never block on the console.
1162
+ */
1163
+ const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
1112
1164
  // ../shared/src/validate.ts
1113
1165
  /**
1114
1166
  * Checks `value` against `schema`. Unknown keys of an answer don't fail it and are left out of the
@@ -1162,8 +1214,9 @@ function describeError(error) {
1162
1214
  * The exit code is 0 unless something failed. Console output is flushed before exiting.
1163
1215
  *
1164
1216
  * The signal handlers are installed before `start`, so a signal that arrives while the bridge
1165
- * starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
1166
- * like `start`.
1217
+ * starts is not fatal: the bridge stops as soon as it has started. That signal also aborts the
1218
+ * `cancel` signal `start` gets, which ends a question on the console the start waits for.
1219
+ * Resolves once started; rejects like `start`.
1167
1220
  */
1168
1221
  async function runUntilStopped(start, proc, options = {}) {
1169
1222
  const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
@@ -1174,6 +1227,7 @@ async function runUntilStopped(start, proc, options = {}) {
1174
1227
  let exiting = false;
1175
1228
  let exitCode = 0;
1176
1229
  let watchdog;
1230
+ const cancelStart = new AbortController();
1177
1231
  /** Ends the child processes the graceful stop didn't get to. */
1178
1232
  const killLeftovers = () => {
1179
1233
  try {
@@ -1203,8 +1257,10 @@ async function runUntilStopped(start, proc, options = {}) {
1203
1257
  };
1204
1258
  for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
1205
1259
  if (bridge === void 0) {
1206
- if (early === void 0) early = signal;
1207
- else {
1260
+ if (early === void 0) {
1261
+ early = signal;
1262
+ cancelStart.abort();
1263
+ } else {
1208
1264
  killLeftovers();
1209
1265
  exit(1);
1210
1266
  }
@@ -1215,7 +1271,7 @@ async function runUntilStopped(start, proc, options = {}) {
1215
1271
  killLeftovers();
1216
1272
  exit(1);
1217
1273
  });
1218
- bridge = await start();
1274
+ bridge = await start(cancelStart.signal);
1219
1275
  const running = bridge;
1220
1276
  const crash = (what) => (error) => {
1221
1277
  running.log.error(`${what}: ${describeError(error)}`);
@@ -1242,6 +1298,74 @@ var AppError = class extends Error {
1242
1298
  function invalidField(field, message) {
1243
1299
  return new AppError("INVALID_REQUEST", `${field}: ${message}`, { field });
1244
1300
  }
1301
+ // src/adapters/in/http/response.ts
1302
+ function sendJson(res, status, body) {
1303
+ const data = JSON.stringify(body);
1304
+ res.writeHead(status, {
1305
+ "content-type": "application/json; charset=utf-8",
1306
+ "content-length": Buffer.byteLength(data)
1307
+ });
1308
+ res.end(data);
1309
+ }
1310
+ function sendNoContent(res) {
1311
+ res.writeHead(204).end();
1312
+ }
1313
+ // src/adapters/in/http/errors.ts
1314
+ /** A request refused for where it comes from: `FORBIDDEN`. */
1315
+ var AccessDeniedError = class extends Error {
1316
+ details;
1317
+ name = "AccessDeniedError";
1318
+ code = "FORBIDDEN";
1319
+ constructor(message, details) {
1320
+ super(message);
1321
+ this.details = details;
1322
+ }
1323
+ };
1324
+ /**
1325
+ * The error body every endpoint uses (docs/usage/http-api.md#errors) and its status. An `AppError`
1326
+ * or `AccessDeniedError` keeps its code. Anything else is `INTERNAL`, with the details in the bridge log only.
1327
+ */
1328
+ function errorResponse(error, logger) {
1329
+ let body;
1330
+ if (error instanceof AppError || error instanceof AccessDeniedError) {
1331
+ body = { error: {
1332
+ code: error.code,
1333
+ message: error.message
1334
+ } };
1335
+ if (error.details !== void 0) body.error.details = error.details;
1336
+ } else {
1337
+ logger.error(`internal error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1338
+ body = { error: {
1339
+ code: "INTERNAL",
1340
+ message: "Internal error, see the bridge log"
1341
+ } };
1342
+ }
1343
+ return {
1344
+ status: ERROR_STATUS[body.error.code],
1345
+ body
1346
+ };
1347
+ }
1348
+ /** Sends the error body every endpoint uses (docs/usage/http-api.md#errors). */
1349
+ function sendError(res, error, logger) {
1350
+ const { status, body } = errorResponse(error, logger);
1351
+ if (res.headersSent) {
1352
+ res.destroy();
1353
+ return;
1354
+ }
1355
+ sendJson(res, status, body);
1356
+ }
1357
+ /**
1358
+ * The same answer on the raw socket of a WebSocket upgrade, which has no `ServerResponse`, then
1359
+ * closes it.
1360
+ */
1361
+ function sendSocketError(socket, error, logger) {
1362
+ const { status, body } = errorResponse(error, logger);
1363
+ const data = JSON.stringify(body);
1364
+ socket.end(`HTTP/1.1 ${status} ${http.STATUS_CODES[status] ?? "Error"}\r\ncontent-type: application/json; charset=utf-8\r
1365
+ content-length: ${Buffer.byteLength(data)}\r\nconnection: close\r
1366
+ \r
1367
+ ` + data);
1368
+ }
1245
1369
  // src/adapters/in/http/access.ts
1246
1370
  /** Methods that don't change anything. Other methods with a foreign `Origin` are refused. */
1247
1371
  const SAFE_METHODS = /* @__PURE__ */ new Set([
@@ -1249,20 +1373,23 @@ const SAFE_METHODS = /* @__PURE__ */ new Set([
1249
1373
  "HEAD",
1250
1374
  "OPTIONS"
1251
1375
  ]);
1376
+ /** `Sec-Fetch-Site` values of a request the user made on the bridge's own page or address bar. */
1377
+ const OWN_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
1252
1378
  /**
1253
- * Throws `FORBIDDEN` if the request comes through a foreign host name or from a foreign page.
1254
- * `strictOrigin` refuses a foreign `Origin` for every method: for the proxied services, where a
1255
- * page could open a WebSocket or read an event stream (docs/usage/security.md#host-and-origin).
1379
+ * Throws an `AccessDeniedError` if the request comes through a foreign host name or from a foreign page
1380
+ * (docs/usage/security.md#host-and-origin).
1256
1381
  */
1257
- function checkAccess(req, rules, { strictOrigin = false } = {}) {
1382
+ function checkAccess(req, rules, { strictOrigin = false, crossSite = "allow" } = {}) {
1258
1383
  const host = (req.headers.host ?? "").toLowerCase();
1259
1384
  const hostname = hostnameOf(host);
1260
- if (hostname === void 0) throw new AppError("FORBIDDEN", "The request has no valid Host header");
1261
- 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 });
1385
+ if (hostname === void 0) throw new AccessDeniedError("The request has no valid Host header");
1386
+ 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 });
1387
+ const fetchSite = req.headers["sec-fetch-site"];
1388
+ if (crossSite === "refuse" && fetchSite !== void 0 && !OWN_FETCH_SITES.has(fetchSite)) throw new AccessDeniedError("Requests from another site are not allowed", { fetchSite });
1262
1389
  const origin = req.headers.origin;
1263
1390
  if (origin === void 0) return;
1264
1391
  if (!strictOrigin && SAFE_METHODS.has(req.method ?? "GET")) return;
1265
- if (origin.toLowerCase() !== `http://${host}`) throw new AppError("FORBIDDEN", `Requests from origin "${origin}" are not allowed`, { origin });
1392
+ if (origin.toLowerCase() !== `http://${host}`) throw new AccessDeniedError(`Requests from origin "${origin}" are not allowed`, { origin });
1266
1393
  }
1267
1394
  /** The host name in a `Host` header (`name:port`, `[::1]:port`), `undefined` if it isn't one. */
1268
1395
  function hostnameOf(host) {
@@ -1286,8 +1413,28 @@ function hostAllowed(hostname, { allowedHosts, ownHostnames }) {
1286
1413
  function ownNames(hostnames) {
1287
1414
  return hostnames.flatMap((name) => [name, name.split(".")[0]]).filter((name) => name !== "");
1288
1415
  }
1416
+ // src/application/ports/out/listener.ts
1417
+ /**
1418
+ * A listener can't use its port: something else listens on it (`EADDRINUSE`), or the system
1419
+ * doesn't allow it (`EACCES`, for example a port in a Windows excluded port range). Startup may
1420
+ * ask for another TCP port then (docs/implementation/tcp-capture.md#listening-and-connections).
1421
+ */
1422
+ var PortUnavailableError = class extends Error {
1423
+ port;
1424
+ reason;
1425
+ name = "PortUnavailableError";
1426
+ constructor(message, port, reason) {
1427
+ super(message);
1428
+ this.port = port;
1429
+ this.reason = reason;
1430
+ }
1431
+ };
1289
1432
  // src/adapters/shared/net/listen.ts
1290
- /** Thrown when a listener can't use its port (for example `EADDRINUSE`). */
1433
+ /**
1434
+ * Thrown when a listener can't start for another reason than its port being unavailable (for
1435
+ * example `EADDRNOTAVAIL`: an address this machine doesn't have). A port that is in use or not
1436
+ * allowed is a `PortUnavailableError`.
1437
+ */
1291
1438
  var ListenError = class extends Error {
1292
1439
  code;
1293
1440
  name = "ListenError";
@@ -1296,15 +1443,31 @@ var ListenError = class extends Error {
1296
1443
  this.code = code;
1297
1444
  }
1298
1445
  };
1446
+ const UNAVAILABLE = {
1447
+ EADDRINUSE: {
1448
+ reason: "in-use",
1449
+ text: "the port is already in use (is another bridge running?)"
1450
+ },
1451
+ EACCES: {
1452
+ reason: "denied",
1453
+ text: "the system does not allow this port (on Windows it may be in an excluded port range: `netsh interface ipv4 show excludedportrange protocol=tcp`)"
1454
+ }
1455
+ };
1456
+ /** The error `listen` rejects with when `server` fails to listen on `host:port`. */
1457
+ function listenFailure(error, host, port) {
1458
+ const where = `Cannot listen on ${host}:${port}`;
1459
+ const unavailable = error.code === void 0 ? void 0 : UNAVAILABLE[error.code];
1460
+ if (unavailable !== void 0) return new PortUnavailableError(`${where}: ${unavailable.text}`, port, unavailable.reason);
1461
+ return new ListenError(`${where}: ${error.message}`, error.code);
1462
+ }
1299
1463
  /**
1300
1464
  * Starts `server` on `host:port` and resolves with the bound port (useful with port 0).
1301
- * Rejects with a `ListenError` that says what went wrong, naming the port.
1465
+ * Rejects with a `PortUnavailableError` or a `ListenError` that says what went wrong, naming the
1466
+ * port.
1302
1467
  */
1303
1468
  async function listen(server, host, port) {
1304
1469
  await new Promise((resolve, reject) => {
1305
- const onError = (error) => {
1306
- reject(new ListenError(`Cannot listen on ${host}:${port}: ${error.code === "EADDRINUSE" ? "the port is already in use (is another bridge running?)" : error.message}`, error.code));
1307
- };
1470
+ const onError = (error) => reject(listenFailure(error, host, port));
1308
1471
  server.once("error", onError);
1309
1472
  server.listen(port, host, () => {
1310
1473
  server.off("error", onError);
@@ -1364,121 +1527,13 @@ function describeListener(scheme, host, port, path = "", interfaces = os.network
1364
1527
  const urls = reachableUrls(scheme, host, port, interfaces).map((url) => `${url}${path}`).join(", ");
1365
1528
  return isWildcard(host) ? `${hostPort(host, port)}, reachable at ${urls}` : urls;
1366
1529
  }
1367
- // src/adapters/in/http/response.ts
1368
- function sendJson(res, status, body) {
1369
- const data = JSON.stringify(body);
1370
- res.writeHead(status, {
1371
- "content-type": "application/json; charset=utf-8",
1372
- "content-length": Buffer.byteLength(data)
1373
- });
1374
- res.end(data);
1375
- }
1376
- function sendNoContent(res) {
1377
- res.writeHead(204).end();
1378
- }
1379
- // src/adapters/in/http/errors.ts
1380
- /**
1381
- * The error body every endpoint uses (docs/usage/http-api.md#errors) and its status. An `AppError`
1382
- * keeps its code. Anything else is `INTERNAL`, with the details in the bridge log only.
1383
- */
1384
- function errorResponse(error, logger) {
1385
- let body;
1386
- if (error instanceof AppError) {
1387
- body = { error: {
1388
- code: error.code,
1389
- message: error.message
1390
- } };
1391
- if (error.details !== void 0) body.error.details = error.details;
1392
- } else {
1393
- logger.error(`internal error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1394
- body = { error: {
1395
- code: "INTERNAL",
1396
- message: "Internal error, see the bridge log"
1397
- } };
1398
- }
1399
- return {
1400
- status: ERROR_STATUS[body.error.code],
1401
- body
1402
- };
1403
- }
1404
- /** Sends the error body every endpoint uses (docs/usage/http-api.md#errors). */
1405
- function sendError(res, error, logger) {
1406
- const { status, body } = errorResponse(error, logger);
1407
- if (res.headersSent) {
1408
- res.destroy();
1409
- return;
1410
- }
1411
- sendJson(res, status, body);
1412
- }
1413
- /**
1414
- * The same answer on the raw socket of a WebSocket upgrade, which has no `ServerResponse`, then
1415
- * closes it.
1416
- */
1417
- function sendSocketError(socket, error, logger) {
1418
- const { status, body } = errorResponse(error, logger);
1419
- const data = JSON.stringify(body);
1420
- socket.end(`HTTP/1.1 ${status} ${http.STATUS_CODES[status] ?? "Error"}\r\ncontent-type: application/json; charset=utf-8\r
1421
- content-length: ${Buffer.byteLength(data)}\r\nconnection: close\r
1422
- \r
1423
- ` + data);
1424
- }
1425
- // src/domain/child-service.ts
1426
- const SERVICE_NAMES = ["playwright", "mcp"];
1427
- /** How the services are named in log lines and errors. */
1428
- const SERVICE_TITLES = {
1429
- playwright: "Playwright server",
1430
- mcp: "Playwright MCP"
1431
- };
1530
+ // src/adapters/shared/net/child-host.ts
1432
1531
  /**
1433
1532
  * Where the child services listen: loopback only. Clients reach them through the bridge's HTTP
1434
1533
  * port, which checks Host and Origin for them like for the API
1435
1534
  * (docs/implementation/decisions.md#the-bridge-is-the-single-way-in).
1436
1535
  */
1437
1536
  const CHILD_HOST = "127.0.0.1";
1438
- /** A service's settings from the config: the Playwright server in the configured version, MCP in the bundled one. */
1439
- function serviceSettings(name, config) {
1440
- if (name === "playwright") {
1441
- const { port, version } = config.playwright;
1442
- return {
1443
- host: CHILD_HOST,
1444
- port,
1445
- version
1446
- };
1447
- }
1448
- return {
1449
- host: CHILD_HOST,
1450
- port: config.mcp.port,
1451
- version: null
1452
- };
1453
- }
1454
- function reachability(name, status, enabled) {
1455
- if (status.state === "running") return { port: status.port };
1456
- const title = SERVICE_TITLES[name];
1457
- if (!enabled) return { unavailable: `${title} is disabled` };
1458
- return { unavailable: `${title} is not running (state: ${status.state})` };
1459
- }
1460
- const RESTART_POLICY = {
1461
- baseDelayMs: 1e3,
1462
- maxDelayMs: 3e4,
1463
- stableMs: 6e4,
1464
- maxCrashesInRow: 5
1465
- };
1466
- /**
1467
- * What to do after a crash. `crashesInRow` counts the crashes before this one, `ranForMs` is how
1468
- * long the service ran before it crashed.
1469
- */
1470
- function nextAfterCrash(crashesInRow, ranForMs, policy = RESTART_POLICY) {
1471
- const streak = (ranForMs >= policy.stableMs ? 0 : crashesInRow) + 1;
1472
- if (streak >= policy.maxCrashesInRow) return {
1473
- action: "fail",
1474
- crashesInRow: streak
1475
- };
1476
- return {
1477
- action: "restart",
1478
- crashesInRow: streak,
1479
- delayMs: Math.min(policy.baseDelayMs * 2 ** (streak - 1), policy.maxDelayMs)
1480
- };
1481
- }
1482
1537
  // src/adapters/in/http/proxy/service-proxy.ts
1483
1538
  /** Headers that belong to one connection and are not passed on (RFC 9110, 7.6.1). */
1484
1539
  const HOP_BY_HOP = /* @__PURE__ */ new Set([
@@ -1918,6 +1973,36 @@ function toWaitResultDto(result) {
1918
1973
  };
1919
1974
  }
1920
1975
  // src/adapters/in/http/dto/input.ts
1976
+ function toFocusRequest({ target, title }) {
1977
+ return {
1978
+ target,
1979
+ title
1980
+ };
1981
+ }
1982
+ function toClickRequest({ x, y, button }) {
1983
+ return {
1984
+ x,
1985
+ y,
1986
+ button
1987
+ };
1988
+ }
1989
+ function toPressKeysRequest(dto) {
1990
+ const { keys, delayMs, expectedTarget } = dto;
1991
+ return {
1992
+ keys,
1993
+ delayMs,
1994
+ expectedTarget
1995
+ };
1996
+ }
1997
+ function toCaptureOptions(dto) {
1998
+ const { quietForMs, firstWithinMs, timeoutMs, settleMs } = dto;
1999
+ return {
2000
+ quietForMs,
2001
+ firstWithinMs,
2002
+ timeoutMs,
2003
+ settleMs
2004
+ };
2005
+ }
1921
2006
  function toInputResultDto({ window }) {
1922
2007
  if (window === void 0) return {};
1923
2008
  return { window: window && {
@@ -1991,7 +2076,7 @@ function answer(exchange, capture, send, record) {
1991
2076
  function inputRoutes(router, deps) {
1992
2077
  const { input, captures, focus, logger } = deps;
1993
2078
  router.add("POST", "/input/focus", { body: FocusRequestSchema }, async ({ req, res, body }) => {
1994
- const request = typedBody(FocusRequestSchema, body);
2079
+ const request = toFocusRequest(typedBody(FocusRequestSchema, body));
1995
2080
  await whileConnected({
1996
2081
  req,
1997
2082
  res,
@@ -2001,23 +2086,25 @@ function inputRoutes(router, deps) {
2001
2086
  signal
2002
2087
  }), (focused) => sendJson(res, 200, toFocusedWindowDto(focused)));
2003
2088
  }).add("POST", "/input/click", { body: ClickRequestSchema }, async ({ req, res, body }) => {
2004
- const { capture, ...request } = typedBody(ClickRequestSchema, body);
2089
+ const dto = typedBody(ClickRequestSchema, body);
2090
+ const request = toClickRequest(dto);
2005
2091
  await answer({
2006
2092
  req,
2007
2093
  res,
2008
2094
  logger
2009
- }, capture, (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
2095
+ }, dto.capture && toCaptureOptions(dto.capture), (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
2010
2096
  ...request,
2011
2097
  capture,
2012
2098
  signal
2013
2099
  }));
2014
2100
  }).add("POST", "/input/keys", { body: KeysRequestSchema }, async ({ req, res, body }) => {
2015
- const { capture, ...request } = typedBody(KeysRequestSchema, body);
2101
+ const dto = typedBody(KeysRequestSchema, body);
2102
+ const request = toPressKeysRequest(dto);
2016
2103
  await answer({
2017
2104
  req,
2018
2105
  res,
2019
2106
  logger
2020
- }, capture, (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
2107
+ }, dto.capture && toCaptureOptions(dto.capture), (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
2021
2108
  ...request,
2022
2109
  capture,
2023
2110
  signal
@@ -2081,6 +2168,14 @@ function sessionRoutes(router, { sessions }) {
2081
2168
  sendJson(res, 200, toSessionListDto(sessions.list()));
2082
2169
  });
2083
2170
  }
2171
+ // src/adapters/in/http/dto/stream.ts
2172
+ function toPositionEventDto() {
2173
+ return {};
2174
+ }
2175
+ /** `sessionId` is left out when everything was cleared. */
2176
+ function toClearEventDto(sessionId) {
2177
+ return sessionId === void 0 ? {} : { sessionId };
2178
+ }
2084
2179
  // src/adapters/in/http/sse/sse-frames.ts
2085
2180
  /**
2086
2181
  * Frames already built, by the entry or session they show. Every open stream gets the same
@@ -2103,9 +2198,9 @@ function sseFrame(event) {
2103
2198
  const data = JSON.stringify(toSpeechEntryDto(event.entry));
2104
2199
  return `id: ${event.entry.seq}\nevent: entry\ndata: ${data}\n\n`;
2105
2200
  });
2106
- case "position": return `id: ${event.seq}\nevent: position\ndata: {}\n\n`;
2201
+ case "position": return `id: ${event.seq}\nevent: position\ndata: ${JSON.stringify(toPositionEventDto())}\n\n`;
2107
2202
  case "session": return cached(event.session, () => `event: session\ndata: ${JSON.stringify(toSessionDto(event.session))}\n\n`);
2108
- case "clear": return event.sessionId === void 0 ? "event: clear\ndata: {}\n\n" : `event: clear\ndata: ${JSON.stringify({ sessionId: event.sessionId })}\n\n`;
2203
+ case "clear": return `event: clear\ndata: ${JSON.stringify(toClearEventDto(event.sessionId))}\n\n`;
2109
2204
  default: return `event: ${event.type}\ndata: {}\n\n`;
2110
2205
  }
2111
2206
  }
@@ -2140,11 +2235,9 @@ function speechRoutes(router, deps) {
2140
2235
  const label = stringParam(url, "label");
2141
2236
  if (label === void 0) throw invalidField("label", "is required");
2142
2237
  sendJson(res, 200, toLatestMarkerDto(speech.latestMarker(label, sessionParam(url))));
2143
- }).add("GET", "/speech/wait", { query: WAIT_QUERY }, async ({ res, url }) => {
2144
- const controller = new AbortController();
2145
- res.on("close", () => {
2146
- if (!res.writableEnded) controller.abort();
2147
- });
2238
+ }).add("GET", "/speech/wait", { query: WAIT_QUERY }, async ({ req, res, url }) => {
2239
+ const signal = hangUpSignal(req, res);
2240
+ signal.addEventListener("abort", () => logger.debug("speech wait: the client hung up before the answer"), { once: true });
2148
2241
  let result;
2149
2242
  try {
2150
2243
  result = await waits.wait({
@@ -2154,10 +2247,10 @@ function speechRoutes(router, deps) {
2154
2247
  since: intParam(url, "since"),
2155
2248
  timeoutMs: intParam(url, "timeoutMs"),
2156
2249
  session: sessionParam(url),
2157
- signal: controller.signal
2250
+ signal
2158
2251
  });
2159
2252
  } catch (error) {
2160
- if (controller.signal.aborted) return;
2253
+ if (signal.aborted) return;
2161
2254
  throw error;
2162
2255
  }
2163
2256
  sendJson(res, 200, toWaitResultDto(result));
@@ -2391,7 +2484,11 @@ var HttpServer = class {
2391
2484
  path = url.pathname;
2392
2485
  if (isApiPath(url.pathname)) res.setHeader(API_VERSION_HEADER, API_VERSION);
2393
2486
  const route = this.proxy.match(url.pathname);
2394
- this.checkAccess(req, route !== void 0);
2487
+ const api = route !== void 0 || isApiPath(url.pathname);
2488
+ this.checkAccess(req, {
2489
+ strictOrigin: route !== void 0,
2490
+ crossSite: api ? "refuse" : "allow"
2491
+ });
2395
2492
  if (route) this.proxy.forward(route, req, res, url);
2396
2493
  else if (this.deps.ui && !isApiPath(url.pathname)) await this.deps.ui(req, res);
2397
2494
  else await this.router.find(method, url.pathname)({
@@ -2414,7 +2511,10 @@ var HttpServer = class {
2414
2511
  const url = parseUrl(req.url);
2415
2512
  const route = this.proxy.match(url.pathname);
2416
2513
  if (route?.scheme !== "ws") throw new AppError("NOT_FOUND", `No WebSocket endpoint at ${url.pathname}`);
2417
- this.checkAccess(req, true);
2514
+ this.checkAccess(req, {
2515
+ strictOrigin: true,
2516
+ crossSite: "refuse"
2517
+ });
2418
2518
  this.deps.logger.debug(`upgrade ${url.pathname} → ${route.name}`);
2419
2519
  this.proxy.upgrade(route, req, socket, head, url);
2420
2520
  } catch (error) {
@@ -2423,13 +2523,14 @@ var HttpServer = class {
2423
2523
  }
2424
2524
  /**
2425
2525
  * Host and origin rules (docs/usage/security.md#host-and-origin). The services refuse a foreign
2426
- * origin for every method: a page could open a WebSocket or read an event stream.
2526
+ * origin for every method: a page could open a WebSocket or read an event stream. The API and
2527
+ * the services refuse what a browser sends for another site's page; the web UI doesn't.
2427
2528
  */
2428
- checkAccess(req, proxied) {
2529
+ checkAccess(req, options) {
2429
2530
  checkAccess(req, {
2430
2531
  allowedHosts: this.allowedHosts,
2431
2532
  ownHostnames: this.deps.hostnames ?? []
2432
- }, { strictOrigin: proxied });
2533
+ }, options);
2433
2534
  }
2434
2535
  };
2435
2536
  /** Whether `pathname` is the API's (`/api/v1`, `/api/v1/…`). An unknown one is an API 404. */
@@ -2445,22 +2546,13 @@ function parseUrl(target) {
2445
2546
  }
2446
2547
  }
2447
2548
  // src/adapters/in/http/ui-mount.ts
2448
- /** The environment variable the UI's BFF reads the bridge's address from. */
2449
- const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
2450
2549
  /** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
2451
2550
  const PROTOCOL_HEADER = "x-sr-bridge-protocol";
2452
2551
  /**
2453
- * The header that tells the UI its page is opened from the bridge's own machine, where the screen
2454
- * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
2455
- * Set (`1`) or removed on every request, so a client can't send it.
2456
- */
2457
- const LOCAL_HEADER = "x-sr-bridge-local";
2458
- /**
2459
- * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
2460
- * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
2461
- * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
2552
+ * The variables {@link UiMount.mount} sets for the UI. Child services don't inherit them
2553
+ * (`adapters/out/process`).
2462
2554
  */
2463
- const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
2555
+ const UI_ENV_NAMES = [BRIDGE_API_URL_ENV, "PROTOCOL_HEADER"];
2464
2556
  /**
2465
2557
  * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
2466
2558
  * none: the bridge runs from source, or the package was built without the UI.
@@ -2665,7 +2757,8 @@ var TcpListener = class {
2665
2757
  line: (text) => this.recordSpeech.record({
2666
2758
  text,
2667
2759
  voice,
2668
- connectionId: id
2760
+ connectionId: id,
2761
+ source: "tcp"
2669
2762
  }),
2670
2763
  lineCut: (max) => this.logger.warn(`connection ${id}: line longer than ${max} bytes, cut it`)
2671
2764
  });
@@ -3149,20 +3242,24 @@ function linkSignals(...signals) {
3149
3242
  // src/application/services/bridge-lifecycle-service.ts
3150
3243
  /**
3151
3244
  * The bridge's state from `starting` over `ready` to `stopping`, and the order of startup and
3152
- * shutdown.
3245
+ * shutdown. `GET /status` reads the state through {@link state}.
3153
3246
  */
3154
3247
  var BridgeLifecycleService = class {
3155
3248
  deps;
3156
3249
  stopping;
3250
+ #state = "starting";
3157
3251
  constructor(deps) {
3158
3252
  this.deps = deps;
3159
3253
  }
3254
+ state() {
3255
+ return this.#state;
3256
+ }
3160
3257
  async start() {
3161
3258
  const ports = await this.listen();
3162
3259
  await this.deps.httpListening(ports.http);
3163
3260
  this.deps.services.startEnabled().then(() => {
3164
3261
  if (this.stopping !== void 0) return;
3165
- this.deps.state.setState("ready");
3262
+ this.#state = "ready";
3166
3263
  this.deps.logger.info(this.deps.readyMessage(ports));
3167
3264
  });
3168
3265
  return ports;
@@ -3186,8 +3283,8 @@ var BridgeLifecycleService = class {
3186
3283
  }
3187
3284
  }
3188
3285
  async shutdown(reason) {
3189
- const { state, shutdown, tcp, http, services, logger } = this.deps;
3190
- state.setState("stopping");
3286
+ const { shutdown, tcp, http, services, logger } = this.deps;
3287
+ this.#state = "stopping";
3191
3288
  logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
3192
3289
  shutdown.abort(shuttingDown());
3193
3290
  const errors = [];
@@ -3206,31 +3303,66 @@ var BridgeLifecycleService = class {
3206
3303
  logger.info("stopped");
3207
3304
  }
3208
3305
  };
3209
- // src/application/services/child-services-service.ts
3210
- /** Runs the Playwright server and Playwright MCP as the configuration says. */
3211
- var ChildServicesService = class {
3212
- deps;
3213
- constructor(deps) {
3214
- this.deps = deps;
3215
- }
3216
- async startEnabled() {
3217
- const config = this.deps.config();
3218
- const enabled = SERVICE_NAMES.filter((name) => config[name].enabled);
3219
- await Promise.all(enabled.map((name) => this.supervisor(name).start()));
3220
- }
3221
- async stopAll() {
3222
- const errors = (await Promise.allSettled(SERVICE_NAMES.map((name) => this.supervisor(name).stop()))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
3223
- if (errors.length === 1) throw errors[0];
3224
- if (errors.length > 1) throw new AggregateError(errors, "stopping the child services failed");
3225
- }
3226
- reachability(name) {
3227
- return reachability(name, this.supervisor(name).status(), this.deps.config()[name].enabled);
3228
- }
3229
- supervisor(name) {
3230
- return this.deps.supervisors[name];
3231
- }
3306
+ // src/domain/child-service.ts
3307
+ const SERVICE_NAMES = ["playwright", "mcp"];
3308
+ /** How the services are named in log lines and errors. */
3309
+ const SERVICE_TITLES = {
3310
+ playwright: "Playwright server",
3311
+ mcp: "Playwright MCP"
3232
3312
  };
3233
- // src/domain/config/defaults.ts
3313
+ function reachability(name, status, enabled) {
3314
+ if (status.state === "running") return { port: status.port };
3315
+ const title = SERVICE_TITLES[name];
3316
+ if (!enabled) return { unavailable: `${title} is disabled` };
3317
+ return { unavailable: `${title} is not running (state: ${status.state})` };
3318
+ }
3319
+ const RESTART_POLICY = {
3320
+ baseDelayMs: 1e3,
3321
+ maxDelayMs: 3e4,
3322
+ stableMs: 6e4,
3323
+ maxCrashesInRow: 5
3324
+ };
3325
+ /**
3326
+ * What to do after a crash. `crashesInRow` counts the crashes before this one, `ranForMs` is how
3327
+ * long the service ran before it crashed.
3328
+ */
3329
+ function nextAfterCrash(crashesInRow, ranForMs, policy = RESTART_POLICY) {
3330
+ const streak = (ranForMs >= policy.stableMs ? 0 : crashesInRow) + 1;
3331
+ if (streak >= policy.maxCrashesInRow) return {
3332
+ action: "fail",
3333
+ crashesInRow: streak
3334
+ };
3335
+ return {
3336
+ action: "restart",
3337
+ crashesInRow: streak,
3338
+ delayMs: Math.min(policy.baseDelayMs * 2 ** (streak - 1), policy.maxDelayMs)
3339
+ };
3340
+ }
3341
+ // src/application/services/child-services-service.ts
3342
+ /** Runs the Playwright server and Playwright MCP as the configuration says. */
3343
+ var ChildServicesService = class {
3344
+ deps;
3345
+ constructor(deps) {
3346
+ this.deps = deps;
3347
+ }
3348
+ async startEnabled() {
3349
+ const config = this.deps.config();
3350
+ const enabled = SERVICE_NAMES.filter((name) => config[name].enabled);
3351
+ await Promise.all(enabled.map((name) => this.supervisor(name).start()));
3352
+ }
3353
+ async stopAll() {
3354
+ const errors = (await Promise.allSettled(SERVICE_NAMES.map((name) => this.supervisor(name).stop()))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
3355
+ if (errors.length === 1) throw errors[0];
3356
+ if (errors.length > 1) throw new AggregateError(errors, "stopping the child services failed");
3357
+ }
3358
+ reachability(name) {
3359
+ return reachability(name, this.supervisor(name).status(), this.deps.config()[name].enabled);
3360
+ }
3361
+ supervisor(name) {
3362
+ return this.deps.supervisors[name];
3363
+ }
3364
+ };
3365
+ // src/domain/config/defaults.ts
3234
3366
  const DEFAULT_CONFIG = {
3235
3367
  tcp: {
3236
3368
  host: "127.0.0.1",
@@ -3325,12 +3457,14 @@ function mergePatch(base, patch) {
3325
3457
  * Throws `INVALID_REQUEST` if two listeners of `config` would use the same port: the bridge's TCP
3326
3458
  * and HTTP ports and the ports of the enabled child services. A port `0` (any free port) can't
3327
3459
  * collide. Checked on the final configuration only: a patch alone doesn't know the other ports.
3460
+ * The error names `changed` if it is one of the two, else the later one.
3328
3461
  */
3329
- function assertDistinctPorts(config) {
3462
+ function assertDistinctPorts(config, changed) {
3330
3463
  const used = /* @__PURE__ */ new Map();
3331
3464
  const listeners = [["tcp.port", config.tcp.port], ["http.port", config.http.port]];
3332
3465
  if (config.playwright.enabled) listeners.push(["playwright.port", config.playwright.port]);
3333
3466
  if (config.mcp.enabled) listeners.push(["mcp.port", config.mcp.port]);
3467
+ listeners.sort(([a], [b]) => Number(a === changed) - Number(b === changed));
3334
3468
  for (const [field, value] of listeners) {
3335
3469
  const other = used.get(value);
3336
3470
  if (value !== 0 && other !== void 0) throw invalidField(field, `port ${value} is already used by ${other}`);
@@ -3388,13 +3522,62 @@ function withUnknownSettings(file, unknown) {
3388
3522
  }
3389
3523
  return Object.fromEntries(result);
3390
3524
  }
3391
- // src/application/services/config-service.ts
3525
+ // src/application/ports/in/load-config.ts
3526
+ /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
3527
+ var ConfigError = class extends Error {
3528
+ name = "ConfigError";
3529
+ };
3530
+ // src/application/services/config-loader.ts
3392
3531
  const show$1 = (value) => JSON.stringify(value);
3393
- const same = (a, b) => show$1(a) === show$1(b);
3532
+ /** `patch` checked, with an error that says where the bad setting came from. */
3533
+ function checked(patch, origin) {
3534
+ try {
3535
+ return validatePatch(patch);
3536
+ } catch (error) {
3537
+ throw new ConfigError(`${origin(error instanceof AppError ? error.details?.field : void 0)}: ${error.message}`, { cause: error });
3538
+ }
3539
+ }
3540
+ /**
3541
+ * The configuration of a start (docs/usage/configuration.md): defaults, then the config file, then
3542
+ * flags and environment variables. `sources` names what sets each of those (`--tcp-port`).
3543
+ * Rejects with a {@link ConfigError}.
3544
+ */
3545
+ async function loadConfig(store, overridesPatch, sources = /* @__PURE__ */ new Map()) {
3546
+ const sourceOf = (field) => sources.get(field) ?? "a flag or environment variable";
3547
+ let loaded;
3548
+ const warnings = [];
3549
+ try {
3550
+ loaded = await store.load((message) => warnings.push(message));
3551
+ } catch (error) {
3552
+ throw new ConfigError(error.message, { cause: error });
3553
+ }
3554
+ const { known, unknown, names } = splitUnknownSettings(loaded);
3555
+ const file = checked(known, () => `Invalid setting in the config file ${store.location}`);
3556
+ const overrides = checked(overridesPatch, (field) => field?.includes(".") ? `Invalid ${sourceOf(field)}` : "Invalid setting");
3557
+ const config = mergeConfig(mergeConfig(DEFAULT_CONFIG, file), overrides);
3558
+ try {
3559
+ assertDistinctPorts(config);
3560
+ } catch (error) {
3561
+ throw new ConfigError(`Invalid setting: ${error.message}`, { cause: error });
3562
+ }
3563
+ for (const name of names) warnings.push(`${name}: unknown setting in ${store.location}, ignored`);
3564
+ 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`);
3565
+ return {
3566
+ config,
3567
+ file,
3568
+ unknownSettings: unknown,
3569
+ pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)])),
3570
+ warnings
3571
+ };
3572
+ }
3573
+ // src/application/services/config-service.ts
3574
+ const show = (value) => JSON.stringify(value);
3575
+ const same = (a, b) => show(a) === show(b);
3394
3576
  /**
3395
3577
  * The configuration (`GET` / `PUT /api/v1/config`). The configuration in use never changes while
3396
3578
  * the bridge runs: an update is saved to the config file and takes effect on the next start
3397
- * (docs/usage/configuration.md#changing-settings).
3579
+ * (docs/usage/configuration.md#changing-settings). The one exception is a TCP port chosen at
3580
+ * startup (`adopt`), before the API answers.
3398
3581
  */
3399
3582
  var ConfigService = class {
3400
3583
  deps;
@@ -3419,24 +3602,54 @@ var ConfigService = class {
3419
3602
  return Object.fromEntries(this.deps.pinned ?? []);
3420
3603
  }
3421
3604
  update(patch) {
3422
- const result = this.queue.then(() => this.apply(patch));
3605
+ return this.enqueue(async () => {
3606
+ const changes = await this.save(patch);
3607
+ this.log(configFields(changes));
3608
+ return this.saved;
3609
+ });
3610
+ }
3611
+ check(patch) {
3612
+ this.validate(patch);
3613
+ }
3614
+ adopt(patch) {
3615
+ return this.enqueue(async () => {
3616
+ const changes = await this.save(patch);
3617
+ const before = configFields(this.active);
3618
+ this.active = mergeConfig(this.active, changes);
3619
+ for (const [field, value] of configFields(changes)) {
3620
+ if (same(value, before.get(field))) continue;
3621
+ this.deps.logger.info(`${field}: ${show(before.get(field))} → ${show(value)}, saved to ${this.deps.store.location}`);
3622
+ }
3623
+ return this.active;
3624
+ });
3625
+ }
3626
+ /** One at a time: a second update starts from the result of the first. */
3627
+ enqueue(run) {
3628
+ const result = this.queue.then(run);
3423
3629
  this.queue = result.catch(() => void 0);
3424
3630
  return result;
3425
3631
  }
3426
- async apply(patch) {
3632
+ /** The valid changes of `patch`, and the saved configuration with them. Throws `AppError`. */
3633
+ validate(patch) {
3427
3634
  const changes = validatePatch(patch);
3428
3635
  const merged = mergeConfig(this.saved, changes);
3429
- assertDistinctPorts(merged);
3636
+ assertDistinctPorts(merged, [...configFields(changes).keys()].find((field) => field.endsWith(".port")));
3637
+ return {
3638
+ changes,
3639
+ merged
3640
+ };
3641
+ }
3642
+ /** Validates `patch` and saves it. Resolves with its changes. */
3643
+ async save(patch) {
3644
+ const { changes, merged } = this.validate(patch);
3430
3645
  const saved = configFields(this.file);
3431
- const patched = configFields(changes);
3432
- if ([...patched].some(([field, value]) => !same(saved.get(field), value))) {
3646
+ if ([...configFields(changes)].some(([field, value]) => !same(saved.get(field), value))) {
3433
3647
  const file = mergePatch(this.file, changes);
3434
3648
  await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}), (warning) => this.deps.logger.warn(warning));
3435
3649
  this.file = file;
3436
3650
  }
3437
3651
  this.saved = merged;
3438
- this.log(patched);
3439
- return merged;
3652
+ return changes;
3440
3653
  }
3441
3654
  log(patched) {
3442
3655
  const { logger, pinned, store } = this.deps;
@@ -3444,10 +3657,78 @@ var ConfigService = class {
3444
3657
  for (const [field, value] of patched) {
3445
3658
  const source = pinned?.get(field);
3446
3659
  if (source !== void 0) logger.warn(`${field}: saved to ${store.location}, but ${source} overrides it on the next start`);
3447
- else if (!same(value, running.get(field))) logger.info(`${field}: ${show$1(running.get(field))} → ${show$1(value)} on the next start`);
3660
+ else if (!same(value, running.get(field))) logger.info(`${field}: ${show(running.get(field))} → ${show(value)} on the next start`);
3448
3661
  }
3449
3662
  }
3450
3663
  };
3664
+ // src/domain/capture-window.ts
3665
+ /** The speech an input caused, from when it was sent until it pauses, none comes or time runs out. */
3666
+ var CaptureWindow = class {
3667
+ sentAt;
3668
+ timing;
3669
+ maxEntries;
3670
+ #entries = [];
3671
+ #omitted = 0;
3672
+ /** When the newest speech was received. */
3673
+ #last;
3674
+ #end;
3675
+ /** @param maxEntries The first entries kept; later ones are only counted. */
3676
+ constructor(sentAt, timing, maxEntries) {
3677
+ this.sentAt = sentAt;
3678
+ this.timing = timing;
3679
+ this.maxEntries = maxEntries;
3680
+ this.#end = sentAt + timing.timeoutMs;
3681
+ }
3682
+ onSpeech(entry) {
3683
+ this.#last = entry.receivedAt.getTime();
3684
+ if (this.#entries.length < this.maxEntries) this.#entries.push(entry);
3685
+ else this.#omitted++;
3686
+ }
3687
+ /** When the capture ends unless more speech comes. */
3688
+ deadline() {
3689
+ const { firstWithinMs, quietForMs } = this.timing;
3690
+ const due = this.#last === void 0 ? this.sentAt + firstWithinMs : this.#last + quietForMs;
3691
+ return Math.min(due, this.#end);
3692
+ }
3693
+ /**
3694
+ * What the capture holds once its deadline has passed. The status comes from the entries' times,
3695
+ * not from the time now: timers may fire a little early.
3696
+ */
3697
+ result() {
3698
+ return {
3699
+ status: this.#last === void 0 ? "no-speech" : this.#last + this.timing.quietForMs <= this.#end ? "silent" : "timeout",
3700
+ entries: this.#entries,
3701
+ omitted: this.#omitted
3702
+ };
3703
+ }
3704
+ };
3705
+ /**
3706
+ * The wait before an input until the newest speech is `settleMs` old, at most `timeoutMs`: after
3707
+ * that the input is sent anyway, and the trailing speech shows in the capture.
3708
+ */
3709
+ var SettleWindow = class {
3710
+ start;
3711
+ timing;
3712
+ #last;
3713
+ /** @param lastSpeechAt When the newest speech so far was received, if there was any. */
3714
+ constructor(start, timing, lastSpeechAt) {
3715
+ this.start = start;
3716
+ this.timing = timing;
3717
+ this.#last = lastSpeechAt;
3718
+ }
3719
+ /** Whether the speech had already been quiet long enough at the start. */
3720
+ get settled() {
3721
+ return this.#last === void 0 || this.#last + this.timing.settleMs <= this.start;
3722
+ }
3723
+ onSpeech(at) {
3724
+ this.#last = at;
3725
+ }
3726
+ /** When the input may be sent unless more speech comes. */
3727
+ deadline() {
3728
+ if (this.#last === void 0) return this.start;
3729
+ return Math.min(this.#last + this.timing.settleMs, this.start + this.timing.timeoutMs);
3730
+ }
3731
+ };
3451
3732
  // src/application/ports/in/capture-input.ts
3452
3733
  /** Defaults and ranges of the capture options, in milliseconds. */
3453
3734
  const CAPTURE_LIMITS = API_LIMITS.capture;
@@ -3564,6 +3845,64 @@ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, l
3564
3845
  });
3565
3846
  return stop;
3566
3847
  }
3848
+ /**
3849
+ * {@link followLog} until `onEvent` says `done`, the time runs out (`timeout`) or the signal
3850
+ * aborts. Nothing is listening or running any more once it has settled.
3851
+ */
3852
+ function followUntil(deps, { since, sessionId, signal, pace, timeLeft, startTimer }, onEvent) {
3853
+ if (signal.aborted) return Promise.reject(abortReason(signal));
3854
+ return new Promise((resolve, reject) => {
3855
+ let done = false;
3856
+ let timer;
3857
+ let stop;
3858
+ const finish = () => {
3859
+ done = true;
3860
+ stop?.();
3861
+ timer?.abort();
3862
+ signal.removeEventListener("abort", onAbort);
3863
+ };
3864
+ const succeed = (how) => {
3865
+ if (done) return;
3866
+ finish();
3867
+ resolve(how);
3868
+ };
3869
+ const fail = (error) => {
3870
+ if (done) return;
3871
+ finish();
3872
+ reject(error instanceof Error ? error : new Error(String(error)));
3873
+ };
3874
+ const onAbort = () => fail(abortReason(signal));
3875
+ const arm = () => {
3876
+ if (done) return;
3877
+ timer?.abort();
3878
+ const own = new AbortController();
3879
+ timer = own;
3880
+ deps.clock.sleep(Math.max(0, timeLeft()), own.signal).then(() => {
3881
+ if (timer === own) succeed("timeout");
3882
+ }, () => {});
3883
+ };
3884
+ signal.addEventListener("abort", onAbort, { once: true });
3885
+ if (startTimer === "at once") arm();
3886
+ try {
3887
+ stop = followLog(deps, {
3888
+ since,
3889
+ sessionId
3890
+ }, (event) => {
3891
+ if (done) return;
3892
+ const step = onEvent(event);
3893
+ if (step === "done") succeed("done");
3894
+ else if (step === "rearm") arm();
3895
+ }, {
3896
+ pace,
3897
+ onCaughtUp: startTimer === "caught up" ? arm : void 0,
3898
+ onError: fail
3899
+ });
3900
+ if (done) stop();
3901
+ } catch (error) {
3902
+ fail(error);
3903
+ }
3904
+ });
3905
+ }
3567
3906
  // src/application/shared/int-option.ts
3568
3907
  /**
3569
3908
  * A numeric use-case option: `fallback` if it is missing, otherwise checked to be an integer
@@ -3589,7 +3928,6 @@ function parseOptions(options) {
3589
3928
  settleMs: ms("settleMs", settleMs)
3590
3929
  };
3591
3930
  }
3592
- const toError = (error) => error instanceof Error ? error : new Error(String(error));
3593
3931
  /**
3594
3932
  * Native input that records the speech it causes (docs/usage/native-input.md#capturing-the-speech-an-input-causes).
3595
3933
  * The start `seq` is read in the input queue right before the input is sent, so no other input
@@ -3630,36 +3968,31 @@ var InputCaptureService = class {
3630
3968
  }
3631
3969
  }
3632
3970
  /**
3633
- * Waits until the newest speech is `settleMs` old, at most `timeoutMs`: after that the input
3634
- * is sent anyway, and the trailing speech shows in the capture. Markers and clears don't shorten
3635
- * the wait: it goes by when speech was received, not by what the buffer holds.
3971
+ * Waits for the speech to settle ({@link SettleWindow}). Markers and clears don't shorten the
3972
+ * wait: it goes by when speech was received, not by what the buffer holds.
3636
3973
  */
3637
- async settle({ settleMs, timeoutMs }, signal) {
3638
- const start = this.now();
3639
- let last = this.deps.log.lastSpeechAt?.getTime();
3640
- if (last === void 0 || last + settleMs <= start) return;
3641
- await this.follow(null, signal, () => Math.min(last + settleMs, start + timeoutMs), (event) => {
3642
- if (event.type === "entry" && event.entry.kind === "speech") last = event.entry.receivedAt.getTime();
3974
+ async settle(options, signal) {
3975
+ const window = new SettleWindow(this.now(), options, this.deps.log.lastSpeechAt?.getTime());
3976
+ if (window.settled) return;
3977
+ await this.follow(null, signal, () => window.deadline(), (event) => {
3978
+ if (event.type !== "entry" || event.entry.kind !== "speech") return void 0;
3979
+ window.onSpeech(event.entry.receivedAt.getTime());
3980
+ return "rearm";
3643
3981
  });
3644
3982
  }
3645
- /** Follows the speech after `startSeq` until it paused, none came, or the time ran out. */
3646
- async record(startSeq, { quietForMs, firstWithinMs, timeoutMs }, signal) {
3647
- const sentAt = this.now();
3648
- const end = sentAt + timeoutMs;
3649
- const entries = [];
3650
- let omitted = 0;
3983
+ /** Follows the speech after `startSeq` until its {@link CaptureWindow} has passed. */
3984
+ async record(startSeq, options, signal) {
3985
+ const window = new CaptureWindow(this.now(), options, CAPTURE_LIMITS.entries);
3651
3986
  let truncated = false;
3652
- let last;
3653
- const deadline = () => Math.min(last === void 0 ? sentAt + firstWithinMs : last + quietForMs, end);
3654
- await this.follow(startSeq, signal, deadline, (event) => {
3987
+ await this.follow(startSeq, signal, () => window.deadline(), (event) => {
3655
3988
  if (event.type === "truncated") truncated = true;
3656
- if (event.type !== "entry" || event.entry.kind !== "speech") return;
3657
- last = event.entry.receivedAt.getTime();
3658
- if (entries.length < CAPTURE_LIMITS.entries) entries.push(event.entry);
3659
- else omitted++;
3989
+ if (event.type !== "entry" || event.entry.kind !== "speech") return void 0;
3990
+ window.onSpeech(event.entry);
3991
+ return "rearm";
3660
3992
  });
3993
+ const { status, entries, omitted } = window.result();
3661
3994
  return {
3662
- status: last === void 0 ? "no-speech" : last + quietForMs <= end ? "silent" : "timeout",
3995
+ status,
3663
3996
  startSeq,
3664
3997
  entries,
3665
3998
  omitted,
@@ -3668,60 +4001,34 @@ var InputCaptureService = class {
3668
4001
  }
3669
4002
  /**
3670
4003
  * Hands `onEvent` the log's events after `since` (`null`: only new ones) until `deadline()`
3671
- * (ms, read again after each speech entry) has passed. Rejects when `signal` aborts.
4004
+ * (ms, read again at each `rearm`) has passed. Rejects when `signal` aborts.
3672
4005
  */
3673
- follow(since, signal, deadline, onEvent) {
3674
- if (signal.aborted) return Promise.reject(abortReason(signal));
3675
- return new Promise((resolve, reject) => {
3676
- let done = false;
3677
- let timer;
3678
- let stopFollow;
3679
- const finish = () => {
3680
- done = true;
3681
- stopFollow?.();
3682
- timer?.abort();
3683
- signal.removeEventListener("abort", onAbort);
3684
- };
3685
- const fail = (error) => {
3686
- if (done) return;
3687
- finish();
3688
- reject(error);
3689
- };
3690
- const onAbort = () => fail(abortReason(signal));
3691
- const arm = () => {
3692
- timer?.abort();
3693
- const own = new AbortController();
3694
- timer = own;
3695
- this.deps.clock.sleep(Math.max(0, deadline() - this.now()), own.signal).then(() => {
3696
- if (done || timer !== own) return;
3697
- finish();
3698
- resolve();
3699
- }, () => {});
3700
- };
3701
- signal.addEventListener("abort", onAbort, { once: true });
3702
- arm();
3703
- try {
3704
- stopFollow = followLog(this.deps, {
3705
- since,
3706
- sessionId: void 0
3707
- }, (event) => {
3708
- if (done) return;
3709
- onEvent(event);
3710
- if (event.type === "entry" && event.entry.kind === "speech") arm();
3711
- }, {
3712
- pace: this.deps.pace?.(),
3713
- onError: (error) => fail(toError(error))
3714
- });
3715
- if (done) stopFollow();
3716
- } catch (error) {
3717
- fail(toError(error));
3718
- }
3719
- });
4006
+ async follow(since, signal, deadline, onEvent) {
4007
+ await followUntil(this.deps, {
4008
+ since,
4009
+ sessionId: void 0,
4010
+ signal,
4011
+ pace: this.deps.pace?.(),
4012
+ timeLeft: () => deadline() - this.now(),
4013
+ startTimer: "at once"
4014
+ }, onEvent);
3720
4015
  }
3721
4016
  now() {
3722
4017
  return this.deps.clock.now().getTime();
3723
4018
  }
3724
4019
  };
4020
+ // src/domain/native-input.ts
4021
+ /** Whether the window belongs to the process tree of a target's browser. */
4022
+ function isWindowOfTarget(window, tree) {
4023
+ return tree.has(window.pid);
4024
+ }
4025
+ /**
4026
+ * The window to bring to the front: the first of `windows` (front to back) that belongs to the
4027
+ * target's process tree and has a title, with `title` one that contains it.
4028
+ */
4029
+ function findTargetWindow(windows, tree, title) {
4030
+ return windows.find((window) => isWindowOfTarget(window, tree) && window.title !== "" && (title === void 0 || window.title.includes(title)));
4031
+ }
3725
4032
  // src/application/shared/browser-targets.ts
3726
4033
  /** The service whose process tree holds a target's browser windows, and its name in messages. */
3727
4034
  const BROWSER_TARGETS = {
@@ -3780,7 +4087,7 @@ var WindowFocusService = class {
3780
4087
  for (let attempt = 0; attempt < tries; attempt++) {
3781
4088
  if (attempt > 0) await clock.sleep(TITLE_WAIT.pollMs, signal);
3782
4089
  const tree = await windows.processTree(pid);
3783
- const found = (await windows.topLevelWindows()).find((window) => tree.has(window.pid) && window.title !== "" && (title === void 0 || window.title.includes(title)));
4090
+ const found = findTargetWindow(await windows.topLevelWindows(), tree, title);
3784
4091
  if (found) return found;
3785
4092
  }
3786
4093
  }
@@ -3826,7 +4133,6 @@ function parseKeys(keys) {
3826
4133
  */
3827
4134
  var NativeInputService = class {
3828
4135
  deps;
3829
- queue = Promise.resolve();
3830
4136
  constructor(deps) {
3831
4137
  this.deps = deps;
3832
4138
  }
@@ -3835,7 +4141,7 @@ var NativeInputService = class {
3835
4141
  checkCoordinate("y", y);
3836
4142
  if (!MOUSE_BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
3837
4143
  let sent = false;
3838
- return this.enqueue(async (signal) => {
4144
+ return this.deps.queue.exclusive(async (signal) => {
3839
4145
  await hooks.beforeInject?.();
3840
4146
  const before = await this.sentTo();
3841
4147
  signal.throwIfAborted();
@@ -3852,7 +4158,7 @@ var NativeInputService = class {
3852
4158
  this.checkSupported(chords);
3853
4159
  const text = `keys ${typeof keys === "string" ? keys : keys.join(" ")}`;
3854
4160
  let sent = 0;
3855
- return this.enqueue(async (signal) => {
4161
+ return this.deps.queue.exclusive(async (signal) => {
3856
4162
  await hooks.beforeInject?.();
3857
4163
  let before = expectedTarget === void 0 ? await this.sentTo() : {};
3858
4164
  for (const [index, chord] of chords.entries()) {
@@ -3917,7 +4223,7 @@ var NativeInputService = class {
3917
4223
  if (error instanceof AppError && error.code === "WRONG_WINDOW") throw error;
3918
4224
  return refuse(`the window in front could not be checked (${error instanceof Error ? error.message : String(error)})`);
3919
4225
  }
3920
- 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);
4226
+ if (!isWindowOfTarget(window, tree)) return refuse(`the window in front ("${window.title}", pid ${window.pid}) does not belong to the browser of ${name}`, window);
3921
4227
  return window;
3922
4228
  }
3923
4229
  checkSupported(chords) {
@@ -3958,32 +4264,18 @@ var NativeInputService = class {
3958
4264
  }
3959
4265
  return first;
3960
4266
  }
3961
- exclusive(task, signal) {
3962
- return this.enqueue(task, signal);
3963
- }
3964
- /**
3965
- * Runs `task` after the earlier ones; a failed task doesn't stop the later ones. `task` isn't
3966
- * run if `signal` aborted or the bridge shut down by its turn. `unsent` says what a stopped
3967
- * request leaves unsent, for the log.
3968
- */
3969
- async enqueue(task, signal, unsent = () => void 0) {
3970
- const stop = linkSignals(this.deps.shutdown, signal);
3971
- const run = this.queue.then(() => {
3972
- stop.signal.throwIfAborted();
3973
- return task(stop.signal);
3974
- });
3975
- this.queue = run.catch(() => void 0);
3976
- try {
3977
- return await run;
3978
- } catch (error) {
3979
- const what = stop.signal.aborted ? unsent() : void 0;
3980
- if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
3981
- throw error;
3982
- } finally {
3983
- stop.dispose();
3984
- }
3985
- }
3986
4267
  };
4268
+ // src/domain/label.ts
4269
+ /**
4270
+ * A label as the API takes it: trimmed, not empty, at most `max` characters (`isTrimmedLabel`, the
4271
+ * rule the request schemas check too). `INVALID_REQUEST` naming `field` otherwise.
4272
+ */
4273
+ function trimmedLabel(field, value, max) {
4274
+ if (isTrimmedLabel(value, max)) return value.trim();
4275
+ throw invalidField(field, value.trim() === "" ? "must not be empty" : `must be at most ${max} characters`);
4276
+ }
4277
+ /** A marker's text, which is also the label a marker is found by. */
4278
+ const markerLabel = (label) => trimmedLabel("label", label, API_LIMITS.markerLength);
3987
4279
  // src/domain/session.ts
3988
4280
  const EMPTY_SESSION_STATS = {
3989
4281
  firstSeq: null,
@@ -4001,16 +4293,13 @@ function summarize(session, stats) {
4001
4293
  }
4002
4294
  /** `name` (required) or `run` (optional), trimmed. `INVALID_REQUEST` if empty or too long. */
4003
4295
  function sessionLabel(field, value) {
4004
- const text = value.trim();
4005
- if (text === "") throw invalidField(field, "must not be empty");
4006
- if (text.length > MAX_SESSION_NAME_LENGTH) throw invalidField(field, `must be at most ${MAX_SESSION_NAME_LENGTH} characters`);
4007
- return text;
4296
+ return trimmedLabel(field, value, MAX_SESSION_NAME_LENGTH);
4008
4297
  }
4009
4298
  // src/application/services/session-service.ts
4010
4299
  const describe = (session) => `session ${session.id} "${session.name}" (client ${session.client ?? "unknown"})`;
4011
4300
  /**
4012
- * Starting, ending and listing sessions (docs/usage/speech-capture.md#sessions). Each start and end
4013
- * is published as a `session` event. The speech log gives entries their `sessionId`. One screen
4301
+ * Starting, ending and listing sessions (docs/usage/speech-capture.md#sessions). The speech log
4302
+ * gives entries their `sessionId` and reports each start and end as a `session` event. One screen
4014
4303
  * reader means one current session: a client that ends or replaces another client's session is not
4015
4304
  * refused, but warned about (docs/implementation/decisions.md#sessions-warn-instead-of-locking).
4016
4305
  */
@@ -4020,24 +4309,13 @@ var SessionService = class {
4020
4309
  this.deps = deps;
4021
4310
  }
4022
4311
  start({ name, run, client }) {
4023
- const label = sessionLabel("name", name);
4024
- const group = run === void 0 || run === null ? null : sessionLabel("run", run);
4025
- const owner = clientLabel(client);
4026
4312
  const { ended, started } = this.deps.log.startSession({
4027
- name: label,
4028
- run: group,
4029
- client: owner,
4313
+ name,
4314
+ run: run ?? null,
4315
+ client: client ?? null,
4030
4316
  startedAt: this.deps.clock.now()
4031
4317
  });
4032
- if (ended) this.deps.events.publish({
4033
- type: "session",
4034
- session: ended
4035
- });
4036
- this.deps.events.publish({
4037
- type: "session",
4038
- session: started
4039
- });
4040
- const replaced = ended && ended.client !== owner ? ended : null;
4318
+ const replaced = ended && ended.client !== started.client ? ended : null;
4041
4319
  if (replaced) this.deps.logger.warn(`${describe(started)} replaced ${describe(replaced)}`);
4042
4320
  return {
4043
4321
  session: started,
@@ -4048,10 +4326,6 @@ var SessionService = class {
4048
4326
  const owner = clientLabel(client);
4049
4327
  const ended = this.deps.log.endSession(this.deps.clock.now(), session);
4050
4328
  if (!ended) return null;
4051
- this.deps.events.publish({
4052
- type: "session",
4053
- session: ended
4054
- });
4055
4329
  if (ended.client !== owner) this.deps.logger.warn(`client ${owner ?? "unknown"} ended ${describe(ended)}`);
4056
4330
  return ended;
4057
4331
  }
@@ -4074,10 +4348,9 @@ function clientLabel(client) {
4074
4348
  /** Page size of `list`: the default and the most a caller may ask for. */
4075
4349
  const LIST_LIMIT = API_LIMITS.list;
4076
4350
  // src/application/services/speech-service.ts
4077
- const MAX_MARKER_LENGTH = API_LIMITS.markerLength;
4078
4351
  /**
4079
4352
  * Recording, reading, clearing and marking speech: every entry gets its `seq` and `sessionId`
4080
- * from the speech log and `receivedAt` from the clock, and is published on the event bus
4353
+ * from the speech log and `receivedAt` from the clock
4081
4354
  * (docs/implementation/tcp-capture.md#from-line-to-speech-entry).
4082
4355
  */
4083
4356
  var SpeechService = class {
@@ -4085,11 +4358,11 @@ var SpeechService = class {
4085
4358
  constructor(deps) {
4086
4359
  this.deps = deps;
4087
4360
  }
4088
- record({ text, voice, connectionId }) {
4361
+ record({ text, voice, source, connectionId }) {
4089
4362
  this.add({
4090
4363
  kind: "speech",
4091
4364
  text,
4092
- source: "tcp",
4365
+ source,
4093
4366
  voice,
4094
4367
  connectionId
4095
4368
  });
@@ -4119,66 +4392,39 @@ var SpeechService = class {
4119
4392
  /** Wipes the buffer and the ended sessions, or one scope. The current session stays current. */
4120
4393
  clear(filter) {
4121
4394
  const session = filter === "active" ? this.deps.log.resolveFilter(filter) ?? void 0 : filter;
4122
- if (session === void 0) {
4123
- this.deps.log.clear();
4124
- this.deps.events.publish({ type: "clear" });
4125
- return;
4126
- }
4127
- this.deps.events.publish({
4128
- type: "clear",
4129
- sessionId: this.deps.log.clearScope(session)
4130
- });
4395
+ if (session === void 0) this.deps.log.clear();
4396
+ else this.deps.log.clearScope(session);
4131
4397
  }
4398
+ /** The speech log trims the label and refuses an empty or too long one. */
4132
4399
  addMarker(label) {
4133
- const text = markerLabel(label);
4134
4400
  return this.add({
4135
4401
  kind: "marker",
4136
- text,
4402
+ text: label,
4137
4403
  source: "api",
4138
4404
  voice: null,
4139
4405
  connectionId: null
4140
4406
  });
4141
4407
  }
4142
4408
  latestMarker(label, session) {
4143
- const text = markerLabel(label);
4144
4409
  const sessionId = this.deps.log.resolveFilter(session);
4145
- return this.deps.log.latestMarker(text, sessionId) ?? null;
4410
+ return this.deps.log.latestMarker(label, sessionId) ?? null;
4146
4411
  }
4147
4412
  add(entry) {
4148
- const stored = this.deps.log.append({
4413
+ return this.deps.log.append({
4149
4414
  ...entry,
4150
4415
  receivedAt: this.deps.clock.now()
4151
4416
  });
4152
- this.deps.events.publish({
4153
- type: "entry",
4154
- entry: stored
4155
- });
4156
- return stored;
4157
4417
  }
4158
4418
  };
4159
- /** A marker label: trimmed, not empty, at most `MAX_MARKER_LENGTH` characters. */
4160
- function markerLabel(label) {
4161
- const text = label.trim();
4162
- if (text === "") throw invalidField("label", "must not be empty");
4163
- if (text.length > MAX_MARKER_LENGTH) throw invalidField("label", `must be at most ${MAX_MARKER_LENGTH} characters`);
4164
- return text;
4165
- }
4166
4419
  // src/application/services/status-service.ts
4167
- /**
4168
- * `GET /api/v1/status`. `BridgeLifecycleService` moves the state from `starting` to `ready` and
4169
- * `stopping` through `BridgeStateControl`.
4170
- */
4420
+ /** `GET /api/v1/status`. */
4171
4421
  var StatusService = class {
4172
4422
  deps;
4173
- state = "starting";
4174
4423
  constructor(deps) {
4175
4424
  this.deps = deps;
4176
4425
  }
4177
- setState(state) {
4178
- this.state = state;
4179
- }
4180
4426
  status() {
4181
- const { capture, log, supervisors, config, version, apiVersion, startedAt, injector, windows } = this.deps;
4427
+ const { state, capture, log, supervisors, config, version, apiVersion, startedAt, injector, windows } = this.deps;
4182
4428
  const { listener, connections } = capture.captureStatus();
4183
4429
  const { tcp } = config();
4184
4430
  const listed = log.sessions();
@@ -4187,7 +4433,7 @@ var StatusService = class {
4187
4433
  bridge: {
4188
4434
  version,
4189
4435
  apiVersion,
4190
- state: this.state,
4436
+ state: state(),
4191
4437
  startedAt
4192
4438
  },
4193
4439
  tcp: {
@@ -4211,6 +4457,102 @@ var StatusService = class {
4211
4457
  };
4212
4458
  }
4213
4459
  };
4460
+ // src/application/shared/input-queue.ts
4461
+ /** One task at a time, in the order they came. A failed task doesn't stop the later ones. */
4462
+ var SerialInputQueue = class {
4463
+ deps;
4464
+ tail = Promise.resolve();
4465
+ constructor(deps) {
4466
+ this.deps = deps;
4467
+ }
4468
+ async exclusive(task, signal, unsent = () => void 0) {
4469
+ const stop = linkSignals(this.deps.shutdown, signal);
4470
+ const run = this.tail.then(() => {
4471
+ stop.signal.throwIfAborted();
4472
+ return task(stop.signal);
4473
+ });
4474
+ this.tail = run.catch(() => void 0);
4475
+ try {
4476
+ return await run;
4477
+ } catch (error) {
4478
+ const what = stop.signal.aborted ? unsent() : void 0;
4479
+ if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
4480
+ throw error;
4481
+ } finally {
4482
+ stop.dispose();
4483
+ }
4484
+ }
4485
+ };
4486
+ // src/application/services/tcp-startup-service.ts
4487
+ /**
4488
+ * Starts the TCP listener on `tcp.port`. If that port is in use or not allowed, it asks the person
4489
+ * at the console for another one, checks it, listens on it and saves it to the config file. It
4490
+ * never picks a port by itself: the socket voice only sends to the port it is set up with
4491
+ * (docs/implementation/tcp-capture.md#listening-and-connections).
4492
+ */
4493
+ var TcpStartupService = class {
4494
+ deps;
4495
+ constructor(deps) {
4496
+ this.deps = deps;
4497
+ }
4498
+ async start() {
4499
+ const { listener, config } = this.deps;
4500
+ const port = config.get().tcp.port;
4501
+ try {
4502
+ return await listener.start(port);
4503
+ } catch (error) {
4504
+ if (!(error instanceof PortUnavailableError) || port === 0) throw error;
4505
+ return this.choosePort(error);
4506
+ }
4507
+ }
4508
+ stop() {
4509
+ return this.deps.listener.stop();
4510
+ }
4511
+ async choosePort(failure) {
4512
+ const { hints, prompt, logger } = this.deps;
4513
+ if (hints.pinned !== void 0) throw hinted(failure, hints.pinned);
4514
+ const giveUp = hinted(failure, hints.choosePort);
4515
+ if (prompt === void 0) throw giveUp;
4516
+ logger.warn(failure.message);
4517
+ for (;;) {
4518
+ const answer = await prompt.askForPort(failure.port);
4519
+ if (answer === void 0) throw giveUp;
4520
+ const port = await this.tryPort(answer);
4521
+ if (port === void 0) continue;
4522
+ await this.save(port);
4523
+ logger.warn(`speech capture listens on port ${port} instead of ${failure.port}: ${hints.pointVoice}`);
4524
+ return port;
4525
+ }
4526
+ }
4527
+ /** Listens on `port`, or warns why not and resolves with `undefined`. */
4528
+ async tryPort(port) {
4529
+ const { listener, config, logger } = this.deps;
4530
+ if (port === 0) {
4531
+ logger.warn("port 0 picks another port on every start, but the voice needs a fixed one");
4532
+ return;
4533
+ }
4534
+ try {
4535
+ config.check({ tcp: { port } });
4536
+ return await listener.start(port);
4537
+ } catch (error) {
4538
+ if (!(error instanceof AppError || error instanceof PortUnavailableError)) throw error;
4539
+ logger.warn(error.message);
4540
+ return;
4541
+ }
4542
+ }
4543
+ /** Saves `port` as `tcp.port`. The bridge uses it anyway if the file can't be written. */
4544
+ async save(port) {
4545
+ const { config, configLocation, hints, logger } = this.deps;
4546
+ try {
4547
+ await config.adopt({ tcp: { port } });
4548
+ } catch (error) {
4549
+ logger.warn(`tcp.port ${port} could not be saved to ${configLocation} (${error instanceof Error ? error.message : String(error)}): ${hints.keepPort(port)}`);
4550
+ }
4551
+ }
4552
+ };
4553
+ function hinted(failure, hint) {
4554
+ return new PortUnavailableError(`${failure.message}. ${hint}`, failure.port, failure.reason);
4555
+ }
4214
4556
  // src/application/services/transcript-service.ts
4215
4557
  /** Logs each recorded speech line, and each session start and end, at `debug`. */
4216
4558
  var TranscriptService = class {
@@ -4233,26 +4575,56 @@ var TranscriptService = class {
4233
4575
  });
4234
4576
  }
4235
4577
  };
4236
- // src/domain/text-match.ts
4237
- /** Longest `regex` a wait accepts. */
4238
- const MAX_REGEX_LENGTH = API_LIMITS.wait.regexLength;
4578
+ // src/domain/last-seen.ts
4239
4579
  /**
4240
- * Builds a matcher for `wait`. Exactly one of `contains` and `regex` is required.
4241
- * Only `kind: "speech"` entries match, never markers.
4580
+ * The last `limit` entries pushed, and how many came before them: what a wait that timed out
4581
+ * answers with (docs/usage/http-api.md).
4242
4582
  */
4243
- function createSpeechMatcher(options) {
4244
- const { contains, regex, normalize = false } = options;
4245
- if (contains === void 0 && regex === void 0) throw new AppError("INVALID_REQUEST", "One of \"contains\" and \"regex\" is required", { field: "contains" });
4246
- if (contains !== void 0 && regex !== void 0) throw new AppError("INVALID_REQUEST", "Use either \"contains\" or \"regex\", not both", { field: "regex" });
4247
- let pattern;
4248
- if (regex !== void 0) {
4249
- if (regex === "") throw invalidField("regex", "must not be empty");
4250
- checkRegexLength(regex);
4251
- try {
4252
- pattern = new RegExp(regex, "u");
4253
- } catch (error) {
4254
- throw invalidField("regex", error.message);
4255
- }
4583
+ var LastSeen = class {
4584
+ limit;
4585
+ #entries = [];
4586
+ #dropped = 0;
4587
+ constructor(limit) {
4588
+ this.limit = limit;
4589
+ }
4590
+ push(entry) {
4591
+ this.#entries.push(entry);
4592
+ if (this.#entries.length >= 2 * this.limit) this.#trim();
4593
+ }
4594
+ result() {
4595
+ this.#trim();
4596
+ return {
4597
+ seen: this.#entries,
4598
+ omitted: this.#dropped
4599
+ };
4600
+ }
4601
+ #trim() {
4602
+ const over = this.#entries.length - this.limit;
4603
+ if (over <= 0) return;
4604
+ this.#entries.splice(0, over);
4605
+ this.#dropped += over;
4606
+ }
4607
+ };
4608
+ // src/domain/text-match.ts
4609
+ /** Longest `regex` a wait accepts. */
4610
+ const MAX_REGEX_LENGTH = API_LIMITS.wait.regexLength;
4611
+ /**
4612
+ * Builds a matcher for `wait`. Exactly one of `contains` and `regex` is required.
4613
+ * Only `kind: "speech"` entries match, never markers.
4614
+ */
4615
+ function createSpeechMatcher(options) {
4616
+ const { contains, regex, normalize = false } = options;
4617
+ if (contains === void 0 && regex === void 0) throw new AppError("INVALID_REQUEST", "One of \"contains\" and \"regex\" is required", { field: "contains" });
4618
+ if (contains !== void 0 && regex !== void 0) throw new AppError("INVALID_REQUEST", "Use either \"contains\" or \"regex\", not both", { field: "regex" });
4619
+ let pattern;
4620
+ if (regex !== void 0) {
4621
+ if (regex === "") throw invalidField("regex", "must not be empty");
4622
+ checkRegexLength(regex);
4623
+ try {
4624
+ pattern = new RegExp(regex, "u");
4625
+ } catch (error) {
4626
+ throw invalidField("regex", error.message);
4627
+ }
4256
4628
  }
4257
4629
  const test = createTextTest(pattern ?? contains ?? "", normalize);
4258
4630
  if (test === void 0) throw invalidField("contains", "must not be empty");
@@ -4273,28 +4645,6 @@ const WAIT_TIMEOUT_MS = API_LIMITS.wait.timeoutMs;
4273
4645
  /** How many of the entries a wait saw its timeout answer holds at most: the last ones. */
4274
4646
  const WAIT_SEEN_LIMIT = API_LIMITS.wait.seen;
4275
4647
  // src/application/services/wait-for-speech-service.ts
4276
- /** The last {@link WAIT_SEEN_LIMIT} entries pushed, and how many came before them. */
4277
- var LastSeen = class {
4278
- #entries = [];
4279
- #dropped = 0;
4280
- push(entry) {
4281
- this.#entries.push(entry);
4282
- if (this.#entries.length >= 2 * WAIT_SEEN_LIMIT) this.#trim();
4283
- }
4284
- result() {
4285
- this.#trim();
4286
- return {
4287
- seen: this.#entries,
4288
- omitted: this.#dropped
4289
- };
4290
- }
4291
- #trim() {
4292
- const over = this.#entries.length - WAIT_SEEN_LIMIT;
4293
- if (over <= 0) return;
4294
- this.#entries.splice(0, over);
4295
- this.#dropped += over;
4296
- }
4297
- };
4298
4648
  /**
4299
4649
  * Long-poll for a speech entry (`GET /api/v1/speech/wait`): looks through the buffer after
4300
4650
  * `since`, then follows the new entries, with nothing missed or seen twice in between.
@@ -4320,127 +4670,66 @@ var WaitForSpeechService = class {
4320
4670
  const matches = createSpeechMatcher(options);
4321
4671
  const sessionId = this.deps.log.resolveFilter(options.session);
4322
4672
  if (signal?.aborted) throw abortReason(signal);
4323
- return new Promise((resolve, reject) => {
4324
- const seen = new LastSeen();
4325
- let done = false;
4326
- let stop;
4327
- /** The client's signal and the shutdown's. */
4328
- const ended = linkSignals(this.deps.shutdown, signal);
4329
- const finish = () => {
4330
- done = true;
4331
- stop?.();
4332
- timer.abort();
4333
- ended.dispose();
4334
- };
4335
- const fail = (error) => {
4336
- finish();
4337
- reject(error);
4338
- };
4339
- const timer = new AbortController();
4340
- const startTimer = () => {
4341
- if (done) return;
4342
- this.deps.clock.sleep(timeoutMs, timer.signal).then(() => {
4343
- if (done) return;
4344
- finish();
4345
- resolve({
4346
- status: "timeout",
4347
- ...seen.result()
4348
- });
4349
- }, () => {});
4350
- };
4351
- ended.signal.addEventListener("abort", () => fail(abortReason(ended.signal)), { once: true });
4352
- const failed = (error) => fail(error instanceof Error ? error : new Error(String(error)));
4353
- try {
4354
- stop = followLog(this.deps, {
4355
- since,
4356
- sessionId
4357
- }, (event) => {
4358
- if (done || event.type !== "entry") return;
4359
- seen.push(event.entry);
4360
- if (!matches(event.entry)) return;
4361
- finish();
4362
- resolve({
4363
- status: "matched",
4364
- entry: event.entry
4365
- });
4366
- }, {
4367
- pace: this.deps.pace?.(),
4368
- onCaughtUp: startTimer,
4369
- onError: failed
4370
- });
4371
- if (done) stop();
4372
- } catch (error) {
4373
- failed(error);
4374
- }
4375
- });
4673
+ const seen = new LastSeen(WAIT_SEEN_LIMIT);
4674
+ let match;
4675
+ /** The client's signal and the shutdown's. */
4676
+ const ended = linkSignals(this.deps.shutdown, signal);
4677
+ try {
4678
+ await followUntil(this.deps, {
4679
+ since,
4680
+ sessionId,
4681
+ signal: ended.signal,
4682
+ pace: this.deps.pace?.(),
4683
+ timeLeft: () => timeoutMs,
4684
+ startTimer: "caught up"
4685
+ }, (event) => {
4686
+ if (event.type !== "entry") return void 0;
4687
+ seen.push(event.entry);
4688
+ if (!matches(event.entry)) return void 0;
4689
+ match = event.entry;
4690
+ return "done";
4691
+ });
4692
+ } finally {
4693
+ ended.dispose();
4694
+ }
4695
+ return match ? {
4696
+ status: "matched",
4697
+ entry: match
4698
+ } : {
4699
+ status: "timeout",
4700
+ ...seen.result()
4701
+ };
4376
4702
  }
4377
4703
  };
4378
- // src/composition/load-config.ts
4379
- /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
4380
- var ConfigError = class extends Error {
4381
- name = "ConfigError";
4382
- };
4383
- /** `patch` checked, with an error that says where the bad setting came from. */
4384
- function checked(patch, origin) {
4385
- try {
4386
- return validatePatch(patch);
4387
- } catch (error) {
4388
- throw new ConfigError(`${origin(error instanceof AppError ? error.details?.field : void 0)}: ${error.message}`, { cause: error });
4389
- }
4390
- }
4704
+ // src/composition/service-routes.ts
4391
4705
  /**
4392
- * Defaults, then the config file, then flags and environment variables. Settings of the file this
4393
- * bridge doesn't know are left out of `config` and `file` and returned in `unknown`. The store's
4394
- * `warnings` are returned too: there is no log yet, it is built from the result.
4706
+ * The child services' paths on the bridge's HTTP port (docs/usage/playwright-mcp.md): the
4707
+ * Playwright server's WebSocket at `/`, MCP's streamable HTTP at `/mcp`.
4395
4708
  */
4396
- async function loadConfig(store, overridesPatch, sourceOf) {
4397
- let saved;
4398
- const warnings = [];
4399
- try {
4400
- saved = await store.load((message) => warnings.push(message));
4401
- } catch (error) {
4402
- throw new ConfigError(error.message, { cause: error });
4403
- }
4404
- const { known, unknown, names: ignored } = splitUnknownSettings(saved);
4405
- const file = checked(known, () => `Invalid setting in the config file ${store.location}`);
4406
- const overrides = checked(overridesPatch, (field) => field?.includes(".") ? `Invalid ${sourceOf(field)}` : "Invalid setting");
4407
- const config = mergeConfig(mergeConfig(DEFAULT_CONFIG, file), overrides);
4408
- try {
4409
- assertDistinctPorts(config);
4410
- } catch (error) {
4411
- throw new ConfigError(`Invalid setting: ${error.message}`, { cause: error });
4412
- }
4413
- return {
4414
- config,
4415
- file,
4416
- overrides,
4417
- unknown,
4418
- ignored,
4419
- warnings
4420
- };
4421
- }
4422
- // src/composition/summary.ts
4423
- const PATHS = {
4709
+ const SERVICE_ROUTES = {
4424
4710
  playwright: {
4425
4711
  path: PLAYWRIGHT_PATH,
4712
+ upstreamPath: "/",
4426
4713
  scheme: "ws"
4427
4714
  },
4428
4715
  mcp: {
4429
4716
  path: PLAYWRIGHT_MCP_PATH,
4717
+ upstreamPath: "/mcp",
4430
4718
  scheme: "http"
4431
4719
  }
4432
4720
  };
4721
+ // src/composition/summary.ts
4433
4722
  /**
4434
4723
  * The block logged when the bridge is ready: what listens where, and which child services run.
4435
4724
  * It is the one place to look for the URLs to use and for a component that did not start
4436
4725
  * (docs/usage/operations.md#line-format).
4437
4726
  */
4438
4727
  function readySummary(input) {
4439
- const { config, ports, supervisors } = input;
4728
+ const { config, ports, services } = input;
4440
4729
  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(", ")]];
4441
- for (const name of Object.keys(PATHS)) {
4442
- const { path, scheme } = PATHS[name];
4443
- const { state, version } = supervisors[name].status();
4730
+ for (const name of SERVICE_NAMES) {
4731
+ const { path, scheme } = SERVICE_ROUTES[name];
4732
+ const { state, version } = services[name];
4444
4733
  const urls = reachableUrls(scheme, config.http.host, ports.http).map((url) => `${url}${path}`).join(", ");
4445
4734
  let value;
4446
4735
  if (!config[name].enabled) value = "off (disabled in the config)";
@@ -4592,6 +4881,12 @@ function bindExtendedKeyboard(koffi) {
4592
4881
  keyUp: (key) => send(key, KEYEVENTF_KEYUP$1)
4593
4882
  };
4594
4883
  }
4884
+ // src/composition/koffi.ts
4885
+ /** Loads `koffi`, an optional dependency: rejects where it is not installed or can't run. */
4886
+ async function loadKoffi() {
4887
+ const module = await import("koffi");
4888
+ return module.default ?? module;
4889
+ }
4595
4890
  // src/composition/input.ts
4596
4891
  /**
4597
4892
  * Loads `@jitsi/robotjs`, an optional dependency. When it can't be loaded (no prebuilt binary for
@@ -4617,8 +4912,7 @@ async function createInputInjector(logger) {
4617
4912
  async function createExtendedKeyboard(logger) {
4618
4913
  if (process.platform !== "win32") return void 0;
4619
4914
  try {
4620
- const module = await import("koffi");
4621
- return bindExtendedKeyboard(module.default ?? module);
4915
+ return bindExtendedKeyboard(await loadKoffi());
4622
4916
  } catch (error) {
4623
4917
  const reason = `koffi could not be loaded (${error instanceof Error ? error.message : String(error)})`;
4624
4918
  logger.warn(`the keys numpadenter and numpaddivide are off: ${reason}`);
@@ -4700,7 +4994,6 @@ function bindWin32(koffi) {
4700
4994
  const IsWindowVisible = user32.func("int __stdcall IsWindowVisible(intptr_t hWnd)");
4701
4995
  const GetWindow = user32.func("intptr_t __stdcall GetWindow(intptr_t hWnd, uint32_t uCmd)");
4702
4996
  const GetWindowTextW = user32.func("int __stdcall GetWindowTextW(intptr_t hWnd, _Out_ void *lpString, int nMaxCount)");
4703
- const GetClassNameW = user32.func("int __stdcall GetClassNameW(intptr_t hWnd, _Out_ void *lpClassName, int nMaxCount)");
4704
4997
  const IsIconic = user32.func("int __stdcall IsIconic(intptr_t hWnd)");
4705
4998
  const ShowWindow = user32.func("int __stdcall ShowWindow(intptr_t hWnd, int nCmdShow)");
4706
4999
  const keybd_event = user32.func("void __stdcall keybd_event(uint8_t bVk, uint8_t bScan, uint32_t dwFlags, uintptr_t dwExtraInfo)");
@@ -4749,7 +5042,6 @@ function bindWin32(koffi) {
4749
5042
  isVisible: (hwnd) => IsWindowVisible(hwnd) !== 0,
4750
5043
  ownerWindow: (hwnd) => Number(GetWindow(hwnd, GW_OWNER)),
4751
5044
  title: (hwnd) => text(GetWindowTextW, hwnd),
4752
- className: (hwnd) => text(GetClassNameW, hwnd),
4753
5045
  isMinimized: (hwnd) => IsIconic(hwnd) !== 0,
4754
5046
  restore: (hwnd) => void ShowWindow(hwnd, SW_RESTORE),
4755
5047
  tapAlt() {
@@ -4816,8 +5108,7 @@ var Win32WindowSystem = class {
4816
5108
  windows.push({
4817
5109
  handle: hwnd,
4818
5110
  pid: win32.owner(hwnd).pid,
4819
- title: win32.title(hwnd),
4820
- className: win32.className(hwnd)
5111
+ title: win32.title(hwnd)
4821
5112
  });
4822
5113
  }
4823
5114
  return Promise.resolve(windows);
@@ -4861,8 +5152,7 @@ async function createWindowSystem(logger) {
4861
5152
  return new DisabledWindowSystem("only on Windows");
4862
5153
  }
4863
5154
  try {
4864
- const module = await import("koffi");
4865
- const windows = new Win32WindowSystem(bindWin32(module.default ?? module));
5155
+ const windows = new Win32WindowSystem(bindWin32(await loadKoffi()));
4866
5156
  logger.info("bringing windows to the front is available (koffi)");
4867
5157
  return windows;
4868
5158
  } catch (error) {
@@ -4871,6 +5161,18 @@ async function createWindowSystem(logger) {
4871
5161
  return new DisabledWindowSystem(reason);
4872
5162
  }
4873
5163
  }
5164
+ // src/adapters/out/log/terminal-text.ts
5165
+ /**
5166
+ * Escape sequences (CSI such as colours, OSC such as a window title, and the short ones) and the
5167
+ * other control characters, except tab. Text in log lines comes from outside: speech, session and
5168
+ * client names, the voice header, child process output. A terminal would act on what this removes
5169
+ * (docs/usage/operations.md#line-format).
5170
+ */
5171
+ const CONTROL = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-_]?|\u009b[0-?]*[ -/]*[@-~]|[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g;
5172
+ /** `text` without escape sequences and control characters other than tab (one line). */
5173
+ function stripControlChars(text) {
5174
+ return text.replace(CONTROL, "");
5175
+ }
4874
5176
  // src/adapters/out/log/format.ts
4875
5177
  const ESC = "\x1B[";
4876
5178
  const RESET = `${ESC}0m`;
@@ -4898,12 +5200,13 @@ function paint(text, colour, enabled) {
4898
5200
  /**
4899
5201
  * Formats one message as one or more log lines (without line breaks). Every line of a
4900
5202
  * multi-line message gets the full prefix, timestamp and level. Padding is counted without
4901
- * colour codes.
5203
+ * colour codes. Escape sequences and control characters in the message are removed: only the
5204
+ * bridge's own colours reach the terminal.
4902
5205
  */
4903
5206
  function formatLogLines(prefix, level, time, message, colour) {
4904
5207
  const tag = `[${prefix}]`;
4905
5208
  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);
4906
- return message.split(/\r?\n/).map((line) => head + line);
5209
+ return message.split(/\r?\n/).map((line) => head + stripControlChars(line));
4907
5210
  }
4908
5211
  // src/adapters/out/log/bridge-log.ts
4909
5212
  const LEVEL_RANK = {
@@ -5085,6 +5388,87 @@ function createLogging(config, options) {
5085
5388
  log.always("bridge", startupMessage(config, options.version, options.configLocation, file));
5086
5389
  return log;
5087
5390
  }
5391
+ // src/adapters/out/terminal/terminal-prompt.ts
5392
+ /** Answers that quit instead of naming a port. */
5393
+ const QUIT = /* @__PURE__ */ new Set([
5394
+ "",
5395
+ "q",
5396
+ "quit",
5397
+ "exit"
5398
+ ]);
5399
+ /**
5400
+ * Driven adapter: asks a question on the console and reads one line. Ctrl+C, end of input (Ctrl+D,
5401
+ * Ctrl+Z on Windows) and the `signal` cancel it. It lets go of the input after each question, so
5402
+ * the process can still exit.
5403
+ */
5404
+ var TerminalPrompt = class {
5405
+ options;
5406
+ constructor(options) {
5407
+ this.options = options;
5408
+ }
5409
+ async askForPort(failedPort) {
5410
+ for (;;) {
5411
+ const answer = await this.ask(`TCP port ${failedPort} can't be used. TCP port for the socket voice (Enter to quit): `);
5412
+ if (answer === void 0 || QUIT.has(answer.toLowerCase())) return void 0;
5413
+ if (/^\d+$/.test(answer)) return Number(answer);
5414
+ this.options.warn(`${JSON.stringify(answer)} is not a port number`);
5415
+ }
5416
+ }
5417
+ /**
5418
+ * Shows `question` and resolves with the trimmed answer, or with `undefined` if the person
5419
+ * cancels (Ctrl+C, end of input) or the start is cancelled.
5420
+ */
5421
+ async ask(question) {
5422
+ const { input, output, flush, terminal, signal } = this.options;
5423
+ if (signal?.aborted === true) return void 0;
5424
+ await flush().catch(() => void 0);
5425
+ const rl = createInterface({
5426
+ input,
5427
+ output,
5428
+ ...terminal === void 0 ? {} : { terminal }
5429
+ });
5430
+ const abortQuestion = new AbortController();
5431
+ let settled = false;
5432
+ let cancel = () => void 0;
5433
+ const cancelled = new Promise((resolve) => {
5434
+ cancel = () => {
5435
+ if (settled) return;
5436
+ settled = true;
5437
+ output.write("\n");
5438
+ resolve(void 0);
5439
+ };
5440
+ });
5441
+ rl.once("SIGINT", cancel);
5442
+ rl.once("close", cancel);
5443
+ signal?.addEventListener("abort", cancel, { once: true });
5444
+ try {
5445
+ const answer = rl.question(question, { signal: abortQuestion.signal }).then((line) => line.trim(), () => void 0);
5446
+ const result = await Promise.race([answer, cancelled]);
5447
+ settled = true;
5448
+ return result;
5449
+ } finally {
5450
+ signal?.removeEventListener("abort", cancel);
5451
+ abortQuestion.abort();
5452
+ rl.close();
5453
+ }
5454
+ }
5455
+ };
5456
+ // src/composition/prompt.ts
5457
+ /**
5458
+ * The console prompt, or `undefined` when nobody can answer: stdin or stdout is not a terminal
5459
+ * (a service, CI, a test, output piped to a file). `cancel` ends a pending question.
5460
+ */
5461
+ function createOperatorPrompt(warn, cancel) {
5462
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) return void 0;
5463
+ return new TerminalPrompt({
5464
+ input: process.stdin,
5465
+ output: process.stdout,
5466
+ flush: flushTerminal,
5467
+ warn,
5468
+ terminal: true,
5469
+ ...cancel === void 0 ? {} : { signal: cancel }
5470
+ });
5471
+ }
5088
5472
  // src/composition/pace.ts
5089
5473
  /**
5090
5474
  * A `pace` for a replay or a wait's look through the buffer (`FollowOptions`): lets other work
@@ -5094,25 +5478,28 @@ function yieldEvery(n) {
5094
5478
  let count = 0;
5095
5479
  return () => ++count % n === 0 ? setImmediate() : void 0;
5096
5480
  }
5097
- // src/composition/proxies.ts
5481
+ // src/composition/tcp-startup-hints.ts
5482
+ const VOICE_DOCS = "docs/usage/vm-setup.md#more-voices--other-ports";
5098
5483
  /**
5099
- * The child services' paths on the bridge's HTTP port (docs/usage/playwright-mcp.md): the
5100
- * Playwright server's WebSocket at `/`, MCP's streamable HTTP at `/mcp`.
5484
+ * The ways to set the TCP port by hand, as startup names them. `pinnedBy`: what sets `tcp.port`
5485
+ * if a flag or an environment variable does, for example `--tcp-port`.
5101
5486
  */
5487
+ function tcpStartupHints(configLocation, pinnedBy) {
5488
+ return {
5489
+ ...pinnedBy === void 0 ? {} : { pinned: `${pinnedBy} sets this port: choose a free one there` },
5490
+ choosePort: `Start with --tcp-port <port>, or set tcp.port in ${configLocation}`,
5491
+ pointVoice: `point the socket voice to it (${VOICE_DOCS})`,
5492
+ keepPort: (port) => `start with --tcp-port ${port} next time`
5493
+ };
5494
+ }
5495
+ // src/composition/proxies.ts
5496
+ /** The pass-through of each child service on the bridge's HTTP port. */
5102
5497
  function proxyRoutes(services) {
5103
- return [{
5104
- name: SERVICE_TITLES.playwright,
5105
- path: PLAYWRIGHT_PATH,
5106
- upstreamPath: "/",
5107
- scheme: "ws",
5108
- target: () => services.reachability("playwright")
5109
- }, {
5110
- name: SERVICE_TITLES.mcp,
5111
- path: PLAYWRIGHT_MCP_PATH,
5112
- upstreamPath: "/mcp",
5113
- scheme: "http",
5114
- target: () => services.reachability("mcp")
5115
- }];
5498
+ return SERVICE_NAMES.map((name) => ({
5499
+ name: SERVICE_TITLES[name],
5500
+ ...SERVICE_ROUTES[name],
5501
+ target: () => services.reachability(name)
5502
+ }));
5116
5503
  }
5117
5504
  // src/adapters/shared/net/port-probe.ts
5118
5505
  /** Where to probe a listener on a wildcard host: the loopback address of that family. */
@@ -5136,196 +5523,50 @@ function portOpen(host, port, timeoutMs = 1e3) {
5136
5523
  socket.once("error", () => done(false));
5137
5524
  });
5138
5525
  }
5139
- // src/adapters/out/process/child-process-supervisor.ts
5140
- /** How long the port may take to open after the start, before it counts as a crash. */
5141
- const READY_TIMEOUT_MS = 6e4;
5142
- /**
5143
- * Runs one child service (docs/usage/operations.md#child-service-crashes): prepare, spawn, wait for
5144
- * its port, restart after a crash with a growing delay, give up after too many crashes in a row,
5145
- * and kill the whole process tree on stop.
5146
- */
5147
- var ChildProcessSupervisor = class {
5148
- options;
5149
- settings;
5150
- /** Settings of the current run, until it is stopped. `status()` reports these. */
5151
- active = null;
5152
- state = "stopped";
5153
- restarts = 0;
5154
- exitCode = null;
5155
- lastError = null;
5156
- crashesInRow = 0;
5157
- child = null;
5158
- runningSince = null;
5159
- /** When the current launch began, for the time to `running` in the log. */
5160
- launchedAt = 0;
5161
- restartTimer;
5162
- abort = null;
5163
- /** Bumped by every launch and stop, so callbacks of an older run do nothing. */
5164
- generation = 0;
5165
- waiters = [];
5166
- constructor(options) {
5167
- this.options = options;
5168
- this.settings = options.settings;
5169
- }
5170
- pid() {
5171
- return this.state === "running" ? this.child?.pid ?? null : null;
5172
- }
5173
- status() {
5174
- const { version, port } = this.active ?? this.resolved();
5175
- return {
5176
- state: this.state,
5177
- version,
5178
- port,
5179
- restarts: this.restarts,
5180
- exitCode: this.exitCode,
5181
- lastError: this.lastError
5182
- };
5183
- }
5184
- start() {
5185
- if (this.state === "running") return Promise.resolve();
5186
- const settled = new Promise((resolve) => this.waiters.push(resolve));
5187
- if (this.state === "stopped" || this.state === "failed") {
5188
- this.restarts = 0;
5189
- this.crashesInRow = 0;
5190
- this.exitCode = null;
5191
- this.lastError = null;
5192
- this.launch();
5193
- }
5194
- return settled;
5195
- }
5196
- async stop() {
5197
- this.generation++;
5198
- clearTimeout(this.restartTimer);
5199
- this.abort?.abort();
5200
- this.abort = null;
5201
- const child = this.child;
5202
- this.child = null;
5203
- this.runningSince = null;
5204
- this.active = null;
5205
- const wasStopped = this.state === "stopped";
5206
- this.setState("stopped");
5207
- if (!wasStopped) this.options.logger.info(`${this.options.name} stopped`);
5208
- if (child) await killTree(child);
5209
- }
5210
- resolved() {
5211
- const { host, port, version } = this.settings;
5212
- return {
5213
- host,
5214
- port,
5215
- version: version ?? this.options.defaultVersion
5216
- };
5217
- }
5218
- setState(state) {
5219
- this.state = state;
5220
- if (state === "running" || state === "failed" || state === "stopped") for (const resolve of this.waiters.splice(0)) resolve();
5221
- }
5222
- launch() {
5223
- const generation = ++this.generation;
5224
- const current = () => generation === this.generation;
5225
- const settings = this.resolved();
5226
- this.active = settings;
5227
- const abort = new AbortController();
5228
- this.abort = abort;
5229
- this.setState("starting");
5230
- this.launchedAt = Date.now();
5231
- this.options.logger.info(`starting ${this.options.name} ${settings.version}`);
5232
- const failed = (how, error) => {
5233
- if (!current()) return;
5234
- const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
5235
- this.options.logger.error(`${this.options.name} ${cause}`);
5236
- this.crashed(null, "failed to start", cause);
5237
- };
5238
- this.options.prepare(settings, abort.signal).then(async (command) => {
5239
- if (!current()) return;
5240
- if (await portOpen(settings.host, settings.port)) {
5241
- if (!current()) return;
5242
- const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
5243
- this.options.logger.error(`${this.options.name}: ${cause}`);
5244
- this.crashed(null, "could not start", cause);
5245
- return;
5246
- }
5247
- if (current()) this.spawn(command, settings, generation);
5248
- }, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
5249
- }
5250
- spawn(command, settings, generation) {
5251
- const current = () => generation === this.generation;
5252
- const child = spawn(command.command, [...command.args], {
5253
- ...treeSpawnOptions,
5254
- stdio: [
5255
- "ignore",
5256
- "pipe",
5257
- "pipe"
5258
- ]
5259
- });
5260
- this.child = child;
5261
- trackTree(child);
5262
- pipeLines(child, this.options.output);
5263
- let exited = false;
5264
- let cause;
5265
- const onExit = (code, signal) => {
5266
- if (exited) return;
5267
- exited = true;
5268
- if (!current()) return;
5269
- this.child = null;
5270
- killTree(child);
5271
- const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
5272
- this.crashed(code, what, cause);
5273
- };
5274
- child.once("exit", onExit);
5275
- child.once("error", (error) => {
5276
- const failure = `could not be started: ${error.message}`;
5277
- this.options.logger.error(`${this.options.name} ${failure}`);
5278
- if (child.pid === void 0) {
5279
- cause = failure;
5280
- onExit(null, null);
5281
- }
5282
- });
5283
- this.waitForPort(settings, generation, () => exited).then((open) => {
5284
- if (!current() || exited) return;
5285
- if (open) {
5286
- this.runningSince = Date.now();
5287
- this.setState("running");
5288
- const seconds = ((Date.now() - this.launchedAt) / 1e3).toFixed(1);
5289
- this.options.logger.info(`${this.options.name} running (${seconds}s)`);
5290
- } else {
5291
- cause = `did not open port ${settings.port} in time`;
5292
- this.options.logger.error(`${this.options.name} ${cause}, killing it`);
5293
- killTree(child);
5294
- }
5526
+ // src/adapters/out/process/child-process-runner.ts
5527
+ function run(command, { output, hiddenEnv }) {
5528
+ const env = { ...process.env };
5529
+ for (const name of hiddenEnv ?? []) delete env[name];
5530
+ const child = spawn(command.command, [...command.args], {
5531
+ ...treeSpawnOptions,
5532
+ env,
5533
+ stdio: [
5534
+ "ignore",
5535
+ "pipe",
5536
+ "pipe"
5537
+ ]
5538
+ });
5539
+ trackTree(child);
5540
+ pipeLines(child, output);
5541
+ const exited = new Promise((resolve) => {
5542
+ child.once("exit", (code, signal) => resolve({
5543
+ code,
5544
+ signal
5545
+ }));
5546
+ child.on("error", (error) => {
5547
+ if (child.pid === void 0) resolve({
5548
+ code: null,
5549
+ signal: null,
5550
+ failure: error.message
5551
+ });
5552
+ else output.warn(`process error: ${error.message}`);
5295
5553
  });
5296
- }
5297
- async waitForPort(settings, generation, exited) {
5298
- const deadline = Date.now() + READY_TIMEOUT_MS;
5299
- while (generation === this.generation && !exited() && Date.now() < deadline) {
5300
- if (await portOpen(settings.host, settings.port)) return true;
5301
- await setTimeout$1(this.options.probeIntervalMs ?? 200);
5302
- }
5303
- return false;
5304
- }
5305
- /** `what` goes to the log, `cause` to the status. */
5306
- crashed(code, what, cause = what) {
5307
- const { name, logger } = this.options;
5308
- const ranForMs = this.runningSince === null ? 0 : Date.now() - this.runningSince;
5309
- this.runningSince = null;
5310
- this.exitCode = code;
5311
- this.lastError = cause;
5312
- const decision = nextAfterCrash(this.crashesInRow, ranForMs, this.options.policy);
5313
- this.crashesInRow = decision.crashesInRow;
5314
- if (decision.action === "fail") {
5315
- logger.error(`${name} ${what}, ${decision.crashesInRow} crashes in a row: giving up. Restart the bridge to try again`);
5316
- this.setState("failed");
5317
- return;
5318
- }
5319
- logger.error(`${name} ${what}, restart ${this.restarts + 1} in ${formatDelay(decision.delayMs)}`);
5320
- this.setState("crashed");
5321
- this.restartTimer = setTimeout(() => {
5322
- this.restarts++;
5323
- this.launch();
5324
- }, decision.delayMs);
5325
- }
5326
- };
5327
- function formatDelay(ms) {
5328
- return ms >= 1e3 ? `${ms / 1e3} s` : `${ms} ms`;
5554
+ });
5555
+ return {
5556
+ pid: child.pid ?? null,
5557
+ exited,
5558
+ kill: () => killTree(child)
5559
+ };
5560
+ }
5561
+ /** A child service as processes without a shell, whose whole tree `kill` ends. */
5562
+ function childProcessRunner(options) {
5563
+ return {
5564
+ prepare: async (settings, signal) => {
5565
+ const command = await options.prepare(settings, signal);
5566
+ return () => run(command, options);
5567
+ },
5568
+ portOpen
5569
+ };
5329
5570
  }
5330
5571
  // src/adapters/out/process/quiet-output.ts
5331
5572
  /**
@@ -5420,7 +5661,7 @@ function bundledMcp() {
5420
5661
  };
5421
5662
  }
5422
5663
  /**
5423
- * Supervisor for Playwright MCP in HTTP mode, the bundled version. Each start first runs
5664
+ * Playwright MCP in HTTP mode, the bundled version, as a child service. Each start first runs
5424
5665
  * `cli.js install-browser --no-shell chromium`, which installs the Chromium of MCP's own
5425
5666
  * Playwright and skips a build that is already there. It listens on loopback, and clients reach
5426
5667
  * it through the bridge, which sends a loopback `Host`: MCP's own host check (by default
@@ -5452,17 +5693,16 @@ function playwrightMcp(options) {
5452
5693
  ]
5453
5694
  };
5454
5695
  };
5455
- return new ChildProcessSupervisor({
5456
- name: "mcp",
5457
- settings: options.settings,
5458
- defaultVersion: version,
5459
- prepare: options.launch ?? prepare,
5460
- logger: options.logger,
5461
- output,
5462
- ...options.policy ? { policy: options.policy } : {}
5463
- });
5696
+ return {
5697
+ runner: childProcessRunner({
5698
+ prepare: options.launch ?? prepare,
5699
+ output,
5700
+ hiddenEnv: options.hiddenEnv
5701
+ }),
5702
+ defaultVersion: version
5703
+ };
5464
5704
  }
5465
- // src/domain/version.ts
5705
+ // src/adapters/out/npm/exact-version.ts
5466
5706
  /**
5467
5707
  * An exact npm version (`1.56.1`, `1.57.0-beta-1`). Versions end up on an `npm install` command
5468
5708
  * line (`playwright.version`, `adapters/out/npm`), so nothing else may get through.
@@ -5578,7 +5818,7 @@ async function ensurePlaywright(options) {
5578
5818
  * version (docs/usage/playwright-mcp.md#playwright-server).
5579
5819
  */
5580
5820
  const DEFAULT_PLAYWRIGHT_VERSION = "1.65.1";
5581
- /** Supervisor for `playwright run-server` in the configured version. */
5821
+ /** `playwright run-server` in the configured version, as a child service. */
5582
5822
  function playwrightServer(options) {
5583
5823
  const { cacheRoot } = options;
5584
5824
  const output = quietOutput(options.output, listeningLine);
@@ -5602,34 +5842,236 @@ function playwrightServer(options) {
5602
5842
  ]
5603
5843
  };
5604
5844
  };
5605
- return new ChildProcessSupervisor({
5606
- name: "playwright",
5607
- settings: options.settings,
5608
- defaultVersion: DEFAULT_PLAYWRIGHT_VERSION,
5609
- prepare: options.launch ?? prepare,
5610
- logger: options.logger,
5611
- output,
5612
- ...options.policy ? { policy: options.policy } : {}
5613
- });
5845
+ return {
5846
+ runner: childProcessRunner({
5847
+ prepare: options.launch ?? prepare,
5848
+ output,
5849
+ hiddenEnv: options.hiddenEnv
5850
+ }),
5851
+ defaultVersion: DEFAULT_PLAYWRIGHT_VERSION
5852
+ };
5853
+ }
5854
+ // src/application/services/supervised-service.ts
5855
+ /** How long the port may take to open after the start, before it counts as a crash. */
5856
+ const READY_TIMEOUT_MS = 6e4;
5857
+ /**
5858
+ * Runs one child service (docs/usage/operations.md#child-service-crashes): prepare, spawn, wait for
5859
+ * its port, restart after a crash with a growing delay, give up after too many crashes in a row,
5860
+ * and end the whole process tree on stop.
5861
+ */
5862
+ var SupervisedService = class {
5863
+ deps;
5864
+ /** Settings of the current run, until it is stopped. `status()` reports these. */
5865
+ active = null;
5866
+ state = "stopped";
5867
+ restarts = 0;
5868
+ exitCode = null;
5869
+ lastError = null;
5870
+ crashesInRow = 0;
5871
+ child = null;
5872
+ runningSince = null;
5873
+ /** When the current launch began, for the time to `running` in the log. */
5874
+ launchedAt = 0;
5875
+ /** Of the current launch: aborting it ends its preparation and its waits. */
5876
+ abort = null;
5877
+ /** Bumped by every launch and stop, so callbacks of an older run do nothing. */
5878
+ generation = 0;
5879
+ waiters = [];
5880
+ constructor(deps) {
5881
+ this.deps = deps;
5882
+ }
5883
+ pid() {
5884
+ return this.state === "running" ? this.child?.pid ?? null : null;
5885
+ }
5886
+ status() {
5887
+ const { version, port } = this.active ?? this.resolved();
5888
+ return {
5889
+ state: this.state,
5890
+ version,
5891
+ port,
5892
+ restarts: this.restarts,
5893
+ exitCode: this.exitCode,
5894
+ lastError: this.lastError
5895
+ };
5896
+ }
5897
+ start() {
5898
+ if (this.state === "running") return Promise.resolve();
5899
+ const settled = new Promise((resolve) => this.waiters.push(resolve));
5900
+ if (this.state === "stopped" || this.state === "failed") {
5901
+ this.restarts = 0;
5902
+ this.crashesInRow = 0;
5903
+ this.exitCode = null;
5904
+ this.lastError = null;
5905
+ this.launch();
5906
+ }
5907
+ return settled;
5908
+ }
5909
+ async stop() {
5910
+ this.generation++;
5911
+ this.abort?.abort();
5912
+ this.abort = null;
5913
+ const child = this.child;
5914
+ this.child = null;
5915
+ this.runningSince = null;
5916
+ this.active = null;
5917
+ const wasStopped = this.state === "stopped";
5918
+ this.setState("stopped");
5919
+ if (!wasStopped) this.deps.logger.info(`${this.deps.name} stopped`);
5920
+ if (child) await child.kill();
5921
+ }
5922
+ resolved() {
5923
+ const { host, port, version } = this.deps.settings;
5924
+ return {
5925
+ host,
5926
+ port,
5927
+ version: version ?? this.deps.defaultVersion
5928
+ };
5929
+ }
5930
+ setState(state) {
5931
+ this.state = state;
5932
+ if (state === "running" || state === "failed" || state === "stopped") for (const resolve of this.waiters.splice(0)) resolve();
5933
+ }
5934
+ launch() {
5935
+ const generation = ++this.generation;
5936
+ const current = () => generation === this.generation;
5937
+ const { name, runner, logger } = this.deps;
5938
+ const settings = this.resolved();
5939
+ this.active = settings;
5940
+ const abort = new AbortController();
5941
+ this.abort = abort;
5942
+ this.setState("starting");
5943
+ this.launchedAt = this.now();
5944
+ logger.info(`starting ${name} ${settings.version}`);
5945
+ const failed = (how, error) => {
5946
+ if (!current()) return;
5947
+ const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
5948
+ logger.error(`${name} ${cause}`);
5949
+ this.crashed(null, "failed to start", cause);
5950
+ };
5951
+ runner.prepare(settings, abort.signal).then(async (spawn) => {
5952
+ if (!current()) return;
5953
+ if (await runner.portOpen(settings.host, settings.port)) {
5954
+ if (!current()) return;
5955
+ const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
5956
+ logger.error(`${name}: ${cause}`);
5957
+ this.crashed(null, "could not start", cause);
5958
+ return;
5959
+ }
5960
+ if (current()) this.watch(spawn(), settings, generation, abort.signal);
5961
+ }, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
5962
+ }
5963
+ /** Follows a spawned child: until its port opens, and until it ends. */
5964
+ watch(child, settings, generation, signal) {
5965
+ const current = () => generation === this.generation;
5966
+ const { name, logger } = this.deps;
5967
+ this.child = child;
5968
+ let exited = false;
5969
+ let cause;
5970
+ child.exited.then(({ code, signal, failure }) => {
5971
+ exited = true;
5972
+ if (!current()) return;
5973
+ this.child = null;
5974
+ child.kill();
5975
+ if (failure !== void 0) {
5976
+ cause = `could not be started: ${failure}`;
5977
+ logger.error(`${name} ${cause}`);
5978
+ }
5979
+ const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
5980
+ this.crashed(code, what, cause);
5981
+ });
5982
+ this.waitForPort(settings, signal, () => exited).then((open) => {
5983
+ if (!current() || exited) return;
5984
+ if (open) {
5985
+ this.runningSince = this.now();
5986
+ this.setState("running");
5987
+ const seconds = ((this.now() - this.launchedAt) / 1e3).toFixed(1);
5988
+ logger.info(`${name} running (${seconds}s)`);
5989
+ } else {
5990
+ cause = `did not open port ${settings.port} in time`;
5991
+ logger.error(`${name} ${cause}, killing it`);
5992
+ child.kill();
5993
+ }
5994
+ });
5995
+ }
5996
+ async waitForPort(settings, signal, exited) {
5997
+ const { runner, clock, probeIntervalMs = 200 } = this.deps;
5998
+ const deadline = this.now() + READY_TIMEOUT_MS;
5999
+ while (!signal.aborted && !exited() && this.now() < deadline) {
6000
+ if (await runner.portOpen(settings.host, settings.port)) return true;
6001
+ await clock.sleep(probeIntervalMs, signal).catch(() => void 0);
6002
+ }
6003
+ return false;
6004
+ }
6005
+ /** `what` goes to the log, `cause` to the status. */
6006
+ crashed(code, what, cause = what) {
6007
+ const { name, logger, clock, policy } = this.deps;
6008
+ const ranForMs = this.runningSince === null ? 0 : this.now() - this.runningSince;
6009
+ this.runningSince = null;
6010
+ this.exitCode = code;
6011
+ this.lastError = cause;
6012
+ const decision = nextAfterCrash(this.crashesInRow, ranForMs, policy);
6013
+ this.crashesInRow = decision.crashesInRow;
6014
+ if (decision.action === "fail") {
6015
+ logger.error(`${name} ${what}, ${decision.crashesInRow} crashes in a row: giving up. Restart the bridge to try again`);
6016
+ this.setState("failed");
6017
+ return;
6018
+ }
6019
+ logger.error(`${name} ${what}, restart ${this.restarts + 1} in ${formatDelay(decision.delayMs)}`);
6020
+ this.setState("crashed");
6021
+ clock.sleep(decision.delayMs, this.abort?.signal).then(() => {
6022
+ this.restarts++;
6023
+ this.launch();
6024
+ }, () => void 0);
6025
+ }
6026
+ now() {
6027
+ return this.deps.clock.now().getTime();
6028
+ }
6029
+ };
6030
+ function formatDelay(ms) {
6031
+ return ms >= 1e3 ? `${ms / 1e3} s` : `${ms} ms`;
6032
+ }
6033
+ // src/composition/service-settings.ts
6034
+ /** A service's settings from the config: the Playwright server in the configured version, MCP in the bundled one. */
6035
+ function serviceSettings(name, config) {
6036
+ if (name === "playwright") {
6037
+ const { port, version } = config.playwright;
6038
+ return {
6039
+ host: CHILD_HOST,
6040
+ port,
6041
+ version
6042
+ };
6043
+ }
6044
+ return {
6045
+ host: CHILD_HOST,
6046
+ port: config.mcp.port,
6047
+ version: null
6048
+ };
5614
6049
  }
5615
6050
  // src/composition/services.ts
5616
6051
  /** One supervisor per child service, not started yet (`ChildServicesService` runs them). */
5617
- function createSupervisors(config, options, log) {
6052
+ function createSupervisors(config, options, log, clock) {
5618
6053
  const logger = log.for("bridge");
6054
+ const supervise = (name, program) => new SupervisedService({
6055
+ name,
6056
+ settings: serviceSettings(name, config),
6057
+ ...program,
6058
+ clock,
6059
+ logger
6060
+ });
6061
+ const playwright = playwrightServer({
6062
+ cacheRoot: options.playwrightDir ?? defaultPlaywrightDir(),
6063
+ output: log.for("playwright-server"),
6064
+ hiddenEnv: UI_ENV_NAMES,
6065
+ ...options.playwrightLaunch ? { launch: options.playwrightLaunch } : {}
6066
+ });
6067
+ const mcp = playwrightMcp({
6068
+ output: log.for("playwright-mcp"),
6069
+ hiddenEnv: UI_ENV_NAMES,
6070
+ ...options.mcpLaunch ? { launch: options.mcpLaunch } : {}
6071
+ });
5619
6072
  return {
5620
- playwright: playwrightServer({
5621
- settings: serviceSettings("playwright", config),
5622
- cacheRoot: options.playwrightDir ?? defaultPlaywrightDir(),
5623
- logger,
5624
- output: log.for("playwright-server"),
5625
- ...options.playwrightLaunch ? { launch: options.playwrightLaunch } : {}
5626
- }),
5627
- mcp: playwrightMcp({
5628
- settings: serviceSettings("mcp", config),
5629
- logger,
5630
- output: log.for("playwright-mcp"),
5631
- ...options.mcpLaunch ? { launch: options.mcpLaunch } : {}
5632
- })
6073
+ playwright: supervise("playwright", playwright),
6074
+ mcp: supervise("mcp", mcp)
5633
6075
  };
5634
6076
  }
5635
6077
  // src/domain/capture.ts
@@ -5771,6 +6213,9 @@ var SeqQueue = class {
5771
6213
  * - At most one session is current. The log keeps the current session and the ended ones with
5772
6214
  * entries still in the buffer; an ended session is forgotten once its last entry is dropped or
5773
6215
  * cleared, and `id`s are never given out twice.
6216
+ * - Every change is reported to `onEvent`, once the log is in its new state, so no caller can
6217
+ * forget it. Deleting a session reports nothing
6218
+ * (docs/implementation/decisions.md#deleting-a-session-is-a-400-for-the-current-one-and-sends-no-event).
5774
6219
  *
5775
6220
  * Adding, dropping and the session statistics are O(1), reading after a `seq` is O(log n).
5776
6221
  */
@@ -5792,7 +6237,10 @@ var SpeechLog = class {
5792
6237
  #currentId = null;
5793
6238
  /** The newest session id given out, `runStart - 1` before the first session. */
5794
6239
  #lastSessionId;
5795
- constructor(maxEntries, runStart = 1) {
6240
+ #onEvent;
6241
+ /** @param onEvent Gets every change (the composition root publishes it on the event bus). */
6242
+ constructor(maxEntries, runStart = 1, onEvent = () => {}) {
6243
+ this.#onEvent = onEvent;
5796
6244
  this.#maxEntries = maxEntries;
5797
6245
  this.#runStart = runStart;
5798
6246
  this.#nextSeq = runStart;
@@ -5812,10 +6260,15 @@ var SpeechLog = class {
5812
6260
  get lastSpeechAt() {
5813
6261
  return this.#lastSpeechAt;
5814
6262
  }
5815
- /** Stores an entry in the current session (if any) and returns it with its `seq`. */
6263
+ /**
6264
+ * Stores an entry in the current session (if any) and returns it with its `seq`. A marker's text
6265
+ * is a label (`markerLabel`): trimmed, `INVALID_REQUEST` if empty or too long.
6266
+ */
5816
6267
  append(draft) {
6268
+ const text = draft.kind === "marker" ? markerLabel(draft.text) : draft.text;
5817
6269
  const entry = {
5818
6270
  ...draft,
6271
+ text,
5819
6272
  seq: this.#nextSeq++,
5820
6273
  sessionId: this.#currentId
5821
6274
  };
@@ -5828,6 +6281,10 @@ var SpeechLog = class {
5828
6281
  own.push(entry);
5829
6282
  if (entry.kind === "speech") this.#lastSpeechAt = entry.receivedAt;
5830
6283
  this.#trim();
6284
+ this.#onEvent({
6285
+ type: "entry",
6286
+ entry
6287
+ });
5831
6288
  return entry;
5832
6289
  }
5833
6290
  /**
@@ -5854,7 +6311,8 @@ var SpeechLog = class {
5854
6311
  * session (`null`: outside sessions). `undefined` if there is none (also when it was dropped).
5855
6312
  */
5856
6313
  latestMarker(label, sessionId) {
5857
- return (sessionId === void 0 ? this.#entries : this.#bySession.get(sessionId))?.findLast((entry) => entry.kind === "marker" && entry.text === label);
6314
+ const text = markerLabel(label);
6315
+ return (sessionId === void 0 ? this.#entries : this.#bySession.get(sessionId))?.findLast((entry) => entry.kind === "marker" && entry.text === text);
5858
6316
  }
5859
6317
  /**
5860
6318
  * Removes the entries (and markers) of the current session or of the entries outside sessions
@@ -5869,6 +6327,10 @@ var SpeechLog = class {
5869
6327
  this.#entries.removeWhere((entry) => entry.sessionId === scope);
5870
6328
  this.#bySession.delete(scope);
5871
6329
  this.#droppedBySession.delete(scope);
6330
+ this.#onEvent({
6331
+ type: "clear",
6332
+ sessionId: scope
6333
+ });
5872
6334
  return scope;
5873
6335
  }
5874
6336
  /** Removes all entries and the ended sessions. The current session stays current. */
@@ -5878,6 +6340,7 @@ var SpeechLog = class {
5878
6340
  this.#droppedUpToSeq = 0;
5879
6341
  this.#droppedBySession.clear();
5880
6342
  for (const session of this.#sessions.values()) if (session.endedAt !== null) this.#sessions.delete(session.id);
6343
+ this.#onEvent({ type: "clear" });
5881
6344
  }
5882
6345
  stats() {
5883
6346
  return {
@@ -5887,20 +6350,38 @@ var SpeechLog = class {
5887
6350
  lastSeq: this.#entries.last()?.seq ?? null
5888
6351
  };
5889
6352
  }
5890
- /** Ends the current session, if any, and starts a new current one. */
6353
+ /**
6354
+ * Ends the current session, if any, and starts a new current one. Its `name`, `run` and `client`
6355
+ * are labels (`sessionLabel`): trimmed, `INVALID_REQUEST` if empty or too long.
6356
+ */
5891
6357
  startSession(session) {
5892
- const ended = this.endSession(session.startedAt);
6358
+ const name = sessionLabel("name", session.name);
6359
+ const run = session.run === null ? null : sessionLabel("run", session.run);
6360
+ const client = session.client === null ? null : sessionLabel("client", session.client);
6361
+ const ended = this.#end(session.startedAt);
5893
6362
  const started = {
5894
6363
  ...session,
6364
+ name,
6365
+ run,
6366
+ client,
5895
6367
  id: ++this.#lastSessionId,
5896
6368
  endedAt: null,
5897
6369
  startSeq: this.headSeq
5898
6370
  };
5899
6371
  this.#sessions.set(started.id, started);
5900
6372
  this.#currentId = started.id;
6373
+ const summary = summarize(started, EMPTY_SESSION_STATS);
6374
+ if (ended) this.#onEvent({
6375
+ type: "session",
6376
+ session: ended
6377
+ });
6378
+ this.#onEvent({
6379
+ type: "session",
6380
+ session: summary
6381
+ });
5901
6382
  return {
5902
6383
  ended,
5903
- started: summarize(started, EMPTY_SESSION_STATS)
6384
+ started: summary
5904
6385
  };
5905
6386
  }
5906
6387
  /**
@@ -5909,6 +6390,15 @@ var SpeechLog = class {
5909
6390
  * never gave out.
5910
6391
  */
5911
6392
  endSession(endedAt, id) {
6393
+ const ended = this.#end(endedAt, id);
6394
+ if (ended) this.#onEvent({
6395
+ type: "session",
6396
+ session: ended
6397
+ });
6398
+ return ended;
6399
+ }
6400
+ /** {@link endSession} without reporting it, for a change that isn't complete yet. */
6401
+ #end(endedAt, id) {
5912
6402
  if (id !== void 0) this.#requireIssued(id);
5913
6403
  const current = this.currentSession();
5914
6404
  if (!current || id !== void 0 && current.id !== id) return null;
@@ -6009,10 +6499,9 @@ async function flushOutput() {
6009
6499
  await flushTerminal();
6010
6500
  await flushConsole();
6011
6501
  }
6012
- const show = (value) => JSON.stringify(value);
6013
6502
  /** A busy port needs no stack: the message says what to do. Anything else is unexpected. */
6014
6503
  function describeStartFailure(error) {
6015
- if (error instanceof ListenError) return error.message;
6504
+ if (error instanceof ListenError || error instanceof PortUnavailableError) return error.message;
6016
6505
  return error instanceof Error ? error.stack ?? String(error) : String(error);
6017
6506
  }
6018
6507
  /**
@@ -6024,8 +6513,7 @@ async function startBridge(options) {
6024
6513
  const { version } = options;
6025
6514
  const seams = options.testSeams ?? {};
6026
6515
  const store = seams.configStore ?? new FsConfigStore(options.configFile ?? defaultConfigFile());
6027
- const sourceOf = (field) => options.overrideSources?.get(field) ?? "a flag or environment variable";
6028
- const { config, file: savedFile, overrides, unknown: unknownSettings, ignored, warnings } = await loadConfig(store, options.overrides, sourceOf);
6516
+ const { config, file: savedFile, unknownSettings, pinned, warnings } = await loadConfig(store, options.overrides, options.overrideSources);
6029
6517
  const log = createLogging(config, {
6030
6518
  version,
6031
6519
  configLocation: store.location,
@@ -6034,13 +6522,11 @@ async function startBridge(options) {
6034
6522
  const bridgeLogger = log.for("bridge");
6035
6523
  const configLogger = log.for("config");
6036
6524
  for (const warning of warnings) configLogger.warn(warning);
6037
- for (const name of ignored) configLogger.warn(`${name}: unknown setting in ${store.location}, ignored`);
6038
- 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`);
6039
6525
  try {
6040
6526
  const clock = seams.clock ?? new SystemClock();
6041
6527
  const startedAt = clock.now();
6042
- const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
6043
6528
  const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
6529
+ const speechLog = new SpeechLog(config.buffer.maxEntries, firstSeqOfRun(startedAt.getTime()), (event) => events.publish(event));
6044
6530
  new TranscriptService({
6045
6531
  events,
6046
6532
  transcript: log.for("speech-capture", { channel: "speech" })
@@ -6061,20 +6547,23 @@ async function startBridge(options) {
6061
6547
  });
6062
6548
  const sessions = new SessionService({
6063
6549
  log: speechLog,
6064
- events,
6065
6550
  clock,
6066
6551
  logger: log.for("bridge")
6067
6552
  });
6068
6553
  const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
6069
6554
  const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
6070
- const supervisors = createSupervisors(config, seams, log);
6555
+ const supervisors = createSupervisors(config, seams, log, clock);
6556
+ const inputQueue = new SerialInputQueue({
6557
+ shutdown: shutdown.signal,
6558
+ logger: log.for("native-input")
6559
+ });
6071
6560
  const input = new NativeInputService({
6561
+ queue: inputQueue,
6072
6562
  injector,
6073
6563
  windows,
6074
6564
  services: supervisors,
6075
6565
  clock,
6076
- logger: log.for("native-input"),
6077
- shutdown: shutdown.signal
6566
+ logger: log.for("native-input")
6078
6567
  });
6079
6568
  const captures = new InputCaptureService({
6080
6569
  input,
@@ -6090,23 +6579,38 @@ async function startBridge(options) {
6090
6579
  active: config,
6091
6580
  file: savedFile,
6092
6581
  unknownSettings,
6093
- pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
6582
+ pinned
6094
6583
  });
6095
6584
  const focus = new WindowFocusService({
6096
6585
  windows,
6097
- queue: input,
6586
+ queue: inputQueue,
6098
6587
  services: supervisors,
6099
6588
  clock,
6100
6589
  logger: log.for("native-input")
6101
6590
  });
6102
6591
  const childServices = new ChildServicesService({
6103
6592
  supervisors,
6104
- config: () => configService.get(),
6105
- logger: bridgeLogger
6593
+ config: () => configService.get()
6106
6594
  });
6107
6595
  const captureState = new CaptureState(() => clock.now());
6108
6596
  const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
6597
+ const prompt = seams.prompt === void 0 ? createOperatorPrompt((message) => configLogger.warn(message), options.cancelStart) : seams.prompt;
6598
+ const tcpStartup = new TcpStartupService({
6599
+ listener: {
6600
+ start: (port) => tcp.start({
6601
+ ...config.tcp,
6602
+ port
6603
+ }),
6604
+ stop: () => tcp.stop()
6605
+ },
6606
+ config: configService,
6607
+ hints: tcpStartupHints(store.location, pinned.get("tcp.port")),
6608
+ ...prompt === null || prompt === void 0 ? {} : { prompt },
6609
+ configLocation: store.location,
6610
+ logger: configLogger
6611
+ });
6109
6612
  const status = new StatusService({
6613
+ state: () => lifecycle.state(),
6110
6614
  capture: captureState,
6111
6615
  log: speechLog,
6112
6616
  supervisors,
@@ -6134,11 +6638,7 @@ async function startBridge(options) {
6134
6638
  ...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
6135
6639
  });
6136
6640
  const lifecycle = new BridgeLifecycleService({
6137
- state: status,
6138
- tcp: {
6139
- start: () => tcp.start(config.tcp),
6140
- stop: () => tcp.stop()
6141
- },
6641
+ tcp: tcpStartup,
6142
6642
  http: {
6143
6643
  start: () => http.start(config.http),
6144
6644
  stop: () => http.stop()
@@ -6147,9 +6647,9 @@ async function startBridge(options) {
6147
6647
  services: childServices,
6148
6648
  shutdown,
6149
6649
  readyMessage: (ports) => readySummary({
6150
- config,
6650
+ config: configService.get(),
6151
6651
  ports,
6152
- supervisors,
6652
+ services: status.status().services,
6153
6653
  webUi: ui !== void 0,
6154
6654
  nativeInput: injector.availability,
6155
6655
  tookMs: clock.now().getTime() - startedAt.getTime()
@@ -6413,8 +6913,9 @@ if (options.version) {
6413
6913
  process.exit(0);
6414
6914
  }
6415
6915
  try {
6416
- await runUntilStopped(() => startBridge({
6916
+ await runUntilStopped((cancelStart) => startBridge({
6417
6917
  version,
6918
+ cancelStart,
6418
6919
  overrides: options.overrides,
6419
6920
  overrideSources: options.sources,
6420
6921
  ...options.configFile === void 0 ? {} : { configFile: options.configFile }