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,802 @@
1
+ import { pickLang } from "./protocol.js";
2
+ import { a as speechRate } from "./speech-rate-DXeJjRTc.js";
3
+ import { O as encodeWav, s as existingCtx } from "./mic-audio-C3Shud_F.js";
4
+ import { a as echoScore, r as ECHO_WINDOW_MS } from "./echo-BvzPSI0x.js";
5
+
6
+ //#region src/voice-out.ts
7
+ /**
8
+ * How the agent's voice leaves the page, and how the mic is opened:
9
+ *
10
+ * - `liagent:voice-out` (localStorage) picks the output: "speech" (the
11
+ * default: the device's own speechSynthesis) or "cloud" (each sentence
12
+ * fetched from the host's TTS endpoint and played through one `<audio>`
13
+ * element routed through the mic's AudioContext and a GainNode — page
14
+ * audio, so the browser's echo canceller has it as its reference, and the
15
+ * gain ducks it; iOS ignores `element.volume`). "cloud" needs a TTS URL
16
+ * from the host (`voice({ tts })`); without one it is "speech".
17
+ * - `liagent:voice-aec` (default on) opens the mic with echoCancellation,
18
+ * noiseSuppression and autoGainControl and keeps it open while the agent
19
+ * speaks. "0": capture is held while the agent speaks instead.
20
+ *
21
+ * createCloudOut takes its browser pieces injected (fetch, the element, the
22
+ * AudioContext), so it is tested with fakes in test/voice-out.test.ts.
23
+ */
24
+ const VOICE_OUT_KEY = "liagent:voice-out";
25
+ const VOICE_AEC_KEY = "liagent:voice-aec";
26
+ /** A clip resumed after an interruption starts this much before where it stopped. */
27
+ const RESUME_REWIND_S = .3;
28
+ const ignore = () => {};
29
+ /** Clips (blob URLs) kept for replays and resumes. */
30
+ const CLIP_CACHE = 64;
31
+ const read = (k) => {
32
+ try {
33
+ return globalThis.localStorage?.getItem(k) ?? null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ };
38
+ /** The output asked for on this device: "cloud" only when set so. */
39
+ const outMode = () => read(VOICE_OUT_KEY) === "cloud" ? "cloud" : "speech";
40
+ /** Echo-cancelled barge-in (default on; "0" = capture held while the agent speaks). */
41
+ const aecOn = () => read(VOICE_AEC_KEY) !== "0";
42
+ /** A base URL as a TtsUrl: `?lang=<base language>&text=<text>` added to its query. */
43
+ function ttsUrlFrom(src) {
44
+ if (typeof src === "function") return src;
45
+ return (text, lang) => `${src}${src.includes("?") ? "&" : "?"}lang=${encodeURIComponent(lang.split(/[-_]/)[0] ?? lang)}&text=${encodeURIComponent(text)}`;
46
+ }
47
+ /** Why a sentence cannot be fetched at all (null: try the endpoint). */
48
+ function cloudSkip(text, lang, lim = {}) {
49
+ const langs = lim.langs ? new Set(lim.langs) : null;
50
+ if (langs && !langs.has(lang.toLowerCase().split(/[-_]/)[0] ?? "")) return "lang";
51
+ if (!text.trim()) return "empty";
52
+ if (lim.maxText !== void 0 && text.length > lim.maxText) return "long";
53
+ return null;
54
+ }
55
+ /**
56
+ * Cloud replies: one `<audio>` element for the whole page (unlocked once in
57
+ * a gesture, so iOS lets later sentences play), routed through the
58
+ * AudioContext and one GainNode. A sentence that cannot be fetched or played
59
+ * calls `onfail` (the session reads it with speechSynthesis instead).
60
+ */
61
+ function createCloudOut(d) {
62
+ const toUrl = d.toUrl ?? ((b) => URL.createObjectURL(b));
63
+ const revoke = d.revoke ?? ((u) => URL.revokeObjectURL(u));
64
+ /** Read each time: the page's output may switch endpoints. */
65
+ const lim = () => ({
66
+ langs: d.langs,
67
+ maxText: d.maxText
68
+ });
69
+ const clips = /* @__PURE__ */ new Map();
70
+ let el = null;
71
+ let gain = null;
72
+ let wired = false;
73
+ /** Bumped by every play and stop: the element's events for older ones are ignored. */
74
+ let turn = 0;
75
+ const element = () => {
76
+ if (!el) {
77
+ el = d.element();
78
+ el.preload = "auto";
79
+ }
80
+ if (!wired) {
81
+ const ctx = d.ctx();
82
+ if (ctx) {
83
+ wired = true;
84
+ try {
85
+ const g = ctx.createGain();
86
+ ctx.createMediaElementSource(el).connect(g);
87
+ g.connect(ctx.destination);
88
+ gain = g;
89
+ } catch {
90
+ gain = null;
91
+ }
92
+ }
93
+ }
94
+ return el;
95
+ };
96
+ const fetchClip = (text, lang) => {
97
+ const key = `${lang}\n${text}`;
98
+ const have = clips.get(key);
99
+ if (have) return have;
100
+ const url = d.url();
101
+ const p = url ? d.fetch(url(text, lang)).then(async (r) => {
102
+ const why = r.headers.get("X-Voice");
103
+ if (!r.ok) throw new Error(`http ${r.status}${why ? ` ${why}` : ""}`);
104
+ return toUrl(await r.blob());
105
+ }) : Promise.reject(/* @__PURE__ */ new Error("no tts url"));
106
+ clips.set(key, p);
107
+ p.catch(() => clips.delete(key));
108
+ if (clips.size > CLIP_CACHE) {
109
+ const first = clips.entries().next().value;
110
+ if (first) {
111
+ clips.delete(first[0]);
112
+ first[1].then(revoke, ignore);
113
+ }
114
+ }
115
+ return p;
116
+ };
117
+ const ramp = (level, ms) => {
118
+ const ctx = d.ctx();
119
+ if (gain && ctx) {
120
+ const now = ctx.currentTime;
121
+ gain.gain.cancelScheduledValues(now);
122
+ gain.gain.setValueAtTime(gain.gain.value, now);
123
+ gain.gain.linearRampToValueAtTime(level, now + ms / 1e3);
124
+ } else if (el) el.volume = level;
125
+ };
126
+ const setLevel = (level) => {
127
+ const ctx = d.ctx();
128
+ if (gain && ctx) {
129
+ gain.gain.cancelScheduledValues(ctx.currentTime);
130
+ gain.gain.setValueAtTime(level, ctx.currentTime);
131
+ } else if (el) el.volume = level;
132
+ };
133
+ return {
134
+ unlock() {
135
+ const a = element();
136
+ if (!a.paused) return;
137
+ a.src = silentWav();
138
+ a.play().then(() => a.pause(), ignore);
139
+ },
140
+ gain: () => gain,
141
+ prepare(text, lang) {
142
+ if (!cloudSkip(text, lang, lim())) fetchClip(text, lang).catch(ignore);
143
+ },
144
+ play(s, ev) {
145
+ const me = ++turn;
146
+ const live = () => me === turn;
147
+ const fail = (why) => void Promise.resolve().then(() => live() && ev.onfail?.(why));
148
+ const pb = {
149
+ route: "audio",
150
+ stop() {
151
+ if (!live()) return {};
152
+ turn++;
153
+ const a = el;
154
+ if (!a) return { at: s.at };
155
+ a.pause();
156
+ return { at: Math.max(0, a.currentTime - RESUME_REWIND_S) };
157
+ },
158
+ volume: (level, ms) => live() && ramp(level, ms)
159
+ };
160
+ const skip = cloudSkip(s.text, s.lang, lim());
161
+ if (skip) {
162
+ fail(skip);
163
+ return pb;
164
+ }
165
+ fetchClip(s.text, s.lang).then((url) => {
166
+ if (!live()) return;
167
+ const a = element();
168
+ d.ctx()?.resume?.().catch(ignore);
169
+ setLevel(s.volume);
170
+ a.onended = () => live() && ev.onend();
171
+ a.onerror = () => live() && ev.onerror();
172
+ a.onloadedmetadata = () => {
173
+ if (!live()) return;
174
+ a.onloadedmetadata = null;
175
+ a.currentTime = s.at;
176
+ const rate = s.rate ?? 1;
177
+ a.defaultPlaybackRate = rate;
178
+ a.playbackRate = rate;
179
+ a.preservesPitch = true;
180
+ a.webkitPreservesPitch = true;
181
+ a.play().catch((e) => {
182
+ if (live()) ev.onfail?.(`play ${e?.name ?? "error"}`);
183
+ });
184
+ };
185
+ a.src = url;
186
+ a.load();
187
+ }, (e) => live() && ev.onfail?.(String(e?.message ?? e)));
188
+ return pb;
189
+ }
190
+ };
191
+ }
192
+ /** 10 ms of silence (8 kHz WAV): what unlock() plays in the gesture. */
193
+ let silent = "";
194
+ const silentWav = () => {
195
+ if (silent) return silent;
196
+ let bin = "";
197
+ for (const b of encodeWav(new Float32Array(80), 8e3)) bin += String.fromCharCode(b);
198
+ return silent = `data:audio/wav;base64,${btoa(bin)}`;
199
+ };
200
+ const CLOUD_KEY = "__liagentCloudOut";
201
+ /**
202
+ * The page's cloud output (null outside a browser), on fetch, new Audio()
203
+ * and the page's AudioContext. `tts` (and `limits`) set the endpoint; a
204
+ * later call with another one switches to it.
205
+ */
206
+ function cloudOut(tts, limits) {
207
+ const g = globalThis;
208
+ let h = g[CLOUD_KEY];
209
+ if (!h) {
210
+ if (typeof Audio === "undefined" || typeof fetch === "undefined") return null;
211
+ const holder = {
212
+ url: null,
213
+ lim: limits ?? {},
214
+ out: null
215
+ };
216
+ holder.out = createCloudOut({
217
+ url: () => holder.url,
218
+ fetch: (u) => fetch(u, { credentials: "same-origin" }),
219
+ element: () => new Audio(),
220
+ ctx: () => existingCtx(),
221
+ get langs() {
222
+ return holder.lim.langs;
223
+ },
224
+ get maxText() {
225
+ return holder.lim.maxText;
226
+ }
227
+ });
228
+ h = g[CLOUD_KEY] = holder;
229
+ }
230
+ if (tts !== void 0) h.url = tts ? ttsUrlFrom(tts) : null;
231
+ if (limits) h.lim = limits;
232
+ return h.out;
233
+ }
234
+ /** The cloud output has an endpoint to fetch from. */
235
+ const cloudReady = () => !!globalThis[CLOUD_KEY]?.url;
236
+
237
+ //#endregion
238
+ //#region src/voice.ts
239
+ /**
240
+ * Hands-free voice out: the one place that decides when agent replies are
241
+ * read aloud, how loud, and how the mic treats them. The page has one
242
+ * session (`voice()`, kept on globalThis), so every copy of the module — a
243
+ * bundled box, a hot-loaded one — reads through the same queue.
244
+ *
245
+ * import { voice } from "liagent/voice";
246
+ * const v = voice({ tts: "/api/tts" }); // tts: only for the "cloud" output
247
+ * box.voice = v; // the box calls v.speak(text, id) / v.stop(why)
248
+ * mic.voice = v; // <liagent-mic>: ducking, barge-in, the echo guard
249
+ *
250
+ * - Replies go in a FIFO queue, one utterance per sentence (sentences longer
251
+ * than CHUNK_MAX are cut at a clause or a space); a new reply waits behind
252
+ * the one being read and never cuts it off.
253
+ * - Output (src/voice-out.ts, `liagent:voice-out`): the device's
254
+ * speechSynthesis ("speech", the default; the most natural installed voice,
255
+ * voiceQuality), or "cloud": each sentence from the host's TTS endpoint,
256
+ * played through the page's own audio so the echo canceller hears it. A
257
+ * sentence the cloud cannot voice is read by speechSynthesis instead.
258
+ * - The speed (src/speech-rate.ts, `liagent:speech-rate`) applies from the
259
+ * next utterance, on both outputs.
260
+ * - Mic on: every reply is read, whatever the read-aloud toggle says (the
261
+ * toggle itself is never changed, so it is "restored" when the mic stops).
262
+ * Mic off: a reply is read only with the toggle on (`liagent:speak`, the
263
+ * box's) and `here()` (default: this tab is visible).
264
+ * - Echo (`liagent:voice-aec`, default on): the mic stays open while the
265
+ * agent speaks — echo cancellation, then the text guard (src/echo.ts)
266
+ * drops what leaks through. The user speaking over the agent ducks it to
267
+ * DUCK_LEVEL; speech that goes on for BARGE_IN_MS (and sounds like speech:
268
+ * isBargeIn) is a barge-in and pauses the reading. With
269
+ * `liagent:voice-aec` = "0": `hold` is true while an utterance plays (and
270
+ * RESUME_TAIL_MS after), and the mic holds its capture.
271
+ * - An interruption (a barge-in, a tap on the mic, typing) stops the utterance
272
+ * and remembers where: the clip's time (cloud), else the last word boundary
273
+ * the browser reported, else the start of that sentence. Speech or a tap
274
+ * resumes once the user's line was sent, or after IDLE_RESUME_MS of quiet;
275
+ * typing waits for resume() (a send, or a blur). `stop()` clears the queue.
276
+ *
277
+ * Everything browser-shaped is injected, so this is tested with fakes
278
+ * (test/voice-session.test.ts). Event-driven only: utterance and clip
279
+ * events and one-shot timers, never polling.
280
+ */
281
+ /** Capture resumes this long after the last utterance ends (the room's echo; hold mode). */
282
+ const RESUME_TAIL_MS = 400;
283
+ /** An interruption with nothing said (or nothing more) resumes the reading after this. */
284
+ const IDLE_RESUME_MS = 1500;
285
+ /** While the user talks over the agent, the agent plays this loud… */
286
+ const DUCK_LEVEL = .25;
287
+ /** …reached over this long (cloud; speechSynthesis takes it from its next sentence)… */
288
+ const DUCK_ATTACK_MS = 80;
289
+ /** …and back to full over this long once the user stops. */
290
+ const DUCK_RELEASE_MS = 200;
291
+ /** The user talking over the agent this long is a barge-in: the reading pauses. */
292
+ const BARGE_IN_MS = 1500;
293
+ /**
294
+ * …and only if it sounds like speech: the VAD's mean speech probability over
295
+ * that window reaches this (above Silero's own 0.5 start threshold, since the
296
+ * echo that leaks through tends to score lower). Weaker speech keeps the
297
+ * agent ducked and is judged again after another BARGE_IN_MS.
298
+ */
299
+ const BARGE_IN_PROB = .7;
300
+ /** Sentences are cut to at most this many characters (a TTS endpoint's usual limit). */
301
+ const CHUNK_MAX = 200;
302
+ /** localStorage: the read-aloud toggle ("0" = replies silent), the box's own key. */
303
+ const SPEAK_KEY = "liagent:speak";
304
+ /** globalThis key of the shared session. */
305
+ const VOICE_SESSION_KEY = "__liagentVoice";
306
+ /** The session's version: a copy on the page with another one is replaced. */
307
+ const V = 1;
308
+ /** Message ids already read, so a replayed message is not read twice. */
309
+ const SPOKEN_IDS = 200;
310
+ const CJK_STOP = "。.!?";
311
+ const LATIN_STOP = ".!?";
312
+ const CLOSERS = "」』)】〕〉》\"'”’)]";
313
+ /**
314
+ * A reply as sentences: cut after 。.!? (with any closing quotes or
315
+ * brackets), after . ! ? followed by a space or the end (so 3.14 and e.g.
316
+ * mid-word stay whole), and at every newline. Blank pieces are dropped.
317
+ */
318
+ function sentences(text) {
319
+ const out = [];
320
+ let cur = "";
321
+ const push = () => {
322
+ const t = cur.trim();
323
+ if (t) out.push(t);
324
+ cur = "";
325
+ };
326
+ for (let i = 0; i < text.length; i++) {
327
+ const c = text[i] ?? "";
328
+ if (c === "\n" || c === "\r") {
329
+ push();
330
+ continue;
331
+ }
332
+ cur += c;
333
+ const cjk = CJK_STOP.includes(c);
334
+ if (!cjk && !LATIN_STOP.includes(c)) continue;
335
+ while (i + 1 < text.length && (CJK_STOP + LATIN_STOP + CLOSERS).includes(text[i + 1] ?? "\n")) cur += text[++i];
336
+ if (cjk || i + 1 >= text.length || /\s/.test(text[i + 1] ?? "")) push();
337
+ }
338
+ push();
339
+ return out;
340
+ }
341
+ const CLAUSE = /[、,,;;::]/;
342
+ /** A sentence in pieces of at most `max` chars: after the last clause mark, else a space, else hard. */
343
+ function chunk(s, max = CHUNK_MAX) {
344
+ const out = [];
345
+ let rest = s.trim();
346
+ while (rest.length > max) {
347
+ const head = rest.slice(0, max);
348
+ let cut = -1;
349
+ for (let i = head.length - 1; i > max / 3; i--) if (CLAUSE.test(head[i] ?? "")) {
350
+ cut = i + 1;
351
+ break;
352
+ }
353
+ if (cut < 0) {
354
+ const sp = head.lastIndexOf(" ");
355
+ cut = sp > max / 3 ? sp + 1 : max;
356
+ }
357
+ out.push(rest.slice(0, cut).trim());
358
+ rest = rest.slice(cut).trim();
359
+ }
360
+ if (rest) out.push(rest);
361
+ return out;
362
+ }
363
+ /** A barge-in, by the VAD's speech probabilities over the window (none known, as with the energy VAD: yes). */
364
+ function isBargeIn(probs, min = BARGE_IN_PROB) {
365
+ if (!probs.length) return true;
366
+ return probs.reduce((a, b) => a + b, 0) / probs.length >= min;
367
+ }
368
+ /**
369
+ * How natural a voice sounds, higher is better. iOS lists its Eloquence
370
+ * voices (Eddy, Flo, Grandma, …) and the novelty ones (Bahh, Bubbles,
371
+ * Zarvox, …) first for most languages, and marks every voice `default`, so
372
+ * "the first voice of the language" sounds robotic or silly there. Prefer
373
+ * Premium/Enhanced (and Siri), then the regular named voice.
374
+ */
375
+ function voiceQuality(v) {
376
+ const uri = (v.voiceURI ?? "").toLowerCase();
377
+ if (uri.includes("eloquence") || uri.includes("speech.synthesis.voice.")) return 0;
378
+ if (uri.includes("premium")) return 4;
379
+ if (uri.includes("enhanced")) return 3;
380
+ if (uri.includes("siri")) return 3;
381
+ return 2;
382
+ }
383
+ /**
384
+ * An installed voice for `lang`: the exact locale first, then the same
385
+ * language; among those the most natural (voiceQuality), the default first.
386
+ */
387
+ function pickNaturalVoice(voices, lang) {
388
+ const norm = (l) => l.replace(/_/g, "-").toLowerCase();
389
+ const want = norm(lang);
390
+ const base = want.split("-")[0];
391
+ const exact = voices.filter((v) => norm(v.lang) === want);
392
+ const same = voices.filter((v) => norm(v.lang).split("-")[0] === base);
393
+ const pool = exact.length ? exact : same;
394
+ const best = Math.max(-1, ...pool.map(voiceQuality));
395
+ const top = pool.filter((v) => voiceQuality(v) === best);
396
+ return top.find((v) => v.default) ?? top[0];
397
+ }
398
+ const WHYS = [
399
+ "speech",
400
+ "tap",
401
+ "typing"
402
+ ];
403
+ function createVoice(d) {
404
+ const setTimer = d.setTimer ?? ((f, ms) => setTimeout(f, ms));
405
+ const clearTimer = d.clearTimer ?? ((t) => clearTimeout(t));
406
+ const now = d.now ?? (() => Date.now());
407
+ const cloud = () => d.cloud?.() ?? null;
408
+ const mode = () => d.mode?.() === "cloud" && cloud() ? "cloud" : "speech";
409
+ const aec = () => d.aec?.() ?? true;
410
+ let log = d.log ?? (() => {});
411
+ let mic = false;
412
+ let speaking = false;
413
+ const queue = [];
414
+ /** Interruptions under way; the reading waits while any is. */
415
+ const pauses = /* @__PURE__ */ new Set();
416
+ /** The sentence playing: how, (speech) the char of the last word boundary heard, and its record. */
417
+ let current = null;
418
+ let tail;
419
+ let idle;
420
+ /** Bumped whenever the utterance playing is dropped: its late events are ignored. */
421
+ let epoch = 0;
422
+ /** The agent's volume: 1, or DUCK_LEVEL while the user talks over it. */
423
+ let level = 1;
424
+ /** Ducked: the barge-in timer, and the speech probabilities heard since it was armed. */
425
+ let duck = null;
426
+ const said = [];
427
+ const spokenIds = [];
428
+ const subs = /* @__PURE__ */ new Set();
429
+ const state = () => ({
430
+ mic,
431
+ speaking,
432
+ hold: speaking && !aec(),
433
+ ducked: !!duck,
434
+ queued: queue.length,
435
+ paused: pauses.size > 0
436
+ });
437
+ const emit = () => {
438
+ const s = state();
439
+ for (const f of subs) f(s);
440
+ };
441
+ const focusRule = () => d.enabled() && (d.here?.() ?? true);
442
+ const canSpeak = () => !!d.synth() || mode() === "cloud";
443
+ const ended = () => {
444
+ if (current && current.said.end === void 0) current.said.end = now();
445
+ };
446
+ /** Read one sentence with speechSynthesis (from its last word boundary). */
447
+ const speech = (head, ev, e) => {
448
+ const s = d.synth();
449
+ if (!s) return null;
450
+ const from = head.from;
451
+ const u = d.utter(head.text.slice(from), head.lang);
452
+ if (level !== 1) u.volume = level;
453
+ u.rate = d.rate?.() ?? 1;
454
+ u.onboundary = (b) => {
455
+ if (e !== epoch || !current) return;
456
+ if (b.name && b.name !== "word") return;
457
+ current.mark = from + Math.max(0, b.charIndex | 0);
458
+ };
459
+ u.onend = () => ev.onend();
460
+ u.onerror = () => ev.onerror();
461
+ s.speak(u);
462
+ return {
463
+ route: "speech",
464
+ stop: () => {
465
+ s.cancel();
466
+ return {};
467
+ },
468
+ volume: () => {}
469
+ };
470
+ };
471
+ /** Speak the head of the queue, if nothing is playing and nothing waits (the caller emits). */
472
+ const next = () => {
473
+ if (current || pauses.size || !canSpeak()) return;
474
+ const head = queue[0];
475
+ if (!head) return;
476
+ const e = epoch;
477
+ const done = () => {
478
+ if (e !== epoch) return;
479
+ ended();
480
+ current = null;
481
+ queue.shift();
482
+ next();
483
+ if (!current) {
484
+ clearTimer(tail);
485
+ tail = setTimer(() => {
486
+ if (e !== epoch || current) return;
487
+ speaking = false;
488
+ emit();
489
+ }, RESUME_TAIL_MS);
490
+ }
491
+ emit();
492
+ };
493
+ const info = {
494
+ lang: head.lang,
495
+ chars: head.text.length
496
+ };
497
+ const ev = {
498
+ onend: done,
499
+ onerror: done,
500
+ onfail: (reason) => {
501
+ if (e !== epoch || !current) return;
502
+ log({
503
+ ev: "voice-out",
504
+ out: "cloud",
505
+ route: "speech",
506
+ fallback: reason,
507
+ ...info
508
+ });
509
+ const p = speech(head, ev, e);
510
+ if (!p) return done();
511
+ current.p = p;
512
+ }
513
+ };
514
+ const rec = {
515
+ text: head.text,
516
+ start: now()
517
+ };
518
+ const c = mode() === "cloud" ? cloud() : null;
519
+ current = {
520
+ p: null,
521
+ mark: head.from,
522
+ said: rec
523
+ };
524
+ const p = c ? c.play({
525
+ text: head.text,
526
+ lang: head.lang,
527
+ at: head.at,
528
+ volume: level,
529
+ rate: d.rate?.() ?? 1
530
+ }, ev) : speech(head, ev, e);
531
+ if (!p) {
532
+ current = null;
533
+ return;
534
+ }
535
+ current.p = p;
536
+ said.push(rec);
537
+ if (said.length > 50) said.shift();
538
+ log({
539
+ ev: "voice-out",
540
+ out: c ? "cloud" : "speech",
541
+ route: p.route,
542
+ ...info,
543
+ volume: level,
544
+ at: head.at || void 0,
545
+ from: head.from || void 0
546
+ });
547
+ const after = queue[1];
548
+ if (c && after) c.prepare?.(after.text, after.lang);
549
+ clearTimer(tail);
550
+ speaking = true;
551
+ };
552
+ /** Drop the utterance playing (keeping where it got to) and release the mic at once. */
553
+ const halt = (keepPlace) => {
554
+ epoch++;
555
+ clearTimer(tail);
556
+ if (current) {
557
+ ended();
558
+ const place = current.p.stop();
559
+ const head = queue[0];
560
+ if (keepPlace && head) if (current.p.route === "audio") head.at = place.at ?? head.at;
561
+ else {
562
+ head.from = current.mark;
563
+ head.at = 0;
564
+ }
565
+ current = null;
566
+ }
567
+ speaking = false;
568
+ };
569
+ const setLevel = (l, ms) => {
570
+ level = l;
571
+ current?.p.volume(l, ms);
572
+ };
573
+ /** Back to full volume: ramped (the user stopped) or at once (the reading stopped). */
574
+ const unduck = (ms) => {
575
+ if (!duck) return;
576
+ clearTimer(duck.timer);
577
+ duck = null;
578
+ setLevel(1, ms);
579
+ };
580
+ const armBarge = () => {
581
+ const dk = duck;
582
+ if (!dk) return;
583
+ clearTimer(dk.timer);
584
+ dk.timer = setTimer(() => {
585
+ if (duck !== dk) return;
586
+ const probs = dk.probs;
587
+ dk.probs = [];
588
+ const prob = probs.length ? probs.reduce((a, b) => a + b, 0) / probs.length : void 0;
589
+ if (!isBargeIn(probs)) {
590
+ log({
591
+ ev: "voice-duck-hold",
592
+ prob
593
+ });
594
+ return armBarge();
595
+ }
596
+ log({
597
+ ev: "voice-barge-in",
598
+ prob
599
+ });
600
+ api.interrupt("speech");
601
+ }, BARGE_IN_MS);
602
+ };
603
+ const resume = () => {
604
+ clearTimer(idle);
605
+ if (!pauses.size) return;
606
+ pauses.clear();
607
+ next();
608
+ emit();
609
+ };
610
+ const clear = () => {
611
+ halt(false);
612
+ unduck(0);
613
+ clearTimer(idle);
614
+ queue.length = 0;
615
+ pauses.clear();
616
+ emit();
617
+ };
618
+ const api = {
619
+ v: V,
620
+ state,
621
+ subscribe(f) {
622
+ subs.add(f);
623
+ return () => void subs.delete(f);
624
+ },
625
+ setLog(f) {
626
+ log = f;
627
+ },
628
+ log: (ev) => log(ev),
629
+ mode,
630
+ aec,
631
+ shouldSpeak: () => mic || focusRule(),
632
+ readAloud: () => mic || d.enabled(),
633
+ setMic(on) {
634
+ if (mic === on) return;
635
+ mic = on;
636
+ if (!on && !focusRule()) return clear();
637
+ emit();
638
+ },
639
+ reply(text) {
640
+ if (!canSpeak() || !api.shouldSpeak()) return false;
641
+ const lang = pickLang(text);
642
+ const add = sentences(text).flatMap((s) => chunk(s)).map((t) => ({
643
+ text: t,
644
+ lang,
645
+ from: 0,
646
+ at: 0
647
+ }));
648
+ const first = add[0];
649
+ if (!first) return false;
650
+ const c = mode() === "cloud" ? cloud() : null;
651
+ if (c && !queue.length) c.prepare?.(first.text, lang);
652
+ queue.push(...add);
653
+ next();
654
+ emit();
655
+ return true;
656
+ },
657
+ speak(text, id) {
658
+ if (id) {
659
+ if (spokenIds.includes(id)) return;
660
+ spokenIds.push(id);
661
+ if (spokenIds.length > SPOKEN_IDS) spokenIds.shift();
662
+ }
663
+ api.reply(text);
664
+ },
665
+ stop(why) {
666
+ if (why && WHYS.includes(why)) return api.interrupt(why);
667
+ clear();
668
+ },
669
+ unlock() {
670
+ d.unlock?.();
671
+ },
672
+ userSpeech() {
673
+ if (current && aec()) {
674
+ if (!duck) {
675
+ duck = {
676
+ timer: void 0,
677
+ probs: []
678
+ };
679
+ setLevel(DUCK_LEVEL, DUCK_ATTACK_MS);
680
+ log({
681
+ ev: "voice-duck",
682
+ route: current.p.route
683
+ });
684
+ emit();
685
+ }
686
+ armBarge();
687
+ return;
688
+ }
689
+ api.interrupt("speech");
690
+ },
691
+ userFrame(prob) {
692
+ duck?.probs.push(prob);
693
+ },
694
+ interrupt(why) {
695
+ if (!queue.length && !current) {
696
+ unduck(0);
697
+ if (speaking) {
698
+ halt(false);
699
+ emit();
700
+ }
701
+ return;
702
+ }
703
+ halt(true);
704
+ unduck(0);
705
+ pauses.add(why);
706
+ clearTimer(idle);
707
+ if (why === "tap") idle = setTimer(resume, IDLE_RESUME_MS);
708
+ emit();
709
+ },
710
+ userIdle() {
711
+ if (duck) {
712
+ unduck(DUCK_RELEASE_MS);
713
+ emit();
714
+ return;
715
+ }
716
+ if (!pauses.has("speech") && !pauses.has("tap")) return;
717
+ clearTimer(idle);
718
+ idle = setTimer(resume, IDLE_RESUME_MS);
719
+ },
720
+ resume,
721
+ echoCheck(transcript, durationMs = 0) {
722
+ const t = now();
723
+ const from = t - durationMs;
724
+ const recent = said.filter((r) => (r.end ?? t) >= from - ECHO_WINDOW_MS).map((r) => r.text);
725
+ const during = said.some((r) => r.start <= t && (r.end ?? t) >= from);
726
+ return {
727
+ ...echoScore(transcript, recent),
728
+ during
729
+ };
730
+ },
731
+ echoDropped() {
732
+ if (pauses.size === 1 && pauses.has("speech")) resume();
733
+ }
734
+ };
735
+ return api;
736
+ }
737
+ const synth = () => typeof speechSynthesis === "undefined" ? null : speechSynthesis;
738
+ /** Whether agent replies are read aloud on this device (on unless turned off; the box's toggle). */
739
+ const speechEnabled = (key = SPEAK_KEY) => {
740
+ try {
741
+ return globalThis.localStorage?.getItem(key) !== "0";
742
+ } catch {
743
+ return true;
744
+ }
745
+ };
746
+ /** The default `here`: this tab is visible. */
747
+ function speakHere() {
748
+ return typeof document !== "undefined" && document.visibilityState === "visible";
749
+ }
750
+ /**
751
+ * Utterances still playing are kept here: Chrome may garbage-collect one
752
+ * nothing references, and then its `end` never fires.
753
+ */
754
+ const alive = /* @__PURE__ */ new Set();
755
+ /** The page's voice session, shared by every copy of this module; `opts` (re)configure it. */
756
+ function voice(opts) {
757
+ const g = globalThis;
758
+ const have = g[VOICE_SESSION_KEY];
759
+ if (have && have.v === V && have.configure) {
760
+ if (opts) have.configure(opts);
761
+ return have;
762
+ }
763
+ let o = { ...opts };
764
+ if (o.tts !== void 0) cloudOut(o.tts, o.ttsLimits);
765
+ const v = createVoice({
766
+ synth,
767
+ enabled: () => (o.enabled ?? speechEnabled)(),
768
+ here: () => (o.here ?? speakHere)(),
769
+ cloud: () => cloudReady() ? cloudOut() : null,
770
+ mode: () => (o.mode ?? outMode)(),
771
+ aec: () => (o.aec ?? aecOn)(),
772
+ rate: () => (o.rate ?? speechRate)(),
773
+ unlock: () => {
774
+ if ((o.mode ?? outMode)() === "cloud" && cloudReady()) cloudOut()?.unlock();
775
+ },
776
+ log: o.log,
777
+ utter: (text, lang) => {
778
+ const u = new SpeechSynthesisUtterance(text);
779
+ u.lang = lang;
780
+ const pick = pickNaturalVoice(speechSynthesis.getVoices(), lang);
781
+ if (pick) u.voice = pick;
782
+ alive.add(u);
783
+ u.addEventListener("end", () => alive.delete(u));
784
+ u.addEventListener("error", () => alive.delete(u));
785
+ return u;
786
+ }
787
+ });
788
+ const out = Object.assign(v, { configure(next) {
789
+ o = {
790
+ ...o,
791
+ ...next
792
+ };
793
+ if (next.tts !== void 0 || next.ttsLimits) cloudOut(o.tts ?? null, o.ttsLimits);
794
+ if (next.log) v.setLog(next.log);
795
+ } });
796
+ g[VOICE_SESSION_KEY] = out;
797
+ return out;
798
+ }
799
+
800
+ //#endregion
801
+ export { aecOn as C, createCloudOut as D, cloudSkip as E, outMode as O, VOICE_OUT_KEY as S, cloudReady as T, speechEnabled as _, DUCK_LEVEL as a, RESUME_REWIND_S as b, RESUME_TAIL_MS as c, chunk as d, createVoice as f, speakHere as g, sentences as h, DUCK_ATTACK_MS as i, ttsUrlFrom as k, SPEAK_KEY as l, pickNaturalVoice as m, BARGE_IN_PROB as n, DUCK_RELEASE_MS as o, isBargeIn as p, CHUNK_MAX as r, IDLE_RESUME_MS as s, BARGE_IN_MS as t, VOICE_SESSION_KEY as u, voice as v, cloudOut as w, VOICE_AEC_KEY as x, voiceQuality as y };
802
+ //# sourceMappingURL=voice-D7yeS9VM.js.map