@fishaudio/agent-widget-react-native 0.0.0-stage → 1.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,1922 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+
8
+ // src/widget.tsx
9
+ import {
10
+ useConversation
11
+ } from "@fishaudio/agent-react-native";
12
+
13
+ // ../widget-shared/dist/index.js
14
+ import { DEFAULT_SERVER_URL } from "@fishaudio/agent-client";
15
+ var __typeError2 = (msg) => {
16
+ throw TypeError(msg);
17
+ };
18
+ var __accessCheck2 = (obj, member, msg) => member.has(obj) || __typeError2("Cannot " + msg);
19
+ var __privateGet2 = (obj, member, getter) => (__accessCheck2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
20
+ var __privateAdd2 = (obj, member, value) => member.has(obj) ? __typeError2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
21
+ var __privateSet = (obj, member, value, setter) => (__accessCheck2(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
22
+ var __privateMethod = (obj, member, method) => (__accessCheck2(obj, member, "access private method"), method);
23
+ var __privateWrapper = (obj, member, setter, getter) => ({
24
+ set _(value) {
25
+ __privateSet(obj, member, value, setter);
26
+ },
27
+ get _() {
28
+ return __privateGet2(obj, member, getter);
29
+ }
30
+ });
31
+ var DEFAULT_TEXTS = {
32
+ statusConnecting: "Connecting\u2026",
33
+ statusReconnecting: "Reconnecting\u2026",
34
+ statusLive: "Live",
35
+ statusEnded: "Call ended",
36
+ greeting: "Hey! How can I help?",
37
+ homeHint: "Start a voice chat, or type below.",
38
+ startVoice: "Start a voice chat",
39
+ restartVoice: "Start a new voice chat",
40
+ continueWithText: "Or continue by typing",
41
+ endedDividerLabel: "Call ended",
42
+ composerPlaceholder: "Or type a message\u2026",
43
+ consentTitle: "Before you start",
44
+ consentBody: "This conversation is powered by Fish Audio. Your voice is processed in real time to run the call. By continuing, you agree to our Terms of Service and Privacy Policy.",
45
+ consentAgree: "Agree & continue",
46
+ consentDecline: "Not now",
47
+ poweredBy: "Powered by Fish Audio",
48
+ listening: "Listening",
49
+ thinking: "Thinking",
50
+ speaking: "Speaking",
51
+ errorMicDenied: "Microphone access was denied \u2014 check your browser settings.",
52
+ errorOrigin: "This site isn't allowed to talk to this agent.",
53
+ errorUnavailable: "This agent is temporarily unavailable.",
54
+ errorConnection: "Connection failed \u2014 please try again.",
55
+ openLabel: "Open assistant",
56
+ closeLabel: "Close",
57
+ minimizeLabel: "Minimize",
58
+ expandLabel: "Expand",
59
+ sendLabel: "Send",
60
+ muteLabel: "Mute microphone",
61
+ unmuteLabel: "Unmute microphone",
62
+ muteShort: "mute",
63
+ unmuteShort: "unmute",
64
+ endCallLabel: "End call",
65
+ dismissLabel: "Dismiss",
66
+ toolRunning: "Running",
67
+ toolDone: "Done",
68
+ toolFailed: "Failed"
69
+ };
70
+ function resolveSettings(attrs, remote) {
71
+ const texts = {
72
+ ...DEFAULT_TEXTS,
73
+ ...remote?.text_contents,
74
+ ...attrs.texts
75
+ };
76
+ const greeting = attrs.greeting ?? attrs.texts?.greeting ?? remote?.greeting;
77
+ if (greeting !== void 0) {
78
+ texts.greeting = greeting;
79
+ }
80
+ const consentBody = attrs.consentText ?? attrs.texts?.consentBody ?? remote?.consent_text;
81
+ if (consentBody !== void 0) {
82
+ texts.consentBody = consentBody;
83
+ }
84
+ return {
85
+ agentId: attrs.agentId,
86
+ serverUrl: attrs.serverUrl,
87
+ userId: attrs.userId,
88
+ language: attrs.language,
89
+ dynamicVariables: attrs.dynamicVariables,
90
+ agentName: attrs.agentName ?? remote?.agent_name ?? "Agent",
91
+ proactiveMessage: attrs.proactiveMessage ?? remote?.proactive_message,
92
+ proactiveDelaySeconds: attrs.proactiveDelaySeconds ?? 3,
93
+ transcript: attrs.transcript ?? remote?.transcript_enabled ?? true,
94
+ textInput: attrs.textInput ?? remote?.text_input_enabled ?? true,
95
+ micMuting: attrs.micMuting ?? remote?.mic_muting_enabled ?? true,
96
+ consent: attrs.consent ?? remote?.consent_required ?? false,
97
+ consentKey: attrs.consentKey ?? "fish-agent-consent",
98
+ termsUrl: attrs.termsUrl,
99
+ privacyUrl: attrs.privacyUrl,
100
+ position: attrs.position ?? "bottom-right",
101
+ avatarUrl: attrs.avatarUrl,
102
+ launcherIconUrl: attrs.launcherIconUrl,
103
+ texts
104
+ };
105
+ }
106
+ var _entries;
107
+ var _listeners;
108
+ var _generation;
109
+ var _dividerCount;
110
+ var _TranscriptStore_instances;
111
+ var upsertSpeech_fn;
112
+ var upsertTool_fn;
113
+ var upsert_fn;
114
+ var emit_fn;
115
+ var TranscriptStore = class {
116
+ constructor() {
117
+ __privateAdd2(this, _TranscriptStore_instances);
118
+ __privateAdd2(this, _entries, []);
119
+ __privateAdd2(this, _listeners, /* @__PURE__ */ new Set());
120
+ __privateAdd2(this, _generation, 0);
121
+ __privateAdd2(this, _dividerCount, 0);
122
+ }
123
+ get entries() {
124
+ return __privateGet2(this, _entries);
125
+ }
126
+ subscribe(listener) {
127
+ __privateGet2(this, _listeners).add(listener);
128
+ return () => __privateGet2(this, _listeners).delete(listener);
129
+ }
130
+ clear() {
131
+ if (__privateGet2(this, _entries).length > 0) {
132
+ __privateSet(this, _entries, []);
133
+ __privateMethod(this, _TranscriptStore_instances, emit_fn).call(this);
134
+ }
135
+ }
136
+ /** Append an end-of-call divider (no-op on an empty transcript). */
137
+ pushDivider(label) {
138
+ if (__privateGet2(this, _entries).length === 0) {
139
+ return;
140
+ }
141
+ const id = `divider:${++__privateWrapper(this, _dividerCount)._}`;
142
+ __privateMethod(this, _TranscriptStore_instances, upsert_fn).call(this, id, { kind: "divider", id, label });
143
+ }
144
+ /** Wire a live session; returns the detach function. */
145
+ attach(session) {
146
+ const generation = ++__privateWrapper(this, _generation)._;
147
+ const scoped = (id) => `${generation}:${id}`;
148
+ const onUserTranscript = ({
149
+ segmentId,
150
+ text,
151
+ final
152
+ }) => __privateMethod(this, _TranscriptStore_instances, upsertSpeech_fn).call(this, scoped(`u:${segmentId}`), "user", text, final);
153
+ const onAgentDelta = ({ segmentId, text }) => __privateMethod(this, _TranscriptStore_instances, upsertSpeech_fn).call(this, scoped(`a:${segmentId}`), "agent", text, false);
154
+ const onAgentResponse = ({ segmentId, text }) => __privateMethod(this, _TranscriptStore_instances, upsertSpeech_fn).call(this, scoped(`a:${segmentId}`), "agent", text, true);
155
+ const onToolStarted = (event) => __privateMethod(this, _TranscriptStore_instances, upsertTool_fn).call(this, {
156
+ kind: "tool",
157
+ id: scoped(`t:${event.callId}`),
158
+ callId: event.callId,
159
+ toolName: event.toolName,
160
+ source: event.source,
161
+ status: "running",
162
+ input: event.input,
163
+ inputTruncated: event.inputTruncated
164
+ });
165
+ const onToolCompleted = (event) => __privateMethod(this, _TranscriptStore_instances, upsertTool_fn).call(this, {
166
+ kind: "tool",
167
+ id: scoped(`t:${event.callId}`),
168
+ callId: event.callId,
169
+ toolName: event.toolName,
170
+ source: event.source,
171
+ status: "done",
172
+ output: event.output,
173
+ outputTruncated: event.outputTruncated
174
+ });
175
+ const onToolFailed = (event) => __privateMethod(this, _TranscriptStore_instances, upsertTool_fn).call(this, {
176
+ kind: "tool",
177
+ id: scoped(`t:${event.callId}`),
178
+ callId: event.callId,
179
+ toolName: event.toolName,
180
+ source: event.source,
181
+ status: "error",
182
+ error: event.error
183
+ });
184
+ session.on("userTranscript", onUserTranscript);
185
+ session.on("agentResponseDelta", onAgentDelta);
186
+ session.on("agentResponse", onAgentResponse);
187
+ session.on("toolCallStarted", onToolStarted);
188
+ session.on("toolCallCompleted", onToolCompleted);
189
+ session.on("toolCallFailed", onToolFailed);
190
+ return () => {
191
+ session.off("userTranscript", onUserTranscript);
192
+ session.off("agentResponseDelta", onAgentDelta);
193
+ session.off("agentResponse", onAgentResponse);
194
+ session.off("toolCallStarted", onToolStarted);
195
+ session.off("toolCallCompleted", onToolCompleted);
196
+ session.off("toolCallFailed", onToolFailed);
197
+ };
198
+ }
199
+ };
200
+ _entries = /* @__PURE__ */ new WeakMap();
201
+ _listeners = /* @__PURE__ */ new WeakMap();
202
+ _generation = /* @__PURE__ */ new WeakMap();
203
+ _dividerCount = /* @__PURE__ */ new WeakMap();
204
+ _TranscriptStore_instances = /* @__PURE__ */ new WeakSet();
205
+ upsertSpeech_fn = function(id, role, text, final) {
206
+ const entry = { kind: "message", id, role, text, final };
207
+ __privateMethod(this, _TranscriptStore_instances, upsert_fn).call(this, id, entry);
208
+ };
209
+ upsertTool_fn = function(entry) {
210
+ const existing = __privateGet2(this, _entries).find(
211
+ (candidate) => candidate.kind === "tool" && candidate.id === entry.id
212
+ );
213
+ __privateMethod(this, _TranscriptStore_instances, upsert_fn).call(this, entry.id, existing ? { ...existing, ...entry } : entry);
214
+ };
215
+ upsert_fn = function(id, entry) {
216
+ const index = __privateGet2(this, _entries).findIndex((candidate) => candidate.id === id);
217
+ const next = [...__privateGet2(this, _entries)];
218
+ if (index === -1) {
219
+ next.push(entry);
220
+ } else {
221
+ next[index] = entry;
222
+ }
223
+ __privateSet(this, _entries, next);
224
+ __privateMethod(this, _TranscriptStore_instances, emit_fn).call(this);
225
+ };
226
+ emit_fn = function() {
227
+ for (const listener of __privateGet2(this, _listeners)) {
228
+ listener();
229
+ }
230
+ };
231
+ async function fetchRemoteConfig(serverUrl, agentId, origin) {
232
+ const base = (serverUrl ?? DEFAULT_SERVER_URL).replace(/\/$/, "");
233
+ try {
234
+ const response = await fetch(
235
+ `${base}/v1/agent/agents/${encodeURIComponent(agentId)}/widget`,
236
+ {
237
+ headers: { Accept: "application/json", ...origin ? { Origin: origin } : {} },
238
+ signal: typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(3e3) : void 0
239
+ }
240
+ );
241
+ if (!response.ok) {
242
+ return null;
243
+ }
244
+ const body = await response.json();
245
+ return typeof body === "object" && body !== null ? body : null;
246
+ } catch {
247
+ return null;
248
+ }
249
+ }
250
+ function formatTimer(seconds) {
251
+ const minutes = Math.floor(seconds / 60);
252
+ const rest = seconds % 60;
253
+ return `${minutes}:${rest.toString().padStart(2, "0")}`;
254
+ }
255
+ function showsErrorBanner(error) {
256
+ return error.recovered !== true && error.code !== "tool_failed" && error.code !== "tool_timeout";
257
+ }
258
+ function errorText(texts, code) {
259
+ switch (code) {
260
+ case "mic_permission_denied":
261
+ return texts.errorMicDenied;
262
+ case "origin_forbidden":
263
+ case "agent_not_public":
264
+ return texts.errorOrigin;
265
+ case "insufficient_credit":
266
+ return texts.errorUnavailable;
267
+ default:
268
+ return texts.errorConnection;
269
+ }
270
+ }
271
+ function formatToolPayload(payload, truncated) {
272
+ if (!truncated) {
273
+ try {
274
+ return JSON.stringify(JSON.parse(payload), null, 1);
275
+ } catch {
276
+ }
277
+ }
278
+ return payload;
279
+ }
280
+
281
+ // src/widget.tsx
282
+ import { forwardRef, useEffect as useEffect4, useImperativeHandle, useMemo as useMemo2, useRef as useRef3, useState as useState5 } from "react";
283
+ import {
284
+ BackHandler,
285
+ KeyboardAvoidingView,
286
+ PermissionsAndroid,
287
+ Platform as Platform2,
288
+ StyleSheet as StyleSheet3,
289
+ useColorScheme,
290
+ useWindowDimensions,
291
+ View as View4
292
+ } from "react-native";
293
+
294
+ // src/texts.ts
295
+ var MOBILE_TEXTS = {
296
+ errorMicDenied: "Microphone access was denied. Turn it on in Settings.",
297
+ errorOrigin: "This app isn't allowed to talk to this agent."
298
+ };
299
+ var DEFAULT_TEXTS2 = { ...DEFAULT_TEXTS, ...MOBILE_TEXTS };
300
+
301
+ // src/images.ts
302
+ import { createContext, useContext, useState } from "react";
303
+ var ImagesContext = createContext({});
304
+ function useWidgetImages() {
305
+ return useContext(ImagesContext);
306
+ }
307
+ function sourceKey(source) {
308
+ if (source === void 0 || source === null) {
309
+ return void 0;
310
+ }
311
+ return typeof source === "number" ? `asset:${source}` : JSON.stringify(source);
312
+ }
313
+ var loadedKeys = /* @__PURE__ */ new Set();
314
+ function useImageWithFallback(source) {
315
+ const key = sourceKey(source);
316
+ const [failedKey, setFailedKey] = useState(void 0);
317
+ const [loadedKey, setLoadedKey] = useState(void 0);
318
+ const usable = key !== void 0 && failedKey !== key;
319
+ return {
320
+ source: usable ? source : void 0,
321
+ loaded: usable && (loadedKey === key || loadedKeys.has(key)),
322
+ onLoad: () => {
323
+ if (key !== void 0) {
324
+ loadedKeys.add(key);
325
+ setLoadedKey(key);
326
+ }
327
+ },
328
+ onError: () => setFailedKey(key)
329
+ };
330
+ }
331
+
332
+ // src/theme.ts
333
+ import { createContext as createContext2, useContext as useContext2 } from "react";
334
+ var LIGHT_THEME = {
335
+ accent: "#0f0e0d",
336
+ accentText: "#ffffff",
337
+ orbColor1: "#7cc4ff",
338
+ orbColor2: "#0a3f8f",
339
+ background: "#ffffff",
340
+ text: "#141414",
341
+ textSecondary: "#8a8a86",
342
+ border: "#ebeae8",
343
+ bubbleAgentBackground: "#0f0e0d",
344
+ bubbleAgentText: "#ffffff",
345
+ bubbleUserBackground: "#f4f3f1",
346
+ bubbleUserText: "#141414",
347
+ danger: "#e5484d",
348
+ live: "#30a46c",
349
+ radius: 20,
350
+ fabSize: 60,
351
+ offset: 20
352
+ };
353
+ var DARK_THEME = {
354
+ ...LIGHT_THEME,
355
+ accent: "#f4f3f1",
356
+ accentText: "#0f0e0d",
357
+ background: "#1a1918",
358
+ text: "#f4f3f1",
359
+ textSecondary: "#9a9994",
360
+ border: "#2e2d2b",
361
+ bubbleAgentBackground: "#f4f3f1",
362
+ bubbleAgentText: "#0f0e0d",
363
+ bubbleUserBackground: "#2a2927",
364
+ bubbleUserText: "#f4f3f1"
365
+ };
366
+ var ThemeContext = createContext2(LIGHT_THEME);
367
+ function useTheme() {
368
+ return useContext2(ThemeContext);
369
+ }
370
+
371
+ // src/drag.tsx
372
+ import { useEffect, useMemo, useRef, useState as useState2 } from "react";
373
+ import { PanResponder, View } from "react-native";
374
+ import { jsx } from "react/jsx-runtime";
375
+ var DRAG_SLOP = 6;
376
+ var SNAP_MS = 200;
377
+ function restingPoint(position, bounds, size) {
378
+ const x = position.side === "left" ? bounds.left : bounds.width - bounds.right - size.width;
379
+ const minY = bounds.top;
380
+ const maxY = Math.max(minY, bounds.height - bounds.bottom - size.height);
381
+ const y = position.edge === "top" ? position.distance : bounds.height - position.distance - size.height;
382
+ return { x, y: Math.min(Math.max(y, minY), maxY) };
383
+ }
384
+ function snapPosition(rect, bounds) {
385
+ const side = rect.x + rect.width / 2 < bounds.width / 2 ? "left" : "right";
386
+ const centerY = rect.y + rect.height / 2;
387
+ if (centerY < bounds.height / 2) {
388
+ return { side, edge: "top", distance: Math.max(bounds.top, rect.y) };
389
+ }
390
+ return { side, edge: "bottom", distance: Math.max(bounds.bottom, bounds.height - rect.y - rect.height) };
391
+ }
392
+ function Draggable({
393
+ cornerStyle,
394
+ position,
395
+ bounds,
396
+ enabled,
397
+ onDragStart,
398
+ onDragEnd,
399
+ anchorSize,
400
+ children
401
+ }) {
402
+ const [point, setPoint] = useState2(null);
403
+ const [size, setSize] = useState2(null);
404
+ const current = useRef({ x: 0, y: 0 });
405
+ const cornerRect = useRef(null);
406
+ const start = useRef({ x: 0, y: 0 });
407
+ const busy = useRef(false);
408
+ const frame = useRef(null);
409
+ const latest = useRef({ bounds, size, onDragStart, onDragEnd, cornerStyle, anchorSize });
410
+ latest.current = { bounds, size, onDragStart, onDragEnd, cornerStyle, anchorSize };
411
+ const placedRef = useRef(false);
412
+ const place = (next) => {
413
+ current.current = next;
414
+ placedRef.current = true;
415
+ setPoint(next);
416
+ };
417
+ const stopGlide = () => {
418
+ if (frame.current !== null) {
419
+ cancelAnimationFrame(frame.current);
420
+ frame.current = null;
421
+ }
422
+ };
423
+ useEffect(() => stopGlide, []);
424
+ const rest = position && bounds && size ? restingPoint(position, bounds, size) : null;
425
+ useEffect(() => {
426
+ if (rest && !busy.current) {
427
+ place(rest);
428
+ }
429
+ }, [rest?.x, rest?.y]);
430
+ const responder = useMemo(
431
+ () => PanResponder.create({
432
+ // Capture, so a drag that starts on the button's Pressable still moves the launcher.
433
+ onMoveShouldSetPanResponderCapture: (_, g) => Math.abs(g.dx) > DRAG_SLOP || Math.abs(g.dy) > DRAG_SLOP,
434
+ onPanResponderGrant: () => {
435
+ busy.current = true;
436
+ stopGlide();
437
+ const corner = cornerRect.current;
438
+ if (corner && !placedRef.current) {
439
+ const a = latest.current.anchorSize ?? corner;
440
+ const c = latest.current.cornerStyle;
441
+ current.current = {
442
+ x: c.right !== void 0 ? corner.x + corner.width - a.width : corner.x,
443
+ y: c.bottom !== void 0 ? corner.y + corner.height - a.height : corner.y
444
+ };
445
+ }
446
+ start.current = { ...current.current };
447
+ latest.current.onDragStart();
448
+ },
449
+ onPanResponderMove: (_, g) => {
450
+ place({ x: start.current.x + g.dx, y: start.current.y + g.dy });
451
+ },
452
+ onPanResponderRelease: () => {
453
+ const { bounds: b, size: s, onDragEnd: done } = latest.current;
454
+ if (!b || !s) {
455
+ busy.current = false;
456
+ return;
457
+ }
458
+ const next = snapPosition({ ...current.current, ...s }, b);
459
+ const from = { ...current.current };
460
+ const to = restingPoint(next, b, s);
461
+ const began = Date.now();
462
+ const step = () => {
463
+ const t = Math.min(1, (Date.now() - began) / SNAP_MS);
464
+ const k = 1 - (1 - t) ** 3;
465
+ place({ x: from.x + (to.x - from.x) * k, y: from.y + (to.y - from.y) * k });
466
+ if (t < 1) {
467
+ frame.current = requestAnimationFrame(step);
468
+ } else {
469
+ frame.current = null;
470
+ busy.current = false;
471
+ }
472
+ };
473
+ frame.current = requestAnimationFrame(step);
474
+ done(next);
475
+ },
476
+ onPanResponderTerminate: () => {
477
+ busy.current = false;
478
+ },
479
+ onPanResponderTerminationRequest: () => false
480
+ }),
481
+ []
482
+ );
483
+ return /* @__PURE__ */ jsx(
484
+ View,
485
+ {
486
+ ...enabled ? responder.panHandlers : {},
487
+ onLayout: (e) => {
488
+ const { x, y, width, height } = e.nativeEvent.layout;
489
+ if (point === null) {
490
+ cornerRect.current = { x, y, width, height };
491
+ }
492
+ setSize((old) => old && old.width === width && old.height === height ? old : { width, height });
493
+ },
494
+ style: point ? { position: "absolute", left: point.x, top: point.y } : (
495
+ // A remembered position waits for the size before showing, instead of flashing in the corner.
496
+ [cornerStyle, position ? { opacity: 0 } : null]
497
+ ),
498
+ children
499
+ }
500
+ );
501
+ }
502
+
503
+ // src/views.tsx
504
+ import { useEffect as useEffect3, useState as useState4 } from "react";
505
+ import { Image as Image2, Linking, Pressable as Pressable2, StyleSheet as StyleSheet2, Text as Text2, View as View3 } from "react-native";
506
+
507
+ // src/icons.tsx
508
+ import { Line, Path, Polyline, Svg } from "react-native-svg";
509
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
510
+ function icon(children) {
511
+ return function Icon({ size = 16, color }) {
512
+ return /* @__PURE__ */ jsx2(
513
+ Svg,
514
+ {
515
+ width: size,
516
+ height: size,
517
+ viewBox: "0 0 24 24",
518
+ fill: "none",
519
+ stroke: color,
520
+ strokeWidth: 2,
521
+ strokeLinecap: "round",
522
+ strokeLinejoin: "round",
523
+ children
524
+ }
525
+ );
526
+ };
527
+ }
528
+ var IconAudioLines = icon(
529
+ /* @__PURE__ */ jsxs(Fragment, { children: [
530
+ /* @__PURE__ */ jsx2(Path, { d: "M2 10v3" }),
531
+ /* @__PURE__ */ jsx2(Path, { d: "M6 6v11" }),
532
+ /* @__PURE__ */ jsx2(Path, { d: "M10 3v18" }),
533
+ /* @__PURE__ */ jsx2(Path, { d: "M14 8v7" }),
534
+ /* @__PURE__ */ jsx2(Path, { d: "M18 5v13" }),
535
+ /* @__PURE__ */ jsx2(Path, { d: "M22 10v3" })
536
+ ] })
537
+ );
538
+ var IconX = icon(
539
+ /* @__PURE__ */ jsxs(Fragment, { children: [
540
+ /* @__PURE__ */ jsx2(Path, { d: "M18 6 6 18" }),
541
+ /* @__PURE__ */ jsx2(Path, { d: "m6 6 12 12" })
542
+ ] })
543
+ );
544
+ var IconMinimize = icon(
545
+ /* @__PURE__ */ jsxs(Fragment, { children: [
546
+ /* @__PURE__ */ jsx2(Polyline, { points: "4 14 10 14 10 20" }),
547
+ /* @__PURE__ */ jsx2(Polyline, { points: "20 10 14 10 14 4" }),
548
+ /* @__PURE__ */ jsx2(Line, { x1: "14", x2: "21", y1: "10", y2: "3" }),
549
+ /* @__PURE__ */ jsx2(Line, { x1: "3", x2: "10", y1: "21", y2: "14" })
550
+ ] })
551
+ );
552
+ var IconSend = icon(
553
+ /* @__PURE__ */ jsxs(Fragment, { children: [
554
+ /* @__PURE__ */ jsx2(Path, { d: "m22 2-7 20-4-9-9-4Z" }),
555
+ /* @__PURE__ */ jsx2(Path, { d: "M22 2 11 13" })
556
+ ] })
557
+ );
558
+ var IconMic = icon(
559
+ /* @__PURE__ */ jsxs(Fragment, { children: [
560
+ /* @__PURE__ */ jsx2(Path, { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" }),
561
+ /* @__PURE__ */ jsx2(Path, { d: "M19 10v2a7 7 0 0 1-14 0v-2" }),
562
+ /* @__PURE__ */ jsx2(Line, { x1: "12", x2: "12", y1: "19", y2: "22" })
563
+ ] })
564
+ );
565
+ var IconMicOff = icon(
566
+ /* @__PURE__ */ jsxs(Fragment, { children: [
567
+ /* @__PURE__ */ jsx2(Path, { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" }),
568
+ /* @__PURE__ */ jsx2(Path, { d: "M19 10v2a7 7 0 0 1-14 0v-2" }),
569
+ /* @__PURE__ */ jsx2(Line, { x1: "12", x2: "12", y1: "19", y2: "22" }),
570
+ /* @__PURE__ */ jsx2(Line, { x1: "3", x2: "21", y1: "3", y2: "21" })
571
+ ] })
572
+ );
573
+ var IconPhone = icon(
574
+ /* @__PURE__ */ jsx2(Path, { d: "M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" })
575
+ );
576
+ var IconPhoneOff = icon(
577
+ /* @__PURE__ */ jsxs(Fragment, { children: [
578
+ /* @__PURE__ */ jsx2(Path, { d: "M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91" }),
579
+ /* @__PURE__ */ jsx2(Line, { x1: "22", x2: "2", y1: "2", y2: "22" })
580
+ ] })
581
+ );
582
+ var IconChevronDown = icon(/* @__PURE__ */ jsx2(Path, { d: "m6 9 6 6 6-6" }));
583
+
584
+ // src/parts.tsx
585
+ import { useEffect as useEffect2, useId, useRef as useRef2, useState as useState3 } from "react";
586
+ import {
587
+ AccessibilityInfo,
588
+ Animated,
589
+ Easing,
590
+ Image,
591
+ Platform,
592
+ Pressable,
593
+ ScrollView,
594
+ StyleSheet,
595
+ Text,
596
+ TextInput,
597
+ View as View2
598
+ } from "react-native";
599
+ import { Circle, Defs, RadialGradient, Stop, Svg as Svg2 } from "react-native-svg";
600
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
601
+ var MONO = Platform.select({ ios: "Menlo", default: "monospace" });
602
+ function useReducedMotion() {
603
+ const [reduced, setReduced] = useState3(false);
604
+ useEffect2(() => {
605
+ let active = true;
606
+ void AccessibilityInfo.isReduceMotionEnabled?.().then((value) => active && setReduced(value)).catch(() => void 0);
607
+ const subscription = AccessibilityInfo.addEventListener?.("reduceMotionChanged", setReduced);
608
+ return () => {
609
+ active = false;
610
+ subscription?.remove();
611
+ };
612
+ }, []);
613
+ return reduced;
614
+ }
615
+ function useLoop(running, duration, easing = Easing.linear) {
616
+ const value = useRef2(new Animated.Value(0)).current;
617
+ useEffect2(() => {
618
+ if (!running) {
619
+ value.setValue(0);
620
+ return;
621
+ }
622
+ const loop = Animated.loop(
623
+ Animated.timing(value, { toValue: 1, duration, easing, useNativeDriver: true })
624
+ );
625
+ loop.start();
626
+ return () => loop.stop();
627
+ }, [running, duration, easing, value]);
628
+ return running ? value : null;
629
+ }
630
+ function Orb({ size, mode }) {
631
+ const theme = useTheme();
632
+ const reduced = useReducedMotion();
633
+ const gradientId = `fa-orb-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
634
+ const animate = mode !== void 0 && !reduced;
635
+ const pulse = useLoop(animate && mode === "listening", 1800, Easing.out(Easing.ease));
636
+ const spin = useLoop(animate && mode === "thinking", 900);
637
+ const glow = useLoop(animate && mode === "speaking", 1200, Easing.inOut(Easing.ease));
638
+ const ring = size + 10;
639
+ const avatar = useImageWithFallback(useWidgetImages().avatar);
640
+ return /* @__PURE__ */ jsxs2(
641
+ View2,
642
+ {
643
+ style: { width: size, height: size, alignItems: "center", justifyContent: "center" },
644
+ accessibilityElementsHidden: true,
645
+ importantForAccessibility: "no-hide-descendants",
646
+ children: [
647
+ mode === "speaking" ? /* @__PURE__ */ jsx3(
648
+ Animated.View,
649
+ {
650
+ style: [
651
+ styles.ring,
652
+ {
653
+ width: ring + 6,
654
+ height: ring + 6,
655
+ borderRadius: (ring + 6) / 2,
656
+ backgroundColor: theme.orbColor1,
657
+ opacity: glow ? glow.interpolate({ inputRange: [0, 0.5, 1], outputRange: [0.18, 0.4, 0.18] }) : 0.3,
658
+ transform: glow ? [{ scale: glow.interpolate({ inputRange: [0, 0.5, 1], outputRange: [0.92, 1.05, 0.92] }) }] : []
659
+ }
660
+ ]
661
+ }
662
+ ) : null,
663
+ avatar.loaded ? null : /* @__PURE__ */ jsxs2(Svg2, { width: size, height: size, children: [
664
+ /* @__PURE__ */ jsx3(Defs, { children: /* @__PURE__ */ jsxs2(RadialGradient, { id: gradientId, cx: "32%", cy: "30%", r: "80%", fx: "32%", fy: "30%", children: [
665
+ /* @__PURE__ */ jsx3(Stop, { offset: "0", stopColor: theme.orbColor1 }),
666
+ /* @__PURE__ */ jsx3(Stop, { offset: "0.72", stopColor: theme.orbColor2 })
667
+ ] }) }),
668
+ /* @__PURE__ */ jsx3(Circle, { cx: size / 2, cy: size / 2, r: size / 2, fill: `url(#${gradientId})` })
669
+ ] }),
670
+ avatar.source !== void 0 ? (
671
+ // Mounted while the orb shows so it can load; hidden until it has.
672
+ /* @__PURE__ */ jsx3(
673
+ Image,
674
+ {
675
+ source: avatar.source,
676
+ onLoad: avatar.onLoad,
677
+ onError: avatar.onError,
678
+ fadeDuration: 0,
679
+ resizeMode: "cover",
680
+ style: [
681
+ avatar.loaded ? null : styles.loading,
682
+ { width: size, height: size, borderRadius: size / 2, backgroundColor: theme.background }
683
+ ]
684
+ }
685
+ )
686
+ ) : null,
687
+ mode === "listening" ? /* @__PURE__ */ jsx3(
688
+ Animated.View,
689
+ {
690
+ style: [
691
+ styles.ring,
692
+ {
693
+ width: ring,
694
+ height: ring,
695
+ borderRadius: ring / 2,
696
+ borderColor: theme.orbColor1,
697
+ opacity: pulse ? pulse.interpolate({ inputRange: [0, 0.7, 1], outputRange: [0.9, 0, 0] }) : 0.7,
698
+ transform: pulse ? [{ scale: pulse.interpolate({ inputRange: [0, 0.7, 1], outputRange: [0.92, 1.14, 1.14] }) }] : []
699
+ }
700
+ ]
701
+ }
702
+ ) : null,
703
+ mode === "thinking" ? /* @__PURE__ */ jsx3(
704
+ Animated.View,
705
+ {
706
+ style: [
707
+ styles.ring,
708
+ {
709
+ width: ring,
710
+ height: ring,
711
+ borderRadius: ring / 2,
712
+ borderColor: "transparent",
713
+ borderTopColor: theme.orbColor2,
714
+ transform: spin ? [{ rotate: spin.interpolate({ inputRange: [0, 1], outputRange: ["0deg", "360deg"] }) }] : []
715
+ }
716
+ ]
717
+ }
718
+ ) : null
719
+ ]
720
+ }
721
+ );
722
+ }
723
+ var IDLE_LEVELS = [6, 10, 16, 22, 18, 12, 8, 14, 20, 16, 10, 6, 12, 18, 10, 6].map((h) => h / 22);
724
+ function Waveform({ active, bars = 16, barWidth = 3, gap = 3, height = 22, color }) {
725
+ const reduced = useReducedMotion();
726
+ const wave = useLoop(active && !reduced, 1400);
727
+ return /* @__PURE__ */ jsx3(
728
+ View2,
729
+ {
730
+ style: { flexDirection: "row", alignItems: "center", height, gap },
731
+ accessibilityElementsHidden: true,
732
+ importantForAccessibility: "no-hide-descendants",
733
+ children: Array.from({ length: bars }, (_, index) => {
734
+ const level = IDLE_LEVELS[index % IDLE_LEVELS.length];
735
+ const base = Math.max(3, level * height);
736
+ const phase = index / bars;
737
+ const scale = wave ? wave.interpolate({
738
+ inputRange: [0, phase * 0.5, phase * 0.5 + 0.25, phase * 0.5 + 0.5, 1],
739
+ outputRange: [0.45, 0.45, 1, 0.45, 0.45]
740
+ }) : 1;
741
+ return /* @__PURE__ */ jsx3(
742
+ Animated.View,
743
+ {
744
+ style: {
745
+ width: barWidth,
746
+ height: base,
747
+ borderRadius: barWidth / 2,
748
+ backgroundColor: color,
749
+ transform: [{ scaleY: scale }]
750
+ }
751
+ },
752
+ index
753
+ );
754
+ })
755
+ }
756
+ );
757
+ }
758
+ function ToolChip({ entry, texts }) {
759
+ const theme = useTheme();
760
+ const [expanded, setExpanded] = useState3(false);
761
+ const statusLabel = entry.status === "running" ? texts.toolRunning : entry.status === "done" ? texts.toolDone : texts.toolFailed;
762
+ const dotColor = entry.status === "running" ? "#f5a623" : entry.status === "done" ? theme.live : theme.danger;
763
+ const detail = (label, value) => /* @__PURE__ */ jsxs2(View2, { children: [
764
+ /* @__PURE__ */ jsx3(Text, { style: [styles.toolDetailLabel, { color: theme.textSecondary }], children: label }),
765
+ /* @__PURE__ */ jsx3(Text, { style: [styles.toolDetailText, { color: theme.text }], children: value })
766
+ ] }, label);
767
+ return /* @__PURE__ */ jsxs2(View2, { style: styles.tool, children: [
768
+ /* @__PURE__ */ jsxs2(
769
+ Pressable,
770
+ {
771
+ accessibilityRole: "button",
772
+ accessibilityLabel: `${entry.toolName}, ${statusLabel}`,
773
+ accessibilityState: { expanded },
774
+ onPress: () => setExpanded((value) => !value),
775
+ style: [styles.toolChip, { borderColor: theme.border, backgroundColor: theme.background }],
776
+ children: [
777
+ /* @__PURE__ */ jsx3(View2, { style: [styles.toolDot, { backgroundColor: dotColor }] }),
778
+ /* @__PURE__ */ jsx3(Text, { style: [styles.toolName, { color: theme.text }], children: entry.toolName }),
779
+ /* @__PURE__ */ jsx3(View2, { style: expanded ? styles.rotated : void 0, children: /* @__PURE__ */ jsx3(IconChevronDown, { size: 12, color: theme.textSecondary }) })
780
+ ]
781
+ }
782
+ ),
783
+ expanded ? /* @__PURE__ */ jsxs2(
784
+ ScrollView,
785
+ {
786
+ style: [styles.toolDetail, { backgroundColor: theme.bubbleUserBackground }],
787
+ contentContainerStyle: { gap: 6 },
788
+ nestedScrollEnabled: true,
789
+ children: [
790
+ entry.input !== void 0 ? detail("input", formatToolPayload(entry.input, entry.inputTruncated)) : null,
791
+ entry.output !== void 0 ? detail("output", formatToolPayload(entry.output, entry.outputTruncated)) : null,
792
+ entry.error !== void 0 ? detail("error", entry.error) : null
793
+ ]
794
+ }
795
+ ) : null
796
+ ] });
797
+ }
798
+ function Transcript({
799
+ entries,
800
+ texts
801
+ }) {
802
+ const theme = useTheme();
803
+ const ref = useRef2(null);
804
+ return /* @__PURE__ */ jsx3(
805
+ ScrollView,
806
+ {
807
+ ref,
808
+ style: styles.transcript,
809
+ contentContainerStyle: styles.transcriptContent,
810
+ onContentSizeChange: () => ref.current?.scrollToEnd({ animated: true }),
811
+ keyboardShouldPersistTaps: "handled",
812
+ accessibilityLiveRegion: "polite",
813
+ children: entries.map(
814
+ (entry) => entry.kind === "message" ? /* @__PURE__ */ jsx3(
815
+ View2,
816
+ {
817
+ style: [
818
+ styles.bubble,
819
+ entry.role === "agent" ? [styles.bubbleAgent, { backgroundColor: theme.bubbleAgentBackground }] : [styles.bubbleUser, { backgroundColor: theme.bubbleUserBackground }]
820
+ ],
821
+ children: /* @__PURE__ */ jsx3(
822
+ Text,
823
+ {
824
+ selectable: true,
825
+ style: [
826
+ styles.bubbleText,
827
+ { color: entry.role === "agent" ? theme.bubbleAgentText : theme.bubbleUserText }
828
+ ],
829
+ children: entry.text
830
+ }
831
+ )
832
+ },
833
+ entry.id
834
+ ) : entry.kind === "divider" ? /* @__PURE__ */ jsxs2(View2, { style: styles.divider, accessibilityRole: "text", children: [
835
+ /* @__PURE__ */ jsx3(View2, { style: [styles.dividerLine, { backgroundColor: theme.border }] }),
836
+ /* @__PURE__ */ jsx3(Text, { style: [styles.dividerText, { color: theme.textSecondary }], children: entry.label }),
837
+ /* @__PURE__ */ jsx3(View2, { style: [styles.dividerLine, { backgroundColor: theme.border }] })
838
+ ] }, entry.id) : /* @__PURE__ */ jsx3(ToolChip, { entry, texts }, entry.id)
839
+ )
840
+ }
841
+ );
842
+ }
843
+ function Composer({ placeholder, sendLabel, disabled, divided, onSend, onActivity }) {
844
+ const theme = useTheme();
845
+ const [value, setValue] = useState3("");
846
+ const canSend = !disabled && value.trim().length > 0;
847
+ const submit = () => {
848
+ const text = value.trim();
849
+ if (!text || disabled) {
850
+ return;
851
+ }
852
+ setValue("");
853
+ onSend(text);
854
+ };
855
+ return /* @__PURE__ */ jsxs2(View2, { style: [styles.composer, divided ? { borderTopWidth: 1, borderTopColor: theme.border } : null], children: [
856
+ /* @__PURE__ */ jsx3(
857
+ TextInput,
858
+ {
859
+ style: [styles.input, { borderColor: theme.border, color: theme.text, backgroundColor: theme.background }],
860
+ value,
861
+ placeholder,
862
+ placeholderTextColor: theme.textSecondary,
863
+ editable: !disabled,
864
+ returnKeyType: "send",
865
+ submitBehavior: "submit",
866
+ onSubmitEditing: submit,
867
+ onChangeText: (text) => {
868
+ setValue(text);
869
+ onActivity?.();
870
+ }
871
+ }
872
+ ),
873
+ /* @__PURE__ */ jsx3(
874
+ Pressable,
875
+ {
876
+ accessibilityRole: "button",
877
+ accessibilityLabel: sendLabel,
878
+ accessibilityState: { disabled: !canSend },
879
+ disabled: !canSend,
880
+ onPress: submit,
881
+ style: [styles.send, { backgroundColor: theme.accent, opacity: canSend ? 1 : 0.4 }],
882
+ children: /* @__PURE__ */ jsx3(IconSend, { size: 16, color: theme.accentText })
883
+ }
884
+ )
885
+ ] });
886
+ }
887
+ var styles = StyleSheet.create({
888
+ ring: { position: "absolute", borderWidth: 2 },
889
+ loading: { position: "absolute", opacity: 0 },
890
+ tool: { alignSelf: "flex-start", maxWidth: "100%" },
891
+ toolChip: {
892
+ flexDirection: "row",
893
+ alignItems: "center",
894
+ alignSelf: "flex-start",
895
+ gap: 8,
896
+ borderWidth: 1,
897
+ borderRadius: 999,
898
+ paddingVertical: 6,
899
+ paddingHorizontal: 12
900
+ },
901
+ toolDot: { width: 8, height: 8, borderRadius: 4 },
902
+ toolName: { fontFamily: MONO, fontSize: 12 },
903
+ rotated: { transform: [{ rotate: "180deg" }] },
904
+ toolDetail: { marginTop: 6, maxHeight: 140, borderRadius: 12, paddingVertical: 10, paddingHorizontal: 12 },
905
+ toolDetailLabel: { fontSize: 11 },
906
+ toolDetailText: { fontFamily: MONO, fontSize: 11.5, lineHeight: 17 },
907
+ transcript: { flex: 1 },
908
+ transcriptContent: { padding: 16, gap: 10 },
909
+ bubble: { maxWidth: "80%", paddingVertical: 10, paddingHorizontal: 14 },
910
+ bubbleAgent: {
911
+ alignSelf: "flex-start",
912
+ borderTopLeftRadius: 6,
913
+ borderTopRightRadius: 24,
914
+ borderBottomLeftRadius: 24,
915
+ borderBottomRightRadius: 24
916
+ },
917
+ bubbleUser: {
918
+ alignSelf: "flex-end",
919
+ borderTopLeftRadius: 24,
920
+ borderTopRightRadius: 6,
921
+ borderBottomLeftRadius: 24,
922
+ borderBottomRightRadius: 24
923
+ },
924
+ bubbleText: { fontSize: 15, lineHeight: 21 },
925
+ divider: { flexDirection: "row", alignItems: "center", gap: 10, marginVertical: 6 },
926
+ dividerLine: { flex: 1, height: StyleSheet.hairlineWidth },
927
+ dividerText: { fontSize: 12 },
928
+ composer: { flexDirection: "row", alignItems: "center", gap: 8, paddingVertical: 12, paddingHorizontal: 16 },
929
+ input: { flex: 1, minWidth: 0, height: 40, borderWidth: 1, borderRadius: 999, paddingHorizontal: 16, fontSize: 15 },
930
+ send: { width: 40, height: 40, borderRadius: 20, alignItems: "center", justifyContent: "center" }
931
+ });
932
+
933
+ // src/views.tsx
934
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
935
+ function shadow(theme, radius, opacity) {
936
+ return {
937
+ shadowColor: "#0f0e0d",
938
+ shadowOpacity: opacity,
939
+ shadowRadius: radius,
940
+ shadowOffset: { width: 0, height: radius / 3 },
941
+ elevation: Math.round(radius / 2),
942
+ backgroundColor: theme.background
943
+ };
944
+ }
945
+ function openUrl(url) {
946
+ void Linking.openURL(url).catch(() => void 0);
947
+ }
948
+ function FabView({ settings, proactiveVisible, alignEnd, onOpen, onDismissProactive }) {
949
+ const theme = useTheme();
950
+ const launcherIcon = useImageWithFallback(useWidgetImages().launcherIcon);
951
+ const top = settings.position.startsWith("top");
952
+ const bubble = proactiveVisible && settings.proactiveMessage ? /* @__PURE__ */ jsxs3(
953
+ View3,
954
+ {
955
+ style: [
956
+ styles2.proactive,
957
+ shadow(theme, 20, 0.14),
958
+ { borderColor: theme.border },
959
+ top ? { marginTop: 12 } : { marginBottom: 12 }
960
+ ],
961
+ children: [
962
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.proactiveText, { color: theme.text }], children: settings.proactiveMessage }),
963
+ /* @__PURE__ */ jsx4(
964
+ Pressable2,
965
+ {
966
+ accessibilityRole: "button",
967
+ accessibilityLabel: settings.texts.dismissLabel,
968
+ hitSlop: 10,
969
+ onPress: onDismissProactive,
970
+ style: [
971
+ styles2.proactiveDismiss,
972
+ alignEnd ? { right: -9 } : { left: -9 },
973
+ { borderColor: theme.border, backgroundColor: theme.background }
974
+ ],
975
+ children: /* @__PURE__ */ jsx4(IconX, { size: 11, color: theme.textSecondary })
976
+ }
977
+ )
978
+ ]
979
+ }
980
+ ) : null;
981
+ const fab = /* @__PURE__ */ jsxs3(
982
+ Pressable2,
983
+ {
984
+ accessibilityRole: "button",
985
+ accessibilityLabel: settings.texts.openLabel,
986
+ onPress: onOpen,
987
+ style: ({ pressed }) => [
988
+ shadow(theme, 24, 0.22),
989
+ {
990
+ width: theme.fabSize,
991
+ height: theme.fabSize,
992
+ borderRadius: theme.fabSize / 2,
993
+ backgroundColor: theme.accent,
994
+ alignItems: "center",
995
+ justifyContent: "center",
996
+ transform: [{ scale: pressed ? 0.95 : 1 }]
997
+ }
998
+ ],
999
+ children: [
1000
+ launcherIcon.loaded ? null : /* @__PURE__ */ jsx4(IconAudioLines, { size: 26, color: theme.accentText }),
1001
+ launcherIcon.source !== void 0 ? (
1002
+ // Mounted while the default icon shows so it can load; hidden until it has.
1003
+ /* @__PURE__ */ jsx4(
1004
+ Image2,
1005
+ {
1006
+ source: launcherIcon.source,
1007
+ onLoad: launcherIcon.onLoad,
1008
+ onError: launcherIcon.onError,
1009
+ fadeDuration: 0,
1010
+ resizeMode: "cover",
1011
+ style: {
1012
+ position: launcherIcon.loaded ? "relative" : "absolute",
1013
+ opacity: launcherIcon.loaded ? 1 : 0,
1014
+ width: theme.fabSize,
1015
+ height: theme.fabSize,
1016
+ borderRadius: theme.fabSize / 2
1017
+ }
1018
+ }
1019
+ )
1020
+ ) : null
1021
+ ]
1022
+ }
1023
+ );
1024
+ return /* @__PURE__ */ jsxs3(View3, { style: { alignItems: alignEnd ? "flex-end" : "flex-start" }, children: [
1025
+ top ? fab : bubble,
1026
+ top ? bubble : fab
1027
+ ] });
1028
+ }
1029
+ function PanelShell({
1030
+ settings,
1031
+ status,
1032
+ mode,
1033
+ live,
1034
+ starting,
1035
+ muted,
1036
+ onToggleMute,
1037
+ onEnd,
1038
+ onMinimize,
1039
+ onClose,
1040
+ style,
1041
+ children
1042
+ }) {
1043
+ const theme = useTheme();
1044
+ const { texts } = settings;
1045
+ const inCall = live || starting;
1046
+ return /* @__PURE__ */ jsxs3(View3, { style: [styles2.panel, { backgroundColor: theme.background, borderColor: theme.border }, style], children: [
1047
+ /* @__PURE__ */ jsxs3(View3, { style: [styles2.header, { borderBottomColor: theme.border }], children: [
1048
+ /* @__PURE__ */ jsxs3(View3, { style: styles2.headerLeft, children: [
1049
+ /* @__PURE__ */ jsx4(Orb, { size: 32, mode }),
1050
+ /* @__PURE__ */ jsxs3(View3, { style: styles2.headerNames, children: [
1051
+ /* @__PURE__ */ jsx4(Text2, { numberOfLines: 1, style: [styles2.headerTitle, { color: theme.text }], children: settings.agentName }),
1052
+ status != null ? /* @__PURE__ */ jsx4(View3, { style: styles2.headerStatus, children: status }) : null
1053
+ ] })
1054
+ ] }),
1055
+ /* @__PURE__ */ jsxs3(View3, { style: styles2.headerActions, children: [
1056
+ /* @__PURE__ */ jsx4(IconButton, { label: texts.minimizeLabel, onPress: onMinimize, children: /* @__PURE__ */ jsx4(IconMinimize, { size: 16, color: theme.textSecondary }) }),
1057
+ inCall ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
1058
+ settings.micMuting ? /* @__PURE__ */ jsxs3(
1059
+ Pressable2,
1060
+ {
1061
+ accessibilityRole: "button",
1062
+ accessibilityLabel: muted ? texts.unmuteLabel : texts.muteLabel,
1063
+ accessibilityState: { selected: muted, disabled: !live },
1064
+ disabled: !live,
1065
+ onPress: onToggleMute,
1066
+ style: [
1067
+ styles2.headerPill,
1068
+ { backgroundColor: muted ? theme.accent : "rgba(128, 128, 128, 0.14)", opacity: live ? 1 : 0.5 }
1069
+ ],
1070
+ children: [
1071
+ muted ? /* @__PURE__ */ jsx4(IconMic, { size: 13, color: theme.accentText }) : /* @__PURE__ */ jsx4(IconMicOff, { size: 13, color: theme.text }),
1072
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.headerPillText, { color: muted ? theme.accentText : theme.text }], children: muted ? texts.unmuteShort : texts.muteShort })
1073
+ ]
1074
+ }
1075
+ ) : null,
1076
+ /* @__PURE__ */ jsx4(
1077
+ Pressable2,
1078
+ {
1079
+ accessibilityRole: "button",
1080
+ accessibilityLabel: texts.endCallLabel,
1081
+ hitSlop: 6,
1082
+ onPress: onEnd,
1083
+ style: [styles2.headerEnd, { backgroundColor: theme.danger }],
1084
+ children: /* @__PURE__ */ jsx4(IconPhoneOff, { size: 15, color: "#ffffff" })
1085
+ }
1086
+ )
1087
+ ] }) : /* @__PURE__ */ jsx4(IconButton, { label: texts.closeLabel, onPress: onClose, children: /* @__PURE__ */ jsx4(IconX, { size: 16, color: theme.textSecondary }) })
1088
+ ] })
1089
+ ] }),
1090
+ children,
1091
+ /* @__PURE__ */ jsx4(Pressable2, { accessibilityRole: "link", onPress: () => openUrl("https://fish.audio"), style: styles2.footer, children: /* @__PURE__ */ jsx4(Text2, { style: [styles2.footerText, { color: theme.textSecondary }], children: texts.poweredBy }) })
1092
+ ] });
1093
+ }
1094
+ function IconButton({ label, onPress, children }) {
1095
+ return /* @__PURE__ */ jsx4(
1096
+ Pressable2,
1097
+ {
1098
+ accessibilityRole: "button",
1099
+ accessibilityLabel: label,
1100
+ hitSlop: 6,
1101
+ onPress,
1102
+ style: ({ pressed }) => [styles2.iconButton, pressed ? { opacity: 0.6 } : null],
1103
+ children
1104
+ }
1105
+ );
1106
+ }
1107
+ function LiveStatus({ label, color, dot }) {
1108
+ return /* @__PURE__ */ jsxs3(Fragment2, { children: [
1109
+ dot ? /* @__PURE__ */ jsx4(View3, { style: [styles2.liveDot, { backgroundColor: dot }] }) : null,
1110
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.headerStatusText, { color }], children: label })
1111
+ ] });
1112
+ }
1113
+ function ErrorLine({ error }) {
1114
+ const theme = useTheme();
1115
+ return error ? /* @__PURE__ */ jsx4(Text2, { accessibilityRole: "alert", style: [styles2.error, { color: theme.danger }], children: error }) : null;
1116
+ }
1117
+ function Cta({ label, wide, onPress }) {
1118
+ const theme = useTheme();
1119
+ return /* @__PURE__ */ jsxs3(
1120
+ Pressable2,
1121
+ {
1122
+ accessibilityRole: "button",
1123
+ onPress,
1124
+ style: ({ pressed }) => [
1125
+ styles2.cta,
1126
+ wide ? styles2.ctaWide : null,
1127
+ { backgroundColor: theme.accent, opacity: pressed ? 0.85 : 1 }
1128
+ ],
1129
+ children: [
1130
+ /* @__PURE__ */ jsx4(IconPhone, { size: 16, color: theme.accentText }),
1131
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.ctaText, { color: theme.accentText }], children: label })
1132
+ ]
1133
+ }
1134
+ );
1135
+ }
1136
+ function HomeView({ settings, fill, error, onStartVoice, onSendText }) {
1137
+ const theme = useTheme();
1138
+ const { texts } = settings;
1139
+ return /* @__PURE__ */ jsxs3(Fragment2, { children: [
1140
+ /* @__PURE__ */ jsxs3(View3, { style: [styles2.home, fill ? styles2.fill : null], children: [
1141
+ /* @__PURE__ */ jsx4(Orb, { size: 72 }),
1142
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.homeGreeting, { color: theme.text }], children: texts.greeting }),
1143
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.homeHint, { color: theme.textSecondary }], children: settings.textInput ? texts.homeHint : texts.startVoice }),
1144
+ /* @__PURE__ */ jsx4(Cta, { label: texts.startVoice, onPress: onStartVoice })
1145
+ ] }),
1146
+ /* @__PURE__ */ jsx4(ErrorLine, { error }),
1147
+ settings.textInput ? /* @__PURE__ */ jsx4(Composer, { placeholder: texts.composerPlaceholder, sendLabel: texts.sendLabel, onSend: onSendText }) : null
1148
+ ] });
1149
+ }
1150
+ function ConsentView({ settings, fill, onAgree, onDecline }) {
1151
+ const theme = useTheme();
1152
+ const { texts, termsUrl, privacyUrl } = settings;
1153
+ return /* @__PURE__ */ jsxs3(View3, { style: [styles2.consent, fill ? styles2.fill : null], children: [
1154
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.consentTitle, { color: theme.text }], children: texts.consentTitle }),
1155
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.consentTerms, { color: theme.text, backgroundColor: theme.bubbleUserBackground }], children: texts.consentBody }),
1156
+ termsUrl || privacyUrl ? /* @__PURE__ */ jsxs3(View3, { style: styles2.consentLinks, children: [
1157
+ termsUrl ? /* @__PURE__ */ jsx4(Text2, { accessibilityRole: "link", onPress: () => openUrl(termsUrl), style: [styles2.link, { color: theme.text }], children: "Terms of Service" }) : null,
1158
+ privacyUrl ? /* @__PURE__ */ jsx4(
1159
+ Text2,
1160
+ {
1161
+ accessibilityRole: "link",
1162
+ onPress: () => openUrl(privacyUrl),
1163
+ style: [styles2.link, { color: theme.text }],
1164
+ children: "Privacy Policy"
1165
+ }
1166
+ ) : null
1167
+ ] }) : null,
1168
+ /* @__PURE__ */ jsxs3(View3, { style: styles2.consentButtons, children: [
1169
+ /* @__PURE__ */ jsx4(
1170
+ Pressable2,
1171
+ {
1172
+ accessibilityRole: "button",
1173
+ onPress: onDecline,
1174
+ style: [styles2.button, { borderWidth: 1, borderColor: theme.border, backgroundColor: theme.background }],
1175
+ children: /* @__PURE__ */ jsx4(Text2, { style: [styles2.buttonText, { color: theme.text }], children: texts.consentDecline })
1176
+ }
1177
+ ),
1178
+ /* @__PURE__ */ jsx4(Pressable2, { accessibilityRole: "button", onPress: onAgree, style: [styles2.button, { backgroundColor: theme.accent }], children: /* @__PURE__ */ jsx4(Text2, { style: [styles2.buttonText, { color: theme.accentText, fontWeight: "500" }], children: texts.consentAgree }) })
1179
+ ] })
1180
+ ] });
1181
+ }
1182
+ function CallView({
1183
+ settings,
1184
+ entries,
1185
+ phase,
1186
+ mode,
1187
+ error,
1188
+ onRestartVoice,
1189
+ onSendText,
1190
+ onActivity
1191
+ }) {
1192
+ const theme = useTheme();
1193
+ const { texts } = settings;
1194
+ const live = phase === "live";
1195
+ const ended = phase === "ended";
1196
+ const [typingRevealed, setTypingRevealed] = useState4(false);
1197
+ useEffect3(() => {
1198
+ if (!ended) {
1199
+ setTypingRevealed(false);
1200
+ }
1201
+ }, [ended]);
1202
+ return /* @__PURE__ */ jsxs3(Fragment2, { children: [
1203
+ settings.transcript ? /* @__PURE__ */ jsx4(Transcript, { entries, texts }) : /* @__PURE__ */ jsx4(View3, { style: [styles2.home, { flex: 1, justifyContent: "center" }], children: /* @__PURE__ */ jsx4(Orb, { size: 72, mode: live ? mode : void 0 }) }),
1204
+ /* @__PURE__ */ jsx4(ErrorLine, { error }),
1205
+ !ended ? /* @__PURE__ */ jsxs3(View3, { style: [styles2.modeStatus, { borderTopColor: theme.border }], children: [
1206
+ /* @__PURE__ */ jsx4(Waveform, { active: live, bars: 5, barWidth: 2, gap: 3, height: 12, color: theme.textSecondary }),
1207
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.modeStatusText, { color: theme.textSecondary }], children: live ? texts[mode] : texts.statusConnecting })
1208
+ ] }) : null,
1209
+ settings.textInput && (!ended || typingRevealed) ? /* @__PURE__ */ jsx4(
1210
+ Composer,
1211
+ {
1212
+ placeholder: texts.composerPlaceholder,
1213
+ sendLabel: texts.sendLabel,
1214
+ disabled: phase === "starting",
1215
+ divided: ended,
1216
+ onSend: onSendText,
1217
+ onActivity
1218
+ }
1219
+ ) : null,
1220
+ ended ? /* @__PURE__ */ jsxs3(View3, { style: [styles2.ended, { borderTopColor: theme.border }], children: [
1221
+ /* @__PURE__ */ jsx4(Cta, { label: texts.restartVoice, wide: true, onPress: onRestartVoice }),
1222
+ settings.textInput && !typingRevealed ? /* @__PURE__ */ jsx4(Pressable2, { accessibilityRole: "button", onPress: () => setTypingRevealed(true), style: styles2.linkButton, children: /* @__PURE__ */ jsx4(Text2, { style: [styles2.linkButtonText, { color: theme.textSecondary }], children: texts.continueWithText }) }) : null
1223
+ ] }) : null
1224
+ ] });
1225
+ }
1226
+ function MinimizedPill({ settings, seconds, live, onExpand, onEnd }) {
1227
+ const theme = useTheme();
1228
+ const { texts } = settings;
1229
+ return /* @__PURE__ */ jsxs3(View3, { style: [styles2.pill, shadow(theme, 24, 0.18), { borderColor: theme.border }], children: [
1230
+ /* @__PURE__ */ jsxs3(Pressable2, { accessibilityRole: "button", accessibilityLabel: texts.expandLabel, onPress: onExpand, style: styles2.pillExpand, children: [
1231
+ /* @__PURE__ */ jsx4(Orb, { size: 32, mode: "speaking" }),
1232
+ /* @__PURE__ */ jsx4(Waveform, { active: live, bars: 6, barWidth: 2.5, gap: 2.5, height: 18, color: theme.text }),
1233
+ /* @__PURE__ */ jsx4(Text2, { style: [styles2.pillTimer, { color: theme.text }], children: formatTimer(seconds) })
1234
+ ] }),
1235
+ /* @__PURE__ */ jsx4(
1236
+ Pressable2,
1237
+ {
1238
+ accessibilityRole: "button",
1239
+ accessibilityLabel: texts.endCallLabel,
1240
+ onPress: onEnd,
1241
+ style: [styles2.pillEnd, { backgroundColor: theme.danger }],
1242
+ children: /* @__PURE__ */ jsx4(IconPhoneOff, { size: 14, color: "#ffffff" })
1243
+ }
1244
+ )
1245
+ ] });
1246
+ }
1247
+ var styles2 = StyleSheet2.create({
1248
+ proactive: {
1249
+ maxWidth: 260,
1250
+ borderWidth: 1,
1251
+ borderRadius: 14,
1252
+ paddingVertical: 12,
1253
+ paddingHorizontal: 16
1254
+ },
1255
+ proactiveText: { fontSize: 14, lineHeight: 20 },
1256
+ proactiveDismiss: {
1257
+ position: "absolute",
1258
+ top: -9,
1259
+ width: 22,
1260
+ height: 22,
1261
+ borderRadius: 11,
1262
+ borderWidth: 1,
1263
+ alignItems: "center",
1264
+ justifyContent: "center"
1265
+ },
1266
+ panel: { overflow: "hidden", flexDirection: "column" },
1267
+ header: {
1268
+ flexDirection: "row",
1269
+ alignItems: "center",
1270
+ justifyContent: "space-between",
1271
+ gap: 12,
1272
+ paddingVertical: 14,
1273
+ paddingHorizontal: 16,
1274
+ borderBottomWidth: StyleSheet2.hairlineWidth
1275
+ },
1276
+ headerLeft: { flexDirection: "row", alignItems: "center", gap: 10, flexShrink: 1 },
1277
+ headerNames: { flexShrink: 1 },
1278
+ headerTitle: { fontSize: 15, fontWeight: "600" },
1279
+ headerStatus: { flexDirection: "row", alignItems: "center", gap: 5 },
1280
+ headerStatusText: { fontSize: 12 },
1281
+ liveDot: { width: 6, height: 6, borderRadius: 3 },
1282
+ headerActions: { flexDirection: "row", alignItems: "center", gap: 6 },
1283
+ iconButton: { width: 32, height: 32, borderRadius: 8, alignItems: "center", justifyContent: "center" },
1284
+ headerPill: {
1285
+ flexDirection: "row",
1286
+ alignItems: "center",
1287
+ gap: 6,
1288
+ height: 30,
1289
+ paddingHorizontal: 11,
1290
+ borderRadius: 999
1291
+ },
1292
+ headerPillText: { fontSize: 13 },
1293
+ headerEnd: { width: 30, height: 30, borderRadius: 15, alignItems: "center", justifyContent: "center" },
1294
+ modeStatus: {
1295
+ flexDirection: "row",
1296
+ alignItems: "center",
1297
+ justifyContent: "center",
1298
+ gap: 8,
1299
+ paddingTop: 10,
1300
+ paddingBottom: 4,
1301
+ paddingHorizontal: 16,
1302
+ borderTopWidth: StyleSheet2.hairlineWidth
1303
+ },
1304
+ modeStatusText: { fontSize: 12 },
1305
+ footer: { paddingTop: 6, paddingBottom: 10, alignItems: "center" },
1306
+ footerText: { fontSize: 12 },
1307
+ error: { fontSize: 13, textAlign: "center", paddingTop: 8, paddingHorizontal: 16 },
1308
+ fill: { flex: 1, justifyContent: "center" },
1309
+ home: { paddingTop: 36, paddingBottom: 28, paddingHorizontal: 24, alignItems: "center", gap: 6 },
1310
+ homeGreeting: { marginTop: 14, fontSize: 16, fontWeight: "600", textAlign: "center" },
1311
+ homeHint: { fontSize: 14, textAlign: "center" },
1312
+ cta: {
1313
+ marginTop: 16,
1314
+ flexDirection: "row",
1315
+ alignItems: "center",
1316
+ justifyContent: "center",
1317
+ gap: 8,
1318
+ height: 44,
1319
+ paddingHorizontal: 22,
1320
+ borderRadius: 999
1321
+ },
1322
+ ctaWide: { marginTop: 0, alignSelf: "stretch" },
1323
+ ctaText: { fontSize: 15, fontWeight: "500" },
1324
+ consent: { paddingTop: 24, paddingBottom: 28, paddingHorizontal: 24, alignItems: "center", gap: 14 },
1325
+ consentTitle: { fontSize: 16, fontWeight: "600" },
1326
+ consentTerms: { borderRadius: 12, padding: 14, fontSize: 13, lineHeight: 20, overflow: "hidden" },
1327
+ consentLinks: { flexDirection: "row", gap: 12 },
1328
+ link: { fontSize: 13, textDecorationLine: "underline" },
1329
+ consentButtons: { flexDirection: "row", gap: 10 },
1330
+ button: { height: 42, paddingHorizontal: 18, borderRadius: 999, alignItems: "center", justifyContent: "center" },
1331
+ buttonText: { fontSize: 15 },
1332
+ ended: {
1333
+ alignItems: "center",
1334
+ gap: 4,
1335
+ paddingTop: 12,
1336
+ paddingBottom: 14,
1337
+ paddingHorizontal: 16,
1338
+ borderTopWidth: StyleSheet2.hairlineWidth
1339
+ },
1340
+ linkButton: { paddingVertical: 6, paddingHorizontal: 8 },
1341
+ linkButtonText: { fontSize: 14 },
1342
+ pill: {
1343
+ flexDirection: "row",
1344
+ alignItems: "center",
1345
+ gap: 10,
1346
+ borderWidth: 1,
1347
+ borderRadius: 999,
1348
+ padding: 10
1349
+ },
1350
+ pillExpand: { flexDirection: "row", alignItems: "center", gap: 10 },
1351
+ pillTimer: { fontSize: 14, fontVariant: ["tabular-nums"] },
1352
+ pillEnd: { width: 34, height: 34, borderRadius: 17, alignItems: "center", justifyContent: "center" }
1353
+ });
1354
+
1355
+ // src/widget.tsx
1356
+ import { jsx as jsx5 } from "react/jsx-runtime";
1357
+ var SHEET_BELOW_WIDTH = 600;
1358
+ var CARD_WIDTH = 380;
1359
+ var CARD_MAX_HEIGHT = 600;
1360
+ var proactiveDismissed = false;
1361
+ var draggedPosition = null;
1362
+ var acceptedConsentKeys = /* @__PURE__ */ new Set();
1363
+ var _handlers;
1364
+ var CallbackBridge = class {
1365
+ constructor() {
1366
+ __privateAdd(this, _handlers, /* @__PURE__ */ new Map());
1367
+ }
1368
+ on(event, handler) {
1369
+ let set = __privateGet(this, _handlers).get(event);
1370
+ if (!set) {
1371
+ set = /* @__PURE__ */ new Set();
1372
+ __privateGet(this, _handlers).set(event, set);
1373
+ }
1374
+ set.add(handler);
1375
+ return this;
1376
+ }
1377
+ off(event, handler) {
1378
+ __privateGet(this, _handlers).get(event)?.delete(handler);
1379
+ return this;
1380
+ }
1381
+ emit(event, payload) {
1382
+ for (const handler of __privateGet(this, _handlers).get(event) ?? []) {
1383
+ handler(payload);
1384
+ }
1385
+ }
1386
+ };
1387
+ _handlers = new WeakMap();
1388
+ var BRIDGED_EVENTS = [
1389
+ "userTranscript",
1390
+ "agentResponseDelta",
1391
+ "agentResponse",
1392
+ "toolCallStarted",
1393
+ "toolCallCompleted",
1394
+ "toolCallFailed"
1395
+ ];
1396
+ function mergeCallbacks(ours, theirs) {
1397
+ const merged = { ...ours };
1398
+ for (const [key, callback] of Object.entries(theirs ?? {})) {
1399
+ if (typeof callback !== "function") {
1400
+ continue;
1401
+ }
1402
+ const own = merged[key];
1403
+ merged[key] = own ? (payload) => {
1404
+ own(payload);
1405
+ callback(payload);
1406
+ } : callback;
1407
+ }
1408
+ return merged;
1409
+ }
1410
+ function isAbort(error) {
1411
+ return error instanceof Error && error.name === "AbortError";
1412
+ }
1413
+ async function ensureMicrophonePermission() {
1414
+ if (Platform2.OS !== "android") {
1415
+ return true;
1416
+ }
1417
+ const permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO;
1418
+ if (await PermissionsAndroid.check(permission)) {
1419
+ return true;
1420
+ }
1421
+ return await PermissionsAndroid.request(permission) === PermissionsAndroid.RESULTS.GRANTED;
1422
+ }
1423
+ var FishAgentWidget = forwardRef(
1424
+ function FishAgentWidget2(props, ref) {
1425
+ const propsRef = useRef3(props);
1426
+ propsRef.current = props;
1427
+ const systemScheme = useColorScheme();
1428
+ const scheme = props.colorScheme === "system" ? systemScheme ?? "light" : props.colorScheme ?? "light";
1429
+ const theme = useMemo2(
1430
+ () => ({ ...scheme === "dark" ? DARK_THEME : LIGHT_THEME, ...props.theme }),
1431
+ [scheme, props.theme]
1432
+ );
1433
+ const avatarKey = sourceKey(props.avatar);
1434
+ const launcherIconKey = sourceKey(props.launcherIcon);
1435
+ const images = useMemo2(
1436
+ () => ({ avatar: props.avatar, launcherIcon: props.launcherIcon }),
1437
+ [avatarKey, launcherIconKey]
1438
+ );
1439
+ const [remote, setRemote] = useState5(null);
1440
+ const attributes = {
1441
+ agentId: props.agentId,
1442
+ serverUrl: props.serverUrl,
1443
+ userId: props.userId,
1444
+ language: props.language,
1445
+ dynamicVariables: props.dynamicVariables,
1446
+ agentName: props.agentName,
1447
+ greeting: props.greeting,
1448
+ proactiveMessage: props.proactiveMessage,
1449
+ proactiveDelaySeconds: props.proactiveDelay,
1450
+ transcript: props.transcript,
1451
+ textInput: props.textInput,
1452
+ micMuting: props.micMuting,
1453
+ consent: props.consent,
1454
+ consentKey: props.consentKey,
1455
+ consentText: props.consentText,
1456
+ termsUrl: props.termsUrl,
1457
+ privacyUrl: props.privacyUrl,
1458
+ position: props.position,
1459
+ texts: props.textContents
1460
+ };
1461
+ const settings = resolveSettings(attributes, remote);
1462
+ for (const [key, value] of Object.entries(MOBILE_TEXTS)) {
1463
+ if (remote?.text_contents?.[key] === void 0 && props.textContents?.[key] === void 0) {
1464
+ settings.texts[key] = value;
1465
+ }
1466
+ }
1467
+ const { texts } = settings;
1468
+ const conversation = useConversation(
1469
+ {},
1470
+ { callNotification: props.callNotification, audioOutput: props.audioOutput }
1471
+ );
1472
+ const [open, setOpen] = useState5(false);
1473
+ const [dragged, setDragged] = useState5(draggedPosition);
1474
+ const [container, setContainer] = useState5(null);
1475
+ const [phase, setPhase] = useState5("idle");
1476
+ const [pending, setPending] = useState5(null);
1477
+ const [seconds, setSeconds] = useState5(0);
1478
+ const [error, setError] = useState5(null);
1479
+ const [pendingText, setPendingText] = useState5(null);
1480
+ const [proactiveVisible, setProactiveVisible] = useState5(false);
1481
+ const storeRef = useRef3(null);
1482
+ storeRef.current ?? (storeRef.current = new TranscriptStore());
1483
+ const store = storeRef.current;
1484
+ const [entries, setEntries] = useState5(store.entries);
1485
+ const secondsRef = useRef3(0);
1486
+ const liveRef = useRef3(null);
1487
+ const detachRef = useRef3(null);
1488
+ const attemptRef = useRef3(null);
1489
+ const startingRef = useRef3(false);
1490
+ const consentAcceptedRef = useRef3(false);
1491
+ const lastActivityRef = useRef3(0);
1492
+ useImperativeHandle(ref, () => ({ expand: () => setOpen(true) }), []);
1493
+ useEffect4(() => store.subscribe(() => setEntries(store.entries)), [store]);
1494
+ useEffect4(() => {
1495
+ const agentId = props.agentId;
1496
+ if (!agentId) {
1497
+ return;
1498
+ }
1499
+ let stale = false;
1500
+ void fetchRemoteConfig(props.serverUrl, agentId, props.origin).then((config) => {
1501
+ if (!stale && config) {
1502
+ setRemote(config);
1503
+ }
1504
+ });
1505
+ return () => {
1506
+ stale = true;
1507
+ };
1508
+ }, [props.agentId, props.serverUrl, props.origin]);
1509
+ useEffect4(() => {
1510
+ const storage = props.consentStorage;
1511
+ if (!settings.consent || !storage) {
1512
+ return;
1513
+ }
1514
+ let stale = false;
1515
+ void Promise.resolve().then(() => storage.getItem(settings.consentKey)).then((value) => {
1516
+ if (!stale && value === "accepted") {
1517
+ consentAcceptedRef.current = true;
1518
+ }
1519
+ }).catch(() => void 0);
1520
+ return () => {
1521
+ stale = true;
1522
+ };
1523
+ }, [settings.consent, settings.consentKey, props.consentStorage]);
1524
+ useEffect4(() => {
1525
+ if (open || !settings.proactiveMessage || proactiveDismissed) {
1526
+ setProactiveVisible(false);
1527
+ return;
1528
+ }
1529
+ const timer = setTimeout(() => setProactiveVisible(true), settings.proactiveDelaySeconds * 1e3);
1530
+ return () => clearTimeout(timer);
1531
+ }, [open, settings.proactiveMessage, settings.proactiveDelaySeconds]);
1532
+ useEffect4(() => {
1533
+ if (phase !== "live") {
1534
+ return;
1535
+ }
1536
+ setSeconds(0);
1537
+ secondsRef.current = 0;
1538
+ const startedAt = Date.now();
1539
+ const timer = setInterval(() => {
1540
+ const elapsed = Math.floor((Date.now() - startedAt) / 1e3);
1541
+ secondsRef.current = elapsed;
1542
+ setSeconds(elapsed);
1543
+ }, 500);
1544
+ return () => clearInterval(timer);
1545
+ }, [phase]);
1546
+ useEffect4(() => {
1547
+ if (!open) {
1548
+ return;
1549
+ }
1550
+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
1551
+ setOpen(false);
1552
+ return true;
1553
+ });
1554
+ return () => subscription.remove();
1555
+ }, [open]);
1556
+ useEffect4(
1557
+ () => () => {
1558
+ if (attemptRef.current) {
1559
+ attemptRef.current.cancelled = true;
1560
+ }
1561
+ detachRef.current?.();
1562
+ },
1563
+ []
1564
+ );
1565
+ const reportError = (detail) => propsRef.current.onError?.(detail);
1566
+ const needsConsent = () => settings.consent && !consentAcceptedRef.current && !acceptedConsentKeys.has(settings.consentKey);
1567
+ const restingPhase = () => store.entries.length > 0 ? "ended" : "idle";
1568
+ const startCall = async (kind, firstText) => {
1569
+ if (startingRef.current || liveRef.current || phase === "starting" || phase === "live") {
1570
+ return;
1571
+ }
1572
+ startingRef.current = true;
1573
+ setError(null);
1574
+ setPendingText(firstText ?? null);
1575
+ setPhase("starting");
1576
+ const attempt = { cancelled: false };
1577
+ attemptRef.current = attempt;
1578
+ const bridge = new CallbackBridge();
1579
+ try {
1580
+ const current = propsRef.current;
1581
+ const options = { microphone: kind === "voice" };
1582
+ if (current.sessionTokenProvider) {
1583
+ options.sessionToken = await current.sessionTokenProvider();
1584
+ } else if (settings.agentId) {
1585
+ options.agentId = settings.agentId;
1586
+ if (current.origin) {
1587
+ options.origin = current.origin;
1588
+ }
1589
+ if (settings.serverUrl) {
1590
+ options.serverUrl = settings.serverUrl;
1591
+ }
1592
+ if (settings.language) {
1593
+ options.language = settings.language;
1594
+ }
1595
+ if (settings.dynamicVariables) {
1596
+ options.dynamicVariables = settings.dynamicVariables;
1597
+ }
1598
+ if (settings.userId) {
1599
+ options.endUserId = settings.userId;
1600
+ }
1601
+ } else {
1602
+ console.error("[fish-agent] set agentId or sessionTokenProvider to start a session");
1603
+ throw new Error("missing configuration");
1604
+ }
1605
+ if (attempt.cancelled) {
1606
+ throw Object.assign(new Error("cancelled"), { name: "AbortError" });
1607
+ }
1608
+ if (current.clientTools) {
1609
+ options.clientTools = current.clientTools;
1610
+ }
1611
+ current.onCall?.(options);
1612
+ const ours = {
1613
+ onDisconnect: ({ reason }) => {
1614
+ if (liveRef.current !== bridge) {
1615
+ return;
1616
+ }
1617
+ liveRef.current = null;
1618
+ detachRef.current?.();
1619
+ detachRef.current = null;
1620
+ store.pushDivider(`${texts.endedDividerLabel} \xB7 ${formatTimer(secondsRef.current)}`);
1621
+ setPhase("ended");
1622
+ propsRef.current.onDisconnect?.({ reason });
1623
+ },
1624
+ onError: (sessionError) => {
1625
+ if (liveRef.current !== bridge) {
1626
+ return;
1627
+ }
1628
+ if (showsErrorBanner(sessionError)) {
1629
+ setError(errorText(texts, sessionError.code));
1630
+ }
1631
+ reportError({
1632
+ code: sessionError.code,
1633
+ message: sessionError.message,
1634
+ ...sessionError.stage !== void 0 ? { stage: sessionError.stage } : {},
1635
+ ...sessionError.recovered !== void 0 ? { recovered: sessionError.recovered } : {}
1636
+ });
1637
+ }
1638
+ };
1639
+ for (const event of BRIDGED_EVENTS) {
1640
+ const key = `on${event.charAt(0).toUpperCase()}${event.slice(1)}`;
1641
+ ours[key] = (payload) => bridge.emit(event, payload);
1642
+ }
1643
+ options.callbacks = mergeCallbacks(ours, options.callbacks);
1644
+ detachRef.current?.();
1645
+ detachRef.current = store.attach(bridge);
1646
+ const sessionId = await conversation.startSession(options);
1647
+ if (attempt.cancelled) {
1648
+ throw Object.assign(new Error("cancelled"), { name: "AbortError" });
1649
+ }
1650
+ liveRef.current = bridge;
1651
+ setPendingText(null);
1652
+ setPhase("live");
1653
+ if (firstText) {
1654
+ conversation.sendUserMessage(firstText);
1655
+ }
1656
+ propsRef.current.onConnect?.({ sessionId });
1657
+ } catch (startError) {
1658
+ if (liveRef.current !== bridge) {
1659
+ detachRef.current?.();
1660
+ detachRef.current = null;
1661
+ }
1662
+ setPendingText(null);
1663
+ setPhase(restingPhase());
1664
+ if (attempt.cancelled || isAbort(startError)) {
1665
+ return;
1666
+ }
1667
+ const code = startError.code;
1668
+ setError(errorText(texts, code));
1669
+ reportError({
1670
+ code: code ?? "connection_failed",
1671
+ message: startError instanceof Error ? startError.message : String(startError)
1672
+ });
1673
+ } finally {
1674
+ startingRef.current = false;
1675
+ if (attemptRef.current === attempt) {
1676
+ attemptRef.current = null;
1677
+ }
1678
+ }
1679
+ };
1680
+ const gate = (action) => {
1681
+ if (needsConsent()) {
1682
+ setPending(action);
1683
+ return;
1684
+ }
1685
+ void startCall(action.kind, action.kind === "text" ? action.text : void 0);
1686
+ };
1687
+ const requestVoice = () => gate({ kind: "voice" });
1688
+ const requestText = (text) => {
1689
+ if (phase === "live" && liveRef.current) {
1690
+ conversation.sendUserMessage(text);
1691
+ return;
1692
+ }
1693
+ gate({ kind: "text", text });
1694
+ };
1695
+ const agreeConsent = () => {
1696
+ consentAcceptedRef.current = true;
1697
+ acceptedConsentKeys.add(settings.consentKey);
1698
+ const storage = propsRef.current.consentStorage;
1699
+ if (storage) {
1700
+ void Promise.resolve().then(() => storage.setItem(settings.consentKey, "accepted")).catch(() => void 0);
1701
+ }
1702
+ const action = pending;
1703
+ setPending(null);
1704
+ if (action) {
1705
+ void startCall(action.kind, action.kind === "text" ? action.text : void 0);
1706
+ }
1707
+ };
1708
+ const toggleMute = async () => {
1709
+ if (!liveRef.current) {
1710
+ return;
1711
+ }
1712
+ const next = !conversation.micMuted;
1713
+ try {
1714
+ if (!next && !await ensureMicrophonePermission()) {
1715
+ setError(texts.errorMicDenied);
1716
+ reportError({ code: "mic_permission_denied", message: "Microphone permission was denied" });
1717
+ return;
1718
+ }
1719
+ await conversation.setMicMuted(next);
1720
+ setError(null);
1721
+ } catch (muteError) {
1722
+ const code = muteError.code;
1723
+ if (code === "mic_permission_denied") {
1724
+ setError(texts.errorMicDenied);
1725
+ }
1726
+ reportError({
1727
+ code: code ?? "connection_failed",
1728
+ message: muteError instanceof Error ? muteError.message : String(muteError)
1729
+ });
1730
+ }
1731
+ };
1732
+ const endCall = () => {
1733
+ if (attemptRef.current) {
1734
+ attemptRef.current.cancelled = true;
1735
+ }
1736
+ void conversation.endSession().catch(() => void 0);
1737
+ };
1738
+ const closePanel = () => {
1739
+ endCall();
1740
+ setError(null);
1741
+ setPending(null);
1742
+ setOpen(false);
1743
+ };
1744
+ const dismissProactive = () => {
1745
+ proactiveDismissed = true;
1746
+ setProactiveVisible(false);
1747
+ };
1748
+ const onActivity = () => {
1749
+ if (phase !== "live") {
1750
+ return;
1751
+ }
1752
+ const now = Date.now();
1753
+ if (now - lastActivityRef.current > 1500) {
1754
+ lastActivityRef.current = now;
1755
+ conversation.sendUserActivity();
1756
+ }
1757
+ };
1758
+ const screen = useWindowDimensions();
1759
+ const insets = props.insets ?? {};
1760
+ const top = settings.position.startsWith("top");
1761
+ const draggable = props.draggable === true;
1762
+ const position = draggable ? dragged : null;
1763
+ const alignEnd = position ? position.side === "right" : settings.position.endsWith("right");
1764
+ const corner = {
1765
+ position: "absolute",
1766
+ [top ? "top" : "bottom"]: theme.offset + ((top ? insets.top : insets.bottom) ?? 0),
1767
+ [alignEnd ? "right" : "left"]: theme.offset + ((alignEnd ? insets.right : insets.left) ?? 0)
1768
+ };
1769
+ const bounds = container && {
1770
+ ...container,
1771
+ left: theme.offset + (insets.left ?? 0),
1772
+ right: theme.offset + (insets.right ?? 0),
1773
+ top: theme.offset + (insets.top ?? 0),
1774
+ bottom: theme.offset + (insets.bottom ?? 0)
1775
+ };
1776
+ const launcher = (children, anchorSize) => /* @__PURE__ */ jsx5(
1777
+ Draggable,
1778
+ {
1779
+ anchorSize,
1780
+ cornerStyle: corner,
1781
+ position,
1782
+ bounds,
1783
+ enabled: draggable,
1784
+ onDragStart: () => {
1785
+ if (proactiveVisible) {
1786
+ dismissProactive();
1787
+ }
1788
+ },
1789
+ onDragEnd: (next) => {
1790
+ draggedPosition = next;
1791
+ setDragged(next);
1792
+ },
1793
+ children
1794
+ }
1795
+ );
1796
+ let content;
1797
+ if (!open) {
1798
+ content = phase === "live" || phase === "starting" ? launcher(
1799
+ /* @__PURE__ */ jsx5(
1800
+ MinimizedPill,
1801
+ {
1802
+ settings,
1803
+ seconds,
1804
+ live: phase === "live",
1805
+ onExpand: () => setOpen(true),
1806
+ onEnd: endCall
1807
+ }
1808
+ )
1809
+ ) : launcher(
1810
+ /* @__PURE__ */ jsx5(
1811
+ FabView,
1812
+ {
1813
+ settings,
1814
+ proactiveVisible,
1815
+ alignEnd,
1816
+ onOpen: () => setOpen(true),
1817
+ onDismissProactive: dismissProactive
1818
+ }
1819
+ ),
1820
+ { width: theme.fabSize, height: theme.fabSize }
1821
+ );
1822
+ } else {
1823
+ const reconnecting = conversation.status === "reconnecting";
1824
+ const status = phase === "starting" ? /* @__PURE__ */ jsx5(LiveStatus, { label: texts.statusConnecting, color: theme.textSecondary }) : phase === "live" ? reconnecting ? /* @__PURE__ */ jsx5(LiveStatus, { label: texts.statusReconnecting, color: theme.textSecondary }) : /* @__PURE__ */ jsx5(
1825
+ LiveStatus,
1826
+ {
1827
+ label: `${texts.statusLive} \xB7 ${formatTimer(seconds)}`,
1828
+ color: theme.textSecondary,
1829
+ dot: theme.live
1830
+ }
1831
+ ) : phase === "ended" ? /* @__PURE__ */ jsx5(LiveStatus, { label: texts.statusEnded, color: theme.textSecondary }) : null;
1832
+ const inCall = phase !== "idle" && pending === null;
1833
+ const sheet = screen.width < SHEET_BELOW_WIDTH;
1834
+ const callHeight = Math.min(CARD_MAX_HEIGHT, screen.height - 2 * theme.offset - (insets.top ?? 0) - (insets.bottom ?? 0));
1835
+ const panelStyle = sheet ? { flex: 1 } : [
1836
+ styles3.card,
1837
+ { width: CARD_WIDTH, borderRadius: theme.radius, maxHeight: callHeight },
1838
+ inCall && settings.transcript ? { height: callHeight } : null
1839
+ ];
1840
+ const panel = /* @__PURE__ */ jsx5(
1841
+ PanelShell,
1842
+ {
1843
+ settings,
1844
+ status,
1845
+ mode: phase === "live" ? conversation.mode : void 0,
1846
+ live: phase === "live",
1847
+ starting: phase === "starting",
1848
+ muted: conversation.micMuted,
1849
+ onToggleMute: () => void toggleMute(),
1850
+ onEnd: endCall,
1851
+ onMinimize: () => setOpen(false),
1852
+ onClose: closePanel,
1853
+ style: panelStyle,
1854
+ children: pending !== null ? /* @__PURE__ */ jsx5(ConsentView, { settings, fill: sheet, onAgree: agreeConsent, onDecline: () => setPending(null) }) : phase === "idle" ? /* @__PURE__ */ jsx5(HomeView, { settings, fill: sheet, error, onStartVoice: requestVoice, onSendText: requestText }) : /* @__PURE__ */ jsx5(
1855
+ CallView,
1856
+ {
1857
+ settings,
1858
+ entries: pendingText !== null && phase === "starting" ? [...entries, { kind: "message", id: "pending:first", role: "user", text: pendingText, final: true }] : entries,
1859
+ phase,
1860
+ mode: conversation.mode,
1861
+ error,
1862
+ onRestartVoice: requestVoice,
1863
+ onSendText: requestText,
1864
+ onActivity
1865
+ }
1866
+ )
1867
+ }
1868
+ );
1869
+ content = sheet ? (
1870
+ // Insets on an outer view: KeyboardAvoidingView sets its own paddingBottom.
1871
+ /* @__PURE__ */ jsx5(
1872
+ View4,
1873
+ {
1874
+ style: [
1875
+ StyleSheet3.absoluteFill,
1876
+ {
1877
+ backgroundColor: theme.background,
1878
+ paddingTop: insets.top ?? 0,
1879
+ paddingBottom: insets.bottom ?? 0,
1880
+ paddingLeft: insets.left ?? 0,
1881
+ paddingRight: insets.right ?? 0
1882
+ }
1883
+ ],
1884
+ children: /* @__PURE__ */ jsx5(KeyboardAvoidingView, { behavior: "padding", style: styles3.fill, children: panel })
1885
+ }
1886
+ )
1887
+ ) : /* @__PURE__ */ jsx5(KeyboardAvoidingView, { behavior: "padding", style: corner, children: panel });
1888
+ }
1889
+ return /* @__PURE__ */ jsx5(ThemeContext.Provider, { value: theme, children: /* @__PURE__ */ jsx5(ImagesContext.Provider, { value: images, children: /* @__PURE__ */ jsx5(
1890
+ View4,
1891
+ {
1892
+ pointerEvents: "box-none",
1893
+ style: [StyleSheet3.absoluteFill, styles3.layer, props.style],
1894
+ onLayout: (e) => setContainer({ width: e.nativeEvent.layout.width, height: e.nativeEvent.layout.height }),
1895
+ children: content
1896
+ }
1897
+ ) }) });
1898
+ }
1899
+ );
1900
+ var styles3 = StyleSheet3.create({
1901
+ fill: { flex: 1 },
1902
+ // Android draws higher elevation on top regardless of render order, so an
1903
+ // app's elevated views (Button, cards) would otherwise cover the panel.
1904
+ layer: { elevation: 1e3, zIndex: 1e3 },
1905
+ card: {
1906
+ borderWidth: 1,
1907
+ shadowColor: "#0f0e0d",
1908
+ shadowOpacity: 0.18,
1909
+ shadowRadius: 48,
1910
+ shadowOffset: { width: 0, height: 16 },
1911
+ elevation: 16
1912
+ }
1913
+ });
1914
+ export {
1915
+ DEFAULT_TEXTS2 as DEFAULT_TEXTS,
1916
+ FishAgentWidget
1917
+ };
1918
+ /*!
1919
+ * Icon path data from lucide (https://lucide.dev), used under the ISC license.
1920
+ * See THIRD-PARTY-NOTICES.txt in this package for the full notice.
1921
+ */
1922
+ //# sourceMappingURL=index.js.map