screenreader-speech-capture 0.8.2 → 0.9.0-feat-bridge-focus-window.23

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 (176) hide show
  1. package/dist/cli.mjs +906 -249
  2. package/dist/ui/adapter-node.js +1 -1
  3. package/dist/ui/client/ui/_app/immutable/chunks/{CM9WugkD.js → 0YgL1EU2.js} +36 -36
  4. package/dist/ui/client/ui/_app/immutable/chunks/0YgL1EU2.js.br +0 -0
  5. package/dist/ui/client/ui/_app/immutable/chunks/0YgL1EU2.js.gz +0 -0
  6. package/dist/ui/client/ui/_app/immutable/chunks/BYvlzyV8.js +1 -0
  7. package/dist/ui/client/ui/_app/immutable/chunks/BYvlzyV8.js.br +2 -0
  8. package/dist/ui/client/ui/_app/immutable/chunks/BYvlzyV8.js.gz +0 -0
  9. package/dist/ui/client/ui/_app/immutable/chunks/BfvDkxmG.js +3 -0
  10. package/dist/ui/client/ui/_app/immutable/chunks/BfvDkxmG.js.br +0 -0
  11. package/dist/ui/client/ui/_app/immutable/chunks/BfvDkxmG.js.gz +0 -0
  12. package/dist/ui/client/ui/_app/immutable/chunks/CSCPyqWx.js +1 -0
  13. package/dist/ui/client/ui/_app/immutable/chunks/CSCPyqWx.js.br +3 -0
  14. package/dist/ui/client/ui/_app/immutable/chunks/CSCPyqWx.js.gz +0 -0
  15. package/dist/ui/client/ui/_app/immutable/chunks/{Fimt9aTv.js → Cba3ZwaX.js} +11 -11
  16. package/dist/ui/client/ui/_app/immutable/chunks/Cba3ZwaX.js.br +0 -0
  17. package/dist/ui/client/ui/_app/immutable/chunks/Cba3ZwaX.js.gz +0 -0
  18. package/dist/ui/client/ui/_app/immutable/chunks/DErxe_FC.js +3 -0
  19. package/dist/ui/client/ui/_app/immutable/chunks/DErxe_FC.js.br +0 -0
  20. package/dist/ui/client/ui/_app/immutable/chunks/DErxe_FC.js.gz +0 -0
  21. package/dist/ui/client/ui/_app/immutable/chunks/Dqufijaz.js +1 -0
  22. package/dist/ui/client/ui/_app/immutable/chunks/Dqufijaz.js.br +0 -0
  23. package/dist/ui/client/ui/_app/immutable/chunks/Dqufijaz.js.gz +0 -0
  24. package/dist/ui/client/ui/_app/immutable/chunks/WpCriteK.js +1 -0
  25. package/dist/ui/client/ui/_app/immutable/chunks/WpCriteK.js.br +1 -0
  26. package/dist/ui/client/ui/_app/immutable/chunks/WpCriteK.js.gz +0 -0
  27. package/dist/ui/client/ui/_app/immutable/chunks/wbLSPbHY.js +4 -0
  28. package/dist/ui/client/ui/_app/immutable/chunks/wbLSPbHY.js.br +0 -0
  29. package/dist/ui/client/ui/_app/immutable/chunks/wbLSPbHY.js.gz +0 -0
  30. package/dist/ui/client/ui/_app/immutable/entry/app.B6hhDf4F.js +2 -0
  31. package/dist/ui/client/ui/_app/immutable/entry/app.B6hhDf4F.js.br +0 -0
  32. package/dist/ui/client/ui/_app/immutable/entry/app.B6hhDf4F.js.gz +0 -0
  33. package/dist/ui/client/ui/_app/immutable/entry/{start.uodUAHNT.js → start.Dluk7nQO.js} +2 -2
  34. package/dist/ui/client/ui/_app/immutable/entry/start.Dluk7nQO.js.br +0 -0
  35. package/dist/ui/client/ui/_app/immutable/entry/start.Dluk7nQO.js.gz +0 -0
  36. package/dist/ui/client/ui/_app/immutable/nodes/0.D-lhv0Us.js +1 -0
  37. package/dist/ui/client/ui/_app/immutable/nodes/0.D-lhv0Us.js.br +0 -0
  38. package/dist/ui/client/ui/_app/immutable/nodes/0.D-lhv0Us.js.gz +0 -0
  39. package/dist/ui/client/ui/_app/immutable/nodes/1.Cs4GAsCO.js +1 -0
  40. package/dist/ui/client/ui/_app/immutable/nodes/1.Cs4GAsCO.js.br +1 -0
  41. package/dist/ui/client/ui/_app/immutable/nodes/1.Cs4GAsCO.js.gz +0 -0
  42. package/dist/ui/client/ui/_app/immutable/nodes/2.CmuzlN_T.js +52 -0
  43. package/dist/ui/client/ui/_app/immutable/nodes/2.CmuzlN_T.js.br +0 -0
  44. package/dist/ui/client/ui/_app/immutable/nodes/2.CmuzlN_T.js.gz +0 -0
  45. package/dist/ui/client/ui/_app/immutable/nodes/3.DMXXeBbC.js +5 -0
  46. package/dist/ui/client/ui/_app/immutable/nodes/3.DMXXeBbC.js.br +0 -0
  47. package/dist/ui/client/ui/_app/immutable/nodes/3.DMXXeBbC.js.gz +0 -0
  48. package/dist/ui/client/ui/_app/immutable/nodes/{4.DY8qq4Io.js → 4.CMHCNMDn.js} +1 -1
  49. package/dist/ui/client/ui/_app/immutable/nodes/4.CMHCNMDn.js.br +0 -0
  50. package/dist/ui/client/ui/_app/immutable/nodes/4.CMHCNMDn.js.gz +0 -0
  51. package/dist/ui/client/ui/_app/version.json +1 -1
  52. package/dist/ui/client/ui/_app/version.json.br +0 -0
  53. package/dist/ui/client/ui/_app/version.json.gz +0 -0
  54. package/dist/ui/server/.vite/manifest.json +97 -54
  55. package/dist/ui/server/chunks/composition.js +112 -118
  56. package/dist/ui/server/chunks/composition.js.map +1 -1
  57. package/dist/ui/server/chunks/config.js +139 -3
  58. package/dist/ui/server/chunks/config.js.map +1 -1
  59. package/dist/ui/server/chunks/exports.js +19 -204
  60. package/dist/ui/server/chunks/exports.js.map +1 -1
  61. package/dist/ui/server/chunks/functions.js +1 -1
  62. package/dist/ui/server/chunks/icon-button.js +1 -1
  63. package/dist/ui/server/chunks/instance.js +9 -56
  64. package/dist/ui/server/chunks/instance.js.map +1 -1
  65. package/dist/ui/server/chunks/internal.js +55 -4
  66. package/dist/ui/server/chunks/internal.js.map +1 -1
  67. package/dist/ui/server/chunks/outlined-text-field.js +1 -1
  68. package/dist/ui/server/chunks/remote-1j2tn2d.js +4 -0
  69. package/dist/ui/server/chunks/remote.js +1565 -0
  70. package/dist/ui/server/chunks/remote.js.map +1 -0
  71. package/dist/ui/server/chunks/scope.js +13 -0
  72. package/dist/ui/server/chunks/scope.js.map +1 -0
  73. package/dist/ui/server/chunks/server-errors.js +48 -1
  74. package/dist/ui/server/chunks/server-errors.js.map +1 -1
  75. package/dist/ui/server/chunks/server2.js +24 -1
  76. package/dist/ui/server/chunks/server2.js.map +1 -1
  77. package/dist/ui/server/chunks/sessions.js +65 -0
  78. package/dist/ui/server/chunks/sessions.js.map +1 -0
  79. package/dist/ui/server/chunks/sessions.remote.js +56 -0
  80. package/dist/ui/server/chunks/sessions.remote.js.map +1 -0
  81. package/dist/ui/server/chunks/shared-errors.js +214 -0
  82. package/dist/ui/server/chunks/shared-errors.js.map +1 -0
  83. package/dist/ui/server/chunks/src.js +112 -42
  84. package/dist/ui/server/chunks/src.js.map +1 -1
  85. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js +3 -5
  86. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js.map +1 -1
  87. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js +3 -4
  88. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js.map +1 -1
  89. package/dist/ui/server/entries/endpoints/api/sessions/_id_id_/_server.ts.js +12 -0
  90. package/dist/ui/server/entries/endpoints/api/sessions/_id_id_/_server.ts.js.map +1 -0
  91. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js +4 -9
  92. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js.map +1 -1
  93. package/dist/ui/server/entries/endpoints/api/sessions/end/_server.ts.js +2 -3
  94. package/dist/ui/server/entries/endpoints/api/sessions/end/_server.ts.js.map +1 -1
  95. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js +6 -9
  96. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js.map +1 -1
  97. package/dist/ui/server/entries/endpoints/api/speech/stream/_server.ts.js +3 -3
  98. package/dist/ui/server/entries/endpoints/api/speech/stream/_server.ts.js.map +1 -1
  99. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js +2 -3
  100. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js.map +1 -1
  101. package/dist/ui/server/entries/fallbacks/error.svelte.js +1 -1
  102. package/dist/ui/server/entries/hooks.server.js +145 -1
  103. package/dist/ui/server/entries/hooks.server.js.map +1 -1
  104. package/dist/ui/server/entries/pages/_layout.server.ts.js +2 -3
  105. package/dist/ui/server/entries/pages/_layout.server.ts.js.map +1 -1
  106. package/dist/ui/server/entries/pages/_layout.svelte.js +4 -2
  107. package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
  108. package/dist/ui/server/entries/pages/_page.server.ts.js +3 -3
  109. package/dist/ui/server/entries/pages/_page.server.ts.js.map +1 -1
  110. package/dist/ui/server/entries/pages/_page.svelte.js +8 -62
  111. package/dist/ui/server/entries/pages/_page.svelte.js.map +1 -1
  112. package/dist/ui/server/entries/pages/settings/_page.svelte.js +3 -2
  113. package/dist/ui/server/entries/pages/settings/_page.svelte.js.map +1 -1
  114. package/dist/ui/server/entries/params.js +60 -0
  115. package/dist/ui/server/entries/params.js.map +1 -0
  116. package/dist/ui/server/env.js +1 -1
  117. package/dist/ui/server/index.js +2 -2
  118. package/dist/ui/server/manifest-full.js +7 -6
  119. package/dist/ui/server/manifest.js +7 -6
  120. package/dist/ui/server/nodes/0.js +1 -1
  121. package/dist/ui/server/nodes/1.js +1 -1
  122. package/dist/ui/server/nodes/2.js +1 -1
  123. package/dist/ui/server/nodes/3.js +1 -1
  124. package/dist/ui/server/nodes/4.js +1 -1
  125. package/dist/ui/server/remote-entry.js +1 -1565
  126. package/dist/ui/server/server.js +7 -6
  127. package/package.json +3 -2
  128. package/dist/ui/client/ui/_app/immutable/chunks/C67ohLw_.js +0 -1
  129. package/dist/ui/client/ui/_app/immutable/chunks/C67ohLw_.js.br +0 -3
  130. package/dist/ui/client/ui/_app/immutable/chunks/C67ohLw_.js.gz +0 -0
  131. package/dist/ui/client/ui/_app/immutable/chunks/CKeiBgOI.js +0 -1
  132. package/dist/ui/client/ui/_app/immutable/chunks/CKeiBgOI.js.br +0 -1
  133. package/dist/ui/client/ui/_app/immutable/chunks/CKeiBgOI.js.gz +0 -0
  134. package/dist/ui/client/ui/_app/immutable/chunks/CM9WugkD.js.br +0 -0
  135. package/dist/ui/client/ui/_app/immutable/chunks/CM9WugkD.js.gz +0 -0
  136. package/dist/ui/client/ui/_app/immutable/chunks/CVUOwNb5.js +0 -3
  137. package/dist/ui/client/ui/_app/immutable/chunks/CVUOwNb5.js.br +0 -0
  138. package/dist/ui/client/ui/_app/immutable/chunks/CVUOwNb5.js.gz +0 -0
  139. package/dist/ui/client/ui/_app/immutable/chunks/CXrPUR7p.js +0 -4
  140. package/dist/ui/client/ui/_app/immutable/chunks/CXrPUR7p.js.br +0 -0
  141. package/dist/ui/client/ui/_app/immutable/chunks/CXrPUR7p.js.gz +0 -0
  142. package/dist/ui/client/ui/_app/immutable/chunks/Dksil5Gu.js +0 -1
  143. package/dist/ui/client/ui/_app/immutable/chunks/Dksil5Gu.js.br +0 -0
  144. package/dist/ui/client/ui/_app/immutable/chunks/Dksil5Gu.js.gz +0 -0
  145. package/dist/ui/client/ui/_app/immutable/chunks/DnL0kOQY.js +0 -1
  146. package/dist/ui/client/ui/_app/immutable/chunks/DnL0kOQY.js.br +0 -2
  147. package/dist/ui/client/ui/_app/immutable/chunks/DnL0kOQY.js.gz +0 -0
  148. package/dist/ui/client/ui/_app/immutable/chunks/Fimt9aTv.js.br +0 -0
  149. package/dist/ui/client/ui/_app/immutable/chunks/Fimt9aTv.js.gz +0 -0
  150. package/dist/ui/client/ui/_app/immutable/chunks/h7UQ89-l.js +0 -3
  151. package/dist/ui/client/ui/_app/immutable/chunks/h7UQ89-l.js.br +0 -0
  152. package/dist/ui/client/ui/_app/immutable/chunks/h7UQ89-l.js.gz +0 -0
  153. package/dist/ui/client/ui/_app/immutable/entry/app.BQe0vf14.js +0 -2
  154. package/dist/ui/client/ui/_app/immutable/entry/app.BQe0vf14.js.br +0 -0
  155. package/dist/ui/client/ui/_app/immutable/entry/app.BQe0vf14.js.gz +0 -0
  156. package/dist/ui/client/ui/_app/immutable/entry/start.uodUAHNT.js.br +0 -0
  157. package/dist/ui/client/ui/_app/immutable/entry/start.uodUAHNT.js.gz +0 -0
  158. package/dist/ui/client/ui/_app/immutable/nodes/0.kO9a4iA1.js +0 -1
  159. package/dist/ui/client/ui/_app/immutable/nodes/0.kO9a4iA1.js.br +0 -0
  160. package/dist/ui/client/ui/_app/immutable/nodes/0.kO9a4iA1.js.gz +0 -0
  161. package/dist/ui/client/ui/_app/immutable/nodes/1.jZ-iBVjE.js +0 -1
  162. package/dist/ui/client/ui/_app/immutable/nodes/1.jZ-iBVjE.js.br +0 -2
  163. package/dist/ui/client/ui/_app/immutable/nodes/1.jZ-iBVjE.js.gz +0 -0
  164. package/dist/ui/client/ui/_app/immutable/nodes/2.CWoJ2uhd.js +0 -52
  165. package/dist/ui/client/ui/_app/immutable/nodes/2.CWoJ2uhd.js.br +0 -0
  166. package/dist/ui/client/ui/_app/immutable/nodes/2.CWoJ2uhd.js.gz +0 -0
  167. package/dist/ui/client/ui/_app/immutable/nodes/3.DcigOv3T.js +0 -5
  168. package/dist/ui/client/ui/_app/immutable/nodes/3.DcigOv3T.js.br +0 -0
  169. package/dist/ui/client/ui/_app/immutable/nodes/3.DcigOv3T.js.gz +0 -0
  170. package/dist/ui/client/ui/_app/immutable/nodes/4.DY8qq4Io.js.br +0 -0
  171. package/dist/ui/client/ui/_app/immutable/nodes/4.DY8qq4Io.js.gz +0 -0
  172. package/dist/ui/server/chunks/bridge-api.js +0 -105
  173. package/dist/ui/server/chunks/bridge-api.js.map +0 -1
  174. package/dist/ui/server/entries/endpoints/api/sessions/_id_/_server.ts.js +0 -13
  175. package/dist/ui/server/entries/endpoints/api/sessions/_id_/_server.ts.js.map +0 -1
  176. package/dist/ui/server/remote-entry.js.map +0 -1
