@blinq_ai/widget 0.1.0 → 0.1.2
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/README.md +12 -4
- package/dist/blinq-widget.iife.global.js +1923 -997
- package/dist/blinq-widget.iife.global.js.map +1 -1
- package/dist/browser.cjs +1580 -796
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.cts +3 -2
- package/dist/browser.d.ts +3 -2
- package/dist/browser.js +168 -1114
- package/dist/browser.js.map +1 -1
- package/dist/{chunk-2BSH3PRA.js → chunk-DQF42RXH.js} +1884 -145
- package/dist/chunk-DQF42RXH.js.map +1 -0
- package/dist/cli.js +122 -14
- package/dist/index.cjs +1886 -142
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +96 -108
- package/dist/index.d.ts +96 -108
- package/dist/index.js +11 -1
- package/dist/widget-core-D0ZdQY2E.d.cts +253 -0
- package/dist/widget-core-D0ZdQY2E.d.ts +253 -0
- package/package.json +3 -2
- package/dist/chunk-2BSH3PRA.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/widget-core.ts","../src/page-capabilities.ts","../src/page-tools.ts","../src/embed-shell.tsx","../src/voice-input.ts"],"sourcesContent":["import * as React from \"react\"\nimport { createRoot, type Root } from \"react-dom/client\"\n\nimport {\n PageToolRegistry,\n collectNormalizedPageContext,\n detectNativeWebMcpSupport,\n type PageHighlightTarget,\n type RuntimeCapability,\n type RuntimeMode,\n type ToolExecutionOutcome,\n} from \"./page-tools\"\nimport {\n WidgetEmbedShell,\n type WidgetActionConversationItem,\n type WidgetConversationItem,\n type WidgetPlanConversationItem,\n type WidgetShellState,\n} from \"./embed-shell\"\nimport { VoiceInputController } from \"./voice-input\"\n\nexport interface BlinqWidgetInitOptions {\n publicToken: string\n apiBaseUrl?: string\n mcpEndpoint?: string\n mount?: string | HTMLElement\n}\n\nexport type BlinqWidgetConfigFile = BlinqWidgetInitOptions\n\ninterface WidgetConfig {\n widget_id: string\n name: string\n ai_persona_name: string\n ai_persona_prompt: string\n theme_color: string\n position: \"bottom-right\" | \"bottom-left\"\n is_active: boolean\n allowed_domain: string\n}\n\ninterface InitResponse {\n session_id: string\n session_token: string\n widget_config: WidgetConfig\n runtime: RuntimeCapability\n resumed?: boolean\n active_run?: GoalRunPreview | null\n}\n\ninterface SseEnvelope {\n event: string\n data: string\n}\n\ninterface PublicToolRequestPayload {\n tool_call_id: string\n goal_run_id: string\n step_id: string\n step_index: number\n tool_name: string\n display_name: string\n arguments: Record<string, unknown>\n requires_confirmation: boolean\n target_summary: string\n}\n\ninterface GoalStepPreview {\n id: string\n index: number\n kind: string\n title: string\n status: string\n target_summary?: string | null\n}\n\ninterface GoalRunPreview {\n id: string\n goal: string\n goal_kind: string\n language: string\n status: string\n current_step_index: number\n total_steps: number\n summary?: string | null\n progress_label?: string | null\n status_reason?: string | null\n expected_route?: string | null\n loop_guarded?: boolean\n requires_approval?: boolean\n steps: GoalStepPreview[]\n}\n\ninterface GoalProgressPayload {\n run: GoalRunPreview\n label: string\n}\n\ninterface PublicStatusPayload {\n phase:\n | \"thinking\"\n | \"searching_knowledge\"\n | \"searching_site\"\n | \"planning\"\n | \"awaiting_approval\"\n | \"executing_plan\"\n label: string\n}\n\ninterface HighlightEventPayload {\n targets: PageHighlightTarget[]\n reason?: string\n}\n\ninterface ChatHistoryEntry {\n role: \"user\" | \"assistant\"\n text: string\n}\n\nexport interface BlinqWidgetRuntimeStatus extends RuntimeCapability {\n message: string\n}\n\nconst DEFAULT_API_BASE_URL = \"http://localhost:8000\"\nconst STORAGE_KEY = \"blinq-widget-fingerprint\"\nconst HISTORY_STORAGE_PREFIX = \"blinq-widget-history\"\nconst MINIMIZED_STORAGE_PREFIX = \"blinq-widget-minimized\"\nconst SESSION_STORAGE_PREFIX = \"blinq-widget-session\"\nconst MAX_STORED_HISTORY = 30\nconst MAX_HISTORY_FOR_REQUEST = 12\nconst DEFAULT_GREETING =\n \"Blinq подключен. Спросите про текущую страницу, настройку платформы или следующий шаг.\"\n\nfunction isBrowser() {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\"\n}\n\nfunction resolveMount(mount?: string | HTMLElement): HTMLElement {\n if (!isBrowser()) {\n throw new Error(\"Blinq можно подключить только в браузере\")\n }\n if (mount instanceof HTMLElement) {\n return mount\n }\n if (typeof mount === \"string\") {\n const target = document.querySelector<HTMLElement>(mount)\n if (!target) {\n throw new Error(`Не найден mount-элемент: ${mount}`)\n }\n return target\n }\n return document.body\n}\n\nfunction getOrCreateFingerprint() {\n if (!isBrowser()) {\n return \"server-widget-user\"\n }\n const existing = window.localStorage.getItem(STORAGE_KEY)\n if (existing) {\n return existing\n }\n const next = `fingerprint_${crypto.randomUUID()}`\n window.localStorage.setItem(STORAGE_KEY, next)\n return next\n}\n\nfunction runtimeMessage(mode: RuntimeMode) {\n if (mode === \"read-only-fallback\") {\n return \"Готов объяснить текущую страницу и подсказать следующий шаг.\"\n }\n return \"Готов помочь с онбордингом и вопросами по платформе.\"\n}\n\nfunction normalizedRouteFromUrl(value: string) {\n try {\n const url = new URL(value, window.location.origin)\n const path = url.pathname || \"/\"\n return path === \"\" ? \"/\" : path\n } catch {\n return \"/\"\n }\n}\n\nasync function parseSseStream(\n stream: ReadableStream<Uint8Array>,\n onEvent: (event: SseEnvelope) => void\n) {\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n let buffer = \"\"\n let currentEvent = \"message\"\n let currentData = \"\"\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n buffer += decoder.decode(value, { stream: true })\n const chunks = buffer.split(\"\\n\")\n buffer = chunks.pop() ?? \"\"\n\n for (const line of chunks) {\n if (line.startsWith(\"event:\")) {\n currentEvent = line.slice(6).trim()\n } else if (line.startsWith(\"data:\")) {\n currentData += line.slice(5).trim()\n } else if (line.trim() === \"\") {\n if (currentData) {\n onEvent({ event: currentEvent, data: currentData })\n }\n currentEvent = \"message\"\n currentData = \"\"\n }\n }\n }\n\n if (currentData) {\n onEvent({ event: currentEvent, data: currentData })\n }\n}\n\nfunction normalizedConfig(\n config: BlinqWidgetConfigFile | { default: BlinqWidgetConfigFile }\n): BlinqWidgetConfigFile {\n if (\"default\" in config) {\n return config.default\n }\n return config as BlinqWidgetConfigFile\n}\n\nfunction createConversationId(prefix: string) {\n return `${prefix}_${crypto.randomUUID()}`\n}\n\nfunction normalizeAssistantStreamChunk(currentText: string, nextChunk: string) {\n if (!currentText) {\n return nextChunk.replace(/^\\s+/, \"\")\n }\n return nextChunk\n}\n\nfunction normalizeAssistantFinalText(text: string) {\n return text.replace(/^\\s+/, \"\")\n}\n\nexport class BlinqWidget {\n private readonly options: BlinqWidgetInitOptions\n private readonly apiBaseUrl: string\n private sessionId: string | null = null\n private sessionToken: string | null = null\n private widgetConfig: WidgetConfig | null = null\n private runtimeStatus: BlinqWidgetRuntimeStatus | null = null\n private registry: PageToolRegistry | null = null\n private root: HTMLElement | null = null\n private reactRoot: Root | null = null\n private voiceController: VoiceInputController | null = null\n private history: ChatHistoryEntry[] = []\n private items: WidgetConversationItem[] = []\n private minimized = false\n private isSending = false\n private inputValue = \"\"\n private statusText = \"Проверяем доступные действия страницы.\"\n private voiceSupported = false\n private voiceListening = false\n private voiceWaveform: number[] = []\n private voiceDurationMs = 0\n private voiceStartedAt: number | null = null\n private lastVoiceSampleAt = 0\n private confirmResolve: ((value: boolean) => void) | null = null\n private confirmItemId: string | null = null\n private activeRun: GoalRunPreview | null = null\n private pendingAssistantIndicator = false\n private executedToolCounts = new Map<string, number>()\n private lastAutoResumeKey: string | null = null\n private readonly shellHandlers = {\n onOpen: () => this.setMinimized(false),\n onCollapse: () => this.setMinimized(true),\n onInputChange: (value: string) => {\n this.inputValue = value\n this.renderReactApp()\n },\n onSubmit: () => {\n void this.submitComposerMessage()\n },\n onToggleVoice: () => this.toggleVoiceInput(),\n onApproveAction: (id: string) => {\n if (this.confirmItemId === id) {\n this.resolveConfirmation(true)\n }\n },\n onDeclineAction: (id: string) => {\n if (this.confirmItemId === id) {\n this.resolveConfirmation(false)\n }\n },\n onApprovePlan: () => {\n void this.respondToPlan(true)\n },\n onDeclinePlan: () => {\n void this.respondToPlan(false)\n },\n }\n\n constructor(options: BlinqWidgetInitOptions) {\n this.options = options\n this.apiBaseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL\n }\n\n async init() {\n await this.startSession()\n if (isBrowser()) {\n this.restoreHistory()\n this.restoreMinimizedState()\n this.restoreConversationView()\n this.render()\n this.setupVoiceInput()\n this.registry = new PageToolRegistry(this.confirmToolExecution.bind(this))\n const nativeRegistered = await this.registry.registerNativeTools()\n this.syncRuntimeStatus(nativeRegistered)\n if (this.shouldAutoResumeActiveRun()) {\n window.setTimeout(() => {\n void this.continueActiveRun()\n }, 60)\n }\n }\n return this\n }\n\n getRuntimeStatus() {\n return this.runtimeStatus\n }\n\n destroy() {\n this.voiceController?.destroy()\n this.registry?.destroy()\n this.voiceController = null\n this.registry = null\n this.reactRoot?.unmount()\n this.reactRoot = null\n this.root?.remove()\n this.root = null\n }\n\n private currentState(): WidgetShellState {\n return {\n minimized: this.minimized,\n assistantName: this.widgetConfig?.ai_persona_name ?? \"Blinq Ассистент\",\n runtimeLabel: \"webmcp://embedded\",\n statusText: this.statusText,\n showThinkingIndicator: this.pendingAssistantIndicator,\n inputValue: this.inputValue,\n accentColor: \"#111111\",\n side: this.widgetConfig?.position === \"bottom-left\" ? \"left\" : \"right\",\n isSending: this.isSending,\n voiceSupported: this.voiceSupported,\n voiceListening: this.voiceListening,\n voiceWaveform: this.voiceWaveform,\n voiceDurationMs: this.voiceDurationMs,\n items: this.items,\n }\n }\n\n private renderReactApp() {\n if (!this.reactRoot) {\n return\n }\n\n this.reactRoot.render(\n React.createElement(WidgetEmbedShell, {\n state: this.currentState(),\n ...this.shellHandlers,\n })\n )\n }\n\n private async startSession() {\n const response = await fetch(`${this.apiBaseUrl}/pub/init`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n public_token: this.options.publicToken,\n domain: window.location.hostname,\n page_url: window.location.href,\n user_fingerprint: getOrCreateFingerprint(),\n previous_session_id: this.restoreStoredSessionId(),\n client_capabilities: {\n secure_context: window.isSecureContext,\n native_webmcp_supported: detectNativeWebMcpSupport(),\n page_actions_supported: true,\n },\n }),\n })\n\n if (!response.ok) {\n const payload = (await response.json().catch(() => ({}))) as { detail?: string }\n throw new Error(payload.detail ?? \"Не удалось инициализировать виджет Blinq\")\n }\n\n const payload = (await response.json()) as InitResponse\n this.sessionId = payload.session_id\n this.sessionToken = payload.session_token\n this.widgetConfig = payload.widget_config\n this.activeRun = payload.active_run ?? null\n this.runtimeStatus = {\n ...payload.runtime,\n message: runtimeMessage(payload.runtime.mode),\n }\n this.persistSessionId()\n this.statusText = this.runtimeStatus.message\n }\n\n private render() {\n const mount = resolveMount(this.options.mount)\n if (!this.root) {\n this.root = document.createElement(\"div\")\n mount.appendChild(this.root)\n this.reactRoot = createRoot(this.root)\n }\n\n this.renderReactApp()\n }\n\n private preferredSpeechLanguage() {\n const htmlLang = document.documentElement.lang.trim()\n if (htmlLang) {\n return htmlLang\n }\n return navigator.language || \"ru-RU\"\n }\n\n private setupVoiceInput() {\n this.voiceController = new VoiceInputController({\n getLanguage: () => this.preferredSpeechLanguage(),\n onInterimTranscript: () => {},\n onFinalTranscript: (text) => {\n this.inputValue = text\n this.setStatus(\"Голос распознан. Проверьте текст и нажмите отправить.\")\n this.renderReactApp()\n },\n onListeningChange: (isListening) => {\n if (isListening) {\n this.startVoiceVisualization()\n } else {\n this.resetVoiceVisualization()\n }\n this.syncVoiceState()\n },\n onLevelChange: (level) => {\n this.updateVoiceVisualization(level)\n },\n onStatusChange: (status) => {\n this.setStatus(status)\n },\n onError: (message) => {\n this.setStatus(message)\n this.syncVoiceState()\n },\n })\n\n this.syncVoiceState()\n }\n\n private syncVoiceState() {\n this.voiceSupported = this.voiceController?.supported ?? false\n this.voiceListening = this.voiceController?.isListening ?? false\n if (!this.voiceListening) {\n this.resetVoiceVisualization()\n }\n this.renderReactApp()\n }\n\n private startVoiceVisualization() {\n this.voiceStartedAt = Date.now()\n this.voiceDurationMs = 0\n this.voiceWaveform = []\n this.lastVoiceSampleAt = 0\n }\n\n private resetVoiceVisualization() {\n this.voiceStartedAt = null\n this.voiceDurationMs = 0\n this.voiceWaveform = []\n this.lastVoiceSampleAt = 0\n }\n\n private updateVoiceVisualization(level: number) {\n if (!this.voiceListening) {\n return\n }\n\n const now = Date.now()\n if (this.voiceStartedAt === null) {\n this.startVoiceVisualization()\n this.voiceStartedAt = now\n }\n\n this.voiceDurationMs = Math.max(0, now - (this.voiceStartedAt ?? now))\n const nextLevel = Math.max(0.1, Math.min(1, level))\n\n if (this.voiceWaveform.length === 0 || now - this.lastVoiceSampleAt >= 90) {\n this.voiceWaveform = [...this.voiceWaveform, nextLevel].slice(-40)\n this.lastVoiceSampleAt = now\n } else {\n this.voiceWaveform = [\n ...this.voiceWaveform.slice(0, -1),\n nextLevel,\n ]\n }\n\n this.renderReactApp()\n }\n\n private async submitComposerMessage(message = this.inputValue) {\n const nextMessage = message.trim()\n if (!nextMessage) {\n return \"\"\n }\n if (this.isSending) {\n this.setStatus(\"Дождитесь завершения текущего ответа.\")\n this.inputValue = nextMessage\n this.renderReactApp()\n return \"\"\n }\n\n this.inputValue = \"\"\n this.renderReactApp()\n\n try {\n return await this.sendMessage(nextMessage)\n } catch {\n return \"\"\n }\n }\n\n private toggleVoiceInput() {\n if (!this.voiceController) {\n this.setStatus(\"Голосовой ввод недоступен.\")\n return\n }\n\n if (this.voiceController.isListening) {\n this.voiceController.stop()\n return\n }\n\n this.voiceController.start()\n this.syncVoiceState()\n }\n\n private minimizedStorageKey() {\n return `${MINIMIZED_STORAGE_PREFIX}:${window.location.hostname}:${this.options.publicToken.slice(0, 18)}`\n }\n\n private sessionStorageKey() {\n return `${SESSION_STORAGE_PREFIX}:${window.location.hostname}:${this.options.publicToken.slice(0, 18)}`\n }\n\n private restoreStoredSessionId() {\n if (!isBrowser()) {\n return null\n }\n return window.localStorage.getItem(this.sessionStorageKey())\n }\n\n private persistSessionId() {\n if (!isBrowser() || !this.sessionId) {\n return\n }\n window.localStorage.setItem(this.sessionStorageKey(), this.sessionId)\n }\n\n private restoreMinimizedState() {\n if (!isBrowser()) {\n return\n }\n this.minimized = window.localStorage.getItem(this.minimizedStorageKey()) === \"1\"\n }\n\n private persistMinimizedState() {\n if (!isBrowser()) {\n return\n }\n window.localStorage.setItem(this.minimizedStorageKey(), this.minimized ? \"1\" : \"0\")\n }\n\n private setMinimized(nextValue: boolean) {\n this.minimized = nextValue\n this.persistMinimizedState()\n this.renderReactApp()\n }\n\n private historyStorageKey() {\n return `${HISTORY_STORAGE_PREFIX}:${window.location.hostname}:${this.options.publicToken.slice(0, 18)}`\n }\n\n private restoreHistory() {\n if (!isBrowser()) {\n return\n }\n\n try {\n const raw = window.localStorage.getItem(this.historyStorageKey())\n if (!raw) {\n this.history = []\n return\n }\n\n const parsed = JSON.parse(raw) as unknown\n if (!Array.isArray(parsed)) {\n this.history = []\n return\n }\n\n this.history = parsed\n .filter((entry): entry is ChatHistoryEntry => {\n if (!entry || typeof entry !== \"object\") {\n return false\n }\n const role = (entry as { role?: unknown }).role\n const text = (entry as { text?: unknown }).text\n return (role === \"user\" || role === \"assistant\") && typeof text === \"string\"\n })\n .slice(-MAX_STORED_HISTORY)\n } catch {\n this.history = []\n }\n }\n\n private persistHistory() {\n if (!isBrowser()) {\n return\n }\n\n try {\n window.localStorage.setItem(\n this.historyStorageKey(),\n JSON.stringify(this.history.slice(-MAX_STORED_HISTORY))\n )\n } catch {\n // Ignore storage quota or privacy-mode failures and keep the widget usable.\n }\n }\n\n private rememberMessage(entry: ChatHistoryEntry) {\n const text = entry.text.trim()\n if (!text) {\n return\n }\n this.history.push({ role: entry.role, text })\n this.history = this.history.slice(-MAX_STORED_HISTORY)\n this.persistHistory()\n }\n\n private recentHistoryForRequest() {\n return this.history.slice(-MAX_HISTORY_FOR_REQUEST).map((entry) => ({\n role: entry.role,\n text: entry.text,\n }))\n }\n\n private restoreConversationView() {\n if (this.history.length === 0) {\n this.items = [\n {\n id: createConversationId(\"message\"),\n type: \"message\",\n role: \"assistant\",\n text: DEFAULT_GREETING,\n status: \"done\",\n },\n ]\n } else {\n this.items = this.history.map((entry) => ({\n id: createConversationId(\"message\"),\n type: \"message\",\n role: entry.role,\n text: entry.text,\n status: \"done\",\n }))\n }\n\n if (this.activeRun) {\n this.upsertPlanItem(this.activeRun)\n }\n }\n\n private updateActionState(id: string, state: WidgetActionConversationItem[\"state\"]) {\n this.items = this.items.map((item) =>\n item.type === \"action\" && item.id === id ? { ...item, state } : item\n )\n this.renderReactApp()\n }\n\n private planItemId(runId: string) {\n return `plan_${runId}`\n }\n\n private upsertPlanItem(run: GoalRunPreview, progressLabel?: string | null) {\n const existingPlanItem = this.items.find(\n (item) => item.type === \"plan\" && item.id === this.planItemId(run.id)\n )\n if (this.activeRun?.id && this.activeRun.id !== run.id) {\n this.executedToolCounts.clear()\n }\n this.activeRun = {\n ...run,\n progress_label: progressLabel ?? run.progress_label ?? null,\n }\n\n const nextPlanItem: WidgetPlanConversationItem = {\n id: this.planItemId(run.id),\n type: \"plan\",\n goal: run.goal,\n status: run.status,\n progressLabel: progressLabel ?? run.progress_label ?? null,\n statusReason: run.status_reason ?? null,\n expectedRoute: run.expected_route ?? null,\n loopGuarded: run.loop_guarded ?? false,\n currentStepIndex:\n run.status === \"completed\"\n ? run.total_steps\n : Math.min(run.total_steps, run.current_step_index + 1),\n totalSteps: run.total_steps,\n approvalState: run.requires_approval\n ? \"pending\"\n : run.status === \"abandoned\"\n ? \"declined\"\n : existingPlanItem && existingPlanItem.type === \"plan\" && existingPlanItem.approvalState === \"declined\"\n ? \"declined\"\n : \"approved\",\n steps: run.steps.map((step) => ({\n id: step.id,\n title: step.title,\n status: step.status,\n kind: step.kind,\n })),\n }\n\n const existingIndex = this.items.findIndex(\n (item) => item.type === \"plan\" && item.id === nextPlanItem.id\n )\n\n if (existingIndex >= 0) {\n this.items = this.items.map((item, index) => (index === existingIndex ? nextPlanItem : item))\n } else {\n this.items = [...this.items, nextPlanItem]\n }\n\n this.renderReactApp()\n }\n\n private removeEmptyMessage(id: string | null) {\n if (!id) {\n return\n }\n this.items = this.items.filter(\n (item) => !(item.type === \"message\" && item.id === id && item.text.trim().length === 0)\n )\n }\n\n private resolveConfirmation(value: boolean) {\n if (this.confirmItemId) {\n this.updateActionState(this.confirmItemId, value ? \"approved\" : \"declined\")\n }\n\n if (this.confirmResolve) {\n const resolve = this.confirmResolve\n this.confirmResolve = null\n this.confirmItemId = null\n resolve(value)\n }\n }\n\n private async confirmToolExecution(request: {\n displayName: string\n targetSummary: string\n arguments: Record<string, unknown>\n }) {\n if (this.minimized) {\n this.setMinimized(false)\n }\n\n if (this.confirmResolve) {\n this.resolveConfirmation(false)\n }\n\n const itemId = createConversationId(\"action\")\n this.items = [\n ...this.items,\n {\n id: itemId,\n type: \"action\",\n displayName: request.displayName,\n targetSummary: request.targetSummary,\n arguments: request.arguments,\n state: \"pending\",\n },\n ]\n this.confirmItemId = itemId\n this.setStatus(`Нужно подтверждение: ${request.displayName}`)\n this.renderReactApp()\n\n return await new Promise<boolean>((resolve) => {\n this.confirmResolve = resolve\n })\n }\n\n private syncRuntimeStatus(nativeRegistered: boolean) {\n if (!this.runtimeStatus) {\n return\n }\n\n const mode: RuntimeMode = nativeRegistered\n ? \"native-webmcp-active\"\n : this.registry?.canExecuteWriteTools()\n ? \"blinq-page-tools-active\"\n : \"read-only-fallback\"\n\n this.runtimeStatus = {\n ...this.runtimeStatus,\n mode,\n native_webmcp_supported: nativeRegistered,\n embedded_page_tools_supported: true,\n message: runtimeMessage(mode),\n }\n this.setStatus(this.runtimeStatus.message)\n }\n\n private setStatus(text: string) {\n this.statusText = text\n this.renderReactApp()\n }\n\n private appendMessage(\n text: string,\n role: \"user\" | \"assistant\",\n options?: {\n persist?: boolean\n status?: \"thinking\" | \"streaming\" | \"done\"\n }\n ) {\n const id = createConversationId(\"message\")\n this.items = [\n ...this.items,\n {\n id,\n type: \"message\",\n role,\n text,\n status: options?.status ?? \"done\",\n },\n ]\n this.renderReactApp()\n if (options?.persist !== false) {\n this.rememberMessage({ role, text })\n }\n return id\n }\n\n private updateMessage(id: string, text: string, status?: \"thinking\" | \"streaming\" | \"done\") {\n this.items = this.items.map((item) =>\n item.type === \"message\" && item.id === id\n ? { ...item, text, status: status ?? item.status }\n : item\n )\n this.renderReactApp()\n }\n\n private latestAssistantMessage() {\n const candidate = [...this.items]\n .reverse()\n .find((item) => item.type === \"message\" && item.role === \"assistant\")\n return candidate && candidate.type === \"message\" ? candidate : null\n }\n\n private finalizeAssistantMessage(text: string, options?: { persist?: boolean }) {\n if (!text.trim()) {\n return\n }\n\n const latestAssistant = this.latestAssistantMessage()\n if (latestAssistant) {\n this.updateMessage(latestAssistant.id, text, \"done\")\n return\n }\n\n this.appendMessage(text, \"assistant\", {\n persist: options?.persist ?? false,\n status: \"done\",\n })\n }\n\n private showThinkingIndicator() {\n if (!this.pendingAssistantIndicator) {\n this.pendingAssistantIndicator = true\n this.renderReactApp()\n }\n }\n\n private hideThinkingIndicator() {\n if (this.pendingAssistantIndicator) {\n this.pendingAssistantIndicator = false\n this.renderReactApp()\n }\n }\n\n private currentPageContext() {\n return this.registry?.collectPageContext() ?? collectNormalizedPageContext()\n }\n\n private currentRoute() {\n return normalizedRouteFromUrl(window.location.href)\n }\n\n private shouldAutoResumeActiveRun() {\n if (!this.activeRun || this.activeRun.status !== \"awaiting_navigation\") {\n return false\n }\n\n const currentRoute = this.currentRoute()\n if (!this.activeRun.expected_route || currentRoute !== this.activeRun.expected_route) {\n if (this.activeRun.status_reason) {\n this.setStatus(this.activeRun.status_reason)\n }\n return false\n }\n\n const nextKey = `${this.activeRun.id}:${currentRoute}`\n if (this.lastAutoResumeKey === nextKey) {\n return false\n }\n this.lastAutoResumeKey = nextKey\n return true\n }\n\n private async handleToolRequest(request: PublicToolRequestPayload): Promise<ToolExecutionOutcome> {\n if (!this.registry) {\n return {\n status: \"error\",\n error: \"Реестр действий страницы недоступен\",\n }\n }\n\n const executionKey = JSON.stringify({\n stepId: request.step_id,\n toolName: request.tool_name,\n arguments: request.arguments,\n route: this.currentRoute(),\n })\n const executionCount = (this.executedToolCounts.get(executionKey) ?? 0) + 1\n this.executedToolCounts.set(executionKey, executionCount)\n if (executionCount > 2) {\n const error = \"Повторяющееся действие на этой странице было остановлено.\"\n this.setStatus(error)\n return {\n status: \"error\",\n error,\n }\n }\n\n this.setStatus(`Ожидается локальное действие: ${request.display_name}`)\n const outcome = await this.registry.executeTool({\n tool_name: request.tool_name,\n display_name: request.display_name,\n target_summary: request.target_summary,\n requires_confirmation: request.requires_confirmation,\n arguments: request.arguments,\n })\n if (outcome.status === \"success\") {\n this.setStatus(`Действие выполнено: ${request.display_name}`)\n } else if (outcome.status === \"cancelled\") {\n this.setStatus(`Действие отменено: ${request.display_name}`)\n } else {\n this.setStatus(outcome.error ?? \"Не удалось выполнить действие на странице.\")\n }\n return outcome\n }\n\n private async streamChatStep(\n path: string,\n body: Record<string, unknown>,\n responseMessageId: string | null,\n accumulatedText = \"\"\n ): Promise<string> {\n if (!this.sessionToken) {\n throw new Error(\"Сессия виджета ещё не инициализирована\")\n }\n\n const response = await fetch(`${this.apiBaseUrl}${path}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.sessionToken}`,\n },\n body: JSON.stringify(body),\n })\n\n if (!response.ok || !response.body) {\n const payload = (await response.json().catch(() => ({}))) as { detail?: string }\n throw new Error(payload.detail ?? \"Не удалось получить потоковый ответ\")\n }\n\n let nextToolRequest: PublicToolRequestPayload | null = null\n let finalText = accumulatedText\n let deferredNavigationHref: string | null = null\n\n await parseSseStream(response.body, ({ event, data }) => {\n const payload = JSON.parse(data) as {\n text?: string\n message?: string\n }\n\n if (event === \"metadata\") {\n return\n }\n if (event === \"status\") {\n const statusPayload = JSON.parse(data) as PublicStatusPayload\n this.setStatus(statusPayload.label)\n }\n if (event === \"plan\") {\n this.hideThinkingIndicator()\n this.upsertPlanItem(JSON.parse(data) as GoalRunPreview)\n }\n if (event === \"progress\") {\n this.hideThinkingIndicator()\n const progress = JSON.parse(data) as GoalProgressPayload\n this.upsertPlanItem(progress.run, progress.label)\n this.setStatus(progress.label)\n }\n if (event === \"highlight\") {\n const highlight = JSON.parse(data) as HighlightEventPayload\n this.registry?.highlightTargets(highlight.targets ?? [])\n }\n if (event === \"delta\" && payload.text) {\n const normalizedChunk = normalizeAssistantStreamChunk(finalText, payload.text)\n if (!normalizedChunk && !finalText.trim()) {\n return\n }\n this.hideThinkingIndicator()\n if (!responseMessageId) {\n responseMessageId = this.appendMessage(\"\", \"assistant\", {\n persist: false,\n status: \"thinking\",\n })\n }\n finalText += normalizedChunk\n if (responseMessageId) {\n this.updateMessage(responseMessageId, finalText, \"streaming\")\n }\n }\n if (event === \"tool_request\") {\n this.hideThinkingIndicator()\n nextToolRequest = JSON.parse(data) as PublicToolRequestPayload\n }\n if (event === \"error\") {\n this.hideThinkingIndicator()\n this.setStatus(payload.message ?? \"Ошибка потока виджета.\")\n }\n if (event === \"done\") {\n this.hideThinkingIndicator()\n if (payload.text && !finalText.trim()) {\n finalText = normalizeAssistantFinalText(payload.text)\n if (responseMessageId) {\n this.updateMessage(responseMessageId, finalText, \"done\")\n }\n }\n this.setStatus(\"Готов к следующему сообщению.\")\n }\n })\n\n if (!nextToolRequest) {\n return finalText\n }\n\n const toolRequest = nextToolRequest as PublicToolRequestPayload\n const outcome = await this.handleToolRequest(toolRequest)\n const possibleNavigationHref =\n outcome.status === \"success\" &&\n outcome.result &&\n typeof outcome.result.href === \"string\" &&\n outcome.result.deferred_navigation\n ? outcome.result.href\n : null\n if (possibleNavigationHref) {\n deferredNavigationHref = possibleNavigationHref\n }\n const nextText = await this.streamChatStep(\n \"/pub/chat/tool-result\",\n {\n session_id: this.sessionId,\n tool_call_id: toolRequest.tool_call_id,\n step_id: toolRequest.step_id,\n status: outcome.status,\n result: outcome.result ?? null,\n error: outcome.error ?? null,\n page_context: this.currentPageContext(),\n },\n responseMessageId,\n finalText\n )\n if (deferredNavigationHref) {\n window.location.assign(deferredNavigationHref)\n }\n return nextText\n }\n\n async sendMessage(message: string) {\n if (!this.sessionId || !this.sessionToken) {\n throw new Error(\"Сессия виджета ещё не инициализирована\")\n }\n if (this.isSending) {\n this.setStatus(\"Дождитесь завершения текущего ответа.\")\n return \"\"\n }\n\n this.isSending = true\n this.showThinkingIndicator()\n this.syncVoiceState()\n this.renderReactApp()\n\n const requestHistory = this.recentHistoryForRequest()\n let responseMessageId: string | null = null\n\n try {\n this.appendMessage(message, \"user\")\n const finalText = await this.streamChatStep(\n \"/pub/chat\",\n {\n session_id: this.sessionId,\n message,\n history: requestHistory,\n page_context: this.currentPageContext(),\n },\n responseMessageId\n )\n this.finalizeAssistantMessage(finalText, { persist: false })\n if (finalText.trim()) {\n this.rememberMessage({ role: \"assistant\", text: finalText })\n }\n return finalText\n } catch (error) {\n const messageText = error instanceof Error ? error.message : \"Blinq не смог ответить.\"\n this.finalizeAssistantMessage(messageText, { persist: false })\n this.rememberMessage({ role: \"assistant\", text: messageText })\n throw error\n } finally {\n this.hideThinkingIndicator()\n this.isSending = false\n this.syncVoiceState()\n this.renderReactApp()\n }\n }\n\n private async continueActiveRun() {\n if (!this.sessionId || !this.sessionToken || !this.activeRun || this.isSending) {\n return\n }\n if (this.activeRun.status !== \"awaiting_navigation\") {\n return\n }\n if (this.activeRun.expected_route && this.currentRoute() !== this.activeRun.expected_route) {\n this.setStatus(this.activeRun.status_reason ?? \"Жду переход на нужную страницу.\")\n return\n }\n\n this.isSending = true\n this.showThinkingIndicator()\n this.renderReactApp()\n\n try {\n const finalText = await this.streamChatStep(\n \"/pub/chat\",\n {\n session_id: this.sessionId,\n message: \"\",\n continue_active_run: true,\n history: this.recentHistoryForRequest(),\n page_context: this.currentPageContext(),\n },\n null\n )\n this.finalizeAssistantMessage(finalText)\n } finally {\n this.hideThinkingIndicator()\n this.isSending = false\n this.renderReactApp()\n }\n }\n\n async respondToPlan(approved: boolean) {\n if (!this.sessionId || !this.sessionToken || !this.activeRun) {\n return\n }\n if (this.isSending) {\n return\n }\n\n this.isSending = true\n this.showThinkingIndicator()\n this.renderReactApp()\n\n try {\n const finalText = await this.streamChatStep(\n \"/pub/plan/approve\",\n {\n session_id: this.sessionId,\n goal_run_id: this.activeRun.id,\n approved,\n page_context: this.currentPageContext(),\n },\n null\n )\n\n if (finalText.trim()) {\n this.finalizeAssistantMessage(finalText, { persist: false })\n this.rememberMessage({ role: \"assistant\", text: finalText })\n }\n } finally {\n this.hideThinkingIndicator()\n this.isSending = false\n this.renderReactApp()\n }\n }\n\n async endSession() {\n if (!this.sessionId || !this.sessionToken) {\n return\n }\n await fetch(`${this.apiBaseUrl}/pub/session/end`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.sessionToken}`,\n },\n body: JSON.stringify({ session_id: this.sessionId }),\n keepalive: true,\n }).catch(() => undefined)\n if (isBrowser()) {\n window.localStorage.removeItem(this.sessionStorageKey())\n }\n }\n}\n\nexport async function init(options: BlinqWidgetInitOptions) {\n const widget = new BlinqWidget(options)\n return widget.init()\n}\n\nexport async function initFromConfig(\n config: BlinqWidgetConfigFile | { default: BlinqWidgetConfigFile }\n) {\n return init(normalizedConfig(config))\n}\n\nexport async function createBlinqWidget(options: BlinqWidgetInitOptions) {\n return init(options)\n}\n","export interface ActionableElementHint {\n type: \"button\" | \"link\" | \"input\" | \"textarea\" | \"submit\"\n label?: string\n selector: string\n placeholder?: string\n href?: string\n form_selector?: string\n context_text?: string\n input_type?: string\n}\n\nexport type SemanticToolKind =\n | \"add-item\"\n | \"delete-item\"\n | \"toggle-item\"\n | \"clear-completed\"\n | \"open-link\"\n | \"submit-form\"\n | \"activate-element\"\n\nexport interface SemanticToolDescriptor {\n name: string\n kind: SemanticToolKind\n title: string\n description: string\n target_summary: string\n keywords: string[]\n input_schema?: Record<string, unknown>\n default_arguments?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}\n\nexport interface PageFormDescriptor {\n selector: string\n title: string\n context_text?: string\n field_selector?: string\n field_label?: string\n submit_selector?: string\n submit_label?: string\n}\n\nexport interface PageListItemActionDescriptor {\n kind: \"delete-item\" | \"toggle-item\" | \"open-link\"\n selector?: string\n href?: string\n label: string\n target_summary: string\n}\n\nexport interface PageListItemDescriptor {\n selector: string\n title: string\n context_text: string\n actions: PageListItemActionDescriptor[]\n}\n\nexport interface PageGraph {\n forms: PageFormDescriptor[]\n list_items: PageListItemDescriptor[]\n standalone_actions: ActionableElementHint[]\n}\n\nexport interface NormalizedPageContext {\n url: string\n title: string\n selection: string\n visible_text: string\n actionable_elements: ActionableElementHint[]\n page_graph: PageGraph\n semantic_tools: SemanticToolDescriptor[]\n}\n\nconst MAX_VISIBLE_TEXT_LENGTH = 2500\nconst MAX_ACTIONABLE_HINTS = 30\nconst MAX_SEMANTIC_TOOLS = 40\n\nfunction isBrowser() {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\"\n}\n\nfunction selectedText() {\n if (!isBrowser()) {\n return \"\"\n }\n return window.getSelection()?.toString().trim() ?? \"\"\n}\n\nfunction visibleText() {\n if (!isBrowser()) {\n return \"\"\n }\n return document.body.innerText.replace(/\\s+/g, \" \").trim().slice(0, MAX_VISIBLE_TEXT_LENGTH)\n}\n\nfunction normalizedText(value: string | null | undefined) {\n return (value ?? \"\").replace(/\\s+/g, \" \").trim()\n}\n\nfunction normalizedWords(...values: Array<string | null | undefined>) {\n return Array.from(\n new Set(\n values\n .flatMap((value) => normalizedText(value).toLowerCase().split(/[^a-zа-я0-9]+/i))\n .filter((part) => part.length >= 2)\n )\n )\n}\n\nfunction escapeSelectorValue(value: string) {\n if (typeof CSS !== \"undefined\" && typeof CSS.escape === \"function\") {\n return CSS.escape(value)\n }\n return value.replace(/[\"\\\\]/g, \"\\\\$&\")\n}\n\nfunction nthOfType(element: Element) {\n let index = 1\n let sibling = element.previousElementSibling\n while (sibling) {\n if (sibling.tagName === element.tagName) {\n index += 1\n }\n sibling = sibling.previousElementSibling\n }\n return index\n}\n\nfunction buildPathSelector(element: Element) {\n const segments: string[] = []\n let current: Element | null = element\n\n while (current && segments.length < 4 && current !== document.body) {\n const tag = current.tagName.toLowerCase()\n segments.unshift(`${tag}:nth-of-type(${nthOfType(current)})`)\n current = current.parentElement\n }\n\n return segments.length > 0 ? `body > ${segments.join(\" > \")}` : null\n}\n\nfunction selectorForElement(element: Element | null): string | null {\n if (!element || !(element instanceof Element)) {\n return null\n }\n\n if (element.id) {\n return `#${escapeSelectorValue(element.id)}`\n }\n\n const dataTestId = element.getAttribute(\"data-testid\")\n if (dataTestId) {\n return `[data-testid=\"${escapeSelectorValue(dataTestId)}\"]`\n }\n\n const name = element.getAttribute(\"name\")\n if (name) {\n return `${element.tagName.toLowerCase()}[name=\"${escapeSelectorValue(name)}\"]`\n }\n\n const ariaLabel = element.getAttribute(\"aria-label\")\n if (ariaLabel) {\n return `${element.tagName.toLowerCase()}[aria-label=\"${escapeSelectorValue(ariaLabel)}\"]`\n }\n\n if (\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLButtonElement\n ) {\n const placeholder = element.getAttribute(\"placeholder\")\n if (placeholder) {\n return `${element.tagName.toLowerCase()}[placeholder=\"${escapeSelectorValue(placeholder)}\"]`\n }\n }\n\n return buildPathSelector(element)\n}\n\nfunction contextTextForElement(element: Element) {\n const contextualContainer =\n element.closest(\"li, tr, [role='listitem'], [data-testid], article, section, form\") ??\n element.parentElement\n\n if (!contextualContainer) {\n return undefined\n }\n\n const text = normalizedText(contextualContainer.textContent)\n if (!text) {\n return undefined\n }\n\n return text.slice(0, 240)\n}\n\nfunction hintFromElement(element: Element): ActionableElementHint | null {\n const selector = selectorForElement(element)\n if (!selector) {\n return null\n }\n\n const formSelector = selectorForElement(element.closest(\"form\"))\n const textContent = normalizedText(element.textContent)\n const contextText = contextTextForElement(element)\n\n if (element instanceof HTMLAnchorElement && element.href) {\n return {\n type: \"link\",\n label: textContent || element.getAttribute(\"aria-label\") || element.href,\n selector,\n href: element.href,\n form_selector: formSelector ?? undefined,\n context_text: contextText,\n }\n }\n\n if (element instanceof HTMLTextAreaElement) {\n return {\n type: \"textarea\",\n label: textContent || element.getAttribute(\"aria-label\") || undefined,\n selector,\n placeholder: element.placeholder || undefined,\n form_selector: formSelector ?? undefined,\n context_text: contextText,\n }\n }\n\n if (element instanceof HTMLInputElement) {\n const type = element.type === \"submit\" ? \"submit\" : \"input\"\n return {\n type,\n label: textContent || element.value || element.getAttribute(\"aria-label\") || undefined,\n selector,\n placeholder: element.placeholder || undefined,\n form_selector: formSelector ?? undefined,\n context_text: contextText,\n input_type: element.type || undefined,\n }\n }\n\n if (element instanceof HTMLButtonElement || element.getAttribute(\"role\") === \"button\") {\n return {\n type: element instanceof HTMLButtonElement && element.type === \"submit\" ? \"submit\" : \"button\",\n label: textContent || element.getAttribute(\"aria-label\") || undefined,\n selector,\n form_selector: formSelector ?? undefined,\n context_text: contextText,\n }\n }\n\n return null\n}\n\nfunction collectActionableElements() {\n if (!isBrowser()) {\n return []\n }\n\n const elements = Array.from(\n document.querySelectorAll(\"button, a[href], input:not([type='hidden']), textarea, [role='button']\")\n )\n\n const hints: ActionableElementHint[] = []\n for (const element of elements) {\n const hint = hintFromElement(element)\n if (!hint) {\n continue\n }\n hints.push(hint)\n if (hints.length >= MAX_ACTIONABLE_HINTS) {\n break\n }\n }\n return hints\n}\n\nfunction slugPart(value: string) {\n return normalizedText(value)\n .toLowerCase()\n .replace(/[^a-zа-я0-9]+/gi, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 48)\n}\n\nfunction hashValue(value: string) {\n let hash = 0\n for (let index = 0; index < value.length; index += 1) {\n hash = (hash * 31 + value.charCodeAt(index)) >>> 0\n }\n return hash.toString(36)\n}\n\nfunction makeToolName(kind: SemanticToolKind, seed: string) {\n const slug = slugPart(seed) || \"target\"\n return `blinq.semantic.${kind}.${slug}.${hashValue(`${kind}:${seed}`)}`\n}\n\nfunction looksLikeAddLabel(value: string) {\n const text = value.toLowerCase()\n return /(добав|add|create|new|созда|қос|енгіз)/.test(text)\n}\n\nfunction looksLikeDeleteLabel(value: string) {\n const text = value.toLowerCase()\n return /(удал|delete|remove|өшір|жой)/.test(text)\n}\n\nfunction looksLikeClearCompletedLabel(value: string) {\n const text = value.toLowerCase()\n return /(очист|clear|тазала).*(выполн|completed|аяқталған)|(completed).*(clear|remove)/.test(text)\n}\n\nfunction looksLikeGenericActionLabel(value: string) {\n const text = value.toLowerCase()\n return /(open|view|edit|archive|start|run|save|send|submit|launch|continue|next|apply|confirm|перейд|открой|посмотр|измен|архив|запуст|сохран|отправ|продолж|далее|примен|подтверд|аш|өт|сақта|жібер|жалғастыр|таңда)/.test(\n text\n )\n}\n\nfunction buttonLikeText(element: Element) {\n if (element instanceof HTMLInputElement) {\n return normalizedText(element.value || element.getAttribute(\"aria-label\"))\n }\n return normalizedText(element.textContent || element.getAttribute(\"aria-label\"))\n}\n\nfunction deriveItemTitle(container: Element) {\n const cloned = container.cloneNode(true) as Element\n cloned.querySelectorAll(\"button, a, [role='button']\").forEach((node) => node.remove())\n const text = normalizedText(cloned.textContent)\n if (text) {\n return text.slice(0, 120)\n }\n return normalizedText(container.textContent).slice(0, 120)\n}\n\nfunction collectForms(): PageFormDescriptor[] {\n if (!isBrowser()) {\n return []\n }\n\n const forms = Array.from(document.querySelectorAll(\"form\")).slice(0, 8)\n const collected: PageFormDescriptor[] = []\n\n for (const form of forms) {\n const selector = selectorForElement(form)\n if (!selector) {\n continue\n }\n const field = form.querySelector<HTMLInputElement | HTMLTextAreaElement>(\n \"input:not([type='hidden']):not([type='checkbox']):not([type='radio']):not([type='submit']), textarea\"\n )\n const submit = form.querySelector<HTMLButtonElement | HTMLInputElement>(\n \"button[type='submit'], input[type='submit'], button:not([type])\"\n )\n const fieldSelector = selectorForElement(field)\n const submitSelector = selectorForElement(submit)\n const fieldLabel =\n normalizedText(field?.getAttribute(\"aria-label\")) ||\n normalizedText(field?.getAttribute(\"placeholder\")) ||\n normalizedText(field?.getAttribute(\"name\"))\n const submitLabel = submit ? buttonLikeText(submit) : \"\"\n const title = submitLabel || fieldLabel || normalizedText(form.getAttribute(\"aria-label\")) || selector\n\n collected.push({\n selector,\n title,\n context_text: contextTextForElement(form),\n field_selector: fieldSelector ?? undefined,\n field_label: fieldLabel || undefined,\n submit_selector: submitSelector ?? undefined,\n submit_label: submitLabel || undefined,\n })\n }\n\n return collected\n}\n\nfunction collectListItems(): PageListItemDescriptor[] {\n if (!isBrowser()) {\n return []\n }\n\n const candidates = Array.from(\n document.querySelectorAll(\"li, [role='listitem'], tr, [data-testid='todo-item']\")\n ).slice(0, 20)\n\n const items: PageListItemDescriptor[] = []\n for (const container of candidates) {\n const selector = selectorForElement(container)\n if (!selector) {\n continue\n }\n\n const contextText = normalizedText(container.textContent)\n if (!contextText) {\n continue\n }\n\n const actions: PageListItemActionDescriptor[] = []\n\n const toggleControl = container.querySelector<HTMLInputElement>(\"input[type='checkbox']\")\n const toggleSelector = selectorForElement(toggleControl)\n if (toggleSelector) {\n actions.push({\n kind: \"toggle-item\",\n selector: toggleSelector,\n label: \"Отметить задачу\",\n target_summary: contextText.slice(0, 160),\n })\n }\n\n const deleteButton = Array.from(\n container.querySelectorAll<HTMLButtonElement | HTMLAnchorElement | HTMLInputElement>(\n \"button, a, input[type='button'], input[type='submit']\"\n )\n ).find((element) => looksLikeDeleteLabel(buttonLikeText(element)))\n const deleteSelector = selectorForElement(deleteButton ?? null)\n if (deleteSelector) {\n actions.push({\n kind: \"delete-item\",\n selector: deleteSelector,\n label: buttonLikeText(deleteButton ?? container) || \"Удалить элемент\",\n target_summary: contextText.slice(0, 160),\n })\n }\n\n const openLink = Array.from(container.querySelectorAll<HTMLAnchorElement>(\"a[href]\"))[0]\n const openSelector = selectorForElement(openLink)\n if (openSelector && openLink?.href) {\n actions.push({\n kind: \"open-link\",\n selector: openSelector,\n href: openLink.href,\n label: buttonLikeText(openLink) || openLink.href,\n target_summary: contextText.slice(0, 160),\n })\n }\n\n if (actions.length === 0) {\n continue\n }\n\n items.push({\n selector,\n title: deriveItemTitle(container),\n context_text: contextText.slice(0, 160),\n actions,\n })\n }\n\n return items\n}\n\nfunction collectSemanticTools(\n actionableElements: ActionableElementHint[],\n pageGraph: PageGraph\n): SemanticToolDescriptor[] {\n const tools: SemanticToolDescriptor[] = []\n const usedSelectors = new Set<string>()\n const usedHrefs = new Set<string>()\n\n for (const form of pageGraph.forms) {\n if (form.field_selector && (form.submit_selector || form.selector)) {\n const submitSeed = `${form.selector}:${form.submit_selector ?? form.title}`\n if (looksLikeAddLabel(form.submit_label || form.title)) {\n tools.push({\n name: makeToolName(\"add-item\", submitSeed),\n kind: \"add-item\",\n title: \"Добавить элемент\",\n description: `Добавить новый элемент через ${form.title}.`,\n target_summary: form.context_text || form.title,\n keywords: normalizedWords(form.title, form.field_label, form.submit_label, \"add create new добавить создать қос енгіз\"),\n input_schema: {\n type: \"object\",\n properties: {\n value: { type: \"string\" },\n },\n required: [\"value\"],\n },\n metadata: {\n field_selector: form.field_selector,\n submit_selector: form.submit_selector,\n form_selector: form.selector,\n field_label: form.field_label,\n },\n })\n }\n\n if (form.submit_selector) {\n usedSelectors.add(form.submit_selector)\n tools.push({\n name: makeToolName(\"submit-form\", submitSeed),\n kind: \"submit-form\",\n title: form.submit_label ? `Отправить: ${form.submit_label}` : \"Отправить форму\",\n description: `Отправить форму ${form.title}.`,\n target_summary: form.context_text || form.title,\n keywords: normalizedWords(form.title, form.submit_label, \"submit send save отправить сохранить сақта жібер\"),\n metadata: {\n selector: form.selector,\n submit_selector: form.submit_selector,\n form_selector: form.selector,\n },\n })\n }\n\n usedSelectors.add(form.selector)\n if (form.field_selector) {\n usedSelectors.add(form.field_selector)\n }\n }\n }\n\n for (const item of pageGraph.list_items) {\n for (const action of item.actions) {\n const seed = `${item.selector}:${action.kind}:${action.selector ?? action.href ?? item.title}`\n if (action.kind === \"delete-item\" && action.selector) {\n usedSelectors.add(action.selector)\n tools.push({\n name: makeToolName(\"delete-item\", seed),\n kind: \"delete-item\",\n title: `Удалить: ${item.title}`,\n description: `Удалить элемент ${item.title}.`,\n target_summary: item.context_text,\n keywords: normalizedWords(item.title, item.context_text, action.label, \"delete remove удалить өшір жой\"),\n metadata: {\n selector: action.selector,\n item_title: item.title,\n item_context: item.context_text,\n },\n })\n }\n\n if (action.kind === \"toggle-item\" && action.selector) {\n usedSelectors.add(action.selector)\n tools.push({\n name: makeToolName(\"toggle-item\", seed),\n kind: \"toggle-item\",\n title: `Изменить статус: ${item.title}`,\n description: `Переключить состояние выполнения для ${item.title}.`,\n target_summary: item.context_text,\n keywords: normalizedWords(item.title, item.context_text, \"toggle complete check uncheck отметить выполнить белгіле аяқта\"),\n metadata: {\n selector: action.selector,\n item_title: item.title,\n item_context: item.context_text,\n },\n })\n }\n\n if (action.kind === \"open-link\" && action.href) {\n if (action.selector) {\n usedSelectors.add(action.selector)\n }\n usedHrefs.add(action.href)\n tools.push({\n name: makeToolName(\"open-link\", seed),\n kind: \"open-link\",\n title: `Открыть: ${item.title}`,\n description: `Открыть ссылку для ${item.title}.`,\n target_summary: item.context_text,\n keywords: normalizedWords(item.title, item.context_text, action.label, action.href, \"open link перейти открыть аш өту\"),\n metadata: {\n href: action.href,\n selector: action.selector,\n },\n })\n }\n }\n }\n\n for (const hint of actionableElements) {\n const label = normalizedText(hint.label)\n const contextText = normalizedText(hint.context_text)\n const selector = hint.selector\n\n if (usedSelectors.has(selector)) {\n continue\n }\n\n if (hint.type === \"button\" && label && looksLikeClearCompletedLabel(`${label} ${hint.context_text ?? \"\"}`)) {\n usedSelectors.add(selector)\n tools.push({\n name: makeToolName(\"clear-completed\", `${selector}:${label}`),\n kind: \"clear-completed\",\n title: label,\n description: `Очистить выполненные элементы через ${label}.`,\n target_summary: hint.context_text || label,\n keywords: normalizedWords(label, hint.context_text, \"clear completed очистить выполненные тазалау аяқталған\"),\n metadata: {\n selector,\n },\n })\n }\n\n if (hint.type === \"link\" && hint.href) {\n if (usedHrefs.has(hint.href)) {\n continue\n }\n usedSelectors.add(selector)\n usedHrefs.add(hint.href)\n tools.push({\n name: makeToolName(\"open-link\", `${selector}:${hint.href}`),\n kind: \"open-link\",\n title: label || hint.href,\n description: `Открыть ссылку ${label || hint.href}.`,\n target_summary: hint.context_text || label || hint.href,\n keywords: normalizedWords(label, hint.href, hint.context_text, \"open link перейти открыть аш өту\"),\n metadata: {\n href: hint.href,\n selector,\n },\n })\n }\n\n if (hint.type === \"input\" && hint.input_type === \"checkbox\") {\n usedSelectors.add(selector)\n tools.push({\n name: makeToolName(\"toggle-item\", `${selector}:${label}:${contextText}`),\n kind: \"toggle-item\",\n title: label || \"Переключить флажок\",\n description: `Переключить чекбокс или переключатель ${label || selector}.`,\n target_summary: contextText || label || selector,\n keywords: normalizedWords(label, contextText, \"toggle complete check uncheck enable disable включи выключи отметь сними\"),\n metadata: {\n selector,\n item_title: label || contextText || selector,\n item_context: contextText || label || selector,\n },\n })\n }\n\n if (hint.type === \"submit\" && (hint.form_selector || selector)) {\n usedSelectors.add(selector)\n if (hint.form_selector) {\n usedSelectors.add(hint.form_selector)\n }\n tools.push({\n name: makeToolName(\"submit-form\", `${hint.form_selector ?? selector}:${label || contextText}`),\n kind: \"submit-form\",\n title: label || \"Отправить форму\",\n description: `Отправить форму через ${label || selector}.`,\n target_summary: contextText || label || selector,\n keywords: normalizedWords(label, contextText, \"submit send save отправить сохранить сақта жібер\"),\n metadata: {\n selector: hint.form_selector || selector,\n submit_selector: selector,\n form_selector: hint.form_selector || selector,\n },\n })\n }\n\n if (\n hint.type === \"button\" &&\n label &&\n !looksLikeDeleteLabel(`${label} ${contextText}`) &&\n !looksLikeClearCompletedLabel(`${label} ${contextText}`) &&\n looksLikeGenericActionLabel(`${label} ${contextText}`)\n ) {\n usedSelectors.add(selector)\n tools.push({\n name: makeToolName(\"activate-element\", `${selector}:${label}:${contextText}`),\n kind: \"activate-element\",\n title: label,\n description: `Выполнить действие страницы: ${label}.`,\n target_summary: contextText || label,\n keywords: normalizedWords(label, contextText, \"click press activate нажми кликни бас таңда\"),\n metadata: {\n selector,\n label,\n },\n })\n }\n }\n\n return tools.slice(0, MAX_SEMANTIC_TOOLS)\n}\n\nexport function collectNormalizedPageContext(): NormalizedPageContext {\n const actionableElements = collectActionableElements()\n const pageGraph: PageGraph = {\n forms: collectForms(),\n list_items: collectListItems(),\n standalone_actions: actionableElements.filter(\n (hint) =>\n hint.type === \"button\" ||\n hint.type === \"submit\" ||\n (hint.type === \"input\" && hint.input_type === \"checkbox\")\n ),\n }\n const semanticTools = collectSemanticTools(actionableElements, pageGraph)\n\n return {\n url: isBrowser() ? window.location.href : \"\",\n title: isBrowser() ? document.title : \"\",\n selection: selectedText(),\n visible_text: visibleText(),\n actionable_elements: actionableElements,\n page_graph: pageGraph,\n semantic_tools: semanticTools,\n }\n}\n","import {\n collectNormalizedPageContext,\n type NormalizedPageContext,\n type SemanticToolDescriptor,\n} from \"./page-capabilities\"\n\nexport type RuntimeMode =\n | \"native-webmcp-active\"\n | \"blinq-page-tools-active\"\n | \"read-only-fallback\"\n\nexport interface ToolCapability {\n name: string\n description: string\n read_only: boolean\n}\n\nexport interface RuntimeCapability {\n mode: RuntimeMode\n native_webmcp_supported: boolean\n embedded_page_tools_supported: boolean\n write_requires_confirmation: boolean\n tool_capabilities: ToolCapability[]\n}\n\nexport type {\n ActionableElementHint,\n NormalizedPageContext,\n PageGraph,\n PageFormDescriptor,\n PageListItemDescriptor,\n SemanticToolDescriptor,\n} from \"./page-capabilities\"\nexport { collectNormalizedPageContext } from \"./page-capabilities\"\n\nexport interface ToolExecutionRequest {\n tool_name: string\n display_name?: string\n target_summary?: string\n requires_confirmation?: boolean\n arguments: Record<string, unknown>\n}\n\nexport interface ToolExecutionOutcome {\n status: \"success\" | \"cancelled\" | \"error\"\n result?: Record<string, unknown>\n error?: string\n}\n\nexport interface PageHighlightTarget {\n selector: string\n label?: string\n}\n\ninterface NativeModelContextTool {\n name: string\n description: string\n inputSchema?: Record<string, unknown>\n annotations?: {\n readOnlyHint?: boolean\n }\n execute: (input: Record<string, unknown>) => Promise<unknown>\n}\n\ninterface NativeModelContext {\n registerTool: (\n tool: NativeModelContextTool,\n options?: {\n signal?: AbortSignal\n }\n ) => void\n}\n\ntype NavigatorWithModelContext = Navigator & {\n modelContext?: NativeModelContext\n}\n\ntype ToolDefinition = {\n capability: ToolCapability\n inputSchema?: Record<string, unknown>\n describeTarget?: (input: Record<string, unknown>) => string\n execute: (input: Record<string, unknown>) => Promise<Record<string, unknown>>\n}\n\ntype ConfirmationHandler = (request: {\n displayName: string\n targetSummary: string\n arguments: Record<string, unknown>\n}) => Promise<boolean>\n\nfunction isBrowser() {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\"\n}\n\nfunction selectedText() {\n if (!isBrowser()) {\n return \"\"\n }\n return window.getSelection()?.toString().trim() ?? \"\"\n}\n\nfunction normalizedText(value: string | null | undefined) {\n return (value ?? \"\").replace(/\\s+/g, \" \").trim()\n}\n\nfunction setFormFieldValue(\n target: HTMLInputElement | HTMLTextAreaElement,\n value: string\n) {\n const prototype =\n target instanceof HTMLTextAreaElement\n ? HTMLTextAreaElement.prototype\n : HTMLInputElement.prototype\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"value\")\n\n if (descriptor?.set) {\n descriptor.set.call(target, value)\n return\n }\n\n target.value = value\n}\n\nfunction associatedForm(target: HTMLElement) {\n return target instanceof HTMLFormElement ? target : (target.closest(\"form\") as HTMLFormElement | null)\n}\n\nfunction submitAssociatedForm(target: HTMLElement) {\n const form = associatedForm(target)\n\n if (!form) {\n throw new Error(\"Не найдена форма для выбранного элемента\")\n }\n\n const isSubmitter =\n target instanceof HTMLButtonElement ||\n (target instanceof HTMLInputElement && target.type === \"submit\")\n\n if (typeof form.requestSubmit === \"function\") {\n if (isSubmitter) {\n form.requestSubmit(target as HTMLButtonElement | HTMLInputElement)\n } else {\n form.requestSubmit()\n }\n return\n }\n\n const submitEvent = new Event(\"submit\", { bubbles: true, cancelable: true })\n const shouldContinue = form.dispatchEvent(submitEvent)\n if (shouldContinue) {\n form.submit()\n }\n}\n\nasync function waitForDomSettle() {\n await new Promise((resolve) => window.setTimeout(resolve, 80))\n}\n\nfunction bodyTextIncludes(query: string) {\n if (!isBrowser()) {\n return false\n }\n const haystack = normalizedText(document.body.innerText).toLowerCase()\n return haystack.includes(normalizedText(query).toLowerCase())\n}\n\nasync function verifyFormSubmission(target: HTMLElement) {\n const form = associatedForm(target)\n if (!form) {\n throw new Error(\"Не найдена форма для проверки результата\")\n }\n\n const successSelector = normalizedText(form.dataset.blinqSuccessSelector)\n const successText = normalizedText(form.dataset.blinqSuccessText)\n\n if (successSelector) {\n const successTarget = document.querySelector<HTMLElement>(successSelector)\n if (!successTarget) {\n throw new Error(`Не найден элемент подтверждения: ${successSelector}`)\n }\n\n const content = normalizedText(successTarget.textContent || successTarget.innerText)\n if (successText && !content.toLowerCase().includes(successText.toLowerCase())) {\n throw new Error(\"Форма отправлена, но подтверждение сохранения не появилось\")\n }\n\n return {\n submitted: true,\n verified: true,\n success_selector: successSelector,\n success_text: content,\n }\n }\n\n if (successText) {\n if (!bodyTextIncludes(successText)) {\n throw new Error(\"Форма отправлена, но ожидаемый текст подтверждения не найден\")\n }\n\n return {\n submitted: true,\n verified: true,\n success_text: successText,\n }\n }\n\n return { submitted: true }\n}\n\nfunction findTarget(selector: string) {\n const target = document.querySelector<HTMLElement>(selector)\n if (!target) {\n throw new Error(`Элемент не найден: ${selector}`)\n }\n return target\n}\n\nfunction isDuplicateNativeToolError(error: unknown) {\n if (!(error instanceof Error)) {\n return false\n }\n const message = error.message.toLowerCase()\n return (\n message.includes(\"duplicate tool name\") ||\n message.includes(\"already registered\") ||\n message.includes(\"already exists\")\n )\n}\n\nfunction metadataString(\n descriptor: SemanticToolDescriptor,\n key: string\n) {\n const value = descriptor.metadata?.[key]\n return typeof value === \"string\" ? value : \"\"\n}\n\nfunction buildSemanticToolDefinition(\n descriptor: SemanticToolDescriptor\n): ToolDefinition | null {\n const summary = descriptor.target_summary || descriptor.description\n\n if (descriptor.kind === \"add-item\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n inputSchema: descriptor.input_schema,\n describeTarget: () => summary,\n execute: async (input) => {\n const fieldSelector = metadataString(descriptor, \"field_selector\")\n const submitSelector = metadataString(descriptor, \"submit_selector\")\n const formSelector = metadataString(descriptor, \"form_selector\")\n const value = String(input.value ?? \"\").trim()\n\n if (!fieldSelector || !value) {\n throw new Error(\"Для добавления нужен селектор поля и значение\")\n }\n\n const fieldTarget = findTarget(fieldSelector) as HTMLInputElement | HTMLTextAreaElement\n fieldTarget.focus()\n setFormFieldValue(fieldTarget, value)\n fieldTarget.dispatchEvent(new Event(\"input\", { bubbles: true }))\n fieldTarget.dispatchEvent(new Event(\"change\", { bubbles: true }))\n\n const submitTarget = submitSelector\n ? findTarget(submitSelector)\n : formSelector\n ? findTarget(formSelector)\n : fieldTarget\n submitAssociatedForm(submitTarget)\n await waitForDomSettle()\n\n if (!bodyTextIncludes(value)) {\n throw new Error(`Не удалось подтвердить, что элемент \"${value}\" появился на странице`)\n }\n\n return { success: true, value, verified: true }\n },\n }\n }\n\n if (descriptor.kind === \"delete-item\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n describeTarget: () => summary,\n execute: async () => {\n const selector = metadataString(descriptor, \"selector\")\n const itemTitle = metadataString(descriptor, \"item_title\") || summary\n findTarget(selector).click()\n await waitForDomSettle()\n\n if (itemTitle && bodyTextIncludes(itemTitle)) {\n throw new Error(`Элемент \"${itemTitle}\" всё ещё виден после удаления`)\n }\n\n return { success: true, verified: true }\n },\n }\n }\n\n if (descriptor.kind === \"toggle-item\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n describeTarget: () => summary,\n execute: async () => {\n const selector = metadataString(descriptor, \"selector\")\n const target = findTarget(selector)\n if (!(target instanceof HTMLInputElement) || target.type !== \"checkbox\") {\n throw new Error(\"Для переключения нужен селектор чекбокса\")\n }\n\n const before = target.checked\n target.click()\n await waitForDomSettle()\n\n if (target.checked === before) {\n throw new Error(\"Состояние чекбокса не изменилось\")\n }\n\n return { success: true, checked: target.checked, verified: true }\n },\n }\n }\n\n if (descriptor.kind === \"clear-completed\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n describeTarget: () => summary,\n execute: async () => {\n const selector = metadataString(descriptor, \"selector\")\n const checkedBefore = document.querySelectorAll<HTMLInputElement>(\"input[type='checkbox']:checked\").length\n findTarget(selector).click()\n await waitForDomSettle()\n const checkedAfter = document.querySelectorAll<HTMLInputElement>(\"input[type='checkbox']:checked\").length\n\n if (checkedAfter >= checkedBefore && checkedBefore > 0) {\n throw new Error(\"Выполненные элементы не были очищены\")\n }\n\n return { success: true, checked_before: checkedBefore, checked_after: checkedAfter, verified: true }\n },\n }\n }\n\n if (descriptor.kind === \"open-link\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n describeTarget: () => summary,\n execute: async () => {\n const href = metadataString(descriptor, \"href\")\n if (!href) {\n throw new Error(\"Для открытия ссылки нужен адрес href\")\n }\n return { success: true, href, deferred_navigation: true }\n },\n }\n }\n\n if (descriptor.kind === \"submit-form\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n describeTarget: () => summary,\n execute: async () => {\n const selector = metadataString(descriptor, \"form_selector\") || metadataString(descriptor, \"selector\")\n const target = findTarget(selector)\n submitAssociatedForm(target)\n await waitForDomSettle()\n return { success: true, selector, ...(await verifyFormSubmission(target)) }\n },\n }\n }\n\n if (descriptor.kind === \"activate-element\") {\n return {\n capability: {\n name: descriptor.name,\n description: descriptor.description,\n read_only: false,\n },\n describeTarget: () => summary,\n execute: async () => {\n const selector = metadataString(descriptor, \"selector\")\n findTarget(selector).click()\n return { success: true, selector }\n },\n }\n }\n\n return null\n}\n\nexport function detectNativeWebMcpSupport() {\n if (!isBrowser() || !window.isSecureContext) {\n return false\n }\n const navigatorWithModelContext = navigator as NavigatorWithModelContext\n return typeof navigatorWithModelContext.modelContext?.registerTool === \"function\"\n}\n\nexport class PageToolRegistry {\n private readonly confirmationHandler: ConfirmationHandler\n private readonly tools = new Map<string, ToolDefinition>()\n private readonly nativeRegistrations: AbortController[] = []\n private latestPageContext: NormalizedPageContext | null = null\n private nativeToolsActive = false\n private highlightLayer: HTMLDivElement | null = null\n private highlightTimer: number | null = null\n\n constructor(confirmationHandler: ConfirmationHandler) {\n this.confirmationHandler = confirmationHandler\n this.refreshToolCatalog()\n }\n\n private buildBaseTools() {\n const tools = new Map<string, ToolDefinition>()\n\n tools.set(\"blinq.read_visible_page_context\", {\n capability: {\n name: \"blinq.read_visible_page_context\",\n description: \"Прочитать текущий URL, заголовок страницы, видимый текст и каталог действий.\",\n read_only: true,\n },\n execute: async () => ({ page_context: this.collectPageContext() }),\n })\n\n tools.set(\"blinq.read_selection\", {\n capability: {\n name: \"blinq.read_selection\",\n description: \"Прочитать текст, который сейчас выделен на странице.\",\n read_only: true,\n },\n execute: async () => ({ selection: selectedText() }),\n })\n\n tools.set(\"blinq.highlight_element\", {\n capability: {\n name: \"blinq.highlight_element\",\n description: \"Подсветить элемент страницы по CSS-селектору, чтобы показать пользователю, о чём идёт речь.\",\n read_only: true,\n },\n inputSchema: {\n type: \"object\",\n properties: {\n selector: { type: \"string\" },\n label: { type: \"string\" },\n },\n required: [\"selector\"],\n },\n describeTarget: (input) => `Подсветить элемент: ${String(input.selector ?? \"\")}`,\n execute: async (input) => {\n const selector = String(input.selector ?? \"\")\n const label = String(input.label ?? \"\").trim() || undefined\n const highlighted = this.highlightTargets([{ selector, label }])\n if (!highlighted) {\n throw new Error(`Не удалось подсветить элемент: ${selector}`)\n }\n return { success: true, selector, label: label ?? null }\n },\n })\n\n tools.set(\"blinq.scroll_to_element\", {\n capability: {\n name: \"blinq.scroll_to_element\",\n description: \"Прокрутить страницу к первому элементу по CSS-селектору.\",\n read_only: false,\n },\n inputSchema: { type: \"object\", properties: { selector: { type: \"string\" } }, required: [\"selector\"] },\n describeTarget: (input) => `Прокрутка к элементу: ${String(input.selector ?? \"\")}`,\n execute: async (input) => {\n const selector = String(input.selector ?? \"\")\n const target = findTarget(selector)\n target.scrollIntoView({ behavior: \"smooth\", block: \"center\" })\n return { success: true, selector }\n },\n })\n\n tools.set(\"blinq.click_element\", {\n capability: {\n name: \"blinq.click_element\",\n description: \"Нажать первую подходящую кнопку, ссылку или интерактивный элемент.\",\n read_only: false,\n },\n inputSchema: { type: \"object\", properties: { selector: { type: \"string\" } }, required: [\"selector\"] },\n describeTarget: (input) => `Нажать элемент: ${String(input.selector ?? \"\")}`,\n execute: async (input) => {\n const selector = String(input.selector ?? \"\")\n const target = findTarget(selector)\n const isSubmitButton = target instanceof HTMLButtonElement && target.type === \"submit\"\n const isSubmitInput = target instanceof HTMLInputElement && target.type === \"submit\"\n if (isSubmitButton || isSubmitInput) {\n submitAssociatedForm(target)\n await waitForDomSettle()\n return { success: true, selector, ...(await verifyFormSubmission(target)) }\n }\n target.click()\n await waitForDomSettle()\n return { success: true, selector }\n },\n })\n\n tools.set(\"blinq.fill_field\", {\n capability: {\n name: \"blinq.fill_field\",\n description: \"Заполнить поле ввода или textarea по CSS-селектору.\",\n read_only: false,\n },\n inputSchema: {\n type: \"object\",\n properties: {\n selector: { type: \"string\" },\n value: { type: \"string\" },\n },\n required: [\"selector\", \"value\"],\n },\n describeTarget: (input) =>\n `Заполнить ${String(input.selector ?? \"\")} значением \"${String(input.value ?? \"\")}\"`,\n execute: async (input) => {\n const selector = String(input.selector ?? \"\")\n const value = String(input.value ?? \"\")\n const target = findTarget(selector) as HTMLInputElement | HTMLTextAreaElement\n target.focus()\n setFormFieldValue(target, value)\n target.dispatchEvent(new Event(\"input\", { bubbles: true }))\n target.dispatchEvent(new Event(\"change\", { bubbles: true }))\n await waitForDomSettle()\n return { success: true, selector, value, verified: target.value === value }\n },\n })\n\n tools.set(\"blinq.submit_form\", {\n capability: {\n name: \"blinq.submit_form\",\n description: \"Отправить ближайшую форму для выбранного селектора.\",\n read_only: false,\n },\n inputSchema: { type: \"object\", properties: { selector: { type: \"string\" } }, required: [\"selector\"] },\n describeTarget: (input) => `Отправить форму рядом с ${String(input.selector ?? \"\")}`,\n execute: async (input) => {\n const selector = String(input.selector ?? \"\")\n const target = findTarget(selector)\n submitAssociatedForm(target)\n await waitForDomSettle()\n return { success: true, selector, ...(await verifyFormSubmission(target)) }\n },\n })\n\n tools.set(\"blinq.open_link\", {\n capability: {\n name: \"blinq.open_link\",\n description: \"Открыть URL в текущей вкладке.\",\n read_only: false,\n },\n inputSchema: { type: \"object\", properties: { href: { type: \"string\" } }, required: [\"href\"] },\n describeTarget: (input) => `Открыть ${String(input.href ?? \"\")}`,\n execute: async (input) => {\n const href = String(input.href ?? \"\")\n if (!href) {\n throw new Error(\"Нужен адрес ссылки\")\n }\n return { success: true, href, deferred_navigation: true }\n },\n })\n\n return tools\n }\n\n private refreshToolCatalog() {\n const pageContext = collectNormalizedPageContext()\n const tools = this.buildBaseTools()\n\n for (const descriptor of pageContext.semantic_tools) {\n const tool = buildSemanticToolDefinition(descriptor)\n if (tool) {\n tools.set(descriptor.name, tool)\n }\n }\n\n this.tools.clear()\n for (const [name, tool] of tools) {\n this.tools.set(name, tool)\n }\n\n this.latestPageContext = pageContext\n return pageContext\n }\n\n private async onMutatingToolSuccess() {\n this.refreshToolCatalog()\n // A successful page action should stay successful even if native tool\n // re-registration is flaky in the current browser preview.\n if (this.nativeToolsActive) {\n try {\n await this.registerNativeTools()\n } catch {\n this.nativeToolsActive = false\n }\n }\n }\n\n collectPageContext() {\n return this.refreshToolCatalog()\n }\n\n getToolCapabilities() {\n this.refreshToolCatalog()\n return Array.from(this.tools.values()).map((tool) => tool.capability)\n }\n\n clearHighlights() {\n if (this.highlightTimer !== null) {\n window.clearTimeout(this.highlightTimer)\n this.highlightTimer = null\n }\n this.highlightLayer?.remove()\n this.highlightLayer = null\n }\n\n private ensureHighlightLayer() {\n if (this.highlightLayer) {\n return this.highlightLayer\n }\n const layer = document.createElement(\"div\")\n layer.setAttribute(\"data-blinq-highlight-layer\", \"true\")\n Object.assign(layer.style, {\n position: \"fixed\",\n inset: \"0\",\n pointerEvents: \"none\",\n zIndex: \"2147483646\",\n })\n document.body.appendChild(layer)\n this.highlightLayer = layer\n return layer\n }\n\n highlightTargets(\n targets: PageHighlightTarget[],\n options?: {\n durationMs?: number\n }\n ) {\n if (!isBrowser() || targets.length === 0) {\n return false\n }\n\n this.clearHighlights()\n const layer = this.ensureHighlightLayer()\n let highlightedCount = 0\n\n for (const target of targets) {\n if (!target.selector) {\n continue\n }\n\n let element: HTMLElement | null = null\n try {\n element = document.querySelector<HTMLElement>(target.selector)\n } catch {\n element = null\n }\n\n if (!element) {\n continue\n }\n\n const rect = element.getBoundingClientRect()\n if (rect.width <= 0 || rect.height <= 0) {\n continue\n }\n\n const frame = document.createElement(\"div\")\n Object.assign(frame.style, {\n position: \"fixed\",\n left: `${Math.max(rect.left - 6, 4)}px`,\n top: `${Math.max(rect.top - 6, 4)}px`,\n width: `${Math.max(rect.width + 12, 18)}px`,\n height: `${Math.max(rect.height + 12, 18)}px`,\n border: \"2px solid rgba(17, 17, 17, 0.92)\",\n borderRadius: \"16px\",\n background: \"rgba(17, 17, 17, 0.05)\",\n boxShadow: \"0 0 0 1px rgba(255, 255, 255, 0.85), 0 18px 38px rgba(17, 17, 17, 0.14)\",\n opacity: \"0\",\n transform: \"scale(0.985)\",\n transition: \"opacity 180ms ease, transform 180ms ease\",\n })\n\n const glow = document.createElement(\"div\")\n Object.assign(glow.style, {\n position: \"absolute\",\n inset: \"-8px\",\n borderRadius: \"20px\",\n border: \"1px solid rgba(17, 17, 17, 0.14)\",\n animation: \"blinq-highlight-pulse 1.2s ease-in-out infinite\",\n })\n frame.appendChild(glow)\n\n if (target.label) {\n const badge = document.createElement(\"div\")\n badge.textContent = target.label\n Object.assign(badge.style, {\n position: \"absolute\",\n top: \"-14px\",\n left: \"10px\",\n maxWidth: \"min(220px, 70vw)\",\n padding: \"4px 10px\",\n borderRadius: \"999px\",\n background: \"#111111\",\n color: \"#ffffff\",\n fontFamily:\n \"\\\"Inter\\\", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \\\"Segoe UI\\\", sans-serif\",\n fontSize: \"11px\",\n fontWeight: \"600\",\n lineHeight: \"1.3\",\n whiteSpace: \"nowrap\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n boxShadow: \"0 8px 18px rgba(17, 17, 17, 0.16)\",\n })\n frame.appendChild(badge)\n }\n\n layer.appendChild(frame)\n window.requestAnimationFrame(() => {\n frame.style.opacity = \"1\"\n frame.style.transform = \"scale(1)\"\n })\n highlightedCount += 1\n }\n\n if (!document.getElementById(\"blinq-highlight-style\")) {\n const style = document.createElement(\"style\")\n style.id = \"blinq-highlight-style\"\n style.textContent = `\n @keyframes blinq-highlight-pulse {\n 0%, 100% { opacity: 0.55; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.02); }\n }\n `\n document.head.appendChild(style)\n }\n\n if (highlightedCount === 0) {\n this.clearHighlights()\n return false\n }\n\n this.highlightTimer = window.setTimeout(() => {\n this.clearHighlights()\n }, options?.durationMs ?? 2200)\n\n return true\n }\n\n canExecuteWriteTools() {\n return isBrowser()\n }\n\n async executeTool(request: ToolExecutionRequest): Promise<ToolExecutionOutcome> {\n let tool = this.tools.get(request.tool_name)\n if (!tool) {\n this.refreshToolCatalog()\n tool = this.tools.get(request.tool_name)\n }\n\n if (!tool) {\n return {\n status: \"error\",\n error: `Неизвестный инструмент: ${request.tool_name}`,\n }\n }\n\n const displayName = request.display_name ?? tool.capability.name\n const targetSummary =\n request.target_summary ??\n tool.describeTarget?.(request.arguments) ??\n tool.capability.description\n\n const requiresConfirmation = request.requires_confirmation ?? !tool.capability.read_only\n\n if (!tool.capability.read_only && requiresConfirmation) {\n const confirmed = await this.confirmationHandler({\n displayName,\n targetSummary,\n arguments: request.arguments,\n })\n if (!confirmed) {\n return {\n status: \"cancelled\",\n error: \"Пользователь отклонил действие\",\n }\n }\n }\n\n try {\n const result = await tool.execute(request.arguments)\n if (!tool.capability.read_only) {\n await this.onMutatingToolSuccess()\n }\n return { status: \"success\", result }\n } catch (error) {\n return {\n status: \"error\",\n error: error instanceof Error ? error.message : \"Неизвестная ошибка действия на странице\",\n }\n }\n }\n\n unregisterNativeTools() {\n while (this.nativeRegistrations.length > 0) {\n this.nativeRegistrations.pop()?.abort()\n }\n this.nativeToolsActive = false\n }\n\n async registerNativeTools() {\n const navigatorWithModelContext = navigator as NavigatorWithModelContext\n const modelContext = navigatorWithModelContext.modelContext\n if (!window.isSecureContext || !modelContext?.registerTool) {\n return false\n }\n\n this.refreshToolCatalog()\n this.unregisterNativeTools()\n\n for (const [toolName, tool] of this.tools) {\n const controller = new AbortController()\n try {\n modelContext.registerTool(\n {\n name: toolName,\n description: tool.capability.description,\n inputSchema: tool.inputSchema,\n annotations: {\n readOnlyHint: tool.capability.read_only,\n },\n execute: async (input) => {\n const outcome = await this.executeTool({\n tool_name: toolName,\n display_name: tool.capability.name,\n arguments: input,\n })\n return outcome\n },\n },\n { signal: controller.signal }\n )\n this.nativeRegistrations.push(controller)\n } catch (error) {\n controller.abort()\n if (isDuplicateNativeToolError(error)) {\n this.nativeToolsActive = true\n continue\n }\n throw error\n }\n }\n\n this.nativeToolsActive = true\n return true\n }\n\n destroy() {\n this.clearHighlights()\n this.unregisterNativeTools()\n }\n}\n","import * as React from \"react\"\nimport {\n AssistantRuntimeProvider,\n MessagePrimitive,\n ThreadPrimitive,\n useExternalStoreRuntime,\n useMessage,\n type MessageStatus as AssistantMessageStatus,\n type ThreadMessageLike,\n} from \"@assistant-ui/react\"\n\ntype ClassValue = string | false | null | undefined\n\nfunction cn(...values: ClassValue[]) {\n return values.filter(Boolean).join(\" \")\n}\n\ntype ButtonVariant = \"default\" | \"outline\" | \"ghost\" | \"destructive\"\ntype ButtonSize = \"default\" | \"sm\" | \"icon\" | \"icon-sm\"\ntype BadgeVariant = \"default\" | \"outline\" | \"soft\" | \"accent\"\n\nfunction buttonClassName(variant: ButtonVariant = \"default\", size: ButtonSize = \"default\") {\n const variantClass =\n variant === \"outline\"\n ? \"blinq-button-outline\"\n : variant === \"ghost\"\n ? \"blinq-button-ghost\"\n : variant === \"destructive\"\n ? \"blinq-button-destructive\"\n : \"blinq-button-default\"\n\n const sizeClass =\n size === \"sm\"\n ? \"blinq-button-sm\"\n : size === \"icon\"\n ? \"blinq-button-icon\"\n : size === \"icon-sm\"\n ? \"blinq-button-icon-sm\"\n : \"blinq-button-md\"\n\n return cn(\"blinq-button\", variantClass, sizeClass)\n}\n\nfunction badgeClassName(variant: BadgeVariant = \"default\") {\n if (variant === \"outline\") {\n return \"blinq-badge-pill blinq-badge-pill-outline\"\n }\n if (variant === \"soft\") {\n return \"blinq-badge-pill blinq-badge-pill-soft\"\n }\n if (variant === \"accent\") {\n return \"blinq-badge-pill blinq-badge-pill-accent\"\n }\n return \"blinq-badge-pill blinq-badge-pill-default\"\n}\n\nfunction Button({\n className,\n variant,\n size,\n ...props\n}: React.ButtonHTMLAttributes<HTMLButtonElement> & {\n variant?: ButtonVariant\n size?: ButtonSize\n}) {\n return <button className={cn(buttonClassName(variant, size), className)} {...props} />\n}\n\nfunction Input({ className, ...props }: React.InputHTMLAttributes<HTMLInputElement>) {\n return <input className={cn(\"blinq-input\", className)} {...props} />\n}\n\nfunction Card({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={cn(\"blinq-card\", className)} {...props} />\n}\n\nfunction CardHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={cn(\"blinq-card-header\", className)} {...props} />\n}\n\nfunction CardTitle({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={cn(\"blinq-card-title\", className)} {...props} />\n}\n\nfunction CardDescription({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={cn(\"blinq-card-description\", className)} {...props} />\n}\n\nfunction CardContent({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={cn(\"blinq-card-content\", className)} {...props} />\n}\n\nfunction Badge({\n className,\n variant,\n ...props\n}: React.HTMLAttributes<HTMLDivElement> & {\n variant?: BadgeVariant\n}) {\n return <div className={cn(badgeClassName(variant), className)} {...props} />\n}\n\nfunction Separator({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={cn(\"blinq-separator\", className)} {...props} />\n}\n\nfunction LauncherIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"18\"\n height=\"18\"\n fill=\"none\"\n aria-hidden=\"true\"\n className=\"blinq-launcher-agent\"\n >\n <circle className=\"blinq-agent-orbit\" cx=\"12\" cy=\"12\" r=\"9\" />\n <circle className=\"blinq-agent-spark\" cx=\"18.6\" cy=\"8.2\" r=\"1.2\" />\n <path\n className=\"blinq-agent-antenna\"\n d=\"M12 4.8V6.8\"\n stroke=\"currentColor\"\n strokeWidth=\"1.6\"\n strokeLinecap=\"round\"\n />\n <circle className=\"blinq-agent-antenna-dot\" cx=\"12\" cy=\"4.1\" r=\"1.1\" fill=\"currentColor\" />\n <rect\n className=\"blinq-agent-head\"\n x=\"7\"\n y=\"7.4\"\n width=\"10\"\n height=\"9.2\"\n rx=\"3.2\"\n fill=\"currentColor\"\n />\n <circle className=\"blinq-agent-eye\" cx=\"10.2\" cy=\"11.3\" r=\"0.9\" fill=\"#111111\" />\n <circle className=\"blinq-agent-eye\" cx=\"13.8\" cy=\"11.3\" r=\"0.9\" fill=\"#111111\" />\n <path\n className=\"blinq-agent-mouth\"\n d=\"M10 14.2c.7.55 1.38.82 2 .82s1.3-.27 2-.82\"\n stroke=\"#111111\"\n strokeWidth=\"1.3\"\n strokeLinecap=\"round\"\n />\n <path\n className=\"blinq-agent-neck\"\n d=\"M10.2 17.1h3.6\"\n stroke=\"currentColor\"\n strokeWidth=\"1.4\"\n strokeLinecap=\"round\"\n />\n </svg>\n )\n}\n\nfunction CollapseIcon() {\n return (\n <svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" aria-hidden=\"true\">\n <path d=\"M6 12h12\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\nfunction MicrophoneIcon({ listening }: { listening: boolean }) {\n if (listening) {\n return (\n <svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" aria-hidden=\"true\">\n <rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"2.5\" fill=\"currentColor\" />\n </svg>\n )\n }\n\n return (\n <svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M12 3.75a2.75 2.75 0 0 1 2.75 2.75v5.25a2.75 2.75 0 1 1-5.5 0V6.5A2.75 2.75 0 0 1 12 3.75Z\"\n fill=\"currentColor\"\n />\n <path\n d=\"M7.5 10.5a.75.75 0 0 1 .75.75a3.75 3.75 0 1 0 7.5 0a.75.75 0 0 1 1.5 0A5.25 5.25 0 0 1 12.75 16.4V18.5H15a.75.75 0 0 1 0 1.5H9a.75.75 0 0 1 0-1.5h2.25v-2.1A5.25 5.25 0 0 1 6.75 11.25a.75.75 0 0 1 .75-.75Z\"\n fill=\"currentColor\"\n />\n </svg>\n )\n}\n\nfunction SendIcon() {\n return (\n <svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M5.5 12h11M12.5 5l6.5 7-6.5 7\"\n stroke=\"currentColor\"\n strokeWidth=\"1.8\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n )\n}\n\nfunction ThinkingSparkIcon() {\n return (\n <span className=\"blinq-thinking-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n )\n}\n\nexport interface WidgetMessageConversationItem {\n id: string\n type: \"message\"\n role: \"user\" | \"assistant\"\n text: string\n status: \"thinking\" | \"streaming\" | \"done\"\n}\n\nexport interface WidgetActionConversationItem {\n id: string\n type: \"action\"\n displayName: string\n targetSummary: string\n arguments: Record<string, unknown>\n state: \"pending\" | \"approved\" | \"declined\"\n}\n\nexport interface WidgetPlanStepItem {\n id: string\n title: string\n status: string\n kind: string\n}\n\nexport interface WidgetPlanConversationItem {\n id: string\n type: \"plan\"\n goal: string\n status: string\n progressLabel: string | null\n statusReason?: string | null\n expectedRoute?: string | null\n loopGuarded?: boolean\n currentStepIndex: number\n totalSteps: number\n approvalState: \"pending\" | \"approved\" | \"declined\"\n steps: WidgetPlanStepItem[]\n}\n\nexport type WidgetConversationItem =\n | WidgetMessageConversationItem\n | WidgetActionConversationItem\n | WidgetPlanConversationItem\n\nexport interface WidgetShellState {\n minimized: boolean\n assistantName: string\n runtimeLabel: string\n statusText: string\n showThinkingIndicator: boolean\n inputValue: string\n accentColor: string\n side: \"left\" | \"right\"\n isSending: boolean\n voiceSupported: boolean\n voiceListening: boolean\n voiceWaveform: number[]\n voiceDurationMs: number\n items: WidgetConversationItem[]\n}\n\ninterface WidgetEmbedShellProps {\n state: WidgetShellState\n onOpen(): void\n onCollapse(): void\n onInputChange(value: string): void\n onSubmit(): void\n onToggleVoice(): void\n onApproveAction(id: string): void\n onDeclineAction(id: string): void\n onApprovePlan(): void\n onDeclinePlan(): void\n}\n\nfunction isAssistantMessageRunning(status?: AssistantMessageStatus) {\n return status?.type === \"running\"\n}\n\nfunction itemToThreadMessage(item: WidgetConversationItem): ThreadMessageLike {\n if (item.type === \"message\") {\n return {\n id: item.id,\n role: item.role,\n status:\n item.role === \"assistant\"\n ? item.status === \"done\"\n ? { type: \"complete\", reason: \"stop\" }\n : { type: \"running\" }\n : undefined,\n content: item.text ? [{ type: \"text\", text: item.text }] : [],\n metadata: {\n custom: {\n blinqKind: \"message\",\n },\n },\n }\n }\n\n if (item.type === \"plan\") {\n return {\n id: item.id,\n role: \"assistant\",\n status:\n item.status === \"completed\"\n ? { type: \"complete\", reason: \"stop\" }\n : item.status === \"failed\"\n ? { type: \"incomplete\", reason: \"error\" }\n : { type: \"running\" },\n content: [{ type: \"data\", name: \"blinq-plan\", data: item }],\n metadata: {\n custom: {\n blinqKind: \"plan\",\n },\n },\n }\n }\n\n return {\n id: item.id,\n role: \"assistant\",\n status:\n item.state === \"approved\"\n ? { type: \"running\" }\n : { type: \"complete\", reason: \"stop\" },\n content: [{ type: \"data\", name: \"blinq-action\", data: item }],\n metadata: {\n custom: {\n blinqKind: \"action\",\n },\n },\n }\n}\n\nfunction conversationToThreadMessages(items: WidgetConversationItem[]) {\n return items.map(itemToThreadMessage)\n}\n\nfunction ThreadMessageBubble({\n accentColor,\n onApproveAction,\n onDeclineAction,\n onApprovePlan,\n onDeclinePlan,\n}: {\n accentColor: string\n onApproveAction(id: string): void\n onDeclineAction(id: string): void\n onApprovePlan(): void\n onDeclinePlan(): void\n}) {\n const role = useMessage((state) => state.role)\n const messageId = useMessage((state) => state.id)\n const status = useMessage((state) => state.status)\n const content = useMessage((state) => state.content)\n const isDataOnly =\n Array.isArray(content) &&\n content.length === 1 &&\n typeof content[0] !== \"string\" &&\n content[0]?.type === \"data\"\n const messageText = React.useMemo(\n () =>\n content\n .filter((part): part is Extract<typeof part, { type: \"text\" }> => typeof part !== \"string\" && part.type === \"text\")\n .map((part) => part.text)\n .join(\"\"),\n [content]\n )\n const [animateFreshText, setAnimateFreshText] = React.useState(false)\n const [hasAnimatedStreamingReveal, setHasAnimatedStreamingReveal] = React.useState(false)\n\n React.useEffect(() => {\n setAnimateFreshText(false)\n setHasAnimatedStreamingReveal(false)\n }, [messageId])\n\n React.useEffect(() => {\n if (\n role !== \"assistant\" ||\n isDataOnly ||\n !isAssistantMessageRunning(status) ||\n !messageText.trim() ||\n hasAnimatedStreamingReveal\n ) {\n return\n }\n\n setAnimateFreshText(true)\n setHasAnimatedStreamingReveal(true)\n const timeoutId = window.setTimeout(() => {\n setAnimateFreshText(false)\n }, 220)\n\n return () => window.clearTimeout(timeoutId)\n }, [role, isDataOnly, messageText, hasAnimatedStreamingReveal])\n\n return (\n <MessagePrimitive.Root\n className=\"blinq-message\"\n data-role={role}\n data-kind={isDataOnly ? \"artifact\" : \"bubble\"}\n data-status={status?.type ?? \"complete\"}\n >\n <MessagePrimitive.Parts>\n {({ part }) => {\n if (part.type === \"text\") {\n if (!part.text) {\n return null\n }\n\n return (\n <div\n className={cn(\n \"blinq-message-copy\",\n role === \"assistant\" && animateFreshText && \"blinq-message-copy-reveal\"\n )}\n >\n {part.text}\n </div>\n )\n }\n\n if (part.type === \"data\" && part.name === \"blinq-action\") {\n const actionItem = part.data as WidgetActionConversationItem\n return (\n <ActionCard\n item={actionItem}\n accentColor={accentColor}\n onApprove={() => onApproveAction(actionItem.id)}\n onDecline={() => onDeclineAction(actionItem.id)}\n />\n )\n }\n\n if (part.type === \"data\" && part.name === \"blinq-plan\") {\n return (\n <PlanCard\n item={part.data as WidgetPlanConversationItem}\n onApprove={onApprovePlan}\n onDecline={onDeclinePlan}\n />\n )\n }\n\n return null\n }}\n </MessagePrimitive.Parts>\n </MessagePrimitive.Root>\n )\n}\n\nfunction ThinkingPlaceholder() {\n return (\n <div className=\"blinq-message blinq-thinking-card\" data-role=\"assistant\" data-kind=\"bubble\">\n <div className=\"blinq-thinking\">\n <ThinkingSparkIcon />\n <span>Думаю над ответом</span>\n </div>\n </div>\n )\n}\n\nfunction formatRecordingDuration(durationMs: number) {\n const totalSeconds = Math.max(0, Math.floor(durationMs / 1000))\n const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, \"0\")\n const seconds = String(totalSeconds % 60).padStart(2, \"0\")\n return `${minutes}:${seconds}`\n}\n\nfunction VoiceWaveform({\n durationMs,\n samples,\n}: {\n durationMs: number\n samples: number[]\n}) {\n const waveform = samples.length > 0 ? samples : [0.18]\n\n return (\n <div className=\"blinq-recording-input\" role=\"status\" aria-live=\"polite\">\n <div className=\"blinq-recording-time\">{formatRecordingDuration(durationMs)}</div>\n <div className=\"blinq-recording-waveform\" aria-hidden=\"true\">\n {waveform.map((sample, index) => {\n const scale = Math.max(0.16, Math.min(1, sample))\n return (\n <span\n key={`voice-wave-${index}`}\n className=\"blinq-recording-waveform-bar\"\n style={{ transform: `scaleY(${scale})` }}\n />\n )\n })}\n </div>\n </div>\n )\n}\n\nfunction ActionCard({\n item,\n accentColor,\n onApprove,\n onDecline,\n}: {\n item: WidgetActionConversationItem\n accentColor: string\n onApprove(): void\n onDecline(): void\n}) {\n return (\n <Card\n className=\"blinq-action-card\"\n style={\n item.state === \"approved\"\n ? { borderColor: \"rgba(17, 17, 17, 0.22)\" }\n : item.state === \"declined\"\n ? { borderColor: \"rgba(17, 17, 17, 0.12)\" }\n : undefined\n }\n >\n <CardHeader>\n <CardTitle>{item.displayName}</CardTitle>\n <CardDescription>{item.targetSummary}</CardDescription>\n </CardHeader>\n <CardContent>\n <details className=\"blinq-action-details\">\n <summary>Показать детали действия</summary>\n <pre className=\"blinq-code\">{JSON.stringify(item.arguments, null, 2)}</pre>\n </details>\n {item.state !== \"pending\" ? (\n <div className=\"blinq-action-state\" data-state={item.state}>\n {item.state === \"approved\" ? \"Выполняю действие\" : \"Действие отклонено\"}\n </div>\n ) : null}\n {item.state === \"pending\" ? (\n <div className=\"blinq-actions\">\n <Button type=\"button\" variant=\"outline\" onClick={onDecline}>\n Отклонить\n </Button>\n <Button\n type=\"button\"\n onClick={onApprove}\n style={{\n background: accentColor,\n }}\n >\n Выполнить\n </Button>\n </div>\n ) : null}\n </CardContent>\n </Card>\n )\n}\n\nfunction PlanCard({\n item,\n onApprove,\n onDecline,\n}: {\n item: WidgetPlanConversationItem\n onApprove(): void\n onDecline(): void\n}) {\n return (\n <Card className=\"blinq-action-card blinq-plan-card\">\n <CardHeader>\n <div className=\"flex items-center justify-between gap-3\">\n <div>\n <CardTitle>План</CardTitle>\n <CardDescription>{item.goal}</CardDescription>\n </div>\n <Badge variant={item.status === \"completed\" ? \"default\" : item.status === \"failed\" ? \"outline\" : \"soft\"}>\n {item.status === \"completed\"\n ? \"Готово\"\n : item.status === \"failed\"\n ? \"Ошибка\"\n : item.status === \"awaiting_navigation\"\n ? \"Переход\"\n : \"В работе\"}\n </Badge>\n </div>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n {item.progressLabel ? <div className=\"blinq-action-state\">{item.progressLabel}</div> : null}\n {item.statusReason ? <div className=\"blinq-card-description\">{item.statusReason}</div> : null}\n <div className=\"space-y-2\">\n {item.steps.map((step, index) => (\n <div\n key={step.id}\n className=\"blinq-plan-step\"\n data-current={index === item.currentStepIndex ? \"true\" : \"false\"}\n data-status={step.status}\n >\n <span className=\"blinq-plan-step-index\">{index + 1}</span>\n <div className=\"blinq-plan-step-copy\">\n <div>{step.title}</div>\n <div className=\"blinq-plan-step-meta\">\n {step.status === \"completed\"\n ? \"Выполнено\"\n : step.status === \"failed\"\n ? \"Ошибка\"\n : step.status === \"cancelled\"\n ? \"Отменено\"\n : index === item.currentStepIndex\n ? \"Текущий шаг\"\n : \"Ожидает\"}\n </div>\n </div>\n </div>\n ))}\n </div>\n {item.approvalState === \"pending\" ? (\n <div className=\"blinq-actions\">\n <Button type=\"button\" variant=\"outline\" onClick={onDecline}>\n Отклонить\n </Button>\n <Button type=\"button\" onClick={onApprove}>\n Выполнить\n </Button>\n </div>\n ) : null}\n </CardContent>\n </Card>\n )\n}\n\nfunction AssistantConversationThread({\n items,\n showThinkingIndicator,\n accentColor,\n onApproveAction,\n onDeclineAction,\n onApprovePlan,\n onDeclinePlan,\n}: {\n items: WidgetConversationItem[]\n showThinkingIndicator: boolean\n accentColor: string\n onApproveAction(id: string): void\n onDeclineAction(id: string): void\n onApprovePlan(): void\n onDeclinePlan(): void\n}) {\n const messages = React.useMemo(() => conversationToThreadMessages(items), [items])\n const runtime = useExternalStoreRuntime({\n messages,\n isRunning: messages.some((message) => message.role === \"assistant\" && message.status?.type === \"running\"),\n convertMessage: (message) => message,\n onNew: async () => undefined,\n })\n const scrollRef = React.useRef<HTMLDivElement | null>(null)\n\n React.useEffect(() => {\n if (!scrollRef.current) {\n return\n }\n scrollRef.current.scrollTop = scrollRef.current.scrollHeight\n }, [items])\n\n const assistantMessageComponent = React.useMemo(\n () =>\n function AssistantMessageComponent() {\n return (\n <ThreadMessageBubble\n accentColor={accentColor}\n onApproveAction={onApproveAction}\n onDeclineAction={onDeclineAction}\n onApprovePlan={onApprovePlan}\n onDeclinePlan={onDeclinePlan}\n />\n )\n },\n [accentColor, onApproveAction, onDeclineAction, onApprovePlan, onDeclinePlan]\n )\n\n const userMessageComponent = React.useMemo(\n () =>\n function UserMessageComponent() {\n return (\n <ThreadMessageBubble\n accentColor={accentColor}\n onApproveAction={onApproveAction}\n onDeclineAction={onDeclineAction}\n onApprovePlan={onApprovePlan}\n onDeclinePlan={onDeclinePlan}\n />\n )\n },\n [accentColor, onApproveAction, onDeclineAction, onApprovePlan, onDeclinePlan]\n )\n\n return (\n <AssistantRuntimeProvider runtime={runtime}>\n <ThreadPrimitive.Root className=\"blinq-thread\">\n <ThreadPrimitive.Viewport ref={scrollRef} className=\"blinq-scroll blinq-thread-viewport\">\n <ThreadPrimitive.Messages\n components={{\n UserMessage: userMessageComponent,\n AssistantMessage: assistantMessageComponent,\n }}\n />\n {showThinkingIndicator ? <ThinkingPlaceholder /> : null}\n </ThreadPrimitive.Viewport>\n </ThreadPrimitive.Root>\n </AssistantRuntimeProvider>\n )\n}\n\nexport function WidgetEmbedShell({\n state,\n onOpen,\n onCollapse,\n onInputChange,\n onSubmit,\n onToggleVoice,\n onApproveAction,\n onDeclineAction,\n onApprovePlan,\n onDeclinePlan,\n}: WidgetEmbedShellProps) {\n return (\n <div\n className=\"blinq-shell\"\n data-side={state.side}\n style={{ [\"--blinq-accent\" as string]: state.accentColor }}\n >\n {!state.minimized ? (\n <div className=\"blinq-panel\">\n <div className=\"blinq-header\">\n <div className=\"blinq-header-row\">\n <div className=\"blinq-header-copy\">\n <div className=\"blinq-heading\">{state.assistantName}</div>\n </div>\n <Button\n type=\"button\"\n size=\"icon-sm\"\n variant=\"ghost\"\n aria-label=\"Свернуть виджет\"\n title=\"Свернуть виджет\"\n onClick={onCollapse}\n >\n <CollapseIcon />\n </Button>\n </div>\n {state.statusText ? <div className=\"blinq-status-line\">{state.statusText}</div> : null}\n </div>\n <AssistantConversationThread\n items={state.items}\n showThinkingIndicator={state.showThinkingIndicator}\n accentColor={state.accentColor}\n onApproveAction={onApproveAction}\n onDeclineAction={onDeclineAction}\n onApprovePlan={onApprovePlan}\n onDeclinePlan={onDeclinePlan}\n />\n\n <form\n className=\"blinq-composer\"\n onSubmit={(event) => {\n event.preventDefault()\n onSubmit()\n }}\n >\n <div className=\"blinq-composer-controls\">\n <div className=\"blinq-input-shell\">\n <Button\n type=\"button\"\n size=\"icon-sm\"\n variant={state.voiceListening ? \"destructive\" : \"ghost\"}\n className=\"blinq-input-mic\"\n aria-label={state.voiceListening ? \"Остановить голосовой ввод\" : \"Начать голосовой ввод\"}\n title={\n !state.voiceSupported\n ? \"Голосовой ввод не поддерживается в этом браузере\"\n : state.voiceListening\n ? \"Остановить запись\"\n : \"Начать голосовой ввод\"\n }\n disabled={!state.voiceSupported || state.isSending}\n onClick={onToggleVoice}\n >\n <MicrophoneIcon listening={state.voiceListening} />\n </Button>\n\n {state.voiceListening ? (\n <VoiceWaveform\n durationMs={state.voiceDurationMs}\n samples={state.voiceWaveform}\n />\n ) : (\n <Input\n value={state.inputValue}\n placeholder=\"Например: найди нужную кнопку или заполни форму\"\n onChange={(event) => onInputChange(event.currentTarget.value)}\n disabled={state.isSending}\n />\n )}\n\n <Button\n type=\"submit\"\n size=\"icon-sm\"\n className=\"blinq-input-send\"\n aria-label=\"Отправить сообщение\"\n title=\"Отправить сообщение\"\n disabled={state.isSending || state.voiceListening}\n >\n <SendIcon />\n </Button>\n </div>\n </div>\n </form>\n </div>\n ) : null}\n\n {state.minimized ? (\n <Button\n type=\"button\"\n size=\"icon\"\n className=\"blinq-launcher blinq-launcher-icon-only\"\n aria-label={`Открыть ${state.assistantName}`}\n title={`Открыть ${state.assistantName}`}\n onClick={onOpen}\n >\n <span className=\"blinq-launcher-badge\">\n <LauncherIcon />\n </span>\n </Button>\n ) : null}\n </div>\n )\n}\n","type VoiceCallbacks = {\n getLanguage: () => string\n onInterimTranscript: (text: string) => void\n onFinalTranscript: (text: string) => void\n onListeningChange: (isListening: boolean) => void\n onLevelChange: (level: number) => void\n onStatusChange: (status: string) => void\n onError: (message: string) => void\n}\n\ntype SpeechRecognitionAlternativeLike = {\n transcript: string\n}\n\ntype SpeechRecognitionResultLike = {\n isFinal: boolean\n length: number\n [index: number]: SpeechRecognitionAlternativeLike\n}\n\ntype SpeechRecognitionResultListLike = {\n length: number\n [index: number]: SpeechRecognitionResultLike\n}\n\ntype SpeechRecognitionEventLike = Event & {\n resultIndex: number\n results: SpeechRecognitionResultListLike\n}\n\ntype SpeechRecognitionErrorEventLike = Event & {\n error?: string\n message?: string\n}\n\ninterface SpeechRecognitionLike extends EventTarget {\n lang: string\n interimResults: boolean\n continuous: boolean\n maxAlternatives: number\n onresult: ((event: SpeechRecognitionEventLike) => void) | null\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null\n onend: (() => void) | null\n onstart: (() => void) | null\n start: () => void\n stop: () => void\n abort: () => void\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionLike\n\ntype SpeechRecognitionWindow = Window & {\n SpeechRecognition?: SpeechRecognitionConstructor\n webkitSpeechRecognition?: SpeechRecognitionConstructor\n}\n\nconst FILLER_PHRASES = [\n \"you know\",\n \"i mean\",\n \"sort of\",\n \"kind of\",\n \"and so on\",\n \"как бы\",\n \"в общем\",\n \"вообще-то\",\n \"это самое\",\n \"так сказать\",\n \"по сути\",\n \"скажем так\",\n \"и так далее\",\n \"на самом деле\",\n \"if you know\",\n \"basically\",\n \"literally\",\n \"actually\",\n \"really\",\n \"короче\",\n \"значит\",\n \"собственно\",\n \"просто\",\n \"ладно\",\n \"ну вот\",\n \"ну\",\n \"вот\",\n \"типа\",\n \"эм\",\n \"ээ\",\n \"эээ\",\n \"мм\",\n \"uh\",\n \"um\",\n \"er\",\n \"ah\",\n \"like\",\n \"well\",\n]\n\nfunction escapeRegex(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\nfunction normalizeWhitespace(text: string) {\n return text.replace(/\\s+/g, \" \").trim()\n}\n\nfunction removeFillerPhrases(text: string) {\n let cleaned = text\n for (const phrase of [...FILLER_PHRASES].sort((left, right) => right.length - left.length)) {\n const escaped = escapeRegex(phrase)\n const pattern = new RegExp(`(^|[\\\\s,.;:!?()\\\\[\\\\]{}-])${escaped}(?=$|[\\\\s,.;:!?()\\\\[\\\\]{}-])`, \"giu\")\n cleaned = cleaned.replace(pattern, (_match, boundary: string) => boundary || \" \")\n }\n return cleaned\n}\n\nfunction dedupeAdjacentWords(text: string) {\n const parts = text.split(/\\s+/)\n const nextParts: string[] = []\n let previousKey = \"\"\n\n for (const part of parts) {\n const wordKey = part.toLowerCase().replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\")\n if (wordKey && wordKey === previousKey) {\n continue\n }\n nextParts.push(part)\n previousKey = wordKey\n }\n\n return nextParts.join(\" \")\n}\n\nfunction normalizePunctuation(text: string) {\n return text\n .replace(/\\s+([,.;:!?])/g, \"$1\")\n .replace(/([,.;:!?])([^\\s])/g, \"$1 $2\")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\nexport function sanitizeSpokenText(text: string) {\n const cleaned = normalizePunctuation(\n dedupeAdjacentWords(removeFillerPhrases(normalizeWhitespace(text)))\n )\n return cleaned\n}\n\nexport function supportsVoiceInput() {\n if (typeof window === \"undefined\") {\n return false\n }\n const recognitionWindow = window as SpeechRecognitionWindow\n return Boolean(recognitionWindow.SpeechRecognition || recognitionWindow.webkitSpeechRecognition)\n}\n\nfunction recognitionConstructor() {\n if (typeof window === \"undefined\") {\n return null\n }\n const recognitionWindow = window as SpeechRecognitionWindow\n return (\n recognitionWindow.SpeechRecognition ||\n recognitionWindow.webkitSpeechRecognition ||\n null\n ) as SpeechRecognitionConstructor | null\n}\n\nfunction errorMessageForCode(code: string | undefined) {\n switch (code) {\n case \"not-allowed\":\n case \"service-not-allowed\":\n return \"Доступ к микрофону заблокирован.\"\n case \"audio-capture\":\n return \"Микрофон не найден.\"\n case \"network\":\n return \"Ошибка сети при распознавании речи.\"\n case \"no-speech\":\n return \"Речь не распознана.\"\n case \"aborted\":\n return \"Голосовой ввод был отменён.\"\n default:\n return \"Не удалось обработать голосовой ввод.\"\n }\n}\n\nexport class VoiceInputController {\n private readonly callbacks: VoiceCallbacks\n private readonly recognition: SpeechRecognitionLike | null\n private finalTranscript = \"\"\n private interimTranscript = \"\"\n private shouldSendOnEnd = false\n private listening = false\n private sessionActive = false\n private manualStopRequested = false\n private restartTimeoutId: number | null = null\n private statusAfterEnd = \"Голосовой ввод остановлен.\"\n private mediaStream: MediaStream | null = null\n private audioContext: AudioContext | null = null\n private analyser: AnalyserNode | null = null\n private sourceNode: MediaStreamAudioSourceNode | null = null\n private levelFrameId: number | null = null\n private smoothedLevel = 0\n\n constructor(callbacks: VoiceCallbacks) {\n this.callbacks = callbacks\n const Recognition = recognitionConstructor()\n this.recognition = Recognition ? new Recognition() : null\n\n if (!this.recognition) {\n return\n }\n\n this.recognition.continuous = true\n this.recognition.interimResults = true\n this.recognition.maxAlternatives = 1\n\n this.recognition.onstart = () => {\n this.listening = true\n this.sessionActive = true\n this.callbacks.onListeningChange(true)\n this.callbacks.onStatusChange(\"Слушаю. Нажмите стоп, когда будете готовы отправить.\")\n }\n\n this.recognition.onresult = (event) => {\n let finalChunk = this.finalTranscript\n let interimChunk = \"\"\n\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index]\n const transcript = result[0]?.transcript ?? \"\"\n if (!transcript) {\n continue\n }\n if (result.isFinal) {\n finalChunk = `${finalChunk} ${transcript}`.trim()\n } else {\n interimChunk = `${interimChunk} ${transcript}`.trim()\n }\n }\n\n this.finalTranscript = finalChunk\n this.interimTranscript = interimChunk\n const preview = sanitizeSpokenText(`${finalChunk} ${interimChunk}`.trim())\n this.callbacks.onInterimTranscript(preview)\n if (preview) {\n this.callbacks.onStatusChange(`Черновик голоса: ${preview}`)\n }\n }\n\n this.recognition.onerror = (event) => {\n if (event.error === \"no-speech\" && this.sessionActive && !this.manualStopRequested) {\n this.statusAfterEnd = \"Продолжаю слушать...\"\n return\n }\n if (event.error === \"aborted\" && this.manualStopRequested) {\n this.statusAfterEnd = \"Голосовой ввод остановлен.\"\n return\n }\n this.sessionActive = false\n this.shouldSendOnEnd = false\n this.statusAfterEnd = errorMessageForCode(event.error)\n this.stopLevelMonitoring()\n this.callbacks.onError(this.statusAfterEnd)\n }\n\n this.recognition.onend = () => {\n this.listening = false\n if (this.sessionActive && !this.manualStopRequested) {\n this.callbacks.onStatusChange(\"Продолжаю слушать...\")\n this.scheduleRestart()\n return\n }\n\n this.sessionActive = false\n this.stopLevelMonitoring()\n this.finalizeTranscript()\n }\n }\n\n get supported() {\n return Boolean(this.recognition)\n }\n\n get isListening() {\n return this.sessionActive || this.listening\n }\n\n private finalizeTranscript() {\n this.callbacks.onListeningChange(false)\n this.callbacks.onLevelChange(0)\n const finalText = sanitizeSpokenText(this.finalTranscript)\n this.finalTranscript = \"\"\n this.interimTranscript = \"\"\n const shouldSend = this.shouldSendOnEnd\n this.shouldSendOnEnd = false\n this.manualStopRequested = false\n\n if (!shouldSend) {\n this.callbacks.onStatusChange(this.statusAfterEnd)\n this.statusAfterEnd = \"Голосовой ввод остановлен.\"\n return\n }\n\n if (!finalText) {\n this.callbacks.onStatusChange(\"Не удалось получить полезный текст из голоса.\")\n this.statusAfterEnd = \"Голосовой ввод остановлен.\"\n return\n }\n\n this.callbacks.onStatusChange(\"Голос распознан. Проверьте текст и отправьте сообщение.\")\n this.statusAfterEnd = \"Голосовой ввод остановлен.\"\n this.callbacks.onFinalTranscript(finalText)\n }\n\n private stopLevelMonitoring() {\n if (this.levelFrameId !== null) {\n window.cancelAnimationFrame(this.levelFrameId)\n this.levelFrameId = null\n }\n\n this.analyser?.disconnect()\n this.sourceNode?.disconnect()\n this.analyser = null\n this.sourceNode = null\n\n if (this.mediaStream) {\n for (const track of this.mediaStream.getTracks()) {\n track.stop()\n }\n this.mediaStream = null\n }\n\n if (this.audioContext) {\n void this.audioContext.close().catch(() => undefined)\n this.audioContext = null\n }\n\n this.smoothedLevel = 0\n this.callbacks.onLevelChange(0)\n }\n\n private sampleLevel() {\n if (!this.analyser) {\n this.callbacks.onLevelChange(0)\n return\n }\n\n const data = new Uint8Array(this.analyser.fftSize)\n const tick = () => {\n if (!this.analyser || (!this.sessionActive && !this.listening)) {\n this.callbacks.onLevelChange(0)\n return\n }\n\n this.analyser.getByteTimeDomainData(data)\n let sum = 0\n for (const value of data) {\n const normalized = (value - 128) / 128\n sum += normalized * normalized\n }\n const rms = Math.sqrt(sum / data.length)\n const level = Math.min(1, rms * 4.6)\n this.smoothedLevel = this.smoothedLevel * 0.68 + level * 0.32\n this.callbacks.onLevelChange(this.smoothedLevel)\n this.levelFrameId = window.requestAnimationFrame(tick)\n }\n\n tick()\n }\n\n private async startLevelMonitoring() {\n if (typeof window === \"undefined\" || !window.isSecureContext || !navigator.mediaDevices?.getUserMedia) {\n this.callbacks.onLevelChange(0)\n return\n }\n\n this.stopLevelMonitoring()\n\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: {\n echoCancellation: true,\n noiseSuppression: true,\n },\n })\n\n if (!this.sessionActive && !this.listening) {\n for (const track of stream.getTracks()) {\n track.stop()\n }\n return\n }\n\n const AudioContextCtor = window.AudioContext || (window as Window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext\n if (!AudioContextCtor) {\n for (const track of stream.getTracks()) {\n track.stop()\n }\n return\n }\n\n this.mediaStream = stream\n this.audioContext = new AudioContextCtor()\n this.sourceNode = this.audioContext.createMediaStreamSource(stream)\n this.analyser = this.audioContext.createAnalyser()\n this.analyser.fftSize = 128\n this.analyser.smoothingTimeConstant = 0.72\n this.sourceNode.connect(this.analyser)\n this.sampleLevel()\n } catch {\n this.callbacks.onLevelChange(0)\n }\n }\n\n private clearRestartTimer() {\n if (this.restartTimeoutId !== null) {\n window.clearTimeout(this.restartTimeoutId)\n this.restartTimeoutId = null\n }\n }\n\n private scheduleRestart() {\n this.clearRestartTimer()\n this.restartTimeoutId = window.setTimeout(() => {\n this.restartTimeoutId = null\n if (!this.recognition || !this.sessionActive || this.manualStopRequested) {\n return\n }\n try {\n this.recognition.lang = this.callbacks.getLanguage()\n this.recognition.start()\n } catch {\n this.sessionActive = false\n this.callbacks.onListeningChange(false)\n this.callbacks.onError(\"Не удалось продолжить голосовой ввод.\")\n }\n }, 160)\n }\n\n start() {\n if (!this.recognition) {\n this.callbacks.onError(\"Голосовой ввод не поддерживается в этом браузере.\")\n return false\n }\n if (this.sessionActive || this.listening) {\n return true\n }\n\n this.finalTranscript = \"\"\n this.interimTranscript = \"\"\n this.shouldSendOnEnd = false\n this.sessionActive = true\n this.manualStopRequested = false\n this.statusAfterEnd = \"Голосовой ввод остановлен.\"\n this.recognition.lang = this.callbacks.getLanguage()\n this.clearRestartTimer()\n\n try {\n this.recognition.start()\n void this.startLevelMonitoring()\n return true\n } catch {\n this.sessionActive = false\n this.stopLevelMonitoring()\n this.callbacks.onError(\"Не удалось запустить голосовой ввод.\")\n return false\n }\n }\n\n stop() {\n if (!this.recognition || (!this.listening && !this.sessionActive)) {\n return\n }\n this.manualStopRequested = true\n this.sessionActive = false\n this.shouldSendOnEnd = true\n this.clearRestartTimer()\n this.stopLevelMonitoring()\n if (this.listening) {\n this.recognition.stop()\n } else {\n this.finalizeTranscript()\n }\n }\n\n cancel() {\n if (!this.recognition) {\n return\n }\n this.manualStopRequested = true\n this.sessionActive = false\n this.shouldSendOnEnd = false\n this.clearRestartTimer()\n this.stopLevelMonitoring()\n if (this.listening) {\n this.recognition.abort()\n } else {\n this.callbacks.onListeningChange(false)\n this.callbacks.onLevelChange(0)\n }\n }\n\n destroy() {\n this.cancel()\n if (!this.recognition) {\n return\n }\n this.recognition.onstart = null\n this.recognition.onresult = null\n this.recognition.onerror = null\n this.recognition.onend = null\n }\n}\n"],"mappings":";AAAA,YAAYA,YAAW;AACvB,SAAS,kBAA6B;;;ACwEtC,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB;AAE3B,SAAS,YAAY;AACnB,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa;AAC9D;AAEA,SAAS,eAAe;AACtB,MAAI,CAAC,UAAU,GAAG;AAChB,WAAO;AAAA,EACT;AACA,SAAO,OAAO,aAAa,GAAG,SAAS,EAAE,KAAK,KAAK;AACrD;AAEA,SAAS,cAAc;AACrB,MAAI,CAAC,UAAU,GAAG;AAChB,WAAO;AAAA,EACT;AACA,SAAO,SAAS,KAAK,UAAU,QAAQ,QAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,uBAAuB;AAC7F;AAEA,SAAS,eAAe,OAAkC;AACxD,UAAQ,SAAS,IAAI,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACjD;AAEA,SAAS,mBAAmB,QAA0C;AACpE,SAAO,MAAM;AAAA,IACX,IAAI;AAAA,MACF,OACG,QAAQ,CAAC,UAAU,eAAe,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC,EAC9E,OAAO,CAAC,SAAS,KAAK,UAAU,CAAC;AAAA,IACtC;AAAA,EACF;AACF;AAEA,SAAS,oBAAoB,OAAe;AAC1C,MAAI,OAAO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