@screenreader-speech-capture/bridge 0.0.2 → 0.1.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 (102) hide show
  1. package/dist/cli.mjs +1085 -944
  2. package/dist/ui/adapter-node.js +1 -1
  3. package/dist/ui/client/ui/_app/immutable/chunks/{BnU72Mow.js → BfHif6xP.js} +1 -1
  4. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js.br +0 -0
  5. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js.gz +0 -0
  6. package/dist/ui/client/ui/_app/immutable/chunks/{BS7n1gMj.js → BrPqgVT6.js} +1 -1
  7. package/dist/ui/client/ui/_app/immutable/chunks/BrPqgVT6.js.br +0 -0
  8. package/dist/ui/client/ui/_app/immutable/chunks/BrPqgVT6.js.gz +0 -0
  9. package/dist/ui/client/ui/_app/immutable/chunks/{CK3uUd4t.js → C7D7xLuA.js} +1 -1
  10. package/dist/ui/client/ui/_app/immutable/chunks/C7D7xLuA.js.br +0 -0
  11. package/dist/ui/client/ui/_app/immutable/chunks/C7D7xLuA.js.gz +0 -0
  12. package/dist/ui/client/ui/_app/immutable/chunks/{B1Ryegye.js → Cc902J0D.js} +1 -1
  13. package/dist/ui/client/ui/_app/immutable/chunks/Cc902J0D.js.br +0 -0
  14. package/dist/ui/client/ui/_app/immutable/chunks/Cc902J0D.js.gz +0 -0
  15. package/dist/ui/client/ui/_app/immutable/chunks/{CMWEX9XL.js → D9JU-e3z.js} +1 -1
  16. package/dist/ui/client/ui/_app/immutable/chunks/D9JU-e3z.js.br +0 -0
  17. package/dist/ui/client/ui/_app/immutable/chunks/D9JU-e3z.js.gz +0 -0
  18. package/dist/ui/client/ui/_app/immutable/chunks/{DOY87jO2.js → KD5R77Wj.js} +1 -1
  19. package/dist/ui/client/ui/_app/immutable/chunks/KD5R77Wj.js.br +0 -0
  20. package/dist/ui/client/ui/_app/immutable/chunks/KD5R77Wj.js.gz +0 -0
  21. package/dist/ui/client/ui/_app/immutable/chunks/{B1vArRqi.js → PzCUpBms.js} +1 -1
  22. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js.br +0 -0
  23. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js.gz +0 -0
  24. package/dist/ui/client/ui/_app/immutable/chunks/{4wvZDMeR.js → Roub4aju.js} +1 -1
  25. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js.br +0 -0
  26. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js.gz +0 -0
  27. package/dist/ui/client/ui/_app/immutable/chunks/{tKonUL5Y.js → ux9AxWa3.js} +1 -1
  28. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js.br +0 -0
  29. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js.gz +0 -0
  30. package/dist/ui/client/ui/_app/immutable/entry/{app.C8tsut3X.js → app.DM2PRoLw.js} +2 -2
  31. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js.br +0 -0
  32. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js.gz +0 -0
  33. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js +1 -0
  34. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js.br +0 -0
  35. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js.gz +0 -0
  36. package/dist/ui/client/ui/_app/immutable/nodes/{3.WT26F_BF.js → 3.CywuMQ0y.js} +1 -1
  37. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js.br +0 -0
  38. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js.gz +0 -0
  39. package/dist/ui/client/ui/_app/immutable/nodes/{4.tiDJxi6M.js → 4.BYvsTY13.js} +1 -1
  40. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js.br +0 -0
  41. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js.gz +0 -0
  42. package/dist/ui/client/ui/_app/immutable/nodes/{5.MzfJoePg.js → 5.xWNFTFjr.js} +1 -1
  43. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js.br +0 -0
  44. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js.gz +0 -0
  45. package/dist/ui/client/ui/_app/immutable/nodes/{6.bNZhqiRK.js → 6.Dnf8S10l.js} +1 -1
  46. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js.br +0 -0
  47. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js.gz +0 -0
  48. package/dist/ui/client/ui/_app/version.json +1 -1
  49. package/dist/ui/client/ui/_app/version.json.br +0 -0
  50. package/dist/ui/client/ui/_app/version.json.gz +0 -0
  51. package/dist/ui/server/chunks/composition.js +8 -5
  52. package/dist/ui/server/chunks/composition.js.map +1 -1
  53. package/dist/ui/server/chunks/instance.js +3 -3
  54. package/dist/ui/server/chunks/internal.js +1 -1
  55. package/dist/ui/server/chunks/src.js +19 -12
  56. package/dist/ui/server/chunks/src.js.map +1 -1
  57. package/dist/ui/server/entries/hooks.server.js +3 -2
  58. package/dist/ui/server/entries/hooks.server.js.map +1 -1
  59. package/dist/ui/server/entries/pages/_layout.svelte.js +1 -1
  60. package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
  61. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js +1 -1
  62. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js.map +1 -1
  63. package/dist/ui/server/manifest-full.js +1 -1
  64. package/dist/ui/server/manifest.js +1 -1
  65. package/dist/ui/server/nodes/0.js +1 -1
  66. package/dist/ui/server/nodes/3.js +1 -1
  67. package/dist/ui/server/nodes/4.js +1 -1
  68. package/dist/ui/server/nodes/5.js +1 -1
  69. package/dist/ui/server/nodes/6.js +1 -1
  70. package/dist/ui/server/server.js +1 -1
  71. package/package.json +1 -1
  72. package/dist/ui/client/ui/_app/immutable/chunks/4wvZDMeR.js.br +0 -0
  73. package/dist/ui/client/ui/_app/immutable/chunks/4wvZDMeR.js.gz +0 -0
  74. package/dist/ui/client/ui/_app/immutable/chunks/B1Ryegye.js.br +0 -0
  75. package/dist/ui/client/ui/_app/immutable/chunks/B1Ryegye.js.gz +0 -0
  76. package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js.br +0 -0
  77. package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js.gz +0 -0
  78. package/dist/ui/client/ui/_app/immutable/chunks/BS7n1gMj.js.br +0 -0
  79. package/dist/ui/client/ui/_app/immutable/chunks/BS7n1gMj.js.gz +0 -0
  80. package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js.br +0 -0
  81. package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js.gz +0 -0
  82. package/dist/ui/client/ui/_app/immutable/chunks/CK3uUd4t.js.br +0 -0
  83. package/dist/ui/client/ui/_app/immutable/chunks/CK3uUd4t.js.gz +0 -0
  84. package/dist/ui/client/ui/_app/immutable/chunks/CMWEX9XL.js.br +0 -0
  85. package/dist/ui/client/ui/_app/immutable/chunks/CMWEX9XL.js.gz +0 -0
  86. package/dist/ui/client/ui/_app/immutable/chunks/DOY87jO2.js.br +0 -0
  87. package/dist/ui/client/ui/_app/immutable/chunks/DOY87jO2.js.gz +0 -0
  88. package/dist/ui/client/ui/_app/immutable/chunks/tKonUL5Y.js.br +0 -0
  89. package/dist/ui/client/ui/_app/immutable/chunks/tKonUL5Y.js.gz +0 -0
  90. package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js.br +0 -0
  91. package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js.gz +0 -0
  92. package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js +0 -1
  93. package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js.br +0 -0
  94. package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js.gz +0 -0
  95. package/dist/ui/client/ui/_app/immutable/nodes/3.WT26F_BF.js.br +0 -0
  96. package/dist/ui/client/ui/_app/immutable/nodes/3.WT26F_BF.js.gz +0 -0
  97. package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js.br +0 -0
  98. package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js.gz +0 -0
  99. package/dist/ui/client/ui/_app/immutable/nodes/5.MzfJoePg.js.br +0 -0
  100. package/dist/ui/client/ui/_app/immutable/nodes/5.MzfJoePg.js.gz +0 -0
  101. package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js.br +0 -0
  102. package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js.gz +0 -0
package/dist/cli.mjs CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
+ import { once, setMaxListeners } from "node:events";
3
4
  import os, { hostname } from "node:os";
4
5
  import http from "node:http";
5
6
  import net from "node:net";
6
- import { finished } from "node:stream";
7
+ import { finished, pipeline } from "node:stream";
7
8
  import { setImmediate, setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ import fs, { existsSync, readFileSync } from "node:fs";
8
10
  import { TextDecoder as TextDecoder$1, parseArgs } from "node:util";
9
- import fs, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
11
+ import fs$1, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
10
12
  import path from "node:path";
11
13
  import { Worker } from "node:worker_threads";
12
- import fs$1, { existsSync, readFileSync } from "node:fs";
13
14
  import { execFile, spawn, spawnSync } from "node:child_process";
14
- import { once } from "node:events";
15
15
  import readline from "node:readline";
16
16
  // package.json
17
- var version = "0.0.2";
17
+ var version = "0.1.0";
18
18
  // ../shared/src/api-version.ts
19
19
  /**
20
20
  * `<major>.<minor>` of the HTTP API. Minor versions only add things, with the exceptions in
21
21
  * docs/usage/http-api.md#versioning. Within a major version the enums of the answers never grow
22
22
  * (`openapi/freeze.test.ts`).
23
23
  */
24
- const API_VERSION = "1.31";
24
+ const API_VERSION = "1.33";
25
25
  /** Path prefix of every API route. */
26
26
  const API_PREFIX = "/api/v1";
27
27
  /**
@@ -742,7 +742,7 @@ function safeParse(schema, input, config$1) {
742
742
  issues: dataset.issues
743
743
  };
744
744
  }
745
- // ../shared/src/limits.ts
745
+ // ../shared/src/rules/limits.ts
746
746
  /** Ranges of the speech endpoints. */
747
747
  const API_LIMITS = {
748
748
  /** `GET /speech?limit=`: the default and the most a caller may ask for. */
@@ -836,6 +836,22 @@ const isTrimmedLabel = (text, max) => {
836
836
  const trimmed = text.trim();
837
837
  return trimmed !== "" && trimmed.length <= max;
838
838
  };
839
+ // ../shared/src/rules/vocabulary.ts
840
+ /** `log.level`, from the least to the most detail. */
841
+ const LOG_LEVELS = [
842
+ "error",
843
+ "warn",
844
+ "info",
845
+ "debug"
846
+ ];
847
+ /** The buttons of a native click. */
848
+ const MOUSE_BUTTONS = [
849
+ "left",
850
+ "right",
851
+ "middle"
852
+ ];
853
+ /** Whose browser a focus or a key press means. */
854
+ const FOCUS_TARGETS = ["mcp", "playwright"];
839
855
  // ../shared/src/config.ts
840
856
  /** A `TextDecoder` label other than UTF-16 (the framing splits the bytes on 0x0A first). */
841
857
  function isSupportedEncoding(label) {
@@ -845,12 +861,6 @@ function isSupportedEncoding(label) {
845
861
  return false;
846
862
  }
847
863
  }
848
- const LOG_LEVELS = [
849
- "error",
850
- "warn",
851
- "info",
852
- "debug"
853
- ];
854
864
  const range = ({ min, max }) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min), /* @__PURE__ */ maxValue(max));
855
865
  const port = range(CONFIG_LIMITS.port);
856
866
  /** Port of a child service: `0` ("any free port") would leave the bridge no port to proxy to. */
@@ -907,6 +917,7 @@ const ERROR_STATUS = {
907
917
  FORBIDDEN: 403,
908
918
  INPUT_DISABLED: 409,
909
919
  FOCUS_FAILED: 409,
920
+ WRONG_WINDOW: 409,
910
921
  SERVICE_UNAVAILABLE: 503,
911
922
  INTERNAL: 500
912
923
  };
@@ -926,23 +937,20 @@ CAPTURE.entries, `${CAPTURE.entries}`;
926
937
  const ClickRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
927
938
  x: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen x in physical pixels."), /* @__PURE__ */ examples([640])),
928
939
  y: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen y in physical pixels."), /* @__PURE__ */ examples([12])),
929
- button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist([
930
- "left",
931
- "right",
932
- "middle"
933
- ])), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
940
+ button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(MOUSE_BUTTONS)), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
934
941
  capture
935
942
  }), /* @__PURE__ */ description("`POST /input/click`: a native mouse click at a screen point, to give a window the focus. Added in API 1.14."));
936
943
  const KeysRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
937
944
  keys: /* @__PURE__ */ pipe(/* @__PURE__ */ union([/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty()), /* @__PURE__ */ pipe(/* @__PURE__ */ array(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty())), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(maxKeys$1))]), /* @__PURE__ */ description(`One chord (\`Insert+T\`) or a sequence of chords (\`["h", "h", "Insert+Down"]\`). Chords join modifiers (\`Control\`, \`Shift\`, \`Alt\`, \`Win\`, \`Insert\`, \`CapsLock\`) and one key with \`+\`. Names are case-insensitive (docs/usage/native-input.md#key-names); the numpad keys (\`numpad7\`, \`numpadEnter\`, …) since API 1.30. At most ${maxKeys$1} chords.`), /* @__PURE__ */ examples(["Insert+T"])),
938
945
  delayMs: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(0), /* @__PURE__ */ maxValue(delayMs$1.max))), /* @__PURE__ */ description(`Pause between the chords of a sequence in milliseconds, ${delayMs$1.default} if omitted.`)),
946
+ expectedTarget: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(FOCUS_TARGETS)), /* @__PURE__ */ description("Only send the keys while a window of this browser is in front: `mcp` (Playwright MCP) or `playwright` (the Playwright server). Checked before every chord; otherwise, and where the bridge cannot tell, `409 WRONG_WINDOW` and no further chord is sent (docs/usage/native-input.md#requiring-a-target-window). Added in API 1.32.")),
939
947
  capture
940
948
  }), /* @__PURE__ */ description("`POST /input/keys`: send key presses to the focused window. Added in API 1.14."));
941
949
  const FocusRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
942
- target: /* @__PURE__ */ pipe(/* @__PURE__ */ picklist(["mcp", "playwright"]), /* @__PURE__ */ description("Whose browser: `mcp` (Playwright MCP) or `playwright` (the Playwright server, for tests).")),
950
+ target: /* @__PURE__ */ pipe(/* @__PURE__ */ picklist(FOCUS_TARGETS), /* @__PURE__ */ description("Whose browser: `mcp` (Playwright MCP) or `playwright` (the Playwright server, for tests).")),
943
951
  title: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(API_LIMITS.input.focusTitleLength))), /* @__PURE__ */ description("Only a window whose title contains this text, for example a marker the caller put into `document.title`. Without it, the front-most window of the target."))
944
952
  }), /* @__PURE__ */ description("`POST /input/focus`: bring a browser window the bridge started to the front. Added in API 1.21."));
945
- // ../shared/src/key-chord.ts
953
+ // ../shared/src/rules/key-chord.ts
946
954
  /**
947
955
  * The key names of `POST /input/keys` (docs/usage/native-input.md#key-names). The bridge parses
948
956
  * chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
@@ -1042,38 +1050,12 @@ function parseKeyChord$1(chord) {
1042
1050
  }
1043
1051
  };
1044
1052
  }
1045
- // ../shared/src/services.ts
1053
+ // ../shared/src/rules/service-paths.ts
1046
1054
  /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
1047
1055
  const PLAYWRIGHT_PATH = "/playwright";
1048
1056
  /** Playwright MCP (streamable HTTP): `http://<bridge>:5151/playwright-mcp`. */
1049
1057
  const PLAYWRIGHT_MCP_PATH = "/playwright-mcp";
