@miiflow/assistant-ui 0.3.2 → 0.3.3

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.
@@ -2,8 +2,8 @@ import {b}from'../chunk-NSTK5EUQ.js';import {useState,useRef,useEffect,useMemo,u
2
2
  createThread(input: $input) {
3
3
  thread { id status name isPreview }
4
4
  }
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 ke(t,n,u){let c=E(t);await fetch(`${c}/api/embed/update`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({user_data:u})});}async function de(t,n,u){let p=`${E(t)}/api/embed/upload-attachment`,_=new FormData;_.append("file",u);let f=await fetch(p,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"x-mii-user-id":U()},body:_});if(!f.ok){let P=await f.text();throw new Error(`Upload failed: ${f.status} - ${P}`)}let s=(await f.json()).attachment?.id;if(!s)throw new Error("No attachment ID returned");return s}async function pe(t,n,u){let c=E(t),p=await fetch(`${c}/api/embed/system-event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"x-mii-user-id":U()},body:JSON.stringify({thread_id:n.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 G(t,n,u){let c=E(t),p=await fetch(`${c}/api/embed/tool-result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.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 Q(t,n,u){let c=E(t);if(u.length===1){let p=await fetch(`${c}/api/embed/register-tool`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.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 ${n.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 ge=new Set(["string","number","integer","boolean","array","object","null"]),Se=/^[a-zA-Z_][a-zA-Z0-9_]*$/,y=class extends Error{constructor(n){super(n),this.name="ToolValidationError";}};function ie(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");Ce(t.name),Te(t.description),Ie(t.parameters);}function Ce(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(!Se.test(t))throw new y("Tool name must start with letter/underscore and contain only alphanumeric characters and underscores")}function Te(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 Ie(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[n,u]of Object.entries(t.properties))oe(n,u);if(t.required!==void 0){if(!Array.isArray(t.required))throw new y("'required' must be an array");for(let n of t.required)if(typeof n!="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 oe(t,n){if(typeof n!="object"||n===null||Array.isArray(n))throw new y(`Property '${t}' schema must be an object`);if(n.type!==void 0){let u=Array.isArray(n.type)?n.type:[n.type];for(let c of u)if(!ge.has(c))throw new y(`Invalid type '${c}' for property '${t}'. Valid types: ${Array.from(ge).join(", ")}`)}if(n.enum!==void 0&&!Array.isArray(n.enum))throw new y(`Property '${t}' enum must be an array`);if(n.properties&&typeof n.properties=="object")for(let[u,c]of Object.entries(n.properties))oe(`${t}.${u}`,c);n.items&&(Array.isArray(n.items)?n.items.forEach((u,c)=>{oe(`${t}[${c}]`,u);}):oe(`${t}[]`,n.items));}function re(t){return {name:t.name,description:t.description,parameters:t.parameters}}var De=21e3,xe=1e3,ve=3e4;function Ae(t,n){if(t.webSocketUrl){let f=new URL(t.webSocketUrl);return f.pathname=`/ws/assistant/thread/${n.config.thread_id}/`,f.searchParams.set("role","user"),f.searchParams.set("user_id",U()),f.searchParams.set("embed_token",n.token),f.toString()}let p=E(t).replace(/\/api$/,"").replace(/^https:/,"wss:").replace(/^http:/,"ws:"),_=U();return `${p}/ws/assistant/thread/${n.config.thread_id}/?role=user&user_id=${encodeURIComponent(_)}&embed_token=${encodeURIComponent(n.token)}`}function Me(t){let n=t?.config.branding;return n?{customName:n.custom_name,messageFontSize:n.message_font_size,welcomeMessage:n.welcome_message,chatboxPlaceholder:n.chatbox_placeholder,backgroundBubbleColor:n.background_bubble_color,headerBackgroundColor:n.header_background_color,showHeader:n.show_header,rotatingPlaceholders:n.rotating_placeholders,presetQuestions:n.preset_questions,chatbotLogo:n.chatbot_logo,assistantAvatar:n.assistant_avatar}:null}async function Ee(t,n,u,c){let p=new TextDecoder,_=Date.now(),f="",b=null,s=[],P,z,ee=false,I="answer",g="",S,F,A,x,B,W,N,q,J,O,H,L,X,V,te=false,Z="",ne=n.config.branding,o=()=>{(g||I==="tool")&&(s.push({type:I,content:g,toolName:S,toolDescription:F,success:A,status:x,subtaskId:B,planData:W,subtaskData:N,isSynthesis:q,isReplan:J,toolArgs:O,replanAttempt:H,maxReplans:L,failureReason:X,progress:V}),g="",S=void 0,F=void 0,A=void 0,x=void 0,B=void 0,W=void 0,N=void 0,q=void 0,J=void 0,O=void 0,H=void 0,L=void 0,X=void 0,V=void 0);},d=()=>{let m=s.map(C=>C);return (g||I==="tool")&&m.push({type:I,content:g,toolName:S,toolDescription:F,success:A,status:x,subtaskId:B,planData:W,subtaskData:N,isSynthesis:q,isReplan:J,toolArgs:O,replanAttempt:H,maxReplans:L,failureReason:X,progress:V}),m},i=()=>{let m=d();if(b)c.onMessageUpdate({id:b,textContent:f,reasoning:m,suggestedActions:P});else {b=`assistant-${Date.now()}`;let C={id:b,textContent:f,participant:{id:"assistant",name:ne?.custom_name||n.config.assistant_name,role:"assistant",avatarUrl:ne?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true,reasoning:m,suggestedActions:P};c.onMessageCreate(C);}};for(;;){let{done:m,value:C}=await t.read();if(m)break;let h=p.decode(C,{stream:true}),j=(Z+h).split(`
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 ke(t,n,u){let c=E(t);await fetch(`${c}/api/embed/update`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({user_data:u})});}async function de(t,n,u){let p=`${E(t)}/api/embed/upload-attachment`,_=new FormData;_.append("file",u);let f=await fetch(p,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"x-mii-user-id":U()},body:_});if(!f.ok){let P=await f.text();throw new Error(`Upload failed: ${f.status} - ${P}`)}let s=(await f.json()).attachment?.id;if(!s)throw new Error("No attachment ID returned");return s}async function pe(t,n,u){let c=E(t),p=await fetch(`${c}/api/embed/system-event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"x-mii-user-id":U()},body:JSON.stringify({thread_id:n.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 G(t,n,u){let c=E(t),p=await fetch(`${c}/api/embed/tool-result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.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 Q(t,n,u){let c=E(t);if(u.length===1){let p=await fetch(`${c}/api/embed/register-tool`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.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 ${n.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 ge=new Set(["string","number","integer","boolean","array","object","null"]),Se=/^[a-zA-Z_][a-zA-Z0-9_]*$/,y=class extends Error{constructor(n){super(n),this.name="ToolValidationError";}};function ie(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");Ce(t.name),Te(t.description),Ie(t.parameters);}function Ce(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(!Se.test(t))throw new y("Tool name must start with letter/underscore and contain only alphanumeric characters and underscores")}function Te(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 Ie(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[n,u]of Object.entries(t.properties))oe(n,u);if(t.required!==void 0){if(!Array.isArray(t.required))throw new y("'required' must be an array");for(let n of t.required)if(typeof n!="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 oe(t,n){if(typeof n!="object"||n===null||Array.isArray(n))throw new y(`Property '${t}' schema must be an object`);if(n.type!==void 0){let u=Array.isArray(n.type)?n.type:[n.type];for(let c of u)if(!ge.has(c))throw new y(`Invalid type '${c}' for property '${t}'. Valid types: ${Array.from(ge).join(", ")}`)}if(n.enum!==void 0&&!Array.isArray(n.enum))throw new y(`Property '${t}' enum must be an array`);if(n.properties&&typeof n.properties=="object")for(let[u,c]of Object.entries(n.properties))oe(`${t}.${u}`,c);n.items&&(Array.isArray(n.items)?n.items.forEach((u,c)=>{oe(`${t}[${c}]`,u);}):oe(`${t}[]`,n.items));}function re(t){return {name:t.name,description:t.description,parameters:t.parameters}}var De=21e3,xe=1e3,ve=3e4;function Ae(t,n){if(t.webSocketUrl){let f=new URL(t.webSocketUrl);return f.pathname=`/ws/assistant/thread/${n.config.thread_id}/`,f.searchParams.set("role","user"),f.searchParams.set("user_id",U()),f.searchParams.set("embed_token",n.token),f.toString()}let p=E(t).replace(/\/api$/,"").replace(/^https:/,"wss:").replace(/^http:/,"ws:"),_=U();return `${p}/ws/assistant/thread/${n.config.thread_id}/?role=user&user_id=${encodeURIComponent(_)}&embed_token=${encodeURIComponent(n.token)}`}function Me(t){let n=t?.config.branding;return n?{customName:n.custom_name,messageFontSize:n.message_font_size,welcomeMessage:n.welcome_message,chatboxPlaceholder:n.chatbox_placeholder,backgroundBubbleColor:n.background_bubble_color,headerBackgroundColor:n.header_background_color,showHeader:n.show_header,rotatingPlaceholders:n.rotating_placeholders,presetQuestions:n.preset_questions,chatbotLogo:n.chatbot_logo,assistantAvatar:n.assistant_avatar}:null}async function Ee(t,n,u,c){let p=new TextDecoder,_=Date.now(),f="",b=null,s=[],P,z,ee=false,T="answer",g="",S,F,A,x,B,W,N,q,J,O,H,L,X,V,te=false,Z="",ne=n.config.branding,o=()=>{(g||T==="tool")&&(s.push({type:T,content:g,toolName:S,toolDescription:F,success:A,status:x,subtaskId:B,planData:W,subtaskData:N,isSynthesis:q,isReplan:J,toolArgs:O,replanAttempt:H,maxReplans:L,failureReason:X,progress:V}),g="",S=void 0,F=void 0,A=void 0,x=void 0,B=void 0,W=void 0,N=void 0,q=void 0,J=void 0,O=void 0,H=void 0,L=void 0,X=void 0,V=void 0);},d=()=>{let m=s.map(C=>C);return (g||T==="tool")&&m.push({type:T,content:g,toolName:S,toolDescription:F,success:A,status:x,subtaskId:B,planData:W,subtaskData:N,isSynthesis:q,isReplan:J,toolArgs:O,replanAttempt:H,maxReplans:L,failureReason:X,progress:V}),m},i=()=>{let m=d();if(b)c.onMessageUpdate({id:b,textContent:f,reasoning:m,suggestedActions:P});else {b=`assistant-${Date.now()}`;let C={id:b,textContent:f,participant:{id:"assistant",name:ne?.custom_name||n.config.assistant_name,role:"assistant",avatarUrl:ne?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true,reasoning:m,suggestedActions:P};c.onMessageCreate(C);}};for(;;){let{done:m,value:C}=await t.read();if(m)break;let h=p.decode(C,{stream:true}),j=(Z+h).split(`
6
6
  `);h.endsWith(`
7
- `)?Z="":Z=j.pop()||"";for(let T of j){if(!T.startsWith("data: "))continue;let M=T.slice(6);if(M==="[DONE]")break;try{let e=JSON.parse(M);if(e.type==="assistant_chunk"){if(e.is_tool_planned){(g||I!=="answer")&&(o(),I="answer"),s.push({type:"tool",content:"",toolName:e.tool_name,toolDescription:e.tool_description,status:"planned",subtaskId:e.subtask_id}),i();continue}if(e.is_tool_executing){for(let a=s.length-1;a>=0;a--){let l=s[a];if(l.type==="tool"&&l.toolName===e.tool_name&&(e.subtask_id===void 0||l.subtaskId===e.subtask_id)){s[a].status="executing";break}}i();continue}if(e.is_observation){for(let a=s.length-1;a>=0;a--){let l=s[a];if(l.type==="tool"&&l.toolName===e.tool_name&&(e.subtask_id===void 0||l.subtaskId===e.subtask_id)){s[a].status="completed";break}}i();continue}if(e.suggested_actions){P=e.suggested_actions.map(a=>({id:a.action,label:a.label,value:a.action})),i();continue}if(e.is_wave_start){(g||I!=="answer")&&(o(),I="answer"),s.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}}),i();continue}if(e.is_wave_complete){s.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}}),i();continue}if(e.is_parallel_subtask_start){s.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}}),i();continue}if(e.is_parallel_subtask_complete){s.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}}),i();continue}if(e.is_multi_agent_planning){te=!0,(g||I!=="answer")&&(o(),I="answer"),s.push({type:"multi_agent_planning",content:"",isMultiAgent:!0}),i();continue}if(e.is_reasoning&&e.reasoning_delta){let a=s.findIndex(l=>l.type==="thinking"&&l.isMultiAgent);a>=0?s[a]={...s[a],content:(s[a].content||"")+e.reasoning_delta}:s.push({type:"thinking",content:e.reasoning_delta,isMultiAgent:!0}),i();continue}if(e.is_multi_agent_planning_complete){let a=s.findIndex(l=>l.type==="multi_agent_planning"&&l.isMultiAgent);a>=0?s[a]={...s[a],subagentAllocations:e.subagents||[]}:s.push({type:"multi_agent_planning",content:"",isMultiAgent:!0,subagentAllocations:e.subagents||[]}),i();continue}if(e.is_multi_agent_execution_start)continue;if(e.is_subagent_start){s.push({type:"subagent_start",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,task:e.task,status:"running"}}),i();continue}if(e.is_subagent_progress){let a=s.findIndex(l=>l.type==="subagent_start"&&l.subagentInfo?.id===e.subagent_id);a!==-1&&s[a].subagentInfo&&(s[a]={...s[a],content:e.progress||""}),i();continue}if(e.is_subagent_complete){s.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}}),i();continue}if(e.is_subagent_failed){s.push({type:"subagent_failed",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,status:"failed",error:e.error}}),i();continue}if(e.is_synthesis_start&&te){s.push({type:"synthesis",content:"",isMultiAgent:!0,isSynthesis:!0}),i();continue}if(e.plan_data){let a=e.plan_data;W={goal:a.goal||"",reasoning:a.reasoning||"",subtasks:(a.subtasks||[]).map(l=>({id:Number(l.id),description:l.description,required_tools:l.required_tools,dependencies:l.dependencies,status:"pending"})),total_subtasks:a.subtasks?.length||0,completed_subtasks:0,failed_subtasks:0,progress_percentage:0};}e.subtask_data&&(N=e.subtask_data),e.is_synthesis_start&&(q=!0),e.is_replan&&(J=!0),e.tool_args&&(O=e.tool_args),e.replan_attempt!==void 0&&(H=e.replan_attempt),e.max_replans!==void 0&&(L=e.max_replans),e.failure_reason&&(X=e.failure_reason),e.progress&&(V=e.progress);let r="answer";if(e.is_thinking?r="thinking":e.is_planning||e.is_plan_complete||e.is_replanning?r="planning":e.is_subtask_start||e.is_subtask_complete||e.is_subtask_failed?r="subtask":e.is_progress_update&&(r="progress"),r!==I&&(o(),I=r),e.tool_name&&(S=e.tool_name),e.success!==void 0&&(A=e.success),e.subtask_id!==void 0&&(B=e.subtask_id),r==="thinking"){g+=e.chunk||"";let a=g.match(/"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/);a&&(g=a[1].replace(/\\n/g,`
8
- `).replace(/\\"/g,'"').replace(/\\t/g," ").replace(/\\\\/g,"\\"));}else if(r==="answer"){let a=e.chunk?.trim()||"",l=f.trim();a&&l&&a===l||(f+=e.chunk||"");}else g+=e.chunk||"";e.previous_message_id&&c.onUserMessageIdUpdate(u,e.previous_message_id),i();}else if(e.type==="claude_text"){f+=e.chunk||"";let r=s.find(a=>a.type==="claude_text");r?r.content+=e.chunk||"":s.push({type:"claude_text",content:e.chunk||"",orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_thinking")s.push({type:"claude_thinking",content:e.content||"",orchestrator:"claude_agent_sdk"}),i();else if(e.type==="claude_file_read"){let r={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(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=r:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_file_edit"){let r={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(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=r:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_file_write"){let r={toolUseId:e.tool_use_id,operation:"write",filePath:e.file_path,status:e.status,error:e.error,durationMs:e.duration_ms},a=s.findIndex(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=r:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_bash"){let r={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(l=>l.type==="terminal"&&l.toolUseId===e.tool_use_id);a>=0?s[a].terminalData=r:s.push({type:"terminal",content:"",toolUseId:e.tool_use_id,terminalData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_search"){let r={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},a=s.findIndex(l=>l.type==="search_results"&&l.toolUseId===e.tool_use_id);a>=0?s[a].searchResultsData=r:s.push({type:"search_results",content:"",toolUseId:e.tool_use_id,searchResultsData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_web_search"||e.type==="claude_web_fetch"){let r={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(l=>l.type==="web_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].webOperationData=r:s.push({type:"web_operation",content:"",toolUseId:e.tool_use_id,webOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_subagent_start"){let r={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:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_subagent_chunk"){let r=s.findIndex(a=>a.type==="subagent"&&a.subagentData?.subagentId===e.subagent_id);r>=0&&s[r].subagentData&&s[r].subagentData.nestedChunks.push({type:e.is_tool?"tool":"answer",content:e.chunk||"",toolName:e.tool_name,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_subagent_complete"){let r=s.findIndex(a=>a.type==="subagent"&&a.subagentData?.subagentId===e.subagent_id);r>=0&&s[r].subagentData&&(s[r].subagentData.status="completed",s[r].subagentData.result=e.result,s[r].subagentData.durationMs=e.duration_ms),i();}else if(e.type==="claude_tool_use"||e.type==="claude_tool_result"){let r={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(l=>l.claudeToolData?.toolUseId===e.tool_use_id);a>=0?s[a].claudeToolData=r:s.push({type:"tool",content:e.content||"",toolUseId:e.tool_use_id,toolName:e.tool_name,toolDescription:e.tool_description,status:r.status==="pending"?"planned":"completed",claudeToolData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="clarification_needed"){o();let r={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:r.question,clarificationData:r,subtaskId:e.subtask_id}),z=r,f||(f=r.question),i();}else if(e.type==="assistant_complete"){o(),ee=!0;let r=e.message?.text_content||f,a=e.message?.id,l=e.message?.metadata?.sources,w=(Date.now()-_)/1e3;c.onComplete(b,r,a,s,P,l,z,w),f=r,a&&(b=a);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){o();let r=(Date.now()-_)/1e3;c.onComplete(b,f||"",e.message_id,s,P,void 0,z,r);}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 Oe(t){let[n,u]=useState([]),[c,p]=useState(false),[_,f]=useState(null),[b$1,s]=useState(null),[P,z]=useState(true),[ee,I]=useState(null),g=useRef(t);g.current=t;let S=useRef(b$1);S.current=b$1;let F=useRef(c);F.current=c;let A=useRef(new Map),x=useRef(new Map);useEffect(()=>{let o=false;async function d(){try{let i=await ue(g.current);o||(s(i),z(!1));}catch(i){o||(I(i instanceof Error?i.message:"Failed to initialize"),z(false));}}return d(),()=>{o=true;}},[t.publicKey,t.assistantId]);let B=useMemo(()=>Me(b$1),[b$1]),W=b(B),N=useRef(new Map),q=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");let i=await de(g.current,d,o);return N.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},[]),J=useCallback(o=>{N.current.delete(o);},[]),O=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");let{invocation_id:i,tool_name:m,parameters:C}=o;console.log(`[Miiflow] Tool invocation received: "${m}" (id: ${i})`);let h=A.current.get(m);if(!h)return false;try{let k=await Promise.race([h(C),new Promise((j,T)=>setTimeout(()=>T(new Error("Tool execution timeout (30s)")),3e4))]);return console.log(`[Miiflow] Tool "${m}" executed successfully (id: ${i})`),await G(g.current,d,{invocation_id:i,result:k}),console.log(`[Miiflow] Tool result sent for "${m}" (id: ${i})`),!0}catch(k){return console.error(`[Miiflow] Tool '${m}' execution failed:`,k),await G(g.current,d,{invocation_id:i,error:k instanceof Error?k.message:String(k)}),true}},[]);useEffect(()=>{if(!b$1)return;let o=b$1,d=null,i=null,m=null,C=0,h=false;function k(){if(h)return;let j=Ae(g.current,o);d=new WebSocket(j),d.onopen=()=>{console.log("[Miiflow] WebSocket connected"),C=0,i=setInterval(()=>{d?.readyState===WebSocket.OPEN&&d.send(JSON.stringify({type:"heartbeat"}));},De);},d.onmessage=T=>{try{let M=JSON.parse(T.data);M.type==="client_tool_invocation"&&M.invocation&&O(M.invocation).then(async e=>{if(!e){let r=g.current.onToolInvocationFallback;r&&await r(M.invocation)||G(g.current,o,{invocation_id:M.invocation.invocation_id,error:`No handler found for tool '${M.invocation.tool_name}'`}).catch(console.error);}}).catch(console.error);}catch{}},d.onclose=()=>{if(i&&(clearInterval(i),i=null),!h){let T=Math.min(xe*Math.pow(2,C),ve);C++,console.log(`[Miiflow] WebSocket closed, reconnecting in ${T}ms`),m=setTimeout(k,T);}},d.onerror=T=>{console.error("[Miiflow] WebSocket error:",T);};}return k(),()=>{h=true,i&&clearInterval(i),m&&clearTimeout(m),d&&(d.onclose=null,d.close());}},[b$1,O]);let H=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");await pe(g.current,d,o);},[]),L=useCallback(async(o,d)=>{let i=S.current,m=!!o.trim(),C=d&&d.length>0;if(!m&&!C||F.current||!i)return;let h=`msg-${Date.now()}`,k=d?.map(e=>N.current.get(e)).filter(Boolean),j={id:h,textContent:o,participant:{id:"user",name:g.current.userName||"You",role:"user"},createdAt:new Date().toISOString(),attachments:k?.length?k:void 0};d?.forEach(e=>N.current.delete(e));let T=`assistant-pending-${Date.now()}`,M={id:T,textContent:"",participant:{id:"assistant",name:i.config.branding?.custom_name||i.config.assistant_name,role:"assistant",avatarUrl:i.config.branding?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true};u(e=>[...e,j,M]),p(true),f(T),g.current.onUserMessageCreated?.({id:h,content:o});try{let e=E(g.current),r=await fetch(`${e}/assistant/message/stream/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.token}`,"x-mii-user-id":U()},body:JSON.stringify({thread_id:i.config.thread_id,text_content:o,message_id:h,metadata:{},attachment_ids:d||[]})});if(!r.ok)throw new Error(`HTTP error: ${r.status}`);let a=r.body?.getReader();if(!a)throw new Error("No response body");let l=await Ee(a,i,h,{onMessageCreate:w=>{f(w.id),u(D=>[...D.filter(R=>R.id!==T),w]);},onMessageUpdate:w=>{u(D=>D.map(v=>v.id===w.id?{...v,...w}:v));},onUserMessageIdUpdate:(w,D)=>{u(v=>v.map(R=>R.id===w?{...R,id:D}:R));},onComplete:(w,D,v,R,ae,_e,be,we)=>{w&&u(ye=>ye.map(se=>se.id===w?{...se,id:v||se.id,textContent:D,isStreaming:!1,reasoning:R,suggestedActions:ae,citations:_e,pendingClarification:be,executionTime:we}:se)),g.current.onAssistantMessageComplete?.({id:v||w||"",content:D});},onToolInvocation:async w=>{if(!await O(w)){let v=g.current.onToolInvocationFallback;if(!(v?await v(w):!1)){let ae=S.current;ae&&await G(g.current,ae,{invocation_id:w.invocation_id,error:`No handler found for tool '${w.tool_name}'`});}}}});l.assistantMsgId&&u(w=>w.map(D=>D.id===l.assistantMsgId?{...D,isStreaming:!1}:D));}catch(e){console.error("[Miiflow] Send error:",e);let r=S.current,a={id:`error-${Date.now()}`,textContent:"Sorry, I encountered an error. Please try again.",participant:{id:"assistant",name:r?.config.branding?.custom_name||r?.config.assistant_name||"Assistant",role:"assistant",avatarUrl:r?.config.branding?.assistant_avatar},createdAt:new Date().toISOString()};u(l=>[...l.filter(w=>w.id!==T),a]),I(e instanceof Error?e.message:"Send failed");}finally{p(false),f(null);}},[O]),X=useCallback(async()=>{let o=S.current;if(!o)throw new Error("Not initialized");let d=await ce(g.current,o);d.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:d.threadId},token:d.token||o.token};if(S.current=i,s(i),u([]),x.current.size>0){console.log(`[Miiflow] Re-registering ${x.current.size} tools on new thread`);try{await Q(g.current,i,Array.from(x.current.values()));}catch(m){console.warn("[Miiflow] Failed to re-register tools:",m);}}return d.threadId},[]),V=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");ie(o),A.current.set(o.name,o.handler);let i=re(o);x.current.set(o.name,i);try{await Q(g.current,d,[i]),console.log(`[Miiflow] Tool registered: "${o.name}"`);}catch(m){throw A.current.delete(o.name),x.current.delete(o.name),m}},[]),te=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");for(let h of o)ie(h);let i=new Map(A.current),m=new Map(x.current),C=[];for(let h of o){A.current.set(h.name,h.handler);let k=re(h);x.current.set(h.name,k),C.push(k);}try{await Q(g.current,d,C);let h=o.map(k=>k.name);console.log(`[Miiflow] Tools registered: ${JSON.stringify(h)} (${o.length} tools)`);}catch(h){throw A.current=i,x.current=m,h}},[]),Z=useMemo(()=>n.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,executionTime:o.executionTime})),[n]),ne=useCallback(o=>{s(o);},[]);return {messages:Z,isStreaming:c,streamingMessageId:_,sendMessage:L,uploadFile:q,removeUploadedAttachment:J,session:b$1,loading:P,error:ee,branding:B,brandingCSSVars:W,startNewThread:X,registerTool:V,registerTools:te,sendSystemEvent:H,handleToolInvocation:O,updateSession:ne}}function le(t){try{let n=t.split(".");if(n.length!==3)return null;let u=n[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 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{y as ToolValidationError,ce as createThread,E as getBackendBaseUrl,U as getOrCreateUserId,Ue as getTimeUntilExpiry,ue as initSession,Ne as isTokenExpired,Pe as isTokenExpiringSoon,le as parseTokenExpiry,Q 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
7
+ `)?Z="":Z=j.pop()||"";for(let I of j){if(!I.startsWith("data: "))continue;let M=I.slice(6);if(M==="[DONE]")break;try{let e=JSON.parse(M);if(e.type==="assistant_chunk"){if(e.is_tool_planned){(g||T!=="answer")&&(o(),T="answer"),s.push({type:"tool",content:"",toolName:e.tool_name,toolDescription:e.tool_description,status:"planned",subtaskId:e.subtask_id}),i();continue}if(e.is_tool_executing){for(let a=s.length-1;a>=0;a--){let l=s[a];if(l.type==="tool"&&l.toolName===e.tool_name&&(e.subtask_id===void 0||l.subtaskId===e.subtask_id)){s[a].status="executing";break}}i();continue}if(e.is_observation){for(let a=s.length-1;a>=0;a--){let l=s[a];if(l.type==="tool"&&l.toolName===e.tool_name&&(e.subtask_id===void 0||l.subtaskId===e.subtask_id)){s[a].status="completed";break}}i();continue}if(e.suggested_actions){P=e.suggested_actions.map(a=>({id:a.action,label:a.label,value:a.action})),i();continue}if(e.is_wave_start){(g||T!=="answer")&&(o(),T="answer"),s.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}}),i();continue}if(e.is_wave_complete){s.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}}),i();continue}if(e.is_parallel_subtask_start){s.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}}),i();continue}if(e.is_parallel_subtask_complete){s.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}}),i();continue}if(e.is_multi_agent_planning){te=!0,(g||T!=="answer")&&(o(),T="answer"),s.push({type:"multi_agent_planning",content:"",isMultiAgent:!0}),i();continue}if(e.is_reasoning&&e.reasoning_delta){let a=s.findIndex(l=>l.type==="thinking"&&l.isMultiAgent);a>=0?s[a]={...s[a],content:(s[a].content||"")+e.reasoning_delta}:s.push({type:"thinking",content:e.reasoning_delta,isMultiAgent:!0}),i();continue}if(e.is_multi_agent_planning_complete){let a=s.findIndex(l=>l.type==="multi_agent_planning"&&l.isMultiAgent);a>=0?s[a]={...s[a],subagentAllocations:e.subagents||[]}:s.push({type:"multi_agent_planning",content:"",isMultiAgent:!0,subagentAllocations:e.subagents||[]}),i();continue}if(e.is_multi_agent_execution_start)continue;if(e.is_subagent_start){s.push({type:"subagent_start",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,task:e.task,status:"running"}}),i();continue}if(e.is_subagent_progress){let a=s.findIndex(l=>l.type==="subagent_start"&&l.subagentInfo?.id===e.subagent_id);a!==-1&&s[a].subagentInfo&&(s[a]={...s[a],content:e.progress||""}),i();continue}if(e.is_subagent_complete){s.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}}),i();continue}if(e.is_subagent_failed){s.push({type:"subagent_failed",content:"",isMultiAgent:!0,subagentInfo:{id:e.subagent_id,name:e.subagent_name,status:"failed",error:e.error}}),i();continue}if(e.is_synthesis_start&&te){s.push({type:"synthesis",content:"",isMultiAgent:!0,isSynthesis:!0}),i();continue}if(e.plan_data){let a=e.plan_data;W={goal:a.goal||"",reasoning:a.reasoning||"",subtasks:(a.subtasks||[]).map(l=>({id:Number(l.id),description:l.description,required_tools:l.required_tools,dependencies:l.dependencies,status:"pending"})),total_subtasks:a.subtasks?.length||0,completed_subtasks:0,failed_subtasks:0,progress_percentage:0};}e.subtask_data&&(N=e.subtask_data),e.is_synthesis_start&&(q=!0),e.is_replan&&(J=!0),e.tool_args&&(O=e.tool_args),e.replan_attempt!==void 0&&(H=e.replan_attempt),e.max_replans!==void 0&&(L=e.max_replans),e.failure_reason&&(X=e.failure_reason),e.progress&&(V=e.progress);let r="answer";if(e.is_thinking?r="thinking":e.is_planning||e.is_plan_complete||e.is_replanning?r="planning":e.is_subtask_start||e.is_subtask_complete||e.is_subtask_failed?r="subtask":e.is_progress_update&&(r="progress"),r!==T&&(o(),T=r),e.tool_name&&(S=e.tool_name),e.success!==void 0&&(A=e.success),e.subtask_id!==void 0&&(B=e.subtask_id),r==="thinking"){g+=e.chunk||"";let a=g.match(/"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/);a&&(g=a[1].replace(/\\n/g,`
8
+ `).replace(/\\"/g,'"').replace(/\\t/g," ").replace(/\\\\/g,"\\"));}else if(r==="answer"){let a=e.chunk?.trim()||"",l=f.trim();a&&l&&a===l||(f+=e.chunk||"");}else g+=e.chunk||"";e.previous_message_id&&c.onUserMessageIdUpdate(u,e.previous_message_id),i();}else if(e.type==="claude_text"){f+=e.chunk||"";let r=s.find(a=>a.type==="claude_text");r?r.content+=e.chunk||"":s.push({type:"claude_text",content:e.chunk||"",orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_thinking")s.push({type:"claude_thinking",content:e.content||"",orchestrator:"claude_agent_sdk"}),i();else if(e.type==="claude_file_read"){let r={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(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=r:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_file_edit"){let r={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(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=r:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_file_write"){let r={toolUseId:e.tool_use_id,operation:"write",filePath:e.file_path,status:e.status,error:e.error,durationMs:e.duration_ms},a=s.findIndex(l=>l.type==="file_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].fileOperationData=r:s.push({type:"file_operation",content:"",toolUseId:e.tool_use_id,fileOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_bash"){let r={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(l=>l.type==="terminal"&&l.toolUseId===e.tool_use_id);a>=0?s[a].terminalData=r:s.push({type:"terminal",content:"",toolUseId:e.tool_use_id,terminalData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_search"){let r={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},a=s.findIndex(l=>l.type==="search_results"&&l.toolUseId===e.tool_use_id);a>=0?s[a].searchResultsData=r:s.push({type:"search_results",content:"",toolUseId:e.tool_use_id,searchResultsData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_web_search"||e.type==="claude_web_fetch"){let r={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(l=>l.type==="web_operation"&&l.toolUseId===e.tool_use_id);a>=0?s[a].webOperationData=r:s.push({type:"web_operation",content:"",toolUseId:e.tool_use_id,webOperationData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_subagent_start"){let r={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:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_subagent_chunk"){let r=s.findIndex(a=>a.type==="subagent"&&a.subagentData?.subagentId===e.subagent_id);r>=0&&s[r].subagentData&&s[r].subagentData.nestedChunks.push({type:e.is_tool?"tool":"answer",content:e.chunk||"",toolName:e.tool_name,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="claude_subagent_complete"){let r=s.findIndex(a=>a.type==="subagent"&&a.subagentData?.subagentId===e.subagent_id);r>=0&&s[r].subagentData&&(s[r].subagentData.status="completed",s[r].subagentData.result=e.result,s[r].subagentData.durationMs=e.duration_ms),i();}else if(e.type==="claude_tool_use"||e.type==="claude_tool_result"){let r={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(l=>l.claudeToolData?.toolUseId===e.tool_use_id);a>=0?s[a].claudeToolData=r:s.push({type:"tool",content:e.content||"",toolUseId:e.tool_use_id,toolName:e.tool_name,toolDescription:e.tool_description,status:r.status==="pending"?"planned":"completed",claudeToolData:r,orchestrator:"claude_agent_sdk"}),i();}else if(e.type==="clarification_needed"){o();let r={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:r.question,clarificationData:r,subtaskId:e.subtask_id}),z=r,f||(f=r.question),i();}else if(e.type==="assistant_complete"){o(),ee=!0;let r=e.message?.text_content||f,a=e.message?.id,l=e.message?.metadata?.sources,w=(Date.now()-_)/1e3;c.onComplete(b,r,a,s,P,l,z,w),f=r,a&&(b=a);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){o();let r=(Date.now()-_)/1e3;c.onComplete(b,f||"",e.message_id,s,P,void 0,z,r);}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 Oe(t){let[n,u]=useState([]),[c,p]=useState(false),[_,f]=useState(null),[b$1,s]=useState(null),[P,z]=useState(true),[ee,T]=useState(null),g=useRef(t);g.current=t;let S=useRef(b$1);S.current=b$1;let F=useRef(c);F.current=c;let A=useRef(new Map),x=useRef(new Map);useEffect(()=>{let o=false;async function d(){try{let i=await ue(g.current);o||(s(i),z(!1));}catch(i){o||(T(i instanceof Error?i.message:"Failed to initialize"),z(false));}}return d(),()=>{o=true;}},[t.publicKey,t.assistantId]);let B=useMemo(()=>Me(b$1),[b$1]),W=b(B),N=useRef(new Map),q=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");let i=await de(g.current,d,o);return N.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},[]),J=useCallback(o=>{N.current.delete(o);},[]),O=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");let{invocation_id:i,tool_name:m,parameters:C}=o;console.log(`[Miiflow] Tool invocation received: "${m}" (id: ${i})`);let h=A.current.get(m);if(!h)return false;try{let k=await Promise.race([h(C),new Promise((j,I)=>setTimeout(()=>I(new Error("Tool execution timeout (30s)")),3e4))]);return console.log(`[Miiflow] Tool "${m}" executed successfully (id: ${i})`),await G(g.current,d,{invocation_id:i,result:k}),console.log(`[Miiflow] Tool result sent for "${m}" (id: ${i})`),!0}catch(k){return console.error(`[Miiflow] Tool '${m}' execution failed:`,k),await G(g.current,d,{invocation_id:i,error:k instanceof Error?k.message:String(k)}),true}},[]);useEffect(()=>{if(!b$1)return;let o=b$1,d=null,i=null,m=null,C=0,h=false;function k(){if(h)return;let j=Ae(g.current,o);d=new WebSocket(j),d.onopen=()=>{console.log("[Miiflow] WebSocket connected"),C=0,i=setInterval(()=>{d?.readyState===WebSocket.OPEN&&d.send(JSON.stringify({type:"heartbeat"}));},De);},d.onmessage=I=>{try{let M=JSON.parse(I.data);M.type==="client_tool_invocation"&&M.invocation&&O(M.invocation).then(async e=>{if(!e){let r=g.current.onToolInvocationFallback;r&&await r(M.invocation)||G(g.current,o,{invocation_id:M.invocation.invocation_id,error:`No handler found for tool '${M.invocation.tool_name}'`}).catch(console.error);}}).catch(console.error);}catch{}},d.onclose=()=>{if(i&&(clearInterval(i),i=null),!h){let I=Math.min(xe*Math.pow(2,C),ve);C++,m=setTimeout(k,I);}},d.onerror=()=>{};}return k(),()=>{h=true,i&&clearInterval(i),m&&clearTimeout(m),d&&(d.onclose=null,d.close());}},[b$1,O]);let H=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");await pe(g.current,d,o);},[]),L=useCallback(async(o,d)=>{let i=S.current,m=!!o.trim(),C=d&&d.length>0;if(!m&&!C||F.current||!i)return;let h=`msg-${Date.now()}`,k=d?.map(e=>N.current.get(e)).filter(Boolean),j={id:h,textContent:o,participant:{id:"user",name:g.current.userName||"You",role:"user"},createdAt:new Date().toISOString(),attachments:k?.length?k:void 0};d?.forEach(e=>N.current.delete(e));let I=`assistant-pending-${Date.now()}`,M={id:I,textContent:"",participant:{id:"assistant",name:i.config.branding?.custom_name||i.config.assistant_name,role:"assistant",avatarUrl:i.config.branding?.assistant_avatar},createdAt:new Date().toISOString(),isStreaming:true};u(e=>[...e,j,M]),p(true),f(I),g.current.onUserMessageCreated?.({id:h,content:o});try{let e=E(g.current),r=await fetch(`${e}/assistant/message/stream/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.token}`,"x-mii-user-id":U()},body:JSON.stringify({thread_id:i.config.thread_id,text_content:o,message_id:h,metadata:{},attachment_ids:d||[]})});if(!r.ok)throw new Error(`HTTP error: ${r.status}`);let a=r.body?.getReader();if(!a)throw new Error("No response body");let l=await Ee(a,i,h,{onMessageCreate:w=>{f(w.id),u(D=>[...D.filter(R=>R.id!==I),w]);},onMessageUpdate:w=>{u(D=>D.map(v=>v.id===w.id?{...v,...w}:v));},onUserMessageIdUpdate:(w,D)=>{u(v=>v.map(R=>R.id===w?{...R,id:D}:R));},onComplete:(w,D,v,R,ae,_e,be,we)=>{w&&u(ye=>ye.map(se=>se.id===w?{...se,id:v||se.id,textContent:D,isStreaming:!1,reasoning:R,suggestedActions:ae,citations:_e,pendingClarification:be,executionTime:we}:se)),g.current.onAssistantMessageComplete?.({id:v||w||"",content:D});},onToolInvocation:async w=>{if(!await O(w)){let v=g.current.onToolInvocationFallback;if(!(v?await v(w):!1)){let ae=S.current;ae&&await G(g.current,ae,{invocation_id:w.invocation_id,error:`No handler found for tool '${w.tool_name}'`});}}}});l.assistantMsgId&&u(w=>w.map(D=>D.id===l.assistantMsgId?{...D,isStreaming:!1}:D));}catch(e){console.error("[Miiflow] Send error:",e);let r=S.current,a={id:`error-${Date.now()}`,textContent:"Sorry, I encountered an error. Please try again.",participant:{id:"assistant",name:r?.config.branding?.custom_name||r?.config.assistant_name||"Assistant",role:"assistant",avatarUrl:r?.config.branding?.assistant_avatar},createdAt:new Date().toISOString()};u(l=>[...l.filter(w=>w.id!==I),a]),T(e instanceof Error?e.message:"Send failed");}finally{p(false),f(null);}},[O]),X=useCallback(async()=>{let o=S.current;if(!o)throw new Error("Not initialized");let d=await ce(g.current,o);d.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:d.threadId},token:d.token||o.token};if(S.current=i,s(i),u([]),x.current.size>0){console.log(`[Miiflow] Re-registering ${x.current.size} tools on new thread`);try{await Q(g.current,i,Array.from(x.current.values()));}catch(m){console.warn("[Miiflow] Failed to re-register tools:",m);}}return d.threadId},[]),V=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");ie(o),A.current.set(o.name,o.handler);let i=re(o);x.current.set(o.name,i);try{await Q(g.current,d,[i]),console.log(`[Miiflow] Tool registered: "${o.name}"`);}catch(m){throw A.current.delete(o.name),x.current.delete(o.name),m}},[]),te=useCallback(async o=>{let d=S.current;if(!d)throw new Error("Not initialized");for(let h of o)ie(h);let i=new Map(A.current),m=new Map(x.current),C=[];for(let h of o){A.current.set(h.name,h.handler);let k=re(h);x.current.set(h.name,k),C.push(k);}try{await Q(g.current,d,C);let h=o.map(k=>k.name);console.log(`[Miiflow] Tools registered: ${JSON.stringify(h)} (${o.length} tools)`);}catch(h){throw A.current=i,x.current=m,h}},[]),Z=useMemo(()=>n.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,executionTime:o.executionTime})),[n]),ne=useCallback(o=>{s(o);},[]);return {messages:Z,isStreaming:c,streamingMessageId:_,sendMessage:L,uploadFile:q,removeUploadedAttachment:J,session:b$1,loading:P,error:ee,branding:B,brandingCSSVars:W,startNewThread:X,registerTool:V,registerTools:te,sendSystemEvent:H,handleToolInvocation:O,updateSession:ne}}function le(t){try{let n=t.split(".");if(n.length!==3)return null;let u=n[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 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{y as ToolValidationError,ce as createThread,E as getBackendBaseUrl,U as getOrCreateUserId,Ue as getTimeUntilExpiry,ue as initSession,Ne as isTokenExpired,Pe as isTokenExpiringSoon,le as parseTokenExpiry,Q 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
9
9
  //# sourceMappingURL=index.js.map