@chatterfly/widget 0.1.0 → 0.3.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.d.ts CHANGED
@@ -1,13 +1,85 @@
1
+ import * as react from 'react';
2
+ import { ComponentType, ReactNode } from 'react';
1
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { ComponentType } from 'react';
3
4
 
5
+ /**
6
+ * Structured error codes surfaced via `onError` (Phase 114.1). Covers the
7
+ * classic embed-support cases so a host can branch on `code` instead of
8
+ * parsing prose. `WidgetError` stringifies to `message`, so existing
9
+ * `onError={(err) => console.error(String(err))}`-style handlers keep working.
10
+ */
11
+ type WidgetErrorCode = "config_missing_api_base" | "config_missing_target" | "workflow_not_public" | "no_live_deployment" | "network" | "token_expired" | "run_failed" | "unknown";
12
+ declare class WidgetError {
13
+ code: WidgetErrorCode;
14
+ message: string;
15
+ constructor(code: WidgetErrorCode, message: string);
16
+ toString(): string;
17
+ }
18
+ /**
19
+ * Imperative handle exposed via `ref` on `ChatterflyWidget` (Phase 114.1).
20
+ * Lets host chrome trigger actions without prop churn — e.g. a "Start over"
21
+ * button, a manual disconnect control, or programmatic message sends.
22
+ */
23
+ interface ChatterflyWidgetHandle {
24
+ /**
25
+ * Restart the conversation. For `workflowId`/`deploymentId` (serverless
26
+ * auto-start) embeds, mints a brand-new run. For a direct `runId` +
27
+ * `participantToken` embed, reconnects the existing run's stream (useful to
28
+ * recover from an "offline" state).
29
+ */
30
+ restart: () => void;
31
+ /** Manually close the connection and stop automatic reconnection. */
32
+ disconnect: () => void;
33
+ /** Send a free-form chat message on an active deliberation session. */
34
+ sendMessage: (text: string) => void;
35
+ }
36
+ /**
37
+ * Typed convenience wrapper over the widget's `--cf-*` CSS custom properties.
38
+ * Friendlier for React hosts than authoring a CSS scope by hand — each key
39
+ * maps 1:1 to the CSS variable of the same purpose (see docs/embedding.md).
40
+ * Unset keys fall back to the CSS defaults (or the `colorScheme` preset).
41
+ */
42
+ interface ThemeTokens {
43
+ primary?: string;
44
+ accent?: string;
45
+ info?: string;
46
+ bg?: string;
47
+ fg?: string;
48
+ muted?: string;
49
+ border?: string;
50
+ surface?: string;
51
+ error?: string;
52
+ radius?: string;
53
+ font?: string;
54
+ height?: string;
55
+ bubbleBotBg?: string;
56
+ bubbleBotFg?: string;
57
+ bubbleUserBg?: string;
58
+ bubbleUserFg?: string;
59
+ headerBg?: string;
60
+ headerFg?: string;
61
+ inputBg?: string;
62
+ shadow?: string;
63
+ spacing?: string;
64
+ avatarSize?: string;
65
+ }
66
+ /**
67
+ * `light` (default) keeps the CSS defaults; `dark` applies the shipped dark
68
+ * token preset; `auto` follows the host page's `prefers-color-scheme`.
69
+ */
70
+ type ColorScheme = "light" | "dark" | "auto";
4
71
  interface WidgetConfig {
5
72
  /** The run ID to connect to. */
6
73
  runId: string;
7
74
  /** Short-lived JWT issued by POST /runs or POST /runs/:id/tokens. */
8
75
  participantToken: string;
9
- /** Base URL of the Chatterfly backend. Defaults to http://localhost:8080. */
10
- apiBase?: string;
76
+ /**
77
+ * Base URL of the Chatterfly backend. Required — there is no localhost
78
+ * default (Phase 114.1: a silent dev-only default is a production trap for
79
+ * third-party embeds). Omitting it produces a `config_missing_api_base`
80
+ * error via `onError` instead of silently pointing at localhost.
81
+ */
82
+ apiBase: string;
11
83
  /** Public deployment ID. When provided, the widget automatically starts a new run. */
12
84
  deploymentId?: string;
13
85
  /**
@@ -17,6 +89,14 @@ interface WidgetConfig {
17
89
  * `deploymentId` for serverless embeds. Ignored if `deploymentId` or `runId` is set.
18
90
  */
19
91
  workflowId?: string;
92
+ /**
93
+ * Initial input values forwarded to the serverless start call (`workflowId`
94
+ * / `deploymentId` auto-start paths only). Lets a host skip intake
95
+ * questions it already has an answer for (e.g. a logged-in user's name).
96
+ * Validated server-side against the workflow's declared inputs, exactly
97
+ * like `POST /api/v1/runs`. Ignored when connecting via `runId` directly.
98
+ */
99
+ initialInput?: Record<string, unknown>;
20
100
  }
