@miiflow/assistant-ui 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +209 -46
  2. package/dist/{WelcomeScreen-EGO8Qt2y.d.ts → WelcomeScreen-CSzlU0Yx.d.ts} +41 -9
  3. package/dist/{avatar-CD685KQV.d.ts → avatar-B_AvYfE8.d.ts} +4 -1
  4. package/dist/chunk-7QNDCHY7.js +2 -0
  5. package/dist/chunk-7QNDCHY7.js.map +1 -0
  6. package/dist/chunk-BINTGT2Q.js +5 -0
  7. package/dist/chunk-BINTGT2Q.js.map +1 -0
  8. package/dist/chunk-HNHLLH6W.js +2 -0
  9. package/dist/chunk-HNHLLH6W.js.map +1 -0
  10. package/dist/{chunk-WG77GQR3.js → chunk-ISMTV5BU.js} +2 -2
  11. package/dist/{chunk-WG77GQR3.js.map → chunk-ISMTV5BU.js.map} +1 -1
  12. package/dist/chunk-LDTAZ4GT.js +2 -0
  13. package/dist/chunk-LDTAZ4GT.js.map +1 -0
  14. package/dist/chunk-OU5ITGKX.js +2 -0
  15. package/dist/chunk-OU5ITGKX.js.map +1 -0
  16. package/dist/chunk-W7HQXA2Z.js +146 -0
  17. package/dist/chunk-W7HQXA2Z.js.map +1 -0
  18. package/dist/client/index.d.ts +66 -5
  19. package/dist/client/index.js +6 -6
  20. package/dist/client/index.js.map +1 -1
  21. package/dist/composer/index.d.ts +37 -3
  22. package/dist/composer/index.js +1 -1
  23. package/dist/context/index.d.ts +10 -3
  24. package/dist/context/index.js +1 -1
  25. package/dist/hooks/index.d.ts +11 -141
  26. package/dist/hooks/index.js +1 -1
  27. package/dist/index.d.ts +5 -5
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/{message-D0oMw3tR.d.ts → message-DTNTKSQr.d.ts} +1 -1
  31. package/dist/primitives/index.d.ts +3 -3
  32. package/dist/primitives/index.js +1 -1
  33. package/dist/{streaming-CmQo_OOA.d.ts → streaming-BfLEgW5u.d.ts} +81 -3
  34. package/dist/styled/index.d.ts +410 -11
  35. package/dist/styled/index.js +1 -1
  36. package/dist/styles-no-preflight.css +1 -1
  37. package/dist/styles.css +3 -1
  38. package/dist/use-branding-css-vars-CR2tjSV8.d.ts +155 -0
  39. package/package.json +2 -1
  40. package/dist/chunk-4WWJTYYA.js +0 -2
  41. package/dist/chunk-4WWJTYYA.js.map +0 -1
  42. package/dist/chunk-6RN7SUWT.js +0 -2
  43. package/dist/chunk-6RN7SUWT.js.map +0 -1
  44. package/dist/chunk-D2PFIJNZ.js +0 -2
  45. package/dist/chunk-D2PFIJNZ.js.map +0 -1
  46. package/dist/chunk-HYFMOOLH.js +0 -133
  47. package/dist/chunk-HYFMOOLH.js.map +0 -1
  48. package/dist/chunk-NKLA5PPB.js +0 -2
  49. package/dist/chunk-NKLA5PPB.js.map +0 -1
  50. package/dist/chunk-ZP4FGAAH.js +0 -2
  51. package/dist/chunk-ZP4FGAAH.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { C as ChatMessage } from '../message-D0oMw3tR.js';
1
+ import { C as ChatMessage } from '../message-DTNTKSQr.js';
2
2
  import { B as BrandingData } from '../branding-NieTEGQf.js';
3
- import '../streaming-CmQo_OOA.js';
3
+ import '../streaming-BfLEgW5u.js';
4
4
 
5
5
  /**
6
6
  * Types for the Miiflow chat client (transport layer).
@@ -19,9 +19,28 @@ interface MiiflowChatConfig {
19
19
  userEmail?: string;
20
20
  /** Optional user metadata (JSON string) */
21
21
  userMetadata?: string;
22
- /** HMAC for identity verification */
22
+ /**
23
+ * The exact JSON string your server signed, sent verbatim as
24
+ * `X-Embed-User-Data`.
25
+ *
26
+ * It must be byte-identical to what was HMAC'd — the signature covers these
27
+ * bytes, so re-serializing here (even to equivalent JSON) invalidates it.
28
+ * That is why this is a string you supply rather than something the SDK
29
+ * assembles from `userId`/`userName`/`userEmail`: those are convenience
30
+ * fields for unsigned sessions, and no client-side serializer can be relied
31
+ * on to reproduce your server's output byte for byte.
32
+ *
33
+ * Shape is up to you; the backend reads `user_id` (the identity the session
34
+ * is keyed on) and optionally `name`/`email`, and keeps the rest as
35
+ * session metadata.
36
+ *
37
+ * Send with `hmac` and `timestamp` — all three travel together or the
38
+ * backend treats the session as anonymous.
39
+ */
40
+ userData?: string;
41
+ /** Hex HMAC-SHA256 of `` `${userData}|${timestamp}` `` keyed by your embed private key. Server-side only. */
23
42
  hmac?: string;
24
- /** Timestamp for HMAC verification */
43
+ /** Unix seconds, as a string. Must be within 5 minutes of server time. */
25
44
  timestamp?: string;
26
45
  /** Override base URL (auto-detected from bundleUrl otherwise) */
27
46
  baseUrl?: string;
