agent-yes 1.303.1 → 1.304.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 (184) hide show
  1. package/README.md +54 -0
  2. package/default.config.yaml +5 -5
  3. package/dist/{JsonlStore-BpYZZTap.js → JsonlStore-CB_0sfdT.js} +5 -4
  4. package/dist/{SUPPORTED_CLIS-Dq9Lq9WJ.js → SUPPORTED_CLIS-C_1IiOj3.js} +2 -2
  5. package/dist/SUPPORTED_CLIS-Do3GHAY1.js +12 -0
  6. package/dist/{agentShare-suB6yPgO.js → agentShare-BvpEm-Fr.js} +10 -9
  7. package/dist/{askCli-BU3CNCLU.js → askCli-KmMf-3wA.js} +6 -6
  8. package/dist/{browser-BmxN1Ur9.js → browser-BAFPmEvN.js} +2 -2
  9. package/dist/{callback-Ctj3_Wxp.js → callback-BiSUhjw7.js} +6 -6
  10. package/dist/callback-SqLD2mMX.js +17 -0
  11. package/dist/{callbackCore-DSJWhqAe.js → callbackCore-BZ_10zyc.js} +1 -1
  12. package/dist/{callbackCore-BesbQ6-Z.js → callbackCore-Deve5pv3.js} +1 -1
  13. package/dist/{channels-j5nWuzlQ.js → channels-Y36S0ccW.js} +2 -2
  14. package/dist/cli.js +118 -13
  15. package/dist/{cmdDsh-2LP0grim.js → cmdDsh-DZ8bLsH7.js} +1 -1
  16. package/dist/cmdKill-CzSBfWmx.js +116 -0
  17. package/dist/{cmdPs-wc1j85fi.js → cmdPs-DBt23Qz0.js} +11 -10
  18. package/dist/{cwdConflictWarn-skQSMwEh.js → cwdConflictWarn-y-epQyOj.js} +21 -5
  19. package/dist/{cwdPassthroughHint-BUbWMoz0.js → cwdPassthroughHint-CzWh0hrw.js} +1 -1
  20. package/dist/{expose-Dawq1LxC.js → expose-Bhsn5yUz.js} +2 -2
  21. package/dist/forceKill-BDqxx4uQ.js +44 -0
  22. package/dist/{forkNested-CavHyWzA.js → forkNested-3heLs5XC.js} +45 -5
  23. package/dist/{globalPidIndex-CRB5KtyL.js → globalPidIndex-BsjlId-h.js} +6 -5
  24. package/dist/{globalPidIndex-BftWlg2V.js → globalPidIndex-uoz8Esqz.js} +2 -2
  25. package/dist/{hist-Cs0KFSUW.js → hist-DY16wm7g.js} +1 -1
  26. package/dist/{identity-DA7YI9km.js → identity-C0MxfwI2.js} +1 -1
  27. package/dist/{identity-Bk-aG_xl.js → identity-Ckav3-Up.js} +1 -1
  28. package/dist/index.js +7 -7
  29. package/dist/{initMsg-CcTqFtsp.js → initMsg-BEVDWYnv.js} +1 -1
  30. package/dist/{initMsg-D9KJnfgC.js → initMsg-GPU52N-j.js} +1 -1
  31. package/dist/liagent/box-BSIrRRc_.js +2320 -0
  32. package/dist/liagent/box-DloywR57.d.ts +409 -0
  33. package/dist/liagent/box.d.ts +3 -0
  34. package/dist/liagent/box.js +3 -0
  35. package/dist/liagent/cli.d.ts +1 -0
  36. package/dist/liagent/cli.js +908 -0
  37. package/dist/liagent/client.d.ts +28 -0
  38. package/dist/liagent/client.js +240 -0
  39. package/dist/liagent/echo-BvzPSI0x.js +86 -0
  40. package/dist/liagent/echo-W2RcMEny.d.ts +38 -0
  41. package/dist/liagent/hub.d.ts +405 -0
  42. package/dist/liagent/hub.js +1831 -0
  43. package/dist/liagent/index.d.ts +14 -0
  44. package/dist/liagent/index.js +10 -0
  45. package/dist/liagent/liagent.js +339 -0
  46. package/dist/liagent/mic-audio-C3Shud_F.js +754 -0
  47. package/dist/liagent/mic-audio-DMCWtEI-.d.ts +317 -0
  48. package/dist/liagent/mic-button-CtZHFBSG.js +651 -0
  49. package/dist/liagent/mic-button-Y0ioPetQ.d.ts +248 -0
  50. package/dist/liagent/mic.d.ts +3 -0
  51. package/dist/liagent/mic.js +4 -0
  52. package/dist/liagent/progress-CJs08bXb.js +473 -0
  53. package/dist/liagent/progress-CfE-meHr.d.ts +205 -0
  54. package/dist/liagent/progress.d.ts +2 -0
  55. package/dist/liagent/progress.js +3 -0
  56. package/dist/liagent/protocol.d.ts +324 -0
  57. package/dist/liagent/protocol.js +504 -0
  58. package/dist/liagent/speech-rate-DXeJjRTc.js +42 -0
  59. package/dist/liagent/state-tree-BZCmAknI.js +353 -0
  60. package/dist/liagent/tree-BrR7NwMf.js +710 -0
  61. package/dist/liagent/tree-HB9RhX_H.d.ts +295 -0
  62. package/dist/liagent/tree.d.ts +2 -0
  63. package/dist/liagent/tree.js +4 -0
  64. package/dist/liagent/ui-strings-B03le3fh.d.ts +27 -0
  65. package/dist/liagent/ui-strings-CJIwW5Gf.js +794 -0
  66. package/dist/liagent/ui.d.ts +394 -0
  67. package/dist/liagent/ui.js +5 -0
  68. package/dist/liagent/voice-D7yeS9VM.js +802 -0
  69. package/dist/liagent/voice-Qo7SCgi8.d.ts +308 -0
  70. package/dist/liagent/voice.d.ts +3 -0
  71. package/dist/liagent/voice.js +4 -0
  72. package/dist/{notifyDaemon-C7GlfJ1E.js → notifyDaemon-DkUB7GV2.js} +10 -9
  73. package/dist/{openBrowser-1cIo4dJL.js → openBrowser-CQAOIrD6.js} +1 -1
  74. package/dist/oxmgrService-DlYHmqyI.js +37 -0
  75. package/dist/oxmgrService-o9L3I6FX.js +3 -0
  76. package/dist/{parentLink-DoEWVGld.js → parentLink-BcAYcO9L.js} +2 -2
  77. package/dist/{parentLink-B58V1RVd.js → parentLink-MBUD3oY2.js} +2 -2
  78. package/dist/{parentPingLoop-C73bbmCE.js → parentPingLoop-DDO592Wh.js} +5 -5
  79. package/dist/{pidStore-433kvh9D.js → pidStore-C50VPk3E.js} +3 -3
  80. package/dist/pidStore-COkPjpW8.js +6 -0
  81. package/dist/{procStats-BvmrBrOs.js → procStats-DwTxj3rs.js} +1 -1
  82. package/dist/{remotes-MfdV9M8u.js → remotes-BqLoB5GR.js} +2 -2
  83. package/dist/{remotes-DevcBeLl.js → remotes-BsMGvAay.js} +3 -3
  84. package/dist/{roomReplyAlias-DFqg_6IU.js → roomReplyAlias-B-v76TA8.js} +3 -3
  85. package/dist/roomReplyAlias-BzWUBkQy.js +6 -0
  86. package/dist/{rustBinary-7VK7oLlW.js → rustBinary-BrJ2p8wy.js} +2 -2
  87. package/dist/{rustBinary-BV4LxMMn.js → rustBinary-vpfpWj1q.js} +2 -2
  88. package/dist/{schedule-Dp0qkNO1.js → schedule-Bzjhl6-h.js} +15 -44
  89. package/dist/schedulesCli-CLqieyQZ.js +784 -0
  90. package/dist/senderAncestry-CVHeKk1Y.js +173 -0
  91. package/dist/senderAncestry-KhAUPCQs.js +3 -0
  92. package/dist/{serve-BpOIIOVc.js → serve-XwFYE0cE.js} +67 -69
  93. package/dist/{serveRust-CbBrcUrg.js → serveRust-BfWkeL6T.js} +31 -4
  94. package/dist/{setup-DdIBk6Iv.js → setup-D4-s2VZw.js} +5 -5
  95. package/dist/{share-w5oRbvlj.js → share-CbFetL5H.js} +1 -1
  96. package/dist/{share-DrS3LYqf.js → share-_TPYAGWC.js} +1 -1
  97. package/dist/{shareCmd-DDENkBW2.js → shareCmd-DUBsVI3e.js} +10 -10
  98. package/dist/spawnGate-Dfj9V76w.js +5 -0
  99. package/dist/{spawnGate-lr3tvA6U.js → spawnGate-Dj_WaS29.js} +3 -3
  100. package/dist/{subcommands-DxgvDmZX.js → subcommands-B7YZJL8n.js} +471 -307
  101. package/dist/subcommands-BZPxFgkT.js +15 -0
  102. package/dist/{systemPathLink-SjUzgSiq.js → systemPathLink-Y3iC7bYV.js} +1 -1
  103. package/dist/{terminal-C2h7tpe0.js → terminal-13cGj3h6.js} +2 -2
  104. package/dist/terminal.js +1 -1
  105. package/dist/{todoAutomation-TTp_Qz9G.js → todoAutomation-CKlrxuZv.js} +2 -2
  106. package/dist/{todoCli-BWm5nZE0.js → todoCli-CU9vSJSJ.js} +6 -6
  107. package/dist/{todoIdentity-BvXZKWJI.js → todoIdentity-CzS1e7VL.js} +2 -2
  108. package/dist/{todoStore-C9RTz0Vs.js → todoStore-msRCEUi1.js} +2 -2
  109. package/dist/{tray-BeRSozJz.js → tray-CLktEN3G.js} +1 -1
  110. package/dist/{trayApp-QQjqhDv1.js → trayApp-5_OlvQcz.js} +2 -2
  111. package/dist/trayApp-DkAPo0m6.js +5 -0
  112. package/dist/{ts-6LF7f4fx.js → ts-njuddXQz.js} +126 -57
  113. package/dist/{versionChecker-Bc62HNf6.js → versionChecker-BJycAanp.js} +2 -2
  114. package/dist/{webrtcLink-va_gAR77.js → webrtcLink-DcvacEci.js} +1 -1
  115. package/dist/{webrtcLink-SsInrVHU.js → webrtcLink-WxS1nTIs.js} +1 -1
  116. package/dist/{webrtcRemote-BlGyNZDC.js → webrtcRemote-C3xQyf3u.js} +2 -2
  117. package/dist/{widget-Crb5zeHL.js → widget-DmRwOlco.js} +3 -3
  118. package/dist/widgets.js +1 -1
  119. package/dist/{workspaceConfig-BLWB5Wu9.js → workspaceConfig-DBgsu81B.js} +1 -1
  120. package/dist/{ws-DIbwNz8Z.js → ws-ByO6JO6m.js} +3 -3
  121. package/dist/{ws-BRhPG1Vy.js → ws-D0-Jg88z.js} +9 -8
  122. package/lab/ui/index.html +1 -1
  123. package/lab/ui/lab/posts/2026-08-11-slack-term-safe-writes.md +1 -1
  124. package/package.json +73 -8
  125. package/ts/JsonlStore.ts +10 -3
  126. package/ts/cli-idle.bun.spec.ts +1 -1
  127. package/ts/cli-idle.spec.ts +1 -1
  128. package/ts/cli.ts +35 -0
  129. package/ts/cmdKill.bun.spec.ts +155 -0
  130. package/ts/cmdKill.spec.ts +155 -0
  131. package/ts/cmdKill.ts +183 -0
  132. package/ts/composerGuard.edges.spec.ts +91 -0
  133. package/ts/composerGuard.spec.ts +53 -6
  134. package/ts/composerGuard.ts +42 -13
  135. package/ts/conptyModeFilter.spec.ts +30 -0
  136. package/ts/conptyModeFilter.ts +53 -0
  137. package/ts/copyLiagent.ts +42 -0
  138. package/ts/cwdConflictWarn.io.spec.ts +50 -0
  139. package/ts/cwdConflictWarn.spec.ts +34 -1
  140. package/ts/cwdConflictWarn.ts +43 -5
  141. package/ts/cwdGuard.spec.ts +110 -0
  142. package/ts/cwdGuard.ts +118 -0
  143. package/ts/forceKill.ts +52 -0
  144. package/ts/forkNested.bun.spec.ts +41 -0
  145. package/ts/forkNested.spec.ts +41 -0
  146. package/ts/forkNested.ts +48 -1
  147. package/ts/globalPidIndex.edges.spec.ts +125 -0
  148. package/ts/globalPidIndex.ts +6 -2
  149. package/ts/index.ts +13 -1
  150. package/ts/interruptSend.bun.spec.ts +99 -0
  151. package/ts/interruptSend.spec.ts +99 -0
  152. package/ts/interruptSend.ts +51 -0
  153. package/ts/lockRegistry.spec.ts +49 -0
  154. package/ts/lsRenderCache.spec.ts +58 -0
  155. package/ts/needsInput.edges.spec.ts +23 -0
  156. package/ts/parseCliArgs.ts +7 -0
  157. package/ts/pushGatePlan.spec.ts +147 -0
  158. package/ts/roomReplyAlias.io.spec.ts +81 -0
  159. package/ts/schedule.ts +5 -1
  160. package/ts/schedules.bun.spec.ts +397 -0
  161. package/ts/schedules.spec.ts +397 -0
  162. package/ts/schedules.ts +517 -0
  163. package/ts/schedulesCli.ts +386 -0
  164. package/ts/sendControl.bun.spec.ts +12 -0
  165. package/ts/senderAncestry.ts +1 -3
  166. package/ts/serve.ts +22 -33
  167. package/ts/serveRust.spec.ts +29 -2
  168. package/ts/serveRust.ts +27 -2
  169. package/ts/sizeNego.bun.spec.ts +9 -2
  170. package/ts/sizeNego.spec.ts +9 -2
  171. package/ts/sizeNego.ts +10 -5
  172. package/ts/subcommands.spec.ts +348 -9
  173. package/ts/subcommands.ts +513 -93
  174. package/ts/suggestAgents.spec.ts +33 -0
  175. package/ts/terminal/browser.ts +1 -1
  176. package/ts/todoParse.spec.ts +22 -1
  177. package/ts/todoParse.ts +19 -0
  178. package/dist/SUPPORTED_CLIS-ByO5twge.js +0 -12
  179. package/dist/callback-D7qfh_7p.js +0 -16
  180. package/dist/pidStore-BRlKRHXY.js +0 -6
  181. package/dist/roomReplyAlias-DuEkSSDI.js +0 -6
  182. package/dist/spawnGate-DeQBTX-o.js +0 -5
  183. package/dist/subcommands-DmiswRy4.js +0 -14
  184. package/dist/trayApp-C4TAvRvU.js +0 -5