21
101
  type RunStatus = "idle" | "connecting" | "replaying" | "running" | "awaiting_input" | "awaiting_voice" | "awaiting_form" | "awaiting_chat" | "awaiting_editor" | "completed" | "error" | "offline";
22
102
  interface ValidationRule {
@@ -153,6 +233,7 @@ type RunEvent = {
153
233
  state?: Record<string, unknown>;
154
234
  } | {
155
235
  type: "run.cancelled";
236
+ state?: Record<string, unknown>;
156
237
  } | {
157
238
  type: "run.failed";
158
239
  error: string;
@@ -190,14 +271,76 @@ interface InputComponentProps {
190
271
  };
191
272
  }
192
273
 
274
+ interface WidgetStrings {
275
+ statusInitialising: string;
276
+ statusConnecting: string;
277
+ statusRunning: string;
278
+ statusCompletedTitle: string;
279
+ statusCompletedBody: string;
280
+ statusErrorTitle: string;
281
+ statusOfflineTitle: string;
282
+ statusOfflineBody: string;
283
+ statusListening: string;
284
+ resumingConversation: string;
285
+ conversationCompleted: string;
286
+ somethingWentWrong: string;
287
+ chatInputPlaceholder: string;
288
+ sendButton: string;
289
+ handBackButton: string;
290
+ converseDoneButton: string;
291
+ }
292
+ declare const defaultStrings: WidgetStrings;
293
+ /** Merge a partial override on top of the defaults. */
294
+ declare function resolveStrings(overrides?: Partial<WidgetStrings>): WidgetStrings;
295
+
296
+ /** Props passed to a `BotBubble`/`UserBubble` override component (Phase 114.3). */
297
+ interface BubbleProps {
298
+ children: ReactNode;
299
+ }
300
+ /** Bubble override map accepted by `ChatTimeline` and passed through from the top-level widget props. */
301
+ interface BubbleComponents {
302
+ BotBubble?: ComponentType<BubbleProps>;
303
+ UserBubble?: ComponentType<BubbleProps>;
304
+ }
305
+ interface ChatTimelineProps {
306
+ entries: TimelineEntry[];
307
+ /** Show typing indicator when waiting for bot response */
308
+ showTyping?: boolean;
309
+ /** Accumulated LLM tokens for the in-progress message; empty when idle */
310
+ streamingText?: string;
311
+ /**
312
+ * Override the plain-text bot/user chat bubbles for full visual control
313
+ * without forking this component. Special-case bubbles (form submission
314
+ * summary, document cards) are unaffected. See `docs/embedding.md`.
315
+ */
316
+ components?: BubbleComponents;
317
+ }
318
+ declare function ChatTimeline({ entries, showTyping, streamingText, components }: ChatTimelineProps): react_jsx_runtime.JSX.Element;
319
+
320
+ interface PersistSessionOptions {
321
+ storage?: "session" | "local";
322
+ key?: string;
323
+ }
324
+ type PersistSessionConfig = boolean | PersistSessionOptions;
325
+
193
326
  interface ChatterflyWidgetProps extends Omit<WidgetConfig, "runId" | "participantToken"> {
194
327
  /** The run ID to connect to. Required unless `deploymentId`/`workflowId` is provided. */
195
328
  runId?: string;
196
329
  /** Short-lived JWT issued by POST /runs. Required unless `deploymentId`/`workflowId` is provided. */
197
330
  participantToken?: string;
198
331
  className?: string;
199
- onCompleted?: () => void;
200
- onError?: (err: string) => void;
332
+ /** Fires once when the run reaches a terminal "completed" state; carries the final run state when available. */
333
+ onCompleted?: (output?: Record<string, unknown>) => void;
334
+ /** Fires once on a terminal "error" state, or on a config/connection failure (missing apiBase, no live deployment, network, etc). */
335
+ onError?: (err: WidgetError) => void;
336
+ /** Firehose — every raw run event, in order. Prefer the granular callbacks below unless you need everything. */
337
+ onEvent?: (event: RunEvent) => void;
338
+ /** Fires whenever the widget's client-side status changes. */
339
+ onStatusChange?: (status: RunStatus) => void;
340
+ /** Fires each time a new HITL session opens (chat, form, input, editor, voice). */
341
+ onSessionOpened?: (session: HITLSession) => void;
342
+ /** Fires for each bot-authored chat message (Message nodes, deliberation replies). */
343
+ onMessage?: (message: ChatMessage) => void;
201
344
  /**
202
345
  * When true, automatically focuses the active input each time a new HITL
203
346
  * session opens. Recommended for internal dashboard surfaces where the user
@@ -205,7 +348,47 @@ interface ChatterflyWidgetProps extends Omit<WidgetConfig, "runId" | "participan
205
348
  * widget never steals focus from the host page.
206
349
  */
207
350
  autoFocusInput?: boolean;
208
- }
351
+ /** Rendered in place of the default spinner while connecting/auto-starting. */
352
+ loadingFallback?: ReactNode;
353
+ /** Typed CSS-variable overrides — see `docs/embedding.md` theming section. */
354
+ theme?: ThemeTokens;
355
+ /** `light` (default) | `dark` | `auto` (follows `prefers-color-scheme`). */
356
+ colorScheme?: ColorScheme;
357
+ /** Rendered above the chat timeline on every state. */
358
+ header?: ReactNode;
359
+ /** Rendered below the active input area on every state. */
360
+ footer?: ReactNode;
361
+ /** Rendered instead of the default "waiting" indicator when running with no active session or timeline content yet. */
362
+ emptyState?: ReactNode;
363
+ /** Rendered instead of the default "Conversation completed." footer. */
364
+ completedState?: ReactNode;
365
+ /** Rendered instead of the default "Something went wrong" footer. */
366
+ errorState?: ReactNode;
367
+ /** Override the plain-text bot/user chat bubbles. See `ChatTimelineProps.components`. */
368
+ components?: BubbleComponents;
369
+ /** Overrides for any built-in chrome literal (status labels, chat affordances). See `WidgetStrings`. */
370
+ strings?: Partial<WidgetStrings>;
371
+ /**
372
+ * Persist the resolved `{ run_id, participant_token }` from a serverless
373
+ * auto-start (`workflowId`/`deploymentId`) so a page refresh resumes the
374
+ * existing run instead of minting a new one. `true` uses sessionStorage;
375
+ * pass an options object to use localStorage or a custom key. Ignored for
376
+ * direct `runId` embeds. Default `false`.
377
+ */
378
+ persistSession?: PersistSessionConfig;
379
+ /** `inline` (default, zero behavior change) | `floating` (docked launcher bubble + expandable panel). */
380
+ mode?: "inline" | "floating";
381
+ /** Where the launcher bubble docks in `floating` mode. Default `bottom-right`. */
382
+ position?: LauncherPosition;
383
+ /** Whether the floating panel starts open. Default `false`. */
384
+ defaultOpen?: boolean;
385
+ /** Fires whenever the floating panel opens/closes. */
386
+ onOpenChange?: (open: boolean) => void;
387
+ /** Override the default chat-bubble launcher icon. */
388
+ launcherIcon?: ReactNode;
389
+ }
390
+ /** `bottom-right` (default) | `bottom-left` — where the launcher bubble docks. */
391
+ type LauncherPosition = "bottom-right" | "bottom-left";
209
392
  /**
210
393
  * Top-level Chatterfly widget.
211
394
  *
@@ -217,14 +400,44 @@ interface ChatterflyWidgetProps extends Omit<WidgetConfig, "runId" | "participan
217
400
  *
218
401
  * Delegates to ChatAdapter for the chat-first participant experience.
219
402
  */
