sidenetai-sdk 2.0.1 → 2.0.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/sidenetai-sdk.es.js +1 -1
- package/dist/sidenetai-sdk.umd.js +1 -1
- package/package.json +18 -18
package/dist/sidenetai-sdk.es.js
CHANGED
|
@@ -28774,7 +28774,7 @@ function HE({
|
|
|
28774
28774
|
] }, kt), At = Mp();
|
|
28775
28775
|
return /* @__PURE__ */ je("div", { ref: bt, className: "relative p-4 pb-3", children: [
|
|
28776
28776
|
/* @__PURE__ */ je("div", { className: "flex flex-row justify-between items-center gap-2 w-full", children: [
|
|
28777
|
-
/* @__PURE__ */ J("span", { className: `flex-1 truncate ${At.headerTitle}`, children: A ? "
|
|
28777
|
+
/* @__PURE__ */ J("span", { className: `flex-1 truncate ${At.headerTitle}`, children: A ? "" : ct }),
|
|
28778
28778
|
/* @__PURE__ */ je("div", { className: "flex flex-row gap-2", children: [
|
|
28779
28779
|
/* @__PURE__ */ J(
|
|
28780
28780
|
"button",
|
|
@@ -262,7 +262,7 @@ ${V}`:`HTTP Error (${U}): ${ut}`}if(w==="validation"&&!v.toLowerCase().startsWit
|
|
|
262
262
|
`;return q.jsx("div",{className:E?"w-full":`flex ${V?"justify-end":"justify-start"}`,children:q.jsxs("div",{className:tt,children:[E&&q.jsx("div",{className:"flex-1",children:q.jsx(KT,{message:U,statusCode:lt,errorType:k})}),!E&&U&&V&&q.jsx("div",{children:q.jsx("p",{className:"whitespace-pre-wrap",children:U})}),!E&&!V&&w&&w.length>0&&q.jsx("div",{className:"space-y-3 mt-3",children:w.map((Ct,St)=>{const K=Ct;return K.type==="tool-call"&&K.toolCall?q.jsx("div",{children:q.jsx(ZT,{toolCall:{toolName:K.toolCall.toolName,args:K.toolCall.args,result:K.toolCall.result,timestamp:new Date().toISOString()}})},St):(K.type==="workflow-steps"||K.type==="workflow-steps-update")&&K.workflowSteps?q.jsx("div",{children:q.jsx(JT,{data:K.workflowSteps})},St):null})}),!E&&!V&&U&&q.jsx("div",{className:"my-3",children:q.jsx(_T,{children:U})})]})})}const kT=({title:v=null,subtitle:U=null})=>{const w=v??"Hello there!",E=U??"How can I help you today?";return q.jsxs("div",{className:"flex flex-col justify-center mx-auto md:mt-20",children:[q.jsx(Ti.motion.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{delay:.5},className:"text-2xl font-semibold text-black dark:text-white",children:w}),q.jsx(Ti.motion.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{delay:.6},className:"text-2xl text-zinc-500 dark:text-zinc-400",children:E})]},"overview")};function WT({messages:v,isStreaming:U,animationKey:w}){const E=ht.useRef(null),k=ht.useRef(null);ht.useEffect(()=>{lt()},[v,U]);const lt=()=>{E.current?.scrollIntoView({behavior:"smooth",block:"end"})};return q.jsxs("div",{ref:k,className:"flex-1 overflow-y-auto scrollbar-hide",children:[v.length===0&&q.jsxs("div",{className:"flex flex-col justify-between h-full gap-10 mx-auto px-10 align-center ",children:[q.jsx("div",{className:"flex-1",children:q.jsx(kT,{},`greeting-${w}`)}),q.jsx("div",{className:"flex-shrink-0"})]}),v.length>0&&v.map(ut=>q.jsx($T,{role:ut.role,content:ut.content,streamItems:ut.streamItems,timestamp:ut.timestamp,isError:ut.isError,errorType:ut.errorType,statusCode:ut.statusCode},ut.id)),v.length>0&&U&&q.jsx("div",{className:"flex justify-start",children:q.jsx("div",{className:" text-gray-900 rounded-lg p-3 max-w-[85%]",children:q.jsxs("div",{className:"flex items-center space-x-1",children:[q.jsx("div",{className:"w-2 h-2 bg-gray-400 rounded-full animate-bounce"}),q.jsx("div",{className:"w-2 h-2 bg-gray-400 rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),q.jsx("div",{className:"w-2 h-2 bg-gray-400 rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]})})}),q.jsx("div",{ref:E})]})}function FT(v,U,w){const[E,k]=ht.useState(!1),[lt,ut]=ht.useState(""),[V,tt]=ht.useState([]),Ct=ht.useRef(new Map),St=ht.useRef(new Map),K=ht.useRef(new Map),ct=ht.useRef(null),[_t,ot]=ht.useState(null),[wt,Tt]=ht.useState(0),zt=ht.useCallback(async(me,cl)=>{k(!0),ut(""),Ct.current=new Map,St.current=new Map,K.current=new Map,ct.current=null;let oe=cl||_t;oe?console.log("🔄 Reusing existing threadId for conversation:",oe):(oe=ET(v),ot(oe),console.log("🆕 Generated new threadId for conversation:",oe));const Ge={id:e1(12),role:"user",content:me,streamItems:[],timestamp:new Date};tt(xe=>[...xe,Ge]);const vt={id:e1(12),role:"assistant",content:"",streamItems:[],timestamp:new Date};tt(xe=>[...xe,vt]);try{if(!v)throw new Error("Copilot ID is required");if(!U)throw new Error("User ID is required");const xe={message:me,threadId:oe,copilotId:v,resourceId:U};if(console.log("📤 Sending request body:",xe),!w)throw new Error('API key is required. Please provide an apiKey when initializing the SDK with initSidenet({ apiKey: "your-key" }).');const at={"Content-Type":"application/json",Authorization:`Bearer ${w}`},ue=await fetch(`http://localhost:8080/api/v1/copilot/${v}/stream`,{method:"POST",headers:at,body:JSON.stringify(xe)});if(!ue.ok){let le="";try{const W=ue.headers.get("content-type");if(W&&W.includes("application/json")){const it=await ue.json();le=it.message||it.error||it.details||""}else{const it=await ue.text();it&&(le=it)}}catch{}const C=`HTTP error! status: ${ue.status}`,L=le?`${C}
|
|
263
263
|
|
|
264
264
|
${le}`:C;throw new Error(L)}if(!ue.body)throw new Error("Response body is null");const jt=ue.body.getReader(),Ht=new TextDecoder;let qt="";try{for(;;){const{done:le,value:C}=await jt.read();if(le)break;const W=Ht.decode(C,{stream:!0}).split(`
|
|
265
|
-
`).filter(it=>it.trim());for(const it of W)try{const Et=it.startsWith("data: ")?it.slice(6):it;if(!Et.trim())continue;const st=JSON.parse(Et);switch(console.log("📥 Received chunk:",st),st.type){case"tool-call":{const mt=st.payload,I=mt?.toolCallId||st.toolCallId,et=mt?.toolName||st.toolName,Yt=mt?.args||st.args;if(I&&et){const Xe=K.current.get(I);let ve={};if(Xe)try{ve=JSON.parse(Xe),console.log("✅ Parsed accumulated args:",ve)}catch(We){console.warn("⚠️ Failed to parse accumulated args, using event args:",We),ve=Yt||{}}else ve=Yt||{};tt(We=>We.map(te=>{if(te.role==="assistant"&&te.id===vt.id){const Kt=te.streamItems,$=Kt.findIndex(ie=>ie.type==="tool-call"&&ie.toolCall?.id===I);if($!==-1){const ie=[...Kt];return ie[$]={...ie[$],toolCall:{...ie[$].toolCall,toolName:et,args:ve}},{...te,streamItems:ie}}else return{...te,streamItems:[...Kt,{type:"tool-call",toolCall:{id:I,toolName:et,args:ve}}]}}return te})),K.current.delete(I),ct.current=I}break}case"tool-result":{const mt=st.payload;let I=mt?.toolCallId||st.toolCallId;const et=mt?.result||st.result;console.log("📦 tool-result received:",{toolCallId:I,hasResult:!!et,resultKeys:et?Object.keys(et):[],payloadToolCallId:mt?.toolCallId,mostRecentToolCallId:ct.current}),!I&&ct.current&&(I=ct.current,console.log("⚠️ tool-result missing toolCallId, using most recent:",I)),I&&et?tt(Yt=>Yt.map(Xe=>{if(Xe.role==="assistant"&&Xe.id===vt.id){const ve=Xe.streamItems,We=ve.filter($=>$.type==="tool-call").map($=>{const ie=$.toolCall;return{id:ie?.id,toolName:ie?.toolName,hasResult:!!ie?.result}});console.log("🔍 Existing tool calls in streamItems:",We),console.log("🔍 Looking for toolCallId:",I);let te=!1;const Kt=ve.map($=>{if($.type==="tool-call"){const ie=$.toolCall;if(ie?.id===I&&!ie?.result)return te=!0,console.log("✅ Found matching tool call by ID, attaching result"),{...$,toolCall:{...ie,result:et}}}return $});if(!te){console.log("⚠️ Could not find tool call by ID, trying to match most recent tool call without result");for(let $=Kt.length-1;$>=0;$--){const ie=Kt[$];if(ie.type==="tool-call"){const Fe=ie.toolCall;if(!Fe?.result){Kt[$]={...ie,toolCall:{...Fe,result:et}},te=!0,console.log("✅ Matched tool call by finding most recent without result");break}}}}if(te)return{...Xe,streamItems:Kt};console.warn("⚠️ Could not find matching tool call for result:",{resultToolCallId:I,toolResult:et,streamItemsCount:ve.length})}return Xe})):console.warn("⚠️ tool-result event missing required fields:",{resultToolCallId:I,hasToolResult:!!et,mostRecentToolCallId:ct.current});break}case"text-delta":{const mt=st.textDelta||st.payload?.text;mt&&(qt+=mt,ut(qt),tt(I=>I.map(et=>et.role==="assistant"&&et.id===vt.id?{...et,content:qt}:et)));break}case"start":st.runId&&st.from==="WORKFLOW"&&console.log("🚀 Workflow started:",st.runId);break;case"step-start":if(st.runId&&st.payload&&st.from==="WORKFLOW"){const mt=st.payload,I=mt.stepCallId,et=mt.stepName,Yt=mt.args,Xe=Yt?`Arguments: ${JSON.stringify(Yt,null,2)}`:"";St.current.set(I,{step_id:I,step_name:et,step_description:Xe,step_status:"running",args:Yt,timestamp:new Date});const ve=Array.from(St.current.values()),We={type:"workflow-steps",workflow_id:et,run_id:st.runId,steps:ve};tt(te=>te.map(Kt=>{if(Kt.role==="assistant"&&Kt.id===vt.id){const $=Kt.streamItems,ie=$.findIndex(Fe=>Fe.type==="workflow-steps"||Fe.type==="workflow-steps-update");if(ie!==-1){const Fe=[...$];return Fe[ie]={...Fe[ie],workflowSteps:We},{...Kt,streamItems:Fe}}else return{...Kt,streamItems:[...$,{type:"workflow-steps",workflowSteps:We}]}}return Kt}))}break;case"step-result":if(st.runId&&st.payload&&st.from==="WORKFLOW"){const mt=st.payload,I=mt.stepCallId,et=mt.status,Yt=St.current.get(I);if(Yt){St.current.set(I,{...Yt,step_status:et==="success"?"success":"error"});const Xe=Array.from(St.current.values()),ve={type:"workflow-steps-update",workflow_id:Yt.step_name,run_id:st.runId,steps:Xe};tt(We=>We.map(te=>te.role==="assistant"&&te.id===vt.id?{...te,streamItems:te.streamItems.map(Kt=>Kt.type==="workflow-steps"||Kt.type==="workflow-steps-update"?{...Kt,workflowSteps:ve}:Kt)}:te))}}break;case"step-output":if(st.payload&&st.from==="USER"){const mt=st.payload.output;mt&&(qt+=mt,ut(qt),tt(I=>I.map(et=>et.role==="assistant"&&et.id===vt.id?{...et,content:qt}:et)))}break;case"step-finish":st.runId&&st.payload&&st.from==="AGENT"&&console.log("🏁 Step finished:",st.runId);break;case"tool-call-input-streaming-start":{const I=st.payload?.toolCallId||st.toolCallId;I&&(K.current.set(I,""),console.log("🔄 Tool call input streaming started for:",I));break}case"tool-call-delta":{const mt=st.payload,I=mt?.toolCallId||st.toolCallId,et=mt?.argsTextDelta||st.argsTextDelta,Yt=mt?.toolName||st.toolName;if(I&&et){const ve=(K.current.get(I)||"")+et;K.current.set(I,ve);try{const We=JSON.parse(ve);console.log("📝 Tool call delta accumulated, parsed args:",We),tt(te=>te.map(Kt=>{if(Kt.role==="assistant"&&Kt.id===vt.id){const $=Kt.streamItems,ie=$.findIndex(Fe=>Fe.type==="tool-call"&&Fe.toolCall?.id===I);if(ie!==-1){const Fe=[...$];return Fe[ie]={...Fe[ie],toolCall:{...Fe[ie].toolCall,args:We}},{...Kt,streamItems:Fe}}else return{...Kt,streamItems:[...$,{type:"tool-call",toolCall:{id:I,toolName:Yt||"Tool calling...",args:We}}]}}return Kt}))}catch{console.log("📝 Tool call delta accumulated (JSON incomplete, waiting for more):",ve)}}break}case"tool-call-input-streaming-end":{const I=st.payload?.toolCallId||st.toolCallId;if(I){const et=K.current.get(I);if(et)try{const Yt=JSON.parse(et);console.log("✅ Tool call input streaming ended, final args:",Yt),tt(Xe=>Xe.map(ve=>{if(ve.role==="assistant"&&ve.id===vt.id){const We=ve.streamItems,te=We.findIndex(Kt=>Kt.type==="tool-call"&&Kt.toolCall?.id===I);if(te!==-1){const Kt=[...We];return Kt[te]={...Kt[te],toolCall:{...Kt[te].toolCall,args:Yt}},{...ve,streamItems:Kt}}}return ve}))}catch(Yt){console.warn("⚠️ Failed to parse final accumulated args:",Yt)}}break}case"error":{const I=st.error?.message||st.message||"An error occurred during streaming";console.error("❌ Stream error received:",I),tt(et=>et.map(Yt=>Yt.role==="assistant"&&Yt.id===vt.id?{...Yt,content:I,isError:!0,errorType:"stream"}:Yt)),k(!1);return}case"finish":st.runId&&st.from==="WORKFLOW"&&console.log("✅ Workflow finished:",st.runId);break}}catch(Et){console.warn("⚠️ Failed to parse chunk:",{originalLine:it,jsonString:it.startsWith("data: ")?it.slice(6):it,error:Et,lineLength:it.length})}}}finally{jt.releaseLock()}tt(le=>le.map(C=>C.role==="assistant"&&C.id===vt.id?{...C,content:qt}:C))}catch(xe){console.error("❌ Error sending message:",xe);let at="An unexpected error occurred",ue,jt;if(xe instanceof Error){at=xe.message;const Ht=at.match(/HTTP error! status: (\d+)/i);Ht?(jt=parseInt(Ht[1],10),ue="http"):at.includes("required")||at.includes("Copilot ID")||at.includes("User ID")||at.includes("API key")?ue="validation":(at.includes("body is null")||at.includes("network")||at.includes("fetch")||at.includes("Failed to fetch"))&&(ue="network")}tt(Ht=>Ht.map(qt=>qt.id===vt.id?{...qt,content:at,isError:!0,errorType:ue,statusCode:jt}:qt))}finally{k(!1)}},[_t,v,U,w]),Wt=ht.useCallback(()=>{Tt(me=>me+1)},[]),he=ht.useCallback(()=>{ot(null),tt([]),ut(""),Ct.current=new Map,St.current=new Map,K.current=new Map,ct.current=null,Wt(),console.log("🔄 Started new conversation thread")},[Wt]);return{sendMessage:zt,isStreaming:E,streamedText:lt,messages:V,setMessages:tt,threadId:_t,resetThread:he,animationKey:wt,triggerAnimation:Wt}}function IT({workflows:v,agents:U,setInput:w}){const E=Am(),k=[{title:"What's the latest news",subtitle:"in France?"},{title:"What's the weather like",subtitle:"in Tokyo?"},{title:"Analyze today's sales",subtitle:"performance vs yesterday"},{title:"Which menu items",subtitle:"are selling best this week?"},{title:"Show me staff",subtitle:"scheduling for this weekend"},{title:"What are the top",subtitle:"cost drivers this month?"},{title:"Generate a report",subtitle:"on food waste trends"},{title:"Which suppliers",subtitle:"need payment this week?"},{title:"Analyze customer",subtitle:"satisfaction scores"},{title:"Show me inventory",subtitle:"items running low"},{title:"What's the profit",subtitle:"margin by category?"},{title:"Which employees",subtitle:"need performance reviews?"},{title:"Analyze peak",subtitle:"hours and staffing needs"},{title:"Show me cash flow",subtitle:"projections for next month"},{title:"Which menu items",subtitle:"should we promote?"},{title:"Analyze delivery",subtitle:"vs dine-in performance"},{title:"What are the main",subtitle:"operational bottlenecks?"},{title:"Show me seasonal",subtitle:"trends in sales data"},{title:"Which equipment",subtitle:"needs maintenance soon?"},{title:"Analyze table",subtitle:"turnover rates"},{title:"What's the impact",subtitle:"of weather on sales?"},{title:"Show me employee",subtitle:"productivity metrics"},{title:"Write me an essay",subtitle:"about the future of AI"},{title:"Summarise",subtitle:"my sales data"}],lt=(K,ct)=>K+" "+ct,ut=U||{},V=v||{},tt=Object.keys(ut).length+Object.keys(V).length,Ct=Math.max(0,10-tt),St=K=>{w(K)};return q.jsx("div",{className:"px-4 rounded-lg ",children:q.jsx("div",{className:"flex flex-wrap gap-2 overflow-y-auto justify-center",style:{maxHeight:"380px"},children:k.slice(0,Ct).map((K,ct)=>q.jsx(Ti.motion.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{delay:.2+(tt+ct)*.1},children:q.jsx(Mp,{variant:"suggestion",className:E.suggestions,onClick:()=>St(lt(K.title,K.subtitle)),children:q.jsxs(Wr,{children:[q.jsx("div",{className:"",children:q.jsx(Op,{variant:"suggestion",className:E.cardTitle,children:K.title})}),q.jsx("p",{className:E.cardSubtitle,children:K.subtitle})]})})},`placeholder-${ct}`))})})}function Wb(v){const U=new Date;return v.toDateString()===U.toDateString()}function PT(v){const U=new Date,w=new Date(U.getTime()-10080*60*1e3);return v>=w&&!Wb(v)}function t3(v){const U=new Date,w=new Date(U.getTime()-720*60*60*1e3),E=new Date(U.getTime()-10080*60*1e3);return v>=w&&v<E}function e3(v){const U={today:[],last7Days:[],last30Days:[],older:[]};return v.forEach(w=>{const E=new Date(w.lastMessageAt);Wb(E)?U.today.push(w):PT(E)?U.last7Days.push(w):t3(E)?U.last30Days.push(w):U.older.push(w)}),U}function l3({threads:v,selectedThreadId:U,onSelectThread:w,isLoading:E,error:k,onResetChat:lt}){const[ut,V]=ht.useState(!1),[tt,Ct]=ht.useState(""),St=ht.useRef(null),K=v.find(Wt=>Wt.id===U),ct=K?.title?Lb(K.title):"",_t=tt?v.filter(Wt=>Wt.title.toLowerCase().includes(tt.toLowerCase())):v,ot=e3(_t);ht.useEffect(()=>{function Wt(he){St.current&&!St.current.contains(he.target)&&V(!1)}if(ut)return document.addEventListener("mousedown",Wt),()=>document.removeEventListener("mousedown",Wt)},[ut]);const wt=Wt=>{w(Wt),V(!1),Ct("")},Tt=(Wt,he)=>he.length===0?null:q.jsxs("div",{className:"mb-3",children:[q.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:Wt}),q.jsx("div",{className:"space-y-0.5",children:he.map(me=>q.jsx("button",{onClick:()=>wt(me.id),className:ln("w-full text-left px-3 py-2 text-sm rounded-md transition-colors","hover:bg-gray-100 dark:hover:bg-gray-800",me.id===U&&"bg-gray-100 dark:bg-gray-800 font-medium"),children:q.jsx("div",{className:"font-medium text-gray-900 dark:text-gray-100 truncate",children:Lb(me.title)||"Untitled Thread"})},me.id))})]},Wt),zt=Am();return q.jsxs("div",{ref:St,className:"relative p-4 pb-3",children:[q.jsxs("div",{className:"flex flex-row justify-between items-center gap-2 w-full",children:[q.jsx("span",{className:`flex-1 truncate ${zt.headerTitle}`,children:E?"Loading threads...":ct}),q.jsxs("div",{className:"flex flex-row gap-2",children:[q.jsx("button",{"aria-label":"New chat",title:"New chat",className:zt.headerButtons,onClick:lt,children:q.jsx(MT,{size:zt.headerButtonSize})}),q.jsx("button",{onClick:()=>V(!ut),disabled:E,className:zt.headerButtons,"aria-label":"Select thread",children:q.jsx(OT,{size:zt.headerButtonSize})})]})]}),ut&&q.jsxs("div",{className:ln(" z-50 mx-4 mt-2","bg-white dark:bg-gray-800","border border-gray-300 dark:border-gray-700","rounded-lg shadow-lg","max-h-96 overflow-hidden flex flex-col"),children:[q.jsx("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700",children:q.jsx("input",{type:"text",placeholder:"Search threads...",value:tt,onChange:Wt=>Ct(Wt.target.value),className:ln("w-full px-3 py-2 text-sm","bg-gray-50 dark:bg-gray-900","border border-gray-300 dark:border-gray-600","rounded-md","text-gray-900 dark:text-gray-100","placeholder:text-gray-500 dark:placeholder:text-gray-400","focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"),autoFocus:!0})}),q.jsx("div",{className:"overflow-y-auto p-2",children:k?q.jsx("div",{className:"px-3 py-8 text-center text-sm text-red-600 dark:text-red-400",children:"Failed to load threads"}):_t.length===0?q.jsx("div",{className:"px-3 py-8 text-center text-sm text-gray-500 dark:text-gray-400",children:tt?"No threads found":"No threads available"}):q.jsxs(q.Fragment,{children:[Tt("Today",ot.today),Tt("Last 7 Days",ot.last7Days),Tt("Last 30 Days",ot.last30Days),Tt("Older",ot.older)]})})]})]})}async function a3(v,U,w,E=100,k=0){if(!v)throw new Error("Copilot ID is required");if(!U)throw new Error("User ID is required");if(!w)throw new Error("API key is required");const lt=new URL(`http://localhost:8080/api/v1/copilot/${v}/threads/list`);lt.searchParams.append("externalUserId",U),lt.searchParams.append("limit",E.toString()),lt.searchParams.append("offset",k.toString());const ut={"Content-Type":"application/json",Authorization:`Bearer ${w}`};try{const V=await fetch(lt.toString(),{method:"GET",headers:ut});if(!V.ok){let St="";try{const _t=V.headers.get("content-type");if(_t&&_t.includes("application/json")){const ot=await V.json();St=ot.message||ot.error||ot.details||""}else{const ot=await V.text();ot&&(St=ot)}}catch{}const K=`HTTP error! status: ${V.status}`,ct=St?`${K}
|
|
265
|
+
`).filter(it=>it.trim());for(const it of W)try{const Et=it.startsWith("data: ")?it.slice(6):it;if(!Et.trim())continue;const st=JSON.parse(Et);switch(console.log("📥 Received chunk:",st),st.type){case"tool-call":{const mt=st.payload,I=mt?.toolCallId||st.toolCallId,et=mt?.toolName||st.toolName,Yt=mt?.args||st.args;if(I&&et){const Xe=K.current.get(I);let ve={};if(Xe)try{ve=JSON.parse(Xe),console.log("✅ Parsed accumulated args:",ve)}catch(We){console.warn("⚠️ Failed to parse accumulated args, using event args:",We),ve=Yt||{}}else ve=Yt||{};tt(We=>We.map(te=>{if(te.role==="assistant"&&te.id===vt.id){const Kt=te.streamItems,$=Kt.findIndex(ie=>ie.type==="tool-call"&&ie.toolCall?.id===I);if($!==-1){const ie=[...Kt];return ie[$]={...ie[$],toolCall:{...ie[$].toolCall,toolName:et,args:ve}},{...te,streamItems:ie}}else return{...te,streamItems:[...Kt,{type:"tool-call",toolCall:{id:I,toolName:et,args:ve}}]}}return te})),K.current.delete(I),ct.current=I}break}case"tool-result":{const mt=st.payload;let I=mt?.toolCallId||st.toolCallId;const et=mt?.result||st.result;console.log("📦 tool-result received:",{toolCallId:I,hasResult:!!et,resultKeys:et?Object.keys(et):[],payloadToolCallId:mt?.toolCallId,mostRecentToolCallId:ct.current}),!I&&ct.current&&(I=ct.current,console.log("⚠️ tool-result missing toolCallId, using most recent:",I)),I&&et?tt(Yt=>Yt.map(Xe=>{if(Xe.role==="assistant"&&Xe.id===vt.id){const ve=Xe.streamItems,We=ve.filter($=>$.type==="tool-call").map($=>{const ie=$.toolCall;return{id:ie?.id,toolName:ie?.toolName,hasResult:!!ie?.result}});console.log("🔍 Existing tool calls in streamItems:",We),console.log("🔍 Looking for toolCallId:",I);let te=!1;const Kt=ve.map($=>{if($.type==="tool-call"){const ie=$.toolCall;if(ie?.id===I&&!ie?.result)return te=!0,console.log("✅ Found matching tool call by ID, attaching result"),{...$,toolCall:{...ie,result:et}}}return $});if(!te){console.log("⚠️ Could not find tool call by ID, trying to match most recent tool call without result");for(let $=Kt.length-1;$>=0;$--){const ie=Kt[$];if(ie.type==="tool-call"){const Fe=ie.toolCall;if(!Fe?.result){Kt[$]={...ie,toolCall:{...Fe,result:et}},te=!0,console.log("✅ Matched tool call by finding most recent without result");break}}}}if(te)return{...Xe,streamItems:Kt};console.warn("⚠️ Could not find matching tool call for result:",{resultToolCallId:I,toolResult:et,streamItemsCount:ve.length})}return Xe})):console.warn("⚠️ tool-result event missing required fields:",{resultToolCallId:I,hasToolResult:!!et,mostRecentToolCallId:ct.current});break}case"text-delta":{const mt=st.textDelta||st.payload?.text;mt&&(qt+=mt,ut(qt),tt(I=>I.map(et=>et.role==="assistant"&&et.id===vt.id?{...et,content:qt}:et)));break}case"start":st.runId&&st.from==="WORKFLOW"&&console.log("🚀 Workflow started:",st.runId);break;case"step-start":if(st.runId&&st.payload&&st.from==="WORKFLOW"){const mt=st.payload,I=mt.stepCallId,et=mt.stepName,Yt=mt.args,Xe=Yt?`Arguments: ${JSON.stringify(Yt,null,2)}`:"";St.current.set(I,{step_id:I,step_name:et,step_description:Xe,step_status:"running",args:Yt,timestamp:new Date});const ve=Array.from(St.current.values()),We={type:"workflow-steps",workflow_id:et,run_id:st.runId,steps:ve};tt(te=>te.map(Kt=>{if(Kt.role==="assistant"&&Kt.id===vt.id){const $=Kt.streamItems,ie=$.findIndex(Fe=>Fe.type==="workflow-steps"||Fe.type==="workflow-steps-update");if(ie!==-1){const Fe=[...$];return Fe[ie]={...Fe[ie],workflowSteps:We},{...Kt,streamItems:Fe}}else return{...Kt,streamItems:[...$,{type:"workflow-steps",workflowSteps:We}]}}return Kt}))}break;case"step-result":if(st.runId&&st.payload&&st.from==="WORKFLOW"){const mt=st.payload,I=mt.stepCallId,et=mt.status,Yt=St.current.get(I);if(Yt){St.current.set(I,{...Yt,step_status:et==="success"?"success":"error"});const Xe=Array.from(St.current.values()),ve={type:"workflow-steps-update",workflow_id:Yt.step_name,run_id:st.runId,steps:Xe};tt(We=>We.map(te=>te.role==="assistant"&&te.id===vt.id?{...te,streamItems:te.streamItems.map(Kt=>Kt.type==="workflow-steps"||Kt.type==="workflow-steps-update"?{...Kt,workflowSteps:ve}:Kt)}:te))}}break;case"step-output":if(st.payload&&st.from==="USER"){const mt=st.payload.output;mt&&(qt+=mt,ut(qt),tt(I=>I.map(et=>et.role==="assistant"&&et.id===vt.id?{...et,content:qt}:et)))}break;case"step-finish":st.runId&&st.payload&&st.from==="AGENT"&&console.log("🏁 Step finished:",st.runId);break;case"tool-call-input-streaming-start":{const I=st.payload?.toolCallId||st.toolCallId;I&&(K.current.set(I,""),console.log("🔄 Tool call input streaming started for:",I));break}case"tool-call-delta":{const mt=st.payload,I=mt?.toolCallId||st.toolCallId,et=mt?.argsTextDelta||st.argsTextDelta,Yt=mt?.toolName||st.toolName;if(I&&et){const ve=(K.current.get(I)||"")+et;K.current.set(I,ve);try{const We=JSON.parse(ve);console.log("📝 Tool call delta accumulated, parsed args:",We),tt(te=>te.map(Kt=>{if(Kt.role==="assistant"&&Kt.id===vt.id){const $=Kt.streamItems,ie=$.findIndex(Fe=>Fe.type==="tool-call"&&Fe.toolCall?.id===I);if(ie!==-1){const Fe=[...$];return Fe[ie]={...Fe[ie],toolCall:{...Fe[ie].toolCall,args:We}},{...Kt,streamItems:Fe}}else return{...Kt,streamItems:[...$,{type:"tool-call",toolCall:{id:I,toolName:Yt||"Tool calling...",args:We}}]}}return Kt}))}catch{console.log("📝 Tool call delta accumulated (JSON incomplete, waiting for more):",ve)}}break}case"tool-call-input-streaming-end":{const I=st.payload?.toolCallId||st.toolCallId;if(I){const et=K.current.get(I);if(et)try{const Yt=JSON.parse(et);console.log("✅ Tool call input streaming ended, final args:",Yt),tt(Xe=>Xe.map(ve=>{if(ve.role==="assistant"&&ve.id===vt.id){const We=ve.streamItems,te=We.findIndex(Kt=>Kt.type==="tool-call"&&Kt.toolCall?.id===I);if(te!==-1){const Kt=[...We];return Kt[te]={...Kt[te],toolCall:{...Kt[te].toolCall,args:Yt}},{...ve,streamItems:Kt}}}return ve}))}catch(Yt){console.warn("⚠️ Failed to parse final accumulated args:",Yt)}}break}case"error":{const I=st.error?.message||st.message||"An error occurred during streaming";console.error("❌ Stream error received:",I),tt(et=>et.map(Yt=>Yt.role==="assistant"&&Yt.id===vt.id?{...Yt,content:I,isError:!0,errorType:"stream"}:Yt)),k(!1);return}case"finish":st.runId&&st.from==="WORKFLOW"&&console.log("✅ Workflow finished:",st.runId);break}}catch(Et){console.warn("⚠️ Failed to parse chunk:",{originalLine:it,jsonString:it.startsWith("data: ")?it.slice(6):it,error:Et,lineLength:it.length})}}}finally{jt.releaseLock()}tt(le=>le.map(C=>C.role==="assistant"&&C.id===vt.id?{...C,content:qt}:C))}catch(xe){console.error("❌ Error sending message:",xe);let at="An unexpected error occurred",ue,jt;if(xe instanceof Error){at=xe.message;const Ht=at.match(/HTTP error! status: (\d+)/i);Ht?(jt=parseInt(Ht[1],10),ue="http"):at.includes("required")||at.includes("Copilot ID")||at.includes("User ID")||at.includes("API key")?ue="validation":(at.includes("body is null")||at.includes("network")||at.includes("fetch")||at.includes("Failed to fetch"))&&(ue="network")}tt(Ht=>Ht.map(qt=>qt.id===vt.id?{...qt,content:at,isError:!0,errorType:ue,statusCode:jt}:qt))}finally{k(!1)}},[_t,v,U,w]),Wt=ht.useCallback(()=>{Tt(me=>me+1)},[]),he=ht.useCallback(()=>{ot(null),tt([]),ut(""),Ct.current=new Map,St.current=new Map,K.current=new Map,ct.current=null,Wt(),console.log("🔄 Started new conversation thread")},[Wt]);return{sendMessage:zt,isStreaming:E,streamedText:lt,messages:V,setMessages:tt,threadId:_t,resetThread:he,animationKey:wt,triggerAnimation:Wt}}function IT({workflows:v,agents:U,setInput:w}){const E=Am(),k=[{title:"What's the latest news",subtitle:"in France?"},{title:"What's the weather like",subtitle:"in Tokyo?"},{title:"Analyze today's sales",subtitle:"performance vs yesterday"},{title:"Which menu items",subtitle:"are selling best this week?"},{title:"Show me staff",subtitle:"scheduling for this weekend"},{title:"What are the top",subtitle:"cost drivers this month?"},{title:"Generate a report",subtitle:"on food waste trends"},{title:"Which suppliers",subtitle:"need payment this week?"},{title:"Analyze customer",subtitle:"satisfaction scores"},{title:"Show me inventory",subtitle:"items running low"},{title:"What's the profit",subtitle:"margin by category?"},{title:"Which employees",subtitle:"need performance reviews?"},{title:"Analyze peak",subtitle:"hours and staffing needs"},{title:"Show me cash flow",subtitle:"projections for next month"},{title:"Which menu items",subtitle:"should we promote?"},{title:"Analyze delivery",subtitle:"vs dine-in performance"},{title:"What are the main",subtitle:"operational bottlenecks?"},{title:"Show me seasonal",subtitle:"trends in sales data"},{title:"Which equipment",subtitle:"needs maintenance soon?"},{title:"Analyze table",subtitle:"turnover rates"},{title:"What's the impact",subtitle:"of weather on sales?"},{title:"Show me employee",subtitle:"productivity metrics"},{title:"Write me an essay",subtitle:"about the future of AI"},{title:"Summarise",subtitle:"my sales data"}],lt=(K,ct)=>K+" "+ct,ut=U||{},V=v||{},tt=Object.keys(ut).length+Object.keys(V).length,Ct=Math.max(0,10-tt),St=K=>{w(K)};return q.jsx("div",{className:"px-4 rounded-lg ",children:q.jsx("div",{className:"flex flex-wrap gap-2 overflow-y-auto justify-center",style:{maxHeight:"380px"},children:k.slice(0,Ct).map((K,ct)=>q.jsx(Ti.motion.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{delay:.2+(tt+ct)*.1},children:q.jsx(Mp,{variant:"suggestion",className:E.suggestions,onClick:()=>St(lt(K.title,K.subtitle)),children:q.jsxs(Wr,{children:[q.jsx("div",{className:"",children:q.jsx(Op,{variant:"suggestion",className:E.cardTitle,children:K.title})}),q.jsx("p",{className:E.cardSubtitle,children:K.subtitle})]})})},`placeholder-${ct}`))})})}function Wb(v){const U=new Date;return v.toDateString()===U.toDateString()}function PT(v){const U=new Date,w=new Date(U.getTime()-10080*60*1e3);return v>=w&&!Wb(v)}function t3(v){const U=new Date,w=new Date(U.getTime()-720*60*60*1e3),E=new Date(U.getTime()-10080*60*1e3);return v>=w&&v<E}function e3(v){const U={today:[],last7Days:[],last30Days:[],older:[]};return v.forEach(w=>{const E=new Date(w.lastMessageAt);Wb(E)?U.today.push(w):PT(E)?U.last7Days.push(w):t3(E)?U.last30Days.push(w):U.older.push(w)}),U}function l3({threads:v,selectedThreadId:U,onSelectThread:w,isLoading:E,error:k,onResetChat:lt}){const[ut,V]=ht.useState(!1),[tt,Ct]=ht.useState(""),St=ht.useRef(null),K=v.find(Wt=>Wt.id===U),ct=K?.title?Lb(K.title):"",_t=tt?v.filter(Wt=>Wt.title.toLowerCase().includes(tt.toLowerCase())):v,ot=e3(_t);ht.useEffect(()=>{function Wt(he){St.current&&!St.current.contains(he.target)&&V(!1)}if(ut)return document.addEventListener("mousedown",Wt),()=>document.removeEventListener("mousedown",Wt)},[ut]);const wt=Wt=>{w(Wt),V(!1),Ct("")},Tt=(Wt,he)=>he.length===0?null:q.jsxs("div",{className:"mb-3",children:[q.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:Wt}),q.jsx("div",{className:"space-y-0.5",children:he.map(me=>q.jsx("button",{onClick:()=>wt(me.id),className:ln("w-full text-left px-3 py-2 text-sm rounded-md transition-colors","hover:bg-gray-100 dark:hover:bg-gray-800",me.id===U&&"bg-gray-100 dark:bg-gray-800 font-medium"),children:q.jsx("div",{className:"font-medium text-gray-900 dark:text-gray-100 truncate",children:Lb(me.title)||"Untitled Thread"})},me.id))})]},Wt),zt=Am();return q.jsxs("div",{ref:St,className:"relative p-4 pb-3",children:[q.jsxs("div",{className:"flex flex-row justify-between items-center gap-2 w-full",children:[q.jsx("span",{className:`flex-1 truncate ${zt.headerTitle}`,children:E?"":ct}),q.jsxs("div",{className:"flex flex-row gap-2",children:[q.jsx("button",{"aria-label":"New chat",title:"New chat",className:zt.headerButtons,onClick:lt,children:q.jsx(MT,{size:zt.headerButtonSize})}),q.jsx("button",{onClick:()=>V(!ut),disabled:E,className:zt.headerButtons,"aria-label":"Select thread",children:q.jsx(OT,{size:zt.headerButtonSize})})]})]}),ut&&q.jsxs("div",{className:ln(" z-50 mx-4 mt-2","bg-white dark:bg-gray-800","border border-gray-300 dark:border-gray-700","rounded-lg shadow-lg","max-h-96 overflow-hidden flex flex-col"),children:[q.jsx("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700",children:q.jsx("input",{type:"text",placeholder:"Search threads...",value:tt,onChange:Wt=>Ct(Wt.target.value),className:ln("w-full px-3 py-2 text-sm","bg-gray-50 dark:bg-gray-900","border border-gray-300 dark:border-gray-600","rounded-md","text-gray-900 dark:text-gray-100","placeholder:text-gray-500 dark:placeholder:text-gray-400","focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"),autoFocus:!0})}),q.jsx("div",{className:"overflow-y-auto p-2",children:k?q.jsx("div",{className:"px-3 py-8 text-center text-sm text-red-600 dark:text-red-400",children:"Failed to load threads"}):_t.length===0?q.jsx("div",{className:"px-3 py-8 text-center text-sm text-gray-500 dark:text-gray-400",children:tt?"No threads found":"No threads available"}):q.jsxs(q.Fragment,{children:[Tt("Today",ot.today),Tt("Last 7 Days",ot.last7Days),Tt("Last 30 Days",ot.last30Days),Tt("Older",ot.older)]})})]})]})}async function a3(v,U,w,E=100,k=0){if(!v)throw new Error("Copilot ID is required");if(!U)throw new Error("User ID is required");if(!w)throw new Error("API key is required");const lt=new URL(`http://localhost:8080/api/v1/copilot/${v}/threads/list`);lt.searchParams.append("externalUserId",U),lt.searchParams.append("limit",E.toString()),lt.searchParams.append("offset",k.toString());const ut={"Content-Type":"application/json",Authorization:`Bearer ${w}`};try{const V=await fetch(lt.toString(),{method:"GET",headers:ut});if(!V.ok){let St="";try{const _t=V.headers.get("content-type");if(_t&&_t.includes("application/json")){const ot=await V.json();St=ot.message||ot.error||ot.details||""}else{const ot=await V.text();ot&&(St=ot)}}catch{}const K=`HTTP error! status: ${V.status}`,ct=St?`${K}
|
|
266
266
|
|
|
267
267
|
${St}`:K;throw new Error(ct)}return(await V.json()).data?.threads||[]}catch(V){throw V instanceof Error?V:new Error("Failed to fetch threads list")}}async function n3(v,U,w,E,k=100,lt=0){if(!v)throw new Error("Copilot ID is required");if(!U)throw new Error("Thread ID is required");if(!w)throw new Error("User ID is required");if(!E)throw new Error("API key is required");const ut=new URL(`http://localhost:8080/api/v1/copilot/${v}/threads/${U}/messages`);ut.searchParams.append("externalUserId",w),ut.searchParams.append("limit",k.toString()),ut.searchParams.append("offset",lt.toString());const V={"Content-Type":"application/json",Authorization:`Bearer ${E}`};try{const tt=await fetch(ut.toString(),{method:"GET",headers:V});if(!tt.ok){let K="";try{const ot=tt.headers.get("content-type");if(ot&&ot.includes("application/json")){const wt=await tt.json();K=wt.message||wt.error||wt.details||""}else{const wt=await tt.text();wt&&(K=wt)}}catch{}const ct=`HTTP error! status: ${tt.status}`,_t=K?`${ct}
|
|
268
268
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sidenetai-sdk",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.2",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/sidenetai-sdk.umd.js",
|
|
7
7
|
"module": "dist/sidenetai-sdk.es.js",
|
|
@@ -19,23 +19,23 @@
|
|
|
19
19
|
"peerDependencies": {
|
|
20
20
|
"react": "^18 || ^19",
|
|
21
21
|
"react-dom": "^18 || ^19",
|
|
22
|
-
"@ai-sdk/react": "
|
|
23
|
-
"@assistant-ui/react": "
|
|
24
|
-
"@assistant-ui/react-data-stream": "
|
|
25
|
-
"@assistant-ui/react-markdown": "
|
|
26
|
-
"@assistant-ui/styles": "
|
|
27
|
-
"@copilotkit/react-core": "
|
|
28
|
-
"@copilotkit/react-ui": "
|
|
29
|
-
"@copilotkit/runtime": "
|
|
30
|
-
"@magicul/react-chat-stream": "
|
|
31
|
-
"@heroicons/react": "
|
|
32
|
-
"@radix-ui/react-slot": "
|
|
33
|
-
"@radix-ui/react-tooltip": "
|
|
34
|
-
"framer-motion": "
|
|
35
|
-
"lucide-react": "
|
|
36
|
-
"react-resizable-panels": "
|
|
37
|
-
"react-syntax-highlighter": "
|
|
38
|
-
"ai": "
|
|
22
|
+
"@ai-sdk/react": ">=2.0.0",
|
|
23
|
+
"@assistant-ui/react": ">=0.9.0",
|
|
24
|
+
"@assistant-ui/react-data-stream": ">=0.9.0",
|
|
25
|
+
"@assistant-ui/react-markdown": ">=0.9.0",
|
|
26
|
+
"@assistant-ui/styles": ">=0.1.0",
|
|
27
|
+
"@copilotkit/react-core": ">=1.0.0",
|
|
28
|
+
"@copilotkit/react-ui": ">=1.0.0",
|
|
29
|
+
"@copilotkit/runtime": ">=1.0.0",
|
|
30
|
+
"@magicul/react-chat-stream": ">=0.5.0",
|
|
31
|
+
"@heroicons/react": ">=2.0.0",
|
|
32
|
+
"@radix-ui/react-slot": ">=1.0.0",
|
|
33
|
+
"@radix-ui/react-tooltip": ">=1.0.0",
|
|
34
|
+
"framer-motion": ">=11.0.0",
|
|
35
|
+
"lucide-react": ">=0.480.0",
|
|
36
|
+
"react-resizable-panels": ">=3.0.0",
|
|
37
|
+
"react-syntax-highlighter": ">=15.5.0",
|
|
38
|
+
"ai": ">=5.0.0"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"dev": "vite",
|