screenreader-speech-capture 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/README.md +8 -2
  2. package/dist/cli.mjs +984 -278
  3. package/dist/ui/adapter-node.js +1 -1
  4. package/dist/ui/client/ui/_app/immutable/chunks/{CM9WugkD.js → 0YgL1EU2.js} +36 -36
  5. package/dist/ui/client/ui/_app/immutable/chunks/0YgL1EU2.js.br +0 -0
  6. package/dist/ui/client/ui/_app/immutable/chunks/0YgL1EU2.js.gz +0 -0
  7. package/dist/ui/client/ui/_app/immutable/chunks/BYvlzyV8.js +1 -0
  8. package/dist/ui/client/ui/_app/immutable/chunks/BYvlzyV8.js.br +2 -0
  9. package/dist/ui/client/ui/_app/immutable/chunks/BYvlzyV8.js.gz +0 -0
  10. package/dist/ui/client/ui/_app/immutable/chunks/BfvDkxmG.js +3 -0
  11. package/dist/ui/client/ui/_app/immutable/chunks/BfvDkxmG.js.br +0 -0
  12. package/dist/ui/client/ui/_app/immutable/chunks/BfvDkxmG.js.gz +0 -0
  13. package/dist/ui/client/ui/_app/immutable/chunks/CSCPyqWx.js +1 -0
  14. package/dist/ui/client/ui/_app/immutable/chunks/CSCPyqWx.js.br +3 -0
  15. package/dist/ui/client/ui/_app/immutable/chunks/CSCPyqWx.js.gz +0 -0
  16. package/dist/ui/client/ui/_app/immutable/chunks/{Fimt9aTv.js → Cba3ZwaX.js} +11 -11
  17. package/dist/ui/client/ui/_app/immutable/chunks/Cba3ZwaX.js.br +0 -0
  18. package/dist/ui/client/ui/_app/immutable/chunks/Cba3ZwaX.js.gz +0 -0
  19. package/dist/ui/client/ui/_app/immutable/chunks/DErxe_FC.js +3 -0
  20. package/dist/ui/client/ui/_app/immutable/chunks/DErxe_FC.js.br +0 -0
  21. package/dist/ui/client/ui/_app/immutable/chunks/DErxe_FC.js.gz +0 -0
  22. package/dist/ui/client/ui/_app/immutable/chunks/Dqufijaz.js +1 -0
  23. package/dist/ui/client/ui/_app/immutable/chunks/Dqufijaz.js.br +0 -0
  24. package/dist/ui/client/ui/_app/immutable/chunks/Dqufijaz.js.gz +0 -0
  25. package/dist/ui/client/ui/_app/immutable/chunks/WpCriteK.js +1 -0
  26. package/dist/ui/client/ui/_app/immutable/chunks/WpCriteK.js.br +1 -0
  27. package/dist/ui/client/ui/_app/immutable/chunks/WpCriteK.js.gz +0 -0
  28. package/dist/ui/client/ui/_app/immutable/chunks/wbLSPbHY.js +4 -0
  29. package/dist/ui/client/ui/_app/immutable/chunks/wbLSPbHY.js.br +0 -0
  30. package/dist/ui/client/ui/_app/immutable/chunks/wbLSPbHY.js.gz +0 -0
  31. package/dist/ui/client/ui/_app/immutable/entry/app.B6hhDf4F.js +2 -0
  32. package/dist/ui/client/ui/_app/immutable/entry/app.B6hhDf4F.js.br +0 -0
  33. package/dist/ui/client/ui/_app/immutable/entry/app.B6hhDf4F.js.gz +0 -0
  34. package/dist/ui/client/ui/_app/immutable/entry/{start.uodUAHNT.js → start.Dluk7nQO.js} +2 -2
  35. package/dist/ui/client/ui/_app/immutable/entry/start.Dluk7nQO.js.br +0 -0
  36. package/dist/ui/client/ui/_app/immutable/entry/start.Dluk7nQO.js.gz +0 -0
  37. package/dist/ui/client/ui/_app/immutable/nodes/0.D-lhv0Us.js +1 -0
  38. package/dist/ui/client/ui/_app/immutable/nodes/0.D-lhv0Us.js.br +0 -0
  39. package/dist/ui/client/ui/_app/immutable/nodes/0.D-lhv0Us.js.gz +0 -0
  40. package/dist/ui/client/ui/_app/immutable/nodes/1.Cs4GAsCO.js +1 -0
  41. package/dist/ui/client/ui/_app/immutable/nodes/1.Cs4GAsCO.js.br +1 -0
  42. package/dist/ui/client/ui/_app/immutable/nodes/1.Cs4GAsCO.js.gz +0 -0
  43. package/dist/ui/client/ui/_app/immutable/nodes/2.CmuzlN_T.js +52 -0
  44. package/dist/ui/client/ui/_app/immutable/nodes/2.CmuzlN_T.js.br +0 -0
  45. package/dist/ui/client/ui/_app/immutable/nodes/2.CmuzlN_T.js.gz +0 -0
  46. package/dist/ui/client/ui/_app/immutable/nodes/3.DMXXeBbC.js +5 -0
  47. package/dist/ui/client/ui/_app/immutable/nodes/3.DMXXeBbC.js.br +0 -0
  48. package/dist/ui/client/ui/_app/immutable/nodes/3.DMXXeBbC.js.gz +0 -0
  49. package/dist/ui/client/ui/_app/immutable/nodes/{4.DY8qq4Io.js → 4.CMHCNMDn.js} +1 -1
  50. package/dist/ui/client/ui/_app/immutable/nodes/4.CMHCNMDn.js.br +0 -0
  51. package/dist/ui/client/ui/_app/immutable/nodes/4.CMHCNMDn.js.gz +0 -0
  52. package/dist/ui/client/ui/_app/version.json +1 -1
  53. package/dist/ui/client/ui/_app/version.json.br +0 -0
  54. package/dist/ui/client/ui/_app/version.json.gz +0 -0
  55. package/dist/ui/server/.vite/manifest.json +97 -54
  56. package/dist/ui/server/chunks/composition.js +112 -118
  57. package/dist/ui/server/chunks/composition.js.map +1 -1
  58. package/dist/ui/server/chunks/config.js +139 -3
  59. package/dist/ui/server/chunks/config.js.map +1 -1
  60. package/dist/ui/server/chunks/exports.js +19 -204
  61. package/dist/ui/server/chunks/exports.js.map +1 -1
  62. package/dist/ui/server/chunks/functions.js +1 -1
  63. package/dist/ui/server/chunks/icon-button.js +1 -1
  64. package/dist/ui/server/chunks/instance.js +9 -56
  65. package/dist/ui/server/chunks/instance.js.map +1 -1
  66. package/dist/ui/server/chunks/internal.js +55 -4
  67. package/dist/ui/server/chunks/internal.js.map +1 -1
  68. package/dist/ui/server/chunks/outlined-text-field.js +1 -1
  69. package/dist/ui/server/chunks/remote-1j2tn2d.js +4 -0
  70. package/dist/ui/server/chunks/remote.js +1565 -0
  71. package/dist/ui/server/chunks/remote.js.map +1 -0
  72. package/dist/ui/server/chunks/scope.js +13 -0
  73. package/dist/ui/server/chunks/scope.js.map +1 -0
  74. package/dist/ui/server/chunks/server-errors.js +48 -1
  75. package/dist/ui/server/chunks/server-errors.js.map +1 -1
  76. package/dist/ui/server/chunks/server2.js +24 -1
  77. package/dist/ui/server/chunks/server2.js.map +1 -1
  78. package/dist/ui/server/chunks/sessions.js +65 -0
  79. package/dist/ui/server/chunks/sessions.js.map +1 -0
  80. package/dist/ui/server/chunks/sessions.remote.js +56 -0
  81. package/dist/ui/server/chunks/sessions.remote.js.map +1 -0
  82. package/dist/ui/server/chunks/shared-errors.js +214 -0
  83. package/dist/ui/server/chunks/shared-errors.js.map +1 -0
  84. package/dist/ui/server/chunks/src.js +123 -44
  85. package/dist/ui/server/chunks/src.js.map +1 -1
  86. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js +3 -5
  87. package/dist/ui/server/entries/endpoints/api/config/_server.ts.js.map +1 -1
  88. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js +3 -4
  89. package/dist/ui/server/entries/endpoints/api/markers/_server.ts.js.map +1 -1
  90. package/dist/ui/server/entries/endpoints/api/sessions/_id_id_/_server.ts.js +12 -0
  91. package/dist/ui/server/entries/endpoints/api/sessions/_id_id_/_server.ts.js.map +1 -0
  92. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js +4 -9
  93. package/dist/ui/server/entries/endpoints/api/sessions/_server.ts.js.map +1 -1
  94. package/dist/ui/server/entries/endpoints/api/sessions/end/_server.ts.js +2 -3
  95. package/dist/ui/server/entries/endpoints/api/sessions/end/_server.ts.js.map +1 -1
  96. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js +6 -9
  97. package/dist/ui/server/entries/endpoints/api/speech/_server.ts.js.map +1 -1
  98. package/dist/ui/server/entries/endpoints/api/speech/stream/_server.ts.js +3 -3
  99. package/dist/ui/server/entries/endpoints/api/speech/stream/_server.ts.js.map +1 -1
  100. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js +2 -3
  101. package/dist/ui/server/entries/endpoints/api/status/_server.ts.js.map +1 -1
  102. package/dist/ui/server/entries/fallbacks/error.svelte.js +1 -1
  103. package/dist/ui/server/entries/hooks.server.js +145 -1
  104. package/dist/ui/server/entries/hooks.server.js.map +1 -1
  105. package/dist/ui/server/entries/pages/_layout.server.ts.js +2 -3
  106. package/dist/ui/server/entries/pages/_layout.server.ts.js.map +1 -1
  107. package/dist/ui/server/entries/pages/_layout.svelte.js +4 -2
  108. package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
  109. package/dist/ui/server/entries/pages/_page.server.ts.js +3 -3
  110. package/dist/ui/server/entries/pages/_page.server.ts.js.map +1 -1
  111. package/dist/ui/server/entries/pages/_page.svelte.js +8 -62
  112. package/dist/ui/server/entries/pages/_page.svelte.js.map +1 -1
  113. package/dist/ui/server/entries/pages/settings/_page.svelte.js +3 -2
  114. package/dist/ui/server/entries/pages/settings/_page.svelte.js.map +1 -1
  115. package/dist/ui/server/entries/params.js +60 -0
  116. package/dist/ui/server/entries/params.js.map +1 -0
  117. package/dist/ui/server/env.js +1 -1
  118. package/dist/ui/server/index.js +2 -2
  119. package/dist/ui/server/manifest-full.js +7 -6
  120. package/dist/ui/server/manifest.js +7 -6
  121. package/dist/ui/server/nodes/0.js +1 -1
  122. package/dist/ui/server/nodes/1.js +1 -1
  123. package/dist/ui/server/nodes/2.js +1 -1
  124. package/dist/ui/server/nodes/3.js +1 -1
  125. package/dist/ui/server/nodes/4.js +1 -1
  126. package/dist/ui/server/remote-entry.js +1 -1565
  127. package/dist/ui/server/server.js +7 -6
  128. package/package.json +3 -2
  129. package/dist/ui/client/ui/_app/immutable/chunks/C67ohLw_.js +0 -1
  130. package/dist/ui/client/ui/_app/immutable/chunks/C67ohLw_.js.br +0 -3
  131. package/dist/ui/client/ui/_app/immutable/chunks/C67ohLw_.js.gz +0 -0
  132. package/dist/ui/client/ui/_app/immutable/chunks/CKeiBgOI.js +0 -1
  133. package/dist/ui/client/ui/_app/immutable/chunks/CKeiBgOI.js.br +0 -1
  134. package/dist/ui/client/ui/_app/immutable/chunks/CKeiBgOI.js.gz +0 -0
  135. package/dist/ui/client/ui/_app/immutable/chunks/CM9WugkD.js.br +0 -0
  136. package/dist/ui/client/ui/_app/immutable/chunks/CM9WugkD.js.gz +0 -0
  137. package/dist/ui/client/ui/_app/immutable/chunks/CVUOwNb5.js +0 -3
  138. package/dist/ui/client/ui/_app/immutable/chunks/CVUOwNb5.js.br +0 -0
  139. package/dist/ui/client/ui/_app/immutable/chunks/CVUOwNb5.js.gz +0 -0
  140. package/dist/ui/client/ui/_app/immutable/chunks/CXrPUR7p.js +0 -4
  141. package/dist/ui/client/ui/_app/immutable/chunks/CXrPUR7p.js.br +0 -0
  142. package/dist/ui/client/ui/_app/immutable/chunks/CXrPUR7p.js.gz +0 -0
  143. package/dist/ui/client/ui/_app/immutable/chunks/Dksil5Gu.js +0 -1
  144. package/dist/ui/client/ui/_app/immutable/chunks/Dksil5Gu.js.br +0 -0
  145. package/dist/ui/client/ui/_app/immutable/chunks/Dksil5Gu.js.gz +0 -0
  146. package/dist/ui/client/ui/_app/immutable/chunks/DnL0kOQY.js +0 -1
  147. package/dist/ui/client/ui/_app/immutable/chunks/DnL0kOQY.js.br +0 -2
  148. package/dist/ui/client/ui/_app/immutable/chunks/DnL0kOQY.js.gz +0 -0
  149. package/dist/ui/client/ui/_app/immutable/chunks/Fimt9aTv.js.br +0 -0
  150. package/dist/ui/client/ui/_app/immutable/chunks/Fimt9aTv.js.gz +0 -0
  151. package/dist/ui/client/ui/_app/immutable/chunks/h7UQ89-l.js +0 -3
  152. package/dist/ui/client/ui/_app/immutable/chunks/h7UQ89-l.js.br +0 -0
  153. package/dist/ui/client/ui/_app/immutable/chunks/h7UQ89-l.js.gz +0 -0
  154. package/dist/ui/client/ui/_app/immutable/entry/app.BQe0vf14.js +0 -2
  155. package/dist/ui/client/ui/_app/immutable/entry/app.BQe0vf14.js.br +0 -0
  156. package/dist/ui/client/ui/_app/immutable/entry/app.BQe0vf14.js.gz +0 -0
  157. package/dist/ui/client/ui/_app/immutable/entry/start.uodUAHNT.js.br +0 -0
  158. package/dist/ui/client/ui/_app/immutable/entry/start.uodUAHNT.js.gz +0 -0
  159. package/dist/ui/client/ui/_app/immutable/nodes/0.kO9a4iA1.js +0 -1
  160. package/dist/ui/client/ui/_app/immutable/nodes/0.kO9a4iA1.js.br +0 -0
  161. package/dist/ui/client/ui/_app/immutable/nodes/0.kO9a4iA1.js.gz +0 -0
  162. package/dist/ui/client/ui/_app/immutable/nodes/1.jZ-iBVjE.js +0 -1
  163. package/dist/ui/client/ui/_app/immutable/nodes/1.jZ-iBVjE.js.br +0 -2
  164. package/dist/ui/client/ui/_app/immutable/nodes/1.jZ-iBVjE.js.gz +0 -0
  165. package/dist/ui/client/ui/_app/immutable/nodes/2.CWoJ2uhd.js +0 -52
  166. package/dist/ui/client/ui/_app/immutable/nodes/2.CWoJ2uhd.js.br +0 -0
  167. package/dist/ui/client/ui/_app/immutable/nodes/2.CWoJ2uhd.js.gz +0 -0
  168. package/dist/ui/client/ui/_app/immutable/nodes/3.DcigOv3T.js +0 -5
  169. package/dist/ui/client/ui/_app/immutable/nodes/3.DcigOv3T.js.br +0 -0
  170. package/dist/ui/client/ui/_app/immutable/nodes/3.DcigOv3T.js.gz +0 -0
  171. package/dist/ui/client/ui/_app/immutable/nodes/4.DY8qq4Io.js.br +0 -0
  172. package/dist/ui/client/ui/_app/immutable/nodes/4.DY8qq4Io.js.gz +0 -0
  173. package/dist/ui/server/chunks/bridge-api.js +0 -105
  174. package/dist/ui/server/chunks/bridge-api.js.map +0 -1
  175. package/dist/ui/server/entries/endpoints/api/sessions/_id_/_server.ts.js +0 -13
  176. package/dist/ui/server/entries/endpoints/api/sessions/_id_/_server.ts.js.map +0 -1
  177. package/dist/ui/server/remote-entry.js.map +0 -1