package/dist/cli.mjs CHANGED
@@ -13,13 +13,13 @@ import { execFile, spawn, spawnSync } from "node:child_process";
13
13
  import { once } from "node:events";
14
14
  import readline from "node:readline";
15
15
  // package.json
16
- var version = "0.8.2";
16
+ var version = "0.9.0-feat-bridge-focus-window.23";
17
17
  // ../shared/src/api-version.ts
18
18
  /**
19
19
  * `<major>.<minor>` of the HTTP API. Minor versions only add things
20
20
  * (docs/usage/http-api.md#versioning).
21
21
  */
22
- const API_VERSION = "1.18";
22
+ const API_VERSION = "1.21";
23
23
  /** Path prefix of every API route. */
24
24
  const API_PREFIX = "/api/v1";
25
25
  const DEFAULT_CONFIG$1 = {
@@ -651,7 +651,38 @@ const API_LIMITS = {
651
651
  max: 1e4
652
652
  },
653
653
  /** Most chords in one request. */
654
- maxKeys: 100
654
+ maxKeys: 100,
655
+ /** Longest `title` of `POST /input/focus`. */
656
+ focusTitleLength: 200
657
+ },
658
+ /**
659
+ * `capture` of `POST /input/click` and `POST /input/keys` (and the client's `record()`, which
660
+ * uses the same defaults): the defaults and ranges in milliseconds.
661
+ */
662
+ capture: {
663
+ /** Silence that ends the capture. */
664
+ quietForMs: {
665
+ default: 500,
666
+ min: 1,
667
+ max: 6e4
668
+ },
669
+ /** How long the first speech may take after the input. */
670
+ firstWithinMs: {
671
+ default: 2e3,
672
+ max: 3e5
673
+ },
674
+ /** Longest capture, counted from the input. */
675
+ timeoutMs: {
676
+ default: 1e4,
677
+ max: 3e5
678
+ },
679
+ /** Silence to wait for before the input (0: none). */
680
+ settleMs: {
681
+ default: 0,
682
+ max: 6e4
683
+ },
684
+ /** Entries the answer holds at most: the first ones. */
685
+ entries: 1e4
655
686
  }
656
687
  };
657
688
  /** Ranges of the settings (`GET` / `PUT /config`). */
@@ -751,33 +782,125 @@ const ERROR_STATUS = {
751
782
  NOT_FOUND: 404,
752
783
  FORBIDDEN: 403,
753
784
  INPUT_DISABLED: 409,
785
+ FOCUS_FAILED: 409,
754
786
  SERVICE_UNAVAILABLE: 503,
755
787
  INTERNAL: 500
756
788
  };
789
+ API_LIMITS.wait.seen, `${API_LIMITS.wait.seen}`;
790
+ `${API_LIMITS.markerLength}`;
757
791
  // ../shared/src/input.ts
758
792
  const { coordinate: coordinate$1, delayMs: delayMs$1, maxKeys: maxKeys$1 } = API_LIMITS.input;
793
+ const CAPTURE = API_LIMITS.capture;
794
+ CAPTURE.quietForMs.min, CAPTURE.quietForMs.max, `${CAPTURE.quietForMs.default}`, CAPTURE.firstWithinMs.max, `${CAPTURE.firstWithinMs.default}`, CAPTURE.timeoutMs.max, `${CAPTURE.timeoutMs.default}`, CAPTURE.settleMs.max;
795
+ CAPTURE.entries, `${CAPTURE.entries}`;
759
796
  -coordinate$1, -coordinate$1;
760
797
  `${maxKeys$1}`, delayMs$1.max, `${delayMs$1.default}`;
