@guideai/react-native 0.2.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useOnboarding-CFxofFst.cjs","sources":["../../core/src/chat/chat-view.ts","../../sdk/src/whiteboard/scene.ts","../src/whiteboard/store.ts","../src/react/useWhiteboard.ts","../src/react/useGuideAI.ts","../src/react/useOnboarding.ts"],"sourcesContent":["// ============================================================\n// @guideai/core — Chat View Interface\n// ============================================================\n//\n// The seam between the chat *brain* (ChatManager) and whatever\n// displays it. `ChatRenderer` is the built-in DOM implementation;\n// `HeadlessChatView` emits events instead so a host application can\n// render the conversation with its own components.\n//\n// Every method here is a command to display something. Nothing in\n// this file reads the page — page reading (snapshot, fingerprint,\n// detection) lives in the brain and runs in both modes.\n\nimport type { AssistantPlanStep, ToolCallResponse, DemoSuggestion } from '../copilot/copilot-types';\nimport type {\n ChatCallbacks,\n ChatMessage,\n ChatMode,\n ChatRenderOptions,\n EscalationSignal,\n GeneratedStep,\n ToolCallDisplayInfo,\n} from './chat-types';\nimport type { NavigationAction } from '../copilot/copilot-types';\nimport type { VoiceLanguagePreference } from '../voice/voice-language';\nimport type { VoiceMediaCommand } from '../voice/voice-language';\n\n/**\n * What the mic control is doing right now. Drives the button's look and\n * its accessible label; the brain owns the transitions.\n */\nexport type VoiceStatus =\n | 'idle'\n | 'connecting'\n | 'listening'\n | 'thinking'\n | 'speaking'\n | 'error';\n\n/** One-shot recording status for the separate record-and-send control. */\nexport type BatchVoiceStatus =\n | 'idle'\n | 'requesting'\n | 'recording'\n | 'transcribing'\n | 'error';\n\nexport type WalkthroughButtonState = 'building' | 'ready' | 'error';\n\n/** A field the intro card may ask for — the server's closed set. */\nexport type IntroField = 'name' | 'email' | 'company' | 'role' | 'phone';\n\nexport interface IntroCardRequest {\n fields: IntroField[];\n /**\n * The site looks visitors up by work email, so the card says so under the\n * fields (UK GDPR transparency: told before the email is given).\n */\n lookupNotice?: boolean;\n /**\n * The visitor pressed Save. Resolves to an error message to show on the\n * card, or null once saved (the caller then hides the card).\n */\n onSubmit: (values: Partial<Record<IntroField, string>>) => Promise<string | null>;\n onSkip: () => void;\n}\n\n/**\n * Display surface for a chat conversation.\n *\n * Implemented by `ChatRenderer` (DOM) and `HeadlessChatView` (events).\n * `ChatManager` depends on this and never on the concrete renderer.\n */\nexport interface ChatView {\n // ── Lifecycle ──────────────────────────────────────────────\n render(callbacks: ChatCallbacks, options?: ChatRenderOptions): void;\n remove(): void;\n isOpen(): boolean;\n\n // ── Messages ───────────────────────────────────────────────\n addMessage(msg: ChatMessage): void;\n loadHistory(messages: ChatMessage[]): void;\n clearMessages(): void;\n addWalkthroughCompleteMessage(): void;\n /** Disable open confirmation cards after an answer given by voice. */\n settleConfirmation?(answer: 'confirmed' | 'cancelled'): void;\n\n // ── Streaming ──────────────────────────────────────────────\n beginStreamingMessage(): void;\n appendStreamDelta(delta: string): void;\n finalizeStreamingMessage(msg: ChatMessage): void;\n setStreaming(streaming: boolean): void;\n\n // ── Busy state ─────────────────────────────────────────────\n setLoading(loading: boolean): void;\n setLoadingStatus(status: string): void;\n\n // ── Mode ───────────────────────────────────────────────────\n setMode(mode: ChatMode): void;\n showModeBanner(): void;\n showModeSwitch(): void;\n showModePill(): void;\n showModeIntro(): void;\n\n // ── Tool calls ─────────────────────────────────────────────\n addToolCallCard(tool: string, description?: string): void;\n updateToolCallCard(tool: string, success: boolean, summary?: string): void;\n /** Draw the plan the assistant stated for the message being streamed. */\n renderPlan(plan: { steps: AssistantPlanStep[]; note?: string | null }): void;\n /** Advance the plan step that owns this endpoint. */\n markPlanStep(tool: string, state: 'running' | 'done' | 'failed'): void;\n\n // ── Walkthroughs & demos ───────────────────────────────────\n setWalkthroughButtonState(\n messageId: string,\n state: WalkthroughButtonState,\n errorMessage?: string,\n ): void;\n playDemo(demo: DemoSuggestion): boolean;\n /** Control the active demo/native media without an agent round-trip. */\n controlActiveMedia(command: VoiceMediaCommand, demo?: DemoSuggestion | null): Promise<boolean>;\n\n // ── Input ──────────────────────────────────────────────────\n setInputValue(value: string): void;\n\n // ── Voice ──────────────────────────────────────────────────\n /** Reveal the mic control. Hidden until the site is known to support voice. */\n showVoiceButton(): void;\n /** Hide the mic control again (plan lost, capability withdrawn). */\n hideVoiceButton(): void;\n /** Paint the mic control for the current voice state. */\n setVoiceStatus(status: VoiceStatus, message?: string): void;\n /** Show partial/final speech beside the live controls without hiding chat history. */\n setLiveVoiceTranscript(event: { role: 'user' | 'assistant'; text: string; final: boolean }): void;\n /** Accessible first-use chooser. Null means the visitor cancelled. */\n requestVoiceLanguage(\n options: VoiceLanguagePreference[],\n current?: VoiceLanguagePreference | null,\n ): Promise<VoiceLanguagePreference | null>;\n /** Show the selected language on voice surfaces. */\n setVoiceLanguage(language: VoiceLanguagePreference): void;\n /** Reveal the lower-cost record-one-message control. */\n showBatchVoiceButton(): void;\n /** Hide the record-one-message control. */\n hideBatchVoiceButton(): void;\n /** Paint the record-one-message control for its current state. */\n setBatchVoiceStatus(status: BatchVoiceStatus, message?: string): void;\n /**\n * Show the spoken-reply switch for recorded messages; null hides it.\n * Optional: headless hosts read replies themselves.\n */\n setVoiceReplyState?(enabled: boolean | null): void;\n /** Live support became unavailable: hide the \"talk to a person\" control. */\n hideSupportButton?(): void;\n\n // ── Support handoff ────────────────────────────────────────\n showSupportButton(): void;\n\n // ── Intro card (a skill's `collects_intro`) ────────────────\n /** Offer the skippable \"who are you\" card. Optional: headless hosts may omit it. */\n showIntroCard?(request: IntroCardRequest): void;\n /** Take the card down (saved, skipped, or no longer wanted). */\n hideIntroCard?(): void;\n\n // ── Expand / collapse (docked sidebar) ─────────────────────\n expand(dock?: 'right' | 'left' | 'bottom'): void;\n collapse(): void;\n toggleExpand(dock?: 'right' | 'left' | 'bottom'): void;\n isExpandedSidebar(): boolean;\n}\n\n/**\n * Events emitted by `HeadlessChatView`, keyed by event name.\n *\n * These mirror the `ChatView` commands: where the DOM renderer would\n * draw something, the headless view announces it instead.\n */\nexport interface ChatViewEvents {\n /** A complete message was added to the conversation. */\n message: ChatMessage;\n /** Prior conversation was restored. */\n history: ChatMessage[];\n /** The conversation was cleared. */\n cleared: void;\n /** A walkthrough finished. */\n walkthroughComplete: void;\n\n /** A streaming answer started. */\n 'stream:start': void;\n /** A chunk of a streaming answer arrived. */\n 'stream:delta': { delta: string; text: string };\n /** A streaming answer completed. */\n 'stream:end': ChatMessage;\n /** Streaming became active or inactive. */\n streaming: { streaming: boolean };\n\n /** Busy state changed. `status` carries the latest status line. */\n loading: { loading: boolean; status: string | null };\n\n /** The active chat mode changed. */\n mode: { mode: ChatMode };\n /** A mode affordance should be surfaced (banner, switch, pill, intro). */\n modeHint: { kind: 'banner' | 'switch' | 'pill' | 'intro'; mode: ChatMode };\n\n /** A tool call started. */\n 'tool:start': { tool: string; description?: string };\n /** A tool call finished. */\n 'tool:end': { tool: string; success: boolean; summary?: string };\n\n /** The assistant stated what it is about to do. */\n 'plan:start': { plan: { steps: AssistantPlanStep[]; note?: string | null } };\n /** A plan step changed state as its endpoint ran. */\n 'plan:step': { tool: string; state: 'running' | 'done' | 'failed' };\n\n /** A walkthrough build changed state. */\n walkthroughState: {\n messageId: string;\n state: WalkthroughButtonState;\n error?: string;\n };\n /** A demo is ready to play. Host decides whether it can show it. */\n demo: DemoSuggestion;\n\n /** The brain wants text placed in the input box. */\n inputValue: { value: string };\n\n /** The mic control became available or unavailable. */\n 'voice:available': { available: boolean };\n /** Voice status changed. */\n 'voice:status': { status: VoiceStatus; message?: string };\n /** Partial and final transcript updates for host-owned voice UI. */\n 'voice:transcript': { role: 'user' | 'assistant'; text: string; final: boolean };\n /** Headless hosts can render their own chooser when this event is emitted. */\n 'voice:languageRequested': {\n options: VoiceLanguagePreference[];\n current: VoiceLanguagePreference | null;\n /** Answer with the visitor's pick, or null to keep `current`. */\n choose: (language: VoiceLanguagePreference | null) => void;\n };\n 'voice:languageChanged': { language: VoiceLanguagePreference };\n /** Batch voice became available or unavailable. */\n 'batchVoice:available': { available: boolean };\n /** Batch voice status changed. */\n 'batchVoice:status': { status: BatchVoiceStatus; message?: string };\n\n /** Escalation to human support should be offered. */\n supportOffered: void;\n /** Whether a \"talk to a person\" control should show at all (live support on). */\n 'support:available': { available: boolean };\n /** Live support with a person: where the conversation stands. */\n 'support:state': HeadlessSupportState;\n /** Live support with a person: a message on the thread (visitor, agent or system). */\n 'support:message': HeadlessSupportMessage;\n\n /** The agent speaks first: show this line (and its quick replies) as a greeting. */\n opener: { text: string; replies: string[] };\n /** Ask the visitor for these details before chatting. Call `onSubmit` / `onSkip`. */\n 'intro:requested': IntroCardRequest;\n /** The intro card is no longer needed. */\n 'intro:hidden': void;\n /** A pending action was answered (by the visitor, or by voice). */\n 'confirmation:settled': { answer: 'confirmed' | 'cancelled' };\n /** Spoken replies are on or off; null when the site has no voice. */\n voiceReply: { enabled: boolean | null };\n /** A tool call needs explicit user confirmation before running. */\n confirmationNeeded: ToolCallResponse;\n\n /** The view was torn down. */\n closed: void;\n}\n\nexport type ChatViewEventName = keyof ChatViewEvents;\n\nexport type ChatViewListener<K extends ChatViewEventName> = (\n payload: ChatViewEvents[K],\n) => void;\n\n/**\n * One answer, flattened for a host application.\n *\n * `text` is the same string our own chat bubble would display. Everything\n * the brain produced alongside it is here too, and `raw` is the untouched\n * message if the host wants something this shape does not name.\n */\nexport interface HeadlessReply {\n /** Display-ready answer text. */\n text: string;\n /** Present when GuideAI routed this turn to the host's configured assistant. */\n intent: 'delegate' | null;\n /** Model-supplied explanation of the routing decision. */\n intentReason: string | null;\n /** Walkthrough steps, selectors already resolved against the live page. */\n steps: GeneratedStep[] | null;\n /** Title for the walkthrough, when there is one. */\n title: string | null;\n /** A playable demo, when the brain suggested one. */\n demo: DemoSuggestion | null;\n /** A page the answer wants to send the visitor to. */\n navigation: NavigationAction | null;\n /** Present when the brain recommends handing off to a human. */\n escalation: EscalationSignal | null;\n /** Tools executed while producing this answer, in order. */\n toolsUsed: ToolCallDisplayInfo[];\n /** A tool awaiting explicit user confirmation before it runs. */\n pendingAction: ToolCallResponse | null;\n /**\n * Pictures the agent drew for this answer (diagrams, timelines, charts).\n * Each also sits in `text`, where it belongs, as a Markdown image.\n */\n images: HeadlessImage[];\n /** The untouched message the brain produced. */\n raw: ChatMessage;\n}\n\n/** A picture drawn for an answer: a PNG to show, and the SVG it was drawn as. */\nexport interface HeadlessImage {\n url: string;\n svg: string | null;\n alt: string;\n width: number;\n height: number;\n}\n\n/** Only pictures our server drew and stored are passed on. */\nconst DRAWING_URL = /^https:\\/\\/res\\.cloudinary\\.com\\/[\\w-]+\\/image\\/upload\\//;\nconst IMAGE_BLOCK = /```image[ \\t]*\\n([\\s\\S]*?)```/g;\n\n/**\n * Image blocks become Markdown images a host can render with whatever it\n * already uses for Markdown, and are listed on their own as well.\n */\nexport function headlessImages(text: string): { text: string; images: HeadlessImage[] } {\n const images: HeadlessImage[] = [];\n const out = (text || '').replace(IMAGE_BLOCK, (_block, raw: string) => {\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(raw.trim()) as Record<string, unknown>;\n } catch {\n return '';\n }\n if (typeof data.url !== 'string' || !DRAWING_URL.test(data.url)) return '';\n const image: HeadlessImage = {\n url: data.url,\n svg: typeof data.svg === 'string' && DRAWING_URL.test(data.svg) ? data.svg : null,\n alt: typeof data.alt === 'string' ? data.alt.slice(0, 200) : '',\n width: Math.round(Number(data.width)) || 1600,\n height: Math.round(Number(data.height)) || 900,\n };\n images.push(image);\n return `![${image.alt.replace(/[[\\]]/g, '')}](${image.url})`;\n });\n return { text: out, images };\n}\n\n/** Live support with a person, as a headless host draws it. */\nexport interface HeadlessSupportState {\n /**\n * `intake`: ask for name, email and the issue, then call `support.start()`.\n * `open`: the thread is live; `support.send()` adds to it.\n * `closed`: the host closed its panel; the thread is kept for this session.\n * `unavailable`: live support is switched off for this site.\n */\n status: 'intake' | 'open' | 'closed' | 'unavailable';\n /** People from the site's team online right now. */\n agentsOnline: number;\n /** The site's own opening line for live support, if it set one. */\n greeting: string;\n /** What the visitor gave last time (or identify() data), to prefill intake. */\n contact: { name: string; email: string };\n}\n\nexport interface HeadlessSupportMessage {\n id: string;\n from: 'visitor' | 'agent' | 'system';\n /** The agent's name, when the inbox shares it. */\n name: string | null;\n text: string;\n at: string;\n}\n\n/** A completed answer produced outside GuideAI but presented through its normal UI pipeline. */\nexport interface ExternalReply {\n text: string;\n steps?: GeneratedStep[] | null;\n title?: string | null;\n navigation?: NavigationAction | null;\n}\n\n/** Flattens a brain-produced message into the host-facing reply shape. */\nexport function toHeadlessReply(msg: ChatMessage): HeadlessReply {\n // The headless view has already turned pictures into Markdown images.\n const { text, images } = msg.images ? { text: msg.text, images: msg.images } : headlessImages(msg.text);\n return {\n text,\n intent: msg.intent ?? null,\n intentReason: msg.intentReason ?? null,\n steps: msg.guideSteps ?? null,\n title: msg.guideTitle ?? null,\n demo: msg.demo ?? null,\n navigation: msg.navigation ?? null,\n escalation: msg.escalation ?? null,\n toolsUsed: msg.toolCalls ?? [],\n pendingAction: msg.confirmationNeeded ? msg.pendingToolCall ?? null : null,\n images,\n raw: msg,\n };\n}\n","// ============================================================\n// @guideai/sdk — Whiteboard scene: the plan a board plays\n// ============================================================\n//\n// A scene is a title and a few steps. Each step is a line of narration and\n// what the pen does while it is said: a sketch (lines, polygons, curves,\n// ovals, angle marks, dots), handwriting, a mark round something, a small\n// table, a picture, a highlight, an erase. Everything sits on an even grid,\n// 160 wide by 100 tall (v3: one unit is the same length both ways, so a\n// square is square); the browser turns it into strokes. A scene without\n// `v: 3` is the older 0-100-both-ways grid and is stretched onto this one.\n//\n// A step may also annotate the visitor's real page (`point`): a pen ring or\n// underline on a control or section that is on their screen right now. That\n// is not drawing — the board draws the idea; a point marks the real thing.\n//\n// The server checks every plan before sending it, and this checks it again:\n// a host can hand the board its own scene (`GuideAI.whiteboard.play`), and a\n// board only ever draws what passes here. Labels are text, never markup.\n\nexport const LIMITS = {\n steps: 12,\n itemsPerStep: 8,\n items: 60,\n say: 300,\n text: 60,\n art: 80,\n title: 80,\n id: 24,\n freePoints: 32,\n tableRows: 6,\n tableCols: 4,\n cell: 24,\n artContours: 400,\n contourChars: 20_000,\n} as const;\n\nexport const INK_KINDS = [\n 'line', 'arrow', 'poly', 'curve', 'free', 'oval', 'corner', 'arc', 'dot',\n 'circle', 'box', 'underline', 'cross', 'tick', 'bracket',\n] as const;\n/** Pen items drawn through a list of points. */\nconst POINT_INKS: readonly string[] = ['poly', 'curve', 'free', 'corner', 'arc'];\n/** The board grid: x 0-160, y 0-100. */\nexport const BOARD_W = 160;\nexport const BOARD_H = 100;\n/** How a point marks the real page. */\nexport const POINT_MARKS = ['circle', 'underline', 'box'] as const;\nexport type PointMark = (typeof POINT_MARKS)[number];\nexport type InkKind = (typeof INK_KINDS)[number];\nexport type Size = 's' | 'm' | 'l';\nexport type Tone = 'ink' | 'blue' | 'red' | 'green';\nexport type Point = [number, number];\nexport type Box = [number, number, number, number];\n\nexport type BoardItem =\n | { kind: 'art'; id?: string; art: string; at: Box; tone: Tone }\n | { kind: 'text'; id?: string; text: string; at: Point; size: Size; tone: Tone }\n | { kind: 'ink'; id?: string; ink: InkKind; at?: Point | Box; to?: Point; pts?: Point[]; closed?: boolean; tone: Tone }\n | { kind: 'table'; id?: string; rows: string[][]; at: [number, number, number]; tone: Tone }\n | { kind: 'mark'; mark: string }\n | { kind: 'point'; point: string; as: PointMark }\n | { kind: 'erase'; erase: string };\n\nexport interface BoardStep {\n say: string;\n clear: boolean;\n draw: BoardItem[];\n}\n\n/** Ink for a picture: traced contours (SVG path data) in their own box. */\nexport interface ArtInk {\n view_box: string;\n transform: string;\n contours: string[];\n}\n\nexport interface BoardScene {\n /** 3: the even 160 x 100 grid. Absent (a host's board): 0-100 both ways. */\n v?: 2 | 3;\n title: string;\n /** Example numbers: the board says so. */\n sample: boolean;\n steps: BoardStep[];\n /** Pictures by description: a built-in icon, or traced ink. */\n art: Record<string, { icon: string } | ArtInk>;\n}\n\nexport class SceneError extends Error {\n override name = 'SceneError';\n}\n\nconst ID = /^[A-Za-z0-9_-]{1,24}$/;\nconst SIZES: readonly string[] = ['s', 'm', 'l'];\nconst TONES: readonly string[] = ['ink', 'blue', 'red', 'green'];\n/** Path data is drawn, never run: only commands and numbers may appear. */\nconst PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\\s+-]*$/;\n\nconst flat = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim().slice(0, max) : '';\n\nconst clamp = (n: number, top = BOARD_H): number => Math.round(Math.min(top, Math.max(0, n)) * 10) / 10;\n\nfunction num(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\n/** x on the old 0-100 grid is stretched by this onto the even one. */\nlet wide = 1;\n\nfunction point(raw: unknown): Point | null {\n if (!Array.isArray(raw) || raw.length !== 2) return null;\n const [x, y] = raw.map(num);\n return x === null || y === null ? null : [clamp(x * wide, BOARD_W), clamp(y)];\n}\n\nfunction box(raw: unknown): Box | null {\n if (!Array.isArray(raw) || raw.length !== 4) return null;\n const v = raw.map(num);\n if (v.some((n) => n === null)) return null;\n const x = clamp((v[0] as number) * wide, BOARD_W);\n const y = clamp(v[1] as number);\n const w = Math.min(Math.max(1, (v[2] as number) * wide), BOARD_W - x);\n const h = Math.min(Math.max(1, v[3] as number), BOARD_H - y);\n return w >= 1 && h >= 1 ? [x, y, w, h] : null;\n}\n\nfunction tone(raw: unknown): Tone {\n return typeof raw === 'string' && TONES.includes(raw) ? (raw as Tone) : 'ink';\n}\n\nfunction id(raw: unknown): string | undefined {\n return typeof raw === 'string' && ID.test(raw) ? raw : undefined;\n}\n\nfunction item(raw: unknown): BoardItem | null {\n if (!raw || typeof raw !== 'object') return null;\n const r = raw as Record<string, unknown>;\n const kinds = ['art', 'text', 'ink', 'rows', 'mark', 'erase', 'point'].filter((k) => r[k] !== undefined && r[k] !== null && r[k] !== '');\n if (kinds.length !== 1) return null;\n switch (kinds[0]) {\n case 'art': {\n const at = box(r.at);\n const art = flat(r.art, LIMITS.art);\n return at && art ? { kind: 'art', id: id(r.id), art, at, tone: tone(r.tone) } : null;\n }\n case 'text': {\n const at = point(Array.isArray(r.at) ? r.at.slice(0, 2) : null);\n const text = flat(r.text, LIMITS.text);\n const size = typeof r.size === 'string' && SIZES.includes(r.size) ? (r.size as Size) : 'm';\n return at && text ? { kind: 'text', id: id(r.id), text, at, size, tone: tone(r.tone) } : null;\n }\n case 'ink': {\n const ink = r.ink as InkKind;\n if (!(INK_KINDS as readonly string[]).includes(ink)) return null;\n const base = { kind: 'ink' as const, id: id(r.id), ink, tone: tone(r.tone) };\n if (POINT_INKS.includes(ink)) {\n const pts = Array.isArray(r.pts) ? r.pts.slice(0, LIMITS.freePoints).map(point).filter((p): p is Point => !!p) : [];\n if (ink === 'corner' || ink === 'arc') return pts.length === 3 ? { ...base, pts } : null;\n if (pts.length < 2) return null;\n return ink === 'poly' && r.closed === true ? { ...base, pts, closed: true } : { ...base, pts };\n }\n if (ink === 'dot') {\n const at = point(r.at);\n return at ? { ...base, at } : null;\n }\n if (ink === 'line' || ink === 'arrow') {\n const at = point(r.at);\n const to = point(r.to);\n return at && to ? { ...base, at, to } : null;\n }\n const at = box(r.at);\n return at ? { ...base, at } : null;\n }\n case 'rows': {\n if (!Array.isArray(r.rows) || !Array.isArray(r.at) || r.at.length < 2) return null;\n const rows = r.rows\n .slice(0, LIMITS.tableRows)\n .filter((row): row is unknown[] => Array.isArray(row) && row.length > 0)\n .map((row) => row.slice(0, LIMITS.tableCols).map((cell) => flat(String(cell ?? ''), LIMITS.cell)));\n const at = point(r.at.slice(0, 2));\n if (!rows.length || !at) return null;\n const width = (num(r.at[2]) ?? 40) * wide;\n return { kind: 'table', id: id(r.id), rows, at: [at[0], at[1], Math.min(Math.max(5, width), BOARD_W - at[0])], tone: tone(r.tone) };\n }\n case 'mark': {\n const mark = id(r.mark);\n return mark ? { kind: 'mark', mark } : null;\n }\n case 'erase': {\n const erase = id(r.erase);\n return erase ? { kind: 'erase', erase } : null;\n }\n case 'point': {\n const target = id(r.point);\n const as = typeof r.as === 'string' && (POINT_MARKS as readonly string[]).includes(r.as) ? (r.as as PointMark) : 'circle';\n return target ? { kind: 'point', point: target, as } : null;\n }\n default:\n return null;\n }\n}\n\nfunction artInk(raw: unknown): { icon: string } | ArtInk | null {\n if (!raw || typeof raw !== 'object') return null;\n const r = raw as Record<string, unknown>;\n if (typeof r.icon === 'string') return /^[a-z]{1,20}$/.test(r.icon) ? { icon: r.icon } : null;\n if (!Array.isArray(r.contours)) return null;\n const contours = r.contours\n .slice(0, LIMITS.artContours)\n .filter((d): d is string => typeof d === 'string' && d.length <= LIMITS.contourChars && PATH_DATA.test(d));\n const viewBox = typeof r.view_box === 'string' && /^[\\d.\\s-]+$/.test(r.view_box) ? r.view_box : '0 0 100 100';\n const transform = typeof r.transform === 'string' && /^[a-z()\\d.,\\s-]*$/i.test(r.transform) ? r.transform : '';\n return contours.length ? { view_box: viewBox, transform, contours } : null;\n}\n\n/**\n * A scene the board may draw, from anything: the server's reply or a host's\n * own object. Fixes what it can (clamps, cuts, drops a bad item) and throws\n * SceneError when nothing drawable is left.\n */\nexport function validateScene(raw: unknown): BoardScene {\n if (!raw || typeof raw !== 'object') throw new SceneError('A scene is an object.');\n const r = raw as Record<string, unknown>;\n if (!Array.isArray(r.steps) || r.steps.length === 0) throw new SceneError('A scene needs steps.');\n if (r.steps.length > LIMITS.steps) throw new SceneError(`A scene has at most ${LIMITS.steps} steps.`);\n wide = r.v === 3 ? 1 : BOARD_W / 100;\n\n let total = 0;\n const steps: BoardStep[] = [];\n let onBoard = new Set<string>();\n for (const rawStep of r.steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const s = rawStep as Record<string, unknown>;\n const clear = s.clear === true;\n if (clear) onBoard = new Set();\n const draw: BoardItem[] = [];\n const items = Array.isArray(s.draw) ? s.draw.slice(0, LIMITS.itemsPerStep) : [];\n for (const rawItem of items) {\n if (total >= LIMITS.items) break;\n const it = item(rawItem);\n if (!it) continue;\n // A highlight or an erase names something already on the board.\n if (it.kind === 'mark' && !onBoard.has(it.mark)) continue;\n if (it.kind === 'erase') {\n if (!onBoard.has(it.erase)) continue;\n onBoard.delete(it.erase);\n }\n if ('id' in it && it.id) onBoard.add(it.id);\n draw.push(it);\n total += 1;\n }\n const say = flat(s.say, LIMITS.say);\n if (!say && !draw.length) continue;\n steps.push({ say, clear, draw });\n }\n if (!steps.length) throw new SceneError('Nothing in this scene can be drawn.');\n\n const art: BoardScene['art'] = {};\n if (r.art && typeof r.art === 'object') {\n for (const [name, value] of Object.entries(r.art as Record<string, unknown>)) {\n const ink = artInk(value);\n if (ink) art[name.slice(0, LIMITS.art)] = ink;\n }\n }\n return {\n v: 3,\n title: flat(r.title, LIMITS.title) || 'Explanation',\n sample: r.sample === true,\n steps,\n art,\n };\n}\n","// ============================================================\n// @guideai/react-native — whiteboard store\n// ============================================================\n//\n// One board for the whole app, open or not. \"Explain on whiteboard\" asks\n// the server for a board once (POST /chat/whiteboard); the board is kept,\n// so playing it again makes no call. Whether the button shows at all is the\n// Blueprint's choice (GET /chat/blocks): the app never offers a whiteboard\n// the owner left out. A host can also play a board it built from its own\n// data (the layouts), which never reaches a model.\n\nimport { SceneError, validateScene } from '@guideai/whiteboard/scene';\nimport type { BoardScene } from '@guideai/whiteboard/scene';\n\nexport const BLOCKS_PATH = '/api/v1/chat/blocks';\nexport const WHITEBOARD_PATH = '/api/v1/chat/whiteboard';\n/** How long the Blueprint's answer is trusted before asking again. */\nconst BLOCKS_TTL_MS = 60_000;\n/** Boards kept for replay without asking again. */\nconst KEEP = 12;\n\nexport interface WhiteboardApi {\n get<T>(path: string, timeoutMs?: number): Promise<T>;\n post<T>(path: string, body?: unknown, timeoutMs?: number): Promise<T>;\n}\n\nexport type WhiteboardStatus = 'closed' | 'loading' | 'playing' | 'error';\n\nexport interface WhiteboardState {\n status: WhiteboardStatus;\n scene: BoardScene | null;\n error: string | null;\n /** What was asked, for the loading title and Try again. */\n question: string;\n answer?: string;\n}\n\nconst CLOSED: WhiteboardState = { status: 'closed', scene: null, error: null, question: '' };\n\n/** The model's reply blocks (```point, ```suggest…) are not what the visitor read. */\nexport function readableAnswer(text: string): string {\n return text.replace(/```[a-z]*[ \\t]*\\n[\\s\\S]*?```/gi, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nexport class WhiteboardStore {\n private state: WhiteboardState = CLOSED;\n private readonly listeners = new Set<() => void>();\n private readonly kept = new Map<string, BoardScene>();\n private blocks: { at: number; on: boolean } | null = null;\n private blocksPending: Promise<boolean> | null = null;\n private request = 0;\n\n constructor(\n private readonly api: () => WhiteboardApi,\n private readonly language: () => string | undefined = () => undefined,\n private readonly clock: () => number = () => Date.now(),\n ) {}\n\n getState = (): WhiteboardState => this.state;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n /** Whether the Blueprint has the whiteboard. False when it cannot be asked. */\n async available(): Promise<boolean> {\n if (this.blocks && this.clock() - this.blocks.at < BLOCKS_TTL_MS) return this.blocks.on;\n this.blocksPending ??= this.api()\n .get<{ blocks?: { whiteboard?: unknown } }>(BLOCKS_PATH, 10_000)\n .then((res) => res?.blocks?.whiteboard === true, () => false)\n .then((on) => {\n this.blocks = { at: this.clock(), on };\n this.blocksPending = null;\n return on;\n });\n return this.blocksPending;\n }\n\n /** Explain *question* (and the answer on screen) on the board. */\n async explain(question: string, answer?: string): Promise<boolean> {\n const q = question.trim().slice(0, 500);\n if (!q) return false;\n const a = answer ? readableAnswer(answer).slice(0, 4000) : undefined;\n const key = `${q}\\u0000${a ?? ''}`;\n const known = this.kept.get(key);\n if (known) {\n this.set({ status: 'playing', scene: known, error: null, question: q, answer: a });\n return true;\n }\n const token = ++this.request;\n this.set({ status: 'loading', scene: null, error: null, question: q, answer: a });\n try {\n const raw = await this.api().post<unknown>(\n WHITEBOARD_PATH,\n { question: q, answer: a || undefined, language: this.language() },\n 60_000,\n );\n if (token !== this.request) return false;\n const scene = validateScene(raw);\n this.keep(key, scene);\n this.set({ status: 'playing', scene, error: null, question: q, answer: a });\n return true;\n } catch (err) {\n if (token !== this.request) return false;\n this.set({\n status: 'error',\n scene: null,\n error: err instanceof SceneError ? 'This board could not be drawn.' : 'The whiteboard is not available right now.',\n question: q,\n answer: a,\n });\n return false;\n }\n }\n\n /** Ask again after an error. */\n retry(): void {\n if (this.state.status === 'error') void this.explain(this.state.question, this.state.answer);\n }\n\n /** Play a board the host built. A board that cannot be drawn throws SceneError. */\n play(scene: unknown): void {\n const valid = validateScene(scene);\n this.request += 1;\n this.set({ status: 'playing', scene: valid, error: null, question: valid.title });\n }\n\n close(): void {\n this.request += 1;\n this.set(CLOSED);\n }\n\n private keep(key: string, scene: BoardScene): void {\n this.kept.delete(key);\n this.kept.set(key, scene);\n while (this.kept.size > KEEP) {\n const oldest = this.kept.keys().next().value;\n if (oldest === undefined) break;\n this.kept.delete(oldest);\n }\n }\n\n private set(next: WhiteboardState): void {\n this.state = next;\n for (const listener of [...this.listeners]) listener();\n }\n}\n","// ============================================================\n// @guideai/react-native — useWhiteboard\n// ============================================================\n//\n// The whiteboard for a host's own chat UI (GuideAIChat uses the same):\n// `available` says whether the Blueprint has the whiteboard, `explain`\n// opens a board for an answer, `play` draws a board the host built from\n// its own data. Mount <GuideAIWhiteboard /> from '@guideai/react-native/ui'\n// once to show it; GuideAIChat already does.\n\nimport { useCallback, useEffect, useState, useSyncExternalStore } from 'react';\nimport { WhiteboardStore } from '../whiteboard/store';\nimport type { WhiteboardState } from '../whiteboard/store';\nimport { GuideAI, requireConfigured } from '../setup';\n\nlet store: WhiteboardStore | null = null;\nlet owner: unknown = null;\n\n/**\n * The app's one board. A new GuideAI.configure() (another key, so another\n * Blueprint and other boards) gets a new one.\n */\nexport function whiteboardStore(): WhiteboardStore {\n const configured = requireConfigured();\n if (!store || owner !== configured) {\n store?.close();\n owner = configured;\n store = new WhiteboardStore(\n () => configured.api,\n () => {\n const language = configured.profile?.language;\n return typeof language === 'string' && language ? language : undefined;\n },\n );\n }\n return store;\n}\n\n/** Stands in before configure(): never asks the server for anything. */\nconst IDLE = new WhiteboardStore(() => {\n throw new Error('Call GuideAI.configure() before using the whiteboard.');\n});\n\nexport interface UseWhiteboardResult {\n /** The Blueprint has \"Explain on a whiteboard\". False until the server says so. */\n available: boolean;\n state: WhiteboardState;\n /** Explain an answer on the board: the question asked, and the answer given. */\n explain(question: string, answer?: string): Promise<boolean>;\n /** Draw a board the host built (see `whiteboardLayouts`). Throws SceneError if it cannot be drawn. */\n play(scene: unknown): void;\n retry(): void;\n close(): void;\n}\n\nexport function useWhiteboard(): UseWhiteboardResult {\n // Before configure() there is no Blueprint to ask; a closed, idle board.\n const board = GuideAI.isConfigured() ? whiteboardStore() : IDLE;\n const state = useSyncExternalStore(board.subscribe, board.getState, board.getState);\n const [available, setAvailable] = useState(false);\n\n useEffect(() => {\n if (board === IDLE) return;\n let live = true;\n void board.available().then((on) => { if (live) setAvailable(on); });\n return () => { live = false; };\n }, [board]);\n\n return {\n available,\n state,\n explain: useCallback((question: string, answer?: string) => board.explain(question, answer), [board]),\n play: useCallback((scene: unknown) => board.play(scene), [board]),\n retry: useCallback(() => board.retry(), [board]),\n close: useCallback(() => board.close(), [board]),\n };\n}\n","// ============================================================\n// @guideai/react-native — chat hook\n// ============================================================\n//\n// One hook serving both UI requirements: it returns the conversation and\n// a send function, so the default <GuideAIChat> is built on exactly this\n// and a host's own UI gets the same thing. There is no privileged path\n// for the built-in UI — if this hook cannot express a UI, the default\n// one could not have been built either.\n// ============================================================\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { describeToolCall, EP, headlessImages } from '@guideai/core';\nimport type { CopilotHarness, HarnessResponse, HeadlessImage, ToolCallResponse } from '@guideai/core';\nimport { useGuideAIRuntime } from './context';\nimport { traceAssistantAnswer, traceUserMessage } from '../debug/full-trace';\nimport { requireConfigured } from '../setup';\nimport { UploadError } from '../api/rn-api-client';\nimport { useWhiteboard } from './useWhiteboard';\n\nexport interface GuideAIMessage {\n id: string;\n role: 'user' | 'assistant';\n content: string;\n /** When the message was sent or the answer started (ms since epoch). */\n createdAt: number;\n /** On an answer: the user message it replied to. */\n question?: string;\n /** True while tokens are still arriving for this message. */\n streaming?: boolean;\n error?: boolean;\n /**\n * Follow-up suggestions to draw as chips. A tap is just\n * `send(suggestion)`. The site's own when the agent offered some,\n * otherwise the `followUps` the app configured.\n */\n suggestions?: string[];\n /**\n * This answer can be explained on the whiteboard (the Blueprint has the\n * block, and the answer is finished). Draw a button that calls\n * `explainOnWhiteboard(id)`.\n */\n whiteboard?: boolean;\n /**\n * Pictures the agent drew. They are also in `content` as Markdown\n * images where they belong; use this list to place them yourself.\n */\n images?: HeadlessImage[];\n /**\n * A change to the user's data waiting for their yes (\"Create the\n * course\"). Draw Approve / Cancel and call `confirm(id)` or `cancel(id)`.\n */\n pendingAction?: { label: string; tool: string };\n}\n\n/** A recording the host made (expo-audio or any recorder) and saved to a file. */\nexport interface GuideAIVoiceRecording {\n /** `file://…` URI of the finished recording. */\n uri: string;\n /** e.g. 'audio/m4a'. Omitted: guessed from the file extension. */\n mimeType?: string;\n /** BCP-47 language the user spoke, e.g. 'en-NG'. Defaults to 'en-US'. */\n languageCode?: string;\n}\n\nexport interface GuideAIVoiceResult {\n /** What was heard, already sent as the next message; null when nothing was. */\n text: string | null;\n /** Why nothing was sent, in words to show the user. */\n error?: string;\n}\n\n/**\n * Mobile runs in assistant mode only.\n *\n * Guidance mode drives on-screen walkthroughs — highlight this, scroll to\n * that — which the browser SDK performs against live DOM nodes. On a\n * device there is no DOM to drive, no hover, and no highlight overlay\n * (`guideai_highlight_element` is not among the tools this package\n * advertises), so a guidance turn would come back with steps nothing can\n * execute.\n *\n * The backend picks a different prompt template per mode\n * (COPILOT_ACTION_PROMPT_GUIDANCE vs _ASSISTANT), so this is not a\n * cosmetic label — sending 'guidance' asks the model to plan the wrong\n * kind of answer. Narrowed to one value rather than defaulted, so a\n * guidance turn cannot be requested by mistake.\n */\nexport type GuideAIChatMode = 'assistant';\n\n/**\n * Everything a custom chat UI needs, and nothing about how to draw it.\n *\n * A host owns two things — their design, and the text the user typed.\n * This hook owns the rest: the conversation, the streaming, the tool\n * calls, the transport. That split is what lets the agent be upgraded\n * underneath a host's UI without them changing a line.\n */\nexport interface UseGuideAIResult {\n /**\n * The conversation so far, oldest first, ready to draw. An answer that\n * has not produced any text yet is left out; `typing` covers it.\n */\n messages: GuideAIMessage[];\n\n /** An answer is on its way but has no text yet: draw a typing indicator. */\n typing: boolean;\n\n /**\n * Chips to draw under the latest answer: its suggestions, or the app's\n * `followUps`. Empty while a turn runs and before the first answer.\n */\n followUps: string[];\n\n /** The Blueprint has the whiteboard block. */\n whiteboardAvailable: boolean;\n\n /**\n * Explain an answer on the whiteboard, with the question it answered.\n * Mount `<GuideAIWhiteboard />` once to show the board.\n */\n explainOnWhiteboard(messageId: string): Promise<boolean>;\n\n /**\n * The current input text, and its setter.\n *\n * Managed here so a host binds it straight to their TextInput rather\n * than reimplementing \"clear on send, block while busy\" — the two\n * rules every chat UI needs and each one gets subtly wrong.\n */\n input: string;\n setInput(text: string): void;\n\n /**\n * Send `input`, or an explicit string.\n *\n * Ignores empty text and calls made while a turn is in flight, so a\n * host does not have to guard their send button.\n */\n send(question?: string): Promise<void>;\n\n /** True from send() until the turn settles. Drives a disabled state. */\n busy: boolean;\n\n /** Whether `send()` would do anything right now. */\n canSend: boolean;\n\n /** Status text from the agent loop (\"Thinking\", \"Reading cart\"). */\n status: string | null;\n\n /** Re-send the last user message. Useful after a failed turn. */\n retry(): Promise<void>;\n\n /** Drop the conversation and start over. */\n clear(): void;\n\n /** Approve the message's `pendingAction`; the agent carries it out. */\n confirm(messageId: string): Promise<void>;\n\n /** Decline the message's `pendingAction`. Nothing is changed. */\n cancel(messageId: string): void;\n\n /**\n * Push-to-talk: transcribe a recording and send it as the next message.\n * Recording is the host's (no native module here); this uploads it.\n */\n sendVoice(recording: GuideAIVoiceRecording): Promise<GuideAIVoiceResult>;\n\n /** True while a recording is being transcribed. */\n transcribing: boolean;\n}\n\nexport interface UseGuideAIOptions {\n /**\n * Log the full conversation and every request. Defaults to whatever\n * GuideAI.configure({ debug }) was given, so a host sets it once.\n */\n trace?: boolean;\n\n /**\n * The harness, for tests and for a host running two assistants at\n * once. Omitted — the normal case — it comes from GuideAI.configure(),\n * so a host never holds a reference to it.\n */\n harness?: CopilotHarness;\n\n /**\n * Follow-ups offered under an answer that came without suggestions of\n * its own (\"Explain it differently\", \"Give me an example\"). Defaults to\n * GuideAI.configure({ followUps }).\n */\n followUps?: string[];\n}\n\nconst AUDIO_TYPES: Record<string, string> = {\n m4a: 'audio/m4a', mp4: 'audio/mp4', aac: 'audio/aac', caf: 'audio/x-caf',\n wav: 'audio/wav', mp3: 'audio/mpeg', webm: 'audio/webm', ogg: 'audio/ogg', '3gp': 'audio/3gpp',\n};\n\nfunction audioType(uri: string): { type: string; name: string } {\n const extension = (uri.split('?')[0].split('.').pop() ?? '').toLowerCase();\n const type = AUDIO_TYPES[extension] ?? 'audio/m4a';\n return { type, name: `voice.${AUDIO_TYPES[extension] ? extension : 'm4a'}` };\n}\n\n/** The fields a finished turn sets on its reply. */\nfunction replyFields(\n result: HarnessResponse,\n streamed: string,\n): Pick<GuideAIMessage, 'content' | 'images' | 'suggestions' | 'pendingAction'> {\n const { text, images } = headlessImages(answerText(result, streamed));\n const call = result.confirmationNeeded ? result.pendingToolCall : undefined;\n return {\n content: text,\n images: images.length ? images : undefined,\n suggestions: result.quickReplies?.length ? result.quickReplies.slice(0, 4) : undefined,\n pendingAction: call ? { label: call.label?.trim() || describeToolCall(call), tool: call.tool } : undefined,\n };\n}\n\nlet nextId = 0;\nconst nextMessageId = () => `m${(nextId += 1)}`;\n\n/** The user message an answer at `index` replied to. */\nfunction questionBefore(entries: Array<{ role: string; content: string }>, index: number): string | undefined {\n for (let i = index - 1; i >= 0; i -= 1) if (entries[i].role === 'user') return entries[i].content;\n return undefined;\n}\n\n/**\n * What to show for a reply, once the machine payload is stripped out.\n *\n * A guide answer is a ```guide fenced block of step JSON and often nothing\n * else, so sanitizing it can legitimately leave an empty string — and an\n * empty assistant bubble reads as a bug. The steps themselves are already\n * parsed into `guideSteps`/`navigation`, so say what is happening in the\n * words the model put in the steps rather than showing the JSON that\n * produced them.\n */\nfunction answerText(\n result: { answer?: string; guideSteps?: unknown[]; guideTitle?: string },\n fallback: string,\n): string {\n const answer = (result.answer ?? '').trim();\n if (answer) return answer;\n\n const first = result.guideSteps?.[0] as Record<string, unknown> | undefined;\n const body = typeof first?.body === 'string' ? first.body.trim() : '';\n if (body) return body;\n\n const title = typeof first?.title === 'string' ? first.title.trim() : '';\n if (title) return title;\n\n return fallback || 'Done.';\n}\n\n/**\n * What the visitor is told when a turn fails.\n *\n * Deliberately ONE message, with no detail about the cause.\n *\n * An earlier version classified the failure — timeout, network, 401, 5xx —\n * and said something different for each. That is still leaking the\n * diagnosis: a visitor cannot act on \"the request timed out\", and being\n * told which of our services broke is not their problem. Worse, the class\n * names read as blame (\"check your connection\") for what is usually our\n * own misconfiguration.\n *\n * The real diagnosis is logged in full, immediately before this is called,\n * so nothing is lost for whoever is debugging.\n */\nconst FAILURE_MESSAGE =\n \"I'm sorry, I can't complete your request right now. \"\n + 'Would you like to talk to a human?';\n\nexport function useGuideAI(options: UseGuideAIOptions = {}): UseGuideAIResult {\n const runtime = useGuideAIRuntime();\n const configured = requireConfigured();\n const harness = options.harness ?? configured.harness;\n const trace = options.trace ?? configured.debug;\n const defaultFollowUps = options.followUps ?? configured.followUps;\n // Mobile is assistant-mode only; see GuideAIChatMode.\n const mode: GuideAIChatMode = 'assistant';\n const board = useWhiteboard();\n\n const [messages, setMessages] = useState<GuideAIMessage[]>([]);\n const [input, setInput] = useState('');\n const [busy, setBusy] = useState(false);\n const [status, setStatus] = useState<string | null>(null);\n const [transcribing, setTranscribing] = useState(false);\n // Kept for retry(), which must survive the message list being cleared.\n const lastQuestion = useRef<string | null>(null);\n // The tool call behind each message's pendingAction, with the question\n // that led to it — the harness needs both to carry it out.\n const pending = useRef(new Map<string, { call: ToolCallResponse; question: string }>());\n\n // Guards against setting state after unmount — a streamed turn can\n // outlive the screen that started it.\n const mounted = useRef(true);\n useEffect(() => () => { mounted.current = false; }, []);\n\n /**\n * Rehydrate the conversation the harness already persisted.\n *\n * The harness has written every turn to its store all along — that is\n * what `store` in GuideAI.configure() is for, and what lets the model\n * answer follow-ups. Nothing ever read it back into the view, so closing\n * the sheet unmounted this hook and the transcript appeared to be gone\n * while the model still remembered it: the visitor sees an empty panel\n * and the assistant answers as though mid-conversation.\n *\n * Runs once on mount, and only when the view has nothing of its own, so\n * a remount mid-conversation cannot duplicate what is already on screen.\n */\n useEffect(() => {\n // Guarded rather than called directly: `harness` is a documented\n // option, so a host (and every test fake) may pass an object that\n // implements only the turn-taking surface. A missing history API means\n // \"nothing to restore\", never a crash on mount.\n if (typeof harness.hasHistory !== 'function'\n || typeof harness.getConversationHistory !== 'function') return;\n if (!harness.hasHistory()) return;\n\n setMessages((previous) => {\n if (previous.length > 0) return previous;\n return harness.getConversationHistory()\n .filter((entry) => typeof entry.content === 'string' && entry.content.trim())\n .map((entry, index, all) => ({\n id: entry.id ?? `h${index}`,\n role: entry.role,\n content: entry.content,\n createdAt: typeof entry.timestamp === 'number' ? entry.timestamp : Date.now(),\n question: entry.role === 'assistant' ? questionBefore(all, index) : undefined,\n }));\n });\n }, [harness]);\n\n /**\n * Fetch the site's active tool set once, before the first turn.\n *\n * REQUIRED, not an optimisation. The harness builds its ToolExecutor\n * inside initialize() — it cannot be injected, because the base URL and\n * auth config only exist once the server says which tool set is active.\n * Without this, `toolExecutor` stays null, `canExecuteTool()` returns\n * false for every customer API tool, and the turn dies with\n * \"Tool execution is unavailable in this browser context.\"\n *\n * The web SDK does this in chat-manager.ts; mobile needs its own call.\n */\n const initialized = useRef<Promise<boolean> | null>(null);\n const ensureInitialized = useCallback(() => {\n // Cached as a promise so concurrent sends share one request, and a\n // failure does not permanently disable tools — initialize() swallows\n // its own errors and simply leaves customer tools unavailable.\n if (!initialized.current) initialized.current = harness.initialize();\n return initialized.current;\n }, [harness]);\n\n /**\n * Run one agent turn into the assistant message `replyId`: stream its\n * text, then settle it with the answer, pictures, suggestions and any\n * action awaiting approval. Shared by a typed message and an approval.\n */\n const runTurn = useCallback(async (\n replyId: string,\n question: string,\n work: (\n onStatus: (status: string) => void,\n onDelta: (delta: string) => void,\n ) => Promise<HarnessResponse>,\n ) => {\n setBusy(true);\n setStatus(null);\n let streamed = '';\n const appendDelta = (delta: string) => {\n streamed += delta;\n if (!mounted.current) return;\n setMessages((prev) => prev.map((message) => (\n message.id === replyId\n ? { ...message, content: message.content + delta }\n : message\n )));\n };\n\n try {\n // The user's own token for the site's API, read fresh each turn: it\n // may have been refreshed or signed out since the last one.\n await runtime.auth?.refresh();\n const result = await work((next) => { if (mounted.current) setStatus(next); }, appendDelta);\n\n if (trace) traceAssistantAnswer(result.answer ?? '(empty)', result.mode);\n if (result.confirmationNeeded && result.pendingToolCall) {\n pending.current.set(replyId, { call: result.pendingToolCall, question });\n }\n\n if (!mounted.current) return;\n setMessages((prev) => prev.map((message) => (\n message.id === replyId\n // Streamed deltas and the final answer are the same text; trust\n // the final one, which is also what a non-streaming transport\n // returns. Keeping the streamed text when it is longer would\n // duplicate on a transport that replays.\n ? { ...message, ...replyFields(result, streamed), streaming: false }\n : message\n )));\n } catch (error) {\n // Always log the real cause. A non-Error throw would otherwise be\n // rendered as a bare \"Something went wrong\" with the actual\n // diagnosis discarded — which is exactly the case that is hardest\n // to debug from a phone.\n console.log('[GuideAI] ✗ turn failed:', error);\n if (error instanceof Error && error.stack) {\n console.log('[GuideAI] stack:', error.stack);\n }\n\n if (!mounted.current) return;\n setMessages((prev) => prev.map((message) => (\n message.id === replyId\n ? {\n ...message,\n content: FAILURE_MESSAGE,\n streaming: false,\n error: true,\n }\n : message\n )));\n } finally {\n if (mounted.current) {\n setBusy(false);\n setStatus(null);\n }\n }\n }, [runtime, trace]);\n\n const send = useCallback(async (question?: string) => {\n const text = (question ?? input).trim();\n if (!text || busy) return;\n\n lastQuestion.current = text;\n // Clear the box immediately: leaving the text in place while a turn\n // runs invites a double-send.\n if (question === undefined) setInput('');\n\n if (trace) traceUserMessage(text);\n\n const replyId = nextMessageId();\n const now = Date.now();\n setMessages((prev) => [\n ...prev,\n { id: nextMessageId(), role: 'user', content: text, createdAt: now },\n { id: replyId, role: 'assistant', content: '', streaming: true, createdAt: now, question: text },\n ]);\n\n await runTurn(replyId, text, async (onStatus, onDelta) => {\n // Must complete before the first turn, or customer API tools are\n // unavailable for it.\n await ensureInitialized();\n const screen = runtime.getActiveScreen();\n const { profile, visitorId } = requireConfigured();\n return harness.processMessage(\n text,\n screen?.path,\n runtime.captureSnapshot(),\n mode,\n onStatus,\n onDelta,\n undefined,\n undefined,\n // Who is asking, as the app knows them; the agent pitches to it.\n profile ? { profile } : undefined,\n visitorId ?? undefined,\n );\n });\n }, [busy, input, harness, mode, runtime, ensureInitialized, trace, runTurn]);\n\n const retry = useCallback(async () => {\n if (!lastQuestion.current || busy) return;\n // Drop the failed exchange so the retry does not stack a second\n // copy of the question under the first.\n setMessages((prev) => prev.slice(0, -2));\n await send(lastQuestion.current);\n }, [busy, send]);\n\n const clear = useCallback(() => {\n setMessages([]);\n lastQuestion.current = null;\n pending.current.clear();\n }, []);\n\n const settleAction = useCallback((messageId: string) => {\n const action = pending.current.get(messageId);\n pending.current.delete(messageId);\n setMessages((prev) => prev.map((message) => (\n message.id === messageId ? { ...message, pendingAction: undefined } : message\n )));\n return action;\n }, []);\n\n const confirm = useCallback(async (messageId: string) => {\n if (busy) return;\n const action = settleAction(messageId);\n if (!action) return;\n const replyId = nextMessageId();\n setMessages((prev) => [...prev, {\n id: replyId, role: 'assistant', content: '', streaming: true, createdAt: Date.now(), question: action.question,\n }]);\n await runTurn(replyId, action.question, async (onStatus, onDelta) => {\n await ensureInitialized();\n return harness.executeToolCall(action.call, action.question, onStatus, onDelta);\n });\n }, [busy, settleAction, runTurn, ensureInitialized, harness]);\n\n const cancel = useCallback((messageId: string) => {\n if (!settleAction(messageId)) return;\n setMessages((prev) => [...prev, {\n id: nextMessageId(), role: 'assistant', content: \"Okay, I haven't changed anything.\", createdAt: Date.now(),\n }]);\n }, [settleAction]);\n\n const sendVoice = useCallback(async (recording: GuideAIVoiceRecording): Promise<GuideAIVoiceResult> => {\n if (busy || transcribing) return { text: null, error: 'Wait for the current reply to finish.' };\n const guessed = audioType(recording.uri);\n setTranscribing(true);\n try {\n const result = await requireConfigured().api.postFile<{ text?: string }>(\n EP.batchVoiceTranscribe(),\n 'audio',\n { uri: recording.uri, name: guessed.name, type: recording.mimeType || guessed.type },\n { language_code: recording.languageCode || 'en-US' },\n 45_000,\n );\n const heard = result?.text?.trim() || '';\n if (!heard) return { text: null, error: \"I didn't catch that. Please try again.\" };\n if (mounted.current) setTranscribing(false);\n await send(heard);\n return { text: heard };\n } catch (error) {\n console.log('[GuideAI] ✗ voice transcription failed:', error);\n // 422 is the recording itself (too short, silent): the server's words\n // say what to do. Anything else is ours, and the user is told plainly.\n const message = error instanceof UploadError && error.status === 422\n ? error.message\n : \"I couldn't process that recording. Please try again or type your message.\";\n return { text: null, error: message };\n } finally {\n if (mounted.current) setTranscribing(false);\n }\n }, [busy, transcribing, send]);\n\n // What the host draws: no empty bubble for an answer still on its way\n // (`typing` covers it), the app's follow-ups on an answer the agent gave\n // none, and the whiteboard on finished answers when the Blueprint has it.\n const shown = useMemo(() => messages\n .filter((message) => message.content || !message.streaming)\n .map((message): GuideAIMessage => {\n if (message.role !== 'assistant' || message.streaming || message.error || !message.content) return message;\n const suggestions = message.suggestions ?? (defaultFollowUps?.length ? defaultFollowUps : undefined);\n return { ...message, suggestions, whiteboard: board.available || undefined };\n }), [messages, defaultFollowUps, board.available]);\n\n const last = shown[shown.length - 1];\n const followUps = !busy && last?.role === 'assistant' && !last.pendingAction ? last.suggestions ?? [] : [];\n const typing = busy && messages.some((message) => message.streaming && !message.content);\n\n const explainOnWhiteboard = useCallback(async (messageId: string) => {\n const answer = messages.find((message) => message.id === messageId);\n if (!answer || answer.role !== 'assistant' || !answer.content) return false;\n return board.explain(answer.question || answer.content.slice(0, 200), answer.content);\n }, [messages, board]);\n\n return {\n messages: shown,\n typing,\n followUps,\n whiteboardAvailable: board.available,\n explainOnWhiteboard,\n input,\n setInput,\n send,\n busy,\n canSend: Boolean(input.trim()) && !busy,\n status,\n retry,\n clear,\n confirm,\n cancel,\n sendVoice,\n transcribing,\n };\n}\n","import { useCallback, useEffect, useState } from 'react';\nimport { EP, type OnboardingState } from '@guideai/core';\nimport { requireConfigured } from '../setup';\nimport { useGuideAIRuntime } from './context';\n\n/** Reads the same durable checklist as the browser adapter. */\nexport function useOnboarding(): {\n checklist: OnboardingState | null;\n loading: boolean;\n refresh: () => Promise<void>;\n dismiss: () => Promise<void>;\n} {\n const runtime = useGuideAIRuntime();\n const [checklist, setChecklist] = useState<OnboardingState | null>(null);\n const [loading, setLoading] = useState(true);\n\n const refresh = useCallback(async () => {\n const { api, visitorId } = requireConfigured();\n if (!visitorId) { setChecklist(null); setLoading(false); return; }\n try {\n const current = await api.get<OnboardingState | null>(EP.onboardingCurrent(visitorId));\n const screen = runtime.getActiveScreen()?.path;\n const updated = current && !current.completed && !current.dismissed && screen\n ? await api.post<OnboardingState | null>(EP.onboardingObserve(), { user_id: visitorId, screen })\n : current;\n setChecklist(updated);\n } catch {\n // The host application keeps working if the checklist service is unavailable.\n } finally { setLoading(false); }\n }, [runtime]);\n\n const dismiss = useCallback(async () => {\n const { api, visitorId } = requireConfigured();\n if (!visitorId) return;\n const updated = await api.post<OnboardingState | null>(EP.onboardingDismiss(), { user_id: visitorId });\n setChecklist(updated);\n }, []);\n\n useEffect(() => {\n void refresh();\n const timer = setInterval(() => void refresh(), 5000);\n return () => clearInterval(timer);\n }, [refresh]);\n\n return { checklist, loading, refresh, dismiss };\n}\n"],"names":["at","_a","requireConfigured","GuideAI","useSyncExternalStore","useState","useEffect","useCallback","describeToolCall","useGuideAIRuntime","useRef","traceAssistantAnswer","_b","EP","UploadError","useMemo"],"mappings":";;;AAoUA,MAAM,cAAc;AACpB,MAAM,cAAc;AAMb,SAAS,eAAe,MAAyD;AACtF,QAAM,SAA0B,CAAA;AAChC,QAAM,OAAO,QAAQ,IAAI,QAAQ,aAAa,CAAC,QAAQ,QAAgB;AACrE,QAAI;AACJ,QAAI;AACF,aAAO,KAAK,MAAM,IAAI,KAAA,CAAM;AAAA,IAC9B,QAAQ;AACN,aAAO;AAAA,IACT;AACA,QAAI,OAAO,KAAK,QAAQ,YAAY,CAAC,YAAY,KAAK,KAAK,GAAG,EAAG,QAAO;AACxE,UAAM,QAAuB;AAAA,MAC3B,KAAK,KAAK;AAAA,MACV,KAAK,OAAO,KAAK,QAAQ,YAAY,YAAY,KAAK,KAAK,GAAG,IAAI,KAAK,MAAM;AAAA,MAC7E,KAAK,OAAO,KAAK,QAAQ,WAAW,KAAK,IAAI,MAAM,GAAG,GAAG,IAAI;AAAA,MAC7D,OAAO,KAAK,MAAM,OAAO,KAAK,KAAK,CAAC,KAAK;AAAA,MACzC,QAAQ,KAAK,MAAM,OAAO,KAAK,MAAM,CAAC,KAAK;AAAA,IAAA;AAE7C,WAAO,KAAK,KAAK;AACjB,WAAO,KAAK,MAAM,IAAI,QAAQ,UAAU,EAAE,CAAC,KAAK,MAAM,GAAG;AAAA,EAC3D,CAAC;AACD,SAAO,EAAE,MAAM,KAAK,OAAA;AACtB;AC5UO,MAAM,SAAS;AAAA,EACpB,OAAO;AAAA,EACP,cAAc;AAAA,EACd,OAAO;AAAA,EACP,KAAK;AAAA,EACL,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AAAA,EAEP,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,WAAW;AAAA,EACX,MAAM;AAAA,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Module" });
3
+ const React = require("react");
4
+ const expoAudio = require("expo-audio");
5
+ const setup = require("./setup-Bl0ZLz8B.cjs");
6
+ const MIC_REFUSED = "Allow microphone access in Settings to talk to the assistant.";
7
+ const START_FAILED = "The microphone didn't start. Please try again.";
8
+ function profileLanguage() {
9
+ var _a;
10
+ const language = (_a = setup.requireConfigured().profile) == null ? void 0 : _a.language;
11
+ return typeof language === "string" && language.trim() ? language.trim() : void 0;
12
+ }
13
+ function useVoiceInput(chat, options = {}) {
14
+ var _a;
15
+ const recorder = expoAudio.useAudioRecorder(expoAudio.RecordingPresets.HIGH_QUALITY);
16
+ const [recording, setRecording] = React.useState(false);
17
+ const [error, setError] = React.useState(null);
18
+ const limit = React.useRef(null);
19
+ const mounted = React.useRef(true);
20
+ const stopRef = React.useRef(async () => null);
21
+ const maxSeconds = (_a = options.maxSeconds) != null ? _a : 60;
22
+ React.useEffect(() => () => {
23
+ mounted.current = false;
24
+ if (limit.current) clearTimeout(limit.current);
25
+ }, []);
26
+ const finish = React.useCallback(async () => {
27
+ var _a2;
28
+ if (limit.current) clearTimeout(limit.current);
29
+ limit.current = null;
30
+ if (!recorder.isRecording) {
31
+ if (mounted.current) setRecording(false);
32
+ return null;
33
+ }
34
+ await recorder.stop();
35
+ if (mounted.current) setRecording(false);
36
+ await expoAudio.setAudioModeAsync({ allowsRecording: false }).catch(() => void 0);
37
+ return (_a2 = recorder.uri) != null ? _a2 : null;
38
+ }, [recorder]);
39
+ const start = React.useCallback(async () => {
40
+ if (recording || chat.busy || chat.transcribing) return false;
41
+ setError(null);
42
+ const permission = await expoAudio.requestRecordingPermissionsAsync().catch(() => null);
43
+ if (!(permission == null ? void 0 : permission.granted)) {
44
+ if (mounted.current) setError(MIC_REFUSED);
45
+ return false;
46
+ }
47
+ try {
48
+ await expoAudio.setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });
49
+ await recorder.prepareToRecordAsync();
50
+ recorder.record();
51
+ } catch (cause) {
52
+ console.log("[GuideAI] ✗ microphone did not start:", cause);
53
+ if (mounted.current) setError(START_FAILED);
54
+ return false;
55
+ }
56
+ if (mounted.current) setRecording(true);
57
+ limit.current = setTimeout(() => {
58
+ void stopRef.current();
59
+ }, maxSeconds * 1e3);
60
+ return true;
61
+ }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds]);
62
+ const stop = React.useCallback(async () => {
63
+ var _a2, _b;
64
+ let uri = null;
65
+ try {
66
+ uri = await finish();
67
+ } catch (cause) {
68
+ console.log("[GuideAI] ✗ recording did not stop:", cause);
69
+ }
70
+ if (!uri) return null;
71
+ const result = await chat.sendVoice({
72
+ uri,
73
+ languageCode: (_a2 = options.languageCode) != null ? _a2 : profileLanguage()
74
+ });
75
+ if (mounted.current) setError((_b = result.error) != null ? _b : null);
76
+ return result.text;
77
+ }, [finish, chat, options.languageCode]);
78
+ stopRef.current = stop;
79
+ const cancel = React.useCallback(async () => {
80
+ await finish().catch(() => null);
81
+ }, [finish]);
82
+ const toggle = React.useCallback(async () => {
83
+ if (recording) await stop();
84
+ else await start();
85
+ }, [recording, start, stop]);
86
+ return { recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle };
87
+ }
88
+ exports.useVoiceInput = useVoiceInput;
89
+ //# sourceMappingURL=voice.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice.cjs","sources":["../src/voice/useVoiceInput.ts"],"sourcesContent":["// ============================================================\n// @guideai/react-native/voice — push-to-talk\n// ============================================================\n//\n// The whole mic for a host's chat: permission, recording, transcription\n// and sending the words as the next message. The host draws a button and\n// reads `recording` / `transcribing` / `error`; nothing else.\n//\n// Its own entry point because it needs expo-audio (an optional peer): an\n// app that never imports '@guideai/react-native/voice' never needs it.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n RecordingPresets,\n requestRecordingPermissionsAsync,\n setAudioModeAsync,\n useAudioRecorder,\n} from 'expo-audio';\nimport type { UseGuideAIResult } from '../react/useGuideAI';\nimport { requireConfigured } from '../setup';\n\nexport interface UseVoiceInputOptions {\n /** BCP-47 language spoken, e.g. 'en-NG'. Defaults to the user profile's language. */\n languageCode?: string;\n /** A recording stops and is sent after this long. Default 60 s. */\n maxSeconds?: number;\n}\n\nexport interface UseVoiceInputResult {\n /** The mic is on. */\n recording: boolean;\n /** What was said is being turned into text (then sent). */\n transcribing: boolean;\n /** Why the last attempt failed, in words to show the user; null when it didn't. */\n error: string | null;\n /** Start recording. False when the microphone was refused or is busy. */\n start(): Promise<boolean>;\n /** Stop, transcribe and send. Resolves with what was heard, or null. */\n stop(): Promise<string | null>;\n /** Stop and throw the recording away. */\n cancel(): Promise<void>;\n /** Start when idle, stop and send when recording: one mic button. */\n toggle(): Promise<void>;\n}\n\nconst MIC_REFUSED = 'Allow microphone access in Settings to talk to the assistant.';\nconst START_FAILED = \"The microphone didn't start. Please try again.\";\n\n/** The user profile's language as a recognizer code ('fr' → 'fr'), when set. */\nfunction profileLanguage(): string | undefined {\n const language = requireConfigured().profile?.language;\n return typeof language === 'string' && language.trim() ? language.trim() : undefined;\n}\n\n/**\n * Push-to-talk for a chat from `useGuideAI()`:\n *\n * const chat = useGuideAI();\n * const mic = useVoiceInput(chat);\n * <Button onPress={mic.toggle} title={mic.recording ? 'Send' : 'Talk'} />\n */\nexport function useVoiceInput(\n chat: Pick<UseGuideAIResult, 'sendVoice' | 'transcribing' | 'busy'>,\n options: UseVoiceInputOptions = {},\n): UseVoiceInputResult {\n const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);\n const [recording, setRecording] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const limit = useRef<ReturnType<typeof setTimeout> | null>(null);\n const mounted = useRef(true);\n const stopRef = useRef<() => Promise<string | null>>(async () => null);\n const maxSeconds = options.maxSeconds ?? 60;\n\n useEffect(() => () => {\n mounted.current = false;\n if (limit.current) clearTimeout(limit.current);\n }, []);\n\n const finish = useCallback(async (): Promise<string | null> => {\n if (limit.current) clearTimeout(limit.current);\n limit.current = null;\n if (!recorder.isRecording) {\n if (mounted.current) setRecording(false);\n return null;\n }\n await recorder.stop();\n if (mounted.current) setRecording(false);\n // Back to playback, or iOS keeps replies on the earpiece.\n await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);\n return recorder.uri ?? null;\n }, [recorder]);\n\n const start = useCallback(async () => {\n if (recording || chat.busy || chat.transcribing) return false;\n setError(null);\n const permission = await requestRecordingPermissionsAsync().catch(() => null);\n if (!permission?.granted) {\n if (mounted.current) setError(MIC_REFUSED);\n return false;\n }\n try {\n await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });\n await recorder.prepareToRecordAsync();\n recorder.record();\n } catch (cause) {\n console.log('[GuideAI] ✗ microphone did not start:', cause);\n if (mounted.current) setError(START_FAILED);\n return false;\n }\n if (mounted.current) setRecording(true);\n limit.current = setTimeout(() => { void stopRef.current(); }, maxSeconds * 1000);\n return true;\n }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds]);\n\n const stop = useCallback(async () => {\n let uri: string | null = null;\n try {\n uri = await finish();\n } catch (cause) {\n console.log('[GuideAI] ✗ recording did not stop:', cause);\n }\n if (!uri) return null;\n const result = await chat.sendVoice({\n uri,\n languageCode: options.languageCode ?? profileLanguage(),\n });\n if (mounted.current) setError(result.error ?? null);\n return result.text;\n }, [finish, chat, options.languageCode]);\n stopRef.current = stop;\n\n const cancel = useCallback(async () => {\n await finish().catch(() => null);\n }, [finish]);\n\n const toggle = useCallback(async () => {\n if (recording) await stop();\n else await start();\n }, [recording, start, stop]);\n\n return { recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle };\n}\n"],"names":["requireConfigured","useAudioRecorder","RecordingPresets","useState","useRef","useEffect","useCallback","setAudioModeAsync","_a","requestRecordingPermissionsAsync"],"mappings":";;;;;AA6CA,MAAM,cAAc;AACpB,MAAM,eAAe;AAGrB,SAAS,kBAAsC;;AAC7C,QAAM,YAAWA,WAAAA,oBAAoB,YAApBA,mBAA6B;AAC9C,SAAO,OAAO,aAAa,YAAY,SAAS,SAAS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er: a PNG to show, and the SVG it was drawn as. */
2
+ interface HeadlessImage {
3
+ url: string;
4
+ svg: string | null;
5
+ alt: string;
6
+ width: number;
7
+ height: number;
8
+ }
9
+
10
+ interface GuideAIMessage {
11
+ id: string;
12
+ role: 'user' | 'assistant';
13
+ content: string;
14
+ /** When the message was sent or the answer started (ms since epoch). */
15
+ createdAt: number;
16
+ /** On an answer: the user message it replied to. */
17
+ question?: string;
18
+ /** True while tokens are still arriving for this message. */
19
+ streaming?: boolean;
20
+ error?: boolean;
21
+ /**
22
+ * Follow-up suggestions to draw as chips. A tap is just
23
+ * `send(suggestion)`. The site's own when the agent offered some,
24
+ * otherwise the `followUps` the app configured.
25
+ */
26
+ suggestions?: string[];
27
+ /**
28
+ * This answer can be explained on the whiteboard (the Blueprint has the
29
+ * block, and the answer is finished). Draw a button that calls
30
+ * `explainOnWhiteboard(id)`.
31
+ */
32
+ whiteboard?: boolean;
33
+ /**
34
+ * Pictures the agent drew. They are also in `content` as Markdown
35
+ * images where they belong; use this list to place them yourself.
36
+ */
37
+ images?: HeadlessImage[];
38
+ /**
39
+ * A change to the user's data waiting for their yes ("Create the
40
+ * course"). Draw Approve / Cancel and call `confirm(id)` or `cancel(id)`.
41
+ */
42
+ pendingAction?: {
43
+ label: string;
44
+ tool: string;
45
+ };
46
+ }
47
+ /** A recording the host made (expo-audio or any recorder) and saved to a file. */
48
+ interface GuideAIVoiceRecording {
49
+ /** `file://…` URI of the finished recording. */
50
+ uri: string;
51
+ /** e.g. 'audio/m4a'. Omitted: guessed from the file extension. */
52
+ mimeType?: string;
53
+ /** BCP-47 language the user spoke, e.g. 'en-NG'. Defaults to 'en-US'. */
54
+ languageCode?: string;
55
+ }
56
+ interface GuideAIVoiceResult {
57
+ /** What was heard, already sent as the next message; null when nothing was. */
58
+ text: string | null;
59
+ /** Why nothing was sent, in words to show the user. */
60
+ error?: string;
61
+ }
62
+ /**
63
+ * Everything a custom chat UI needs, and nothing about how to draw it.
64
+ *
65
+ * A host owns two things — their design, and the text the user typed.
66
+ * This hook owns the rest: the conversation, the streaming, the tool
67
+ * calls, the transport. That split is what lets the agent be upgraded
68
+ * underneath a host's UI without them changing a line.
69
+ */
70
+ interface UseGuideAIResult {
71
+ /**
72
+ * The conversation so far, oldest first, ready to draw. An answer that
73
+ * has not produced any text yet is left out; `typing` covers it.
74
+ */
75
+ messages: GuideAIMessage[];
76
+ /** An answer is on its way but has no text yet: draw a typing indicator. */
77
+ typing: boolean;
78
+ /**
79
+ * Chips to draw under the latest answer: its suggestions, or the app's
80
+ * `followUps`. Empty while a turn runs and before the first answer.
81
+ */
82
+ followUps: string[];
83
+ /** The Blueprint has the whiteboard block. */
84
+ whiteboardAvailable: boolean;
85
+ /**
86
+ * Explain an answer on the whiteboard, with the question it answered.
87
+ * Mount `<GuideAIWhiteboard />` once to show the board.
88
+ */
89
+ explainOnWhiteboard(messageId: string): Promise<boolean>;
90
+ /**
91
+ * The current input text, and its setter.
92
+ *
93
+ * Managed here so a host binds it straight to their TextInput rather
94
+ * than reimplementing "clear on send, block while busy" — the two
95
+ * rules every chat UI needs and each one gets subtly wrong.
96
+ */
97
+ input: string;
98
+ setInput(text: string): void;
99
+ /**
100
+ * Send `input`, or an explicit string.
101
+ *
102
+ * Ignores empty text and calls made while a turn is in flight, so a
103
+ * host does not have to guard their send button.
104
+ */
105
+ send(question?: string): Promise<void>;
106
+ /** True from send() until the turn settles. Drives a disabled state. */
107
+ busy: boolean;
108
+ /** Whether `send()` would do anything right now. */
109
+ canSend: boolean;
110
+ /** Status text from the agent loop ("Thinking", "Reading cart"). */
111
+ status: string | null;
112
+ /** Re-send the last user message. Useful after a failed turn. */
113
+ retry(): Promise<void>;
114
+ /** Drop the conversation and start over. */
115
+ clear(): void;
116
+ /** Approve the message's `pendingAction`; the agent carries it out. */
117
+ confirm(messageId: string): Promise<void>;
118
+ /** Decline the message's `pendingAction`. Nothing is changed. */
119
+ cancel(messageId: string): void;
120
+ /**
121
+ * Push-to-talk: transcribe a recording and send it as the next message.
122
+ * Recording is the host's (no native module here); this uploads it.
123
+ */
124
+ sendVoice(recording: GuideAIVoiceRecording): Promise<GuideAIVoiceResult>;
125
+ /** True while a recording is being transcribed. */
126
+ transcribing: boolean;
127
+ }
128
+
129
+ interface UseVoiceInputOptions {
130
+ /** BCP-47 language spoken, e.g. 'en-NG'. Defaults to the user profile's language. */
131
+ languageCode?: string;
132
+ /** A recording stops and is sent after this long. Default 60 s. */
133
+ maxSeconds?: number;
134
+ }
135
+ interface UseVoiceInputResult {
136
+ /** The mic is on. */
137
+ recording: boolean;
138
+ /** What was said is being turned into text (then sent). */
139
+ transcribing: boolean;
140
+ /** Why the last attempt failed, in words to show the user; null when it didn't. */
141
+ error: string | null;
142
+ /** Start recording. False when the microphone was refused or is busy. */
143
+ start(): Promise<boolean>;
144
+ /** Stop, transcribe and send. Resolves with what was heard, or null. */
145
+ stop(): Promise<string | null>;
146
+ /** Stop and throw the recording away. */
147
+ cancel(): Promise<void>;
148
+ /** Start when idle, stop and send when recording: one mic button. */
149
+ toggle(): Promise<void>;
150
+ }
151
+ /**
152
+ * Push-to-talk for a chat from `useGuideAI()`:
153
+ *
154
+ * const chat = useGuideAI();
155
+ * const mic = useVoiceInput(chat);
156
+ * <Button onPress={mic.toggle} title={mic.recording ? 'Send' : 'Talk'} />
157
+ */
158
+ declare function useVoiceInput(chat: Pick<UseGuideAIResult, 'sendVoice' | 'transcribing' | 'busy'>, options?: UseVoiceInputOptions): UseVoiceInputResult;
159
+
160
+ export { useVoiceInput };
161
+ export type { UseVoiceInputOptions, UseVoiceInputResult };
package/dist/voice.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import { useState, useRef, useEffect, useCallback } from "react";
2
+ import { useAudioRecorder, RecordingPresets, setAudioModeAsync, requestRecordingPermissionsAsync } from "expo-audio";
3
+ import { r as requireConfigured } from "./setup-CkXajERE.js";
4
+ const MIC_REFUSED = "Allow microphone access in Settings to talk to the assistant.";
5
+ const START_FAILED = "The microphone didn't start. Please try again.";
6
+ function profileLanguage() {
7
+ var _a;
8
+ const language = (_a = requireConfigured().profile) == null ? void 0 : _a.language;
9
+ return typeof language === "string" && language.trim() ? language.trim() : void 0;
10
+ }
11
+ function useVoiceInput(chat, options = {}) {
12
+ var _a;
13
+ const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);
14
+ const [recording, setRecording] = useState(false);
15
+ const [error, setError] = useState(null);
16
+ const limit = useRef(null);
17
+ const mounted = useRef(true);
18
+ const stopRef = useRef(async () => null);
19
+ const maxSeconds = (_a = options.maxSeconds) != null ? _a : 60;
20
+ useEffect(() => () => {
21
+ mounted.current = false;
22
+ if (limit.current) clearTimeout(limit.current);
23
+ }, []);
24
+ const finish = useCallback(async () => {
25
+ var _a2;
26
+ if (limit.current) clearTimeout(limit.current);
27
+ limit.current = null;
28
+ if (!recorder.isRecording) {
29
+ if (mounted.current) setRecording(false);
30
+ return null;
31
+ }
32
+ await recorder.stop();
33
+ if (mounted.current) setRecording(false);
34
+ await setAudioModeAsync({ allowsRecording: false }).catch(() => void 0);
35
+ return (_a2 = recorder.uri) != null ? _a2 : null;
36
+ }, [recorder]);
37
+ const start = useCallback(async () => {
38
+ if (recording || chat.busy || chat.transcribing) return false;
39
+ setError(null);
40
+ const permission = await requestRecordingPermissionsAsync().catch(() => null);
41
+ if (!(permission == null ? void 0 : permission.granted)) {
42
+ if (mounted.current) setError(MIC_REFUSED);
43
+ return false;
44
+ }
45
+ try {
46
+ await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });
47
+ await recorder.prepareToRecordAsync();
48
+ recorder.record();
49
+ } catch (cause) {
50
+ console.log("[GuideAI] ✗ microphone did not start:", cause);
51
+ if (mounted.current) setError(START_FAILED);
52
+ return false;
53
+ }
54
+ if (mounted.current) setRecording(true);
55
+ limit.current = setTimeout(() => {
56
+ void stopRef.current();
57
+ }, maxSeconds * 1e3);
58
+ return true;
59
+ }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds]);
60
+ const stop = useCallback(async () => {
61
+ var _a2, _b;
62
+ let uri = null;
63
+ try {
64
+ uri = await finish();
65
+ } catch (cause) {
66
+ console.log("[GuideAI] ✗ recording did not stop:", cause);
67
+ }
68
+ if (!uri) return null;
69
+ const result = await chat.sendVoice({
70
+ uri,
71
+ languageCode: (_a2 = options.languageCode) != null ? _a2 : profileLanguage()
72
+ });
73
+ if (mounted.current) setError((_b = result.error) != null ? _b : null);
74
+ return result.text;
75
+ }, [finish, chat, options.languageCode]);
76
+ stopRef.current = stop;
77
+ const cancel = useCallback(async () => {
78
+ await finish().catch(() => null);
79
+ }, [finish]);
80
+ const toggle = useCallback(async () => {
81
+ if (recording) await stop();
82
+ else await start();
83
+ }, [recording, start, stop]);
84
+ return { recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle };
85
+ }
86
+ export {
87
+ useVoiceInput
88
+ };
89
+ //# sourceMappingURL=voice.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice.mjs","sources":["../src/voice/useVoiceInput.ts"],"sourcesContent":["// ============================================================\n// @guideai/react-native/voice — push-to-talk\n// ============================================================\n//\n// The whole mic for a host's chat: permission, recording, transcription\n// and sending the words as the next message. The host draws a button and\n// reads `recording` / `transcribing` / `error`; nothing else.\n//\n// Its own entry point because it needs expo-audio (an optional peer): an\n// app that never imports '@guideai/react-native/voice' never needs it.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n RecordingPresets,\n requestRecordingPermissionsAsync,\n setAudioModeAsync,\n useAudioRecorder,\n} from 'expo-audio';\nimport type { UseGuideAIResult } from '../react/useGuideAI';\nimport { requireConfigured } from '../setup';\n\nexport interface UseVoiceInputOptions {\n /** BCP-47 language spoken, e.g. 'en-NG'. Defaults to the user profile's language. */\n languageCode?: string;\n /** A recording stops and is sent after this long. Default 60 s. */\n maxSeconds?: number;\n}\n\nexport interface UseVoiceInputResult {\n /** The mic is on. */\n recording: boolean;\n /** What was said is being turned into text (then sent). */\n transcribing: boolean;\n /** Why the last attempt failed, in words to show the user; null when it didn't. */\n error: string | null;\n /** Start recording. False when the microphone was refused or is busy. */\n start(): Promise<boolean>;\n /** Stop, transcribe and send. Resolves with what was heard, or null. */\n stop(): Promise<string | null>;\n /** Stop and throw the recording away. */\n cancel(): Promise<void>;\n /** Start when idle, stop and send when recording: one mic button. */\n toggle(): Promise<void>;\n}\n\nconst MIC_REFUSED = 'Allow microphone access in Settings to talk to the assistant.';\nconst START_FAILED = \"The microphone didn't start. Please try again.\";\n\n/** The user profile's language as a recognizer code ('fr' → 'fr'), when set. */\nfunction profileLanguage(): string | undefined {\n const language = requireConfigured().profile?.language;\n return typeof language === 'string' && language.trim() ? language.trim() : undefined;\n}\n\n/**\n * Push-to-talk for a chat from `useGuideAI()`:\n *\n * const chat = useGuideAI();\n * const mic = useVoiceInput(chat);\n * <Button onPress={mic.toggle} title={mic.recording ? 'Send' : 'Talk'} />\n */\nexport function useVoiceInput(\n chat: Pick<UseGuideAIResult, 'sendVoice' | 'transcribing' | 'busy'>,\n options: UseVoiceInputOptions = {},\n): UseVoiceInputResult {\n const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);\n const [recording, setRecording] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const limit = useRef<ReturnType<typeof setTimeout> | null>(null);\n const mounted = useRef(true);\n const stopRef = useRef<() => Promise<string | null>>(async () => null);\n const maxSeconds = options.maxSeconds ?? 60;\n\n useEffect(() => () => {\n mounted.current = false;\n if (limit.current) clearTimeout(limit.current);\n }, []);\n\n const finish = useCallback(async (): Promise<string | null> => {\n if (limit.current) clearTimeout(limit.current);\n limit.current = null;\n if (!recorder.isRecording) {\n if (mounted.current) setRecording(false);\n return null;\n }\n await recorder.stop();\n if (mounted.current) setRecording(false);\n // Back to playback, or iOS keeps replies on the earpiece.\n await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);\n return recorder.uri ?? null;\n }, [recorder]);\n\n const start = useCallback(async () => {\n if (recording || chat.busy || chat.transcribing) return false;\n setError(null);\n const permission = await requestRecordingPermissionsAsync().catch(() => null);\n if (!permission?.granted) {\n if (mounted.current) setError(MIC_REFUSED);\n return false;\n }\n try {\n await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });\n await recorder.prepareToRecordAsync();\n recorder.record();\n } catch (cause) {\n console.log('[GuideAI] ✗ microphone did not start:', cause);\n if (mounted.current) setError(START_FAILED);\n return false;\n }\n if (mounted.current) setRecording(true);\n limit.current = setTimeout(() => { void stopRef.current(); }, maxSeconds * 1000);\n return true;\n }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds]);\n\n const stop = useCallback(async () => {\n let uri: string | null = null;\n try {\n uri = await finish();\n } catch (cause) {\n console.log('[GuideAI] ✗ recording did not stop:', cause);\n }\n if (!uri) return null;\n const result = await chat.sendVoice({\n uri,\n languageCode: options.languageCode ?? profileLanguage(),\n });\n if (mounted.current) setError(result.error ?? null);\n return result.text;\n }, [finish, chat, options.languageCode]);\n stopRef.current = stop;\n\n const cancel = useCallback(async () => {\n await finish().catch(() => null);\n }, [finish]);\n\n const toggle = useCallback(async () => {\n if (recording) await stop();\n else await start();\n }, [recording, start, stop]);\n\n return { recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle };\n}\n"],"names":["_a"],"mappings":";;;AA6CA,MAAM,cAAc;AACpB,MAAM,eAAe;AAGrB,SAAS,kBAAsC;;AAC7C,QAAM,YAAW,yBAAoB,YAApB,mBAA6B;AAC9C,SAAO,OAAO,aAAa,YAAY,SAAS,SAAS,SAAS,SAAS;AAC7E;AASO,SAAS,cACd,MACA,UAAgC,IACX;;AACrB,QAAM,WAAW,iBAAiB,iBAAiB,YAAY;AAC/D,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AACtD,QAAM,QAAQ,OAA6C,IAAI;AAC/D,QAAM,UAAU,OAAO,IAAI;AAC3B,QAAM,UAAU,OAAqC,YAAY,IAAI;AACrE,QAAM,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M,OAAO,YAAY,YAAY;;AACnC,QAAI,MAAqB;AACzB,QAAI;AACF,YAAM,MAAM,OAAA;AAAA,IACd,SAAS,OAAO;AACd,cAAQ,IAAI,uCAAuC,KAAK;AAAA,IAC1D;AACA,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,SAAS,MAAM,KAAK,UAAU;AAAA,MAClC;AAAA,MACA,eAAcA,MAAA,QAAQ,iBAAR,OAAAA,MAAwB,gBAAA;AAAA,IAAgB,CACvD;AACD,QAAI,QAAQ,QAAS,WAAS,YAAO,UAAP,YAAgB,IAAI;AAClD,WAAO,OAAO;AAAA,EAChB,GAAG,CAAC,QAAQ,MAAM,QAAQ,YAAY,CAAC;AACvC,UAAQ,UAAU;AAElB,QAAM,SAAS,YAAY,YAAY;AACrC,UAAM,OAAA,EAAS,MAAM,MAAM,IAAI;AAAA,EACjC,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,SAAS,YAAY,YAAY;AACrC,QAAI,iBAAiB,KAAA;AAAA,eACV,MAAA;AAAA,EACb,GAAG,CAAC,WAAW,OAAO,IAAI,CAAC;AAE3B,SAAO,EAAE,WAAW,cAAc,KAAK,cAAc,OAAO,OAAO,MAAM,QAAQ,OAAA;AACnF;"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@guideai/react-native",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
- "description": "GuideAI for React Native: assistant mode with your own login, your own chat UI (or ours), suggestions, pictures and push-to-talk.",
5
+ "description": "GuideAI for React Native: assistant mode with your own login, your own chat UI (or ours), suggestions, whiteboard, pictures and push-to-talk.",
6
6
  "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.mjs",