package/dist/cli.mjs CHANGED
@@ -13,15 +13,20 @@ 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";
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.24";
23
23
  /** Path prefix of every API route. */
24
24
  const API_PREFIX = "/api/v1";
25
+ /**
26
+ * Response header with {@link API_VERSION} on every answer under {@link API_PREFIX} (since 1.22),
27
+ * so a client checks the version on each answer instead of asking `GET /status` first.
28
+ */
29
+ const API_VERSION_HEADER = "X-SR-Speech-Api-Version";
25
30
  const DEFAULT_CONFIG$1 = {
26
31
  lang: void 0,
27
32
  message: void 0,
@@ -651,7 +656,38 @@ const API_LIMITS = {
651
656
  max: 1e4
652
657
  },
653
658
  /** Most chords in one request. */
654
- maxKeys: 100
659
+ maxKeys: 100,
660
+ /** Longest `title` of `POST /input/focus`. */
661
+ focusTitleLength: 200
662
+ },
663
+ /**
664
+ * `capture` of `POST /input/click` and `POST /input/keys` (and the client's `record()`, which
665
+ * uses the same defaults): the defaults and ranges in milliseconds.
666
+ */
667
+ capture: {
668
+ /** Silence that ends the capture. */
669
+ quietForMs: {
670
+ default: 500,
671
+ min: 1,
672
+ max: 6e4
673
+ },
674
+ /** How long the first speech may take after the input. */
675
+ firstWithinMs: {
676
+ default: 2e3,
677
+ max: 3e5
678
+ },
679
+ /** Longest capture, counted from the input. */
680
+ timeoutMs: {
681
+ default: 1e4,
682
+ max: 3e5
683
+ },
684
+ /** Silence to wait for before the input (0: none). */
685
+ settleMs: {
686
+ default: 0,
687
+ max: 6e4
688
+ },
689
+ /** Entries the answer holds at most: the first ones. */
690
+ entries: 1e4
655
691
  }
656
692
  };
657
693
  /** Ranges of the settings (`GET` / `PUT /config`). */
@@ -751,33 +787,125 @@ const ERROR_STATUS = {
751
787
  NOT_FOUND: 404,
752
788
  FORBIDDEN: 403,
753
789
  INPUT_DISABLED: 409,
790
+ FOCUS_FAILED: 409,
754
791
  SERVICE_UNAVAILABLE: 503,
755
792
  INTERNAL: 500
756
793
  };
794
+ API_LIMITS.wait.seen, `${API_LIMITS.wait.seen}`;
795
+ `${API_LIMITS.markerLength}`;
757
796
  // ../shared/src/input.ts
758
797
  const { coordinate: coordinate$1, delayMs: delayMs$1, maxKeys: maxKeys$1 } = API_LIMITS.input;
798
+ const CAPTURE = API_LIMITS.capture;
799
+ CAPTURE.quietForMs.min, CAPTURE.quietForMs.max, `${CAPTURE.quietForMs.default}`, CAPTURE.firstWithinMs.max, `${CAPTURE.firstWithinMs.default}`, CAPTURE.timeoutMs.max, `${CAPTURE.timeoutMs.default}`, CAPTURE.settleMs.max;
800
+ CAPTURE.entries, `${CAPTURE.entries}`;
759
801
  -coordinate$1, -coordinate$1;
760
802
  `${maxKeys$1}`, delayMs$1.max, `${delayMs$1.default}`;