798
+ API_LIMITS.input.focusTitleLength;
799
+ // ../shared/src/key-chord.ts
800
+ /**
801
+ * The key names of `POST /input/keys` (docs/usage/native-input.md#key-names). The bridge parses
802
+ * chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
803
+ * so both use this one copy. Like `text-match.ts`, it belongs to the contract, not to either side.
804
+ */
805
+ /** Keys that can be held down while another key is pressed. `Insert` and `CapsLock` are the screen reader keys. */
806
+ const MODIFIER_KEYS = [
807
+ "control",
808
+ "shift",
809
+ "alt",
810
+ "win",
811
+ "insert",
812
+ "capslock"
813
+ ];
814
+ /** Keys with a name, besides `a`–`z` and `0`–`9`. */
815
+ const NAMED_KEYS = [
816
+ "enter",
817
+ "tab",
818
+ "escape",
819
+ "space",
820
+ "backspace",
821
+ "delete",
822
+ "up",
823
+ "down",
824
+ "left",
825
+ "right",
826
+ "home",
827
+ "end",
828
+ "pageup",
829
+ "pagedown",
830
+ ...Array.from({ length: 12 }, (_, index) => `f${index + 1}`)
831
+ ];
832
+ /** Aliases accepted in a chord, by their lower-case spelling. */
833
+ const KEY_ALIASES = {
834
+ ctrl: "control",
835
+ windows: "win",
836
+ meta: "win",
837
+ esc: "escape",
838
+ return: "enter",
839
+ del: "delete",
840
+ ins: "insert",
841
+ pgup: "pageup",
842
+ pgdn: "pagedown"
843
+ };
844
+ const KEYS = /* @__PURE__ */ new Set([
845
+ ...MODIFIER_KEYS,
846
+ ...NAMED_KEYS,
847
+ ..."abcdefghijklmnopqrstuvwxyz0123456789"
848
+ ]);
849
+ const MODIFIER_SET = new Set(MODIFIER_KEYS);
850
+ /**
851
+ * Parses `Insert+T` or `Control+Shift+Home`: modifiers and one last key, joined with `+`, names
852
+ * case-insensitive. Only modifiers may come before the last key, and none twice. A lone modifier
853
+ * (`Insert`) is a chord of that key.
854
+ */
855
+ function parseKeyChord$1(chord) {
856
+ const names = [];
857
+ for (const part of chord.split("+")) {
858
+ const lower = part.trim().toLowerCase();
859
+ const name = KEY_ALIASES[lower] ?? lower;
860
+ if (!KEYS.has(name)) return {
861
+ ok: false,
862
+ message: `unknown key "${part.trim()}" in "${chord}"`
863
+ };
864
+ names.push(name);
865
+ }
866
+ const key = names.pop();
867
+ if (new Set(names).size !== names.length || names.includes(key)) return {
868
+ ok: false,
869
+ message: `"${chord}" repeats a key`
870
+ };
871
+ const notModifier = names.find((name) => !MODIFIER_SET.has(name));
872
+ if (notModifier !== void 0) return {
873
+ ok: false,
874
+ message: `"${notModifier}" in "${chord}" is not a modifier`
875
+ };
876
+ return {
877
+ ok: true,
878
+ chord: {
879
+ modifiers: names,
880
+ key
881
+ }
882
+ };
883
+ }
761
884
  // ../shared/src/services.ts
762
885
  /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
763
886
  const PLAYWRIGHT_PATH = "/playwright";
764
887
  /** Playwright MCP (streamable HTTP): `http://<bridge>:5151/playwright-mcp`. */
765
888
  const PLAYWRIGHT_MCP_PATH = "/playwright-mcp";
766
889
  // ../shared/src/session.ts
767
- const integer$2 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
768
- const timestamp$2 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
890
+ const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
891
+ const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
769
892
  const label = (text) => /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((text) => isTrimmedLabel(text, API_LIMITS.sessionLabelLength)), /* @__PURE__ */ description(`${text} Trimmed, must not be empty, at most ${API_LIMITS.sessionLabelLength} characters.`));
