@miiflow/assistant-ui 0.5.0 → 0.5.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/dist/{WelcomeScreen-88hzx0rD.d.ts → WelcomeScreen-D32Tsu6G.d.ts} +11 -3
- package/dist/{avatar-B6YLvJt3.d.ts → avatar-CAmTN1L7.d.ts} +1 -1
- package/dist/chunk-4WWJTYYA.js +2 -0
- package/dist/chunk-4WWJTYYA.js.map +1 -0
- package/dist/{chunk-W3HWTAF6.js → chunk-6RN7SUWT.js} +2 -2
- package/dist/{chunk-W3HWTAF6.js.map → chunk-6RN7SUWT.js.map} +1 -1
- package/dist/chunk-VDFIXLNO.js +20 -0
- package/dist/chunk-VDFIXLNO.js.map +1 -0
- package/dist/client/index.d.ts +4 -2
- package/dist/client/index.js +5 -5
- package/dist/client/index.js.map +1 -1
- package/dist/context/index.d.ts +2 -2
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{message-BnGtSz1P.d.ts → message-D3D59U_Q.d.ts} +4 -2
- package/dist/primitives/index.d.ts +3 -3
- package/dist/primitives/index.js +1 -1
- package/dist/{streaming-DrnCgnnh.d.ts → streaming-Q8hp5ev4.d.ts} +1 -0
- package/dist/styled/index.d.ts +67 -61
- package/dist/styled/index.js +1 -1
- package/dist/styles-no-preflight.css +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
- package/dist/chunk-65VDOUZG.js +0 -2
- package/dist/chunk-65VDOUZG.js.map +0 -1
- package/dist/chunk-DEH5ET5U.js +0 -20
- package/dist/chunk-DEH5ET5U.js.map +0 -1
package/dist/client/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as ChatMessage } from '../message-
|
|
1
|
+
import { C as ChatMessage } from '../message-D3D59U_Q.js';
|
|
2
2
|
import { B as BrandingData } from '../branding-SzYU4ncD.js';
|
|
3
|
-
import '../streaming-
|
|
3
|
+
import '../streaming-Q8hp5ev4.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Types for the Miiflow chat client (transport layer).
|
|
@@ -104,6 +104,8 @@ interface MiiflowChatResult {
|
|
|
104
104
|
handleToolInvocation: (invocation: ToolInvocationRequest) => Promise<boolean>;
|
|
105
105
|
/** Update the session externally (e.g. after token refresh) */
|
|
106
106
|
updateSession: (session: EmbedSession) => void;
|
|
107
|
+
/** Stop the current streaming response (aborts fetch, preserves partial content) */
|
|
108
|
+
stopStreaming: () => void;
|
|
107
109
|
}
|
|
108
110
|
interface JSONSchemaProperty {
|
|
109
111
|
type: "string" | "number" | "integer" | "boolean" | "array" | "object" | "null";
|
package/dist/client/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {b}from'../chunk-NSTK5EUQ.js';import {useState,useRef,useEffect,useMemo,useCallback}from'react';function A(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
|
|
1
|
+
import {b}from'../chunk-NSTK5EUQ.js';import {useState,useRef,useEffect,useMemo,useCallback}from'react';function A(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 $(){let t="miiflow-user-id",a=null;try{a=localStorage.getItem(t);}catch{}if(!a){a=`muid_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;try{localStorage.setItem(t,a);}catch{}}return a}async function fe(t){let a=A(t),u=await fetch(`${a}/api/embed/init`,{method:"POST",headers:{"Content-Type":"application/json","X-Embed-Public-Key":t.publicKey,"x-mii-user-id":$()},body:JSON.stringify({assistant_id:t.assistantId,user_data:{user_id:t.userId,name:t.userName,email:t.userEmail}})});if(!u.ok){let p=await u.text();throw new Error(`Init failed: ${u.status} - ${p}`)}let c=await u.json();if(!c.success)throw new Error(c.error||"Failed to initialize session");return {token:c.token,config:c.config,session_id:c.session_id}}async function ge(t,a){let u=A(t),c=await fetch(`${u}/api/embed/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`,"x-mii-user-id":$()},body:JSON.stringify({operationName:"CreateThread",variables:{input:{assistantId:a.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(!
|
|
6
|
-
`);
|
|
7
|
-
`)?
|
|
8
|
-
`).replace(/\\"/g,'"').replace(/\\t/g," ").replace(/\\\\/g,"\\"));}else if(i==="answer"){let a=e.chunk?.trim()||"",o=g.trim();a&&o&&a===o||(g+=e.chunk||"");}else b+=e.chunk||"";e.previous_message_id&&d.onUserMessageIdUpdate(u,e.previous_message_id),l();}else if(e.type==="claude_text"){g+=e.chunk||"";let i=s.find(a=>a.type==="claude_text");i?i.content+=e.chunk||"":s.push({type:"claude_text",content:e.chunk||"",orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_thinking")s.push({type:"claude_thinking",content:e.content||"",orchestrator:"claude_agent_sdk"}),l();else if(e.type==="claude_file_read"){let i={toolUseId:e.tool_use_id,operation:"read",filePath:e.file_path,status:e.status,content:e.content,totalLines:e.total_lines,language:e.language,error:e.error,durationMs:e.duration_ms},a=s.findIndex(o=>o.type==="file_operation"&&o.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=i:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_file_edit"){let i={toolUseId:e.tool_use_id,operation:"edit",filePath:e.file_path,status:e.status,oldString:e.old_string,newString:e.new_string,error:e.error,durationMs:e.duration_ms},a=s.findIndex(o=>o.type==="file_operation"&&o.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=i:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_file_write"){let i={toolUseId:e.tool_use_id,operation:"write",filePath:e.file_path,status:e.status,error:e.error,durationMs:e.duration_ms},a=s.findIndex(o=>o.type==="file_operation"&&o.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=i:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_bash"){let i={toolUseId:e.tool_use_id,command:e.command,description:e.description,status:e.status,stdout:e.stdout,stderr:e.stderr,exitCode:e.exit_code,durationMs:e.duration_ms},a=s.findIndex(o=>o.type==="terminal"&&o.toolUseId===e.tool_use_id);a>=0?s[a].terminalData=i:s.push({type:"terminal",content:"",toolUseId:e.tool_use_id,terminalData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_search"){let i={toolUseId:e.tool_use_id,tool:e.tool,pattern:e.pattern,path:e.path,status:e.status,results:(e.results||[]).map(o=>({filePath:o.file_path,lineNumber:o.line_number,snippet:o.snippet})),totalCount:e.total_count||0,error:e.error,durationMs:e.duration_ms},a=s.findIndex(o=>o.type==="search_results"&&o.toolUseId===e.tool_use_id);a>=0?s[a].searchResultsData=i:s.push({type:"search_results",content:"",toolUseId:e.tool_use_id,searchResultsData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_web_search"||e.type==="claude_web_fetch"){let i={toolUseId:e.tool_use_id,operation:e.type==="claude_web_search"?"search":"fetch",query:e.query,url:e.url,status:e.status,results:e.results,content:e.content,error:e.error,durationMs:e.duration_ms},a=s.findIndex(o=>o.type==="web_operation"&&o.toolUseId===e.tool_use_id);a>=0?s[a].webOperationData=i:s.push({type:"web_operation",content:"",toolUseId:e.tool_use_id,webOperationData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_subagent_start"){let i={subagentId:e.subagent_id,subagentType:e.subagent_type,description:e.description,prompt:e.prompt,status:"running",nestedChunks:[]};s.push({type:"subagent",content:"",toolUseId:e.parent_tool_use_id,subagentData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_subagent_chunk"){let i=s.findIndex(a=>a.type==="subagent"&&a.subagentData?.subagentId===e.subagent_id);i>=0&&s[i].subagentData&&s[i].subagentData.nestedChunks.push({type:e.is_tool?"tool":"answer",content:e.chunk||"",toolName:e.tool_name,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="claude_subagent_complete"){let i=s.findIndex(a=>a.type==="subagent"&&a.subagentData?.subagentId===e.subagent_id);i>=0&&s[i].subagentData&&(s[i].subagentData.status="completed",s[i].subagentData.result=e.result,s[i].subagentData.durationMs=e.duration_ms),l();}else if(e.type==="claude_tool_use"||e.type==="claude_tool_result"){let i={toolUseId:e.tool_use_id,toolName:e.tool_name,toolDescription:e.tool_description,toolInput:e.tool_input,status:e.type==="claude_tool_use"?"pending":e.is_error?"error":"completed",content:e.content,isError:e.is_error,durationMs:e.duration_ms},a=s.findIndex(o=>o.claudeToolData?.toolUseId===e.tool_use_id);a>=0?s[a].claudeToolData=i:s.push({type:"tool",content:e.content||"",toolUseId:e.tool_use_id,toolName:e.tool_name,toolDescription:e.tool_description,status:i.status==="pending"?"planned":"completed",claudeToolData:i,orchestrator:"claude_agent_sdk"}),l();}else if(e.type==="clarification_needed"){c();let i={question:e.question||"",options:e.options||[],context:e.context,allowFreeText:e.allow_free_text!==!1,subtaskId:e.subtask_id,subtaskDescription:e.subtask_description,subagentName:e.subagent_name,subagentRole:e.subagent_role};s.push({type:"clarification_needed",content:i.question,clarificationData:i,subtaskId:e.subtask_id}),j=i,g||(g=i.question),l();}else if(e.type==="media"){let i=e.media_data;i&&($=[...$,{id:i.id,url:i.url,mediaType:i.media_type||"image",altText:i.alt_text}],l());}else if(e.type==="assistant_complete"){c(),Z=!0;let i=e.message?.text_content||g,a=e.message?.id,o=e.message?.metadata?.sources,T=(Date.now()-_)/1e3;d.onComplete(y,i,a,s,O,o,j,T),g=i,a&&(y=a);break}else if(e.type==="client_tool_invocation"&&e.invocation&&d.onToolInvocation)d.onToolInvocation(e.invocation);else {if(e.type==="error")throw new Error(e.error||"Stream error");if(e.type==="done"){if(y&&!Z){c();let i=(Date.now()-_)/1e3;d.onComplete(y,g||"",e.message_id,s,O,void 0,j,i);}else e.message_id&&y&&d.onMessageUpdate({id:y,isStreaming:!1});e.message_id&&(y=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:y,assistantContent:g}}function Oe(t){let[n,u]=useState([]),[d,f]=useState(false),[_,g]=useState(null),[y,s]=useState(null),[O,j]=useState(true),[$,Z]=useState(null),m=useRef(t);m.current=t;let b$1=useRef(y);b$1.current=y;let B=useRef(d);B.current=d;let M=useRef(new Map),D=useRef(new Map);useEffect(()=>{let r=false;async function c(){try{let p=await ue(m.current);r||(s(p),j(!1));}catch(p){r||(Z(p instanceof Error?p.message:"Failed to initialize"),j(false));}}return c(),()=>{r=true;}},[t.publicKey,t.assistantId]);let z=useMemo(()=>Me(y),[y]),F=b(z),P=useRef(new Map),W=useCallback(async r=>{let c=b$1.current;if(!c)throw new Error("Not initialized");let p=await de(m.current,c,r);return P.current.set(p,{id:p,filename:r.name,mimeType:r.type,size:r.size,isImage:r.type.startsWith("image/"),isVideo:r.type.startsWith("video/"),isDocument:!r.type.startsWith("image/")&&!r.type.startsWith("video/")}),p},[]),q=useCallback(r=>{P.current.delete(r);},[]),E=useCallback(async r=>{let c=b$1.current;if(!c)throw new Error("Not initialized");let{invocation_id:p,tool_name:l,parameters:C}=r;console.log(`[Miiflow] Tool invocation received: "${l}" (id: ${p})`);let h=M.current.get(l);if(!h)return false;try{let k=await Promise.race([h(C),new Promise((ee,I)=>setTimeout(()=>I(new Error("Tool execution timeout (30s)")),3e4))]);return console.log(`[Miiflow] Tool "${l}" executed successfully (id: ${p})`),await G(m.current,c,{invocation_id:p,result:k}),console.log(`[Miiflow] Tool result sent for "${l}" (id: ${p})`),!0}catch(k){return console.error(`[Miiflow] Tool '${l}' execution failed:`,k),await G(m.current,c,{invocation_id:p,error:k instanceof Error?k.message:String(k)}),true}},[]);useEffect(()=>{if(!y)return;let r=y,c=null,p=null,l=null,C=0,h=false;function k(){if(h)return;let ee=Ae(m.current,r);c=new WebSocket(ee),c.onopen=()=>{console.log("[Miiflow] WebSocket connected"),C=0,p=setInterval(()=>{c?.readyState===WebSocket.OPEN&&c.send(JSON.stringify({type:"heartbeat"}));},Ie);},c.onmessage=I=>{try{let v=JSON.parse(I.data);v.type==="client_tool_invocation"&&v.invocation&&E(v.invocation).then(async S=>{if(!S){let e=m.current.onToolInvocationFallback;e&&await e(v.invocation)||G(m.current,r,{invocation_id:v.invocation.invocation_id,error:`No handler found for tool '${v.invocation.tool_name}'`}).catch(console.error);}}).catch(console.error);}catch{}},c.onclose=()=>{if(p&&(clearInterval(p),p=null),!h){let I=Math.min(xe*Math.pow(2,C),ve);C++,l=setTimeout(k,I);}},c.onerror=()=>{};}return k(),()=>{h=true,p&&clearInterval(p),l&&clearTimeout(l),c&&(c.onclose=null,c.close());}},[y,E]);let J=useCallback(async r=>{let c=b$1.current;if(!c)throw new Error("Not initialized");await pe(m.current,c,r);},[]),H=useCallback(async(r,c)=>{let p=b$1.current,l=!!r.trim(),C=c&&c.length>0;if(!l&&!C||B.current||!p)return;let h=`msg-${Date.now()}`,k=c?.map(S=>P.current.get(S)).filter(Boolean),ee={id:h,textContent:r,participant:{id:"user",name:m.current.userName||"You",role:"user"},createdAt:new Date().toISOString(),attachments:k?.length?k:void 0};c?.forEach(S=>P.current.delete(S));let I=`assistant-pending-${Date.now()}`,v={id:I,textContent:"",participant:{id:"assistant",name:p.config.branding?.custom_name||p.config.assistant_name,role:"assistant",avatarUrl:p.config.branding?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true};u(S=>[...S,ee,v]),f(true),g(I),m.current.onUserMessageCreated?.({id:h,content:r});try{let S=A(m.current),e=await fetch(`${S}/assistant/message/stream/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p.token}`,"x-mii-user-id":N()},body:JSON.stringify({thread_id:p.config.thread_id,text_content:r,message_id:h,metadata:{},attachment_ids:c||[]})});if(!e.ok)throw new Error(`HTTP error: ${e.status}`);let i=e.body?.getReader();if(!i)throw new Error("No response body");let a=await Ee(i,p,h,{onMessageCreate:o=>{g(o.id),u(T=>[...T.filter(R=>R.id!==I),o]);},onMessageUpdate:o=>{u(T=>T.map(x=>x.id===o.id?{...x,...o}:x));},onUserMessageIdUpdate:(o,T)=>{u(x=>x.map(R=>R.id===o?{...R,id:T}:R));},onComplete:(o,T,x,R,ae,_e,be,ye)=>{o&&u(we=>we.map(se=>se.id===o?{...se,id:x||se.id,textContent:T,isStreaming:!1,reasoning:R,suggestedActions:ae,citations:_e,pendingClarification:be,executionTime:ye}:se)),m.current.onAssistantMessageComplete?.({id:x||o||"",content:T});},onToolInvocation:async o=>{if(!await E(o)){let x=m.current.onToolInvocationFallback;if(!(x?await x(o):!1)){let ae=b$1.current;ae&&await G(m.current,ae,{invocation_id:o.invocation_id,error:`No handler found for tool '${o.tool_name}'`});}}}});a.assistantMsgId&&u(o=>o.map(T=>T.id===a.assistantMsgId?{...T,isStreaming:!1}:T));}catch(S){console.error("[Miiflow] Send error:",S);let e=b$1.current,i={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()};u(a=>[...a.filter(o=>o.id!==I),i]),Z(S instanceof Error?S.message:"Send failed");}finally{f(false),g(null);}},[E]),L=useCallback(async()=>{let r=b$1.current;if(!r)throw new Error("Not initialized");let c=await ce(m.current,r);c.token||console.warn("[Miiflow] CreateThread did not return new token \u2014 tools may register to wrong thread");let p={...r,config:{...r.config,thread_id:c.threadId},token:c.token||r.token};if(b$1.current=p,s(p),u([]),D.current.size>0){console.log(`[Miiflow] Re-registering ${D.current.size} tools on new thread`);try{await te(m.current,p,Array.from(D.current.values()));}catch(l){console.warn("[Miiflow] Failed to re-register tools:",l);}}return c.threadId},[]),X=useCallback(async r=>{let c=b$1.current;if(!c)throw new Error("Not initialized");ie(r),M.current.set(r.name,r.handler);let p=re(r);D.current.set(r.name,p);try{await te(m.current,c,[p]),console.log(`[Miiflow] Tool registered: "${r.name}"`);}catch(l){throw M.current.delete(r.name),D.current.delete(r.name),l}},[]),V=useCallback(async r=>{let c=b$1.current;if(!c)throw new Error("Not initialized");for(let h of r)ie(h);let p=new Map(M.current),l=new Map(D.current),C=[];for(let h of r){M.current.set(h.name,h.handler);let k=re(h);D.current.set(h.name,k),C.push(k);}try{await te(m.current,c,C);let h=r.map(k=>k.name);console.log(`[Miiflow] Tools registered: ${JSON.stringify(h)} (${r.length} tools)`);}catch(h){throw M.current=p,D.current=l,h}},[]),ne=useMemo(()=>n.map(r=>({id:r.id,textContent:r.textContent?.replace(/\[ref:[^\]]+\]/g,"")||r.textContent,participant:r.participant,createdAt:r.createdAt,isStreaming:r.isStreaming,reasoning:r.reasoning,suggestedActions:r.suggestedActions,citations:r.citations,attachments:r.attachments,pendingClarification:r.pendingClarification,executionTime:r.executionTime})),[n]),Q=useCallback(r=>{s(r);},[]);return {messages:ne,isStreaming:d,streamingMessageId:_,sendMessage:H,uploadFile:W,removeUploadedAttachment:q,session:y,loading:O,error:$,branding:z,brandingCSSVars:F,startNewThread:L,registerTool:X,registerTools:V,sendSystemEvent:J,handleToolInvocation:E,updateSession:Q}}function le(t){try{let n=t.split(".");if(n.length!==3)return null;let u=n[1].replace(/-/g,"+").replace(/_/g,"/"),d=atob(u),f=JSON.parse(d);return typeof f.exp=="number"?f.exp*1e3:null}catch{return null}}function Pe(t,n){let u=le(t);return u===null?true:u-Date.now()<=n}function Ne(t){let n=le(t);return n===null?true:Date.now()>=n}function Ue(t){let n=le(t);return n===null?0:Math.max(0,n-Date.now())}export{w as ToolValidationError,ce as createThread,A as getBackendBaseUrl,N as getOrCreateUserId,Ue as getTimeUntilExpiry,ue as initSession,Ne as isTokenExpired,Pe as isTokenExpiringSoon,le as parseTokenExpiry,te as registerToolsOnBackend,pe as sendSystemEvent,G as sendToolResult,re as serializeToolDefinition,ke as updateUser,de as uploadFile,Oe as useMiiflowChat,ie as validateToolDefinition};//# sourceMappingURL=index.js.map
|
|
5
|
+
}`})});if(!c.ok)throw new Error(`Failed to create thread: ${c.status}`);let p=await c.json(),_=p.data?.createThread?.thread?.id;if(!_)throw new Error("No thread ID returned");return {threadId:_,token:p.token}}async function De(t,a,u){let c=A(t);await fetch(`${c}/api/embed/update`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`},body:JSON.stringify({user_data:u})});}async function me(t,a,u){let p=`${A(t)}/api/embed/upload-attachment`,_=new FormData;_.append("file",u);let f=await fetch(p,{method:"POST",headers:{Authorization:`Bearer ${a.token}`,"x-mii-user-id":$()},body:_});if(!f.ok){let P=await f.text();throw new Error(`Upload failed: ${f.status} - ${P}`)}let o=(await f.json()).attachment?.id;if(!o)throw new Error("No attachment ID returned");return o}async function _e(t,a,u){let c=A(t),p=await fetch(`${c}/api/embed/system-event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`,"x-mii-user-id":$()},body:JSON.stringify({thread_id:a.config.thread_id,system_event:{action:u.action,description:u.description,followUpInstruction:u.followUpInstruction,metadata:u.metadata||{}}})});if(!p.ok){let f=await p.text();throw new Error(`Failed to send system event: ${p.status} - ${f}`)}let _=await p.json();if(!_.success)throw new Error(_.error||"Failed to send system event")}async function Z(t,a,u){let c=A(t),p=await fetch(`${c}/api/embed/tool-result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`},body:JSON.stringify(u)});if(!p.ok){let f=await p.text();throw new Error(`Failed to send tool result: ${p.status} - ${f}`)}let _=await p.json();if(!_.success)throw new Error(`Failed to send tool result: ${_.error}`)}async function ne(t,a,u){let c=A(t);if(u.length===1){let p=await fetch(`${c}/api/embed/register-tool`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`},body:JSON.stringify(u[0])});if(!p.ok){let f=await p.text();throw new Error(`Failed to register tool: ${p.status} - ${f}`)}let _=await p.json();if(!_.success)throw new Error(`Failed to register tool: ${_.error||"Unknown error"}`)}else if(u.length>1){let p=await fetch(`${c}/api/embed/register-tools`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.token}`},body:JSON.stringify(u)});if(!p.ok){let f=await p.text();throw new Error(`Failed to register tools: ${p.status} - ${f}`)}let _=await p.json();if(!_.success)throw new Error(`Failed to register tools: ${_.error||"Unknown error"}`)}}var be=new Set(["string","number","integer","boolean","array","object","null"]),Ie=/^[a-zA-Z_][a-zA-Z0-9_]*$/,y=class extends Error{constructor(a){super(a),this.name="ToolValidationError";}};function ce(t){if(!t.name)throw new y("Tool name is required");if(!t.description)throw new y("Tool description is required");if(!t.parameters)throw new y("Tool parameters schema is required");if(typeof t.handler!="function")throw new y("Tool handler must be a function");xe(t.name),ve(t.description),Ae(t.parameters);}function xe(t){if(typeof t!="string")throw new y("Tool name must be a string");if(t.length===0)throw new y("Tool name cannot be empty");if(t.length>64)throw new y("Tool name too long (max 64 characters)");if(!Ie.test(t))throw new y("Tool name must start with letter/underscore and contain only alphanumeric characters and underscores")}function ve(t){if(typeof t!="string")throw new y("Tool description must be a string");if(t.trim().length===0)throw new y("Tool description cannot be empty");if(t.length>500)throw new y("Tool description too long (max 500 characters)")}function Ae(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Parameters must be a JSON Schema object");if(t.type!=="object")throw new y("Parameters schema must be of type 'object' (function parameters)");if(t.properties&&typeof t.properties=="object")for(let[a,u]of Object.entries(t.properties))ue(a,u);if(t.required!==void 0){if(!Array.isArray(t.required))throw new y("'required' must be an array");for(let a of t.required)if(typeof a!="string")throw new y("'required' array must contain only strings")}if(t.additionalProperties!==void 0&&typeof t.additionalProperties!="boolean"&&(typeof t.additionalProperties!="object"||t.additionalProperties===null))throw new y("'additionalProperties' must be boolean or object")}function ue(t,a){if(typeof a!="object"||a===null||Array.isArray(a))throw new y(`Property '${t}' schema must be an object`);if(a.type!==void 0){let u=Array.isArray(a.type)?a.type:[a.type];for(let c of u)if(!be.has(c))throw new y(`Invalid type '${c}' for property '${t}'. Valid types: ${Array.from(be).join(", ")}`)}if(a.enum!==void 0&&!Array.isArray(a.enum))throw new y(`Property '${t}' enum must be an array`);if(a.properties&&typeof a.properties=="object")for(let[u,c]of Object.entries(a.properties))ue(`${t}.${u}`,c);a.items&&(Array.isArray(a.items)?a.items.forEach((u,c)=>{ue(`${t}[${c}]`,u);}):ue(`${t}[]`,a.items));}function de(t){return {name:t.name,description:t.description,parameters:t.parameters}}var Me=21e3,Ee=1e3,Oe=3e4;function Pe(t,a){if(t.webSocketUrl){let f=new URL(t.webSocketUrl);return f.pathname=`/ws/assistant/thread/${a.config.thread_id}/`,f.searchParams.set("role","user"),f.searchParams.set("user_id",$()),f.searchParams.set("embed_token",a.token),f.toString()}let p=A(t).replace(/\/api$/,"").replace(/^https:/,"wss:").replace(/^http:/,"ws:"),_=$();return `${p}/ws/assistant/thread/${a.config.thread_id}/?role=user&user_id=${encodeURIComponent(_)}&embed_token=${encodeURIComponent(a.token)}`}function Ne(t){let a=t?.config.branding;return a?{customName:a.custom_name,messageFontSize:a.message_font_size,welcomeMessage:a.welcome_message,chatboxPlaceholder:a.chatbox_placeholder,backgroundBubbleColor:a.background_bubble_color,headerBackgroundColor:a.header_background_color,showHeader:a.show_header,rotatingPlaceholders:a.rotating_placeholders,presetQuestions:a.preset_questions,chatbotLogo:a.chatbot_logo,assistantAvatar:a.assistant_avatar}:null}async function Ue(t,a,u,c){let p=new TextDecoder,_=Date.now(),f="",b=null,o=[],P,J,R=[],ee=false,g="answer",h="",M,B,x,D,z,H,N,L,X,E,V,G,Y,K,ae=false,te="",se=a.config.branding,U=()=>{(h||g==="tool")&&(o.push({type:g,content:h,toolName:M,toolDescription:B,success:x,status:D,subtaskId:z,planData:H,subtaskData:N,isSynthesis:L,isReplan:X,toolArgs:E,replanAttempt:V,maxReplans:G,failureReason:Y,progress:K}),h="",M=void 0,B=void 0,x=void 0,D=void 0,z=void 0,H=void 0,N=void 0,L=void 0,X=void 0,E=void 0,V=void 0,G=void 0,Y=void 0,K=void 0);},r=()=>{let d=o.map(m=>m);return (h||g==="tool")&&d.push({type:g,content:h,toolName:M,toolDescription:B,success:x,status:D,subtaskId:z,planData:H,subtaskData:N,isSynthesis:L,isReplan:X,toolArgs:E,replanAttempt:V,maxReplans:G,failureReason:Y,progress:K}),d},s=()=>{let d=r();if(b)c.onMessageUpdate({id:b,textContent:f,reasoning:d,suggestedActions:P,medias:R.length>0?R:void 0});else {b=`assistant-${Date.now()}`;let m={id:b,textContent:f,participant:{id:"assistant",name:se?.custom_name||a.config.assistant_name,role:"assistant",avatarUrl:se?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true,reasoning:d,suggestedActions:P,medias:R.length>0?R:void 0};c.onMessageCreate(m);}};for(;;){let{done:d,value:m}=await t.read();if(d)break;let S=p.decode(m,{stream:true}),w=(te+S).split(`
|
|
6
|
+
`);S.endsWith(`
|
|
7
|
+
`)?te="":te=w.pop()||"";for(let F of w){if(!F.startsWith("data: "))continue;let v=F.slice(6);if(v==="[DONE]")break;try{let e=JSON.parse(v);if(e.type==="assistant_chunk"){if(e.is_tool_planned){(h||g!=="answer")&&(U(),g="answer"),o.push({type:"tool",content:"",toolName:e.tool_name,toolDescription:e.tool_description,status:"planned",subtaskId:e.subtask_id}),s();continue}if(e.is_tool_executing){for(let n=o.length-1;n>=0;n--){let l=o[n];if(l.type==="tool"&&l.toolName===e.tool_name&&(e.subtask_id===void 0||l.subtaskId===e.subtask_id)){o[n].status="executing";break}}s();continue}if(e.is_observation){for(let n=o.length-1;n>=0;n--){let l=o[n];if(l.type==="tool"&&l.toolName===e.tool_name&&(e.subtask_id===void 0||l.subtaskId===e.subtask_id)){o[n].status="completed";break}}s();continue}if(e.suggested_actions){P=e.suggested_actions.map(n=>({id:n.action,label:n.label,value:n.action})),s();continue}if(e.is_wave_start){(h||g!=="answer")&&(U(),g="answer"),o.push({type:"wave_start",content:"",waveNumber:e.wave_number,isParallel:!0,waveData:{waveNumber:e.wave_number,subtaskIds:e.subtask_ids||[],parallelCount:e.parallel_count||0,totalWaves:e.total_waves||1}}),s();continue}if(e.is_wave_complete){o.push({type:"wave_complete",content:"",waveNumber:e.wave_number,isParallel:!0,waveData:{waveNumber:e.wave_number,subtaskIds:[],parallelCount:0,totalWaves:0,completedIds:e.completed_ids||[],success:e.success,executionTime:e.execution_time}}),s();continue}if(e.is_parallel_subtask_start){o.push({type:"parallel_subtask_start",content:"",subtaskId:e.subtask_id,waveNumber:e.wave_number,isParallel:!0,parallelSubtaskData:{subtaskId:e.subtask_id,waveNumber:e.wave_number,description:e.description}}),s();continue}if(e.is_parallel_subtask_complete){o.push({type:"parallel_subtask_complete",content:"",subtaskId:e.subtask_id,waveNumber:e.wave_number,isParallel:!0,success:e.success,parallelSubtaskData:{subtaskId:e.subtask_id,waveNumber:e.wave_number,success:e.success,result:e.result,error:e.error,executionTime:e.execution_time}}),s();continue}if(e.is_multi_agent_planning){ae=!0,(h||g!=="answer")&&(U(),g="answer"),o.push({type:"multi_agent_planning",content:"",isMultiAgent:!0}),s();continue}if(e.is_reasoning&&e.reasoning_delta){let n=o.findIndex(l=>l.type==="thinking"&&l.isMultiAgent);n>=0?o[n]={...o[n],content:(o[n].content||"")+e.reasoning_delta}:o.push({type:"thinking",content:e.reasoning_delta,isMultiAgent:!0}),s();continue}if(e.is_multi_agent_planning_complete){let n=o.findIndex(l=>l.type==="multi_agent_planning"&&l.isMultiAgent);n>=0?o[n]={...o[n],subagentAllocations:e.subagents||[]}:o.push({type:"multi_agent_planning",content:"",isMultiAgent:!0,subagentAllocations:e.subagents||[]}),s();continue}if(e.is_multi_agent_execution_start)continue;if(e.is_subagent_start){o.push({type:"subagent_start",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,task:e.task,status:"running"}}),s();continue}if(e.is_subagent_progress){let n=o.findIndex(l=>l.type==="subagent_start"&&l.subagentInfo?.id===e.subagent_id);n!==-1&&o[n].subagentInfo&&(o[n]={...o[n],content:e.progress||""}),s();continue}if(e.is_subagent_complete){o.push({type:"subagent_complete",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,status:"completed",result:e.result,executionTime:e.execution_time}}),s();continue}if(e.is_subagent_failed){o.push({type:"subagent_failed",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,status:"failed",error:e.error}}),s();continue}if(e.is_synthesis_start&&ae){o.push({type:"synthesis",content:"",isMultiAgent:!0,isSynthesis:!0}),s();continue}if(e.plan_data){let n=e.plan_data;H={goal:n.goal||"",reasoning:n.reasoning||"",subtasks:(n.subtasks||[]).map(l=>({id:Number(l.id),description:l.description,required_tools:l.required_tools,dependencies:l.dependencies,status:"pending"})),total_subtasks:n.subtasks?.length||0,completed_subtasks:0,failed_subtasks:0,progress_percentage:0};}e.subtask_data&&(N=e.subtask_data),e.is_synthesis_start&&(L=!0),e.is_replan&&(X=!0),e.tool_args&&(E=e.tool_args),e.replan_attempt!==void 0&&(V=e.replan_attempt),e.max_replans!==void 0&&(G=e.max_replans),e.failure_reason&&(Y=e.failure_reason),e.progress&&(K=e.progress);let i="answer";if(e.is_thinking?i="thinking":e.is_planning||e.is_plan_complete||e.is_replanning?i="planning":e.is_subtask_start||e.is_subtask_complete||e.is_subtask_failed?i="subtask":e.is_progress_update&&(i="progress"),i!==g&&(U(),g=i),e.tool_name&&(M=e.tool_name),e.success!==void 0&&(x=e.success),e.subtask_id!==void 0&&(z=e.subtask_id),i==="thinking"){h+=e.chunk||"";let n=h.match(/"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/);n&&(h=n[1].replace(/\\n/g,`
|
|
8
|
+
`).replace(/\\"/g,'"').replace(/\\t/g," ").replace(/\\\\/g,"\\"));}else if(i==="answer"){let n=e.chunk?.trim()||"",l=f.trim();n&&l&&n===l||(f+=e.chunk||"");}else h+=e.chunk||"";e.previous_message_id&&c.onUserMessageIdUpdate(u,e.previous_message_id),s();}else if(e.type==="claude_text"){f+=e.chunk||"";let i=o.find(n=>n.type==="claude_text");i?i.content+=e.chunk||"":o.push({type:"claude_text",content:e.chunk||"",orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_thinking")o.push({type:"claude_thinking",content:e.content||"",orchestrator:"claude_agent_sdk"}),s();else if(e.type==="claude_file_read"){let i={toolUseId:e.tool_use_id,operation:"read",filePath:e.file_path,status:e.status,content:e.content,totalLines:e.total_lines,language:e.language,error:e.error,durationMs:e.duration_ms},n=o.findIndex(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);n>=0?o[n].fileOperationData=i:o.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_file_edit"){let i={toolUseId:e.tool_use_id,operation:"edit",filePath:e.file_path,status:e.status,oldString:e.old_string,newString:e.new_string,error:e.error,durationMs:e.duration_ms},n=o.findIndex(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);n>=0?o[n].fileOperationData=i:o.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_file_write"){let i={toolUseId:e.tool_use_id,operation:"write",filePath:e.file_path,status:e.status,error:e.error,durationMs:e.duration_ms},n=o.findIndex(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);n>=0?o[n].fileOperationData=i:o.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_bash"){let i={toolUseId:e.tool_use_id,command:e.command,description:e.description,status:e.status,stdout:e.stdout,stderr:e.stderr,exitCode:e.exit_code,durationMs:e.duration_ms},n=o.findIndex(l=>l.type==="terminal"&&l.toolUseId===e.tool_use_id);n>=0?o[n].terminalData=i:o.push({type:"terminal",content:"",toolUseId:e.tool_use_id,terminalData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_search"){let i={toolUseId:e.tool_use_id,tool:e.tool,pattern:e.pattern,path:e.path,status:e.status,results:(e.results||[]).map(l=>({filePath:l.file_path,lineNumber:l.line_number,snippet:l.snippet})),totalCount:e.total_count||0,error:e.error,durationMs:e.duration_ms},n=o.findIndex(l=>l.type==="search_results"&&l.toolUseId===e.tool_use_id);n>=0?o[n].searchResultsData=i:o.push({type:"search_results",content:"",toolUseId:e.tool_use_id,searchResultsData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_web_search"||e.type==="claude_web_fetch"){let i={toolUseId:e.tool_use_id,operation:e.type==="claude_web_search"?"search":"fetch",query:e.query,url:e.url,status:e.status,results:e.results,content:e.content,error:e.error,durationMs:e.duration_ms},n=o.findIndex(l=>l.type==="web_operation"&&l.toolUseId===e.tool_use_id);n>=0?o[n].webOperationData=i:o.push({type:"web_operation",content:"",toolUseId:e.tool_use_id,webOperationData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_subagent_start"){let i={subagentId:e.subagent_id,subagentType:e.subagent_type,description:e.description,prompt:e.prompt,status:"running",nestedChunks:[]};o.push({type:"subagent",content:"",toolUseId:e.parent_tool_use_id,subagentData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_subagent_chunk"){let i=o.findIndex(n=>n.type==="subagent"&&n.subagentData?.subagentId===e.subagent_id);i>=0&&o[i].subagentData&&o[i].subagentData.nestedChunks.push({type:e.is_tool?"tool":"answer",content:e.chunk||"",toolName:e.tool_name,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="claude_subagent_complete"){let i=o.findIndex(n=>n.type==="subagent"&&n.subagentData?.subagentId===e.subagent_id);i>=0&&o[i].subagentData&&(o[i].subagentData.status="completed",o[i].subagentData.result=e.result,o[i].subagentData.durationMs=e.duration_ms),s();}else if(e.type==="claude_tool_use"||e.type==="claude_tool_result"){let i={toolUseId:e.tool_use_id,toolName:e.tool_name,toolDescription:e.tool_description,toolInput:e.tool_input,status:e.type==="claude_tool_use"?"pending":e.is_error?"error":"completed",content:e.content,isError:e.is_error,durationMs:e.duration_ms},n=o.findIndex(l=>l.claudeToolData?.toolUseId===e.tool_use_id);n>=0?o[n].claudeToolData=i:o.push({type:"tool",content:e.content||"",toolUseId:e.tool_use_id,toolName:e.tool_name,toolDescription:e.tool_description,status:i.status==="pending"?"planned":"completed",claudeToolData:i,orchestrator:"claude_agent_sdk"}),s();}else if(e.type==="clarification_needed"){U();let i={question:e.question||"",options:e.options||[],context:e.context,allowFreeText:e.allow_free_text!==!1,subtaskId:e.subtask_id,subtaskDescription:e.subtask_description,subagentName:e.subagent_name,subagentRole:e.subagent_role,toolCallId:e.tool_call_id};o.push({type:"clarification_needed",content:i.question,clarificationData:i,subtaskId:e.subtask_id}),J=i,f||(f=i.question),s();}else if(e.type==="media"){let i=e.media_data;i&&(R=[...R,{id:i.id,url:i.url,mediaType:i.media_type||"image",altText:i.alt_text}],s());}else if(e.type==="assistant_complete"){U(),ee=!0;let i=e.message?.text_content||f,n=e.message?.id,l=e.message?.metadata?.sources,W=(Date.now()-_)/1e3;c.onComplete(b,i,n,o,P,l,J,W),f=i,n&&(b=n);break}else if(e.type==="client_tool_invocation"&&e.invocation&&c.onToolInvocation)c.onToolInvocation(e.invocation);else {if(e.type==="error")throw new Error(e.error||"Stream error");if(e.type==="done"){if(b&&!ee){U();let i=(Date.now()-_)/1e3;c.onComplete(b,f||"",e.message_id,o,P,void 0,J,i);}else e.message_id&&b&&c.onMessageUpdate({id:b,isStreaming:!1});e.message_id&&(b=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:b,assistantContent:f}}function $e(t){let[a,u]=useState([]),[c,p]=useState(false),[_,f]=useState(null),[b$1,o]=useState(null),[P,J]=useState(true),[R,ee]=useState(null),g=useRef(t);g.current=t;let h=useRef(b$1);h.current=b$1;let M=useRef(c);M.current=c;let B=useRef(null),x=useRef(new Map),D=useRef(new Map);useEffect(()=>{let r=false;async function s(){try{let d=await fe(g.current);r||(o(d),J(!1));}catch(d){r||(ee(d instanceof Error?d.message:"Failed to initialize"),J(false));}}return s(),()=>{r=true;}},[t.publicKey,t.assistantId]);let z=useMemo(()=>Ne(b$1),[b$1]),H=b(z),N=useRef(new Map),L=useCallback(async r=>{let s=h.current;if(!s)throw new Error("Not initialized");let d=await me(g.current,s,r);return N.current.set(d,{id:d,filename:r.name,mimeType:r.type,size:r.size,isImage:r.type.startsWith("image/"),isVideo:r.type.startsWith("video/"),isDocument:!r.type.startsWith("image/")&&!r.type.startsWith("video/")}),d},[]),X=useCallback(r=>{N.current.delete(r);},[]),E=useCallback(async r=>{let s=h.current;if(!s)throw new Error("Not initialized");let{invocation_id:d,tool_name:m,parameters:S}=r;console.log(`[Miiflow] Tool invocation received: "${m}" (id: ${d})`);let k=x.current.get(m);if(!k)return false;try{let w=await Promise.race([k(S),new Promise((F,v)=>setTimeout(()=>v(new Error("Tool execution timeout (30s)")),3e4))]);return console.log(`[Miiflow] Tool "${m}" executed successfully (id: ${d})`),await Z(g.current,s,{invocation_id:d,result:w}),console.log(`[Miiflow] Tool result sent for "${m}" (id: ${d})`),!0}catch(w){return console.error(`[Miiflow] Tool '${m}' execution failed:`,w),await Z(g.current,s,{invocation_id:d,error:w instanceof Error?w.message:String(w)}),true}},[]);useEffect(()=>{if(!b$1)return;let r=b$1,s=null,d=null,m=null,S=0,k=false;function w(){if(k)return;let F=Pe(g.current,r);s=new WebSocket(F),s.onopen=()=>{console.log("[Miiflow] WebSocket connected"),S=0,d=setInterval(()=>{s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify({type:"heartbeat"}));},Me);},s.onmessage=v=>{try{let e=JSON.parse(v.data);e.type==="client_tool_invocation"&&e.invocation&&E(e.invocation).then(async i=>{if(!i){let n=g.current.onToolInvocationFallback;n&&await n(e.invocation)||Z(g.current,r,{invocation_id:e.invocation.invocation_id,error:`No handler found for tool '${e.invocation.tool_name}'`}).catch(console.error);}}).catch(console.error);}catch{}},s.onclose=()=>{if(d&&(clearInterval(d),d=null),!k){let v=Math.min(Ee*Math.pow(2,S),Oe);S++,m=setTimeout(w,v);}},s.onerror=()=>{};}return w(),()=>{k=true,d&&clearInterval(d),m&&clearTimeout(m),s&&(s.onclose=null,s.close());}},[b$1,E]);let V=useCallback(async r=>{let s=h.current;if(!s)throw new Error("Not initialized");await _e(g.current,s,r);},[]),G=useCallback(async(r,s,d)=>{let m=h.current,S=!!r.trim(),k=s&&s.length>0;if(!S&&!k||M.current||!m)return;M.current=true;let w=`msg-${Date.now()}`,F=!!d?.is_clarification_response,v=s?.map(n=>N.current.get(n)).filter(Boolean);s?.forEach(n=>N.current.delete(n));let e=`assistant-pending-${Date.now()}`,i={id:e,textContent:"",participant:{id:"assistant",name:m.config.branding?.custom_name||m.config.assistant_name,role:"assistant",avatarUrl:m.config.branding?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true};if(F)u(n=>[...n,i]);else {let n={id:w,textContent:r,participant:{id:"user",name:g.current.userName||"You",role:"user"},createdAt:new Date().toISOString(),attachments:v?.length?v:void 0};u(l=>[...l,n,i]),g.current.onUserMessageCreated?.({id:w,content:r});}p(true),f(e);try{let n=A(g.current),l=new AbortController;B.current=l;let W=await fetch(`${n}/assistant/message/stream/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m.token}`,"x-mii-user-id":$()},body:JSON.stringify({thread_id:m.config.thread_id,text_content:r,message_id:w,metadata:d||{},attachment_ids:s||[]}),signal:l.signal});if(!W.ok)throw new Error(`HTTP error: ${W.status}`);let oe=W.body?.getReader();if(!oe)throw new Error("No response body");let ie=await Ue(oe,m,w,{onMessageCreate:C=>{f(C.id),u(T=>[...T.filter(j=>j.id!==e),C]);},onMessageUpdate:C=>{u(T=>T.map(I=>I.id===C.id?{...I,...C}:I));},onUserMessageIdUpdate:(C,T)=>{u(I=>I.map(j=>j.id===C?{...j,id:T}:j));},onComplete:(C,T,I,j,re,ke,Ce,Se)=>{C&&u(Te=>Te.map(le=>le.id===C?{...le,id:I||le.id,textContent:T,isStreaming:!1,reasoning:j,suggestedActions:re,citations:ke,pendingClarification:Ce,executionTime:Se}:le)),g.current.onAssistantMessageComplete?.({id:I||C||"",content:T});},onToolInvocation:async C=>{if(!await E(C)){let I=g.current.onToolInvocationFallback;if(!(I?await I(C):!1)){let re=h.current;re&&await Z(g.current,re,{invocation_id:C.invocation_id,error:`No handler found for tool '${C.tool_name}'`});}}}});ie.assistantMsgId&&u(C=>C.map(T=>T.id===ie.assistantMsgId?{...T,isStreaming:!1}:T));}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;console.error("[Miiflow] Send error:",n);let l=h.current,W={id:`error-${Date.now()}`,textContent:"Sorry, I encountered an error. Please try again.",participant:{id:"assistant",name:l?.config.branding?.custom_name||l?.config.assistant_name||"Assistant",role:"assistant",avatarUrl:l?.config.branding?.assistant_avatar},createdAt:new Date().toISOString()};u(oe=>[...oe.filter(ie=>ie.id!==e),W]),ee(n instanceof Error?n.message:"Send failed");}finally{B.current=null,p(false),f(null);}},[E]),Y=useCallback(()=>{M.current&&(B.current?.abort(),B.current=null,u(r=>r.map(s=>s.isStreaming?{...s,isStreaming:false}:s)),M.current=false,p(false),f(null));},[]),K=useCallback(async()=>{let r=h.current;if(!r)throw new Error("Not initialized");let s=await ge(g.current,r);s.token||console.warn("[Miiflow] CreateThread did not return new token \u2014 tools may register to wrong thread");let d={...r,config:{...r.config,thread_id:s.threadId},token:s.token||r.token};if(h.current=d,o(d),u([]),D.current.size>0){console.log(`[Miiflow] Re-registering ${D.current.size} tools on new thread`);try{await ne(g.current,d,Array.from(D.current.values()));}catch(m){console.warn("[Miiflow] Failed to re-register tools:",m);}}return s.threadId},[]),ae=useCallback(async r=>{let s=h.current;if(!s)throw new Error("Not initialized");ce(r),x.current.set(r.name,r.handler);let d=de(r);D.current.set(r.name,d);try{await ne(g.current,s,[d]),console.log(`[Miiflow] Tool registered: "${r.name}"`);}catch(m){throw x.current.delete(r.name),D.current.delete(r.name),m}},[]),te=useCallback(async r=>{let s=h.current;if(!s)throw new Error("Not initialized");for(let k of r)ce(k);let d=new Map(x.current),m=new Map(D.current),S=[];for(let k of r){x.current.set(k.name,k.handler);let w=de(k);D.current.set(k.name,w),S.push(w);}try{await ne(g.current,s,S);let k=r.map(w=>w.name);console.log(`[Miiflow] Tools registered: ${JSON.stringify(k)} (${r.length} tools)`);}catch(k){throw x.current=d,D.current=m,k}},[]),se=useMemo(()=>a.map(r=>({id:r.id,textContent:r.textContent?.replace(/\[ref:[^\]]+\]/g,"")||r.textContent,participant:r.participant,createdAt:r.createdAt,isStreaming:r.isStreaming,reasoning:r.reasoning,suggestedActions:r.suggestedActions,citations:r.citations,attachments:r.attachments,pendingClarification:r.pendingClarification,executionTime:r.executionTime})),[a]),U=useCallback(r=>{o(r);},[]);return {messages:se,isStreaming:c,streamingMessageId:_,sendMessage:G,uploadFile:L,removeUploadedAttachment:X,session:b$1,loading:P,error:R,branding:z,brandingCSSVars:H,startNewThread:K,registerTool:ae,registerTools:te,sendSystemEvent:V,handleToolInvocation:E,updateSession:U,stopStreaming:Y}}function pe(t){try{let a=t.split(".");if(a.length!==3)return null;let u=a[1].replace(/-/g,"+").replace(/_/g,"/"),c=atob(u),p=JSON.parse(c);return typeof p.exp=="number"?p.exp*1e3:null}catch{return null}}function Re(t,a){let u=pe(t);return u===null?true:u-Date.now()<=a}function Be(t){let a=pe(t);return a===null?true:Date.now()>=a}function je(t){let a=pe(t);return a===null?0:Math.max(0,a-Date.now())}export{y as ToolValidationError,ge as createThread,A as getBackendBaseUrl,$ as getOrCreateUserId,je as getTimeUntilExpiry,fe as initSession,Be as isTokenExpired,Re as isTokenExpiringSoon,pe as parseTokenExpiry,ne as registerToolsOnBackend,_e as sendSystemEvent,Z as sendToolResult,de as serializeToolDefinition,De as updateUser,me as uploadFile,$e as useMiiflowChat,ce as validateToolDefinition};//# sourceMappingURL=index.js.map
|
|
9
9
|
//# sourceMappingURL=index.js.map
|