803
+ API_LIMITS.input.focusTitleLength;
804
+ // ../shared/src/key-chord.ts
805
+ /**
806
+ * The key names of `POST /input/keys` (docs/usage/native-input.md#key-names). The bridge parses
807
+ * chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
808
+ * so both use this one copy. Like `text-match.ts`, it belongs to the contract, not to either side.
809
+ */
810
+ /** Keys that can be held down while another key is pressed. `Insert` and `CapsLock` are the screen reader keys. */
811
+ const MODIFIER_KEYS = [
812
+ "control",
813
+ "shift",
814
+ "alt",
815
+ "win",
816
+ "insert",
817
+ "capslock"
818
+ ];
819
+ /** Keys with a name, besides `a`–`z` and `0`–`9`. */
820
+ const NAMED_KEYS = [
821
+ "enter",
822
+ "tab",
823
+ "escape",
824
+ "space",
825
+ "backspace",
826
+ "delete",
827
+ "up",
828
+ "down",
829
+ "left",
830
+ "right",
831
+ "home",
832
+ "end",
833
+ "pageup",
834
+ "pagedown",
835
+ ...Array.from({ length: 12 }, (_, index) => `f${index + 1}`)
836
+ ];
837
+ /** Aliases accepted in a chord, by their lower-case spelling. */
838
+ const KEY_ALIASES = {
839
+ ctrl: "control",
840
+ windows: "win",
841
+ meta: "win",
842
+ esc: "escape",
843
+ return: "enter",
844
+ del: "delete",
845
+ ins: "insert",
846
+ pgup: "pageup",
847
+ pgdn: "pagedown"
848
+ };
849
+ const KEYS = /* @__PURE__ */ new Set([
850
+ ...MODIFIER_KEYS,
851
+ ...NAMED_KEYS,
852
+ ..."abcdefghijklmnopqrstuvwxyz0123456789"
853
+ ]);
854
+ const MODIFIER_SET = new Set(MODIFIER_KEYS);
855
+ /**
856
+ * Parses `Insert+T` or `Control+Shift+Home`: modifiers and one last key, joined with `+`, names
857
+ * case-insensitive. Only modifiers may come before the last key, and none twice. A lone modifier
858
+ * (`Insert`) is a chord of that key.
859
+ */
860
+ function parseKeyChord$1(chord) {
861
+ const names = [];
862
+ for (const part of chord.split("+")) {
863
+ const lower = part.trim().toLowerCase();
864
+ const name = KEY_ALIASES[lower] ?? lower;
865
+ if (!KEYS.has(name)) return {
866
+ ok: false,
867
+ message: `unknown key "${part.trim()}" in "${chord}"`
868
+ };
869
+ names.push(name);
870
+ }
871
+ const key = names.pop();
872
+ if (new Set(names).size !== names.length || names.includes(key)) return {
873
+ ok: false,
874
+ message: `"${chord}" repeats a key`
875
+ };
876
+ const notModifier = names.find((name) => !MODIFIER_SET.has(name));
877
+ if (notModifier !== void 0) return {
878
+ ok: false,
879
+ message: `"${notModifier}" in "${chord}" is not a modifier`
880
+ };
881
+ return {
882
+ ok: true,
883
+ chord: {
884
+ modifiers: names,
885
+ key
886
+ }
887
+ };
888
+ }
761
889
  // ../shared/src/services.ts
762
890
  /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
763
891
  const PLAYWRIGHT_PATH = "/playwright";
764
892
  /** Playwright MCP (streamable HTTP): `http://<bridge>:5151/playwright-mcp`. */
765
893
  const PLAYWRIGHT_MCP_PATH = "/playwright-mcp";
766
894
  // ../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());
895
+ const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
896
+ const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
769
897
  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
898
  const sessionEntries = {
771
- id: /* @__PURE__ */ pipe(integer$2(1), /* @__PURE__ */ description("Increasing, restarts at 1 with the bridge.")),
899
+ id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, restarts at 1 with the bridge.")),
772
900
  name: /* @__PURE__ */ string(),
773
901
  run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
774
902
  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."))
903
+ startedAt: timestamp$1,
904
+ endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
905
+ 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.")),
906
+ firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
907
+ lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
908
+ entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
781
909
  };
782
910
  label("For example the test title."), label("Optional label that groups sessions, for example one per test run.");
783
911
  ({ ...sessionEntries });
@@ -786,8 +914,6 @@ label("For example the test title."), label("Optional label that groups sessions
786
914
  * one client ends or replaces another one's session. Optional. API 1.10.
787
915
  */
788
916
  const CLIENT_HEADER = "x-sr-speech-client";
789
- API_LIMITS.wait.seen, `${API_LIMITS.wait.seen}`;
790
- `${API_LIMITS.markerLength}`;
791
917
  // ../shared/src/text-match.ts
792
918
  /**
793
919
  * The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
@@ -1294,9 +1420,9 @@ function booleanParam(url, name) {
1294
1420
  function sessionParam(url) {
1295
1421
  const raw = url.searchParams.get("session");
1296
1422
  if (raw === null || raw === "") return void 0;
1297
- if (raw === "current" || raw === "none") return raw;
1423
+ if (raw === "current" || raw === "active" || raw === "none") return raw;
1298
1424
  const id = /^\d+$/.test(raw) ? Number(raw) : NaN;
1299
- if (!Number.isSafeInteger(id) || id < 1) throw invalidField("session", "must be a session id, current or none");
1425
+ if (!Number.isSafeInteger(id) || id < 1) throw invalidField("session", "must be a session id, current, active or none");
1300
1426
  return id;
1301
1427
  }
1302
1428
  const MAX_BODY_BYTES = 1048576;
@@ -1356,6 +1482,13 @@ function numberField(body, name) {
1356
1482
  function optionalNumberField(body, name) {
1357
1483
  return field(body, name) === void 0 ? void 0 : numberField(body, name);
1358
1484
  }
1485
+ /** An optional field of a JSON body that is a JSON object. */
1486
+ function optionalObjectField(body, name) {
1487
+ const value = field(body, name);
1488
+ if (value === void 0) return void 0;
1489
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidField(name, "must be an object");
1490
+ return value;
1491
+ }
1359
1492
  /** A required field that is a string or an array of strings. */
1360
1493
  function keysField(body, name) {
1361
1494
  const value = field(body, name);
@@ -1399,26 +1532,133 @@ function configRoutes(router, { config }) {
1399
1532
  sendJson(res, 200, toConfigDto(await config.update(await jsonBody(req))));
1400
1533
  });
1401
1534
  }
1535
+ // src/adapters/in/http/dto/speech.ts
1536
+ function toSpeechEntryDto(entry) {
1537
+ return {
1538
+ seq: entry.seq,
1539
+ kind: entry.kind,
1540
+ text: entry.text,
1541
+ receivedAt: entry.receivedAt.toISOString(),
1542
+ source: entry.source,
1543
+ voice: entry.voice,
1544
+ connectionId: entry.connectionId,
1545
+ sessionId: entry.sessionId
1546
+ };
1547
+ }
1548
+ function toSpeechListDto(page) {
1549
+ return {
1550
+ entries: page.entries.map(toSpeechEntryDto),
1551
+ truncated: page.truncated,
1552
+ hasMore: page.hasMore
1553
+ };
1554
+ }
1555
+ function toLatestMarkerDto(marker) {
1556
+ return { marker: marker && toSpeechEntryDto(marker) };
1557
+ }
1558
+ function toWaitResultDto(result) {
1559
+ return result.status === "matched" ? {
1560
+ matched: true,
1561
+ entry: toSpeechEntryDto(result.entry)
1562
+ } : {
1563
+ matched: false,
1564
+ entries: result.seen.map(toSpeechEntryDto),
1565
+ omitted: result.omitted
1566
+ };
1567
+ }
1568
+ // src/adapters/in/http/dto/input.ts
1569
+ function toInputCaptureDto(result) {
1570
+ return {
1571
+ status: result.status,
1572
+ startSeq: result.startSeq,
1573
+ entries: result.entries.map(toSpeechEntryDto),
1574
+ omitted: result.omitted,
1575
+ truncated: result.truncated
1576
+ };
1577
+ }
1578
+ function toFocusedWindowDto(window) {
1579
+ return {
1580
+ title: window.title,
1581
+ pid: window.pid
1582
+ };
1583
+ }
1402
1584
  // 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 }) => {
1585
+ /** The `capture` object of an input request, `undefined` without one. */
1586
+ function captureField(body) {
1587
+ const capture = optionalObjectField(body, "capture");
1588
+ if (capture === void 0) return void 0;
1589
+ const ms = (name) => {
1590
+ try {
1591
+ return optionalNumberField(capture, name);
1592
+ } catch {
1593
+ throw invalidField(`capture.${name}`, "must be a number");
1594
+ }
1595
+ };
1596
+ return {
1597
+ quietForMs: ms("quietForMs"),
1598
+ firstWithinMs: ms("firstWithinMs"),
1599
+ timeoutMs: ms("timeoutMs"),
1600
+ settleMs: ms("settleMs")
1601
+ };
1602
+ }
1603
+ /**
1604
+ * Without `capture`: sends the input and answers 204. With it: records the speech the input
1605
+ * causes and answers 200 (docs/usage/native-input.md#capturing-the-speech-an-input-causes).
1606
+ */
1607
+ async function answer(res, capture, send, record) {
1608
+ if (capture === void 0) {
1609
+ await send();
1610
+ sendNoContent(res);
1611
+ return;
1612
+ }
1613
+ const controller = new AbortController();
1614
+ res.on("close", () => {
1615
+ if (!res.writableEnded) controller.abort();
1616
+ });
1617
+ let result;
1618
+ try {
1619
+ result = await record(capture, controller.signal);
1620
+ } catch (error) {
1621
+ if (controller.signal.aborted) return;
1622
+ throw error;
1623
+ }
1624
+ sendJson(res, 200, toInputCaptureDto(result));
1625
+ }
1626
+ /** `POST /input/click`, `POST /input/keys`, `POST /input/focus` (docs/usage/http-api.md#endpoints). */
1627
+ function inputRoutes(router, { input, captures, focus }) {
1628
+ router.add("POST", "/input/focus", async ({ req, res }) => {
1629
+ const body = await jsonBody(req);
1630
+ const target = stringField(body, "target");
1631
+ if (target !== "mcp" && target !== "playwright") throw invalidField("target", "must be mcp or playwright");
1632
+ sendJson(res, 200, toFocusedWindowDto(await focus.focus({
1633
+ target,
1634
+ title: optionalStringField(body, "title")
1635
+ })));
1636
+ }).add("POST", "/input/click", async ({ req, res }) => {
1406
1637
  const body = await jsonBody(req);
1407
1638
  const button = optionalStringField(body, "button");
1408
1639
  if (button !== void 0 && button !== "left" && button !== "right" && button !== "middle") throw invalidField("button", "must be left, right or middle");
1409
- await input.click({
1640
+ const mouseButton = button;
1641
+ const request = {
1410
1642
  x: numberField(body, "x"),
1411
1643
  y: numberField(body, "y"),
1412
- button
1413
- });
1414
- sendNoContent(res);
1644
+ button: mouseButton
1645
+ };
1646
+ await answer(res, captureField(body), () => input.click(request), (capture, signal) => captures.click({
1647
+ ...request,
1648
+ capture,
1649
+ signal
1650
+ }));
1415
1651
  }).add("POST", "/input/keys", async ({ req, res }) => {
1416
1652
  const body = await jsonBody(req);
1417
- await input.pressKeys({
1653
+ const request = {
1418
1654
  keys: keysField(body, "keys"),
1419
1655
  delayMs: optionalNumberField(body, "delayMs")
1420
- });
1421
- sendNoContent(res);
1656
+ };
1657
+ await answer(res, captureField(body), () => input.pressKeys(request), (capture, signal) => captures.pressKeys({
1658
+ ...request,
1659
+ capture,
1660
+ signal
1661
+ }));
1422
1662
  });
1423
1663
  }