770
893
  const sessionEntries = {
771
- id: /* @__PURE__ */ pipe(integer$2(1), /* @__PURE__ */ description("Increasing, restarts at 1 with the bridge.")),
894
+ id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, restarts at 1 with the bridge.")),
772
895
  name: /* @__PURE__ */ string(),
773
896
  run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
774
897
  client: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Who started it: the `X-SR-Speech-Client` header, `null` if it wasn't sent. Added in API 1.10.")),
775
- startedAt: timestamp$2,
776
- endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$2), /* @__PURE__ */ description("`null` while the session is current.")),
777
- startSeq: /* @__PURE__ */ pipe(integer$2(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
778
- firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$2(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
779
- lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$2(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
780
- entries: /* @__PURE__ */ pipe(integer$2(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
898
+ startedAt: timestamp$1,
899
+ endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
900
+ startSeq: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
901
+ firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
902
+ lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
903
+ entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
781
904
  };
782
905
  label("For example the test title."), label("Optional label that groups sessions, for example one per test run.");
783
906
  ({ ...sessionEntries });
@@ -786,8 +909,6 @@ label("For example the test title."), label("Optional label that groups sessions
786
909
  * one client ends or replaces another one's session. Optional. API 1.10.
787
910
  */
788
911
  const CLIENT_HEADER = "x-sr-speech-client";
789
- API_LIMITS.wait.seen, `${API_LIMITS.wait.seen}`;
790
- `${API_LIMITS.markerLength}`;
791
912
  // ../shared/src/text-match.ts
792
913
  /**
793
914
  * The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
@@ -1356,6 +1477,13 @@ function numberField(body, name) {
1356
1477
  function optionalNumberField(body, name) {
1357
1478
  return field(body, name) === void 0 ? void 0 : numberField(body, name);
1358
1479
  }
1480
+ /** An optional field of a JSON body that is a JSON object. */
1481
+ function optionalObjectField(body, name) {
1482
+ const value = field(body, name);
1483
+ if (value === void 0) return void 0;
1484
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidField(name, "must be an object");
1485
+ return value;
1486
+ }
1359
1487
  /** A required field that is a string or an array of strings. */
1360
1488
  function keysField(body, name) {
1361
1489
  const value = field(body, name);
@@ -1399,26 +1527,133 @@ function configRoutes(router, { config }) {
1399
1527
  sendJson(res, 200, toConfigDto(await config.update(await jsonBody(req))));
1400
1528
  });
1401
1529
  }
1530
+ // src/adapters/in/http/dto/speech.ts
1531
+ function toSpeechEntryDto(entry) {
1532
+ return {
1533
+ seq: entry.seq,
1534
+ kind: entry.kind,
1535
+ text: entry.text,
1536
+ receivedAt: entry.receivedAt.toISOString(),
1537
+ source: entry.source,
1538
+ voice: entry.voice,
1539
+ connectionId: entry.connectionId,
1540
+ sessionId: entry.sessionId
1541
+ };
1542
+ }
1543
+ function toSpeechListDto(page) {
1544
+ return {
1545
+ entries: page.entries.map(toSpeechEntryDto),
1546
+ truncated: page.truncated,
1547
+ hasMore: page.hasMore
1548
+ };
1549
+ }
1550
+ function toLatestMarkerDto(marker) {
1551
+ return { marker: marker && toSpeechEntryDto(marker) };
1552
+ }
1553
+ function toWaitResultDto(result) {
1554
+ return result.status === "matched" ? {
1555
+ matched: true,
1556
+ entry: toSpeechEntryDto(result.entry)
1557
+ } : {
1558
+ matched: false,
1559
+ entries: result.seen.map(toSpeechEntryDto),
1560
+ omitted: result.omitted
1561
+ };
1562
+ }
1563
+ // src/adapters/in/http/dto/input.ts
1564
+ function toInputCaptureDto(result) {
1565
+ return {
1566
+ status: result.status,
1567
+ startSeq: result.startSeq,
1568
+ entries: result.entries.map(toSpeechEntryDto),
1569
+ omitted: result.omitted,
1570
+ truncated: result.truncated
1571
+ };
1572
+ }
1573
+ function toFocusedWindowDto(window) {
1574
+ return {
1575
+ title: window.title,
1576
+ pid: window.pid
1577
+ };
1578
+ }
1402
1579
  // src/adapters/in/http/routes/input-routes.ts
1403
- /** `POST /input/click`, `POST /input/keys` (docs/usage/http-api.md#endpoints). */
1404
- function inputRoutes(router, { input }) {
1405
- router.add("POST", "/input/click", async ({ req, res }) => {
1580
+ /** The `capture` object of an input request, `undefined` without one. */
1581
+ function captureField(body) {
1582
+ const capture = optionalObjectField(body, "capture");
1583
+ if (capture === void 0) return void 0;
1584
+ const ms = (name) => {
1585
+ try {
1586
+ return optionalNumberField(capture, name);
1587
+ } catch {
1588
+ throw invalidField(`capture.${name}`, "must be a number");
1589
+ }
1590
+ };
1591
+ return {
1592
+ quietForMs: ms("quietForMs"),
1593
+ firstWithinMs: ms("firstWithinMs"),
1594
+ timeoutMs: ms("timeoutMs"),
1595
+ settleMs: ms("settleMs")
1596
+ };
1597
+ }
1598
+ /**
1599
+ * Without `capture`: sends the input and answers 204. With it: records the speech the input
1600
+ * causes and answers 200 (docs/usage/native-input.md#capturing-the-speech-an-input-causes).
1601
+ */
1602
+ async function answer(res, capture, send, record) {
1603
+ if (capture === void 0) {
1604
+ await send();
1605
+ sendNoContent(res);
1606
+ return;
1607
+ }
1608
+ const controller = new AbortController();
1609
+ res.on("close", () => {
1610
+ if (!res.writableEnded) controller.abort();
1611
+ });
1612
+ let result;
1613
+ try {
1614
+ result = await record(capture, controller.signal);
1615
+ } catch (error) {
1616
+ if (controller.signal.aborted) return;
1617
+ throw error;
1618
+ }
1619
+ sendJson(res, 200, toInputCaptureDto(result));
1620
+ }
1621
+ /** `POST /input/click`, `POST /input/keys`, `POST /input/focus` (docs/usage/http-api.md#endpoints). */
1622
+ function inputRoutes(router, { input, captures, focus }) {
1623
+ router.add("POST", "/input/focus", async ({ req, res }) => {
1624
+ const body = await jsonBody(req);
1625
+ const target = stringField(body, "target");
1626
+ if (target !== "mcp" && target !== "playwright") throw invalidField("target", "must be mcp or playwright");
1627
+ sendJson(res, 200, toFocusedWindowDto(await focus.focus({
1628
+ target,
1629
+ title: optionalStringField(body, "title")
1630
+ })));
1631
+ }).add("POST", "/input/click", async ({ req, res }) => {
1406
1632
  const body = await jsonBody(req);
1407
1633
  const button = optionalStringField(body, "button");
1408
1634
  if (button !== void 0 && button !== "left" && button !== "right" && button !== "middle") throw invalidField("button", "must be left, right or middle");
1409
- await input.click({
1635
+ const mouseButton = button;
1636
+ const request = {
1410
1637
  x: numberField(body, "x"),
1411
1638
  y: numberField(body, "y"),
1412
- button
1413
- });
1414
- sendNoContent(res);
1639
+ button: mouseButton
1640
+ };
1641
+ await answer(res, captureField(body), () => input.click(request), (capture, signal) => captures.click({
1642
+ ...request,
1643
+ capture,
1644
+ signal
1645
+ }));
1415
1646
  }).add("POST", "/input/keys", async ({ req, res }) => {
1416
1647
  const body = await jsonBody(req);
1417
- await input.pressKeys({
1648
+ const request = {
1418
1649
  keys: keysField(body, "keys"),
1419
1650
  delayMs: optionalNumberField(body, "delayMs")
1420
- });
1421
- sendNoContent(res);
1651
+ };
1652
+ await answer(res, captureField(body), () => input.pressKeys(request), (capture, signal) => captures.pressKeys({
1653
+ ...request,
1654
+ capture,
1655
+ signal
1656
+ }));
1422
1657
  });
1423
1658
  }
1424
1659
  // src/adapters/in/http/dto/session.ts
@@ -1472,36 +1707,6 @@ function sessionRoutes(router, { sessions }) {
1472
1707
  sendNoContent(res);
1473
1708
  }).add("GET", "/sessions", ({ res }) => sendJson(res, 200, toSessionListDto(sessions.list())));
1474
1709
  }
1475
- // src/adapters/in/http/dto/speech.ts
1476
- function toSpeechEntryDto(entry) {
1477
- return {
1478
- seq: entry.seq,
1479
- kind: entry.kind,
1480
- text: entry.text,
1481
- receivedAt: entry.receivedAt.toISOString(),
1482
- source: entry.source,
1483
- voice: entry.voice,
1484
- connectionId: entry.connectionId,
1485
- sessionId: entry.sessionId
1486
- };
1487
- }
1488
- function toSpeechListDto(page) {
1489
- return {
1490
- entries: page.entries.map(toSpeechEntryDto),
1491
- truncated: page.truncated,
1492
- hasMore: page.hasMore
1493
- };
1494
- }
1495
- function toWaitResultDto(result) {
1496
- return result.status === "matched" ? {
1497
- matched: true,
1498
- entry: toSpeechEntryDto(result.entry)
1499
- } : {
1500
- matched: false,
1501
- entries: result.seen.map(toSpeechEntryDto),
1502
- omitted: result.omitted
1503
- };
1504
- }
1505
1710
  // src/adapters/in/http/sse/sse-frames.ts
1506
1711
  /**
1507
1712
  * Frames already built, by the entry or session they show. Every open stream gets the same
@@ -1545,6 +1750,10 @@ function speechRoutes(router, deps) {
1545
1750
  }).add("POST", "/markers", async ({ req, res }) => {
1546
1751
  const label = stringField(await jsonBody(req), "label");
1547
1752
  sendJson(res, 201, toSpeechEntryDto(speech.addMarker(label)));
1753
+ }).add("GET", "/markers/latest", ({ res, url }) => {
1754
+ const label = stringParam(url, "label");
1755
+ if (label === void 0) throw invalidField("label", "is required");
1756
+ sendJson(res, 200, toLatestMarkerDto(speech.latestMarker(label, sessionParam(url))));
1548
1757
  }).add("GET", "/speech/wait", async ({ res, url }) => {
1549
1758
  const controller = new AbortController();
1550
1759
  res.on("close", () => {
@@ -2210,10 +2419,10 @@ var BridgeLifecycleService = class {
2210
2419
  return this.stopping;
2211
2420
  }
2212
2421
  async shutdown(reason) {
2213
- const { state, waits, stopOrder, logger } = this.deps;
2422
+ const { state, pending, stopOrder, logger } = this.deps;
2214
2423
  state.setState("stopping");
2215
2424
  logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
2216
- waits.shutdown();
2425
+ for (const part of pending) part.shutdown();
2217
2426
  const errors = [];
2218
2427
  for (const part of stopOrder) try {
2219
2428
  await part.stop();
@@ -2405,82 +2614,371 @@ var ConfigService = class {
2405
2614
  this.log(patched);
2406
2615
  return merged;
2407
2616
  }
2408
- log(patched) {
2409
- const { logger, pinned, store } = this.deps;
2410
- const running = configFields(this.active);
2411
- for (const [field, value] of patched) {
2412
- const source = pinned?.get(field);
2413
- if (source !== void 0) logger.warn(`${field}: saved to ${store.location}, but ${source} overrides it on the next start`);
2414
- else if (!same(value, running.get(field))) logger.info(`${field}: ${show$1(running.get(field))} → ${show$1(value)} on the next start`);
2617
+ log(patched) {
2618
+ const { logger, pinned, store } = this.deps;
2619
+ const running = configFields(this.active);
2620
+ for (const [field, value] of patched) {
2621
+ const source = pinned?.get(field);
2622
+ if (source !== void 0) logger.warn(`${field}: saved to ${store.location}, but ${source} overrides it on the next start`);
2623
+ else if (!same(value, running.get(field))) logger.info(`${field}: ${show$1(running.get(field))} → ${show$1(value)} on the next start`);
2624
+ }
2625
+ }
2626
+ };
2627
+ // src/application/ports/in/capture-input.ts
2628
+ /** Defaults and ranges of the capture options, in milliseconds. */
2629
+ const CAPTURE_LIMITS = API_LIMITS.capture;
2630
+ // src/application/shared/abort.ts
2631
+ /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
2632
+ function abortReason(signal) {
2633
+ const reason = signal.reason;
2634
+ return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
2635
+ }
2636
+ /** What pending requests (waits, captures) end with when the bridge shuts down. */
2637
+ const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
2638
+ // src/domain/seq-cursor.ts
2639
+ /**
2640
+ * A follower's position in the speech log. `SpeechLog` gives every entry the next `seq`, strictly
2641
+ * rising, so an entry at or below the position was already delivered. A replay from the log and
2642
+ * the live events may therefore overlap in any timing without a duplicate.
2643
+ */
2644
+ var SeqCursor = class {
2645
+ #position;
2646
+ /** `position`: the last `seq` already delivered. `-Infinity` accepts every entry. */
2647
+ constructor(position) {
2648
+ this.#position = position;
2649
+ }
2650
+ get position() {
2651
+ return this.#position;
2652
+ }
2653
+ /** `true`, and moves on to it, if the entry comes after the position; `false` if it was delivered. */
2654
+ advance(entry) {
2655
+ if (entry.seq <= this.#position) return false;
2656
+ this.#position = entry.seq;
2657
+ return true;
2658
+ }
2659
+ };
2660
+ /**
2661
+ * Hands `listener` the log's entries after `since`, then the new events, with nothing missed or
2662
+ * repeated in between (`SpeechUseCases.watch`, the wait). With `sessionId`, only that session's
2663
+ * entries (`null`: those outside sessions); `session` events always come, and a `clear` unless it only cleared another scope. Returns a
2664
+ * function that stops it; calling it again does nothing.
2665
+ *
2666
+ * Without `since` (`null`) no entry is replayed; the first event is `position`, the log's
2667
+ * `headSeq`, so a stream that drops before its first entry still has a cursor to reconnect with.
2668
+ * With `staleSince: 'replay'`, a `since` above `headSeq` (a cursor from another run) is a gap,
2669
+ * not a position to wait for: `truncated`, then the whole buffer. Without it, such a `since`
2670
+ * waits for entries above it (what the wait means by `since`).
2671
+ */
2672
+ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, listener, { pace, onError } = {}) {
2673
+ const { log, events } = deps;
2674
+ let stale = staleSince === "replay" && requested !== null && requested > log.headSeq;
2675
+ const since = stale ? 0 : requested;
2676
+ const cursor = new SeqCursor(since ?? Number.NEGATIVE_INFINITY);
2677
+ let replaying = since !== null;
2678
+ let stopped = false;
2679
+ const unsubscribe = events.subscribe((event) => {
2680
+ if (event.type === "clear" && event.sessionId !== void 0 && sessionId !== void 0) {
2681
+ if (event.sessionId !== sessionId) return;
2682
+ }
2683
+ if (event.type !== "entry") return listener(event);
2684
+ if (replaying || !cursor.advance(event.entry)) return;
2685
+ if (sessionId === void 0 || event.entry.sessionId === sessionId) listener(event);
2686
+ });
2687
+ const stop = () => {
2688
+ stopped = true;
2689
+ unsubscribe();
2690
+ };
2691
+ if (since === null) {
2692
+ listener({
2693
+ type: "position",
2694
+ seq: log.headSeq
2695
+ });
2696
+ return stop;
2697
+ }
2698
+ /** Replays from the cursor until `pace` pauses it (its promise) or it has caught up. */
2699
+ const step = () => {
2700
+ for (;;) {
2701
+ const { entries, truncated, hasMore } = log.page(cursor.position, 500, sessionId);
2702
+ if (truncated || stale) listener({ type: "truncated" });
2703
+ stale = false;
2704
+ for (const entry of entries) {
2705
+ if (!cursor.advance(entry)) continue;
2706
+ listener({
2707
+ type: "entry",
2708
+ entry
2709
+ });
2710
+ const paused = pace?.();
2711
+ if (paused) return paused;
2712
+ }
2713
+ if (!hasMore) {
2714
+ replaying = false;
2715
+ return;
2716
+ }
2717
+ }
2718
+ };
2719
+ const resume = async (paused) => {
2720
+ for (let next = paused; next;) {
2721
+ await next;
2722
+ if (stopped) return;
2723
+ next = step();
2724
+ }
2725
+ };
2726
+ let paused;
2727
+ try {
2728
+ paused = step();
2729
+ } catch (error) {
2730
+ stop();
2731
+ throw error;
2732
+ }
2733
+ if (paused) resume(paused).catch((error) => {
2734
+ stop();
2735
+ onError?.(error);
2736
+ });
2737
+ return stop;
2738
+ }
2739
+ // src/application/shared/int-option.ts
2740
+ /**
2741
+ * A numeric use-case option: `fallback` if it is missing, otherwise checked to be an integer
2742
+ * from `min` to `max` (`INVALID_REQUEST` for `field` if not).
2743
+ */
2744
+ function intOption(field, value, { fallback, min, max }) {
2745
+ if (value === void 0) return fallback;
2746
+ if (!Number.isInteger(value) || value < min || value > max) throw invalidField(field, `must be an integer from ${min} to ${max}`);
2747
+ return value;
2748
+ }
2749
+ // src/application/services/input-capture-service.ts
2750
+ function parseOptions(options) {
2751
+ const { quietForMs, firstWithinMs, timeoutMs, settleMs } = CAPTURE_LIMITS;
2752
+ const ms = (field, limits) => intOption(`capture.${field}`, options[field], {
2753
+ fallback: limits.default,
2754
+ min: limits.min ?? 0,
2755
+ max: limits.max
2756
+ });
2757
+ return {
2758
+ quietForMs: ms("quietForMs", quietForMs),
2759
+ firstWithinMs: ms("firstWithinMs", firstWithinMs),
2760
+ timeoutMs: ms("timeoutMs", timeoutMs),
2761
+ settleMs: ms("settleMs", settleMs)
2762
+ };
2763
+ }
2764
+ const toError = (error) => error instanceof Error ? error : new Error(String(error));
2765
+ /**
2766
+ * Native input that records the speech it causes (docs/usage/native-input.md#capturing-the-speech-an-input-causes).
2767
+ * The start `seq` is read in the input queue right before the input is sent, so no other input
2768
+ * and no speech that came before it gets into the capture; silence is timed from the entries'
2769
+ * `receivedAt`, on the bridge's clock, not from when a client got them.
2770
+ */
2771
+ var InputCaptureService = class {
2772
+ deps;
2773
+ pending = /* @__PURE__ */ new Set();
2774
+ closed = false;
2775
+ constructor(deps) {
2776
+ this.deps = deps;
2777
+ }
2778
+ click({ capture, signal, ...request }) {
2779
+ return this.run(capture, signal, (hooks) => this.deps.input.click(request, hooks));
2780
+ }
2781
+ pressKeys({ capture, signal, ...request }) {
2782
+ return this.run(capture, signal, (hooks) => this.deps.input.pressKeys(request, hooks));
2783
+ }
2784
+ /**
2785
+ * Rejects all pending captures, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
2786
+ * lifecycle port: only the composition root calls it.
2787
+ */
2788
+ shutdown() {
2789
+ this.closed = true;
2790
+ for (const stop of [...this.pending]) stop.abort(shuttingDown());
2791
+ }
2792
+ async run(capture, signal, send) {
2793
+ if (this.closed) throw shuttingDown();
2794
+ const options = parseOptions(capture);
2795
+ if (signal?.aborted) throw abortReason(signal);
2796
+ const stop = new AbortController();
2797
+ const onAbort = () => stop.abort(abortReason(signal));
2798
+ signal?.addEventListener("abort", onAbort, { once: true });
2799
+ this.pending.add(stop);
2800
+ try {
2801
+ let startSeq = 0;
2802
+ await send({ beforeInject: async () => {
2803
+ if (options.settleMs > 0) await this.settle(options, stop.signal);
2804
+ if (stop.signal.aborted) throw abortReason(stop.signal);
2805
+ startSeq = this.deps.log.headSeq;
2806
+ } });
2807
+ return await this.record(startSeq, options, stop.signal);
2808
+ } finally {
2809
+ signal?.removeEventListener("abort", onAbort);
2810
+ this.pending.delete(stop);
2811
+ }
2812
+ }
2813
+ /**
2814
+ * Waits until the newest speech is `settleMs` old, at most `timeoutMs`: after that the input
2815
+ * is sent anyway, and the trailing speech shows in the capture.
2816
+ */
2817
+ async settle({ settleMs, timeoutMs }, signal) {
2818
+ const { log } = this.deps;
2819
+ const start = this.now();
2820
+ const newest = log.page(log.headSeq - 1, 1).entries[0];
2821
+ let last = newest?.kind === "speech" ? newest.receivedAt.getTime() : void 0;
2822
+ if (last === void 0 || last + settleMs <= start) return;
2823
+ await this.follow(null, signal, () => Math.min(last + settleMs, start + timeoutMs), (event) => {
2824
+ if (event.type === "entry" && event.entry.kind === "speech") last = event.entry.receivedAt.getTime();
2825
+ });
2826
+ }
2827
+ /** Follows the speech after `startSeq` until it paused, none came, or the time ran out. */
2828
+ async record(startSeq, { quietForMs, firstWithinMs, timeoutMs }, signal) {
2829
+ const sentAt = this.now();
2830
+ const end = sentAt + timeoutMs;
2831
+ const entries = [];
2832
+ let omitted = 0;
2833
+ let truncated = false;
2834
+ let last;
2835
+ const deadline = () => Math.min(last === void 0 ? sentAt + firstWithinMs : last + quietForMs, end);
2836
+ await this.follow(startSeq, signal, deadline, (event) => {
2837
+ if (event.type === "truncated") truncated = true;
2838
+ if (event.type !== "entry" || event.entry.kind !== "speech") return;
2839
+ last = event.entry.receivedAt.getTime();
2840
+ if (entries.length < CAPTURE_LIMITS.entries) entries.push(event.entry);
2841
+ else omitted++;
2842
+ });
2843
+ return {
2844
+ status: last === void 0 ? "no-speech" : last + quietForMs <= end ? "silent" : "timeout",
2845
+ startSeq,
2846
+ entries,
2847
+ omitted,
2848
+ truncated
2849
+ };
2850
+ }
2851
+ /**
2852
+ * Hands `onEvent` the log's events after `since` (`null`: only new ones) until `deadline()`
2853
+ * (ms, read again after each speech entry) has passed. Rejects when `signal` aborts.
2854
+ */
2855
+ follow(since, signal, deadline, onEvent) {
2856
+ if (signal.aborted) return Promise.reject(abortReason(signal));
2857
+ return new Promise((resolve, reject) => {
2858
+ let done = false;
2859
+ let timer;
2860
+ let stopFollow;
2861
+ const finish = () => {
2862
+ done = true;
2863
+ stopFollow?.();
2864
+ timer?.abort();
2865
+ signal.removeEventListener("abort", onAbort);
2866
+ };
2867
+ const fail = (error) => {
2868
+ if (done) return;
2869
+ finish();
2870
+ reject(error);
2871
+ };
2872
+ const onAbort = () => fail(abortReason(signal));
2873
+ const arm = () => {
2874
+ timer?.abort();
2875
+ const own = new AbortController();
2876
+ timer = own;
2877
+ this.deps.clock.sleep(Math.max(0, deadline() - this.now()), own.signal).then(() => {
2878
+ if (done || timer !== own) return;
2879
+ finish();
2880
+ resolve();
2881
+ }, () => {});
2882
+ };
2883
+ signal.addEventListener("abort", onAbort, { once: true });
2884
+ arm();
2885
+ try {
2886
+ stopFollow = followLog(this.deps, {
2887
+ since,
2888
+ sessionId: void 0
2889
+ }, (event) => {
2890
+ if (done) return;
2891
+ onEvent(event);
2892
+ if (event.type === "entry" && event.entry.kind === "speech") arm();
2893
+ }, {
2894
+ pace: this.deps.pace?.(),
2895
+ onError: (error) => fail(toError(error))
2896
+ });
2897
+ if (done) stopFollow();
2898
+ } catch (error) {
2899
+ fail(toError(error));
2900
+ }
2901
+ });
2902
+ }
2903
+ now() {
2904
+ return this.deps.clock.now().getTime();
2905
+ }
2906
+ };
2907
+ // src/application/services/window-focus-service.ts
2908
+ /** How long a `title` may take to show up in the window title, and how often it is looked for. */
2909
+ const TITLE_WAIT = {
2910
+ timeoutMs: 2e3,
2911
+ pollMs: 50
2912
+ };
2913
+ const TARGETS = {
2914
+ mcp: {
2915
+ service: "mcp",
2916
+ name: "Playwright MCP"
2917
+ },
2918
+ playwright: {
2919
+ service: "playwright",
2920
+ name: "the Playwright server"
2921
+ }
2922
+ };
2923
+ /**
2924
+ * Brings a window of a browser the bridge started to the front
2925
+ * (docs/usage/native-input.md#bringing-the-browser-to-the-front): the front-most visible
2926
+ * top-level window of the target service's process tree, or with `title` the front-most one
2927
+ * whose title contains it.
2928
+ */
2929
+ var WindowFocusService = class {
2930
+ deps;
2931
+ constructor(deps) {
2932
+ this.deps = deps;
2933
+ }
2934
+ async focus({ target, title }) {
2935
+ const known = Object.hasOwn(TARGETS, target) ? TARGETS[target] : void 0;
2936
+ if (!known) throw invalidField("target", "must be mcp or playwright");
2937
+ if (title !== void 0 && (title === "" || title.length > API_LIMITS.input.focusTitleLength)) throw invalidField("title", `must be 1 to ${API_LIMITS.input.focusTitleLength} characters`);
2938
+ const pid = this.deps.services[known.service].pid();
2939
+ if (pid === null) throw new AppError("NOT_FOUND", `${capitalize(known.name)} is not running`);
2940
+ return this.deps.queue.exclusive(async () => {
2941
+ const window = await this.find(pid, title);
2942
+ if (!window) throw notFound(known, title);
2943
+ if (!await this.deps.windows.bringToFront(window)) throw new AppError("FOCUS_FAILED", `Windows did not bring "${window.title}" to the front (is the desktop locked, or does an elevated window have the focus?)`);
2944
+ this.deps.logger.info(`focus ${target}: "${window.title}" (pid ${window.pid})`);
2945
+ return {
2946
+ title: window.title,
2947
+ pid: window.pid
2948
+ };
2949
+ });
2950
+ }
2951
+ /**
2952
+ * The front-most window of the tree below `pid` with a title (containing `title`, if given).
2953
+ * The browser sets its window title a moment after `document.title` changes, so a `title` is
2954
+ * looked for again until {@link TITLE_WAIT} runs out.
2955
+ */
2956
+ async find(pid, title) {
2957
+ const { windows, clock } = this.deps;
2958
+ const tries = title === void 0 ? 1 : TITLE_WAIT.timeoutMs / TITLE_WAIT.pollMs + 1;
2959
+ for (let attempt = 0; attempt < tries; attempt++) {
2960
+ if (attempt > 0) await clock.sleep(TITLE_WAIT.pollMs);
2961
+ const tree = await windows.processTree(pid);
2962
+ const found = (await windows.topLevelWindows()).find((window) => tree.has(window.pid) && window.title !== "" && (title === void 0 || window.title.includes(title)));
2963
+ if (found) return found;
2415
2964
  }
2416
2965
  }
2417
2966
  };
2418
- // src/domain/key-chord.ts
2419
- /** Keys that can be held down while another key is pressed. `Insert` and `CapsLock` are the screen reader keys. */
2420
- const MODIFIERS = [
2421
- "control",
2422
- "shift",
2423
- "alt",
2424
- "win",
2425
- "insert",
2426
- "capslock"
2427
- ];
2428
- const NAMED_KEYS = [
2429
- "enter",
2430
- "tab",
2431
- "escape",
2432
- "space",
2433
- "backspace",
2434
- "delete",
2435
- "up",
2436
- "down",
2437
- "left",
2438
- "right",
2439
- "home",
2440
- "end",
2441
- "pageup",
2442
- "pagedown",
2443
- ...Array.from({ length: 12 }, (_, index) => `f${index + 1}`)
2444
- ];
2445
- /** Aliases accepted in a chord, by their lower-case spelling. */
2446
- const ALIASES = {
2447
- ctrl: "control",
2448
- windows: "win",
2449
- meta: "win",
2450
- esc: "escape",
2451
- return: "enter",
2452
- del: "delete",
2453
- ins: "insert",
2454
- pgup: "pageup",
2455
- pgdn: "pagedown"
2456
- };
2457
- const KEYS = /* @__PURE__ */ new Set([
2458
- ...MODIFIERS,
2459
- ...NAMED_KEYS,
2460
- ..."abcdefghijklmnopqrstuvwxyz0123456789"
2461
- ]);
2462
- const MODIFIER_SET = new Set(MODIFIERS);
2463
- function keyName(chord, raw) {
2464
- const lower = raw.trim().toLowerCase();
2465
- const name = ALIASES[lower] ?? lower;
2466
- if (!KEYS.has(name)) throw invalidField("keys", `unknown key "${raw.trim()}" in "${chord}"`);
2467
- return name;
2967
+ function notFound(target, title) {
2968
+ if (title !== void 0) return new AppError("NOT_FOUND", `No window of ${target.name} has "${title}" in its title (a browser the bridge didn't start?)`);
2969
+ return new AppError("NOT_FOUND", `${capitalize(target.name)} has no browser window yet (Playwright MCP opens its browser on the first browser tool call)`);
2468
2970
  }
2971
+ const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
2972
+ // src/domain/key-chord.ts
2469
2973
  /**
2470
- * Parses `Insert+T` or `Control+Shift+Home`: modifiers and one last key, joined with `+`, names
2471
- * case-insensitive. Only modifiers may come before the last key, and none twice. A lone modifier
2472
- * (`Insert`) is a chord of that key.
2974
+ * Parses `Insert+T` or `Control+Shift+Home` (docs/usage/native-input.md#key-names). Throws
2975
+ * `INVALID_REQUEST` for the field `keys` if the chord is invalid. The domain knows no names of the
2976
+ * input library: the injector maps them.
2473
2977
  */
2474
2978
  function parseKeyChord(chord) {
2475
- const names = chord.split("+").map((part) => keyName(chord, part));
2476
- const key = names.pop();
2477
- if (new Set(names).size !== names.length || names.includes(key)) throw invalidField("keys", `"${chord}" repeats a key`);
2478
- const notModifier = names.find((name) => !MODIFIER_SET.has(name));
2479
- if (notModifier !== void 0) throw invalidField("keys", `"${notModifier}" in "${chord}" is not a modifier`);
2480
- return {
2481
- modifiers: names,
2482
- key
2483
- };
2979
+ const result = parseKeyChord$1(chord);
2980
+ if (!result.ok) throw invalidField("keys", result.message);
2981
+ return result.chord;
2484
2982
  }
2485
2983
  // src/application/services/native-input-service.ts
2486
2984
  const { coordinate, delayMs, maxKeys } = API_LIMITS.input;
@@ -2509,19 +3007,21 @@ var NativeInputService = class {
2509
3007
  constructor(deps) {
2510
3008
  this.deps = deps;
2511
3009
  }
2512
- async click({ x, y, button = "left" }) {
3010
+ async click({ x, y, button = "left" }, hooks = {}) {
2513
3011
  checkCoordinate("x", x);
2514
3012
  checkCoordinate("y", y);
2515
3013
  if (!BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
2516
3014
  await this.enqueue(async () => {
3015
+ await hooks.beforeInject?.();
2517
3016
  await this.deps.injector.click(x, y, button);
2518
3017
  this.deps.logger.info(`click ${button} at ${x},${y}`);
2519
3018
  });
2520
3019
  }
2521
- async pressKeys({ keys, delayMs: delay = delayMs.default }) {
3020
+ async pressKeys({ keys, delayMs: delay = delayMs.default }, hooks = {}) {
2522
3021
  const chords = parseKeys(keys);
2523
3022
  if (!Number.isInteger(delay) || delay < 0 || delay > delayMs.max) throw invalidField("delayMs", `must be an integer from 0 to ${delayMs.max}`);
2524
3023
  await this.enqueue(async () => {
3024
+ await hooks.beforeInject?.();
2525
3025
  for (const [index, chord] of chords.entries()) {
2526
3026
  if (index > 0 && delay > 0) await this.deps.clock.sleep(delay);
2527
3027
  await this.press(chord);
@@ -2542,6 +3042,9 @@ var NativeInputService = class {
2542
3042
  for (const modifier of held.reverse()) await injector.keyUp(modifier);
2543
3043
  }
2544
3044
  }
3045
+ exclusive(task) {
3046
+ return this.enqueue(task);
3047
+ }
2545
3048
  /** Runs `task` after the earlier ones; a failed task doesn't stop the later ones. */
2546
3049
  enqueue(task) {
2547
3050
  const run = this.queue.then(task);
@@ -2637,117 +3140,6 @@ function clientLabel(client) {
2637
3140
  // src/application/ports/in/speech.ts
2638
3141
  /** Page size of `list`: the default and the most a caller may ask for. */
2639
3142
  const LIST_LIMIT = API_LIMITS.list;
2640
- // src/domain/seq-cursor.ts
2641
- /**
2642
- * A follower's position in the speech log. `SpeechLog` gives every entry the next `seq`, strictly
2643
- * rising, so an entry at or below the position was already delivered. A replay from the log and
2644
- * the live events may therefore overlap in any timing without a duplicate.
2645
- */
2646
- var SeqCursor = class {
2647
- #position;
2648
- /** `position`: the last `seq` already delivered. `-Infinity` accepts every entry. */
2649
- constructor(position) {
2650
- this.#position = position;
2651
- }
2652
- get position() {
2653
- return this.#position;
2654
- }
2655
- /** `true`, and moves on to it, if the entry comes after the position; `false` if it was delivered. */
2656
- advance(entry) {
2657
- if (entry.seq <= this.#position) return false;
2658
- this.#position = entry.seq;
2659
- return true;
2660
- }
2661
- };
2662
- /**
2663
- * Hands `listener` the log's entries after `since`, then the new events, with nothing missed or
2664
- * repeated in between (`SpeechUseCases.watch`, the wait). With `sessionId`, only that session's
2665
- * entries (`null`: those outside sessions); `session` events always come, and a `clear` unless it only cleared another scope. Returns a
2666
- * function that stops it; calling it again does nothing.
2667
- *
2668
- * Without `since` (`null`) no entry is replayed; the first event is `position`, the log's
2669
- * `headSeq`, so a stream that drops before its first entry still has a cursor to reconnect with.
2670
- * With `staleSince: 'replay'`, a `since` above `headSeq` (a cursor from another run) is a gap,
2671
- * not a position to wait for: `truncated`, then the whole buffer. Without it, such a `since`
2672
- * waits for entries above it (what the wait means by `since`).
2673
- */
2674
- function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, listener, { pace, onError } = {}) {
2675
- const { log, events } = deps;
2676
- let stale = staleSince === "replay" && requested !== null && requested > log.headSeq;
2677
- const since = stale ? 0 : requested;
2678
- const cursor = new SeqCursor(since ?? Number.NEGATIVE_INFINITY);
2679
- let replaying = since !== null;
2680
- let stopped = false;
2681
- const unsubscribe = events.subscribe((event) => {
2682
- if (event.type === "clear" && event.sessionId !== void 0 && sessionId !== void 0) {
2683
- if (event.sessionId !== sessionId) return;
2684
- }
2685
- if (event.type !== "entry") return listener(event);
2686
- if (replaying || !cursor.advance(event.entry)) return;
2687
- if (sessionId === void 0 || event.entry.sessionId === sessionId) listener(event);
2688
- });
2689
- const stop = () => {
2690
- stopped = true;
2691
- unsubscribe();
2692
- };
2693
- if (since === null) {
2694
- listener({
2695
- type: "position",
2696
- seq: log.headSeq
2697
- });
2698
- return stop;
2699
- }
2700
- /** Replays from the cursor until `pace` pauses it (its promise) or it has caught up. */
2701
- const step = () => {
2702
- for (;;) {
2703
- const { entries, truncated, hasMore } = log.page(cursor.position, 500, sessionId);
2704
- if (truncated || stale) listener({ type: "truncated" });
2705
- stale = false;
2706
- for (const entry of entries) {
2707
- if (!cursor.advance(entry)) continue;
2708
- listener({
2709
- type: "entry",
2710
- entry
2711
- });
2712
- const paused = pace?.();
2713
- if (paused) return paused;
2714
- }
2715
- if (!hasMore) {
2716
- replaying = false;
2717
- return;
2718
- }
2719
- }
2720
- };
2721
- const resume = async (paused) => {
2722
- for (let next = paused; next;) {
2723
- await next;
2724
- if (stopped) return;
2725
- next = step();
2726
- }
2727
- };
2728
- let paused;
2729
- try {
2730
- paused = step();
2731
- } catch (error) {
2732
- stop();
2733
- throw error;
2734
- }
2735
- if (paused) resume(paused).catch((error) => {
2736
- stop();
2737
- onError?.(error);
2738
- });
2739
- return stop;
2740
- }
2741
- // src/application/shared/int-option.ts
2742
- /**
2743
- * A numeric use-case option: `fallback` if it is missing, otherwise checked to be an integer
2744
- * from `min` to `max` (`INVALID_REQUEST` for `field` if not).
2745
- */
2746
- function intOption(field, value, { fallback, min, max }) {
2747
- if (value === void 0) return fallback;
2748
- if (!Number.isInteger(value) || value < min || value > max) throw invalidField(field, `must be an integer from ${min} to ${max}`);
2749
- return value;
2750
- }
2751
3143
  // src/application/services/speech-service.ts
2752
3144
  const MAX_MARKER_LENGTH = API_LIMITS.markerLength;
2753
3145
  /**
@@ -2804,9 +3196,7 @@ var SpeechService = class {
2804
3196
  });
2805
3197
  }
2806
3198
  addMarker(label) {
2807
- const text = label.trim();
2808
- if (text === "") throw invalidField("label", "must not be empty");
2809
- if (text.length > MAX_MARKER_LENGTH) throw invalidField("label", `must be at most ${MAX_MARKER_LENGTH} characters`);
3199
+ const text = markerLabel(label);
2810
3200
  return this.add({
2811
3201
  kind: "marker",
2812
3202
  text,
@@ -2815,6 +3205,11 @@ var SpeechService = class {
2815
3205
  connectionId: null
2816
3206
  });
2817
3207
  }
3208
+ latestMarker(label, session) {
3209
+ const text = markerLabel(label);
3210
+ const sessionId = this.deps.log.resolveFilter(session);
3211
+ return this.deps.log.latestMarker(text, sessionId) ?? null;
3212
+ }
2818
3213
  add(entry) {
2819
3214
  const stored = this.deps.log.append({
2820
3215
  ...entry,
@@ -2827,6 +3222,13 @@ var SpeechService = class {
2827
3222
  return stored;
2828
3223
  }
2829
3224
  };
3225
+ /** A marker label: trimmed, not empty, at most `MAX_MARKER_LENGTH` characters. */
3226
+ function markerLabel(label) {
3227
+ const text = label.trim();
3228
+ if (text === "") throw invalidField("label", "must not be empty");
3229
+ if (text.length > MAX_MARKER_LENGTH) throw invalidField("label", `must be at most ${MAX_MARKER_LENGTH} characters`);
3230
+ return text;
3231
+ }
2830
3232
  // src/application/services/status-service.ts
2831
3233
  /**
2832
3234
  * `GET /api/v1/status`. The composition root moves the state from `starting` to `ready` through
@@ -2932,11 +3334,6 @@ const WAIT_TIMEOUT_MS = API_LIMITS.wait.timeoutMs;
2932
3334
  /** How many of the entries a wait saw its timeout answer holds at most: the last ones. */
2933
3335
  const WAIT_SEEN_LIMIT = API_LIMITS.wait.seen;
2934
3336
  // src/application/services/wait-for-speech-service.ts
2935
- function abortReason(signal) {
2936
- const reason = signal.reason;
2937
- return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The wait was aborted");
2938
- }
2939
- const unavailable = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
2940
3337
  /** The last {@link WAIT_SEEN_LIMIT} entries pushed, and how many came before them. */
2941
3338
  var LastSeen = class {
2942
3339
  #entries = [];
@@ -2971,7 +3368,7 @@ var WaitForSpeechService = class {
2971
3368
  this.deps = deps;
2972
3369
  }
2973
3370
  async wait(options) {
2974
- if (this.closed) throw unavailable();
3371
+ if (this.closed) throw shuttingDown();
2975
3372
  const { signal } = options;
2976
3373
  const since = intOption("since", options.since, {
2977
3374
  fallback: 0,
@@ -3043,7 +3440,7 @@ var WaitForSpeechService = class {
3043
3440
  */
3044
3441
  shutdown() {
3045
3442
  this.closed = true;
3046
- for (const fail of [...this.pending]) fail(unavailable());
3443
+ for (const fail of [...this.pending]) fail(shuttingDown());
3047
3444
  }
3048
3445
  };
3049
3446
  // src/composition/lifecycle.ts
@@ -3195,6 +3592,226 @@ async function createInputInjector(logger) {
3195
3592
  return new DisabledInputInjector(reason);
3196
3593
  }
3197
3594
  }
3595
+ // src/adapters/out/input/disabled-window-system.ts
3596
+ /**
3597
+ * The window system where windows can't be managed (not Windows, or `koffi` could not be loaded):
3598
+ * every call fails with `INPUT_DISABLED`, so the rest of the bridge keeps working.
3599
+ */
3600
+ var DisabledWindowSystem = class {
3601
+ reason;
3602
+ constructor(reason) {
3603
+ this.reason = reason;
3604
+ }
3605
+ processTree(_rootPid) {
3606
+ return this.fail();
3607
+ }
3608
+ topLevelWindows() {
3609
+ return this.fail();
3610
+ }
3611
+ bringToFront(_window) {
3612
+ return this.fail();
3613
+ }
3614
+ fail() {
3615
+ return Promise.reject(new AppError("INPUT_DISABLED", `Windows can't be brought to the front: ${this.reason}`));
3616
+ }
3617
+ };
3618
+ // src/adapters/out/win32/win32-bindings.ts
3619
+ const TH32CS_SNAPPROCESS = 2;
3620
+ const INVALID_HANDLE_VALUE = -1;
3621
+ const GW_OWNER = 4;
3622
+ const SW_RESTORE = 9;
3623
+ const VK_MENU = 18;
3624
+ const KEYEVENTF_KEYUP = 2;
3625
+ /** Characters read of a window title or class name. */
3626
+ const TEXT_LENGTH = 512;
3627
+ /**
3628
+ * Binds the {@link Win32} calls with koffi (Windows only). Handles are `intptr_t` numbers, so they
3629
+ * can be compared and handed back as they are. Only the native calls live here: the logic is in
3630
+ * `Win32WindowSystem`, which the unit tests cover with a fake. Verified by hand on the Windows VM.
3631
+ */
3632
+ function bindWin32(koffi) {
3633
+ const kernel32 = koffi.load("kernel32.dll");
3634
+ const user32 = koffi.load("user32.dll");
3635
+ const ProcessEntry = koffi.struct("PROCESSENTRY32W", {
3636
+ dwSize: "uint32_t",
3637
+ cntUsage: "uint32_t",
3638
+ th32ProcessID: "uint32_t",
3639
+ th32DefaultHeapID: "uintptr_t",
3640
+ th32ModuleID: "uint32_t",
3641
+ cntThreads: "uint32_t",
3642
+ th32ParentProcessID: "uint32_t",
3643
+ pcPriClassBase: "int32_t",
3644
+ dwFlags: "uint32_t",
3645
+ szExeFile: koffi.array("uint16_t", 260)
3646
+ });
3647
+ const entrySize = koffi.sizeof(ProcessEntry);
3648
+ const pidAt = koffi.offsetof(ProcessEntry, "th32ProcessID");
3649
+ const parentAt = koffi.offsetof(ProcessEntry, "th32ParentProcessID");
3650
+ const CreateToolhelp32Snapshot = kernel32.func("intptr_t __stdcall CreateToolhelp32Snapshot(uint32_t dwFlags, uint32_t th32ProcessID)");
3651
+ const Process32FirstW = kernel32.func("int __stdcall Process32FirstW(intptr_t hSnapshot, _Inout_ void *lppe)");
3652
+ const Process32NextW = kernel32.func("int __stdcall Process32NextW(intptr_t hSnapshot, _Inout_ void *lppe)");
3653
+ const CloseHandle = kernel32.func("int __stdcall CloseHandle(intptr_t hObject)");
3654
+ const GetCurrentThreadId = kernel32.func("uint32_t __stdcall GetCurrentThreadId()");
3655
+ koffi.proto("int __stdcall EnumWindowsProc(intptr_t hwnd, intptr_t lParam)");
3656
+ const EnumWindows = user32.func("int __stdcall EnumWindows(EnumWindowsProc *lpEnumFunc, intptr_t lParam)");
3657
+ const GetWindowThreadProcessId = user32.func("uint32_t __stdcall GetWindowThreadProcessId(intptr_t hWnd, _Out_ uint32_t *lpdwProcessId)");
3658
+ const IsWindowVisible = user32.func("int __stdcall IsWindowVisible(intptr_t hWnd)");
3659
+ const GetWindow = user32.func("intptr_t __stdcall GetWindow(intptr_t hWnd, uint32_t uCmd)");
3660
+ const GetWindowTextW = user32.func("int __stdcall GetWindowTextW(intptr_t hWnd, _Out_ void *lpString, int nMaxCount)");
3661
+ const GetClassNameW = user32.func("int __stdcall GetClassNameW(intptr_t hWnd, _Out_ void *lpClassName, int nMaxCount)");
3662
+ const IsIconic = user32.func("int __stdcall IsIconic(intptr_t hWnd)");
3663
+ const ShowWindow = user32.func("int __stdcall ShowWindow(intptr_t hWnd, int nCmdShow)");
3664
+ const keybd_event = user32.func("void __stdcall keybd_event(uint8_t bVk, uint8_t bScan, uint32_t dwFlags, uintptr_t dwExtraInfo)");
3665
+ const SetForegroundWindow = user32.func("int __stdcall SetForegroundWindow(intptr_t hWnd)");
3666
+ const BringWindowToTop = user32.func("int __stdcall BringWindowToTop(intptr_t hWnd)");
3667
+ const GetForegroundWindow = user32.func("intptr_t __stdcall GetForegroundWindow()");
3668
+ const AttachThreadInput = user32.func("int __stdcall AttachThreadInput(uint32_t idAttach, uint32_t idAttachTo, int fAttach)");
3669
+ const text = (read, hwnd) => {
3670
+ const buffer = Buffer.alloc(TEXT_LENGTH * 2);
3671
+ const length = Number(read(hwnd, buffer, TEXT_LENGTH));
3672
+ return buffer.toString("utf16le", 0, Math.max(0, length) * 2);
3673
+ };
3674
+ return {
3675
+ processes() {
3676
+ const snapshot = Number(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
3677
+ if (snapshot === INVALID_HANDLE_VALUE) throw new Error("CreateToolhelp32Snapshot failed");
3678
+ try {
3679
+ const entry = Buffer.alloc(entrySize);
3680
+ entry.writeUInt32LE(entrySize, 0);
3681
+ const list = [];
3682
+ for (let more = Process32FirstW(snapshot, entry) !== 0; more; more = Process32NextW(snapshot, entry) !== 0) list.push({
3683
+ pid: entry.readUInt32LE(pidAt),
3684
+ parentPid: entry.readUInt32LE(parentAt)
3685
+ });
3686
+ return list;
3687
+ } finally {
3688
+ CloseHandle(snapshot);
3689
+ }
3690
+ },
3691
+ topLevelWindows() {
3692
+ const list = [];
3693
+ EnumWindows((hwnd) => {
3694
+ list.push(Number(hwnd));
3695
+ return 1;
3696
+ }, 0);
3697
+ return list;
3698
+ },
3699
+ owner(hwnd) {
3700
+ const pid = [0];
3701
+ const thread = Number(GetWindowThreadProcessId(hwnd, pid));
3702
+ return {
3703
+ pid: pid[0],
3704
+ thread
3705
+ };
3706
+ },
3707
+ isVisible: (hwnd) => IsWindowVisible(hwnd) !== 0,
3708
+ ownerWindow: (hwnd) => Number(GetWindow(hwnd, GW_OWNER)),
3709
+ title: (hwnd) => text(GetWindowTextW, hwnd),
3710
+ className: (hwnd) => text(GetClassNameW, hwnd),
3711
+ isMinimized: (hwnd) => IsIconic(hwnd) !== 0,
3712
+ restore: (hwnd) => void ShowWindow(hwnd, SW_RESTORE),
3713
+ tapAlt() {
3714
+ keybd_event(VK_MENU, 0, 0, 0);
3715
+ keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);
3716
+ },
3717
+ setForeground: (hwnd) => SetForegroundWindow(hwnd) !== 0,
3718
+ bringToTop: (hwnd) => void BringWindowToTop(hwnd),
3719
+ foreground: () => Number(GetForegroundWindow()),
3720
+ currentThread: () => Number(GetCurrentThreadId()),
3721
+ attachInput: (thread, toThread, attach) => AttachThreadInput(thread, toThread, attach ? 1 : 0) !== 0
3722
+ };
3723
+ }
3724
+ // src/adapters/out/win32/win32-window-system.ts
3725
+ /**
3726
+ * {@link WindowSystem} on Win32 (docs/usage/native-input.md#bringing-the-browser-to-the-front).
3727
+ * Windows lets a background process take the foreground only in some cases, so `bringToFront`
3728
+ * first taps Alt (the bridge is then the process that sent the last input, which Windows
3729
+ * allows), and if that wasn't enough, tries once more attached to the foreground window's input
3730
+ * thread.
3731
+ */
3732
+ var Win32WindowSystem = class {
3733
+ win32;
3734
+ constructor(win32) {
3735
+ this.win32 = win32;
3736
+ }
3737
+ processTree(rootPid) {
3738
+ const children = /* @__PURE__ */ new Map();
3739
+ for (const { pid, parentPid } of this.win32.processes()) {
3740
+ if (pid === parentPid) continue;
3741
+ const siblings = children.get(parentPid) ?? [];
3742
+ siblings.push(pid);
3743
+ children.set(parentPid, siblings);
3744
+ }
3745
+ const tree = /* @__PURE__ */ new Set([rootPid]);
3746
+ const open = [rootPid];
3747
+ for (let pid = open.pop(); pid !== void 0; pid = open.pop()) for (const child of children.get(pid) ?? []) {
3748
+ if (tree.has(child)) continue;
3749
+ tree.add(child);
3750
+ open.push(child);
3751
+ }
3752
+ return Promise.resolve(tree);
3753
+ }
3754
+ topLevelWindows() {
3755
+ const { win32 } = this;
3756
+ const windows = [];
3757
+ for (const hwnd of win32.topLevelWindows()) {
3758
+ if (!win32.isVisible(hwnd) || win32.ownerWindow(hwnd) !== 0) continue;
3759
+ windows.push({
3760
+ handle: hwnd,
3761
+ pid: win32.owner(hwnd).pid,
3762
+ title: win32.title(hwnd),
3763
+ className: win32.className(hwnd)
3764
+ });
3765
+ }
3766
+ return Promise.resolve(windows);
3767
+ }
3768
+ bringToFront(window) {
3769
+ const { win32 } = this;
3770
+ const hwnd = window.handle;
3771
+ if (win32.isMinimized(hwnd)) win32.restore(hwnd);
3772
+ win32.tapAlt();
3773
+ win32.setForeground(hwnd);
3774
+ win32.bringToTop(hwnd);
3775
+ if (win32.foreground() !== hwnd) this.attachedToForeground(hwnd);
3776
+ return Promise.resolve(win32.foreground() === hwnd);
3777
+ }
3778
+ /** Brings `hwnd` forward while attached to the input thread of the current foreground window. */
3779
+ attachedToForeground(hwnd) {
3780
+ const { win32 } = this;
3781
+ const current = win32.foreground();
3782
+ const own = win32.currentThread();
3783
+ const theirs = current === 0 ? 0 : win32.owner(current).thread;
3784
+ const attached = theirs !== 0 && theirs !== own && win32.attachInput(own, theirs, true);
3785
+ try {
3786
+ win32.setForeground(hwnd);
3787
+ win32.bringToTop(hwnd);
3788
+ } finally {
3789
+ if (attached) win32.attachInput(own, theirs, false);
3790
+ }
3791
+ }
3792
+ };
3793
+ // src/composition/window-system.ts
3794
+ /**
3795
+ * Loads `koffi`, an optional dependency, and binds the Win32 calls that bring a window to the
3796
+ * front. Not on Windows, or when it can't be loaded, the bridge keeps running with a window
3797
+ * system that answers `INPUT_DISABLED` (docs/usage/native-input.md#bringing-the-browser-to-the-front).
3798
+ */
3799
+ async function createWindowSystem(logger) {
3800
+ if (process.platform !== "win32") {
3801
+ logger.debug("bringing windows to the front is off: only on Windows");
3802
+ return new DisabledWindowSystem("only on Windows");
3803
+ }
3804
+ try {
3805
+ const module = await import("koffi");
3806
+ const windows = new Win32WindowSystem(bindWin32(module.default ?? module));
3807
+ logger.debug("bringing windows to the front is available (koffi)");
3808
+ return windows;
3809
+ } catch (error) {
3810
+ const reason = `koffi could not be loaded (${error instanceof Error ? error.message : String(error)})`;
3811
+ logger.warn(`bringing windows to the front is off: ${reason}`);
3812
+ return new DisabledWindowSystem(reason);
3813
+ }
3814
+ }
3198
3815
  // src/adapters/out/log/format.ts
3199
3816
  const ESC = "\x1B[";
3200
3817
  const RESET = `${ESC}0m`;
@@ -3681,6 +4298,9 @@ var ChildProcessSupervisor = class {
3681
4298
  this.options = options;
3682
4299
  this.settings = options.settings;
3683
4300
  }
4301
+ pid() {
4302
+ return this.state === "running" ? this.child?.pid ?? null : null;
4303
+ }
3684
4304
  status() {
3685
4305
  const { version, port } = this.active ?? this.resolved();
3686
4306
  return {
@@ -4142,6 +4762,12 @@ const PROTOCOL_HEADER = "x-sr-bridge-protocol";
4142
4762
  */
4143
4763
  const LOCAL_HEADER = "x-sr-bridge-local";
4144
4764
  /**
4765
+ * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
4766
+ * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
4767
+ * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
4768
+ */
4769
+ const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
4770
+ /**
4145
4771
  * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
4146
4772
  * none: the bridge runs from source, or the package was built without the UI.
4147
4773
  */
@@ -4183,6 +4809,7 @@ function createUiMount(dir, logger) {
4183
4809
  try {
4184
4810
  process.env[BRIDGE_API_URL_ENV] = apiUrl;
4185
4811
  process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
4812
+ globalThis[UI_LOGGER_KEY] = logger;
4186
4813
  const module = await import(file.href);
4187
4814
  if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
4188
4815
  settle.resolve(module.handler);
@@ -4312,6 +4939,13 @@ var SeqQueue = class {
4312
4939
  hasMore: true
4313
4940
  };
4314
4941
  }
4942
+ /** The newest item the predicate accepts. O(n) from the end. */
4943
+ findLast(predicate) {
4944
+ for (let index = this.#items.length - 1; index >= this.#head; index--) {
4945
+ const item = this.#items[index];
4946
+ if (predicate(item)) return item;
4947
+ }
4948
+ }
4315
4949
  /** Removes every item the predicate accepts, wherever it sits. Keeps the order. O(n). */
4316
4950
  removeWhere(predicate) {
4317
4951
  this.#items = this.#items.slice(this.#head).filter((item) => !predicate(item));
@@ -4399,6 +5033,13 @@ var SpeechLog = class {
4399
5033
  };
4400
5034
  }
4401
5035
  /**
5036
+ * The newest marker whose text is `label`, of all entries or, with `sessionId`, of that
5037
+ * session (`null`: outside sessions). `undefined` if there is none (also when it was dropped).
5038
+ */
5039
+ latestMarker(label, sessionId) {
5040
+ return (sessionId === void 0 ? this.#entries : this.#bySession.get(sessionId))?.findLast((entry) => entry.kind === "marker" && entry.text === label);
5041
+ }
5042
+ /**
4402
5043
  * Removes the entries (and markers) of the current session or of the entries outside sessions
4403
5044
  * (`none`), and returns that scope's id (`null`: outside). The session stays current. `NOT_FOUND`
4404
5045
  * for `current` with none current or an id never given out, `INVALID_REQUEST` for an ended
@@ -4577,6 +5218,13 @@ async function startBridge(options) {
4577
5218
  clock,
4578
5219
  logger: log.for("native-input")
4579
5220
  });
5221
+ const captures = new InputCaptureService({
5222
+ input,
5223
+ log: speechLog,
5224
+ events,
5225
+ clock,
5226
+ pace: () => yieldEvery(256)
5227
+ });
4580
5228
  const configService = new ConfigService({
4581
5229
  store,
4582
5230
  logger: configLogger,
@@ -4585,6 +5233,13 @@ async function startBridge(options) {
4585
5233
  pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
4586
5234
  });
4587
5235
  const supervisors = createSupervisors(config, seams, log);
5236
+ const focus = new WindowFocusService({
5237
+ windows: seams.windowSystem ?? await createWindowSystem(log.for("native-input")),
5238
+ queue: input,
5239
+ services: supervisors,
5240
+ clock,
5241
+ logger: log.for("native-input")
5242
+ });
4588
5243
  const childServices = new ChildServicesService({
4589
5244
  supervisors,
4590
5245
  config: () => configService.get(),
@@ -4609,6 +5264,8 @@ async function startBridge(options) {
4609
5264
  config: configService,
4610
5265
  sessions,
4611
5266
  input,
5267
+ captures,
5268
+ focus,
4612
5269
  logger: log.for("http-api"),
4613
5270
  hostnames: [hostname()],
4614
5271
  proxies: proxyRoutes(childServices),
@@ -4619,7 +5276,7 @@ async function startBridge(options) {
4619
5276
  await ui?.mount(bridgeApiUrl(config.http.host, ports.http));
4620
5277
  const lifecycle = new BridgeLifecycleService({
4621
5278
  state: status,
4622
- waits,
5279
+ pending: [waits, captures],
4623
5280
  startServices: () => childServices.startEnabled(),
4624
5281
  stopOrder: [
4625
5282
  http,