220
- declare function ChatterflyWidget(props: ChatterflyWidgetProps): react_jsx_runtime.JSX.Element;
403
+ declare const ChatterflyWidget: react.ForwardRefExoticComponent<ChatterflyWidgetProps & react.RefAttributes<ChatterflyWidgetHandle>>;
221
404
 
222
405
  interface ChatAdapterProps extends WidgetConfig {
223
406
  className?: string;
224
- onCompleted?: () => void;
225
- onError?: (err: string) => void;
407
+ /** Fires once when the run reaches a terminal "completed" state; carries the final run state when available. */
408
+ onCompleted?: (output?: Record<string, unknown>) => void;
409
+ /** Fires once when the run reaches a terminal "error" state, or on a config/connection failure. */
410
+ onError?: (err: WidgetError) => void;
411
+ /** Firehose — every raw run event, in order. Prefer the granular callbacks below unless you need everything. */
412
+ onEvent?: (event: RunEvent) => void;
413
+ /** Fires whenever the widget's client-side status changes. */
414
+ onStatusChange?: (status: RunStatus) => void;
415
+ /** Fires each time a new HITL session opens (chat, form, input, editor, voice). */
416
+ onSessionOpened?: (session: HITLSession) => void;
417
+ /** Fires for each bot-authored chat message (Message nodes, deliberation replies). */
418
+ onMessage?: (message: ChatMessage) => void;
226
419
  /** See ChatterflyWidgetProps.autoFocusInput. */
227
420
  autoFocusInput?: boolean;
421
+ /** Rendered in place of the default spinner while connecting/auto-starting. */
422
+ loadingFallback?: ReactNode;
423
+ /** Typed CSS-variable overrides — see `docs/embedding.md` theming section. */
424
+ theme?: ThemeTokens;
425
+ /** `light` (default) | `dark` | `auto` (follows `prefers-color-scheme`). */
426
+ colorScheme?: ColorScheme;
427
+ /** Rendered above the chat timeline on every state. */
428
+ header?: ReactNode;
429
+ /** Rendered below the active input area on every state. */
430
+ footer?: ReactNode;
431
+ /** Rendered instead of the default "waiting" indicator when running with no active session or timeline content yet. */
432
+ emptyState?: ReactNode;
433
+ /** Rendered instead of the default "Conversation completed." footer. */
434
+ completedState?: ReactNode;
435
+ /** Rendered instead of the default "Something went wrong" footer. */
436
+ errorState?: ReactNode;
437
+ /** Override the plain-text bot/user chat bubbles. See `ChatTimelineProps.components`. */
438
+ components?: BubbleComponents;
439
+ /** Overrides for any built-in chrome literal (status labels, chat affordances). See `WidgetStrings`. */
440
+ strings?: Partial<WidgetStrings>;
228
441
  }