1424
1664
  // src/adapters/in/http/dto/session.ts
@@ -1472,36 +1712,6 @@ function sessionRoutes(router, { sessions }) {
1472
1712
  sendNoContent(res);
1473
1713
  }).add("GET", "/sessions", ({ res }) => sendJson(res, 200, toSessionListDto(sessions.list())));
1474
1714
  }
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
1715
  // src/adapters/in/http/sse/sse-frames.ts
1506
1716
  /**
1507
1717
  * Frames already built, by the entry or session they show. Every open stream gets the same
@@ -1545,6 +1755,10 @@ function speechRoutes(router, deps) {
1545
1755
  }).add("POST", "/markers", async ({ req, res }) => {
1546
1756
  const label = stringField(await jsonBody(req), "label");
1547
1757
  sendJson(res, 201, toSpeechEntryDto(speech.addMarker(label)));
1758
+ }).add("GET", "/markers/latest", ({ res, url }) => {
1759
+ const label = stringParam(url, "label");
1760
+ if (label === void 0) throw invalidField("label", "is required");
1761
+ sendJson(res, 200, toLatestMarkerDto(speech.latestMarker(label, sessionParam(url))));
1548
1762
  }).add("GET", "/speech/wait", async ({ res, url }) => {
1549
1763
  const controller = new AbortController();
1550
1764
  res.on("close", () => {
@@ -1594,7 +1808,18 @@ function toServiceStatusDto(service) {
1594
1808
  exitCode: service.exitCode
1595
1809
  };
1596
1810
  }
1597
- function toStatusDto({ bridge, tcp, buffer, services, session }) {
1811
+ function toInputAvailabilityDto(availability) {
1812
+ return availability.available ? {
1813
+ available: true,
1814
+ backend: availability.backend,
1815
+ reason: null
1816
+ } : {
1817
+ available: false,
1818
+ backend: null,
1819
+ reason: availability.reason
1820
+ };
1821
+ }
1822
+ function toStatusDto({ bridge, tcp, buffer, services, session, input }) {
1598
1823
  const children = {
1599
1824
  playwright: toServiceStatusDto(services.playwright),
1600
1825
  mcp: toServiceStatusDto(services.mcp)
@@ -1628,6 +1853,10 @@ function toStatusDto({ bridge, tcp, buffer, services, session }) {
1628
1853
  session: {
1629
1854
  current: session.current === null ? null : toSessionDto(session.current),
1630
1855
  count: session.count
1856
+ },
1857
+ input: {
1858
+ native: toInputAvailabilityDto(input.native),
1859
+ focus: toInputAvailabilityDto(input.focus)
1631
1860
  }
1632
1861
  };
1633
1862
  }
@@ -1773,6 +2002,7 @@ var HttpServer = class {
1773
2002
  try {
1774
2003
  const url = parseUrl(req.url);
1775
2004
  path = url.pathname;
2005
+ if (isApiPath(url.pathname)) res.setHeader(API_VERSION_HEADER, API_VERSION);
1776
2006
  const route = this.proxy.match(url.pathname);
1777
2007
  this.checkAccess(req, route !== void 0);
1778
2008
  if (route) this.proxy.forward(route, req, res, url);
@@ -2083,32 +2313,6 @@ var FsConfigStore = class {
2083
2313
  function parseJson(text) {
2084
2314
  return JSON.parse(text.replace(/^\uFEFF/, ""));
2085
2315
  }
2086
- // src/adapters/out/input/disabled-input-injector.ts
2087
- /**
2088
- * The injector when native input can't be loaded (docs/usage/native-input.md#when-input-is-not-available):
2089
- * every call fails with `INPUT_DISABLED`, so the rest of the bridge keeps working.
2090
- */
2091
- var DisabledInputInjector = class {
2092
- reason;
2093
- constructor(reason) {
2094
- this.reason = reason;
2095
- }
2096
- click(_x, _y, _button) {
2097
- return this.fail();
2098
- }
2099
- keyDown() {
2100
- return this.fail();
2101
- }
2102
- keyUp() {
2103
- return this.fail();
2104
- }
2105
- keyTap() {
2106
- return this.fail();
2107
- }
2108
- fail() {
2109
- return Promise.reject(new AppError("INPUT_DISABLED", `Native input is not available: ${this.reason}`));
2110
- }
2111
- };
2112
2316
  // src/adapters/out/memory/in-process-event-bus.ts
2113
2317
  /** Synchronous in-process event bus. A failing listener doesn't stop the others. */