8
8
  "react-native": "./dist/index.cjs",
@@ -20,6 +20,12 @@
20
20
  "import": "./dist/ui.mjs",
21
21
  "require": "./dist/ui.cjs"
22
22
  },
23
+ "./voice": {
24
+ "types": "./dist/voice.d.ts",
25
+ "react-native": "./dist/voice.cjs",
26
+ "import": "./dist/voice.mjs",
27
+ "require": "./dist/voice.cjs"
28
+ },
23
29
  "./package.json": "./package.json"
24
30
  },
25
31
  "files": [
@@ -29,7 +35,9 @@
29
35
  "sideEffects": false,
30
36
  "peerDependencies": {
31
37
  "react": ">=18.0.0",
32
- "react-native": ">=0.73.0"
38
+ "react-native": ">=0.73.0",
39
+ "react-native-svg": ">=13.0.0",
40
+ "expo-audio": ">=0.4.0"
33
41
  },
34
42
  "peerDependenciesMeta": {
35
43
  "react-native": {
@@ -37,6 +45,12 @@
37
45
  },
38
46
  "react": {
39
47
  "optional": true
48
+ },
49
+ "react-native-svg": {
50
+ "optional": true
51
+ },
52
+ "expo-audio": {
53
+ "optional": true
40
54
  }
41
55
  },
42
56
  "devDependencies": {