@@ -0,0 +1,754 @@
1
+ //#region src/mic.ts
2
+ /**
3
+ * The mic, without the browser: a listening mode in which a voice-activity
4
+ * detector cuts speech into utterances, each one sent to the host's STT
5
+ * endpoint as soon as it ends. Requests run in parallel; transcripts are
6
+ * appended in the order spoken. A long utterance also sends rolling partial
7
+ * chunks, whose text shows dimmed until the final one replaces it. Nothing is
8
+ * sent as a chat message here: the text lands in the draft, and the rules
9
+ * below (appendDictation) say when it goes out. The VAD, the upload and the
10
+ * timers are injected, so all of this is tested with fakes (test/mic.test.ts);
11
+ * src/mic-audio.ts has the browser pieces and src/mic-button.ts the element.
12
+ */
13
+ /** Longest utterance: past this it is cut and sent, and listening goes on. */
14
+ const MAX_UTTERANCE_MS = 3e4;
15
+ /** The VADs hand over 16 kHz mono. */
16
+ const RATE = 16e3;
17
+ /** Partials: one every PARTIAL_EVERY_MS of speech, once it is PARTIAL_MIN_MS long… */
18
+ const PARTIAL_EVERY_MS = 2500;
19
+ const PARTIAL_MIN_MS = 3e3;
20
+ /** …each chunk overlapping the one before by this much, so a word cut at its edge is heard whole. */
21
+ const PARTIAL_OVERLAP_MS = 1500;
22
+ /** Shown in the input for an utterance still being transcribed. */
23
+ const PENDING_MARK = "…";
24
+ /**
25
+ * `speaking`: the agent's reply is being read while the mic is on. Capturing
26
+ * wins: with echo cancellation the user can talk over the agent.
27
+ */
28
+ function micStatus(state, pending, speaking = false) {
29
+ if (state === "capturing") return "capturing";
30
+ if (speaking && state === "listening") return "speaking";
31
+ if (pending > 0) return "transcribing";
32
+ if (state === "off") return "idle";
33
+ return state;
34
+ }
35
+ /** A non-2xx answer from the STT endpoint. */
36
+ var SttError = class extends Error {
37
+ constructor(status, message) {
38
+ super(message);
39
+ this.status = status;
40
+ this.name = "SttError";
41
+ }
42
+ };
43
+ const nameOf = (e) => e?.name;
44
+ /** getUserMedia refused or found nothing: the fallback needs the mic too, so it is not tried. */
45
+ function isMicDenied(e) {
46
+ const n = nameOf(e);
47
+ return n === "NotAllowedError" || n === "SecurityError" || n === "NotFoundError";
48
+ }
49
+ const MIC_ERROR_STRINGS_EN = {
50
+ denied: "Microphone permission denied",
51
+ noMic: "No microphone found",
52
+ signIn: "Sign in to use the mic",
53
+ tooMuch: "Too much speech for now; try again in a minute",
54
+ failed: "Transcription failed ({status})",
55
+ other: "Mic: {message}"
56
+ };
57
+ /** The short note by the button for an error. */
58
+ function micErrorNote(e, t = MIC_ERROR_STRINGS_EN) {
59
+ const s = {
60
+ ...MIC_ERROR_STRINGS_EN,
61
+ ...t
62
+ };
63
+ const n = nameOf(e);
64
+ if (n === "NotAllowedError" || n === "SecurityError") return s.denied;
65
+ if (n === "NotFoundError") return s.noMic;
66
+ if (e instanceof SttError) {
67
+ if (e.status === 401) return s.signIn;
68
+ if (e.status === 429) return s.tooMuch;
69
+ return s.failed.replace("{status}", String(e.status));
70
+ }
71
+ return s.other.replace("{message}", String(e?.message ?? e).slice(0, 100));
72
+ }
73
+ /**
74
+ * Utterances in flight, in the order they were spoken. `take()` hands back
75
+ * the text of every finished one that has nothing unfinished before it.
76
+ */
77
+ var UtteranceQueue = class {
78
+ next = 0;
79
+ head = 0;
80
+ done = /* @__PURE__ */ new Map();
81
+ partials = /* @__PURE__ */ new Map();
82
+ add() {
83
+ return this.next++;
84
+ }
85
+ resolve(seq, text) {
86
+ if (seq < this.head) return;
87
+ this.done.set(seq, text);
88
+ this.partials.delete(seq);
89
+ }
90
+ /** Interim text for one not yet resolved (ignored once it is). */
91
+ partial(seq, text) {
92
+ if (seq >= this.head && !this.done.has(seq)) this.partials.set(seq, text);
93
+ }
94
+ getPartial(seq) {
95
+ return this.partials.get(seq) ?? "";
96
+ }
97
+ /** Text now in order (failed ones are skipped), joined with joinText. */
98
+ take() {
99
+ let out = "";
100
+ while (this.done.has(this.head)) {
101
+ const t = this.done.get(this.head);
102
+ this.done.delete(this.head++);
103
+ if (t) out = joinText(out, t);
104
+ }
105
+ return out;
106
+ }
107
+ /** Utterances still being transcribed. */
108
+ pending() {
109
+ return this.next - this.head;
110
+ }
111
+ /**
112
+ * What the input shows, dimmed, after the draft: for each utterance not yet
113
+ * taken, its text (done, waiting on an earlier one), its partial, or
114
+ * PENDING_MARK (one mark for a run of them).
115
+ */
116
+ interim() {
117
+ let out = "";
118
+ let mark = false;
119
+ for (let s = this.head; s < this.next; s++) {
120
+ const t = this.done.has(s) ? this.done.get(s) ?? "" : this.partials.get(s) || PENDING_MARK;
121
+ if (t === PENDING_MARK && mark) continue;
122
+ mark = t === PENDING_MARK;
123
+ out = joinText(out, t);
124
+ }
125
+ return out;
126
+ }
127
+ };
128
+ const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}。、!?]/u;
129
+ /** Append `b` to `a`: a space between them, except between CJK characters or at a line start. */
130
+ function joinText(a, b) {
131
+ const t = b.trim();
132
+ if (!t) return a;
133
+ if (!a || /\s$/.test(a)) return a + t;
134
+ return CJK.test(a.at(-1) ?? "") && CJK.test(t[0] ?? "") ? a + t : `${a} ${t}`;
135
+ }
136
+ /** A draft ending a sentence (any script's full stop, ! or ?). */
137
+ const ENDS_SENTENCE = /[。..!?!?]$/;
138
+ /**
139
+ * Spoken (or IME-dictated) sentences go out at once from this many characters
140
+ * (trimmed): typing arrives a character at a time, so 3 at once is dictation.
141
+ */
142
+ const AUTO_SEND_MIN = 3;
143
+ /**
144
+ * Typed text that arrived at once (an outside dictation IME): AUTO_SEND_MIN
145
+ * or more characters since the draft last settled, and the draft now ends a
146
+ * sentence. Then it is sent at once.
147
+ */
148
+ function isDictationBurst(settledLen, draft) {
149
+ return draft.length - settledLen >= AUTO_SEND_MIN && ENDS_SENTENCE.test(draft.trim());
150
+ }
151
+ const QUESTION_CJK = /(?:吗|嗎|呢|么|麼|吧|か|かな|かしら|の|でしょう|ですか|ますか|니까|나요|까요)$/u;
152
+ const QUESTION_LATIN = /^(?:what|why|how|when|where|who|whom|whose|which|can|could|do|does|did|is|are|was|were|will|would|should|shall|may|might|have|has|had)\b/i;
153
+ const TRAILING_PUNCT = /[\p{P}\s]+$/u;
154
+ /**
155
+ * Spoken text always ends a sentence ("auto-punctuate, then commit"): Whisper
156
+ * usually adds the stop itself; when it doesn't, add one that fits the text —
157
+ * 。/? for CJK, ./? otherwise, a question by its particle or opening word.
158
+ * Text that already ends in any punctuation (…, ~, quotes) is left alone.
159
+ */
160
+ function punctuate(text) {
161
+ const t = text.trim();
162
+ if (!t || /[\p{P}~]$/u.test(t)) return t;
163
+ const bare = t.replace(TRAILING_PUNCT, "");
164
+ if (CJK.test(t)) return t + (QUESTION_CJK.test(bare) ? "?" : "。");
165
+ return t + (QUESTION_LATIN.test(bare) ? "?" : ".");
166
+ }
167
+ /** Letters or digits in any script: something was actually said. */
168
+ const SPOKEN = /[\p{L}\p{N}]/u;
169
+ /**
170
+ * A final transcript lands in the draft, punctuated, and is committed at once
171
+ * (shown, then sent) whenever it carries any words — a short "好" or "OK"
172
+ * too. Partials never come here; typing never does (see isDictationBurst).
173
+ */
174
+ function appendDictation(draft, text) {
175
+ const said = punctuate(text);
176
+ if (!said) return {
177
+ draft,
178
+ send: false
179
+ };
180
+ const next = joinText(draft, said);
181
+ return {
182
+ draft: next,
183
+ send: SPOKEN.test(said) && ENDS_SENTENCE.test(next.trim())
184
+ };
185
+ }
186
+ /** Words (or, in CJK text, characters), and their keys: lowercased, without punctuation. */
187
+ function tokens(s) {
188
+ const cjk = CJK.test(s);
189
+ const raw = cjk ? [...s.replace(/\s+/g, "")] : s.split(/\s+/).filter(Boolean);
190
+ return {
191
+ raw,
192
+ key: raw.map((w) => w.toLowerCase().replace(/[\p{P}\p{S}]/gu, "")),
193
+ cjk
194
+ };
195
+ }
196
+ /**
197
+ * Two overlapping chunks' transcripts as one: the longest run of words that
198
+ * ends `a` and starts `b` is kept once ("the quick brown" + "brown fox" →
199
+ * "the quick brown fox"). With no overlap they are just joined.
200
+ */
201
+ function mergeOverlap(a, b) {
202
+ const A = tokens(a.trim());
203
+ const B = tokens(b.trim());
204
+ for (let k = Math.min(A.key.length, B.key.length); k > 0; k--) {
205
+ const end = A.key.slice(-k);
206
+ if (end.join("") && end.every((w, i) => w === B.key[i])) return joinText(a.trim(), B.raw.slice(k).join(B.cjk ? "" : " "));
207
+ }
208
+ return joinText(a.trim(), b);
209
+ }
210
+ /** Linear resampling to `to` Hz (the fallback VAD records at the device's rate). */
211
+ function resample(input, from, to) {
212
+ if (from === to) return input;
213
+ const n = Math.max(1, Math.round(input.length * to / from));
214
+ const out = new Float32Array(n);
215
+ const step = from / to;
216
+ const last = input.length - 1;
217
+ for (let i = 0; i < n; i++) {
218
+ const x = i * step;
219
+ const j = Math.floor(x);
220
+ const a = input[Math.min(j, last)] ?? 0;
221
+ out[i] = a + ((input[Math.min(j + 1, last)] ?? 0) - a) * (x - j);
222
+ }
223
+ return out;
224
+ }
225
+ /** 16-bit PCM WAV, mono: what every STT model takes, and every browser can make. */
226
+ function encodeWav(samples, rate = RATE) {
227
+ const buf = /* @__PURE__ */ new ArrayBuffer(44 + samples.length * 2);
228
+ const v = new DataView(buf);
229
+ const str = (o, s) => {
230
+ for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i));
231
+ };
232
+ str(0, "RIFF");
233
+ v.setUint32(4, 36 + samples.length * 2, true);
234
+ str(8, "WAVE");
235
+ str(12, "fmt ");
236
+ v.setUint32(16, 16, true);
237
+ v.setUint16(20, 1, true);
238
+ v.setUint16(22, 1, true);
239
+ v.setUint32(24, rate, true);
240
+ v.setUint32(28, rate * 2, true);
241
+ v.setUint16(32, 2, true);
242
+ v.setUint16(34, 16, true);
243
+ str(36, "data");
244
+ v.setUint32(40, samples.length * 2, true);
245
+ for (let i = 0; i < samples.length; i++) {
246
+ const s = Math.max(-1, Math.min(1, samples[i] ?? 0));
247
+ v.setInt16(44 + i * 2, s < 0 ? s * 32768 : s * 32767, true);
248
+ }
249
+ return new Uint8Array(buf);
250
+ }
251
+ /** The RMS level of a frame, for the energy fallback. */
252
+ function rms(frame) {
253
+ let sum = 0;
254
+ for (const x of frame) sum += x * x;
255
+ return Math.sqrt(sum / (frame.length || 1));
256
+ }
257
+ function concat(chunks) {
258
+ const all = new Float32Array(chunks.reduce((n, c) => n + c.length, 0));
259
+ let o = 0;
260
+ for (const c of chunks) {
261
+ all.set(c, o);
262
+ o += c.length;
263
+ }
264
+ return all;
265
+ }
266
+ /**
267
+ * The energy-threshold VAD the mic falls back to when Silero is not given or
268
+ * cannot load: feed it frames; it says when speech starts (two frames over
269
+ * `on`) and ends (`hangMs` under `off`), keeping a frame of audio from before
270
+ * the start.
271
+ */
272
+ function energyGate(opts) {
273
+ const on = opts.on ?? .02;
274
+ const off = opts.off ?? .01;
275
+ const hang = (opts.hangMs ?? 700) * opts.rate / 1e3;
276
+ const min = (opts.minMs ?? 250) * opts.rate / 1e3;
277
+ let loud = 0;
278
+ let quiet = 0;
279
+ let speaking = false;
280
+ let pre = [];
281
+ let chunks = [];
282
+ const cut = () => {
283
+ const all = concat(chunks);
284
+ speaking = false;
285
+ chunks = [];
286
+ quiet = 0;
287
+ loud = 0;
288
+ return all.length < min ? "misfire" : all;
289
+ };
290
+ return {
291
+ push(frame) {
292
+ const level = rms(frame);
293
+ if (!speaking) {
294
+ pre = [...pre.slice(-1), frame];
295
+ loud = level > on ? loud + 1 : 0;
296
+ if (loud < 2) return null;
297
+ speaking = true;
298
+ chunks = pre;
299
+ pre = [];
300
+ return "start";
301
+ }
302
+ chunks.push(frame);
303
+ quiet = level < off ? quiet + frame.length : 0;
304
+ return quiet >= hang ? cut() : null;
305
+ },
306
+ flush() {
307
+ return speaking ? cut() : null;
308
+ }
309
+ };
310
+ }
311
+ /**
312
+ * Listening mode. `toggle()` turns it on (loading the VAD, or the fallback if
313
+ * that fails, unless the mic itself was refused) and off. Each utterance is
314
+ * encoded and uploaded at once; its transcript (in order) goes to `onText`,
315
+ * and `onPending` counts those still out, with the interim text to show
316
+ * dimmed. A capture longer than MAX_UTTERANCE_MS is cut and sent. A 401 turns
317
+ * listening off; a 429 on a partial stops partials until the next turn-on.
318
+ */
319
+ function createMic(d) {
320
+ const setTimer = d.setTimer ?? ((f, ms) => setTimeout(f, ms));
321
+ const clearTimer = d.clearTimer ?? ((t) => clearTimeout(t));
322
+ const q = new UtteranceQueue();
323
+ let state = "off";
324
+ let vad = null;
325
+ let cap;
326
+ /** Bumped on every toggle, so a VAD that finishes loading after "off" is dropped. */
327
+ let gen = 0;
328
+ /** The utterance being captured: its frames, and its seq once a partial reserved one. */
329
+ let live = [];
330
+ let liveLen = 0;
331
+ let sincePartial = 0;
332
+ let cur = null;
333
+ let partialBusy = false;
334
+ let partialsOn = d.partials !== false;
335
+ /** The agent is speaking (hold): capture stops, and anything heard is dropped. */
336
+ let held = false;
337
+ /** Set by a hold: speech that began before it is dropped, even if it ends after. */
338
+ let tainted = false;
339
+ /** VAD pause/start calls, in order. */
340
+ let ctl = Promise.resolve();
341
+ const toMs = (n) => Math.round(n / RATE * 1e3);
342
+ const toSamples = (ms) => ms * RATE / 1e3;
343
+ const set = (s) => {
344
+ state = s;
345
+ d.onState(s);
346
+ };
347
+ const pending = () => d.onPending(q.pending(), q.interim());
348
+ const report = () => {
349
+ const t = q.take();
350
+ if (t) d.onText(t);
351
+ pending();
352
+ };
353
+ const resetLive = () => {
354
+ live = [];
355
+ liveLen = 0;
356
+ sincePartial = 0;
357
+ };
358
+ /** An utterance whose seq a partial reserved ended in nothing. */
359
+ const dropCur = () => {
360
+ if (cur === null) return;
361
+ q.resolve(cur, null);
362
+ cur = null;
363
+ report();
364
+ };
365
+ const fail = (e) => {
366
+ d.onError?.(e);
367
+ if (e instanceof SttError && e.status === 401) off();
368
+ };
369
+ const sendPartial = () => {
370
+ const seq = cur ?? (cur = q.add());
371
+ const n = Math.min(liveLen, sincePartial + toSamples(PARTIAL_OVERLAP_MS));
372
+ const chunk = concat(live).subarray(liveLen - n);
373
+ sincePartial = 0;
374
+ partialBusy = true;
375
+ pending();
376
+ d.upload(encodeWav(chunk), {
377
+ seq,
378
+ durationMs: toMs(n),
379
+ partial: true
380
+ }).then((text) => q.partial(seq, mergeOverlap(q.getPartial(seq), text)), (e) => {
381
+ if (e instanceof SttError && e.status === 429) partialsOn = false;
382
+ if (e instanceof SttError && e.status === 401) fail(e);
383
+ }).finally(() => {
384
+ partialBusy = false;
385
+ pending();
386
+ });
387
+ };
388
+ const events = (g) => ({
389
+ onSpeechStart() {
390
+ if (g !== gen || held) return;
391
+ tainted = false;
392
+ set("capturing");
393
+ resetLive();
394
+ clearTimer(cap);
395
+ cap = setTimer(() => void vad?.flush(), MAX_UTTERANCE_MS);
396
+ },
397
+ onFrame(frame, prob) {
398
+ if (g !== gen || state !== "capturing") return;
399
+ if (prob !== void 0) d.onProb?.(prob);
400
+ live.push(frame);
401
+ liveLen += frame.length;
402
+ sincePartial += frame.length;
403
+ if (partialsOn && !partialBusy && liveLen >= toSamples(PARTIAL_MIN_MS) && sincePartial >= toSamples(PARTIAL_EVERY_MS)) sendPartial();
404
+ },
405
+ onMisfire() {
406
+ if (g !== gen || held) return;
407
+ clearTimer(cap);
408
+ resetLive();
409
+ dropCur();
410
+ if (state === "capturing") set("listening");
411
+ },
412
+ onSpeechEnd(audio) {
413
+ if (held || tainted) return;
414
+ clearTimer(cap);
415
+ const mine = g === gen;
416
+ if (mine && state === "capturing") set("listening");
417
+ const seq = mine && cur !== null ? cur : q.add();
418
+ if (mine) {
419
+ cur = null;
420
+ resetLive();
421
+ }
422
+ pending();
423
+ d.upload(encodeWav(audio), {
424
+ seq,
425
+ durationMs: toMs(audio.length),
426
+ partial: false
427
+ }).then((text) => q.resolve(seq, text), (e) => {
428
+ q.resolve(seq, null);
429
+ fail(e);
430
+ }).finally(report);
431
+ }
432
+ });
433
+ const on = async () => {
434
+ const g = ++gen;
435
+ partialsOn = d.partials !== false;
436
+ set("loading");
437
+ let v;
438
+ try {
439
+ v = await d.load(events(g));
440
+ } catch (e) {
441
+ if (!d.fallback || isMicDenied(e)) {
442
+ if (g === gen) set("off");
443
+ d.onError?.(e);
444
+ return;
445
+ }
446
+ try {
447
+ v = await d.fallback(events(g));
448
+ } catch (e2) {
449
+ if (g === gen) set("off");
450
+ d.onError?.(e2);
451
+ return;
452
+ }
453
+ }
454
+ if (g !== gen) return void v.destroy();
455
+ vad = v;
456
+ if (!held) await v.start();
457
+ set("listening");
458
+ };
459
+ async function off() {
460
+ if (state === "off") return;
461
+ gen++;
462
+ clearTimer(cap);
463
+ const v = vad;
464
+ vad = null;
465
+ const reserved = cur;
466
+ cur = null;
467
+ resetLive();
468
+ set("off");
469
+ if (v) {
470
+ await v.flush();
471
+ await v.destroy();
472
+ }
473
+ if (reserved !== null) {
474
+ cur = reserved;
475
+ dropCur();
476
+ }
477
+ }
478
+ /**
479
+ * Hold capture while the agent speaks (on), resume it (off). Speech being
480
+ * captured is dropped, partials stop, and the VAD is paused; what it hands
481
+ * over meanwhile (a submit-on-pause) is dropped too.
482
+ */
483
+ function hold(on) {
484
+ if (held === on) return;
485
+ held = on;
486
+ if (on) {
487
+ tainted = true;
488
+ clearTimer(cap);
489
+ resetLive();
490
+ dropCur();
491
+ if (state === "capturing") set("listening");
492
+ }
493
+ const v = vad;
494
+ if (v) ctl = ctl.then(() => on ? v.pause() : v.start()).catch(() => {});
495
+ }
496
+ return {
497
+ toggle: () => state === "off" ? on() : off(),
498
+ hold,
499
+ held: () => held,
500
+ off,
501
+ state: () => state
502
+ };
503
+ }
504
+ /** The URL with `lang` added to its query, when a hint is given. */
505
+ function sttUrl(url, lang) {
506
+ if (!lang) return url;
507
+ const at = url.indexOf("#");
508
+ const path = at < 0 ? url : url.slice(0, at);
509
+ const hash = at < 0 ? "" : url.slice(at);
510
+ return `${path}${path.includes("?") ? "&" : "?"}lang=${encodeURIComponent(lang)}${hash}`;
511
+ }
512
+ /**
513
+ * POST one recording to the host's STT endpoint: the raw audio as the body
514
+ * (16 kHz mono 16-bit PCM WAV) and its type as `content-type`. Answers the
515
+ * endpoint's JSON (`text` defaults to ""). Throws SttError on non-2xx, with
516
+ * the JSON's `error` as its message when there is one.
517
+ */
518
+ async function postStt(wav, req, f = fetch) {
519
+ const r = typeof req === "string" ? { url: req } : req;
520
+ const res = await f(sttUrl(r.url, r.lang), {
521
+ method: "POST",
522
+ body: wav,
523
+ headers: {
524
+ "content-type": r.type ?? "audio/wav",
525
+ ...r.headers
526
+ },
527
+ credentials: r.credentials ?? "same-origin"
528
+ });
529
+ const out = await res.json().catch(() => ({}));
530
+ if (!res.ok) throw new SttError(res.status, out.error ?? `stt ${res.status}`);
531
+ return {
532
+ ...out,
533
+ text: typeof out.text === "string" ? out.text : ""
534
+ };
535
+ }
536
+ /** The send tick: two soft sine tones, this loud at their peak, this long in all. */
537
+ const TICK_GAIN = .08;
538
+ const TICK_MS = 80;
539
+ /**
540
+ * A short, soft "tick" when a spoken sentence goes out (opt-in on the
541
+ * element: the `tick` attribute): two sine tones (the second a fifth up,
542
+ * 30 ms later) through one gain with a 5 ms attack and an exponential decay,
543
+ * TICK_MS long, peaking at TICK_GAIN. Web Audio only — no <audio> element —
544
+ * so iOS keeps it silent when the ringer is muted.
545
+ */
546
+ function scheduleTick(ctx, at = ctx.currentTime) {
547
+ const end = at + TICK_MS / 1e3;
548
+ const g = ctx.createGain();
549
+ g.gain.setValueAtTime(1e-4, at);
550
+ g.gain.linearRampToValueAtTime(TICK_GAIN, at + .005);
551
+ g.gain.exponentialRampToValueAtTime(1e-4, end);
552
+ g.connect(ctx.destination);
553
+ const tones = [[880, at], [1320, at + .03]];
554
+ for (const [hz, t] of tones) {
555
+ const o = ctx.createOscillator();
556
+ o.type = "sine";
557
+ o.frequency.setValueAtTime(hz, t);
558
+ o.connect(g);
559
+ o.start(t);
560
+ o.stop(end);
561
+ }
562
+ return end;
563
+ }
564
+
565
+ //#endregion
566
+ //#region src/mic-audio.ts
567
+ /**
568
+ * The mic's browser pieces: the stream's constraints, the page's one
569
+ * AudioContext, Silero VAD (@ricky0123/vad-web, loaded only when the host
570
+ * gives a source for it) and the energy-gate fallback that needs nothing.
571
+ *
572
+ * liagent has no runtime dependencies, so vad-web is never imported here.
573
+ * The host hands over a loader:
574
+ *
575
+ * mic.vad = { load: () => import("@ricky0123/vad-web"),
576
+ * baseAssetPath: "/vad/", onnxWASMBasePath: "/ort/" };
577
+ * mic.vad = vadFromScripts(VAD_DIST_URL, ORT_DIST_URL); // UMD bundles by <script>
578
+ *
579
+ * Without one, or when it fails to load (blocked wasm, offline CDN), the
580
+ * energy gate (src/mic.ts energyGate) cuts the utterances instead.
581
+ */
582
+ /** The mic with echo cancellation on (the default: the user may talk over the agent). */
583
+ const AEC_CONSTRAINTS = {
584
+ echoCancellation: true,
585
+ noiseSuppression: true,
586
+ autoGainControl: true,
587
+ channelCount: 1
588
+ };
589
+ /** Echo cancellation's "off" mode: capture is held while the agent speaks; no auto gain. */
590
+ const LEGACY_CONSTRAINTS = {
591
+ echoCancellation: true,
592
+ noiseSuppression: true,
593
+ channelCount: 1
594
+ };
595
+ const micConstraints = (aec = true) => aec ? { ...AEC_CONSTRAINTS } : { ...LEGACY_CONSTRAINTS };
596
+ /** What the browser actually applied to the mic track (no device ids), for a host's debug log. */
597
+ let applied = null;
598
+ function noteTrack(stream) {
599
+ try {
600
+ const { echoCancellation, noiseSuppression, autoGainControl, sampleRate, channelCount } = stream.getAudioTracks()[0]?.getSettings?.() ?? {};
601
+ applied = {
602
+ echoCancellation,
603
+ noiseSuppression,
604
+ autoGainControl,
605
+ sampleRate,
606
+ channelCount
607
+ };
608
+ } catch {
609
+ applied = null;
610
+ }
611
+ }
612
+ const appliedSettings = () => applied;
613
+ /**
614
+ * The page's one AudioContext for voice: the energy fallback records through
615
+ * it, the send tick plays on it, and cloud replies play through it. Made on
616
+ * the mic tap (a gesture, which iOS needs). Kept on globalThis, so every copy
617
+ * of the module shares it.
618
+ */
619
+ const CTX_KEY = "__liagentAudio";
620
+ function audioCtx() {
621
+ const g = globalThis;
622
+ const have = g[CTX_KEY];
623
+ if (have) return have;
624
+ const Ctx = globalThis.AudioContext ?? globalThis.webkitAudioContext;
625
+ return Ctx ? g[CTX_KEY] = new Ctx() : null;
626
+ }
627
+ /** The AudioContext if one was made (never makes one). */
628
+ const existingCtx = () => globalThis[CTX_KEY] ?? null;
629
+ /** The browser can capture: getUserMedia and Web Audio. */
630
+ const canCapture = () => typeof navigator !== "undefined" && !!navigator.mediaDevices?.getUserMedia && !!(globalThis.AudioContext ?? globalThis.webkitAudioContext);
631
+ /** The mic stream, with the constraints for `aec`; what was applied is noted. */
632
+ async function micStream(aec = true) {
633
+ const s = await navigator.mediaDevices.getUserMedia({ audio: micConstraints(aec) });
634
+ noteTrack(s);
635
+ return s;
636
+ }
637
+ const loadScript = (src) => new Promise((resolve, reject) => {
638
+ if (document.querySelector(`script[src="${CSS.escape(src)}"]`)) return resolve();
639
+ const s = document.createElement("script");
640
+ s.src = src;
641
+ s.async = true;
642
+ s.onload = () => resolve();
643
+ s.onerror = () => {
644
+ s.remove();
645
+ reject(/* @__PURE__ */ new Error(`could not load ${src}`));
646
+ };
647
+ document.head.append(s);
648
+ });
649
+ const dir = (u) => u.endsWith("/") ? u : `${u}/`;
650
+ /**
651
+ * vad-web from its UMD builds, by <script> tags: `vadBase` is vad-web's dist
652
+ * directory (bundle.min.js, the model, the worklet) and `ortBase`
653
+ * onnxruntime-web's (ort.wasm.min.js and the wasm). E.g. pinned on a CDN:
654
+ *
655
+ * vadFromScripts("https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",
656
+ * "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/")
657
+ *
658
+ * The page's CSP must allow both origins (script-src, connect-src, and
659
+ * 'wasm-unsafe-eval').
660
+ */
661
+ function vadFromScripts(vadBase, ortBase) {
662
+ const vad = dir(vadBase);
663
+ const ort = dir(ortBase);
664
+ return {
665
+ baseAssetPath: vad,
666
+ onnxWASMBasePath: ort,
667
+ load: async () => {
668
+ await loadScript(`${ort}ort.wasm.min.js`);
669
+ await loadScript(`${vad}bundle.min.js`);
670
+ const g = globalThis.vad;
671
+ if (!g?.MicVAD) throw new Error("vad-web did not load");
672
+ return g;
673
+ }
674
+ };
675
+ }
676
+ const vadConfig = (s) => typeof s === "function" ? { load: s } : s;
677
+ /**
678
+ * Silero on the session's stream (never stops it): ends an utterance after
679
+ * ~0.8 s of silence; each frame's speech probability goes to onFrame.
680
+ */
681
+ async function sileroVad(ev, stream, src) {
682
+ const c = vadConfig(src);
683
+ const m = await c.load();
684
+ const mod = "MicVAD" in m ? m : m.default;
685
+ if (!mod?.MicVAD) throw new Error("vad-web: no MicVAD");
686
+ const v = await mod.MicVAD.new({
687
+ ...c.baseAssetPath ? { baseAssetPath: c.baseAssetPath } : {},
688
+ ...c.onnxWASMBasePath ? { onnxWASMBasePath: c.onnxWASMBasePath } : {},
689
+ model: c.model ?? "v5",
690
+ submitUserSpeechOnPause: true,
691
+ startOnLoad: false,
692
+ ...c.options,
693
+ getStream: async () => stream,
694
+ pauseStream: async () => {},
695
+ resumeStream: async () => stream,
696
+ onSpeechStart: ev.onSpeechStart,
697
+ onSpeechEnd: ev.onSpeechEnd,
698
+ onVADMisfire: ev.onMisfire,
699
+ onFrameProcessed: (p, frame) => ev.onFrame?.(frame, p?.isSpeech)
700
+ });
701
+ return {
702
+ start: () => v.start(),
703
+ pause: () => v.pause(),
704
+ flush: async () => {
705
+ await v.pause();
706
+ await v.start();
707
+ },
708
+ destroy: () => v.destroy()
709
+ };
710
+ }
711
+ /** The fallback: an energy threshold on the raw signal (energyGate), on the session's stream. */
712
+ async function energyVad(ev, stream) {
713
+ const ctx = audioCtx();
714
+ if (!ctx) throw new Error("no Web Audio");
715
+ const src = ctx.createMediaStreamSource(stream);
716
+ const node = ctx.createScriptProcessor(2048, 1, 1);
717
+ const gate = energyGate({ rate: ctx.sampleRate });
718
+ let on = false;
719
+ const emit = (r) => {
720
+ if (r === "start") ev.onSpeechStart();
721
+ else if (r === "misfire") ev.onMisfire();
722
+ else if (r) ev.onSpeechEnd(resample(r, ctx.sampleRate, RATE));
723
+ };
724
+ node.onaudioprocess = (e) => {
725
+ if (!on) return;
726
+ const frame = new Float32Array(e.inputBuffer.getChannelData(0));
727
+ const r = gate.push(frame);
728
+ if (r === "start") emit(r);
729
+ ev.onFrame?.(resample(frame, ctx.sampleRate, RATE));
730
+ if (r !== "start") emit(r);
731
+ };
732
+ src.connect(node);
733
+ node.connect(ctx.destination);
734
+ return {
735
+ start: () => {
736
+ on = true;
737
+ return ctx.resume();
738
+ },
739
+ pause: () => {
740
+ on = false;
741
+ emit(gate.flush());
742
+ },
743
+ flush: () => emit(gate.flush()),
744
+ destroy: () => {
745
+ on = false;
746
+ node.disconnect();
747
+ src.disconnect();
748
+ }
749
+ };
750
+ }
751
+
752
+ //#endregion
753
+ export { isDictationBurst as A, scheduleTick as B, TICK_GAIN as C, createMic as D, appendDictation as E, micStatus as F, postStt as I, punctuate as L, joinText as M, mergeOverlap as N, encodeWav as O, micErrorNote as P, resample as R, SttError as S, UtteranceQueue as T, sttUrl as V, PARTIAL_EVERY_MS as _, canCapture as a, PENDING_MARK as b, micConstraints as c, sileroVad as d, vadFromScripts as f, MIC_ERROR_STRINGS_EN as g, MAX_UTTERANCE_MS as h, audioCtx as i, isMicDenied as j, energyGate as k, micStream as l, ENDS_SENTENCE as m, LEGACY_CONSTRAINTS as n, energyVad as o, AUTO_SEND_MIN as p, appliedSettings as r, existingCtx as s, AEC_CONSTRAINTS as t, noteTrack as u, PARTIAL_MIN_MS as v, TICK_MS as w, RATE as x, PARTIAL_OVERLAP_MS as y, rms as z };
754
+ //# sourceMappingURL=mic-audio-C3Shud_F.js.map