2114
2318
  var InProcessEventBus = class {
@@ -2210,10 +2414,10 @@ var BridgeLifecycleService = class {
2210
2414
  return this.stopping;
2211
2415
  }
2212
2416
  async shutdown(reason) {
2213
- const { state, waits, stopOrder, logger } = this.deps;
2417
+ const { state, pending, stopOrder, logger } = this.deps;
2214
2418
  state.setState("stopping");
2215
2419
  logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
2216
- waits.shutdown();
2420
+ for (const part of pending) part.shutdown();
2217
2421
  const errors = [];
2218
2422
  for (const part of stopOrder) try {
2219
2423
  await part.stop();
@@ -2415,73 +2619,362 @@ var ConfigService = class {
2415
2619
  }
2416
2620
  }
2417
2621
  };
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;
2622
+ // src/application/ports/in/capture-input.ts
2623
+ /** Defaults and ranges of the capture options, in milliseconds. */
2624
+ const CAPTURE_LIMITS = API_LIMITS.capture;
2625
+ // src/application/shared/abort.ts
2626
+ /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
2627
+ function abortReason(signal) {
2628
+ const reason = signal.reason;
2629
+ return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
2468
2630
  }
2631
+ /** What pending requests (waits, captures) end with when the bridge shuts down. */
2632
+ const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
2633
+ // src/domain/seq-cursor.ts
2469
2634
  /**
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.
2473
- */
2474
- 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`);
2635
+ * A follower's position in the speech log. `SpeechLog` gives every entry the next `seq`, strictly
2636
+ * rising, so an entry at or below the position was already delivered. A replay from the log and
2637
+ * the live events may therefore overlap in any timing without a duplicate.
2638
+ */
2639
+ var SeqCursor = class {
2640
+ #position;
2641
+ /** `position`: the last `seq` already delivered. `-Infinity` accepts every entry. */
2642
+ constructor(position) {
2643
+ this.#position = position;
2644
+ }
2645
+ get position() {
2646
+ return this.#position;
2647
+ }
2648
+ /** `true`, and moves on to it, if the entry comes after the position; `false` if it was delivered. */
2649
+ advance(entry) {
2650
+ if (entry.seq <= this.#position) return false;
2651
+ this.#position = entry.seq;
2652
+ return true;
2653
+ }
2654
+ };
2655
+ /**
2656
+ * Hands `listener` the log's entries after `since`, then the new events, with nothing missed or
2657
+ * repeated in between (`SpeechUseCases.watch`, the wait). With `sessionId`, only that session's
2658
+ * entries (`null`: those outside sessions); `session` events always come, and a `clear` unless it only cleared another scope. Returns a
2659
+ * function that stops it; calling it again does nothing.
2660
+ *
2661
+ * Without `since` (`null`) no entry is replayed; the first event is `position`, the log's
2662
+ * `headSeq`, so a stream that drops before its first entry still has a cursor to reconnect with.
2663
+ * With `staleSince: 'replay'`, a `since` above `headSeq` (a cursor from another run) is a gap,
2664
+ * not a position to wait for: `truncated`, then the whole buffer. Without it, such a `since`
2665
+ * waits for entries above it (what the wait means by `since`).
2666
+ */
2667
+ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, listener, { pace, onError } = {}) {
2668
+ const { log, events } = deps;
2669
+ let stale = staleSince === "replay" && requested !== null && requested > log.headSeq;
2670
+ const since = stale ? 0 : requested;
2671
+ const cursor = new SeqCursor(since ?? Number.NEGATIVE_INFINITY);
2672
+ let replaying = since !== null;
2673
+ let stopped = false;
2674
+ const unsubscribe = events.subscribe((event) => {
2675
+ if (event.type === "clear" && event.sessionId !== void 0 && sessionId !== void 0) {
2676
+ if (event.sessionId !== sessionId) return;
2677
+ }
2678
+ if (event.type !== "entry") return listener(event);
2679
+ if (replaying || !cursor.advance(event.entry)) return;
2680
+ if (sessionId === void 0 || event.entry.sessionId === sessionId) listener(event);
2681
+ });
2682
+ const stop = () => {
2683
+ stopped = true;
2684
+ unsubscribe();
2685
+ };
2686
+ if (since === null) {
2687
+ listener({
2688
+ type: "position",
2689
+ seq: log.headSeq
2690
+ });
2691
+ return stop;
2692
+ }
2693
+ /** Replays from the cursor until `pace` pauses it (its promise) or it has caught up. */
2694
+ const step = () => {
2695
+ for (;;) {
2696
+ const { entries, truncated, hasMore } = log.page(cursor.position, 500, sessionId);
2697
+ if (truncated || stale) listener({ type: "truncated" });
2698
+ stale = false;
2699
+ for (const entry of entries) {
2700
+ if (!cursor.advance(entry)) continue;
2701
+ listener({
2702
+ type: "entry",
2703
+ entry
2704
+ });
2705
+ const paused = pace?.();
2706
+ if (paused) return paused;
2707
+ }
2708
+ if (!hasMore) {
2709
+ replaying = false;
2710
+ return;
2711
+ }
2712
+ }
2713
+ };
2714
+ const resume = async (paused) => {
2715
+ for (let next = paused; next;) {
2716
+ await next;
2717
+ if (stopped) return;
2718
+ next = step();
2719
+ }
2720
+ };
2721
+ let paused;
2722
+ try {
2723
+ paused = step();
2724
+ } catch (error) {
2725
+ stop();
2726
+ throw error;
2727
+ }
2728
+ if (paused) resume(paused).catch((error) => {
2729
+ stop();
2730
+ onError?.(error);
2731
+ });
2732
+ return stop;
2733
+ }
2734
+ // src/application/shared/int-option.ts
2735
+ /**
2736
+ * A numeric use-case option: `fallback` if it is missing, otherwise checked to be an integer
2737
+ * from `min` to `max` (`INVALID_REQUEST` for `field` if not).
2738
+ */
2739
+ function intOption(field, value, { fallback, min, max }) {
2740
+ if (value === void 0) return fallback;
2741
+ if (!Number.isInteger(value) || value < min || value > max) throw invalidField(field, `must be an integer from ${min} to ${max}`);
2742
+ return value;
2743
+ }
2744
+ // src/application/services/input-capture-service.ts
2745
+ function parseOptions(options) {
2746
+ const { quietForMs, firstWithinMs, timeoutMs, settleMs } = CAPTURE_LIMITS;
2747
+ const ms = (field, limits) => intOption(`capture.${field}`, options[field], {
2748
+ fallback: limits.default,
2749
+ min: limits.min ?? 0,
2750
+ max: limits.max
2751
+ });
2480
2752
  return {
2481
- modifiers: names,
2482
- key
2753
+ quietForMs: ms("quietForMs", quietForMs),
2754
+ firstWithinMs: ms("firstWithinMs", firstWithinMs),
2755
+ timeoutMs: ms("timeoutMs", timeoutMs),
2756
+ settleMs: ms("settleMs", settleMs)
2483
2757
  };
2484
2758
  }
2759
+ const toError = (error) => error instanceof Error ? error : new Error(String(error));
2760
+ /**
2761
+ * Native input that records the speech it causes (docs/usage/native-input.md#capturing-the-speech-an-input-causes).
2762
+ * The start `seq` is read in the input queue right before the input is sent, so no other input
2763
+ * and no speech that came before it gets into the capture; silence is timed from the entries'
2764
+ * `receivedAt`, on the bridge's clock, not from when a client got them.
2765
+ */
2766
+ var InputCaptureService = class {
2767
+ deps;
2768
+ pending = /* @__PURE__ */ new Set();
2769
+ closed = false;
2770
+ constructor(deps) {
2771
+ this.deps = deps;
2772
+ }
2773
+ click({ capture, signal, ...request }) {
2774
+ return this.run(capture, signal, (hooks) => this.deps.input.click(request, hooks));
2775
+ }
2776
+ pressKeys({ capture, signal, ...request }) {
2777
+ return this.run(capture, signal, (hooks) => this.deps.input.pressKeys(request, hooks));
2778
+ }
2779
+ /**
2780
+ * Rejects all pending captures, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
2781
+ * lifecycle port: only the composition root calls it.
2782
+ */
2783
+ shutdown() {
2784
+ this.closed = true;
2785
+ for (const stop of [...this.pending]) stop.abort(shuttingDown());
2786
+ }
2787
+ async run(capture, signal, send) {
2788
+ if (this.closed) throw shuttingDown();
2789
+ const options = parseOptions(capture);
2790
+ if (signal?.aborted) throw abortReason(signal);
2791
+ const stop = new AbortController();
2792
+ const onAbort = () => stop.abort(abortReason(signal));
2793
+ signal?.addEventListener("abort", onAbort, { once: true });
2794
+ this.pending.add(stop);
2795
+ try {
2796
+ let startSeq = 0;
2797
+ await send({ beforeInject: async () => {
2798
+ if (options.settleMs > 0) await this.settle(options, stop.signal);
2799
+ if (stop.signal.aborted) throw abortReason(stop.signal);
2800
+ startSeq = this.deps.log.headSeq;
2801
+ } });
2802
+ return await this.record(startSeq, options, stop.signal);
2803
+ } finally {
2804
+ signal?.removeEventListener("abort", onAbort);
2805
+ this.pending.delete(stop);
2806
+ }
2807
+ }
2808
+ /**
2809
+ * Waits until the newest speech is `settleMs` old, at most `timeoutMs`: after that the input
2810
+ * is sent anyway, and the trailing speech shows in the capture.
2811
+ */
2812
+ async settle({ settleMs, timeoutMs }, signal) {
2813
+ const { log } = this.deps;
2814
+ const start = this.now();
2815
+ const newest = log.page(log.headSeq - 1, 1).entries[0];
2816
+ let last = newest?.kind === "speech" ? newest.receivedAt.getTime() : void 0;
2817
+ if (last === void 0 || last + settleMs <= start) return;
2818
+ await this.follow(null, signal, () => Math.min(last + settleMs, start + timeoutMs), (event) => {
2819
+ if (event.type === "entry" && event.entry.kind === "speech") last = event.entry.receivedAt.getTime();
2820
+ });
2821
+ }
2822
+ /** Follows the speech after `startSeq` until it paused, none came, or the time ran out. */
2823
+ async record(startSeq, { quietForMs, firstWithinMs, timeoutMs }, signal) {
2824
+ const sentAt = this.now();
2825
+ const end = sentAt + timeoutMs;
2826
+ const entries = [];
2827
+ let omitted = 0;
2828
+ let truncated = false;
2829
+ let last;
2830
+ const deadline = () => Math.min(last === void 0 ? sentAt + firstWithinMs : last + quietForMs, end);
2831
+ await this.follow(startSeq, signal, deadline, (event) => {
2832
+ if (event.type === "truncated") truncated = true;
2833
+ if (event.type !== "entry" || event.entry.kind !== "speech") return;
2834
+ last = event.entry.receivedAt.getTime();
2835
+ if (entries.length < CAPTURE_LIMITS.entries) entries.push(event.entry);
2836
+ else omitted++;
2837
+ });
2838
+ return {
2839
+ status: last === void 0 ? "no-speech" : last + quietForMs <= end ? "silent" : "timeout",
2840
+ startSeq,
2841
+ entries,
2842
+ omitted,
2843
+ truncated
2844
+ };
2845
+ }
2846
+ /**
2847
+ * Hands `onEvent` the log's events after `since` (`null`: only new ones) until `deadline()`
2848
+ * (ms, read again after each speech entry) has passed. Rejects when `signal` aborts.
2849
+ */
2850
+ follow(since, signal, deadline, onEvent) {
2851
+ if (signal.aborted) return Promise.reject(abortReason(signal));
2852
+ return new Promise((resolve, reject) => {
2853
+ let done = false;
2854
+ let timer;
2855
+ let stopFollow;
2856
+ const finish = () => {
2857
+ done = true;
2858
+ stopFollow?.();
2859
+ timer?.abort();
2860
+ signal.removeEventListener("abort", onAbort);
2861
+ };
2862
+ const fail = (error) => {
2863
+ if (done) return;
2864
+ finish();
2865
+ reject(error);
2866
+ };
2867
+ const onAbort = () => fail(abortReason(signal));
2868
+ const arm = () => {
2869
+ timer?.abort();
2870
+ const own = new AbortController();
2871
+ timer = own;
2872
+ this.deps.clock.sleep(Math.max(0, deadline() - this.now()), own.signal).then(() => {
2873
+ if (done || timer !== own) return;
2874
+ finish();
2875
+ resolve();
2876
+ }, () => {});
2877
+ };
2878
+ signal.addEventListener("abort", onAbort, { once: true });
2879
+ arm();
2880
+ try {
2881
+ stopFollow = followLog(this.deps, {
2882
+ since,
2883
+ sessionId: void 0
2884
+ }, (event) => {
2885
+ if (done) return;
2886
+ onEvent(event);
2887
+ if (event.type === "entry" && event.entry.kind === "speech") arm();
2888
+ }, {
2889
+ pace: this.deps.pace?.(),
2890
+ onError: (error) => fail(toError(error))
2891
+ });
2892
+ if (done) stopFollow();
2893
+ } catch (error) {
2894
+ fail(toError(error));
2895
+ }
2896
+ });
2897
+ }
2898
+ now() {
2899
+ return this.deps.clock.now().getTime();
2900
+ }
2901
+ };
2902
+ // src/application/services/window-focus-service.ts
2903
+ /** How long a `title` may take to show up in the window title, and how often it is looked for. */
2904
+ const TITLE_WAIT = {
2905
+ timeoutMs: 2e3,
2906
+ pollMs: 50
2907
+ };
2908
+ const TARGETS = {
2909
+ mcp: {
2910
+ service: "mcp",
2911
+ name: "Playwright MCP"
2912
+ },
2913
+ playwright: {
2914
+ service: "playwright",
2915
+ name: "the Playwright server"
2916
+ }
2917
+ };
2918
+ /**
2919
+ * Brings a window of a browser the bridge started to the front
2920
+ * (docs/usage/native-input.md#bringing-the-browser-to-the-front): the front-most visible
2921
+ * top-level window of the target service's process tree, or with `title` the front-most one
2922
+ * whose title contains it.
2923
+ */
2924
+ var WindowFocusService = class {
2925
+ deps;
2926
+ constructor(deps) {
2927
+ this.deps = deps;
2928
+ }
2929
+ async focus({ target, title }) {
2930
+ const known = Object.hasOwn(TARGETS, target) ? TARGETS[target] : void 0;
2931
+ if (!known) throw invalidField("target", "must be mcp or playwright");
2932
+ if (title !== void 0 && (title === "" || title.length > API_LIMITS.input.focusTitleLength)) throw invalidField("title", `must be 1 to ${API_LIMITS.input.focusTitleLength} characters`);
2933
+ const pid = this.deps.services[known.service].pid();
2934
+ if (pid === null) throw new AppError("NOT_FOUND", `${capitalize(known.name)} is not running`);
2935
+ return this.deps.queue.exclusive(async () => {
2936
+ const window = await this.find(pid, title);
2937
+ if (!window) throw notFound(known, title);
2938
+ 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?)`);
2939
+ this.deps.logger.info(`focus ${target}: "${window.title}" (pid ${window.pid})`);
2940
+ return {
2941
+ title: window.title,
2942
+ pid: window.pid
2943
+ };
2944
+ });
2945
+ }
2946
+ /**
2947
+ * The front-most window of the tree below `pid` with a title (containing `title`, if given).
2948
+ * The browser sets its window title a moment after `document.title` changes, so a `title` is
2949
+ * looked for again until {@link TITLE_WAIT} runs out.
2950
+ */
2951
+ async find(pid, title) {
2952
+ const { windows, clock } = this.deps;
2953
+ const tries = title === void 0 ? 1 : TITLE_WAIT.timeoutMs / TITLE_WAIT.pollMs + 1;
2954
+ for (let attempt = 0; attempt < tries; attempt++) {
2955
+ if (attempt > 0) await clock.sleep(TITLE_WAIT.pollMs);
2956
+ const tree = await windows.processTree(pid);
2957
+ const found = (await windows.topLevelWindows()).find((window) => tree.has(window.pid) && window.title !== "" && (title === void 0 || window.title.includes(title)));
2958
+ if (found) return found;
2959
+ }
2960
+ }
2961
+ };
2962
+ function notFound(target, title) {
2963
+ 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?)`);
2964
+ return new AppError("NOT_FOUND", `${capitalize(target.name)} has no browser window yet (Playwright MCP opens its browser on the first browser tool call)`);
2965
+ }
2966
+ const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
2967
+ // src/domain/key-chord.ts
2968
+ /**
2969
+ * Parses `Insert+T` or `Control+Shift+Home` (docs/usage/native-input.md#key-names). Throws
2970
+ * `INVALID_REQUEST` for the field `keys` if the chord is invalid. The domain knows no names of the
2971
+ * input library: the injector maps them.
2972
+ */
2973
+ function parseKeyChord(chord) {
2974
+ const result = parseKeyChord$1(chord);
2975
+ if (!result.ok) throw invalidField("keys", result.message);
2976
+ return result.chord;
2977
+ }
2485
2978
  // src/application/services/native-input-service.ts
2486
2979
  const { coordinate, delayMs, maxKeys } = API_LIMITS.input;
2487
2980
  const BUTTONS = [
@@ -2509,19 +3002,21 @@ var NativeInputService = class {
2509
3002
  constructor(deps) {
2510
3003
  this.deps = deps;
2511
3004
  }
2512
- async click({ x, y, button = "left" }) {
3005
+ async click({ x, y, button = "left" }, hooks = {}) {
2513
3006
  checkCoordinate("x", x);
2514
3007
  checkCoordinate("y", y);
2515
3008
  if (!BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
2516
3009
  await this.enqueue(async () => {
3010
+ await hooks.beforeInject?.();
2517
3011
  await this.deps.injector.click(x, y, button);
2518
3012
  this.deps.logger.info(`click ${button} at ${x},${y}`);
2519
3013
  });
2520
3014
  }
2521
- async pressKeys({ keys, delayMs: delay = delayMs.default }) {
3015
+ async pressKeys({ keys, delayMs: delay = delayMs.default }, hooks = {}) {
2522
3016
  const chords = parseKeys(keys);
2523
3017
  if (!Number.isInteger(delay) || delay < 0 || delay > delayMs.max) throw invalidField("delayMs", `must be an integer from 0 to ${delayMs.max}`);
2524
3018
  await this.enqueue(async () => {
3019
+ await hooks.beforeInject?.();
2525
3020
  for (const [index, chord] of chords.entries()) {
2526
3021
  if (index > 0 && delay > 0) await this.deps.clock.sleep(delay);
2527
3022
  await this.press(chord);
@@ -2542,6 +3037,9 @@ var NativeInputService = class {
2542
3037
  for (const modifier of held.reverse()) await injector.keyUp(modifier);
2543
3038
  }
2544
3039
  }
3040
+ exclusive(task) {
3041
+ return this.enqueue(task);
3042
+ }
2545
3043
  /** Runs `task` after the earlier ones; a failed task doesn't stop the later ones. */
2546
3044
  enqueue(task) {
2547
3045
  const run = this.queue.then(task);
@@ -2637,117 +3135,6 @@ function clientLabel(client) {
2637
3135
  // src/application/ports/in/speech.ts
2638
3136
  /** Page size of `list`: the default and the most a caller may ask for. */
2639
3137
  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
3138
  // src/application/services/speech-service.ts
2752
3139
  const MAX_MARKER_LENGTH = API_LIMITS.markerLength;
2753
3140
  /**
@@ -2792,7 +3179,8 @@ var SpeechService = class {
2792
3179
  }, listener, options);
2793
3180
  }
2794
3181
  /** Wipes the buffer and the ended sessions, or one scope. The current session stays current. */
2795
- clear(session) {
3182
+ clear(filter) {
3183
+ const session = filter === "active" ? this.deps.log.resolveFilter(filter) ?? void 0 : filter;
2796
3184
  if (session === void 0) {
2797
3185
  this.deps.log.clear();
2798
3186
  this.deps.events.publish({ type: "clear" });
@@ -2804,9 +3192,7 @@ var SpeechService = class {
2804
3192
  });
2805
3193
  }
2806
3194
  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`);