1050
- // ../shared/src/session.ts
1051
- const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
1052
- const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
1053
- 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.`));
1054
- const sessionEntries = {
1055
- id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, also across restarts (since API 1.29): the first session of a bridge run gets the run's start time in milliseconds, so an id is never given out twice.")),
1056
- name: /* @__PURE__ */ string(),
1057
- run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
1058
- 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.")),
1059
- startedAt: timestamp$1,
1060
- endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
1061
- 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.")),
1062
- firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
1063
- lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
1064
- entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
1065
- };
1066
- const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
1067
- name: /* @__PURE__ */ pipe(label("For example the test title."), /* @__PURE__ */ examples(["checkout test"])),
1068
- run: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(label("Optional label that groups sessions, for example one per test run."))), /* @__PURE__ */ examples(["nightly-42"]))
1069
- });
1070
- ({ ...sessionEntries });
1071
- /**
1072
- * Request header naming the client (for example `host pid 1234`), so the bridge can tell when
1073
- * one client ends or replaces another one's session. Optional. API 1.10.
1074
- */
1075
- const CLIENT_HEADER = "x-sr-speech-client";
1076
- // ../shared/src/text-match.ts
1058
+ // ../shared/src/rules/text-match.ts
1077
1059
  /**
1078
1060
  * The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
1079
1061
  * `GET /speech/wait`, the client in its own waits, so both must use this one copy. It is the only
@@ -1101,6 +1083,32 @@ function createTextTest(match, normalize) {
1101
1083
  if (needle === "") return void 0;
1102
1084
  return (text) => prepare(text).includes(needle);
1103
1085
  }
1086
+ // ../shared/src/session.ts
1087
+ const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
1088
+ const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
1089
+ 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.`));
1090
+ const sessionEntries = {
1091
+ id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, also across restarts (since API 1.29): the first session of a bridge run gets the run's start time in milliseconds, so an id is never given out twice.")),
1092
+ name: /* @__PURE__ */ string(),
1093
+ run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
1094
+ 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.")),
1095
+ startedAt: timestamp$1,
1096
+ endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
1097
+ 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.")),
1098
+ firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
1099
+ lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
1100
+ entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
1101
+ };
1102
+ const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
1103
+ name: /* @__PURE__ */ pipe(label("For example the test title."), /* @__PURE__ */ examples(["checkout test"])),
1104
+ run: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(label("Optional label that groups sessions, for example one per test run."))), /* @__PURE__ */ examples(["nightly-42"]))
1105
+ });
1106
+ ({ ...sessionEntries });
1107
+ /**
1108
+ * Request header naming the client (for example `host pid 1234`), so the bridge can tell when
1109
+ * one client ends or replaces another one's session. Optional. API 1.10.
1110
+ */
1111
+ const CLIENT_HEADER = "x-sr-speech-client";
1104
1112
  // ../shared/src/validate.ts
1105
1113
  /**
1106
1114
  * Checks `value` against `schema`. Unknown keys of an answer don't fail it and are left out of the
@@ -1120,6 +1128,104 @@ function checkDto(schema, value) {
1120
1128
  message: issue.message
1121
1129
  };
1122
1130
  }
1131
+ // src/adapters/in/cli/lifecycle.ts
1132
+ const SHUTDOWN_TIMEOUT_MS = 1e4;
1133
+ /** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
1134
+ function shutdownSignals(platform) {
1135
+ const signals = [
1136
+ "SIGINT",
1137
+ "SIGTERM",
1138
+ "SIGHUP"
1139
+ ];
1140
+ if (platform === "win32") signals.push("SIGBREAK");
1141
+ return signals;
1142
+ }
1143
+ /** Resolves once everything written to `stream` so far is handed to the OS. */
1144
+ function drain(stream) {
1145
+ return new Promise((resolve) => stream.write("", () => resolve()));
1146
+ }
1147
+ /** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
1148
+ async function flushConsole() {
1149
+ await Promise.all([drain(process.stdout), drain(process.stderr)]);
1150
+ }
1151
+ function describeError(error) {
1152
+ return error instanceof Error ? error.stack ?? String(error) : String(error);
1153
+ }
1154
+ /**
1155
+ * Starts the bridge with `start`, then stops it gracefully and exits the process
1156
+ * (docs/usage/operations.md#shutdown):
1157
+ *
1158
+ * - on a shutdown signal. A second signal exits at once.
1159
+ * - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
1160
+ * - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
1161
+ *
1162
+ * The exit code is 0 unless something failed. Console output is flushed before exiting.
1163
+ *
1164
+ * The signal handlers are installed before `start`, so a signal that arrives while the bridge
1165
+ * starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
1166
+ * like `start`.
1167
+ */
1168
+ async function runUntilStopped(start, proc, options = {}) {
1169
+ const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
1170
+ let bridge = void 0;
1171
+ /** A signal that arrived before the bridge had started. */
1172
+ let early;
1173
+ let stopping = false;
1174
+ let exiting = false;
1175
+ let exitCode = 0;
1176
+ let watchdog;
1177
+ /** Ends the child processes the graceful stop didn't get to. */
1178
+ const killLeftovers = () => {
1179
+ try {
1180
+ onForcedExit?.();
1181
+ } catch {}
1182
+ };
1183
+ const forceExit = (code) => {
1184
+ killLeftovers();
1185
+ proc.exit(code);
1186
+ };
1187
+ const exit = (code) => {
1188
+ if (exiting) return forceExit(code);
1189
+ exiting = true;
1190
+ flush().catch(() => void 0).then(() => {
1191
+ clearTimeout(watchdog);
1192
+ proc.exit(code);
1193
+ });
1194
+ };
1195
+ const shutdown = (running, reason) => {
1196
+ stopping = true;
1197
+ watchdog = setTimeout(() => {
1198
+ running.log.error(`shutdown did not finish within ${timeoutMs / 1e3} s, exiting`);
1199
+ exiting = true;
1200
+ forceExit(1);
1201
+ }, timeoutMs).unref();
1202
+ running.stop(reason).then(() => exit(exitCode), () => exit(1));
1203
+ };
1204
+ for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
1205
+ if (bridge === void 0) {
1206
+ if (early === void 0) early = signal;
1207
+ else {
1208
+ killLeftovers();
1209
+ exit(1);
1210
+ }
1211
+ return;
1212
+ }
1213
+ if (!stopping) return shutdown(bridge, signal);
1214
+ bridge.log.warn(`${signal} again, exiting without waiting`);
1215
+ killLeftovers();
1216
+ exit(1);
1217
+ });
1218
+ bridge = await start();
1219
+ const running = bridge;
1220
+ const crash = (what) => (error) => {
1221
+ running.log.error(`${what}: ${describeError(error)}`);
1222
+ exitCode = 1;
1223
+ if (!stopping) shutdown(running, "crash");
1224
+ };
1225
+ proc.on("uncaughtException", crash("uncaught exception"));
1226
+ proc.on("unhandledRejection", crash("unhandled rejection"));
1227
+ if (early !== void 0) shutdown(running, early);
1228
+ }
1123
1229
  // src/domain/errors.ts
1124
1230
  /** An expected error with a stable code, for example a bad request. */
1125
1231
  var AppError = class extends Error {
@@ -1425,7 +1531,7 @@ var ServiceProxy = class {
1425
1531
  for (const [name, value] of Object.entries(answer.headers)) if (!HOP_BY_HOP.has(name)) back[name] = value;
1426
1532
  res.writeHead(answer.statusCode ?? 502, back);
1427
1533
  res.flushHeaders();
1428
- answer.pipe(res);
1534
+ pipeline(answer, res, () => {});
1429
1535
  });