@@ -95,6 +114,9 @@ interface MiiflowChatResult {
95
114
  isStreaming: boolean;
96
115
  /** ID of the message being streamed */
97
116
  streamingMessageId: string | null;
117
+ /** Server setup status line ("Getting started…") for the pre-first-token
118
+ * window; null once real content streams or the turn ends */
119
+ statusText: string | null;
98
120
  /** Send a message to the assistant, optionally with attachment IDs */
99
121
  sendMessage: (content: string, attachmentIds?: string[]) => Promise<void>;
100
122
  /** Upload a file and return its attachment ID */
@@ -331,6 +353,45 @@ declare function measureMessageHeight(text: string, maxWidth: number, options?:
331
353
  */
332
354
  declare function clearMeasurementCache(): void;
333
355
 
356
+ /**
357
+ * Which accumulated tool row an SSE tool frame updates.
358
+ *
359
+ * Shared by every reducer that folds `assistant_chunk` frames into reasoning
360
+ * chunks — the embed's `useMiiflowChat` parser and the web dashboard's live
361
+ * SSE + active-run replay reducers. One implementation on purpose: the two
362
+ * surfaces disagreeing about which row an observation completes is precisely
363
+ * the drift that left native-MCP tool calls unrendered.
364
+ */
365
+ /** The subset of an SSE tool frame needed to find the row it updates. */
366
+ interface ToolFrame {
367
+ tool_call_id?: string;
368
+ tool_name?: string;
369
+ subtask_id?: number;
370
+ }
371
+ /** The subset of an accumulated chunk the matcher reads. Structural so both
372
+ * the package's `AccumulatedChunk` and the app's `StreamingChunk` satisfy it. */
373
+ interface MatchableToolChunk {
374
+ type: string;
375
+ toolName?: string;
376
+ toolCallId?: string;
377
+ subtaskId?: number;
378
+ }
379
+ /**
380
+ * Locate the tool chunk a planned/executing/observation frame belongs to.
381
+ *
382
+ * An id-bearing frame matches ONLY by id. A turn can run several calls of the
383
+ * same tool in one batch (native-MCP turns do this routinely — three
384
+ * `get_profiles` calls in one message), and every one of them is a distinct
385
+ * row: falling back to the name there would fold them into a single row on the
386
+ * planned frame and complete the wrong row on the observation. A miss means
387
+ * "no row for this call yet", which is what the planned handler needs to hear
388
+ * to create one.
389
+ *
390
+ * Frames from paths that carry no id keep the historical behaviour: the most
391
+ * recent same-name row, scoped to the frame's subtask when it has one.
392
+ */
393
+ declare function findToolChunkIndex<T extends MatchableToolChunk>(chunks: T[], frame: ToolFrame): number;
394
+
334
395
  /**
335
396
  * Client-side validator for tool definitions.
336
397
  * Validates tool definitions before they're sent to the backend.
@@ -349,4 +410,4 @@ declare function validateToolDefinition(tool: ClientToolDefinition): void;
349
410
  */
350
411
  declare function serializeToolDefinition(tool: ClientToolDefinition): Omit<ClientToolDefinition, "handler">;
351
412
 
352
- export { type ClientToolDefinition, type EmbedSession, type EmbedSessionBranding, type EmbedSessionConfig, type JSONSchemaObject, type JSONSchemaProperty, type MeasureOptions, type MeasuredText, type MiiflowChatConfig, type MiiflowChatResult, type PageContext, type SystemEvent, type ToolExecutionResult, type ToolHandler, type ToolInvocationRequest, ToolValidationError, type WidgetEventCallback, type WidgetEventPayload, type WidgetEventType, clearMeasurementCache, createThread, getBackendBaseUrl, getOrCreateUserId, getTimeUntilExpiry, initSession, isTokenExpired, isTokenExpiringSoon, measureMessageHeight, parseTokenExpiry, registerToolsOnBackend, sendPageContext, sendSystemEvent, sendToolResult, serializeToolDefinition, updateUser, uploadFile, useMiiflowChat, validateToolDefinition };
413
+ export { type ClientToolDefinition, type EmbedSession, type EmbedSessionBranding, type EmbedSessionConfig, type JSONSchemaObject, type JSONSchemaProperty, type MatchableToolChunk, type MeasureOptions, type MeasuredText, type MiiflowChatConfig, type MiiflowChatResult, type PageContext, type SystemEvent, type ToolExecutionResult, type ToolFrame, type ToolHandler, type ToolInvocationRequest, ToolValidationError, type WidgetEventCallback, type WidgetEventPayload, type WidgetEventType, clearMeasurementCache, createThread, findToolChunkIndex, getBackendBaseUrl, getOrCreateUserId, getTimeUntilExpiry, initSession, isTokenExpired, isTokenExpiringSoon, measureMessageHeight, parseTokenExpiry, registerToolsOnBackend, sendPageContext, sendSystemEvent, sendToolResult, serializeToolDefinition, updateUser, uploadFile, useMiiflowChat, validateToolDefinition };
@@ -1,11 +1,11 @@
1
- export{c as clearMeasurementCache,b as measureMessageHeight}from'../chunk-NG4HKXYB.js';import {b}from'../chunk-QECTWT2H.js';import {useState,useRef,useEffect,useMemo,useCallback}from'react';function ge(e){try{let o=e.split(".");if(o.length!==3)return null;let r=o[1].replace(/-/g,"+").replace(/_/g,"/"),s=atob(r),l=JSON.parse(s);return typeof l.exp=="number"?l.exp*1e3:null}catch{return null}}function we(e,o){let r=ge(e);return r===null?true:r-Date.now()<=o}function We(e){let o=ge(e);return o===null?true:Date.now()>=o}function qe(e){let o=ge(e);return o===null?0:Math.max(0,o-Date.now())}function O(e){return e.baseUrl?e.baseUrl.replace(/\/api\/?$/,""):e.bundleUrl?.includes("localhost")||e.bundleUrl?.includes("127.0.0.1")||false?"http://localhost:8003":"https://api.miiflow.ai"}function B(){let e="miiflow-user-id",o=null;try{o=localStorage.getItem(e);}catch{}if(!o){o=`muid_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;try{localStorage.setItem(e,o);}catch{}}return o}async function ie(e,o={}){let r=O(e),s={"Content-Type":"application/json","X-Embed-Public-Key":e.publicKey,"x-mii-user-id":B()};o.token&&(s.Authorization=`Bearer ${o.token}`);let l=await fetch(`${r}/api/embed/init`,{method:"POST",headers:s,body:JSON.stringify({assistant_id:e.assistantId,user_data:{user_id:e.userId,name:e.userName,email:e.userEmail},...o.tools&&o.tools.length>0?{tools:o.tools}:{}})});if(!l.ok){let d=await l.text();throw new Error(`Init failed: ${l.status} - ${d}`)}let u=await l.json();if(!u.success)throw new Error(u.error||"Failed to initialize session");return {token:u.token,config:u.config,session_id:u.session_id,registeredTools:Array.isArray(u.registered_tools)?u.registered_tools:void 0}}var Je="miiflow-session",Xe=300*1e3;function be(e){return `${Je}:${e.publicKey}:${e.assistantId}:${B()}`}function Me(e){try{let o=localStorage.getItem(be(e));if(!o)return null;let r=JSON.parse(o);return !r?.token||!r?.config||we(r.token,Xe)?null:r}catch{return null}}function Ae(e,o){try{let r={token:o.token,config:o.config};localStorage.setItem(be(e),JSON.stringify(r));}catch{}}function Ie(e){try{localStorage.removeItem(be(e));}catch{}}async function ye(e,o){let r=O(e),s=await fetch(`${r}/api/embed/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`,"x-mii-user-id":B()},body:JSON.stringify({operationName:"CreateThread",variables:{input:{assistantId:o.config.assistant_id,name:"New Thread",isPreview:false}},query:`mutation CreateThread($input: CreateThreadInput!) {
1
+ export{c as clearMeasurementCache,b as measureMessageHeight}from'../chunk-NG4HKXYB.js';import {b}from'../chunk-QECTWT2H.js';import {useState,useRef,useEffect,useMemo,useCallback}from'react';function te(t,n){if(n.tool_call_id)return t.findIndex(r=>r.type==="tool"&&r.toolCallId===n.tool_call_id);for(let r=t.length-1;r>=0;r--){let s=t[r];if(s.type==="tool"&&s.toolName===n.tool_name&&(n.subtask_id===void 0||s.subtaskId===n.subtask_id))return r}return -1}function be(t){try{let n=t.split(".");if(n.length!==3)return null;let r=n[1].replace(/-/g,"+").replace(/_/g,"/"),s=atob(r),l=JSON.parse(s);return typeof l.exp=="number"?l.exp*1e3:null}catch{return null}}function Se(t,n){let r=be(t);return r===null?true:r-Date.now()<=n}function Xe(t){let n=be(t);return n===null?true:Date.now()>=n}function Ge(t){let n=be(t);return n===null?0:Math.max(0,n-Date.now())}function $(t){return t.baseUrl?t.baseUrl.replace(/\/api\/?$/,""):t.bundleUrl?.includes("localhost")||t.bundleUrl?.includes("127.0.0.1")||false?"http://localhost:8003":"https://api.miiflow.ai"}function B(){let t="miiflow-user-id",n=null;try{n=localStorage.getItem(t);}catch{}if(!n){n=`muid_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;try{localStorage.setItem(t,n);}catch{}}return n}async function se(t,n={}){let r=$(t),s={"Content-Type":"application/json","X-Embed-Public-Key":t.publicKey,"x-mii-user-id":B()};n.token&&(s.Authorization=`Bearer ${n.token}`),t.hmac&&t.timestamp&&t.userData&&(s["X-Embed-User-Data"]=t.userData,s["X-Embed-Timestamp"]=t.timestamp,s["X-Embed-Signature"]=t.hmac);let l=await fetch(`${r}/api/embed/init`,{method:"POST",headers:s,body:JSON.stringify({assistant_id:t.assistantId,user_data:{user_id:t.userId,name:t.userName,email:t.userEmail},...n.tools&&n.tools.length>0?{tools:n.tools}:{}})});if(!l.ok){let d=await l.text();throw new Error(`Init failed: ${l.status} - ${d}`)}let p=await l.json();if(!p.success)throw new Error(p.error||"Failed to initialize session");return {token:p.token,config:p.config,session_id:p.session_id,registeredTools:Array.isArray(p.registered_tools)?p.registered_tools:void 0}}var Ye="miiflow-session",Ve=300*1e3;function Te(t){return `${Ye}:${t.publicKey}:${t.assistantId}:${B()}`}function De(t){try{let n=localStorage.getItem(Te(t));if(!n)return null;let r=JSON.parse(n);return !r?.token||!r?.config||Se(r.token,Ve)?null:r}catch{return null}}function Pe(t,n){try{let r={token:n.token,config:n.config};localStorage.setItem(Te(t),JSON.stringify(r));}catch{}}function Oe(t){try{localStorage.removeItem(Te(t));}catch{}}async function _e(t,n){let r=$(t),s=await fetch(`${r}/api/embed/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"x-mii-user-id":B()},body:JSON.stringify({operationName:"CreateThread",variables:{input:{assistantId:n.config.assistant_id,name:"New Thread",isPreview:false}},query:`mutation CreateThread($input: CreateThreadInput!) {
2
2
  createThread(input: $input) {
3
3
  thread { id status name isPreview }
4
4
  }
5
- }`})});if(!s.ok)throw new Error(`Failed to create thread: ${s.status}`);let l=await s.json(),u=l.data?.createThread?.thread?.id;if(!u)throw new Error("No thread ID returned");return {threadId:u,token:l.token}}async function Ge(e,o,r){let s=O(e);await fetch(`${s}/api/embed/update`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify({user_data:r})});}async function Se(e,o,r){let l=`${O(e)}/api/embed/upload-attachment`,u=new FormData;u.append("file",r);let d=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"x-mii-user-id":B()},body:u});if(!d.ok){let A=await d.text();throw new Error(`Upload failed: ${d.status} - ${A}`)}let g=(await d.json()).attachment?.id;if(!g)throw new Error("No attachment ID returned");return g}async function Te(e,o,r){let s=O(e),l=await fetch(`${s}/api/embed/system-event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`,"x-mii-user-id":B()},body:JSON.stringify({thread_id:o.config.thread_id,system_event:{action:r.action,description:r.description,followUpInstruction:r.followUpInstruction,metadata:r.metadata||{}}})});if(!l.ok){let d=await l.text();throw new Error(`Failed to send system event: ${l.status} - ${d}`)}let u=await l.json();if(!u.success)throw new Error(u.error||"Failed to send system event")}async function Ce(e,o,r){let s=O(e),l=await fetch(`${s}/api/embed/page-context`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`,"x-mii-user-id":B()},body:JSON.stringify({thread_id:o.config.thread_id,page_context:{action:r.action,content:r.content,metadata:r.metadata||{}}})});if(!l.ok){let d=await l.text();throw new Error(`Failed to send page context: ${l.status} - ${d}`)}let u=await l.json();if(!u.success)throw new Error(u.error||"Failed to send page context")}async function ee(e,o,r){let s=O(e),l=await fetch(`${s}/api/embed/tool-result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r)});if(!l.ok){let d=await l.text();throw new Error(`Failed to send tool result: ${l.status} - ${d}`)}let u=await l.json();if(!u.success)throw new Error(`Failed to send tool result: ${u.error}`)}async function te(e,o,r){let s=O(e);if(r.length===1){let l=await fetch(`${s}/api/embed/register-tool`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r[0])});if(!l.ok){let d=await l.text();throw new Error(`Failed to register tool: ${l.status} - ${d}`)}let u=await l.json();if(!u.success)throw new Error(`Failed to register tool: ${u.error||"Unknown error"}`)}else if(r.length>1){let l=await fetch(`${s}/api/embed/register-tools`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r)});if(!l.ok){let d=await l.text();throw new Error(`Failed to register tools: ${l.status} - ${d}`)}let u=await l.json();if(!u.success)throw new Error(`Failed to register tools: ${u.error||"Unknown error"}`)}}var De=new Set(["string","number","integer","boolean","array","object","null"]),Ye=/^[a-zA-Z_][a-zA-Z0-9_]*$/,_=class extends Error{constructor(o){super(o),this.name="ToolValidationError";}};function se(e){if(!e.name)throw new _("Tool name is required");if(!e.description)throw new _("Tool description is required");if(!e.parameters)throw new _("Tool parameters schema is required");if(typeof e.handler!="function")throw new _("Tool handler must be a function");Ve(e.name),Ke(e.description),Ze(e.parameters);}function Ve(e){if(typeof e!="string")throw new _("Tool name must be a string");if(e.length===0)throw new _("Tool name cannot be empty");if(e.length>64)throw new _("Tool name too long (max 64 characters)");if(!Ye.test(e))throw new _("Tool name must start with letter/underscore and contain only alphanumeric characters and underscores")}function Ke(e){if(typeof e!="string")throw new _("Tool description must be a string");if(e.trim().length===0)throw new _("Tool description cannot be empty");if(e.length>500)throw new _("Tool description too long (max 500 characters)")}function Ze(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new _("Parameters must be a JSON Schema object");if(e.type!=="object")throw new _("Parameters schema must be of type 'object' (function parameters)");if(e.properties&&typeof e.properties=="object")for(let[o,r]of Object.entries(e.properties))me(o,r);if(e.required!==void 0){if(!Array.isArray(e.required))throw new _("'required' must be an array");for(let o of e.required)if(typeof o!="string")throw new _("'required' array must contain only strings")}if(e.additionalProperties!==void 0&&typeof e.additionalProperties!="boolean"&&(typeof e.additionalProperties!="object"||e.additionalProperties===null))throw new _("'additionalProperties' must be boolean or object")}function me(e,o){if(typeof o!="object"||o===null||Array.isArray(o))throw new _(`Property '${e}' schema must be an object`);if(o.type!==void 0){let r=Array.isArray(o.type)?o.type:[o.type];for(let s of r)if(!De.has(s))throw new _(`Invalid type '${s}' for property '${e}'. Valid types: ${Array.from(De).join(", ")}`)}if(o.enum!==void 0&&!Array.isArray(o.enum))throw new _(`Property '${e}' enum must be an array`);if(o.properties&&typeof o.properties=="object")for(let[r,s]of Object.entries(o.properties))me(`${e}.${r}`,s);o.items&&(Array.isArray(o.items)?o.items.forEach((r,s)=>{me(`${e}[${s}]`,r);}):me(`${e}[]`,o.items));}function ae(e){return {name:e.name,description:e.description,parameters:e.parameters}}var Qe=new Set(["image/jpeg","image/jpg","image/png","image/webp","image/bmp"]);function et(e){return Qe.has(e.type)}function tt(e){return new Promise((o,r)=>{let s=URL.createObjectURL(e),l=new Image;l.onload=()=>{URL.revokeObjectURL(s),o(l);},l.onerror=()=>{URL.revokeObjectURL(s),r(new Error("Failed to load image"));},l.src=s;})}function _e(e,o,r,s){return new Promise((l,u)=>{let d=Math.round(e.naturalWidth*o),y=Math.round(e.naturalHeight*o),g=document.createElement("canvas");g.width=d,g.height=y;let A=g.getContext("2d");if(!A){u(new Error("Canvas 2D context unavailable"));return}A.drawImage(e,0,0,d,y),g.toBlob(U=>{U?l(U):u(new Error("Canvas toBlob returned null"));},s,r);})}async function Pe(e){if(!et(e)||e.size<=4194304)return e;let o=await tt(e),r=Math.min(1,4096/Math.max(o.naturalWidth,o.naturalHeight)),s="image/jpeg",l=[.85,.7,.5,.3,.15],u=[r,r*.75,r*.5,r*.25];for(let y of l){let g=await _e(o,r,y,s);if(g.size<=4194304)return ke(g,e.name,s)}for(let y of u.slice(1))for(let g of l){let A=await _e(o,y,g,s);if(A.size<=4194304)return ke(A,e.name,s)}let d=await _e(o,.1,.1,s);return ke(d,e.name,s)}function ke(e,o,r){let s=o.replace(/\.[^.]+$/,".jpg");return new File([e],s,{type:r,lastModified:Date.now()})}var nt=21e3,Ee=1e3,Ne=3e4,ot=3,rt="miiflow.v1";function it(e,o){if(e.webSocketUrl){let d=new URL(e.webSocketUrl);return d.pathname=`/ws/assistant/thread/${o.config.thread_id}/`,d.searchParams.set("role","user"),d.searchParams.set("user_id",B()),d.toString()}let l=O(e).replace(/\/api$/,"").replace(/^https:/,"wss:").replace(/^http:/,"ws:"),u=B();return `${l}/ws/assistant/thread/${o.config.thread_id}/?role=user&user_id=${encodeURIComponent(u)}`}function st(e){return [rt,`embed-token.${e.token}`]}function Be(e){return e?{customName:e.custom_name,messageFontSize:e.message_font_size,welcomeMessage:e.welcome_message,chatboxPlaceholder:e.chatbox_placeholder,backgroundBubbleColor:e.background_bubble_color,headerBackgroundColor:e.header_background_color,showHeader:e.show_header,rotatingPlaceholders:e.rotating_placeholders,presetQuestions:e.preset_questions,chatbotLogo:e.chatbot_logo,assistantAvatar:e.assistant_avatar}:null}function at(e){return Be(e?.config.branding)}async function lt(e,o,r,s){let l=new TextDecoder,u=Date.now(),d="",y=null,g=[],A,U,ne,j=[],h=false,S="answer",x="",z,$,I,Z,Q,L,X,oe="",G=o.config.branding,W=()=>{(x||S==="tool")&&(g.push({type:S,content:x,toolName:z,toolDescription:$,success:I,status:Z,subtaskId:Q,toolArgs:L,progress:X}),x="",z=void 0,$=void 0,I=void 0,Z=void 0,Q=void 0,L=void 0,X=void 0);},he=()=>{let F=g.map(Y=>Y);return (x||S==="tool")&&F.push({type:S,content:x,toolName:z,toolDescription:$,success:I,status:Z,subtaskId:Q,toolArgs:L,progress:X}),F},M=()=>{let F=he();if(y)s.onMessageUpdate({id:y,textContent:d,reasoning:F,suggestedActions:A,medias:j.length>0?j:void 0});else {y=`assistant-${Date.now()}`;let Y={id:y,textContent:d,participant:{id:"assistant",name:G?.custom_name||o.config.assistant_name,role:"assistant",avatarUrl:G?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true,reasoning:F,suggestedActions:A,medias:j.length>0?j:void 0};s.onMessageCreate(Y);}};for(;;){let{done:F,value:Y}=await e.read();if(F)break;let le=l.decode(Y,{stream:true}),ce=(oe+le).split(`
6
- `);le.endsWith(`
7
- `)?oe="":oe=ce.pop()||"";for(let de of ce){if(!de.startsWith("data: "))continue;let ue=de.slice(6);if(ue==="[DONE]")break;try{let n=JSON.parse(ue);if(n.type==="assistant_chunk"){if(n.is_tool_planned){(x||S!=="answer")&&(W(),S="answer"),d="",g.push({type:"tool",content:"",toolName:n.tool_name,toolDescription:n.tool_description,status:"planned",subtaskId:n.subtask_id}),M();continue}if(n.is_tool_executing){for(let t=g.length-1;t>=0;t--){let i=g[t];if(i.type==="tool"&&i.toolName===n.tool_name&&(n.subtask_id===void 0||i.subtaskId===n.subtask_id)){g[t].status="executing";break}}M();continue}if(n.is_observation){for(let t=g.length-1;t>=0;t--){let i=g[t];if(i.type==="tool"&&i.toolName===n.tool_name&&(n.subtask_id===void 0||i.subtaskId===n.subtask_id)){g[t].status="completed";break}}M();continue}if(n.suggested_actions){A=n.suggested_actions.map(t=>({id:t.action,label:t.label,value:t.action})),M();continue}n.tool_args&&(L=n.tool_args),n.progress&&(X=n.progress);let f="answer";if(n.is_thinking?f="thinking":n.is_planning?f="planning":n.is_progress_update&&(f="progress"),f!==S&&(W(),S=f),n.tool_name&&(z=n.tool_name),n.success!==void 0&&(I=n.success),n.subtask_id!==void 0&&(Q=n.subtask_id),f==="thinking"){x+=n.chunk||"";let t=x.match(/"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/);t&&(x=t[1].replace(/\\n/g,`
8
- `).replace(/\\"/g,'"').replace(/\\t/g," ").replace(/\\\\/g,"\\"));}else if(f==="answer"){let t=n.chunk?.trim()||"",i=d.trim();t&&i&&t===i||(d+=n.chunk||"");}else x+=n.chunk||"";n.previous_message_id&&s.onUserMessageIdUpdate(r,n.previous_message_id),M(),M();}else if(n.type==="subagent_dispatch"){let f=n.sub_event||"",t=Array.isArray(n.subagent_path)&&n.subagent_path.length>0?n.subagent_path:[n.subagent_id||""],i=g,p,w=!1;for(let m=0;m<t.length;m++){let a=t[m],c=i.findIndex(b=>b.type==="subagent"&&b.subagentData?.subagentId===a);if(m===t.length-1)if(c>=0)p=i[c];else if(f==="start"){let b={type:"subagent",content:"",subagentData:{subagentId:a,subagentType:n.handle||"",status:"running",result:"",nestedChunks:[]}};i.push(b),p=b;}else w=!0;else {if(c<0){w=!0;break}let b=i[c].subagentData;if(!b){w=!0;break}i=b.nestedChunks;}}if(!w&&p?.subagentData){let m=p.subagentData;if(f==="progress"){let a=n.chunk||"";m.result=(m.result||"")+a;}else if(f==="complete")m.status="completed",n.result&&(m.result=n.result),n.duration_ms!=null&&(m.durationMs=n.duration_ms);else if(f==="failed")m.status="failed",n.error?m.result=(m.result||"")+`
5
+ }`})});if(!s.ok)throw new Error(`Failed to create thread: ${s.status}`);let l=await s.json(),p=l.data?.createThread?.thread?.id;if(!p)throw new Error("No thread ID returned");return {threadId:p,token:l.token}}async function Ke(t,n,r){let s=$(t);await fetch(`${s}/api/embed/update`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({user_data:r})});}async function Ce(t,n,r){let l=`${$(t)}/api/embed/upload-attachment`,p=new FormData;p.append("file",r);let d=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"x-mii-user-id":B()},body:p});if(!d.ok){let E=await d.text();throw new Error(`Upload failed: ${d.status} - ${E}`)}let u=(await d.json()).attachment?.id;if(!u)throw new Error("No attachment ID returned");return u}async function ke(t,n,r){let s=$(t),l=await fetch(`${s}/api/embed/system-event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"x-mii-user-id":B()},body:JSON.stringify({thread_id:n.config.thread_id,system_event:{action:r.action,description:r.description,followUpInstruction:r.followUpInstruction,metadata:r.metadata||{}}})});if(!l.ok){let d=await l.text();throw new Error(`Failed to send system event: ${l.status} - ${d}`)}let p=await l.json();if(!p.success)throw new Error(p.error||"Failed to send system event")}async function Ee(t,n,r){let s=$(t),l=await fetch(`${s}/api/embed/page-context`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"x-mii-user-id":B()},body:JSON.stringify({thread_id:n.config.thread_id,page_context:{action:r.action,content:r.content,metadata:r.metadata||{}}})});if(!l.ok){let d=await l.text();throw new Error(`Failed to send page context: ${l.status} - ${d}`)}let p=await l.json();if(!p.success)throw new Error(p.error||"Failed to send page context")}async function ne(t,n,r){let s=$(t),l=await fetch(`${s}/api/embed/tool-result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify(r)});if(!l.ok){let d=await l.text();throw new Error(`Failed to send tool result: ${l.status} - ${d}`)}let p=await l.json();if(!p.success)throw new Error(`Failed to send tool result: ${p.error}`)}async function oe(t,n,r){let s=$(t);if(r.length===1){let l=await fetch(`${s}/api/embed/register-tool`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify(r[0])});if(!l.ok){let d=await l.text();throw new Error(`Failed to register tool: ${l.status} - ${d}`)}let p=await l.json();if(!p.success)throw new Error(`Failed to register tool: ${p.error||"Unknown error"}`)}else if(r.length>1){let l=await fetch(`${s}/api/embed/register-tools`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify(r)});if(!l.ok){let d=await l.text();throw new Error(`Failed to register tools: ${l.status} - ${d}`)}let p=await l.json();if(!p.success)throw new Error(`Failed to register tools: ${p.error||"Unknown error"}`)}}var $e=new Set(["string","number","integer","boolean","array","object","null"]),Ze=/^[a-zA-Z_][a-zA-Z0-9_]*$/,k=class extends Error{constructor(n){super(n),this.name="ToolValidationError";}};function ae(t){if(!t.name)throw new k("Tool name is required");if(!t.description)throw new k("Tool description is required");if(!t.parameters)throw new k("Tool parameters schema is required");if(typeof t.handler!="function")throw new k("Tool handler must be a function");Qe(t.name),et(t.description),tt(t.parameters);}function Qe(t){if(typeof t!="string")throw new k("Tool name must be a string");if(t.length===0)throw new k("Tool name cannot be empty");if(t.length>64)throw new k("Tool name too long (max 64 characters)");if(!Ze.test(t))throw new k("Tool name must start with letter/underscore and contain only alphanumeric characters and underscores")}function et(t){if(typeof t!="string")throw new k("Tool description must be a string");if(t.trim().length===0)throw new k("Tool description cannot be empty");if(t.length>500)throw new k("Tool description too long (max 500 characters)")}function tt(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new k("Parameters must be a JSON Schema object");if(t.type!=="object")throw new k("Parameters schema must be of type 'object' (function parameters)");if(t.properties&&typeof t.properties=="object")for(let[n,r]of Object.entries(t.properties))ye(n,r);if(t.required!==void 0){if(!Array.isArray(t.required))throw new k("'required' must be an array");for(let n of t.required)if(typeof n!="string")throw new k("'required' array must contain only strings")}if(t.additionalProperties!==void 0&&typeof t.additionalProperties!="boolean"&&(typeof t.additionalProperties!="object"||t.additionalProperties===null))throw new k("'additionalProperties' must be boolean or object")}function ye(t,n){if(typeof n!="object"||n===null||Array.isArray(n))throw new k(`Property '${t}' schema must be an object`);if(n.type!==void 0){let r=Array.isArray(n.type)?n.type:[n.type];for(let s of r)if(!$e.has(s))throw new k(`Invalid type '${s}' for property '${t}'. Valid types: ${Array.from($e).join(", ")}`)}if(n.enum!==void 0&&!Array.isArray(n.enum))throw new k(`Property '${t}' enum must be an array`);if(n.properties&&typeof n.properties=="object")for(let[r,s]of Object.entries(n.properties))ye(`${t}.${r}`,s);n.items&&(Array.isArray(n.items)?n.items.forEach((r,s)=>{ye(`${t}[${s}]`,r);}):ye(`${t}[]`,n.items));}function le(t){return {name:t.name,description:t.description,parameters:t.parameters}}var nt=new Set(["image/jpeg","image/jpg","image/png","image/webp","image/bmp"]);function ot(t){return nt.has(t.type)}function rt(t){return new Promise((n,r)=>{let s=URL.createObjectURL(t),l=new Image;l.onload=()=>{URL.revokeObjectURL(s),n(l);},l.onerror=()=>{URL.revokeObjectURL(s),r(new Error("Failed to load image"));},l.src=s;})}function xe(t,n,r,s){return new Promise((l,p)=>{let d=Math.round(t.naturalWidth*n),C=Math.round(t.naturalHeight*n),u=document.createElement("canvas");u.width=d,u.height=C;let E=u.getContext("2d");if(!E){p(new Error("Canvas 2D context unavailable"));return}E.drawImage(t,0,0,d,C),u.toBlob(N=>{N?l(N):p(new Error("Canvas toBlob returned null"));},s,r);})}async function Ne(t){if(!ot(t)||t.size<=4194304)return t;let n=await rt(t),r=Math.min(1,4096/Math.max(n.naturalWidth,n.naturalHeight)),s="image/jpeg",l=[.85,.7,.5,.3,.15],p=[r,r*.75,r*.5,r*.25];for(let C of l){let u=await xe(n,r,C,s);if(u.size<=4194304)return ve(u,t.name,s)}for(let C of p.slice(1))for(let u of l){let E=await xe(n,C,u,s);if(E.size<=4194304)return ve(E,t.name,s)}let d=await xe(n,.1,.1,s);return ve(d,t.name,s)}function ve(t,n,r){let s=n.replace(/\.[^.]+$/,".jpg");return new File([t],s,{type:r,lastModified:Date.now()})}var it=21e3,Ae=1e3,Re=3e4,st=3,at="miiflow.v1";function lt(t,n){if(t.webSocketUrl){let d=new URL(t.webSocketUrl);return d.pathname=`/ws/assistant/thread/${n.config.thread_id}/`,d.searchParams.set("role","user"),d.searchParams.set("user_id",B()),d.toString()}let l=$(t).replace(/\/api$/,"").replace(/^https:/,"wss:").replace(/^http:/,"ws:"),p=B();return `${l}/ws/assistant/thread/${n.config.thread_id}/?role=user&user_id=${encodeURIComponent(p)}`}function ct(t){return [at,`embed-token.${t.token}`]}function je(t){return t?{customName:t.custom_name,messageFontSize:t.message_font_size,welcomeMessage:t.welcome_message,chatboxPlaceholder:t.chatbox_placeholder,backgroundBubbleColor:t.background_bubble_color,headerBackgroundColor:t.header_background_color,showHeader:t.show_header,rotatingPlaceholders:t.rotating_placeholders,presetQuestions:t.preset_questions,chatbotLogo:t.chatbot_logo,assistantAvatar:t.assistant_avatar}:null}function dt(t){return je(t?.config.branding)}async function ut(t,n,r,s){var ue,pe;let l=new TextDecoder,p=Date.now(),d="",C=null,u=[],E,N,re,F=[],ce=false,M="answer",f="",x,z,W,U,A,G,Z,L,Q="",j=Date.now(),ee=P=>typeof P?.ts=="number"?P.ts*1e3:Date.now(),de=n.config.branding,H=()=>{(f||M==="tool")&&(u.push({type:M,content:f,toolName:x,toolDescription:z,success:W,status:U,subtaskId:A,toolArgs:G,progress:Z,startedAt:L,endedAt:j}),f="",x=void 0,z=void 0,W=void 0,U=void 0,A=void 0,G=void 0,Z=void 0,L=void 0);},Y=()=>{let P=u.map(V=>V);return (f||M==="tool")&&P.push({type:M,content:f,toolName:x,toolDescription:z,success:W,status:U,subtaskId:A,toolArgs:G,progress:Z,startedAt:L}),P},I=()=>{let P=Y();if(C)s.onMessageUpdate({id:C,textContent:d,reasoning:P,suggestedActions:E,medias:F.length>0?F:void 0});else {C=`assistant-${Date.now()}`;let V={id:C,textContent:d,participant:{id:"assistant",name:de?.custom_name||n.config.assistant_name,role:"assistant",avatarUrl:de?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true,reasoning:P,suggestedActions:E,medias:F.length>0?F:void 0};s.onMessageCreate(V);}};for(;;){let{done:P,value:V}=await t.read();if(P)break;let fe=l.decode(V,{stream:true}),ge=(Q+fe).split(`
6
+ `);fe.endsWith(`
7
+ `)?Q="":Q=ge.pop()||"";for(let me of ge){if(!me.startsWith("data: "))continue;let o=me.slice(6);if(o==="[DONE]")break;try{let e=JSON.parse(o);if(j=ee(e),e.type==="assistant_chunk"){if(e.is_status_update){s.onStatusUpdate?.(e.status_text||null);continue}if(e.is_answer_retraction){d="",I();continue}if(e.is_tool_streaming){(f||M!=="answer")&&(H(),M="answer"),te(u,e)<0&&u.push({type:"tool",content:"",toolName:e.tool_name,toolCallId:e.tool_call_id,status:"planned",subtaskId:e.subtask_id,toolWrites:e.tool_writes,startedAt:j}),I();continue}if(e.is_tool_planned){(f||M!=="answer")&&(H(),M="answer"),d="";let a=e.tool_call_id?te(u,e):-1;a>=0?u[a]={...u[a],toolDescription:e.tool_description??u[a].toolDescription,status:"planned",startedAt:u[a].startedAt??j,toolWrites:u[a].toolWrites??e.tool_writes}:u.push({type:"tool",content:"",toolName:e.tool_name,toolCallId:e.tool_call_id,toolDescription:e.tool_description,status:"planned",subtaskId:e.subtask_id,toolWrites:e.tool_writes,startedAt:j}),I();continue}if(e.is_tool_executing){let a=te(u,e);a>=0&&(u[a].status="executing",(ue=u[a]).startedAt??(ue.startedAt=j),(pe=u[a]).toolWrites??(pe.toolWrites=e.tool_writes)),I();continue}if(e.is_observation){let a=te(u,e);a>=0&&(u[a].status="completed",u[a].endedAt=j,e.success===!1&&(u[a].success=!1)),I();continue}if(e.suggested_actions){E=e.suggested_actions.map(a=>({id:a.action,label:a.label,value:a.action})),I();continue}e.tool_args&&(G=e.tool_args),e.progress&&(Z=e.progress);let i="answer";if(e.is_thinking?i="thinking":e.is_planning?i="planning":e.is_progress_update&&(i="progress"),i!==M&&(H(),M=i),L??(L=j),e.tool_name&&(x=e.tool_name),e.success!==void 0&&(W=e.success),e.subtask_id!==void 0&&(A=e.subtask_id),i==="thinking"){f+=e.chunk||"";let a=f.match(/"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/);a&&(f=a[1].replace(/\\n/g,`
8
+ `).replace(/\\"/g,'"').replace(/\\t/g," ").replace(/\\\\/g,"\\"));}else if(i==="answer"){let a=e.chunk?.trim()||"",y=d.trim();a&&y&&a===y||(d+=e.chunk||"");}else f+=e.chunk||"";e.previous_message_id&&s.onUserMessageIdUpdate(r,e.previous_message_id),I(),I();}else if(e.type==="subagent_dispatch"){let i=e.sub_event||"",a=Array.isArray(e.subagent_path)&&e.subagent_path.length>0?e.subagent_path:[e.subagent_id||""],y=u,c,g=!1;for(let w=0;w<a.length;w++){let S=a[w],b=y.findIndex(T=>T.type==="subagent"&&T.subagentData?.subagentId===S);if(w===a.length-1)if(b>=0)c=y[b];else if(i==="start"){let T={type:"subagent",content:"",subagentData:{subagentId:S,subagentType:e.handle||"",status:"running",result:"",nestedChunks:[],dispatchStep:typeof e.dispatch_step=="number"?e.dispatch_step:void 0}};y.push(T),c=T;}else g=!0;else {if(b<0){g=!0;break}let T=y[b].subagentData;if(!T){g=!0;break}y=T.nestedChunks;}}if(!g&&c?.subagentData){let w=c.subagentData;if(i==="progress"){let S=e.chunk||"";w.result=(w.result||"")+S;}else if(i==="complete")w.status="completed",e.result&&(w.result=e.result),e.duration_ms!=null&&(w.durationMs=e.duration_ms);else if(i==="failed")w.status="failed",e.error?w.result=(w.result||"")+`
9
9
 
10
- Error: ${n.error}`:n.result&&(m.result=n.result),n.duration_ms!=null&&(m.durationMs=n.duration_ms);else if(f==="thinking"){let a=n.chunk||"";if(a){let c=m.nestedChunks,b=c[c.length-1];b&&b.type==="thinking"?b.content=(b.content||"")+a:c.push({type:"thinking",content:a});}}else if(f==="tool"){let a=n.tool_name||"",c=n.tool_description,b=n.status||"planned",T=m.nestedChunks,C=-1;for(let N=T.length-1;N>=0;N--)if(T[N].type==="tool"&&T[N].toolName===a){C=N;break}C>=0?T[C]={...T[C],status:b,toolDescription:c||T[C].toolDescription}:T.push({type:"tool",content:"",toolName:a,toolDescription:c,status:b});}else if(f==="observation"){let a=n.tool_name||"",c=n.success!==!1,b=n.chunk||"",T=m.nestedChunks;for(let C=T.length-1;C>=0;C--)if(T[C].type==="tool"&&T[C].toolName===a){T[C]={...T[C],status:"completed",success:c};break}T.push({type:"observation",content:b,toolName:a,success:c});}}M();}else if(n.type==="clarification_needed"){W();let f={questions:n.questions||[],context:n.context,subtaskId:n.subtask_id,subtaskDescription:n.subtask_description,subagentName:n.subagent_name,subagentRole:n.subagent_role,toolCallId:n.tool_call_id,interruptId:n.interrupt_id,question:n.question||void 0,options:n.options||void 0},t=f.context||f.questions?.[0]?.question||f.question||"";g.push({type:"clarification_needed",content:t,clarificationData:f,subtaskId:n.subtask_id}),U=f,d||(d=t),M();}else if(n.type==="tool_approval_needed"){W();let f={toolName:n.tool_name||"",toolDescription:n.tool_description||"",toolInputs:n.tool_inputs||{},toolSchema:n.tool_schema,toolCallId:n.tool_call_id,interruptId:n.interrupt_id,toolLabel:n.tool_label,preview:n.tool_preview};g.push({type:"tool_approval_needed",content:f.toolDescription,toolApprovalData:f}),ne=f,M();}else if(n.type==="media"){let f=n.media_data;f&&(j=[...j,{id:f.id,url:f.url,mediaType:f.media_type||"image",altText:f.alt_text}],M());}else if(n.type==="assistant_complete"){W(),h=!0;let f=n.message?.text_content||d,t=n.message?.id,i=n.message?.metadata?.sources,p=(Date.now()-u)/1e3;s.onComplete(y,f,t,g,A,i,U,p,ne),d=f,t&&(y=t);break}else if(n.type==="client_tool_invocation"&&n.invocation&&s.onToolInvocation)s.onToolInvocation(n.invocation);else {if(n.type==="error")throw new Error(n.error||"Stream error");if(n.type==="done"){if(y&&!h){W();let f=(Date.now()-u)/1e3;s.onComplete(y,d||"",n.message_id,g,A,void 0,U,f,ne);}else n.message_id&&y&&s.onMessageUpdate({id:y,isStreaming:!1});n.message_id&&(y=n.message_id);break}}}catch(n){if(n instanceof Error&&n.message!=="Stream error"&&(n.message.startsWith("Stream error")||n.message.startsWith("HTTP error")))throw n}}}return {assistantMsgId:y,assistantContent:d}}function ct(e){let[o,r]=useState([]),[s,l]=useState(false),[u,d]=useState(null),[y,g]=useState(null),[A,U]=useState(true),[ne,j]=useState(null),h=useRef(e);h.current=e;let S=useRef(y);S.current=y;let x=useRef(s);x.current=s;let z=useRef(null),$=useRef(new Map),I=useRef(new Map),[Z,Q]=useState(null),L=useRef(null);useEffect(()=>{let t=false,i=Me(h.current);i?.config.branding&&Q(i.config.branding);let w=(h.current.tools??[]).map(a=>{se(a),$.current.set(a.name,a.handler);let c=ae(a);return I.current.set(a.name,c),c});async function m(){try{let a=i?.token,c;try{c=await ie(h.current,{token:a,tools:w});}catch(b){if(a)Ie(h.current),c=await ie(h.current,{tools:w});else throw b}if(t||(Ae(h.current,c),g(c),U(!1)),w.length>0){let b=new Set(c.registeredTools??[]),T=w.filter(C=>!b.has(C.name));T.length>0&&te(h.current,c,T).catch(C=>{console.warn("[Miiflow] Fallback tool registration failed:",C);});}return c}catch(a){return t||(j(a instanceof Error?a.message:"Failed to initialize"),U(false)),null}}return L.current=m(),()=>{t=true;}},[e.publicKey,e.assistantId]);let X=useMemo(()=>at(y)??e.initialBranding??Be(Z),[y,e.initialBranding,Z]),oe=b(X),G=useRef(new Map),W=useCallback(async t=>{let i=S.current;if(!i)throw new Error("Not initialized");if(t.type.startsWith("image/"))try{t=await Pe(t);}catch(w){console.warn("Image compression failed, using original:",w);}let p=await Se(h.current,i,t);return G.current.set(p,{id:p,filename:t.name,mimeType:t.type,size:t.size,isImage:t.type.startsWith("image/"),isVideo:t.type.startsWith("video/"),isDocument:!t.type.startsWith("image/")&&!t.type.startsWith("video/")}),p},[]),he=useCallback(t=>{G.current.delete(t);},[]),M=useCallback(async t=>{let i=S.current;if(!i)throw new Error("Not initialized");let{invocation_id:p,tool_name:w,parameters:m}=t;console.log(`[Miiflow] Tool invocation received: "${w}" (id: ${p})`);let a=$.current.get(w);if(!a)return false;try{let c=await Promise.race([a(m),new Promise((b,T)=>setTimeout(()=>T(new Error("Tool execution timeout (30s)")),3e4))]);return console.log(`[Miiflow] Tool "${w}" executed successfully (id: ${p})`),await ee(h.current,i,{invocation_id:p,result:c}),console.log(`[Miiflow] Tool result sent for "${w}" (id: ${p})`),!0}catch(c){return console.error(`[Miiflow] Tool '${w}' execution failed:`,c),await ee(h.current,i,{invocation_id:p,error:c instanceof Error?c.message:String(c)}),true}},[]);useEffect(()=>{if(!y)return;let t=null,i=null,p=null,w=0,m=0,a=false;function c(){if(a)return;let b=S.current;if(!b)return;let T=it(h.current,b),C=st(b);t=new WebSocket(T,C);let N=false;t.onopen=()=>{console.log("[Miiflow] WebSocket connected"),N=true,w=0,m=0,i=setInterval(()=>{t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"heartbeat"}));},nt);},t.onmessage=v=>{try{let E=JSON.parse(v.data);E.type==="client_tool_invocation"&&E.invocation&&M(E.invocation).then(async H=>{if(!H){let V=h.current.onToolInvocationFallback;if(!(V?await V(E.invocation):!1)){let k=S.current;k&&ee(h.current,k,{invocation_id:E.invocation.invocation_id,error:`No handler found for tool '${E.invocation.tool_name}'`}).catch(console.error);}}}).catch(console.error);}catch{}},t.onclose=()=>{if(i&&(clearInterval(i),i=null),a)return;if(!N){if(m>=ot){console.error("[Miiflow] WebSocket giving up after repeated handshake failures");return}m++,ie(h.current).then(E=>{a||(S.current=E,g(E),p=setTimeout(c,Ee));}).catch(E=>{if(a)return;console.error("[Miiflow] Session refresh failed",E);let H=Math.min(Ee*Math.pow(2,m),Ne);p=setTimeout(c,H);});return}let v=Math.min(Ee*Math.pow(2,w),Ne);w++,p=setTimeout(c,v);},t.onerror=()=>{};}return c(),()=>{a=true,i&&clearInterval(i),p&&clearTimeout(p),t&&(t.onclose=null,t.close());}},[y,M]);let F=useCallback(async t=>{let i=S.current;if(!i)throw new Error("Not initialized");await Te(h.current,i,t);},[]),Y=useCallback(async t=>{let i=S.current;if(!i)throw new Error("Not initialized");await Ce(h.current,i,t);},[]),le=useCallback(async(t,i,p)=>{let w=!!t.trim(),m=i&&i.length>0;if(!w&&!m||x.current)return;let a=S.current;if(!a&&L.current&&(a=await L.current),!a)return;x.current=true;let c=`msg-${Date.now()}`,b=!!p?.is_clarification_response,T=i?.map(v=>G.current.get(v)).filter(Boolean);i?.forEach(v=>G.current.delete(v));let C=`assistant-pending-${Date.now()}`,N={id:C,textContent:"",participant:{id:"assistant",name:a.config.branding?.custom_name||a.config.assistant_name,role:"assistant",avatarUrl:a.config.branding?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true};if(b)r(v=>[...v,N]);else {let v={id:c,textContent:t,participant:{id:"user",name:h.current.userName||"You",role:"user"},createdAt:new Date().toISOString(),attachments:T?.length?T:void 0};r(E=>[...E,v,N]),h.current.onUserMessageCreated?.({id:c,content:t});}l(true),d(C);try{let v=O(h.current),E=new AbortController;z.current=E;let H=await fetch(`${v}/assistant/message/stream/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`,"x-mii-user-id":B()},body:JSON.stringify({thread_id:a.config.thread_id,text_content:t,message_id:c,metadata:p||{},attachment_ids:i||[]}),signal:E.signal});if(!H.ok)throw new Error(`HTTP error: ${H.status}`);let V=H.body?.getReader();if(!V)throw new Error("No response body");let re=await lt(V,a,c,{onMessageCreate:k=>{d(k.id),r(D=>[...D.filter(q=>q.id!==C),k]);},onMessageUpdate:k=>{r(D=>D.map(P=>P.id===k.id?{...P,...k}:P));},onUserMessageIdUpdate:(k,D)=>{r(P=>P.map(q=>q.id===k?{...q,id:D}:q));},onComplete:(k,D,P,q,fe,Re,Ue,je,ze)=>{k&&r(Fe=>Fe.map(pe=>pe.id===k?{...pe,id:P||pe.id,textContent:D,isStreaming:!1,reasoning:q,suggestedActions:fe,citations:Re,pendingClarification:Ue,pendingToolApproval:ze,executionTime:je}:pe)),h.current.onAssistantMessageComplete?.({id:P||k||"",content:D});},onToolInvocation:async k=>{if(!await M(k)){let P=h.current.onToolInvocationFallback;if(!(P?await P(k):!1)){let fe=S.current;fe&&await ee(h.current,fe,{invocation_id:k.invocation_id,error:`No handler found for tool '${k.tool_name}'`});}}}});re.assistantMsgId&&r(k=>k.map(D=>D.id===re.assistantMsgId?{...D,isStreaming:!1}:D));}catch(v){if(v instanceof DOMException&&v.name==="AbortError")return;console.error("[Miiflow] Send error:",v);let E=S.current,H={id:`error-${Date.now()}`,textContent:"Sorry, I encountered an error. Please try again.",participant:{id:"assistant",name:E?.config.branding?.custom_name||E?.config.assistant_name||"Assistant",role:"assistant",avatarUrl:E?.config.branding?.assistant_avatar},createdAt:new Date().toISOString()};r(V=>[...V.filter(re=>re.id!==C),H]),j(v instanceof Error?v.message:"Send failed");}finally{z.current=null,l(false),d(null);}},[M]),ve=useCallback(()=>{x.current&&(z.current?.abort(),z.current=null,r(t=>t.map(i=>i.isStreaming?{...i,isStreaming:false}:i)),x.current=false,l(false),d(null));},[]),ce=useCallback(async()=>{let t=S.current;if(!t)throw new Error("Not initialized");let i=await ye(h.current,t);i.token||console.warn("[Miiflow] CreateThread did not return new token \u2014 tools may register to wrong thread");let p={...t,config:{...t.config,thread_id:i.threadId},token:i.token||t.token};if(S.current=p,g(p),r([]),I.current.size>0){console.log(`[Miiflow] Re-registering ${I.current.size} tools on new thread`);try{await te(h.current,p,Array.from(I.current.values()));}catch(w){console.warn("[Miiflow] Failed to re-register tools:",w);}}return i.threadId},[]),de=useCallback(async t=>{let i=S.current;if(!i)throw new Error("Not initialized");se(t),$.current.set(t.name,t.handler);let p=ae(t);I.current.set(t.name,p);try{await te(h.current,i,[p]),console.log(`[Miiflow] Tool registered: "${t.name}"`);}catch(w){throw $.current.delete(t.name),I.current.delete(t.name),w}},[]),ue=useCallback(async t=>{let i=S.current;if(!i)throw new Error("Not initialized");for(let a of t)se(a);let p=new Map($.current),w=new Map(I.current),m=[];for(let a of t){$.current.set(a.name,a.handler);let c=ae(a);I.current.set(a.name,c),m.push(c);}try{await te(h.current,i,m);let a=t.map(c=>c.name);console.log(`[Miiflow] Tools registered: ${JSON.stringify(a)} (${t.length} tools)`);}catch(a){throw $.current=p,I.current=w,a}},[]),n=useMemo(()=>o.filter(t=>t.participant.role!=="system").map(t=>({id:t.id,textContent:t.textContent?.replace(/\[ref:[^\]]+\]/g,"")||t.textContent,participant:t.participant,createdAt:t.createdAt,isStreaming:t.isStreaming,reasoning:t.reasoning,suggestedActions:t.suggestedActions,citations:t.citations,attachments:t.attachments,pendingClarification:t.pendingClarification,pendingToolApproval:t.pendingToolApproval,executionTime:t.executionTime})),[o]),f=useCallback(t=>{g(t);},[]);return {messages:n,isStreaming:s,streamingMessageId:u,sendMessage:le,uploadFile:W,removeUploadedAttachment:he,session:y,loading:A,error:ne,branding:X,brandingCSSVars:oe,startNewThread:ce,registerTool:de,registerTools:ue,sendSystemEvent:F,sendPageContext:Y,handleToolInvocation:M,updateSession:f,stopStreaming:ve}}export{_ as ToolValidationError,ye as createThread,O as getBackendBaseUrl,B as getOrCreateUserId,qe as getTimeUntilExpiry,ie as initSession,We as isTokenExpired,we as isTokenExpiringSoon,ge as parseTokenExpiry,te as registerToolsOnBackend,Ce as sendPageContext,Te as sendSystemEvent,ee as sendToolResult,ae as serializeToolDefinition,Ge as updateUser,Se as uploadFile,ct as useMiiflowChat,se as validateToolDefinition};//# sourceMappingURL=index.js.map
10
+ Error: ${e.error}`:e.result&&(w.result=e.result),e.duration_ms!=null&&(w.durationMs=e.duration_ms);else if(i==="thinking"){let S=e.chunk||"";if(S){let b=w.nestedChunks,T=b[b.length-1];T&&T.type==="thinking"?T.content=(T.content||"")+S:b.push({type:"thinking",content:S});}}else if(i==="tool"){let S=e.tool_name||"",b=e.tool_description,T=e.status||"planned",m=w.nestedChunks,h=-1;for(let v=m.length-1;v>=0;v--)if(m[v].type==="tool"&&m[v].toolName===S){h=v;break}h>=0?m[h]={...m[h],status:T,toolDescription:b||m[h].toolDescription}:m.push({type:"tool",content:"",toolName:S,toolDescription:b,status:T});}else if(i==="observation"){let S=e.tool_name||"",b=e.success!==!1,T=e.chunk||"",m=w.nestedChunks;for(let h=m.length-1;h>=0;h--)if(m[h].type==="tool"&&m[h].toolName===S){m[h]={...m[h],status:"completed",success:b};break}m.push({type:"observation",content:T,toolName:S,success:b});}}I();}else if(e.type==="clarification_needed"){H();let i={questions:e.questions||[],context:e.context,subtaskId:e.subtask_id,subtaskDescription:e.subtask_description,subagentName:e.subagent_name,subagentRole:e.subagent_role,toolCallId:e.tool_call_id,interruptId:e.interrupt_id,question:e.question||void 0,options:e.options||void 0},a=i.context||i.questions?.[0]?.question||i.question||"";u.push({type:"clarification_needed",content:a,clarificationData:i,subtaskId:e.subtask_id}),N=i,d||(d=a),I();}else if(e.type==="tool_approval_needed"){H();let i={toolName:e.tool_name||"",toolDescription:e.tool_description||"",toolInputs:e.tool_inputs||{},toolSchema:e.tool_schema,toolCallId:e.tool_call_id,interruptId:e.interrupt_id,toolLabel:e.tool_label,preview:e.tool_preview};u.push({type:"tool_approval_needed",content:i.toolDescription,toolApprovalData:i}),re=i,I();}else if(e.type==="media"){let i=e.media_data;i&&(F=[...F,{id:i.id,url:i.url,mediaType:i.media_type||"image",altText:i.alt_text}],I());}else if(e.type==="assistant_complete"){H(),ce=!0;let i=e.message?.text_content||d,a=e.message?.id,y=e.message?.metadata?.sources,c=(Date.now()-p)/1e3;s.onComplete(C,i,a,u,E,y,N,c,re),d=i,a&&(C=a);break}else if(e.type==="client_tool_invocation"&&e.invocation&&s.onToolInvocation)s.onToolInvocation(e.invocation);else {if(e.type==="error")throw new Error(e.error||"Stream error");if(e.type==="done"){if(C&&!ce){H();let i=(Date.now()-p)/1e3;s.onComplete(C,d||"",e.message_id,u,E,void 0,N,i,re);}else e.message_id&&C&&s.onMessageUpdate({id:C,isStreaming:!1});e.message_id&&(C=e.message_id);break}}}catch(e){if(e instanceof Error&&e.message!=="Stream error"&&(e.message.startsWith("Stream error")||e.message.startsWith("HTTP error")))throw e}}}return {assistantMsgId:C,assistantContent:d}}function pt(t){let[n,r]=useState([]),[s,l]=useState(false),[p,d]=useState(null),[C,u]=useState(null),[E,N]=useState(null),[re,F]=useState(true),[ce,M]=useState(null),f=useRef(t);f.current=t;let x=useRef(E);x.current=E;let z=useRef(s);z.current=s;let W=useRef(null),U=useRef(new Map),A=useRef(new Map),[G,Z]=useState(null),L=useRef(null);useEffect(()=>{let o=false,e=De(f.current);e?.config.branding&&Z(e.config.branding);let a=(f.current.tools??[]).map(c=>{ae(c),U.current.set(c.name,c.handler);let g=le(c);return A.current.set(c.name,g),g});async function y(){try{let c=e?.token,g;try{g=await se(f.current,{token:c,tools:a});}catch(w){if(c)Oe(f.current),g=await se(f.current,{tools:a});else throw w}if(o||(Pe(f.current,g),N(g),F(!1)),a.length>0){let w=new Set(g.registeredTools??[]),S=a.filter(b=>!w.has(b.name));S.length>0&&oe(f.current,g,S).catch(b=>{console.warn("[Miiflow] Fallback tool registration failed:",b);});}return g}catch(c){return o||(M(c instanceof Error?c.message:"Failed to initialize"),F(false)),null}}return L.current=y(),()=>{o=true;}},[t.publicKey,t.assistantId]);let Q=useMemo(()=>dt(E)??t.initialBranding??je(G),[E,t.initialBranding,G]),j=b(Q),ee=useRef(new Map),de=useCallback(async o=>{let e=x.current;if(!e)throw new Error("Not initialized");if(o.type.startsWith("image/"))try{o=await Ne(o);}catch(a){console.warn("Image compression failed, using original:",a);}let i=await Ce(f.current,e,o);return ee.current.set(i,{id:i,filename:o.name,mimeType:o.type,size:o.size,isImage:o.type.startsWith("image/"),isVideo:o.type.startsWith("video/"),isDocument:!o.type.startsWith("image/")&&!o.type.startsWith("video/")}),i},[]),H=useCallback(o=>{ee.current.delete(o);},[]),Y=useCallback(async o=>{let e=x.current;if(!e)throw new Error("Not initialized");let{invocation_id:i,tool_name:a,parameters:y}=o;console.log(`[Miiflow] Tool invocation received: "${a}" (id: ${i})`);let c=U.current.get(a);if(!c)return false;try{let g=await Promise.race([c(y),new Promise((w,S)=>setTimeout(()=>S(new Error("Tool execution timeout (30s)")),3e4))]);return console.log(`[Miiflow] Tool "${a}" executed successfully (id: ${i})`),await ne(f.current,e,{invocation_id:i,result:g}),console.log(`[Miiflow] Tool result sent for "${a}" (id: ${i})`),!0}catch(g){return console.error(`[Miiflow] Tool '${a}' execution failed:`,g),await ne(f.current,e,{invocation_id:i,error:g instanceof Error?g.message:String(g)}),true}},[]);useEffect(()=>{if(!E)return;let o=null,e=null,i=null,a=0,y=0,c=false;function g(){if(c)return;let w=x.current;if(!w)return;let S=lt(f.current,w),b=ct(w);o=new WebSocket(S,b);let T=false;o.onopen=()=>{console.log("[Miiflow] WebSocket connected"),T=true,a=0,y=0,e=setInterval(()=>{o?.readyState===WebSocket.OPEN&&o.send(JSON.stringify({type:"heartbeat"}));},it);},o.onmessage=m=>{try{let h=JSON.parse(m.data);h.type==="client_tool_invocation"&&h.invocation&&Y(h.invocation).then(async v=>{if(!v){let K=f.current.onToolInvocationFallback;if(!(K?await K(h.invocation):!1)){let _=x.current;_&&ne(f.current,_,{invocation_id:h.invocation.invocation_id,error:`No handler found for tool '${h.invocation.tool_name}'`}).catch(console.error);}}}).catch(console.error);}catch{}},o.onclose=()=>{if(e&&(clearInterval(e),e=null),c)return;if(!T){if(y>=st){console.error("[Miiflow] WebSocket giving up after repeated handshake failures");return}y++,se(f.current).then(h=>{c||(x.current=h,N(h),i=setTimeout(g,Ae));}).catch(h=>{if(c)return;console.error("[Miiflow] Session refresh failed",h);let v=Math.min(Ae*Math.pow(2,y),Re);i=setTimeout(g,v);});return}let m=Math.min(Ae*Math.pow(2,a),Re);a++,i=setTimeout(g,m);},o.onerror=()=>{};}return g(),()=>{c=true,e&&clearInterval(e),i&&clearTimeout(i),o&&(o.onclose=null,o.close());}},[E,Y]);let I=useCallback(async o=>{let e=x.current;if(!e)throw new Error("Not initialized");await ke(f.current,e,o);},[]),ue=useCallback(async o=>{let e=x.current;if(!e)throw new Error("Not initialized");await Ee(f.current,e,o);},[]),pe=useCallback(async(o,e,i)=>{let a=!!o.trim(),y=e&&e.length>0;if(!a&&!y||z.current)return;let c=x.current;if(!c&&L.current&&(c=await L.current),!c)return;z.current=true;let g=`msg-${Date.now()}`,w=!!i?.is_clarification_response,S=e?.map(m=>ee.current.get(m)).filter(Boolean);e?.forEach(m=>ee.current.delete(m));let b=`assistant-pending-${Date.now()}`,T={id:b,textContent:"",participant:{id:"assistant",name:c.config.branding?.custom_name||c.config.assistant_name,role:"assistant",avatarUrl:c.config.branding?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true};if(w)r(m=>[...m,T]);else {let m={id:g,textContent:o,participant:{id:"user",name:f.current.userName||"You",role:"user"},createdAt:new Date().toISOString(),attachments:S?.length?S:void 0};r(h=>[...h,m,T]),f.current.onUserMessageCreated?.({id:g,content:o});}l(true),u(b);try{let m=$(f.current),h=new AbortController;W.current=h;let v=await fetch(`${m}/assistant/message/stream/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.token}`,"x-mii-user-id":B()},body:JSON.stringify({thread_id:c.config.thread_id,text_content:o,message_id:g,metadata:i||{},attachment_ids:e||[]}),signal:h.signal});if(!v.ok)throw new Error(`HTTP error: ${v.status}`);let K=v.body?.getReader();if(!K)throw new Error("No response body");let ie=await ut(K,c,g,{onMessageCreate:_=>{u(_.id),r(D=>[...D.filter(q=>q.id!==b),_]);},onMessageUpdate:_=>{r(D=>D.map(O=>O.id===_.id?{...O,..._}:O));},onUserMessageIdUpdate:(_,D)=>{r(O=>O.map(q=>q.id===_?{...q,id:D}:q));},onStatusUpdate:_=>{d(_);},onComplete:(_,D,O,q,he,Fe,ze,We,He)=>{_&&r(Le=>Le.map(we=>we.id===_?{...we,id:O||we.id,textContent:D,isStreaming:!1,reasoning:q,suggestedActions:he,citations:Fe,pendingClarification:ze,pendingToolApproval:He,executionTime:We}:we)),f.current.onAssistantMessageComplete?.({id:O||_||"",content:D});},onToolInvocation:async _=>{if(!await Y(_)){let O=f.current.onToolInvocationFallback;if(!(O?await O(_):!1)){let he=x.current;he&&await ne(f.current,he,{invocation_id:_.invocation_id,error:`No handler found for tool '${_.tool_name}'`});}}}});ie.assistantMsgId&&r(_=>_.map(D=>D.id===ie.assistantMsgId?{...D,isStreaming:!1}:D));}catch(m){if(m instanceof DOMException&&m.name==="AbortError")return;console.error("[Miiflow] Send error:",m);let h=x.current,v={id:`error-${Date.now()}`,textContent:"Sorry, I encountered an error. Please try again.",participant:{id:"assistant",name:h?.config.branding?.custom_name||h?.config.assistant_name||"Assistant",role:"assistant",avatarUrl:h?.config.branding?.assistant_avatar},createdAt:new Date().toISOString()};r(K=>[...K.filter(ie=>ie.id!==b),v]),M(m instanceof Error?m.message:"Send failed");}finally{W.current=null,l(false),u(null),d(null);}},[Y]),P=useCallback(()=>{z.current&&(W.current?.abort(),W.current=null,r(o=>o.map(e=>e.isStreaming?{...e,isStreaming:false}:e)),z.current=false,l(false),u(null),d(null));},[]),V=useCallback(async()=>{let o=x.current;if(!o)throw new Error("Not initialized");let e=await _e(f.current,o);e.token||console.warn("[Miiflow] CreateThread did not return new token \u2014 tools may register to wrong thread");let i={...o,config:{...o.config,thread_id:e.threadId},token:e.token||o.token};if(x.current=i,N(i),r([]),A.current.size>0){console.log(`[Miiflow] Re-registering ${A.current.size} tools on new thread`);try{await oe(f.current,i,Array.from(A.current.values()));}catch(a){console.warn("[Miiflow] Failed to re-register tools:",a);}}return e.threadId},[]),fe=useCallback(async o=>{let e=x.current;if(!e)throw new Error("Not initialized");ae(o),U.current.set(o.name,o.handler);let i=le(o);A.current.set(o.name,i);try{await oe(f.current,e,[i]),console.log(`[Miiflow] Tool registered: "${o.name}"`);}catch(a){throw U.current.delete(o.name),A.current.delete(o.name),a}},[]),Ie=useCallback(async o=>{let e=x.current;if(!e)throw new Error("Not initialized");for(let c of o)ae(c);let i=new Map(U.current),a=new Map(A.current),y=[];for(let c of o){U.current.set(c.name,c.handler);let g=le(c);A.current.set(c.name,g),y.push(g);}try{await oe(f.current,e,y);let c=o.map(g=>g.name);console.log(`[Miiflow] Tools registered: ${JSON.stringify(c)} (${o.length} tools)`);}catch(c){throw U.current=i,A.current=a,c}},[]),ge=useMemo(()=>n.filter(o=>o.participant.role!=="system").map(o=>({id:o.id,textContent:o.textContent?.replace(/\[ref:[^\]]+\]/g,"")||o.textContent,participant:o.participant,createdAt:o.createdAt,isStreaming:o.isStreaming,reasoning:o.reasoning,suggestedActions:o.suggestedActions,citations:o.citations,attachments:o.attachments,pendingClarification:o.pendingClarification,pendingToolApproval:o.pendingToolApproval,executionTime:o.executionTime})),[n]),me=useCallback(o=>{N(o);},[]);return {messages:ge,isStreaming:s,streamingMessageId:C,statusText:p,sendMessage:pe,uploadFile:de,removeUploadedAttachment:H,session:E,loading:re,error:ce,branding:Q,brandingCSSVars:j,startNewThread:V,registerTool:fe,registerTools:Ie,sendSystemEvent:I,sendPageContext:ue,handleToolInvocation:Y,updateSession:me,stopStreaming:P}}export{k as ToolValidationError,_e as createThread,te as findToolChunkIndex,$ as getBackendBaseUrl,B as getOrCreateUserId,Ge as getTimeUntilExpiry,se as initSession,Xe as isTokenExpired,Se as isTokenExpiringSoon,be as parseTokenExpiry,oe as registerToolsOnBackend,Ee as sendPageContext,ke as sendSystemEvent,ne as sendToolResult,le as serializeToolDefinition,Ke as updateUser,Ce as uploadFile,pt as useMiiflowChat,ae as validateToolDefinition};//# sourceMappingURL=index.js.map
11
11
  //# sourceMappingURL=index.js.map