229
442
  /**
230
443
  * Chat-first participant experience.
@@ -233,16 +446,7 @@ interface ChatAdapterProps extends WidgetConfig {
233
446
  * The currently active input (from the latest HITL session) appears anchored
234
447
  * at the bottom. Past interactions come from the server timeline.
235
448
  */
236
- declare function ChatAdapter({ runId, participantToken, apiBase, className, onCompleted, onError, autoFocusInput, }: ChatAdapterProps): react_jsx_runtime.JSX.Element;
237
-
238
- interface ChatTimelineProps {
239
- entries: TimelineEntry[];
240
- /** Show typing indicator when waiting for bot response */
241
- showTyping?: boolean;
242
- /** Accumulated LLM tokens for the in-progress message; empty when idle */
243
- streamingText?: string;
244
- }
245
- declare function ChatTimeline({ entries, showTyping, streamingText }: ChatTimelineProps): react_jsx_runtime.JSX.Element;
449
+ declare const ChatAdapter: react.ForwardRefExoticComponent<ChatAdapterProps & react.RefAttributes<ChatterflyWidgetHandle>>;
246
450
 
247
451
  type VoiceOrbState = "idle" | "listening" | "speaking" | "processing" | "confirming" | "error";
248
452
  interface VoiceOrbProps {
@@ -565,10 +769,43 @@ interface UseRunStreamResult {
565
769
  lastSeq: number;
566
770
  /** Accumulated streaming text from in-progress LLM generation. Empty when idle. */
567
771
  streamingText: string;
772
+ /** Final run state, populated once the run reaches a terminal status. */
773
+ output: Record<string, unknown> | null;
568
774
  sendMessage: (content: string) => Promise<void>;
569
775
  submitHandback: (output?: unknown, idempotencyKey?: string) => Promise<ValidationError[] | null>;
776
+ /** Force-close the connection and stop automatic reconnection. */
777
+ disconnect: () => void;
778
+ /** Re-open the connection after a manual `disconnect()` or an "offline" state. */
779
+ reconnect: () => void;
570
780
  }
571
- declare function useRunStream(config: WidgetConfig): UseRunStreamResult;
781
+ declare function useRunStream(config: WidgetConfig, onEvent?: (event: RunEvent) => void): UseRunStreamResult;
782
+
783
+ interface UseChatterflyRunOptions extends Omit<WidgetConfig, "runId" | "participantToken"> {
784
+ /** Direct connection. Required unless `deploymentId`/`workflowId` is provided. */
785
+ runId?: string;
786
+ /** Required alongside `runId`. */
787
+ participantToken?: string;
788
+ /** Persist the resolved session across page loads. See `PersistSessionConfig`. */
789
+ persistSession?: PersistSessionConfig;
790
+ /** Firehose of every raw run event, in order. */
791
+ onEvent?: (event: RunEvent) => void;
792
+ }
793
+ interface UseChatterflyRunResult extends UseRunStreamResult {
794
+ /** True while the serverless auto-start request is in flight. */
795
+ connecting: boolean;
796
+ /** Set when auto-start configuration is invalid or the start request fails. */
797
+ error: WidgetError | null;
798
+ /** Restart: mints a new run for auto-start configs, reconnects for direct `runId`. */
799
+ restart: () => void;
800
+ }
801
+ /**
802
+ * Headless equivalent of `<ChatterflyWidget>` — resolves a run (directly, or
803
+ * via serverless auto-start) and drives its WebSocket state machine, without
804
+ * rendering any UI. Pair with the exported input components
805
+ * (`InputText`, `InputBoolean`, …) or your own to build a fully custom
806
+ * participant surface.
807
+ */
808
+ declare function useChatterflyRun(options: UseChatterflyRunOptions): UseChatterflyRunResult;
572
809
 
573
810
  type SynthState = "idle" | "speaking" | "paused";
574
811
  interface UseSpeechSynthesisResult {
@@ -703,4 +940,4 @@ declare function extractValue(transcript: string, field: FieldSpec): ExtractionR
703
940
  */
704
941
  declare function buildSpokenPrompt(field: FieldSpec, voiceHint?: string): string;
705
942
 
706
- export { ChatAdapter, type ChatAdapterProps, type ChatMessage, ChatTimeline, type ChatTimelineProps, ChatterflyWidget, type ChatterflyWidgetProps, ConnectionOnboarding, type ConnectionOnboardingProps, type ContinuousVoiceSessionResult, type ContinuousVoiceState, type ExtractionResult, type FieldSpec, type HITLSession, InputBoolean, type InputComponentProps, InputDate, InputDisplay, InputFileUpload, InputLocation, InputMultiSelect, InputNumber, InputRating, InputSingleSelect, InputText, InputTextArea, type InputTypeProps, type LiveSessionConfig, type LiveSessionResult, type LiveTranscript, type LiveVoiceState, type RecordingState, type RepeaterSpec, type RequiredConnection, type RunEvent, type RunStatus, type SessionRendererProps, type SynthState, type TimelineEntry, type UseParticipantConnectionsResult, type UseRunStreamResult, type UseSpeechSynthesisResult, type UseTranscribeResult, type UseVoiceRecorderResult, type ValidationError, type ValidationRule, VoiceContinuousRenderer, type VoiceContinuousRendererProps, VoiceLiveRenderer, type VoiceLiveRendererProps, VoiceOrb, type VoiceOrbProps, type VoiceOrbState, VoicePromptCard, type VoicePromptCardProps, VoiceRenderer, type VoiceRendererProps, type WidgetConfig, buildSpokenPrompt, extractValue, getInputComponent, registerInputType, registerSessionRenderer, resolveInputType, resolveSessionRenderer, useContinuousVoiceSession, useGeminiLiveSession, useParticipantConnections, useRunStream, useSpeechSynthesis, useTranscribe, useVoiceRecorder };
943
+ export { type BubbleComponents, type BubbleProps, ChatAdapter, type ChatAdapterProps, type ChatMessage, ChatTimeline, type ChatTimelineProps, ChatterflyWidget, type ChatterflyWidgetHandle, type ChatterflyWidgetProps, type ColorScheme, ConnectionOnboarding, type ConnectionOnboardingProps, type ContinuousVoiceSessionResult, type ContinuousVoiceState, type ExtractionResult, type FieldSpec, type HITLSession, InputBoolean, type InputComponentProps, InputDate, InputDisplay, InputFileUpload, InputLocation, InputMultiSelect, InputNumber, InputRating, InputSingleSelect, InputText, InputTextArea, type InputTypeProps, type LauncherPosition, type LiveSessionConfig, type LiveSessionResult, type LiveTranscript, type LiveVoiceState, type PersistSessionConfig, type PersistSessionOptions, type RecordingState, type RepeaterSpec, type RequiredConnection, type RunEvent, type RunStatus, type SessionRendererProps, type SynthState, type ThemeTokens, type TimelineEntry, type UseChatterflyRunOptions, type UseChatterflyRunResult, type UseParticipantConnectionsResult, type UseRunStreamResult, type UseSpeechSynthesisResult, type UseTranscribeResult, type UseVoiceRecorderResult, type ValidationError, type ValidationRule, VoiceContinuousRenderer, type VoiceContinuousRendererProps, VoiceLiveRenderer, type VoiceLiveRendererProps, VoiceOrb, type VoiceOrbProps, type VoiceOrbState, VoicePromptCard, type VoicePromptCardProps, VoiceRenderer, type VoiceRendererProps, type WidgetConfig, WidgetError, type WidgetErrorCode, type WidgetStrings, buildSpokenPrompt, defaultStrings, extractValue, getInputComponent, registerInputType, registerSessionRenderer, resolveInputType, resolveSessionRenderer, resolveStrings, useChatterflyRun, useContinuousVoiceSession, useGeminiLiveSession, useParticipantConnections, useRunStream, useSpeechSynthesis, useTranscribe, useVoiceRecorder };