3195
+ const text = markerLabel(label);
2810
3196
  return this.add({
2811
3197
  kind: "marker",
2812
3198
  text,
@@ -2815,6 +3201,11 @@ var SpeechService = class {
2815
3201
  connectionId: null
2816
3202
  });
2817
3203
  }
3204
+ latestMarker(label, session) {
3205
+ const text = markerLabel(label);
3206
+ const sessionId = this.deps.log.resolveFilter(session);
3207
+ return this.deps.log.latestMarker(text, sessionId) ?? null;
3208
+ }
2818
3209
  add(entry) {
2819
3210
  const stored = this.deps.log.append({
2820
3211
  ...entry,
@@ -2827,6 +3218,13 @@ var SpeechService = class {
2827
3218
  return stored;
2828
3219
  }
2829
3220
  };
3221
+ /** A marker label: trimmed, not empty, at most `MAX_MARKER_LENGTH` characters. */
3222
+ function markerLabel(label) {
3223
+ const text = label.trim();
3224
+ if (text === "") throw invalidField("label", "must not be empty");
3225
+ if (text.length > MAX_MARKER_LENGTH) throw invalidField("label", `must be at most ${MAX_MARKER_LENGTH} characters`);
3226
+ return text;
3227
+ }
2830
3228
  // src/application/services/status-service.ts
2831
3229
  /**
2832
3230
  * `GET /api/v1/status`. The composition root moves the state from `starting` to `ready` through
@@ -2842,7 +3240,7 @@ var StatusService = class {
2842
3240
  this.state = state;
2843
3241
  }
2844
3242
  status() {
2845
- const { capture, log, supervisors, config, version, apiVersion, startedAt } = this.deps;
3243
+ const { capture, log, supervisors, config, version, apiVersion, startedAt, injector, windows } = this.deps;
2846
3244
  const { listener, connections } = capture.captureStatus();
2847
3245
  const { tcp } = config();
2848
3246
  const listed = log.sessions();
@@ -2866,6 +3264,10 @@ var StatusService = class {
2866
3264
  session: {
2867
3265
  current: listed.find((session) => session.id === currentId) ?? null,
2868
3266
  count: listed.length
3267
+ },
3268
+ input: {
3269
+ native: injector.availability,
3270
+ focus: windows.availability
2869
3271
  }
2870
3272
  };
2871
3273
  }
@@ -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
@@ -3135,10 +3532,41 @@ function readySummary(input) {
3135
3532
  else value = `${state.toUpperCase()}, see the log above (${version})`;
3136
3533
  rows.push([SERVICE_TITLES[name], value]);
3137
3534
  }
3138
- rows.push(["native input", input.nativeInput ?? "off"]);
3535
+ rows.push(["native input", input.nativeInput.available ? input.nativeInput.backend : "off"]);
3139
3536
  const width = Math.max(...rows.map(([label]) => label.length));
3140
3537
  return [`ready in ${(input.tookMs / 1e3).toFixed(1)}s`, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
3141
3538
  }
3539
+ // src/adapters/out/input/disabled-input-injector.ts
3540
+ /**
3541
+ * The injector when native input can't be loaded (docs/usage/native-input.md#when-input-is-not-available):
3542
+ * every call fails with `INPUT_DISABLED`, so the rest of the bridge keeps working.
3543
+ */
3544
+ var DisabledInputInjector = class {
3545
+ reason;
3546
+ availability;
3547
+ constructor(reason) {
3548
+ this.reason = reason;
3549
+ this.availability = {
3550
+ available: false,
3551
+ reason
3552
+ };
3553
+ }
3554
+ click(_x, _y, _button) {
3555
+ return this.fail();
3556
+ }
3557
+ keyDown() {
3558
+ return this.fail();
3559
+ }
3560
+ keyUp() {
3561
+ return this.fail();
3562
+ }
3563
+ keyTap() {
3564
+ return this.fail();
3565
+ }
3566
+ fail() {
3567
+ return Promise.reject(new AppError("INPUT_DISABLED", `Native input is not available: ${this.reason}`));
3568
+ }
3569
+ };
3142
3570
  // src/adapters/out/robotjs/robotjs-input-injector.ts
3143
3571
  /** Domain key names that robotjs spells differently. */
3144
3572
  const ROBOT_KEYS = { win: "command" };
@@ -3150,6 +3578,10 @@ const robotKey = (key) => ROBOT_KEYS[key] ?? key;
3150
3578
  */
3151
3579
  var RobotjsInputInjector = class {
3152
3580
  robot;
3581
+ availability = {
3582
+ available: true,
3583
+ backend: "robotjs"
3584
+ };
3153
3585
  constructor(robot) {
3154
3586
  this.robot = robot;
3155
3587
  }
@@ -3195,6 +3627,235 @@ async function createInputInjector(logger) {
3195
3627
  return new DisabledInputInjector(reason);
3196
3628
  }
3197
3629
  }
3630
+ // src/adapters/out/input/disabled-window-system.ts
3631
+ /**
3632
+ * The window system where windows can't be managed (not Windows, or `koffi` could not be loaded):
3633
+ * every call fails with `INPUT_DISABLED`, so the rest of the bridge keeps working.
3634
+ */
3635
+ var DisabledWindowSystem = class {
3636
+ reason;
3637
+ availability;
3638
+ constructor(reason) {
3639
+ this.reason = reason;
3640
+ this.availability = {
3641
+ available: false,
3642
+ reason
3643
+ };
3644
+ }
3645
+ processTree(_rootPid) {
3646
+ return this.fail();
3647
+ }
3648
+ topLevelWindows() {
3649
+ return this.fail();
3650
+ }
3651
+ bringToFront(_window) {
3652
+ return this.fail();
3653
+ }
3654
+ fail() {
3655
+ return Promise.reject(new AppError("INPUT_DISABLED", `Windows can't be brought to the front: ${this.reason}`));
3656
+ }
3657
+ };
3658
+ // src/adapters/out/win32/win32-bindings.ts
3659
+ const TH32CS_SNAPPROCESS = 2;
3660
+ const INVALID_HANDLE_VALUE = -1;
3661
+ const GW_OWNER = 4;
3662
+ const SW_RESTORE = 9;
3663
+ const VK_MENU = 18;
3664
+ const KEYEVENTF_KEYUP = 2;
3665
+ /** Characters read of a window title or class name. */
3666
+ const TEXT_LENGTH = 512;
3667
+ /**
3668
+ * Binds the {@link Win32} calls with koffi (Windows only). Handles are `intptr_t` numbers, so they
3669
+ * can be compared and handed back as they are. Only the native calls live here: the logic is in
3670
+ * `Win32WindowSystem`, which the unit tests cover with a fake. Verified by hand on the Windows VM.
3671
+ */
3672
+ function bindWin32(koffi) {
3673
+ const kernel32 = koffi.load("kernel32.dll");
3674
+ const user32 = koffi.load("user32.dll");
3675
+ const ProcessEntry = koffi.struct("PROCESSENTRY32W", {
3676
+ dwSize: "uint32_t",
3677
+ cntUsage: "uint32_t",
3678
+ th32ProcessID: "uint32_t",
3679
+ th32DefaultHeapID: "uintptr_t",
3680
+ th32ModuleID: "uint32_t",
3681
+ cntThreads: "uint32_t",
3682
+ th32ParentProcessID: "uint32_t",
3683
+ pcPriClassBase: "int32_t",
3684
+ dwFlags: "uint32_t",
3685
+ szExeFile: koffi.array("uint16_t", 260)
3686
+ });
3687
+ const entrySize = koffi.sizeof(ProcessEntry);
3688
+ const pidAt = koffi.offsetof(ProcessEntry, "th32ProcessID");
3689
+ const parentAt = koffi.offsetof(ProcessEntry, "th32ParentProcessID");
3690
+ const CreateToolhelp32Snapshot = kernel32.func("intptr_t __stdcall CreateToolhelp32Snapshot(uint32_t dwFlags, uint32_t th32ProcessID)");
3691
+ const Process32FirstW = kernel32.func("int __stdcall Process32FirstW(intptr_t hSnapshot, _Inout_ void *lppe)");
3692
+ const Process32NextW = kernel32.func("int __stdcall Process32NextW(intptr_t hSnapshot, _Inout_ void *lppe)");
3693
+ const CloseHandle = kernel32.func("int __stdcall CloseHandle(intptr_t hObject)");
3694
+ const GetCurrentThreadId = kernel32.func("uint32_t __stdcall GetCurrentThreadId()");
3695
+ koffi.proto("int __stdcall EnumWindowsProc(intptr_t hwnd, intptr_t lParam)");
3696
+ const EnumWindows = user32.func("int __stdcall EnumWindows(EnumWindowsProc *lpEnumFunc, intptr_t lParam)");
3697
+ const GetWindowThreadProcessId = user32.func("uint32_t __stdcall GetWindowThreadProcessId(intptr_t hWnd, _Out_ uint32_t *lpdwProcessId)");
3698
+ const IsWindowVisible = user32.func("int __stdcall IsWindowVisible(intptr_t hWnd)");
3699
+ const GetWindow = user32.func("intptr_t __stdcall GetWindow(intptr_t hWnd, uint32_t uCmd)");
3700
+ const GetWindowTextW = user32.func("int __stdcall GetWindowTextW(intptr_t hWnd, _Out_ void *lpString, int nMaxCount)");
3701
+ const GetClassNameW = user32.func("int __stdcall GetClassNameW(intptr_t hWnd, _Out_ void *lpClassName, int nMaxCount)");
3702
+ const IsIconic = user32.func("int __stdcall IsIconic(intptr_t hWnd)");
3703
+ const ShowWindow = user32.func("int __stdcall ShowWindow(intptr_t hWnd, int nCmdShow)");
3704
+ const keybd_event = user32.func("void __stdcall keybd_event(uint8_t bVk, uint8_t bScan, uint32_t dwFlags, uintptr_t dwExtraInfo)");
3705
+ const SetForegroundWindow = user32.func("int __stdcall SetForegroundWindow(intptr_t hWnd)");
3706
+ const BringWindowToTop = user32.func("int __stdcall BringWindowToTop(intptr_t hWnd)");
3707
+ const GetForegroundWindow = user32.func("intptr_t __stdcall GetForegroundWindow()");
3708
+ const AttachThreadInput = user32.func("int __stdcall AttachThreadInput(uint32_t idAttach, uint32_t idAttachTo, int fAttach)");
3709
+ const text = (read, hwnd) => {
3710
+ const buffer = Buffer.alloc(TEXT_LENGTH * 2);
3711
+ const length = Number(read(hwnd, buffer, TEXT_LENGTH));
3712
+ return buffer.toString("utf16le", 0, Math.max(0, length) * 2);
3713
+ };
3714
+ return {
3715
+ processes() {
3716
+ const snapshot = Number(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
3717
+ if (snapshot === INVALID_HANDLE_VALUE) throw new Error("CreateToolhelp32Snapshot failed");
3718
+ try {
3719
+ const entry = Buffer.alloc(entrySize);
3720
+ entry.writeUInt32LE(entrySize, 0);
3721
+ const list = [];
3722
+ for (let more = Process32FirstW(snapshot, entry) !== 0; more; more = Process32NextW(snapshot, entry) !== 0) list.push({
3723
+ pid: entry.readUInt32LE(pidAt),
3724
+ parentPid: entry.readUInt32LE(parentAt)
3725
+ });
3726
+ return list;
3727
+ } finally {
3728
+ CloseHandle(snapshot);
3729
+ }
3730
+ },
3731
+ topLevelWindows() {
3732
+ const list = [];
3733
+ EnumWindows((hwnd) => {
3734
+ list.push(Number(hwnd));
3735
+ return 1;
3736
+ }, 0);
3737
+ return list;
3738
+ },
3739
+ owner(hwnd) {
3740
+ const pid = [0];
3741
+ const thread = Number(GetWindowThreadProcessId(hwnd, pid));
3742
+ return {
3743
+ pid: pid[0],
3744
+ thread
3745
+ };
3746
+ },
3747
+ isVisible: (hwnd) => IsWindowVisible(hwnd) !== 0,
3748
+ ownerWindow: (hwnd) => Number(GetWindow(hwnd, GW_OWNER)),
3749
+ title: (hwnd) => text(GetWindowTextW, hwnd),
3750
+ className: (hwnd) => text(GetClassNameW, hwnd),
3751
+ isMinimized: (hwnd) => IsIconic(hwnd) !== 0,
3752
+ restore: (hwnd) => void ShowWindow(hwnd, SW_RESTORE),
3753
+ tapAlt() {
3754
+ keybd_event(VK_MENU, 0, 0, 0);
3755
+ keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);
3756
+ },
3757
+ setForeground: (hwnd) => SetForegroundWindow(hwnd) !== 0,
3758
+ bringToTop: (hwnd) => void BringWindowToTop(hwnd),
3759
+ foreground: () => Number(GetForegroundWindow()),
3760
+ currentThread: () => Number(GetCurrentThreadId()),
3761
+ attachInput: (thread, toThread, attach) => AttachThreadInput(thread, toThread, attach ? 1 : 0) !== 0
3762
+ };
3763
+ }
3764
+ // src/adapters/out/win32/win32-window-system.ts
3765
+ /**
3766
+ * {@link WindowSystem} on Win32 (docs/usage/native-input.md#bringing-the-browser-to-the-front).
3767
+ * Windows lets a background process take the foreground only in some cases, so `bringToFront`
3768
+ * first taps Alt (the bridge is then the process that sent the last input, which Windows
3769
+ * allows), and if that wasn't enough, tries once more attached to the foreground window's input
3770
+ * thread.
3771
+ */
3772
+ var Win32WindowSystem = class {
3773
+ win32;
3774
+ availability = {
3775
+ available: true,
3776
+ backend: "koffi"
3777
+ };
3778
+ constructor(win32) {
3779
+ this.win32 = win32;
3780
+ }
3781
+ processTree(rootPid) {
3782
+ const children = /* @__PURE__ */ new Map();
3783
+ for (const { pid, parentPid } of this.win32.processes()) {
3784
+ if (pid === parentPid) continue;
3785
+ const siblings = children.get(parentPid) ?? [];
3786
+ siblings.push(pid);
3787
+ children.set(parentPid, siblings);
3788
+ }
3789
+ const tree = /* @__PURE__ */ new Set([rootPid]);
3790
+ const open = [rootPid];
3791
+ for (let pid = open.pop(); pid !== void 0; pid = open.pop()) for (const child of children.get(pid) ?? []) {
3792
+ if (tree.has(child)) continue;
3793
+ tree.add(child);
3794
+ open.push(child);
3795
+ }
3796
+ return Promise.resolve(tree);
3797
+ }
3798
+ topLevelWindows() {
3799
+ const { win32 } = this;
3800
+ const windows = [];
3801
+ for (const hwnd of win32.topLevelWindows()) {
3802
+ if (!win32.isVisible(hwnd) || win32.ownerWindow(hwnd) !== 0) continue;
3803
+ windows.push({
3804
+ handle: hwnd,
3805
+ pid: win32.owner(hwnd).pid,
3806
+ title: win32.title(hwnd),
3807
+ className: win32.className(hwnd)
3808
+ });
3809
+ }
3810
+ return Promise.resolve(windows);
3811
+ }
3812
+ bringToFront(window) {
3813
+ const { win32 } = this;
3814
+ const hwnd = window.handle;
3815
+ if (win32.isMinimized(hwnd)) win32.restore(hwnd);
3816
+ win32.tapAlt();
3817
+ win32.setForeground(hwnd);
3818
+ win32.bringToTop(hwnd);
3819
+ if (win32.foreground() !== hwnd) this.attachedToForeground(hwnd);
3820
+ return Promise.resolve(win32.foreground() === hwnd);
3821
+ }
3822
+ /** Brings `hwnd` forward while attached to the input thread of the current foreground window. */
3823
+ attachedToForeground(hwnd) {
3824
+ const { win32 } = this;
3825
+ const current = win32.foreground();
3826
+ const own = win32.currentThread();
3827
+ const theirs = current === 0 ? 0 : win32.owner(current).thread;
3828
+ const attached = theirs !== 0 && theirs !== own && win32.attachInput(own, theirs, true);
3829
+ try {
3830
+ win32.setForeground(hwnd);
3831
+ win32.bringToTop(hwnd);
3832
+ } finally {
3833
+ if (attached) win32.attachInput(own, theirs, false);
3834
+ }
3835
+ }
3836
+ };
3837
+ // src/composition/window-system.ts
3838
+ /**
3839
+ * Loads `koffi`, an optional dependency, and binds the Win32 calls that bring a window to the
3840
+ * front. Not on Windows, or when it can't be loaded, the bridge keeps running with a window
3841
+ * system that answers `INPUT_DISABLED` (docs/usage/native-input.md#bringing-the-browser-to-the-front).
3842
+ */
3843
+ async function createWindowSystem(logger) {
3844
+ if (process.platform !== "win32") {
3845
+ logger.debug("bringing windows to the front is off: only on Windows");
3846
+ return new DisabledWindowSystem("only on Windows");
3847
+ }
3848
+ try {
3849
+ const module = await import("koffi");
3850
+ const windows = new Win32WindowSystem(bindWin32(module.default ?? module));
3851
+ logger.info("bringing windows to the front is available (koffi)");
3852
+ return windows;
3853
+ } catch (error) {
3854
+ const reason = `koffi could not be loaded (${error instanceof Error ? error.message : String(error)})`;
3855
+ logger.warn(`bringing windows to the front is off: ${reason}`);
3856
+ return new DisabledWindowSystem(reason);
3857
+ }
3858
+ }
3198
3859
  // src/adapters/out/log/format.ts
3199
3860
  const ESC = "\x1B[";
3200
3861
  const RESET = `${ESC}0m`;
@@ -3681,6 +4342,9 @@ var ChildProcessSupervisor = class {
3681
4342
  this.options = options;
3682
4343
  this.settings = options.settings;
3683
4344
  }
4345
+ pid() {
4346
+ return this.state === "running" ? this.child?.pid ?? null : null;
4347
+ }
3684
4348
  status() {
3685
4349
  const { version, port } = this.active ?? this.resolved();
3686
4350
  return {
@@ -4142,6 +4806,12 @@ const PROTOCOL_HEADER = "x-sr-bridge-protocol";
4142
4806
  */
4143
4807
  const LOCAL_HEADER = "x-sr-bridge-local";
4144
4808
  /**
4809
+ * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
4810
+ * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
4811
+ * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
4812
+ */
4813
+ const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
4814
+ /**
4145
4815
  * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
4146
4816
  * none: the bridge runs from source, or the package was built without the UI.
4147
4817
  */
@@ -4183,6 +4853,7 @@ function createUiMount(dir, logger) {
4183
4853
  try {
4184
4854
  process.env[BRIDGE_API_URL_ENV] = apiUrl;
4185
4855
  process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
4856
+ globalThis[UI_LOGGER_KEY] = logger;
4186
4857
  const module = await import(file.href);
4187
4858
  if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
4188
4859
  settle.resolve(module.handler);
@@ -4312,6 +4983,13 @@ var SeqQueue = class {
4312
4983
  hasMore: true
4313
4984
  };
4314
4985
  }
4986
+ /** The newest item the predicate accepts. O(n) from the end. */
4987
+ findLast(predicate) {
4988
+ for (let index = this.#items.length - 1; index >= this.#head; index--) {
4989
+ const item = this.#items[index];
4990
+ if (predicate(item)) return item;
4991
+ }
4992
+ }
4315
4993
  /** Removes every item the predicate accepts, wherever it sits. Keeps the order. O(n). */
4316
4994
  removeWhere(predicate) {
4317
4995
  this.#items = this.#items.slice(this.#head).filter((item) => !predicate(item));
@@ -4399,6 +5077,13 @@ var SpeechLog = class {
4399
5077
  };
4400
5078
  }
4401
5079
  /**
5080
+ * The newest marker whose text is `label`, of all entries or, with `sessionId`, of that
5081
+ * session (`null`: outside sessions). `undefined` if there is none (also when it was dropped).
5082
+ */
5083
+ latestMarker(label, sessionId) {
5084
+ return (sessionId === void 0 ? this.#entries : this.#bySession.get(sessionId))?.findLast((entry) => entry.kind === "marker" && entry.text === label);
5085
+ }
5086
+ /**
4402
5087
  * Removes the entries (and markers) of the current session or of the entries outside sessions
4403
5088
  * (`none`), and returns that scope's id (`null`: outside). The session stays current. `NOT_FOUND`
4404
5089
  * for `current` with none current or an id never given out, `INVALID_REQUEST` for an ended
@@ -4486,18 +5171,20 @@ var SpeechLog = class {
4486
5171
  }
4487
5172
  /**
4488
5173
  * The session `id` a read is limited to, `null` for the entries outside sessions (`none`),
4489
- * `undefined` without a filter. `current` becomes the current session's id now. `NOT_FOUND` for
5174
+ * `undefined` without a filter. `current` becomes the current session's id now, `active` too,
5175
+ * or `undefined` (everything) when none is current: never `NOT_FOUND`. `NOT_FOUND` for
4490
5176
  * `current` with none current, or an id never given out. An ended session whose entries were all
4491
5177
  * dropped is found: it just has no entries.
4492
5178
  */
4493
5179
  resolveFilter(filter) {
4494
5180
  if (filter === void 0) return void 0;
4495
5181
  if (filter === "none") return null;
5182
+ if (filter === "active") return this.#currentId ?? void 0;
4496
5183
  if (filter === "current") {
4497
5184
  if (this.#currentId === null) throw new AppError("NOT_FOUND", "No session is current");
4498
5185
  return this.#currentId;
4499
5186
  }
4500
- if (!Number.isSafeInteger(filter) || filter < 1) throw invalidField("session", "must be a session id, current or none");
5187
+ if (!Number.isSafeInteger(filter) || filter < 1) throw invalidField("session", "must be a session id, current, active or none");
4501
5188
  if (filter > this.#lastSessionId) throw new AppError("NOT_FOUND", `Session ${filter} does not exist`, { session: filter });
4502
5189
  return filter;
4503
5190
  }
@@ -4577,6 +5264,13 @@ async function startBridge(options) {
4577
5264
  clock,
4578
5265
  logger: log.for("native-input")
4579
5266
  });
5267
+ const captures = new InputCaptureService({
5268
+ input,
5269
+ log: speechLog,
5270
+ events,
5271
+ clock,
5272
+ pace: () => yieldEvery(256)
5273
+ });
4580
5274
  const configService = new ConfigService({
4581
5275
  store,
4582
5276
  logger: configLogger,
@@ -4585,6 +5279,14 @@ async function startBridge(options) {
4585
5279
  pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
4586
5280
  });
4587
5281
  const supervisors = createSupervisors(config, seams, log);
5282
+ const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
5283
+ const focus = new WindowFocusService({
5284
+ windows,
5285
+ queue: input,
5286
+ services: supervisors,
5287
+ clock,
5288
+ logger: log.for("native-input")
5289
+ });
4588
5290
  const childServices = new ChildServicesService({
4589
5291
  supervisors,
4590
5292
  config: () => configService.get(),
@@ -4599,7 +5301,9 @@ async function startBridge(options) {
4599
5301
  config: () => configService.get(),
4600
5302
  version,
4601
5303
  apiVersion: API_VERSION,
4602
- startedAt
5304
+ startedAt,
5305
+ injector,
5306
+ windows
4603
5307
  });
4604
5308
  const ui = createUiMount(seams.uiDir ?? shippedUiDir(), log.for("web-ui"));
4605
5309
  const http = new HttpServer({
@@ -4609,6 +5313,8 @@ async function startBridge(options) {
4609
5313
  config: configService,
4610
5314
  sessions,
4611
5315
  input,
5316
+ captures,
5317
+ focus,
4612
5318
  logger: log.for("http-api"),
4613
5319
  hostnames: [hostname()],
4614
5320
  proxies: proxyRoutes(childServices),
@@ -4619,7 +5325,7 @@ async function startBridge(options) {
4619
5325
  await ui?.mount(bridgeApiUrl(config.http.host, ports.http));
4620
5326
  const lifecycle = new BridgeLifecycleService({
4621
5327
  state: status,
4622
- waits,
5328
+ pending: [waits, captures],
4623
5329
  startServices: () => childServices.startEnabled(),
4624
5330
  stopOrder: [
4625
5331
  http,
@@ -4631,7 +5337,7 @@ async function startBridge(options) {
4631
5337
  ports,
4632
5338
  supervisors,
4633
5339
  webUi: ui !== void 0,
4634
- nativeInput: injector instanceof DisabledInputInjector ? null : "robotjs",
5340
+ nativeInput: injector.availability,
4635
5341
  tookMs: clock.now().getTime() - startedAt.getTime()
4636
5342
  }),
4637
5343
  logger: bridgeLogger