1430
1536
  upstream.on("error", (error) => {
1431
1537
  if (res.headersSent) {
@@ -1574,8 +1680,8 @@ async function readJson(req) {
1574
1680
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1575
1681
  /** The object schema of a field, behind `optional` or `nullable`; `undefined` for other types. */
1576
1682
  function nestedSchema(entry) {
1577
- if ("entries" in entry) return entry;
1578
- return "wrapped" in entry ? nestedSchema(entry.wrapped) : void 0;
1683
+ if (entry.entries) return { entries: entry.entries };
1684
+ return entry.wrapped && nestedSchema(entry.wrapped);
1579
1685
  }
1580
1686
  /** Rejects a field the schema doesn't have, naming it with its path (`capture.quietFor`). */
1581
1687
  function checkFields(body, schema, path = "") {
@@ -1590,9 +1696,58 @@ function checkFields(body, schema, path = "") {
1590
1696
  if (nested && isObject(value)) checkFields(value, nested, `${path}${name}.`);
1591
1697
  }
1592
1698
  }
1699
+ /** Whether `value` has the schema's type. An object's fields are not looked at. */
1700
+ function hasType(value, schema) {
1701
+ switch (schema.type) {
1702
+ case "string": return typeof value === "string";
1703
+ case "number": return Number.isFinite(value);
1704
+ case "picklist": return schema.options.includes(value);
1705
+ case "array": return Array.isArray(value) && value.every((item) => hasType(item, schema.item));
1706
+ case "union": return schema.options.some((option) => hasType(value, option));
1707
+ case "strict_object": return isObject(value);
1708
+ case "optional": return value === void 0 || hasType(value, schema.wrapped);
1709
+ case "nullable": return value === null || hasType(value, schema.wrapped);
1710
+ default: throw new Error(`request schema type ${schema.type} is not supported`);
1711
+ }
1712
+ }
1713
+ /** What the error says `value` must be, for a schema `hasType` supports. */
1714
+ function typeName(schema, value) {
1715
+ switch (schema.type) {
1716
+ case "optional": return typeName(schema.wrapped, value);
1717
+ case "nullable": return `${typeName(schema.wrapped, value)} or null`;
1718
+ case "union": return schema.options.map((option) => typeName(option, value)).join(" or ");
1719
+ case "array": return `an array of ${schema.item.type}s`;
1720
+ case "strict_object": return "an object";
1721
+ case "picklist": {
1722
+ if (typeof value !== "string") return "a string";
1723
+ const names = schema.options.map(String);
1724
+ return `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
1725
+ }
1726
+ default: return `a ${schema.type}`;
1727
+ }
1728
+ }
1729
+ /** Rejects the first field, in the schema's order, that doesn't have its type. */
1730
+ function checkTypes(body, schema, path = "") {
1731
+ for (const [name, entry] of Object.entries(schema.entries)) {
1732
+ const value = body[name];
1733
+ if (!hasType(value, entry)) throw invalidField(`${path}${name}`, `must be ${typeName(entry, value)}`);
1734
+ const nested = nestedSchema(entry);
1735
+ if (nested && isObject(value)) checkTypes(value, nested, `${path}${name}.`);
1736
+ }
1737
+ }
1738
+ /**
1739
+ * The body with its fields' types checked against `schema`. Only the types: ranges, lengths and
1740
+ * formats are use-case rules, applied by the application.
1741
+ */
1742
+ function typedBody(schema, body) {
1743
+ if (!isObject(body)) throw invalidField("body", "must be a JSON object");
1744
+ checkTypes(body, schema);
1745
+ return body;
1746
+ }
1593
1747
  /**
1594
1748
  * The JSON body of a POST/PUT: checks the content type, reads it, and rejects anything but an
1595
- * object with fields of `schema`. The fields' types are checked by the caller.
1749
+ * object with fields of `schema`. The fields' types are checked by the route (`typedBody`), those
1750
+ * of `PUT /config` by the domain.
1596
1751
  */
1597
1752
  async function jsonBody(req, schema) {
1598
1753
  requireJson(req);
@@ -1617,52 +1772,6 @@ function requireNoBody(req) {
1617
1772
  });
1618
1773
  });
1619
1774
  }
1620
- /** `body[name]`, or `undefined` when the body isn't a JSON object. */
1621
- function field(body, name) {
1622
- return isObject(body) ? body[name] : void 0;
1623
- }
1624
- /** A required string field of a JSON body. */
1625
- function stringField(body, name) {
1626
- const value = field(body, name);
1627
- if (typeof value !== "string") throw invalidField(name, "must be a string");
1628
- return value;
1629
- }
1630
- /** An optional string field of a JSON body. */
1631
- function optionalStringField(body, name) {
1632
- const value = field(body, name);
1633
- if (value !== void 0 && typeof value !== "string") throw invalidField(name, "must be a string");
1634
- return value;
1635
- }
1636
- /** A required number field of a JSON body. Ranges are checked by the use case. */
1637
- function numberField(body, name) {
1638
- const value = field(body, name);
1639
- if (typeof value !== "number" || !Number.isFinite(value)) throw invalidField(name, "must be a number");
1640
- return value;
1641
- }
1642
- /** An optional number field of a JSON body. */
1643
- function optionalNumberField(body, name) {
1644
- return field(body, name) === void 0 ? void 0 : numberField(body, name);
1645
- }
1646
- /** An optional field of a JSON body that is a JSON object. */
1647
- function optionalObjectField(body, name) {
1648
- const value = field(body, name);
1649
- if (value === void 0) return void 0;
1650
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidField(name, "must be an object");
1651
- return value;
1652
- }
1653
- /** A required field that is a string or an array of strings. */
1654
- function keysField(body, name) {
1655
- const value = field(body, name);
1656
- if (typeof value === "string") return value;
1657
- if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
1658
- throw invalidField(name, "must be a string or an array of strings");
1659
- }
1660
- /** An optional string field of a JSON body that may also be `null`. */
1661
- function nullableStringField(body, name) {
1662
- const value = field(body, name);
1663
- if (value !== void 0 && value !== null && typeof value !== "string") throw invalidField(name, "must be a string or null");
1664
- return value;
1665
- }
1666
1775
  /** The `X-SR-Speech-Client` header (`CLIENT_HEADER`), `null` if missing or empty. */
1667
1776
  function clientHeader(req) {
1668
1777
  const raw = req.headers[CLIENT_HEADER];
@@ -1850,24 +1959,6 @@ function hangUpSignal(req, res) {
1850
1959
  return controller.signal;
1851
1960
  }
1852
1961
  // src/adapters/in/http/routes/input-routes.ts
1853
- /** The `capture` object of an input request, `undefined` without one. */
1854
- function captureField(body) {
1855
- const capture = optionalObjectField(body, "capture");
1856
- if (capture === void 0) return void 0;
1857
- const ms = (name) => {
1858
- try {
1859
- return optionalNumberField(capture, name);
1860
- } catch {
1861
- throw invalidField(`capture.${name}`, "must be a number");
1862
- }
1863
- };
1864
- return {
1865
- quietForMs: ms("quietForMs"),
1866
- firstWithinMs: ms("firstWithinMs"),
1867
- timeoutMs: ms("timeoutMs"),
1868
- settleMs: ms("settleMs")
1869
- };
1870
- }
1871
1962
  /**
1872
1963
  * Runs `task` and answers with `reply`. A client that hangs up first cancels the input that isn't
1873
1964
  * sent yet (docs/usage/native-input.md#when-the-client-gives-up).
@@ -1900,12 +1991,7 @@ function answer(exchange, capture, send, record) {
1900
1991
  function inputRoutes(router, deps) {
1901
1992
  const { input, captures, focus, logger } = deps;
1902
1993
  router.add("POST", "/input/focus", { body: FocusRequestSchema }, async ({ req, res, body }) => {
1903
- const target = stringField(body, "target");
1904
- if (target !== "mcp" && target !== "playwright") throw invalidField("target", "must be mcp or playwright");
1905
- const request = {
1906
- target,
1907
- title: optionalStringField(body, "title")
1908
- };
1994
+ const request = typedBody(FocusRequestSchema, body);
1909
1995
  await whileConnected({
1910
1996
  req,
1911
1997
  res,
@@ -1915,33 +2001,23 @@ function inputRoutes(router, deps) {
1915
2001
  signal
1916
2002
  }), (focused) => sendJson(res, 200, toFocusedWindowDto(focused)));
1917
2003
  }).add("POST", "/input/click", { body: ClickRequestSchema }, async ({ req, res, body }) => {
1918
- const button = optionalStringField(body, "button");
1919
- if (button !== void 0 && button !== "left" && button !== "right" && button !== "middle") throw invalidField("button", "must be left, right or middle");
1920
- const mouseButton = button;
1921
- const request = {
1922
- x: numberField(body, "x"),
1923
- y: numberField(body, "y"),
1924
- button: mouseButton
1925
- };
2004
+ const { capture, ...request } = typedBody(ClickRequestSchema, body);
1926
2005
  await answer({
1927
2006
  req,
1928
2007
  res,
1929
2008
  logger
1930
- }, captureField(body), (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
2009
+ }, capture, (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
1931
2010
  ...request,
1932
2011
  capture,
1933
2012
  signal
1934
2013
  }));
1935
2014
  }).add("POST", "/input/keys", { body: KeysRequestSchema }, async ({ req, res, body }) => {
1936
- const request = {
1937
- keys: keysField(body, "keys"),
1938
- delayMs: optionalNumberField(body, "delayMs")
1939
- };
2015
+ const { capture, ...request } = typedBody(KeysRequestSchema, body);
1940
2016
  await answer({
1941
2017
  req,
1942
2018
  res,
1943
2019
  logger
1944
- }, captureField(body), (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
2020
+ }, capture, (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
1945
2021
  ...request,
1946
2022
  capture,
1947
2023
  signal
@@ -1983,8 +2059,7 @@ function toSessionListDto({ sessions, currentId, outsideEntries }) {
1983
2059
  /** `POST /sessions`, `POST /sessions/end`, `DELETE /sessions`, `GET /sessions` (docs/usage/http-api.md#endpoints). */
1984
2060
  function sessionRoutes(router, { sessions }) {
1985
2061
  router.add("POST", "/sessions", { body: StartSessionRequestSchema }, ({ req, res, body }) => {
1986
- const name = stringField(body, "name");
1987
- const run = nullableStringField(body, "run");
2062
+ const { name, run } = typedBody(StartSessionRequestSchema, body);
1988
2063
  const client = clientHeader(req);
1989
2064
  sendJson(res, 201, toStartSessionResponseDto(sessions.start({
1990
2065
  name,
@@ -2059,7 +2134,7 @@ function speechRoutes(router, deps) {
2059
2134
  speech.clear(sessionParam(url));
2060
2135
  sendNoContent(res);
2061
2136
  }).add("POST", "/markers", { body: MarkerRequestSchema }, ({ res, body }) => {
2062
- const label = stringField(body, "label");
2137
+ const { label } = typedBody(MarkerRequestSchema, body);
2063
2138
  sendJson(res, 201, toSpeechEntryDto(speech.addMarker(label)));
2064
2139
  }).add("GET", "/markers/latest", { query: ["label", "session"] }, ({ res, url }) => {
2065
2140
  const label = stringParam(url, "label");
@@ -2111,7 +2186,8 @@ function toServiceStatusDto(service) {
2111
2186
  version: service.version,
2112
2187
  port: service.port,
2113
2188
  restarts: service.restarts,
2114
- exitCode: service.exitCode
2189
+ exitCode: service.exitCode,
2190
+ lastError: service.lastError
2115
2191
  };
2116
2192
  }
2117
2193
  function toInputAvailabilityDto(availability) {
@@ -2146,7 +2222,8 @@ function toStatusDto({ bridge, tcp, buffer, services, session, input }) {
2146
2222
  id,
2147
2223
  voice,
2148
2224
  connectedAt: connectedAt.toISOString()
2149
- }))
2225
+ })),
2226
+ lastSpeechAt: tcp.lastSpeechAt?.toISOString() ?? null
2150
2227
  },
2151
2228
  buffer: {
2152
2229
  size: buffer.size,
@@ -2367,43 +2444,120 @@ function parseUrl(target) {
2367
2444
  throw new AppError("INVALID_REQUEST", "The request URL is not valid");
2368
2445
  }
2369
2446
  }
2370
- // src/adapters/in/tcp/text-to-socket-parser.ts
2371
- const LF = 10;
2372
- const CR = 13;
2373
- const HEADER = /^voice=(\S.*)$/;
2447
+ // src/adapters/in/http/ui-mount.ts
2448
+ /** The environment variable the UI's BFF reads the bridge's address from. */
2449
+ const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
2450
+ /** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
2451
+ const PROTOCOL_HEADER = "x-sr-bridge-protocol";
2374
2452
  /**
2375
- * Parser for the `text-to-socket` wire format
2376
- * (docs/implementation/tcp-capture.md#framing-and-decoding), one instance per connection. Bytes are
2377
- * split at `\n` *before* decoding, so a multi-byte character split across two TCP packets is
2378
- * decoded correctly.
2453
+ * The header that tells the UI its page is opened from the bridge's own machine, where the screen
2454
+ * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
2455
+ * Set (`1`) or removed on every request, so a client can't send it.
2379
2456
  */
2380
- var TextToSocketParser = class {
2381
- maxLineBytes;
2382
- events;
2383
- decoder;
2384
- pending = [];
2385
- pendingBytes = 0;
2386
- /** After a cut: drop bytes until the next `\n`. */
2387
- discarding = false;
2388
- firstLine = true;
2389
- constructor(encoding, maxLineBytes, events) {
2390
- this.maxLineBytes = maxLineBytes;
2391
- this.events = events;
2392
- this.decoder = new TextDecoder$1(encoding);
2393
- }
2394
- push(chunk) {
2395
- let start = 0;
2396
- while (start < chunk.length) {
2397
- const newline = chunk.indexOf(LF, start);
2398
- const end = newline === -1 ? chunk.length : newline;
2399
- this.append(chunk.subarray(start, end));
2400
- if (newline === -1) return;
2401
- this.completeLine();
2402
- start = newline + 1;
2403
- }
2457
+ const LOCAL_HEADER = "x-sr-bridge-local";
2458
+ /**
2459
+ * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
2460
+ * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
2461
+ * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
2462
+ */
2463
+ const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
2464
+ /**
2465
+ * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
2466
+ * none: the bridge runs from source, or the package was built without the UI.
2467
+ */
2468
+ function createUiMount(dir, logger) {
2469
+ const file = new URL("handler.js", dir);
2470
+ if (!existsSync(file)) {
2471
+ logger.debug(`no web UI at ${file.pathname}`);
2472
+ return;
2404
2473
  }
2405
- /** The connection closed: text still in the buffer becomes a last line. */
2406
- end() {
2474
+ let settle;
2475
+ const loaded = new Promise((resolve, reject) => {
2476
+ settle = {
2477
+ resolve,
2478
+ reject
2479
+ };
2480
+ });
2481
+ loaded.catch(() => void 0);
2482
+ return {
2483
+ handler: async (req, res) => {
2484
+ if (new URL(req.url ?? "/", "http://localhost").pathname === "/") {
2485
+ res.writeHead(302, { location: "/ui/" }).end();
2486
+ return;
2487
+ }
2488
+ let handler;
2489
+ try {
2490
+ handler = await loaded;
2491
+ } catch {
2492
+ throw new AppError("SERVICE_UNAVAILABLE", "The web UI failed to start");
2493
+ }
2494
+ req.headers[PROTOCOL_HEADER] = "http";
2495
+ if (isOwnAddress(req.socket?.remoteAddress)) req.headers[LOCAL_HEADER] = "1";
2496
+ else delete req.headers[LOCAL_HEADER];
2497
+ handler(req, res, () => {
2498
+ res.statusCode = 404;
2499
+ res.end();
2500
+ });
2501
+ },
2502
+ async mount(apiUrl) {
2503
+ try {
2504
+ process.env[BRIDGE_API_URL_ENV] = apiUrl;
2505
+ process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
2506
+ globalThis[UI_LOGGER_KEY] = logger;
2507
+ const module = await import(file.href);
2508
+ if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
2509
+ settle.resolve(module.handler);
2510
+ logger.debug(`web UI loaded from ${file.pathname}`);
2511
+ } catch (error) {
2512
+ logger.error(`web UI failed to start: ${error instanceof Error ? error.message : String(error)}`);
2513
+ settle.reject(error);
2514
+ }
2515
+ }
2516
+ };
2517
+ }
2518
+ /**
2519
+ * Where the BFF reaches the bridge's HTTP API: over loopback, whatever address it listens on.
2520
+ */
2521
+ function bridgeApiUrl(host, port) {
2522
+ return `http://${hostPort(host === "::" ? "::1" : isWildcard(host) ? "127.0.0.1" : host, port)}`;
2523
+ }
2524
+ // src/adapters/in/tcp/text-to-socket-parser.ts
2525
+ const LF = 10;
2526
+ const CR = 13;
2527
+ const HEADER = /^voice=(\S.*)$/;
2528
+ /**
2529
+ * Parser for the `text-to-socket` wire format
2530
+ * (docs/implementation/tcp-capture.md#framing-and-decoding), one instance per connection. Bytes are
2531
+ * split at `\n` *before* decoding, so a multi-byte character split across two TCP packets is
2532
+ * decoded correctly.
2533
+ */
2534
+ var TextToSocketParser = class {
2535
+ maxLineBytes;
2536
+ events;
2537
+ decoder;
2538
+ pending = [];
2539
+ pendingBytes = 0;
2540
+ /** After a cut: drop bytes until the next `\n`. */
2541
+ discarding = false;
2542
+ firstLine = true;
2543
+ constructor(encoding, maxLineBytes, events) {
2544
+ this.maxLineBytes = maxLineBytes;
2545
+ this.events = events;
2546
+ this.decoder = new TextDecoder$1(encoding);
2547
+ }
2548
+ push(chunk) {
2549
+ let start = 0;
2550
+ while (start < chunk.length) {
2551
+ const newline = chunk.indexOf(LF, start);
2552
+ const end = newline === -1 ? chunk.length : newline;
2553
+ this.append(chunk.subarray(start, end));
2554
+ if (newline === -1) return;
2555
+ this.completeLine();
2556
+ start = newline + 1;
2557
+ }
2558
+ }
2559
+ /** The connection closed: text still in the buffer becomes a last line. */
2560
+ end() {
2407
2561
  if (!this.discarding && this.pendingBytes > 0) this.emit();
2408
2562
  this.pending = [];
2409
2563
  this.pendingBytes = 0;
@@ -2559,42 +2713,62 @@ var FsConfigStore = class {
2559
2713
  constructor(location) {
2560
2714
  this.location = location;
2561
2715
  }
2562
- async load() {
2716
+ async load(onWarning) {
2563
2717
  const text = await this.read(this.location);
2564
2718
  if (text === void 0) return void 0;
2565
2719
  try {
2566
2720
  return parseJson(text);
2567
2721
  } catch (error) {
2568
2722
  const backup = await this.readBackup();
2569
- if (backup !== void 0) return backup;
2570
- throw new Error(`The config file ${this.location} is not valid JSON: ${error.message}`, { cause: error });
2723
+ if (isBlank(text) && backup !== void 0) {
2724
+ onWarning?.(`The config file ${this.location} is empty: using the previous version, ${this.location}.bak`);
2725
+ return backup;
2726
+ }
2727
+ const hint = backup === void 0 ? "" : `. Fix it, or copy the previous version, ${this.location}.bak, over it`;
2728
+ throw new Error(`The config file ${this.location} is not valid JSON: ${error.message}${hint}`, { cause: error });
2571
2729
  }
2572
2730
  }
2573
2731
  /**
2574
2732
  * Writes a temporary file, flushes it to disk and renames it, so a crash never leaves half a
2575
- * file. The previous file is kept as `config.json.bak` for `load` to fall back on.
2733
+ * file. The previous file is kept (`keepPrevious`).
2576
2734
  */
2577
- async save(file) {
2578
- await fs.mkdir(path.dirname(this.location), { recursive: true });
2735
+ async save(file, onWarning) {
2736
+ await fs$1.mkdir(path.dirname(this.location), { recursive: true });
2579
2737
  const temporary = `${this.location}.${process.pid}.tmp`;
2580
2738
  try {
2581
- const handle = await fs.open(temporary, "w");
2739
+ const handle = await fs$1.open(temporary, "w");
2582
2740
  try {
2583
2741
  await handle.writeFile(`${JSON.stringify(file, null, 2)}\n`, "utf8");
2584
2742
  await handle.sync();
2585
2743
  } finally {
2586
2744
  await handle.close();
2587
2745
  }
2588
- if (await this.isValid(this.location)) await fs.copyFile(this.location, `${this.location}.bak`);
2589
- await fs.rename(temporary, this.location);
2746
+ await this.keepPrevious(onWarning);
2747
+ await fs$1.rename(temporary, this.location);
2590
2748
  } catch (error) {
2591
- await fs.rm(temporary, { force: true });
2749
+ await fs$1.rm(temporary, { force: true });
2592
2750
  throw error;
2593
2751
  }
2594
2752
  }
2753
+ /**
2754
+ * Keeps the file a save is about to replace: one that parses as `config.json.bak`, for `load`
2755
+ * to fall back on, so a broken one never overwrites a good one. A broken one (edited while the
2756
+ * bridge ran) as `config.json.broken`. A blank one holds nothing to keep.
2757
+ */
2758
+ async keepPrevious(onWarning) {
2759
+ const text = await this.read(this.location);
2760
+ if (text === void 0 || isBlank(text)) return;
2761
+ if (isJson(text)) {
2762
+ await fs$1.copyFile(this.location, `${this.location}.bak`);
2763
+ return;
2764
+ }
2765
+ const kept = `${this.location}.broken`;
2766
+ await fs$1.copyFile(this.location, kept);
2767
+ onWarning?.(`The config file ${this.location} was not valid JSON: kept as ${kept} before saving over it`);
2768
+ }
2595
2769
  async read(file) {
2596
2770
  try {
2597
- return await fs.readFile(file, "utf8");
2771
+ return await fs$1.readFile(file, "utf8");
2598
2772
  } catch (error) {
2599
2773
  if (error.code === "ENOENT") return void 0;
2600
2774
  throw new Error(`Cannot read the config file ${file}: ${error.message}`, { cause: error });
@@ -2608,21 +2782,133 @@ var FsConfigStore = class {
2608
2782
  return;
2609
2783
  }
2610
2784
  }
2611
- async isValid(file) {
2612
- try {
2613
- const text = await this.read(file);
2614
- if (text === void 0) return false;
2615
- parseJson(text);
2616
- return true;
2617
- } catch {
2618
- return false;
2619
- }
2620
- }
2621
2785
  };
2622
2786
  /** `JSON.parse` that accepts a leading byte order mark (Notepad and PowerShell write one). */
2623
2787
  function parseJson(text) {
2624
2788
  return JSON.parse(text.replace(/^\uFEFF/, ""));
2625
2789
  }
2790
+ function isJson(text) {
2791
+ try {
2792
+ parseJson(text);
2793
+ return true;
2794
+ } catch {
2795
+ return false;
2796
+ }
2797
+ }
2798
+ /** Empty, or only white space and NUL bytes: what a crash can leave of a file. */
2799
+ function isBlank(text) {
2800
+ return [...text].every((char) => char === "\0" || char.trim() === "");
2801
+ }
2802
+ // src/adapters/out/log/async-console.ts
2803
+ const MAX_PENDING_BYTES = 1048576;
2804
+ const FLUSH_TIMEOUT_MS = 1e3;
2805
+ /**
2806
+ * Hands text to `channel` without ever blocking. While the console is stuck, text piles up to
2807
+ * `maxPendingBytes`, then new lines are dropped (the log file keeps everything). When the console
2808
+ * takes text again, a line says how many were dropped.
2809
+ */
2810
+ function createAsyncConsole(options) {
2811
+ const { channel, fallback, maxPendingBytes = MAX_PENDING_BYTES } = options;
2812
+ let pending = 0;
2813
+ let dropped = 0;
2814
+ let failed = false;
2815
+ let nextFlush = 0;
2816
+ const waiting = /* @__PURE__ */ new Map();
2817
+ channel.onMessage((message) => {
2818
+ if ("written" in message) {
2819
+ pending = Math.max(0, pending - message.written);
2820
+ return;
2821
+ }
2822
+ waiting.get(message.flushed)?.();
2823
+ });
2824
+ channel.onFailure(() => {
2825
+ failed = true;
2826
+ for (const done of waiting.values()) done();
2827
+ });
2828
+ return {
2829
+ write(text) {
2830
+ if (failed) return fallback(text);
2831
+ if (pending >= maxPendingBytes) {
2832
+ dropped += 1;
2833
+ return;
2834
+ }
2835
+ if (dropped > 0) {
2836
+ const notice = `console output was blocked, ${dropped} lines dropped (see the log file)\n`;
2837
+ dropped = 0;
2838
+ pending += Buffer.byteLength(notice);
2839
+ channel.post(notice);
2840
+ }
2841
+ pending += Buffer.byteLength(text);
2842
+ channel.post(text);
2843
+ },
2844
+ flush(timeoutMs = FLUSH_TIMEOUT_MS) {
2845
+ if (failed) return Promise.resolve();
2846
+ return new Promise((resolve) => {
2847
+ const id = nextFlush++;
2848
+ const finish = () => {
2849
+ clearTimeout(timer);
2850
+ waiting.delete(id);
2851
+ resolve();
2852
+ };
2853
+ const timer = setTimeout(finish, timeoutMs);
2854
+ waiting.set(id, finish);
2855
+ channel.requestFlush(id);
2856
+ });
2857
+ }
2858
+ };
2859
+ }
2860
+ const WORKER_SOURCE = `
2861
+ const { parentPort, workerData } = require('node:worker_threads');
2862
+ const tty = require('node:tty');
2863
+ const stream = new tty.WriteStream(workerData.fd);
2864
+ stream.on('error', () => {});
2865
+ parentPort.on('message', (message) => {
2866
+ if (message.flush !== undefined) {
2867
+ stream.write('', () => parentPort.postMessage({ flushed: message.flush }));
2868
+ return;
2869
+ }
2870
+ const bytes = Buffer.byteLength(message.text);
2871
+ stream.write(message.text, () => parentPort.postMessage({ written: bytes }));
2872
+ });
2873
+ `;
2874
+ function workerChannel(fd) {
2875
+ const worker = new Worker(WORKER_SOURCE, {
2876
+ eval: true,
2877
+ workerData: { fd }
2878
+ });
2879
+ worker.unref();
2880
+ return {
2881
+ post: (text) => worker.postMessage({ text }),
2882
+ requestFlush: (id) => worker.postMessage({ flush: id }),
2883
+ onMessage: (listener) => worker.on("message", listener),
2884
+ onFailure: (listener) => {
2885
+ worker.on("error", listener);
2886
+ worker.on("exit", listener);
2887
+ }
2888
+ };
2889
+ }
2890
+ let console_;
2891
+ /**
2892
+ * A writer for stdout that can't block the bridge, or `undefined` when stdout is not a terminal
2893
+ * (a pipe or file has no selection mode, and `process.stdout` is fine there).
2894
+ */
2895
+ function terminalWriter(stream = process.stdout) {
2896
+ if (stream.isTTY !== true) return void 0;
2897
+ try {
2898
+ console_ ??= createAsyncConsole({
2899
+ channel: workerChannel(1),
2900
+ fallback: (text) => void stream.write(text)
2901
+ });
2902
+ } catch {
2903
+ return;
2904
+ }
2905
+ const writer = console_;
2906
+ return (text) => writer.write(text);
2907
+ }
2908
+ /** Waits (briefly) until the terminal writer has written everything. */
2909
+ function flushTerminal() {
2910
+ return console_?.flush() ?? Promise.resolve();
2911
+ }
2626
2912
  // src/adapters/out/memory/in-process-event-bus.ts
2627
2913
  /** Synchronous in-process event bus. A failing listener doesn't stop the others. */
2628
2914
  var InProcessEventBus = class {
@@ -2704,44 +2990,224 @@ function defaultPlaywrightDir(platform = process.platform, env = process.env, ho
2704
2990
  home
2705
2991
  });
2706
2992
  }
2707
- // src/application/services/bridge-lifecycle-service.ts
2708
- /** The bridge's state from `starting` over `ready` to `stopping`, and the shutdown order. */
2709
- var BridgeLifecycleService = class {
2710
- deps;
2711
- stopping;
2712
- constructor(deps) {
2713
- this.deps = deps;
2714
- }
2715
- start() {
2716
- this.deps.startServices().then(() => {
2717
- if (this.stopping !== void 0) return;
2718
- this.deps.state.setState("ready");
2719
- this.deps.logger.info(this.deps.readyMessage());
2720
- });
2721
- }
2722
- stop(reason) {
2723
- this.stopping ??= this.shutdown(reason);
2724
- return this.stopping;
2725
- }
2726
- async shutdown(reason) {
2727
- const { state, pending, stopOrder, logger } = this.deps;
2728
- state.setState("stopping");
2729
- logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
2730
- for (const part of pending) part.shutdown();
2731
- const errors = [];
2732
- for (const part of stopOrder) try {
2733
- await part.stop();
2734
- } catch (error) {
2735
- logger.error(`shutdown failed: ${String(error)}`);
2736
- errors.push(error);
2737
- }
2738
- if (errors.length === 1) throw errors[0];
2739
- if (errors.length > 1) throw new AggregateError(errors, "shutdown failed");
2740
- logger.info("stopped");
2741
- }
2993
+ // src/adapters/out/process/process-tree.ts
2994
+ /** How long the process group gets after `SIGTERM` before `SIGKILL` (not on Windows). */
2995
+ const TERM_GRACE_MS = 3e3;
2996
+ /**
2997
+ * Spawn options for a child whose whole tree `killTree` can end. On POSIX the child leads its own
2998
+ * process group. On Windows that isn't needed (`taskkill /T` walks the tree), and `detached`
2999
+ * there would open a new console window.
3000
+ */
3001
+ const treeSpawnOptions = {
3002
+ detached: process.platform !== "win32",
3003
+ windowsHide: true
2742
3004
  };
2743
- // src/application/services/child-services-service.ts
2744
- /** Runs the Playwright server and Playwright MCP as the configuration says. */
3005
+ function hasExited(child) {
3006
+ return child.exitCode !== null || child.signalCode !== null;
3007
+ }
3008
+ function killGroup(pid, signal) {
3009
+ try {
3010
+ process.kill(-pid, signal);
3011
+ } catch {}
3012
+ }
3013
+ /** Resolves after `ms`, or when `promise` settles, whichever comes first. */
3014
+ async function within(promise, ms) {
3015
+ let timer;
3016
+ await Promise.race([promise.catch(() => void 0), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
3017
+ clearTimeout(timer);
3018
+ }
3019
+ const exec = (file, args, timeoutMs) => new Promise((resolve) => {
3020
+ execFile(file, [...args], {
3021
+ windowsHide: true,
3022
+ timeout: timeoutMs,
3023
+ killSignal: "SIGKILL"
3024
+ }, (error, stdout) => resolve({
3025
+ ok: error === null,
3026
+ stdout: String(stdout)
3027
+ }));
3028
+ });
3029
+ const TOOL_TIMEOUT_MS = 5e3;
3030
+ /** Trees that may still have processes, for `killAllTreesNow`. */
3031
+ const trees = /* @__PURE__ */ new Set();
3032
+ /**
3033
+ * Remembers a child spawned with `treeSpawnOptions`, so `killAllTreesNow` can end it when the
3034
+ * bridge has to exit without stopping gracefully. `killTree` forgets it; so does `releaseTree`.
3035
+ */
3036
+ function trackTree(child) {
3037
+ trees.add(child);
3038
+ }
3039
+ /** Forgets a child that ended on its own and left nothing behind to kill. */
3040
+ function releaseTree(child) {
3041
+ trees.delete(child);
3042
+ }
3043
+ /**
3044
+ * Ends every tracked tree at once and synchronously, without waiting for anything. For a forced
3045
+ * exit (watchdog, second Ctrl+C), when the graceful `killTree` has no time left: exiting without
3046
+ * this leaves the browsers of the Playwright server behind.
3047
+ */
3048
+ function killAllTreesNow(platform = process.platform) {
3049
+ for (const child of trees) {
3050
+ const { pid } = child;
3051
+ if (pid === void 0) continue;
3052
+ if (platform === "win32") spawnSync("taskkill", [
3053
+ "/T",
3054
+ "/F",
3055
+ "/PID",
3056
+ String(pid)
3057
+ ], {
3058
+ windowsHide: true,
3059
+ stdio: "ignore",
3060
+ timeout: TOOL_TIMEOUT_MS
3061
+ });
3062
+ else killGroup(pid, "SIGKILL");
3063
+ }
3064
+ trees.clear();
3065
+ }
3066
+ /**
3067
+ * Kills `child` and every process it started (docs/usage/operations.md#shutdown). On Windows,
3068
+ * `taskkill /T /F` limited to a few seconds (killing a process there doesn't kill its children;
3069
+ * the orphans of a child that already died are not hunted down, see
3070
+ * docs/implementation/decisions.md#child-process-trees-are-killed-by-the-bridge-not-the-os).
3071
+ * Elsewhere `SIGTERM` to the process group, then `SIGKILL` to whatever is left. Resolves
3072
+ * once `child` has exited, or after a deadline if it can't be killed. Never rejects.
3073
+ * `child` must have been spawned with `treeSpawnOptions`.
3074
+ */
3075
+ async function killTree(child, options = {}) {
3076
+ const { platform = process.platform, toolTimeoutMs = TOOL_TIMEOUT_MS } = options;
3077
+ const { exitTimeoutMs = TOOL_TIMEOUT_MS, exec: run = exec } = options;
3078
+ const { pid } = child;
3079
+ try {
3080
+ if (pid === void 0) return;
3081
+ const exited = hasExited(child) ? Promise.resolve() : once(child, "exit");
3082
+ if (platform === "win32") {
3083
+ if (!hasExited(child)) await run("taskkill", [
3084
+ "/T",
3085
+ "/F",
3086
+ "/PID",
3087
+ String(pid)
3088
+ ], toolTimeoutMs);
3089
+ await within(exited, exitTimeoutMs);
3090
+ return;
3091
+ }
3092
+ killGroup(pid, "SIGTERM");
3093
+ await within(exited, TERM_GRACE_MS);
3094
+ killGroup(pid, "SIGKILL");
3095
+ await within(exited, exitTimeoutMs);
3096
+ } finally {
3097
+ trees.delete(child);
3098
+ }
3099
+ }
3100
+ /** Writes each line of the child's stdout as `info` and of its stderr as `warn`. */
3101
+ function pipeLines(child, output) {
3102
+ if (child.stdout) readline.createInterface({
3103
+ input: child.stdout,
3104
+ crlfDelay: Infinity
3105
+ }).on("line", (line) => output.info(line));
3106
+ if (child.stderr) readline.createInterface({
3107
+ input: child.stderr,
3108
+ crlfDelay: Infinity
3109
+ }).on("line", (line) => output.warn(line));
3110
+ }
3111
+ // src/application/shared/abort.ts
3112
+ /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
3113
+ function abortReason(signal) {
3114
+ const reason = signal.reason;
3115
+ return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
3116
+ }
3117
+ /**
3118
+ * The reason of the bridge's shutdown signal, which pending requests (waits, captures, input) end
3119
+ * with.
3120
+ */
3121
+ const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
3122
+ /**
3123
+ * The signal of one request: aborts with the reason of the first of `signals` that aborts, or at
3124
+ * once if one already has (then the first of them in the list). `undefined` ones are skipped.
3125
+ * `dispose` takes the listeners off them again: call it when the request ends, or a long-lived
3126
+ * signal such as the shutdown's keeps them. Not `AbortSignal.any`, which keeps memory for every
3127
+ * signal made of a long-lived one (docs/implementation/decisions.md#one-shutdown-signal).
3128
+ */
3129
+ function linkSignals(...signals) {
3130
+ const controller = new AbortController();
3131
+ const removers = [];
3132
+ for (const source of signals) {
3133
+ if (source === void 0) continue;
3134
+ const abort = () => controller.abort(abortReason(source));
3135
+ if (source.aborted) {
3136
+ abort();
3137
+ break;
3138
+ }
3139
+ source.addEventListener("abort", abort, { once: true });
3140
+ removers.push(() => source.removeEventListener("abort", abort));
3141
+ }
3142
+ return {
3143
+ signal: controller.signal,
3144
+ dispose: () => {
3145
+ for (const remove of removers) remove();
3146
+ }
3147
+ };
3148
+ }
3149
+ // src/application/services/bridge-lifecycle-service.ts
3150
+ /**
3151
+ * The bridge's state from `starting` over `ready` to `stopping`, and the order of startup and
3152
+ * shutdown.
3153
+ */
3154
+ var BridgeLifecycleService = class {
3155
+ deps;
3156
+ stopping;
3157
+ constructor(deps) {
3158
+ this.deps = deps;
3159
+ }
3160
+ async start() {
3161
+ const ports = await this.listen();
3162
+ await this.deps.httpListening(ports.http);
3163
+ this.deps.services.startEnabled().then(() => {
3164
+ if (this.stopping !== void 0) return;
3165
+ this.deps.state.setState("ready");
3166
+ this.deps.logger.info(this.deps.readyMessage(ports));
3167
+ });
3168
+ return ports;
3169
+ }
3170
+ stop(reason) {
3171
+ this.stopping ??= this.shutdown(reason);
3172
+ return this.stopping;
3173
+ }
3174
+ /** TCP first, so no speech is lost while the rest starts. It stops again if HTTP fails. */
3175
+ async listen() {
3176
+ const { tcp, http } = this.deps;
3177
+ const tcpPort = await tcp.start();
3178
+ try {
3179
+ return {
3180
+ tcp: tcpPort,
3181
+ http: await http.start()
3182
+ };
3183
+ } catch (error) {
3184
+ await tcp.stop();
3185
+ throw error;
3186
+ }
3187
+ }
3188
+ async shutdown(reason) {
3189
+ const { state, shutdown, tcp, http, services, logger } = this.deps;
3190
+ state.setState("stopping");
3191
+ logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
3192
+ shutdown.abort(shuttingDown());
3193
+ const errors = [];
3194
+ for (const stop of [
3195
+ () => http.stop(),
3196
+ () => tcp.stop(),
3197
+ () => services.stopAll()
3198
+ ]) try {
3199
+ await stop();
3200
+ } catch (error) {
3201
+ logger.error(`shutdown failed: ${String(error)}`);
3202
+ errors.push(error);
3203
+ }
3204
+ if (errors.length === 1) throw errors[0];
3205
+ if (errors.length > 1) throw new AggregateError(errors, "shutdown failed");
3206
+ logger.info("stopped");
3207
+ }
3208
+ };
3209
+ // src/application/services/child-services-service.ts
3210
+ /** Runs the Playwright server and Playwright MCP as the configuration says. */
2745
3211
  var ChildServicesService = class {
2746
3212
  deps;
2747
3213
  constructor(deps) {
@@ -2965,7 +3431,7 @@ var ConfigService = class {
2965
3431
  const patched = configFields(changes);
2966
3432
  if ([...patched].some(([field, value]) => !same(saved.get(field), value))) {
2967
3433
  const file = mergePatch(this.file, changes);
2968
- await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}));
3434
+ await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}), (warning) => this.deps.logger.warn(warning));
2969
3435
  this.file = file;
2970
3436
  }
2971
3437
  this.saved = merged;
@@ -2985,14 +3451,6 @@ var ConfigService = class {
2985
3451
  // src/application/ports/in/capture-input.ts
2986
3452
  /** Defaults and ranges of the capture options, in milliseconds. */
2987
3453
  const CAPTURE_LIMITS = API_LIMITS.capture;
2988
- // src/application/shared/abort.ts
2989
- /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
2990
- function abortReason(signal) {
2991
- const reason = signal.reason;
2992
- return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
2993
- }
2994
- /** What pending requests (waits, captures) end with when the bridge shuts down. */
2995
- const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
2996
3454
  // src/domain/seq-cursor.ts
2997
3455
  /**
2998
3456
  * A follower's position in the speech log. `SpeechLog` gives every entry the next `seq`, strictly
@@ -3028,7 +3486,7 @@ var SeqCursor = class {
3028
3486
  * buffer follows. Without it, such a `since` waits for entries above it (what the wait means by
3029
3487
  * `since`; it ignores `truncated`).
3030
3488
  */
3031
- function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, listener, { pace, onError } = {}) {
3489
+ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, listener, { pace, onCaughtUp, onError } = {}) {
3032
3490
  const { log, events } = deps;
3033
3491
  let stale = staleSince === "replay" && requested !== null && requested > log.headSeq;
3034
3492
  const since = stale ? 0 : requested;
@@ -3052,8 +3510,17 @@ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, l
3052
3510
  type: "position",
3053
3511
  seq: log.headSeq
3054
3512
  });
3513
+ onCaughtUp?.();
3055
3514
  return stop;
3056
3515
  }
3516
+ /** The newest `seq` buffered at the start: the replay has caught up once it is past it. */
3517
+ const head = log.headSeq;
3518
+ let caughtUp = false;
3519
+ const reportCaughtUp = () => {
3520
+ if (caughtUp) return;
3521
+ caughtUp = true;
3522
+ onCaughtUp?.();
3523
+ };
3057
3524
  /** Replays from the cursor until `pace` pauses it (its promise) or it has caught up. */
3058
3525
  const step = () => {
3059
3526
  for (;;) {
@@ -3066,11 +3533,13 @@ function followLog(deps, { since: requested, sessionId, staleSince = "wait" }, l
3066
3533
  type: "entry",
3067
3534
  entry
3068
3535
  });
3536
+ if (cursor.position >= head) reportCaughtUp();
3069
3537
  const paused = pace?.();
3070
3538
  if (paused) return paused;
3071
3539
  }
3072
3540
  if (!hasMore) {
3073
3541
  replaying = false;
3542
+ reportCaughtUp();
3074
3543
  return;
3075
3544
  }
3076
3545
  }
@@ -3129,8 +3598,6 @@ const toError = (error) => error instanceof Error ? error : new Error(String(err
3129
3598
  */
3130
3599
  var InputCaptureService = class {
3131
3600
  deps;
3132
- pending = /* @__PURE__ */ new Set();
3133
- closed = false;
3134
3601
  constructor(deps) {
3135
3602
  this.deps = deps;
3136
3603
  }
@@ -3140,22 +3607,11 @@ var InputCaptureService = class {
3140
3607
  pressKeys({ capture, signal, ...request }) {
3141
3608
  return this.run(capture, signal, (hooks) => this.deps.input.pressKeys(request, hooks));
3142
3609
  }
3143
- /**
3144
- * Rejects all pending captures, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
3145
- * lifecycle port: only the composition root calls it.
3146
- */
3147
- shutdown() {
3148
- this.closed = true;
3149
- for (const stop of [...this.pending]) stop.abort(shuttingDown());
3150
- }
3151
3610
  async run(capture, signal, send) {
3152
- if (this.closed) throw shuttingDown();
3611
+ this.deps.shutdown.throwIfAborted();
3153
3612
  const options = parseOptions(capture);
3154
3613
  if (signal?.aborted) throw abortReason(signal);
3155
- const stop = new AbortController();
3156
- const onAbort = () => stop.abort(abortReason(signal));
3157
- signal?.addEventListener("abort", onAbort, { once: true });
3158
- this.pending.add(stop);
3614
+ const stop = linkSignals(this.deps.shutdown, signal);
3159
3615
  try {
3160
3616
  let startSeq = 0;
3161
3617
  return {
@@ -3170,8 +3626,7 @@ var InputCaptureService = class {
3170
3626
  ...await this.record(startSeq, options, stop.signal)
3171
3627
  };
3172
3628
  } finally {
3173
- signal?.removeEventListener("abort", onAbort);
3174
- this.pending.delete(stop);
3629
+ stop.dispose();
3175
3630
  }
3176
3631
  }
3177
3632
  /**
@@ -3267,13 +3722,9 @@ var InputCaptureService = class {
3267
3722
  return this.deps.clock.now().getTime();
3268
3723
  }
3269
3724
  };
3270
- // src/application/services/window-focus-service.ts
3271
- /** How long a `title` may take to show up in the window title, and how often it is looked for. */
3272
- const TITLE_WAIT = {
3273
- timeoutMs: 2e3,
3274
- pollMs: 50
3275
- };
3276
- const TARGETS = {
3725
+ // src/application/shared/browser-targets.ts
3726
+ /** The service whose process tree holds a target's browser windows, and its name in messages. */
3727
+ const BROWSER_TARGETS = {
3277
3728
  mcp: {
3278
3729
  service: "mcp",
3279
3730
  name: "Playwright MCP"
@@ -3283,6 +3734,12 @@ const TARGETS = {
3283
3734
  name: "the Playwright server"
3284
3735
  }
3285
3736
  };
3737
+ // src/application/services/window-focus-service.ts
3738
+ /** How long a `title` may take to show up in the window title, and how often it is looked for. */
3739
+ const TITLE_WAIT = {
3740
+ timeoutMs: 2e3,
3741
+ pollMs: 50
3742
+ };
3286
3743
  /**
3287
3744
  * Brings a window of a browser the bridge started to the front
3288
3745
  * (docs/usage/native-input.md#bringing-the-browser-to-the-front): the front-most visible
@@ -3295,7 +3752,7 @@ var WindowFocusService = class {
3295
3752
  this.deps = deps;
3296
3753
  }
3297
3754
  async focus({ target, title, signal }) {
3298
- const known = Object.hasOwn(TARGETS, target) ? TARGETS[target] : void 0;
3755
+ const known = Object.hasOwn(BROWSER_TARGETS, target) ? BROWSER_TARGETS[target] : void 0;
3299
3756
  if (!known) throw invalidField("target", "must be mcp or playwright");
3300
3757
  if (title !== void 0 && (title === "" || title.length > API_LIMITS.input.focusTitleLength)) throw invalidField("title", `must be 1 to ${API_LIMITS.input.focusTitleLength} characters`);
3301
3758
  const pid = this.deps.services[known.service].pid();
@@ -3346,11 +3803,6 @@ function parseKeyChord(chord) {
3346
3803
  }
3347
3804
  // src/application/services/native-input-service.ts
3348
3805
  const { coordinate, delayMs, maxKeys } = API_LIMITS.input;
3349
- const BUTTONS = [
3350
- "left",
3351
- "right",
3352
- "middle"
3353
- ];
3354
3806
  function checkCoordinate(field, value) {
3355
3807
  if (!Number.isInteger(value) || Math.abs(value) > coordinate) throw invalidField(field, `must be an integer from -${coordinate} to ${coordinate}`);
3356
3808
  }
@@ -3368,20 +3820,20 @@ function parseKeys(keys) {
3368
3820
  * Input nobody waits for isn't sent (docs/usage/native-input.md#when-the-client-gives-up): a
3369
3821
  * request whose signal aborts, or any request once the bridge shuts down, is dropped while it is
3370
3822
  * queued and stops between two chords.
3823
+ *
3824
+ * Keys with an `expectedTarget` are checked before every chord and stop at the first one whose
3825
+ * window in front isn't of that browser (docs/usage/native-input.md#requiring-a-target-window).
3371
3826
  */
3372
3827
  var NativeInputService = class {
3373
3828
  deps;
3374
3829
  queue = Promise.resolve();
3375
- /** One per queued or running request. */
3376
- pending = /* @__PURE__ */ new Set();
3377
- closed = false;
3378
3830
  constructor(deps) {
3379
3831
  this.deps = deps;
3380
3832
  }
3381
3833
  async click({ x, y, button = "left" }, hooks = {}) {
3382
3834
  checkCoordinate("x", x);
3383
3835
  checkCoordinate("y", y);
3384
- if (!BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
3836
+ if (!MOUSE_BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
3385
3837
  let sent = false;
3386
3838
  return this.enqueue(async (signal) => {
3387
3839
  await hooks.beforeInject?.();
@@ -3393,18 +3845,28 @@ var NativeInputService = class {
3393
3845
  return before;
3394
3846
  }, hooks.signal, () => sent ? void 0 : "click not sent");
3395
3847
  }
3396
- async pressKeys({ keys, delayMs: delay = delayMs.default }, hooks = {}) {
3848
+ async pressKeys({ keys, delayMs: delay = delayMs.default, expectedTarget }, hooks = {}) {
3397
3849
  const chords = parseKeys(keys);
3398
3850
  if (!Number.isInteger(delay) || delay < 0 || delay > delayMs.max) throw invalidField("delayMs", `must be an integer from 0 to ${delayMs.max}`);
3851
+ if (expectedTarget !== void 0 && !Object.hasOwn(BROWSER_TARGETS, expectedTarget)) throw invalidField("expectedTarget", "must be mcp or playwright");
3399
3852
  this.checkSupported(chords);
3400
3853
  const text = `keys ${typeof keys === "string" ? keys : keys.join(" ")}`;
3401
3854
  let sent = 0;
3402
3855
  return this.enqueue(async (signal) => {
3403
3856
  await hooks.beforeInject?.();
3404
- const before = await this.sentTo();
3857
+ let before = expectedTarget === void 0 ? await this.sentTo() : {};
3405
3858
  for (const [index, chord] of chords.entries()) {
3406
3859
  if (index > 0) await this.deps.clock.sleep(delay, signal);
3407
3860
  signal.throwIfAborted();
3861
+ if (expectedTarget !== void 0) {
3862
+ const progress = {
3863
+ sentChords: sent,
3864
+ totalChords: chords.length
3865
+ };
3866
+ const window = await this.requireTarget(expectedTarget, progress, text);
3867
+ if (index === 0) before = { window };
3868
+ signal.throwIfAborted();
3869
+ }
3408
3870
  await this.press(chord);
3409
3871
  sent++;
3410
3872
  }
@@ -3426,6 +3888,38 @@ var NativeInputService = class {
3426
3888
  return {};
3427
3889
  }
3428
3890
  }
3891
+ /**
3892
+ * The window in front, if it belongs to the process tree of `target`'s service. Rejects with
3893
+ * `WRONG_WINDOW` otherwise, also where that can't be told.
3894
+ */
3895
+ async requireTarget(target, progress, text) {
3896
+ const { windows, services, logger } = this.deps;
3897
+ const { service, name } = BROWSER_TARGETS[target];
3898
+ const refuse = (reason, window) => {
3899
+ const done = `${progress.sentChords} of ${progress.totalChords} chords sent`;
3900
+ logger.warn(`${text}: ${done}: ${reason}`);
3901
+ throw new AppError("WRONG_WINDOW", `${done}: ${reason}`, {
3902
+ expectedTarget: target,
3903
+ ...progress,
3904
+ ...window === void 0 ? {} : { window }
3905
+ });
3906
+ };
3907
+ const root = services[service].pid();
3908
+ if (root === null) return refuse(`${name} is not running`);
3909
+ let window;
3910
+ let tree;
3911
+ try {
3912
+ window = await windows.foregroundWindow();
3913
+ if (window === void 0) return refuse("the bridge cannot read windows here");
3914
+ if (window === null) return refuse("no window is in front", null);
3915
+ tree = await windows.processTree(root);
3916
+ } catch (error) {
3917
+ if (error instanceof AppError && error.code === "WRONG_WINDOW") throw error;
3918
+ return refuse(`the window in front could not be checked (${error instanceof Error ? error.message : String(error)})`);
3919
+ }
3920
+ if (!tree.has(window.pid)) return refuse(`the window in front ("${window.title}", pid ${window.pid}) does not belong to the browser of ${name}`, window);
3921
+ return window;
3922
+ }
3429
3923
  checkSupported(chords) {
3430
3924
  for (const key of chords.flatMap((chord) => [...chord.modifiers, chord.key])) {
3431
3925
  const reason = this.deps.injector.unsupportedReason(key);
@@ -3441,21 +3935,31 @@ var NativeInputService = class {
3441
3935
  held.push(modifier);
3442
3936
  }
3443
3937
  await injector.keyTap(key);
3444
- } finally {
3445
- for (const modifier of held.reverse()) await injector.keyUp(modifier);
3938
+ } catch (error) {
3939
+ await this.release(held);
3940
+ throw error;
3446
3941
  }
3447
- }
3448
- exclusive(task, signal) {
3449
- return this.enqueue(task, signal);
3942
+ const failed = await this.release(held);
3943
+ if (failed !== void 0) throw failed;
3450
3944
  }
3451
3945
  /**
3452
- * Stops the running input before its next chord and rejects it, the queued input and every later
3453
- * one with `SERVICE_UNAVAILABLE`. The `Shutdown` lifecycle port: only the composition root calls
3454
- * it.
3946
+ * Releases the held keys, the last one first. Every one is tried even if another fails: a
3947
+ * modifier left down would change all later input on the desktop. Resolves with the first
3948
+ * failure, `undefined` if all were released.
3455
3949
  */
3456
- shutdown() {
3457
- this.closed = true;
3458
- for (const stop of [...this.pending]) stop.abort(shuttingDown());
3950
+ async release(held) {
3951
+ let first;
3952
+ for (const key of [...held].reverse()) try {
3953
+ await this.deps.injector.keyUp(key);
3954
+ } catch (error) {
3955
+ const failure = error instanceof Error ? error : new Error(String(error));
3956
+ this.deps.logger.error(`${key} could not be released, it may still be held down (${failure.message})`);
3957
+ first ??= failure;
3958
+ }
3959
+ return first;
3960
+ }
3961
+ exclusive(task, signal) {
3962
+ return this.enqueue(task, signal);
3459
3963
  }
3460
3964
  /**
3461
3965
  * Runs `task` after the earlier ones; a failed task doesn't stop the later ones. `task` isn't
@@ -3463,12 +3967,7 @@ var NativeInputService = class {
3463
3967
  * request leaves unsent, for the log.
3464
3968
  */
3465
3969
  async enqueue(task, signal, unsent = () => void 0) {
3466
- const stop = new AbortController();
3467
- const onAbort = () => stop.abort(abortReason(signal));
3468
- if (this.closed) stop.abort(shuttingDown());
3469
- else if (signal?.aborted) onAbort();
3470
- else signal?.addEventListener("abort", onAbort, { once: true });
3471
- this.pending.add(stop);
3970
+ const stop = linkSignals(this.deps.shutdown, signal);
3472
3971
  const run = this.queue.then(() => {
3473
3972
  stop.signal.throwIfAborted();
3474
3973
  return task(stop.signal);
@@ -3481,8 +3980,7 @@ var NativeInputService = class {
3481
3980
  if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
3482
3981
  throw error;
3483
3982
  } finally {
3484
- signal?.removeEventListener("abort", onAbort);
3485
- this.pending.delete(stop);
3983
+ stop.dispose();
3486
3984
  }
3487
3985
  }
3488
3986
  };
@@ -3667,8 +4165,8 @@ function markerLabel(label) {
3667
4165
  }
3668
4166
  // src/application/services/status-service.ts
3669
4167
  /**
3670
- * `GET /api/v1/status`. The composition root moves the state from `starting` to `ready` through
3671
- * `BridgeStateControl`.
4168
+ * `GET /api/v1/status`. `BridgeLifecycleService` moves the state from `starting` to `ready` and
4169
+ * `stopping` through `BridgeStateControl`.
3672
4170
  */
3673
4171
  var StatusService = class {
3674
4172
  deps;
@@ -3697,7 +4195,8 @@ var StatusService = class {
3697
4195
  host: listener?.host ?? tcp.host,
3698
4196
  port: listener?.port ?? tcp.port,
3699
4197
  encoding: listener?.encoding ?? tcp.encoding,
3700
- connections
4198
+ connections,
4199
+ lastSpeechAt: log.lastSpeechAt ?? null
3701
4200
  },
3702
4201
  buffer: log.stats(),
3703
4202
  services: Object.fromEntries(SERVICE_NAMES.map((name) => [name, supervisors[name].status()])),
@@ -3802,13 +4301,11 @@ var LastSeen = class {
3802
4301
  */
3803
4302
  var WaitForSpeechService = class {
3804
4303
  deps;
3805
- pending = /* @__PURE__ */ new Set();
3806
- closed = false;
3807
4304
  constructor(deps) {
3808
4305
  this.deps = deps;
3809
4306
  }
3810
4307
  async wait(options) {
3811
- if (this.closed) throw shuttingDown();
4308
+ this.deps.shutdown.throwIfAborted();
3812
4309
  const { signal } = options;
3813
4310
  const since = intOption("since", options.since, {
3814
4311
  fallback: 0,
@@ -3827,29 +4324,31 @@ var WaitForSpeechService = class {
3827
4324
  const seen = new LastSeen();
3828
4325
  let done = false;
3829
4326
  let stop;
4327
+ /** The client's signal and the shutdown's. */
4328
+ const ended = linkSignals(this.deps.shutdown, signal);
3830
4329
  const finish = () => {
3831
4330
  done = true;
3832
4331
  stop?.();
3833
4332
  timer.abort();
3834
- signal?.removeEventListener("abort", onAbort);
3835
- this.pending.delete(fail);
4333
+ ended.dispose();
3836
4334
  };
3837
4335
  const fail = (error) => {
3838
4336
  finish();
3839
4337
  reject(error);
3840
4338
  };
3841
- const onAbort = () => fail(abortReason(signal));
3842
4339
  const timer = new AbortController();
3843
- this.deps.clock.sleep(timeoutMs, timer.signal).then(() => {
4340
+ const startTimer = () => {
3844
4341
  if (done) return;
3845
- finish();
3846
- resolve({
3847
- status: "timeout",
3848
- ...seen.result()
3849
- });
3850
- }, () => {});
3851
- signal?.addEventListener("abort", onAbort, { once: true });
3852
- this.pending.add(fail);
4342
+ this.deps.clock.sleep(timeoutMs, timer.signal).then(() => {
4343
+ if (done) return;
4344
+ finish();
4345
+ resolve({
4346
+ status: "timeout",
4347
+ ...seen.result()
4348
+ });
4349
+ }, () => {});
4350
+ };
4351
+ ended.signal.addEventListener("abort", () => fail(abortReason(ended.signal)), { once: true });
3853
4352
  const failed = (error) => fail(error instanceof Error ? error : new Error(String(error)));
3854
4353
  try {
3855
4354
  stop = followLog(this.deps, {
@@ -3866,6 +4365,7 @@ var WaitForSpeechService = class {
3866
4365
  });
3867
4366
  }, {
3868
4367
  pace: this.deps.pace?.(),
4368
+ onCaughtUp: startTimer,
3869
4369
  onError: failed
3870
4370
  });
3871
4371
  if (done) stop();
@@ -3874,40 +4374,7 @@ var WaitForSpeechService = class {
3874
4374
  }
3875
4375
  });
3876
4376
  }
3877
- /**
3878
- * Rejects all pending waits, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
3879
- * lifecycle port, not part of `WaitForSpeech`: only the composition root calls it.
3880
- */
3881
- shutdown() {
3882
- this.closed = true;
3883
- for (const fail of [...this.pending]) fail(shuttingDown());
3884
- }
3885
4377
  };
3886
- // src/composition/lifecycle.ts
3887
- /**
3888
- * Startup order (docs/usage/operations.md#startup): the TCP listener first, so no speech is lost
3889
- * while the rest starts, then HTTP. A failure is logged, and the TCP listener stops if HTTP fails.
3890
- */
3891
- async function startListeners(tcp, http, config, logger) {
3892
- const failed = (error) => logger.error(error instanceof ListenError ? error.message : String(error));
3893
- let tcpPort;
3894
- try {
3895
- tcpPort = await tcp.start(config.tcp);
3896
- } catch (error) {
3897
- failed(error);
3898
- throw error;
3899
- }
3900
- try {
3901
- return {
3902
- tcp: tcpPort,
3903
- http: await http.start(config.http)
3904
- };
3905
- } catch (error) {
3906
- failed(error);
3907
- await tcp.stop();
3908
- throw error;
3909
- }
3910
- }
3911
4378
  // src/composition/load-config.ts
3912
4379
  /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
3913
4380
  var ConfigError = class extends Error {
@@ -3923,12 +4390,14 @@ function checked(patch, origin) {
3923
4390
  }
3924
4391
  /**
3925
4392
  * Defaults, then the config file, then flags and environment variables. Settings of the file this
3926
- * bridge doesn't know are left out of `config` and `file` and returned in `unknown`.
4393
+ * bridge doesn't know are left out of `config` and `file` and returned in `unknown`. The store's
4394
+ * `warnings` are returned too: there is no log yet, it is built from the result.
3927
4395
  */
3928
4396
  async function loadConfig(store, overridesPatch, sourceOf) {
3929
4397
  let saved;
4398
+ const warnings = [];
3930
4399
  try {
3931
- saved = await store.load();
4400
+ saved = await store.load((message) => warnings.push(message));
3932
4401
  } catch (error) {
3933
4402
  throw new ConfigError(error.message, { cause: error });
3934
4403
  }
@@ -3946,7 +4415,8 @@ async function loadConfig(store, overridesPatch, sourceOf) {
3946
4415
  file,
3947
4416
  overrides,
3948
4417
  unknown,
3949
- ignored
4418
+ ignored,
4419
+ warnings
3950
4420
  };
3951
4421
  }
3952
4422
  // src/composition/summary.ts
@@ -4478,116 +4948,6 @@ var BridgeLog = class {
4478
4948
  }
4479
4949
  }
4480
4950
  };
4481
- // src/adapters/out/log/async-console.ts
4482
- const MAX_PENDING_BYTES = 1048576;
4483
- const FLUSH_TIMEOUT_MS = 1e3;
4484
- /**
4485
- * Hands text to `channel` without ever blocking. While the console is stuck, text piles up to
4486
- * `maxPendingBytes`, then new lines are dropped (the log file keeps everything). When the console
4487
- * takes text again, a line says how many were dropped.
4488
- */
4489
- function createAsyncConsole(options) {
4490
- const { channel, fallback, maxPendingBytes = MAX_PENDING_BYTES } = options;
4491
- let pending = 0;
4492
- let dropped = 0;
4493
- let failed = false;
4494
- let nextFlush = 0;
4495
- const waiting = /* @__PURE__ */ new Map();
4496
- channel.onMessage((message) => {
4497
- if ("written" in message) {
4498
- pending = Math.max(0, pending - message.written);
4499
- return;
4500
- }
4501
- waiting.get(message.flushed)?.();
4502
- });
4503
- channel.onFailure(() => {
4504
- failed = true;
4505
- for (const done of waiting.values()) done();
4506
- });
4507
- return {
4508
- write(text) {
4509
- if (failed) return fallback(text);
4510
- if (pending >= maxPendingBytes) {
4511
- dropped += 1;
4512
- return;
4513
- }
4514
- if (dropped > 0) {
4515
- const notice = `console output was blocked, ${dropped} lines dropped (see the log file)\n`;
4516
- dropped = 0;
4517
- pending += Buffer.byteLength(notice);
4518
- channel.post(notice);
4519
- }
4520
- pending += Buffer.byteLength(text);
4521
- channel.post(text);
4522
- },
4523
- flush(timeoutMs = FLUSH_TIMEOUT_MS) {
4524
- if (failed) return Promise.resolve();
4525
- return new Promise((resolve) => {
4526
- const id = nextFlush++;
4527
- const finish = () => {
4528
- clearTimeout(timer);
4529
- waiting.delete(id);
4530
- resolve();
4531
- };
4532
- const timer = setTimeout(finish, timeoutMs);
4533
- waiting.set(id, finish);
4534
- channel.requestFlush(id);
4535
- });
4536
- }
4537
- };
4538
- }
4539
- const WORKER_SOURCE = `
4540
- const { parentPort, workerData } = require('node:worker_threads');
4541
- const tty = require('node:tty');
4542
- const stream = new tty.WriteStream(workerData.fd);
4543
- stream.on('error', () => {});
4544
- parentPort.on('message', (message) => {
4545
- if (message.flush !== undefined) {
4546
- stream.write('', () => parentPort.postMessage({ flushed: message.flush }));
4547
- return;
4548
- }
4549
- const bytes = Buffer.byteLength(message.text);
4550
- stream.write(message.text, () => parentPort.postMessage({ written: bytes }));
4551
- });
4552
- `;
4553
- function workerChannel(fd) {
4554
- const worker = new Worker(WORKER_SOURCE, {
4555
- eval: true,
4556
- workerData: { fd }
4557
- });
4558
- worker.unref();
4559
- return {
4560
- post: (text) => worker.postMessage({ text }),
4561
- requestFlush: (id) => worker.postMessage({ flush: id }),
4562
- onMessage: (listener) => worker.on("message", listener),
4563
- onFailure: (listener) => {
4564
- worker.on("error", listener);
4565
- worker.on("exit", listener);
4566
- }
4567
- };
4568
- }
4569
- let console_;
4570
- /**
4571
- * A writer for stdout that can't block the bridge, or `undefined` when stdout is not a terminal
4572
- * (a pipe or file has no selection mode, and `process.stdout` is fine there).
4573
- */
4574
- function terminalWriter(stream = process.stdout) {
4575
- if (stream.isTTY !== true) return void 0;
4576
- try {
4577
- console_ ??= createAsyncConsole({
4578
- channel: workerChannel(1),
4579
- fallback: (text) => void stream.write(text)
4580
- });
4581
- } catch {
4582
- return;
4583
- }
4584
- const writer = console_;
4585
- return (text) => writer.write(text);
4586
- }
4587
- /** Waits (briefly) until the terminal writer has written everything. */
4588
- function flushTerminal() {
4589
- return console_?.flush() ?? Promise.resolve();
4590
- }
4591
4951
  // src/adapters/out/log/console-sink.ts
4592
4952
  /**
4593
4953
  * Decides whether a console stream gets colours: `NO_COLOR` turns them off, `FORCE_COLOR`
@@ -4612,40 +4972,77 @@ function consoleSink(options = {}) {
4612
4972
  /**
4613
4973
  * Bridge log file (docs/usage/operations.md#logging): no colours, includes the speech channel.
4614
4974
  * Writes synchronously so nothing is lost on a crash. Log volume is small.
4975
+ *
4976
+ * A failure doesn't end the file log. A line that can't be written is lost, and the next one tries
4977
+ * again. A file that can't be rotated keeps growing, and rotation is tried again later.
4615
4978
  */
4616
4979
  function fileSink(file, options = {}) {
4617
4980
  const { maxBytes = 10485760, keep = 5 } = options;
4618
- const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture-bridge: log file disabled: ${error.message}\n`));
4619
- let size = 0;
4620
- let failed = false;
4981
+ const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture-bridge: ${error.message}\n`));
4982
+ /** `undefined`: unknown, the folder and the size are looked at again before the next write. */
4983
+ let size;
4984
+ let writeFailed = false;
4985
+ let rotateFailed = false;
4986
+ /** After a failed rotation: don't try again before the file has this size. */
4987
+ let rotateFrom = 0;
4988
+ const report = (what, error) => onError(new Error(`cannot ${what} the log file: ${error.message}`, { cause: error }));
4989
+ const failedWrite = (error) => {
4990
+ size = void 0;
4991
+ if (!writeFailed) report("write", error);
4992
+ writeFailed = true;
4993
+ };
4994
+ const open = () => {
4995
+ fs.mkdirSync(path.dirname(file), { recursive: true });
4996
+ return fs.existsSync(file) ? fs.statSync(file).size : 0;
4997
+ };
4998
+ /**
4999
+ * Moves the older files up only as far as the first free number, dropping the oldest when there
5000
+ * is none. So a rotation that fails and is tried again doesn't push out one more file each time.
5001
+ */
5002
+ const rotate = () => {
5003
+ if (keep < 1) {
5004
+ fs.rmSync(file, { force: true });
5005
+ return;
5006
+ }
5007
+ let free = 1;
5008
+ while (free < keep && fs.existsSync(`${file}.${free}`)) free++;
5009
+ fs.rmSync(`${file}.${free}`, { force: true });
5010
+ for (let i = free - 1; i >= 1; i--) fs.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
5011
+ fs.renameSync(file, `${file}.1`);
5012
+ };
5013
+ /** Rotates, and returns the size of the file to write to. */
5014
+ const tryRotate = (current) => {
5015
+ try {
5016
+ rotate();
5017
+ rotateFailed = false;
5018
+ rotateFrom = 0;
5019
+ return 0;
5020
+ } catch (error) {
5021
+ if (!rotateFailed) report("rotate", error);
5022
+ rotateFailed = true;
5023
+ rotateFrom = current + Math.ceil(maxBytes / 10);
5024
+ return current;
5025
+ }
5026
+ };
4621
5027
  try {
4622
- fs$1.mkdirSync(path.dirname(file), { recursive: true });
4623
- size = fs$1.existsSync(file) ? fs$1.statSync(file).size : 0;
5028
+ size = open();
4624
5029
  } catch (error) {
4625
- failed = true;
4626
- onError(error);
5030
+ failedWrite(error);
4627
5031
  }
4628
- const rotate = () => {
4629
- fs$1.rmSync(`${file}.${keep}`, { force: true });
4630
- for (let i = keep - 1; i >= 1; i--) if (fs$1.existsSync(`${file}.${i}`)) fs$1.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
4631
- if (keep >= 1) fs$1.renameSync(file, `${file}.1`);
4632
- else fs$1.rmSync(file, { force: true });
4633
- size = 0;
4634
- };
4635
5032
  return {
4636
5033
  colour: false,
4637
5034
  speech: true,
4638
5035
  write(line) {
4639
- if (failed) return;
4640
5036
  const data = `${line}\n`;
4641
5037
  const bytes = Buffer.byteLength(data);
4642
5038
  try {
4643
- if (size > 0 && size + bytes > maxBytes) rotate();
4644
- fs$1.appendFileSync(file, data);
5039
+ size ??= open();
5040
+ if (size > 0 && size + bytes > maxBytes && size >= rotateFrom) size = tryRotate(size);
5041
+ fs.appendFileSync(file, data);
4645
5042
  size += bytes;
5043
+ writeFailed = false;
4646
5044
  } catch (error) {
4647
- failed = true;
4648
- onError(error);
5045
+ failedWrite(error);
4649
5046
  }
4650
5047
  }
4651
5048
  };
@@ -4715,147 +5112,29 @@ function proxyRoutes(services) {
4715
5112
  upstreamPath: "/mcp",
4716
5113
  scheme: "http",
4717
5114
  target: () => services.reachability("mcp")
4718
- }];
4719
- }
4720
- // src/adapters/shared/net/port-probe.ts
4721
- /** Where to probe a listener on a wildcard host: the loopback address of that family. */
4722
- const WILDCARD_PROBE = {
4723
- "0.0.0.0": "127.0.0.1",
4724
- "::": "::1"
4725
- };
4726
- /** Whether something accepts connections on `host:port`, within `timeoutMs`. */
4727
- function portOpen(host, port, timeoutMs = 1e3) {
4728
- return new Promise((resolve) => {
4729
- const socket = net.connect({
4730
- host: WILDCARD_PROBE[host] ?? host,
4731
- port
4732
- });
4733
- const done = (open) => {
4734
- socket.destroy();
4735
- resolve(open);
4736
- };
4737
- socket.setTimeout(timeoutMs, () => done(false));
4738
- socket.once("connect", () => done(true));
4739
- socket.once("error", () => done(false));
4740
- });
4741
- }
4742
- // src/adapters/out/process/process-tree.ts
4743
- /** How long the process group gets after `SIGTERM` before `SIGKILL` (not on Windows). */
4744
- const TERM_GRACE_MS = 3e3;
4745
- /**
4746
- * Spawn options for a child whose whole tree `killTree` can end. On POSIX the child leads its own
4747
- * process group. On Windows that isn't needed (`taskkill /T` walks the tree), and `detached`
4748
- * there would open a new console window.
4749
- */
4750
- const treeSpawnOptions = {
4751
- detached: process.platform !== "win32",
4752
- windowsHide: true
4753
- };
4754
- function hasExited(child) {
4755
- return child.exitCode !== null || child.signalCode !== null;
4756
- }
4757
- function killGroup(pid, signal) {
4758
- try {
4759
- process.kill(-pid, signal);
4760
- } catch {}
4761
- }
4762
- /** Resolves after `ms`, or when `promise` settles, whichever comes first. */
4763
- async function within(promise, ms) {
4764
- let timer;
4765
- await Promise.race([promise.catch(() => void 0), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
4766
- clearTimeout(timer);
4767
- }
4768
- const exec = (file, args, timeoutMs) => new Promise((resolve) => {
4769
- execFile(file, [...args], {
4770
- windowsHide: true,
4771
- timeout: timeoutMs,
4772
- killSignal: "SIGKILL"
4773
- }, (error, stdout) => resolve({
4774
- ok: error === null,
4775
- stdout: String(stdout)
4776
- }));
4777
- });
4778
- const TOOL_TIMEOUT_MS = 5e3;
4779
- /** Trees that may still have processes, for `killAllTreesNow`. */
4780
- const trees = /* @__PURE__ */ new Set();
4781
- /**
4782
- * Remembers a child spawned with `treeSpawnOptions`, so `killAllTreesNow` can end it when the
4783
- * bridge has to exit without stopping gracefully. `killTree` forgets it; so does `releaseTree`.
4784
- */
4785
- function trackTree(child) {
4786
- trees.add(child);
4787
- }
4788
- /** Forgets a child that ended on its own and left nothing behind to kill. */
4789
- function releaseTree(child) {
4790
- trees.delete(child);
4791
- }
4792
- /**
4793
- * Ends every tracked tree at once and synchronously, without waiting for anything. For a forced
4794
- * exit (watchdog, second Ctrl+C), when the graceful `killTree` has no time left: exiting without
4795
- * this leaves the browsers of the Playwright server behind.
4796
- */
4797
- function killAllTreesNow(platform = process.platform) {
4798
- for (const child of trees) {
4799
- const { pid } = child;
4800
- if (pid === void 0) continue;
4801
- if (platform === "win32") spawnSync("taskkill", [
4802
- "/T",
4803
- "/F",
4804
- "/PID",
4805
- String(pid)
4806
- ], {
4807
- windowsHide: true,
4808
- stdio: "ignore",
4809
- timeout: TOOL_TIMEOUT_MS
4810
- });
4811
- else killGroup(pid, "SIGKILL");
4812
- }
4813
- trees.clear();
4814
- }
4815
- /**
4816
- * Kills `child` and every process it started (docs/usage/operations.md#shutdown). On Windows,
4817
- * `taskkill /T /F` limited to a few seconds (killing a process there doesn't kill its children;
4818
- * the orphans of a child that already died are not hunted down, see
4819
- * docs/implementation/decisions.md#child-process-trees-are-killed-by-the-bridge-not-the-os).
4820
- * Elsewhere `SIGTERM` to the process group, then `SIGKILL` to whatever is left. Resolves
4821
- * once `child` has exited, or after a deadline if it can't be killed. Never rejects.
4822
- * `child` must have been spawned with `treeSpawnOptions`.
4823
- */
4824
- async function killTree(child, options = {}) {
4825
- const { platform = process.platform, toolTimeoutMs = TOOL_TIMEOUT_MS } = options;
4826
- const { exitTimeoutMs = TOOL_TIMEOUT_MS, exec: run = exec } = options;
4827
- const { pid } = child;
4828
- try {
4829
- if (pid === void 0) return;
4830
- const exited = hasExited(child) ? Promise.resolve() : once(child, "exit");
4831
- if (platform === "win32") {
4832
- if (!hasExited(child)) await run("taskkill", [
4833
- "/T",
4834
- "/F",
4835
- "/PID",
4836
- String(pid)
4837
- ], toolTimeoutMs);
4838
- await within(exited, exitTimeoutMs);
4839
- return;
4840
- }
4841
- killGroup(pid, "SIGTERM");
4842
- await within(exited, TERM_GRACE_MS);
4843
- killGroup(pid, "SIGKILL");
4844
- await within(exited, exitTimeoutMs);
4845
- } finally {
4846
- trees.delete(child);
4847
- }
4848
- }
4849
- /** Writes each line of the child's stdout as `info` and of its stderr as `warn`. */
4850
- function pipeLines(child, output) {
4851
- if (child.stdout) readline.createInterface({
4852
- input: child.stdout,
4853
- crlfDelay: Infinity
4854
- }).on("line", (line) => output.info(line));
4855
- if (child.stderr) readline.createInterface({
4856
- input: child.stderr,
4857
- crlfDelay: Infinity
4858
- }).on("line", (line) => output.warn(line));
5115
+ }];
5116
+ }
5117
+ // src/adapters/shared/net/port-probe.ts
5118
+ /** Where to probe a listener on a wildcard host: the loopback address of that family. */
5119
+ const WILDCARD_PROBE = {
5120
+ "0.0.0.0": "127.0.0.1",
5121
+ "::": "::1"
5122
+ };
5123
+ /** Whether something accepts connections on `host:port`, within `timeoutMs`. */
5124
+ function portOpen(host, port, timeoutMs = 1e3) {
5125
+ return new Promise((resolve) => {
5126
+ const socket = net.connect({
5127
+ host: WILDCARD_PROBE[host] ?? host,
5128
+ port
5129
+ });
5130
+ const done = (open) => {
5131
+ socket.destroy();
5132
+ resolve(open);
5133
+ };
5134
+ socket.setTimeout(timeoutMs, () => done(false));
5135
+ socket.once("connect", () => done(true));
5136
+ socket.once("error", () => done(false));
5137
+ });
4859
5138
  }
4860
5139
  // src/adapters/out/process/child-process-supervisor.ts
4861
5140
  /** How long the port may take to open after the start, before it counts as a crash. */
@@ -4873,6 +5152,7 @@ var ChildProcessSupervisor = class {
4873
5152
  state = "stopped";
4874
5153
  restarts = 0;
4875
5154
  exitCode = null;
5155
+ lastError = null;
4876
5156
  crashesInRow = 0;
4877
5157
  child = null;
4878
5158
  runningSince = null;
@@ -4897,7 +5177,8 @@ var ChildProcessSupervisor = class {
4897
5177
  version,
4898
5178
  port,
4899
5179
  restarts: this.restarts,
4900
- exitCode: this.exitCode
5180
+ exitCode: this.exitCode,
5181
+ lastError: this.lastError
4901
5182
  };
4902
5183
  }
4903
5184
  start() {
@@ -4907,6 +5188,7 @@ var ChildProcessSupervisor = class {
4907
5188
  this.restarts = 0;
4908
5189
  this.crashesInRow = 0;
4909
5190
  this.exitCode = null;
5191
+ this.lastError = null;
4910
5192
  this.launch();
4911
5193
  }
4912
5194
  return settled;
@@ -4947,20 +5229,23 @@ var ChildProcessSupervisor = class {
4947
5229
  this.setState("starting");
4948
5230
  this.launchedAt = Date.now();
4949
5231
  this.options.logger.info(`starting ${this.options.name} ${settings.version}`);
5232
+ const failed = (how, error) => {
5233
+ if (!current()) return;
5234
+ const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
5235
+ this.options.logger.error(`${this.options.name} ${cause}`);
5236
+ this.crashed(null, "failed to start", cause);
5237
+ };
4950
5238
  this.options.prepare(settings, abort.signal).then(async (command) => {
4951
5239
  if (!current()) return;
4952
5240
  if (await portOpen(settings.host, settings.port)) {
4953
5241
  if (!current()) return;
4954
- this.options.logger.error(`${this.options.name}: port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`);
4955
- this.crashed(null, "could not start");
5242
+ const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
5243
+ this.options.logger.error(`${this.options.name}: ${cause}`);
5244
+ this.crashed(null, "could not start", cause);
4956
5245
  return;
4957
5246
  }
4958
5247
  if (current()) this.spawn(command, settings, generation);
4959
- }, (error) => {
4960
- if (!current()) return;
4961
- this.options.logger.error(`${this.options.name} could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
4962
- this.crashed(null, "failed to start");
4963
- });
5248
+ }, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
4964
5249
  }
4965
5250
  spawn(command, settings, generation) {
4966
5251
  const current = () => generation === this.generation;
@@ -4976,6 +5261,7 @@ var ChildProcessSupervisor = class {
4976
5261
  trackTree(child);
4977
5262
  pipeLines(child, this.options.output);
4978
5263
  let exited = false;
5264
+ let cause;
4979
5265
  const onExit = (code, signal) => {
4980
5266
  if (exited) return;
4981
5267
  exited = true;
@@ -4983,12 +5269,16 @@ var ChildProcessSupervisor = class {
4983
5269
  this.child = null;
4984
5270
  killTree(child);
4985
5271
  const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
4986
- this.crashed(code, what);
5272
+ this.crashed(code, what, cause);
4987
5273
  };
4988
5274
  child.once("exit", onExit);
4989
5275
  child.once("error", (error) => {
4990
- this.options.logger.error(`${this.options.name} could not be started: ${error.message}`);
4991
- if (child.pid === void 0) onExit(null, null);
5276
+ const failure = `could not be started: ${error.message}`;
5277
+ this.options.logger.error(`${this.options.name} ${failure}`);
5278
+ if (child.pid === void 0) {
5279
+ cause = failure;
5280
+ onExit(null, null);
5281
+ }
4992
5282
  });
4993
5283
  this.waitForPort(settings, generation, () => exited).then((open) => {
4994
5284
  if (!current() || exited) return;
@@ -4998,7 +5288,8 @@ var ChildProcessSupervisor = class {
4998
5288
  const seconds = ((Date.now() - this.launchedAt) / 1e3).toFixed(1);
4999
5289
  this.options.logger.info(`${this.options.name} running (${seconds}s)`);
5000
5290
  } else {
5001
- this.options.logger.error(`${this.options.name} did not open port ${settings.port} in time, killing it`);
5291
+ cause = `did not open port ${settings.port} in time`;
5292
+ this.options.logger.error(`${this.options.name} ${cause}, killing it`);
5002
5293
  killTree(child);
5003
5294
  }
5004
5295
  });
@@ -5011,11 +5302,13 @@ var ChildProcessSupervisor = class {
5011
5302
  }
5012
5303
  return false;
5013
5304
  }
5014
- crashed(code, what) {
5305
+ /** `what` goes to the log, `cause` to the status. */
5306
+ crashed(code, what, cause = what) {
5015
5307
  const { name, logger } = this.options;
5016
5308
  const ranForMs = this.runningSince === null ? 0 : Date.now() - this.runningSince;
5017
5309
  this.runningSince = null;
5018
5310
  this.exitCode = code;
5311
+ this.lastError = cause;
5019
5312
  const decision = nextAfterCrash(this.crashesInRow, ranForMs, this.options.policy);
5020
5313
  this.crashesInRow = decision.crashesInRow;
5021
5314
  if (decision.action === "fail") {
@@ -5339,87 +5632,6 @@ function createSupervisors(config, options, log) {
5339
5632
  })
5340
5633
  };
5341
5634
  }
5342
- // src/composition/ui.ts
5343
- /** The environment variable the UI's BFF reads the bridge's address from. */
5344
- const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
5345
- /** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
5346
- const PROTOCOL_HEADER = "x-sr-bridge-protocol";
5347
- /**
5348
- * The header that tells the UI its page is opened from the bridge's own machine, where the screen
5349
- * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
5350
- * Set (`1`) or removed on every request, so a client can't send it.
5351
- */
5352
- const LOCAL_HEADER = "x-sr-bridge-local";
5353
- /**
5354
- * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
5355
- * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
5356
- * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
5357
- */
5358
- const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
5359
- /**
5360
- * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
5361
- * none: the bridge runs from source, or the package was built without the UI.
5362
- */
5363
- function createUiMount(dir, logger) {
5364
- const file = new URL("handler.js", dir);
5365
- if (!existsSync(file)) {
5366
- logger.debug(`no web UI at ${file.pathname}`);
5367
- return;
5368
- }
5369
- let settle;
5370
- const loaded = new Promise((resolve, reject) => {
5371
- settle = {
5372
- resolve,
5373
- reject
5374
- };
5375
- });
5376
- loaded.catch(() => void 0);
5377
- return {
5378
- handler: async (req, res) => {
5379
- if (new URL(req.url ?? "/", "http://localhost").pathname === "/") {
5380
- res.writeHead(302, { location: "/ui/" }).end();
5381
- return;
5382
- }
5383
- let handler;
5384
- try {
5385
- handler = await loaded;
5386
- } catch {
5387
- throw new AppError("SERVICE_UNAVAILABLE", "The web UI failed to start");
5388
- }
5389
- req.headers[PROTOCOL_HEADER] = "http";
5390
- if (isOwnAddress(req.socket?.remoteAddress)) req.headers[LOCAL_HEADER] = "1";
5391
- else delete req.headers[LOCAL_HEADER];
5392
- handler(req, res, () => {
5393
- res.statusCode = 404;
5394
- res.end();
5395
- });
5396
- },
5397
- async mount(apiUrl) {
5398
- try {
5399
- process.env[BRIDGE_API_URL_ENV] = apiUrl;
5400
- process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
5401
- globalThis[UI_LOGGER_KEY] = logger;
5402
- const module = await import(file.href);
5403
- if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
5404
- settle.resolve(module.handler);
5405
- logger.debug(`web UI loaded from ${file.pathname}`);
5406
- } catch (error) {
5407
- logger.error(`web UI failed to start: ${error instanceof Error ? error.message : String(error)}`);
5408
- settle.reject(error);
5409
- }
5410
- }
5411
- };
5412
- }
5413
- /** The shipped UI: `ui/` next to the bundled `cli.mjs` (`dist/ui`). */
5414
- function shippedUiDir() {
5415
- return new URL("./ui/", import.meta.url);
5416
- }
5417
- /**
5418
- * Where the BFF reaches the bridge's HTTP API: over loopback, whatever address it listens on.
5419
- */
5420
- function bridgeApiUrl(host, port) {
5421
- return `http://${hostPort(host === "::" ? "::1" : isWildcard(host) ? "127.0.0.1" : host, port)}`;
5422
- }
5423
5635
  // src/domain/capture.ts
5424
5636
  /**
5425
5637
  * What the capture adapters reported about their listener and connections, for the status. The
@@ -5783,7 +5995,26 @@ var SpeechLog = class {
5783
5995
  }
5784
5996
  };
5785
5997
  // src/main.ts
5998
+ /** The web UI shipped with the package: `ui/` next to the bundled `cli.mjs` (`dist/ui`). */
5999
+ const SHIPPED_UI_DIR = new URL("./ui/", import.meta.url);
6000
+ /**
6001
+ * For an exit that can't wait for `stop()`: ends the child services' process trees at once,
6002
+ * synchronously (docs/usage/operations.md#shutdown).
6003
+ */
6004
+ function killChildProcessesNow() {
6005
+ killAllTreesNow();
6006
+ }
6007
+ /** Writes out the console output that is still buffered, before the process exits. */
6008
+ async function flushOutput() {
6009
+ await flushTerminal();
6010
+ await flushConsole();
6011
+ }
5786
6012
  const show = (value) => JSON.stringify(value);
6013
+ /** A busy port needs no stack: the message says what to do. Anything else is unexpected. */
6014
+ function describeStartFailure(error) {
6015
+ if (error instanceof ListenError) return error.message;
6016
+ return error instanceof Error ? error.stack ?? String(error) : String(error);
6017
+ }
5787
6018
  /**
5788
6019
  * Starts the bridge. An invalid setting rejects with a `ConfigError` before anything starts.
5789
6020
  * Any other failure to start is written to the bridge log before the promise rejects, and so is
@@ -5794,7 +6025,7 @@ async function startBridge(options) {
5794
6025
  const seams = options.testSeams ?? {};
5795
6026
  const store = seams.configStore ?? new FsConfigStore(options.configFile ?? defaultConfigFile());
5796
6027
  const sourceOf = (field) => options.overrideSources?.get(field) ?? "a flag or environment variable";
5797
- const { config, file: savedFile, overrides, unknown: unknownSettings, ignored } = await loadConfig(store, options.overrides, sourceOf);
6028
+ const { config, file: savedFile, overrides, unknown: unknownSettings, ignored, warnings } = await loadConfig(store, options.overrides, sourceOf);
5798
6029
  const log = createLogging(config, {
5799
6030
  version,
5800
6031
  configLocation: store.location,
@@ -5802,231 +6033,143 @@ async function startBridge(options) {
5802
6033
  });
5803
6034
  const bridgeLogger = log.for("bridge");
5804
6035
  const configLogger = log.for("config");
6036
+ for (const warning of warnings) configLogger.warn(warning);
5805
6037
  for (const name of ignored) configLogger.warn(`${name}: unknown setting in ${store.location}, ignored`);
5806
6038
  for (const { field, file: saved, override } of overriddenFields(savedFile, overrides)) configLogger.warn(`${field}: the config file sets ${show(saved)}, but ${sourceOf(field)} sets ${show(override)}, which wins`);
5807
- const clock = seams.clock ?? new SystemClock();
5808
- const startedAt = clock.now();
5809
- const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
5810
- const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
5811
- new TranscriptService({
5812
- events,
5813
- transcript: log.for("speech-capture", { channel: "speech" })
5814
- }).start();
5815
- const speech = new SpeechService({
5816
- log: speechLog,
5817
- events,
5818
- clock
5819
- });
5820
- const waits = new WaitForSpeechService({
5821
- log: speechLog,
5822
- events,
5823
- clock,
5824
- pace: () => yieldEvery(256)
5825
- });
5826
- const sessions = new SessionService({
5827
- log: speechLog,
5828
- events,
5829
- clock,
5830
- logger: log.for("bridge")
5831
- });
5832
- const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
5833
- const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
5834
- const input = new NativeInputService({
5835
- injector,
5836
- windows,
5837
- clock,
5838
- logger: log.for("native-input")
5839
- });
5840
- const captures = new InputCaptureService({
5841
- input,
5842
- log: speechLog,
5843
- events,
5844
- clock,
5845
- pace: () => yieldEvery(256)
5846
- });
5847
- const configService = new ConfigService({
5848
- store,
5849
- logger: configLogger,
5850
- active: config,
5851
- file: savedFile,
5852
- unknownSettings,
5853
- pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
5854
- });
5855
- const supervisors = createSupervisors(config, seams, log);
5856
- const focus = new WindowFocusService({
5857
- windows,
5858
- queue: input,
5859
- services: supervisors,
5860
- clock,
5861
- logger: log.for("native-input")
5862
- });
5863
- const childServices = new ChildServicesService({
5864
- supervisors,
5865
- config: () => configService.get(),
5866
- logger: bridgeLogger
5867
- });
5868
- const captureState = new CaptureState(() => clock.now());
5869
- const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
5870
- const status = new StatusService({
5871
- capture: captureState,
5872
- log: speechLog,
5873
- supervisors,
5874
- config: () => configService.get(),
5875
- version,
5876
- apiVersion: API_VERSION,
5877
- startedAt,
5878
- injector,
5879
- windows
5880
- });
5881
- const ui = createUiMount(seams.uiDir ?? shippedUiDir(), log.for("web-ui"));
5882
- const http = new HttpServer({
5883
- speech,
5884
- waits,
5885
- status,
5886
- config: configService,
5887
- sessions,
5888
- input,
5889
- captures,
5890
- focus,
5891
- logger: log.for("http-api"),
5892
- hostnames: [hostname()],
5893
- proxies: proxyRoutes(childServices),
5894
- ...ui ? { ui: ui.handler } : {},
5895
- ...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
5896
- });
5897
- const ports = await startListeners(tcp, http, config, bridgeLogger);
5898
- await ui?.mount(bridgeApiUrl(config.http.host, ports.http));
5899
- const lifecycle = new BridgeLifecycleService({
5900
- state: status,
5901
- pending: [
6039
+ try {
6040
+ const clock = seams.clock ?? new SystemClock();
6041
+ const startedAt = clock.now();
6042
+ const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
6043
+ const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
6044
+ new TranscriptService({
6045
+ events,
6046
+ transcript: log.for("speech-capture", { channel: "speech" })
6047
+ }).start();
6048
+ const speech = new SpeechService({
6049
+ log: speechLog,
6050
+ events,
6051
+ clock
6052
+ });
6053
+ const shutdown = new AbortController();
6054
+ setMaxListeners(0, shutdown.signal);
6055
+ const waits = new WaitForSpeechService({
6056
+ log: speechLog,
6057
+ events,
6058
+ clock,
6059
+ pace: () => yieldEvery(256),
6060
+ shutdown: shutdown.signal
6061
+ });
6062
+ const sessions = new SessionService({
6063
+ log: speechLog,
6064
+ events,
6065
+ clock,
6066
+ logger: log.for("bridge")
6067
+ });
6068
+ const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
6069
+ const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
6070
+ const supervisors = createSupervisors(config, seams, log);
6071
+ const input = new NativeInputService({
6072
+ injector,
6073
+ windows,
6074
+ services: supervisors,
6075
+ clock,
6076
+ logger: log.for("native-input"),
6077
+ shutdown: shutdown.signal
6078
+ });
6079
+ const captures = new InputCaptureService({
6080
+ input,
6081
+ log: speechLog,
6082
+ events,
6083
+ clock,
6084
+ pace: () => yieldEvery(256),
6085
+ shutdown: shutdown.signal
6086
+ });
6087
+ const configService = new ConfigService({
6088
+ store,
6089
+ logger: configLogger,
6090
+ active: config,
6091
+ file: savedFile,
6092
+ unknownSettings,
6093
+ pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
6094
+ });
6095
+ const focus = new WindowFocusService({
6096
+ windows,
6097
+ queue: input,
6098
+ services: supervisors,
6099
+ clock,
6100
+ logger: log.for("native-input")
6101
+ });
6102
+ const childServices = new ChildServicesService({
6103
+ supervisors,
6104
+ config: () => configService.get(),
6105
+ logger: bridgeLogger
6106
+ });
6107
+ const captureState = new CaptureState(() => clock.now());
6108
+ const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
6109
+ const status = new StatusService({
6110
+ capture: captureState,
6111
+ log: speechLog,
6112
+ supervisors,
6113
+ config: () => configService.get(),
6114
+ version,
6115
+ apiVersion: API_VERSION,
6116
+ startedAt,
6117
+ injector,
6118
+ windows
6119
+ });
6120
+ const ui = createUiMount(seams.uiDir ?? SHIPPED_UI_DIR, log.for("web-ui"));
6121
+ const http = new HttpServer({
6122
+ speech,
5902
6123
  waits,
6124
+ status,
6125
+ config: configService,
6126
+ sessions,
6127
+ input,
5903
6128
  captures,
5904
- input
5905
- ],
5906
- startServices: () => childServices.startEnabled(),
5907
- stopOrder: [
5908
- http,
5909
- tcp,
5910
- { stop: () => childServices.stopAll() }
5911
- ],
5912
- readyMessage: () => readySummary({
5913
- config,
5914
- ports,
5915
- supervisors,
5916
- webUi: ui !== void 0,
5917
- nativeInput: injector.availability,
5918
- tookMs: clock.now().getTime() - startedAt.getTime()
5919
- }),
5920
- logger: bridgeLogger
5921
- });
5922
- lifecycle.start();
5923
- return {
5924
- tcpPort: ports.tcp,
5925
- httpPort: ports.http,
5926
- speech,
5927
- sessions,
5928
- capture: captureState,
5929
- log: bridgeLogger,
5930
- stop: (reason) => lifecycle.stop(reason)
5931
- };
5932
- }
5933
- // src/adapters/in/cli/lifecycle.ts
5934
- const SHUTDOWN_TIMEOUT_MS = 1e4;
5935
- /** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
5936
- function shutdownSignals(platform) {
5937
- const signals = [
5938
- "SIGINT",
5939
- "SIGTERM",
5940
- "SIGHUP"
5941
- ];
5942
- if (platform === "win32") signals.push("SIGBREAK");
5943
- return signals;
5944
- }
5945
- /** Resolves once everything written to `stream` so far is handed to the OS. */
5946
- function drain(stream) {
5947
- return new Promise((resolve) => stream.write("", () => resolve()));
5948
- }
5949
- /** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
5950
- async function flushConsole() {
5951
- await Promise.all([drain(process.stdout), drain(process.stderr)]);
5952
- }
5953
- function describeError(error) {
5954
- return error instanceof Error ? error.stack ?? String(error) : String(error);
5955
- }
5956
- /**
5957
- * Starts the bridge with `start`, then stops it gracefully and exits the process
5958
- * (docs/usage/operations.md#shutdown):
5959
- *
5960
- * - on a shutdown signal. A second signal exits at once.
5961
- * - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
5962
- * - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
5963
- *
5964
- * The exit code is 0 unless something failed. Console output is flushed before exiting.
5965
- *
5966
- * The signal handlers are installed before `start`, so a signal that arrives while the bridge
5967
- * starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
5968
- * like `start`.
5969
- */
5970
- async function runUntilStopped(start, proc, options = {}) {
5971
- const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
5972
- let bridge = void 0;
5973
- /** A signal that arrived before the bridge had started. */
5974
- let early;
5975
- let stopping = false;
5976
- let exiting = false;
5977
- let exitCode = 0;
5978
- let watchdog;
5979
- /** Ends the child processes the graceful stop didn't get to. */
5980
- const killLeftovers = () => {
5981
- try {
5982
- onForcedExit?.();
5983
- } catch {}
5984
- };
5985
- const forceExit = (code) => {
5986
- killLeftovers();
5987
- proc.exit(code);
5988
- };
5989
- const exit = (code) => {
5990
- if (exiting) return forceExit(code);
5991
- exiting = true;
5992
- flush().catch(() => void 0).then(() => {
5993
- clearTimeout(watchdog);
5994
- proc.exit(code);
6129
+ focus,
6130
+ logger: log.for("http-api"),
6131
+ hostnames: [hostname()],
6132
+ proxies: proxyRoutes(childServices),
6133
+ ...ui ? { ui: ui.handler } : {},
6134
+ ...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
5995
6135
  });
5996
- };
5997
- const shutdown = (running, reason) => {
5998
- stopping = true;
5999
- watchdog = setTimeout(() => {
6000
- running.log.error(`shutdown did not finish within ${timeoutMs / 1e3} s, exiting`);
6001
- exiting = true;
6002
- forceExit(1);
6003
- }, timeoutMs).unref();
6004
- running.stop(reason).then(() => exit(exitCode), () => exit(1));
6005
- };
6006
- for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
6007
- if (bridge === void 0) {
6008
- if (early === void 0) early = signal;
6009
- else {
6010
- killLeftovers();
6011
- exit(1);
6012
- }
6013
- return;
6014
- }
6015
- if (!stopping) return shutdown(bridge, signal);
6016
- bridge.log.warn(`${signal} again, exiting without waiting`);
6017
- killLeftovers();
6018
- exit(1);
6019
- });
6020
- bridge = await start();
6021
- const running = bridge;
6022
- const crash = (what) => (error) => {
6023
- running.log.error(`${what}: ${describeError(error)}`);
6024
- exitCode = 1;
6025
- if (!stopping) shutdown(running, "crash");
6026
- };
6027
- proc.on("uncaughtException", crash("uncaught exception"));
6028
- proc.on("unhandledRejection", crash("unhandled rejection"));
6029
- if (early !== void 0) shutdown(running, early);
6136
+ const lifecycle = new BridgeLifecycleService({
6137
+ state: status,
6138
+ tcp: {
6139
+ start: () => tcp.start(config.tcp),
6140
+ stop: () => tcp.stop()
6141
+ },
6142
+ http: {
6143
+ start: () => http.start(config.http),
6144
+ stop: () => http.stop()
6145
+ },
6146
+ httpListening: async (port) => ui?.mount(bridgeApiUrl(config.http.host, port)),
6147
+ services: childServices,
6148
+ shutdown,
6149
+ readyMessage: (ports) => readySummary({
6150
+ config,
6151
+ ports,
6152
+ supervisors,
6153
+ webUi: ui !== void 0,
6154
+ nativeInput: injector.availability,
6155
+ tookMs: clock.now().getTime() - startedAt.getTime()
6156
+ }),
6157
+ logger: bridgeLogger
6158
+ });
6159
+ const ports = await lifecycle.start();
6160
+ return {
6161
+ tcpPort: ports.tcp,
6162
+ httpPort: ports.http,
6163
+ speech,
6164
+ sessions,
6165
+ capture: captureState,
6166
+ log: bridgeLogger,
6167
+ stop: (reason) => lifecycle.stop(reason)
6168
+ };
6169
+ } catch (error) {
6170
+ bridgeLogger.error(describeStartFailure(error));
6171
+ throw error;
6172
+ }
6030
6173
  }
6031
6174
  // src/adapters/in/cli/options.ts
6032
6175
  const SETTINGS = [
@@ -6276,16 +6419,14 @@ try {
6276
6419
  overrideSources: options.sources,
6277
6420
  ...options.configFile === void 0 ? {} : { configFile: options.configFile }
6278
6421
  }), process, {
6279
- onForcedExit: () => killAllTreesNow(),
6280
- flush: async () => {
6281
- await flushTerminal();
6282
- await flushConsole();
6283
- }
6422
+ onForcedExit: killChildProcessesNow,
6423
+ flush: flushOutput
6284
6424
  });
6285
6425
  } catch (error) {
6286
6426
  if (error instanceof ConfigError) fail(error.message);
6287
- await flushTerminal();
6288
- await flushConsole();
6427
+ const reason = error instanceof Error ? error.message : String(error);
6428
+ process.stderr.write(`screenreader-speech-capture-bridge: failed to start: ${reason}\n`);
6429
+ await flushOutput();
6289
6430
  process.exit(1);
6290
6431
  }
6291
6432
  export {};