@arcteninc/core 0.0.40 → 0.0.41

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/index.cjs CHANGED
@@ -14,8 +14,8 @@ Please:
14
14
  import { toolMetadata } from './.arcten/tool-metadata';
15
15
  3. Pass it to useAgent/ArctenAgent:
16
16
  useAgent({ tools: [...], toolMetadata: toolMetadata.functions })
17
- `);return t.map(n=>{if(typeof n!="function")return null;const s=n.name;return!s||s.trim()===""?null:e[s]?{name:s,description:e[s].description,jsonSchema:e[s].parameters}:(typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${s}". This tool will be excluded.
18
- To fix: Run "arcten-extract-types ." and ensure "${s}" is used in ArctenAgent/useAgent.`),null)}).filter(n=>n!==null)}function mh({toolName:t,description:e,args:n,onApprove:s,onDeny:i}){const r=Object.keys(n).length>0;return h.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:h.jsx("span",{className:"text-sm font-medium text-foreground",children:t})}),r&&h.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([o,a])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[o,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},o))})]}),h.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[h.jsxs(Ge,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(q.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Ge,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:i,children:h.jsx(q.X,{className:"h-3 w-3"})})]})]})})}function ph({toolName:t,args:e,isDenied:n,isSafe:s}){const[i,r]=m.useState(!1);if(t==="fetchDocContent")return null;const o=["k","maxResults","_organizationId"];t==="searchDocs"&&o.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([u])=>!o.includes(u))),l=Object.keys(a).length>0;return h.jsxs("div",{className:"my-1",children:[h.jsxs("button",{onClick:()=>l&&r(!i),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors ${n?"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-400":"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400"} ${l?"cursor-pointer hover:bg-opacity-80":""}`,children:[l&&h.jsx("span",{className:"transition-transform duration-200",children:i?h.jsx(q.ChevronDown,{className:"h-3 w-3"}):h.jsx(q.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(q.X,{className:"h-3 w-3"}):s?h.jsx(q.Zap,{className:"h-3 w-3"}):h.jsx(q.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),i&&l&&h.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:h.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,c])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof c=="string"?c:JSON.stringify(c)})]},u))})})]})}function gh({...t}){return h.jsx(Zn.Root,{"data-slot":"collapsible",...t})}function yh({...t}){return h.jsx(Zn.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function xh({...t}){return h.jsx(Zn.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const vh=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),Rs=m.memo(({className:t,...e})=>typeof window>"u"?null:h.jsx(m.Suspense,{fallback:null,children:h.jsx(vh,{className:Q("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);Rs.displayName="Response";const bh=Object.freeze(Object.defineProperty({__proto__:null,Response:Rs},Symbol.toStringTag,{value:"Module"})),wh=({children:t,as:e="p",className:n,duration:s=2,spread:i=2})=>{const r=dh.create(e),o=m.useMemo(()=>(t?.length??0)*i,[t,i]);return h.jsx(r,{animate:{backgroundPosition:"0% center"},className:Q("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${o}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:t})},Th=m.memo(wh),Zr=m.createContext(null),Sh=()=>{const t=m.useContext(Zr);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},Ch=1e3,Ah=1e3,Jr=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:i,duration:r,children:o,...a})=>{const[l,u]=Xs.useControllableState({prop:n,defaultProp:s,onChange:i}),[c,d]=Xs.useControllableState({prop:r,defaultProp:0}),[f,g]=m.useState(!1),[y,v]=m.useState(null);m.useEffect(()=>{e?y===null&&v(Date.now()):y!==null&&(d(Math.ceil((Date.now()-y)/Ah)),v(null))},[e,y,d]),m.useEffect(()=>{if(s&&!e&&l&&!f){const x=setTimeout(()=>{u(!1),g(!0)},Ch);return()=>clearTimeout(x)}},[e,l,s,u,f]);const w=x=>{u(x)};return h.jsx(Zr.Provider,{value:{isStreaming:e,isOpen:l,setIsOpen:u,duration:c},children:h.jsx(gh,{className:Q("not-prose mb-4",t),onOpenChange:w,open:l,...a,children:o})})}),Ph=(t,e)=>t||e===0?h.jsx(Th,{duration:1,children:"Thinking..."}):e===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",e," seconds"]}),Qr=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:i,duration:r}=Sh();return h.jsx(yh,{className:Q("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??h.jsxs(h.Fragment,{children:[h.jsx(q.BrainIcon,{className:"size-4"}),Ph(s,r),h.jsx(q.ChevronDownIcon,{className:Q("size-4 transition-transform",i?"rotate-180":"rotate-0")})]})})}),ta=m.memo(({className:t,children:e,...n})=>h.jsx(xh,{className:Q("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",t),...n,children:h.jsx(Rs,{className:"grid gap-2",children:e})}));Jr.displayName="Reasoning";Qr.displayName="ReasoningTrigger";ta.displayName="ReasoningContent";function Mh({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:i="Chat",logo:r=void 0,defaultWidth:o=384,minWidth:a=300,maxWidth:l=800,initiallyExpanded:u=!1,tools:c=[],safeTools:d=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:y="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:w}){const[x,S]=m.useState(null),b=m.useRef(null),[k,A]=m.useState(null),[V,R]=m.useState(null),P=m.useRef(null),[N,W]=m.useState(u),[U,wt]=m.useState(o),[At,dt]=m.useState(600),[st,pt]=m.useState(!1),[E,G]=m.useState(!1),[X,ot]=m.useState(!1),[_,ue]=m.useState({x:100,y:100}),[Xt,kt]=m.useState(!1),[de,Rt]=m.useState({x:0,y:0}),[he,rn]=m.useState(!1),fe=m.useRef(null),Yt=m.useRef(null),[Nt,me]=m.useState(""),[j,M]=m.useState(null),[L,Z]=m.useState("Thinking..."),[K,rt]=m.useState(new Set),[ea,na]=m.useState(""),[It,sa]=m.useState([]),[an,Ns]=m.useState(!1),[ln,Is]=m.useState([]),[Ls,cn]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[Gt,Re]=m.useState(!1),[Dh,Ne]=m.useState(!1),[Vh,Ie]=m.useState([]),gt=m.useMemo(()=>[...c,...d],[c,d]),Os=m.useMemo(()=>qr(gt,f),[gt,f]),Fs=m.useMemo(()=>new Set(gt.map(p=>p.name)),[gt]),un=m.useMemo(()=>Os.filter(p=>Fs.has(p.name)),[Os,Fs]),Bs=m.useMemo(()=>{const p=new Map;return gt.forEach(T=>p.set(T.name,T)),p},[gt]),$s=m.useMemo(()=>new Set(d.map(p=>p.name)),[d]),zs=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];m.useEffect(()=>{if(typeof window<"u"){const p=localStorage.getItem("arcten-sidebar-expanded");p&&W(JSON.parse(p));const T=localStorage.getItem("arcten-sidebar-width");T&&wt(parseInt(T));const I=localStorage.getItem("arcten-sidebar-height");I&&dt(parseInt(I));const C=localStorage.getItem("arcten-sidebar-detached");C&&G(JSON.parse(C));const B=localStorage.getItem("arcten-sidebar-position");if(B){const Pt=JSON.parse(B),xt=50,Mt=Math.max(xt-o,Math.min(Pt.x,window.innerWidth-xt)),tt=Math.max(0,Math.min(Pt.y,window.innerHeight-xt));ue({x:Mt,y:tt})}const O=localStorage.getItem("arcten-sidebar-minimized");O&&ot(JSON.parse(O)),rn(!0)}},[]),m.useEffect(()=>((async()=>{try{const T=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:w})});if(!T.ok)throw new Error("Failed to fetch token");const I=await T.json();S(I.clientToken),b.current=I.clientToken,R(I.expiresAt),A(null)}catch(T){A(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{P.current&&clearTimeout(P.current)}),[y,w]),m.useEffect(()=>{if(!V)return;P.current&&clearTimeout(P.current);const p=Math.floor(Date.now()/1e3),T=V-p,C=Math.max(0,T-5);return console.log(`Token expires at ${new Date(V*1e3).toISOString()}`),console.log(`Scheduling token refresh in ${C} seconds`),P.current=setTimeout(async()=>{console.log("Refreshing token...");try{const B=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:w})});if(!B.ok)throw new Error("Failed to refresh token");const O=await B.json();S(O.clientToken),b.current=O.clientToken,R(O.expiresAt),A(null),console.log("Token refreshed successfully")}catch(B){console.error("Token refresh failed:",B),A(B instanceof Error?B.message:"Failed to refresh token")}},C*1e3),()=>{P.current&&clearTimeout(P.current)}},[V,y,w]),m.useEffect(()=>{(async()=>{if(gt.length!==0)try{const T=gt.map(C=>({name:C.name,code:C.toString()})),I=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:T})});if(I.ok){const C=await I.json();sa(C.tools)}}catch(T){console.error("Failed to fetch tool descriptions:",T)}})()},[gt]),m.useEffect(()=>{Promise.resolve().then(()=>bh).then(p=>{M(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{na(window.location.pathname)};p(),window.addEventListener("popstate",p);const T=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(T)}},[]);async function Us(){if(!(!w?.id||!x)){Ne(!0);try{const T=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${x}`}})).json();Is(T.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{Ne(!1)}}}m.useEffect(()=>{w?.id&&x&&Us()},[w,x]);function ia(p){const T=Math.floor((Date.now()-p)/1e3);return T<60?"now":T<3600?`${Math.floor(T/60)}m`:T<86400?`${Math.floor(T/3600)}h`:`${Math.floor(T/86400)}d`}function oa(){const p=crypto.randomUUID();cn(p),Oe([]),Ie([]),Re(!1)}async function ra(p){if(x)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${x}`}}),Is(ln.filter(T=>T._id!==p)),p===Ls&&oa()}catch(T){console.error("Failed to delete conversation:",T)}}async function aa(p){cn(p.chatId),Re(!1),Ne(!0);try{const T=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${b.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const C=(await T.json()).messages||[];Oe(C),Ie(C)}catch(T){console.error("Failed to load conversation messages:",T);const I=p.messages||[];Oe(I),Ie(I)}finally{Ne(!1)}}const la=async(p,T={})=>{const I=T.headers?new Headers(T.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(p,{...T,headers:I})},{messages:pe,sendMessage:ca,status:yt,error:_s,stop:Le,addToolResult:ge,setMessages:Oe}=uo.useChat({id:Ls||void 0,transport:new Ye.DefaultChatTransport({api:`${v}/chat`,fetch:la,headers:()=>{const p={};return b.current&&(p.Authorization=`Bearer ${b.current}`),p},body:()=>{const p=un.map(T=>({name:T.name,description:T.description,inputSchema:T.jsonSchema}));return process.env.NODE_ENV==="development"&&console.log("[ArctenAgent] Sending tools to API:",{totalTools:p.length,toolNames:p.map(T=>T.name),allToolNames:gt.map(T=>T.name),filteredToolNames:un.map(T=>T.name)}),{tools:p,systemPrompt:g,currentRoute:ea}}}),sendAutomaticallyWhen:Ye.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{N&&Yt.current&&Yt.current.focus()},[N,pe]);function ua(){W(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function da(){W(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[N]),m.useEffect(()=>{fe.current&&fe.current.scrollIntoView({behavior:"smooth"})},[pe]),m.useEffect(()=>{function p(T){T.key==="Escape"&&(yt==="streaming"||yt==="submitted")&&(T.preventDefault(),Le())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[yt,Le]);function ha(){const p=crypto.randomUUID();cn(p),Oe([]),Ie([]),Re(!1)}function Ws(p){if(p.preventDefault(),!Nt.trim())return;(yt==="streaming"||yt==="submitted")&&Le();const T=zs[Math.floor(Math.random()*zs.length)]||"Thinking...";Z(T),ca({text:Nt}),me("")}function fa(p){const T=p.target.value;me(T)}m.useEffect(()=>{if(!st)return;function p(I){if(E){const C=I.clientX-_.x,B=I.clientY-_.y;C>=a&&C<=l&&wt(C),B>=400&&B<=1e3&&dt(B)}else{const C=window.innerWidth-I.clientX;C>=a&&C<=l&&wt(C)}}function T(){pt(!1),localStorage.setItem("arcten-sidebar-width",U.toString()),localStorage.setItem("arcten-sidebar-height",At.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",T),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",T)}},[st,U,At,E,_,a,l]);function ma(p){p.preventDefault(),pt(!0)}function pa(){G(!0),ot(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function ga(){G(!1),ot(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ks(){ot(!X),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!X))}function ya(p){E&&(kt(!0),Rt({x:p.clientX-_.x,y:p.clientY-_.y}))}return m.useEffect(()=>{if(!E)return;function p(){ue(T=>{const C=window.innerWidth-50,B=window.innerHeight-50,O=50-U,Pt=0,xt=Math.max(O,Math.min(T.x,C)),Mt=Math.max(Pt,Math.min(T.y,B));if(xt!==T.x||Mt!==T.y){const tt={x:xt,y:Mt};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(tt)),tt}return T})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[E,U]),m.useEffect(()=>{if(!Xt)return;function p(I){const C=I.clientX-de.x,B=I.clientY-de.y,O=50,Pt=window.innerWidth-O,xt=window.innerHeight-O,Mt=O-U,tt=0,vt=Math.max(Mt,Math.min(C,Pt)),Lt=Math.max(tt,Math.min(B,xt));ue({x:vt,y:Lt})}function T(){kt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(_))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",T),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",T)}},[Xt,de,_,U]),he?k?h.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:h.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",k]})}):x?h.jsx(Lc,{features:hh,children:h.jsx(Ue,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:E?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:E?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
17
+ `);const n=new Set,s=Object.values(e);return t.map(i=>{if(typeof i!="function")return null;const r=i.name;if(!r||r.trim()==="")return null;let o=e[r];return o&&!n.has(o.name)?n.add(o.name):(o=s.find(a=>!n.has(a.name)),o&&n.add(o.name)),o?{name:o.name,description:o.description,jsonSchema:o.parameters}:(typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${r}". This tool will be excluded.
18
+ To fix: Run "arcten-extract-types ." and ensure "${r}" is used in ArctenAgent/useAgent.`),null)}).filter(i=>i!==null)}function mh({toolName:t,description:e,args:n,onApprove:s,onDeny:i}){const r=Object.keys(n).length>0;return h.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:h.jsx("span",{className:"text-sm font-medium text-foreground",children:t})}),r&&h.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([o,a])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[o,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},o))})]}),h.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[h.jsxs(Ge,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(q.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Ge,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:i,children:h.jsx(q.X,{className:"h-3 w-3"})})]})]})})}function ph({toolName:t,args:e,isDenied:n,isSafe:s}){const[i,r]=m.useState(!1);if(t==="fetchDocContent")return null;const o=["k","maxResults","_organizationId"];t==="searchDocs"&&o.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([u])=>!o.includes(u))),l=Object.keys(a).length>0;return h.jsxs("div",{className:"my-1",children:[h.jsxs("button",{onClick:()=>l&&r(!i),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors ${n?"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-400":"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400"} ${l?"cursor-pointer hover:bg-opacity-80":""}`,children:[l&&h.jsx("span",{className:"transition-transform duration-200",children:i?h.jsx(q.ChevronDown,{className:"h-3 w-3"}):h.jsx(q.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(q.X,{className:"h-3 w-3"}):s?h.jsx(q.Zap,{className:"h-3 w-3"}):h.jsx(q.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),i&&l&&h.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:h.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([u,c])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[u,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof c=="string"?c:JSON.stringify(c)})]},u))})})]})}function gh({...t}){return h.jsx(Zn.Root,{"data-slot":"collapsible",...t})}function yh({...t}){return h.jsx(Zn.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function xh({...t}){return h.jsx(Zn.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const vh=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),Rs=m.memo(({className:t,...e})=>typeof window>"u"?null:h.jsx(m.Suspense,{fallback:null,children:h.jsx(vh,{className:Q("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);Rs.displayName="Response";const bh=Object.freeze(Object.defineProperty({__proto__:null,Response:Rs},Symbol.toStringTag,{value:"Module"})),wh=({children:t,as:e="p",className:n,duration:s=2,spread:i=2})=>{const r=dh.create(e),o=m.useMemo(()=>(t?.length??0)*i,[t,i]);return h.jsx(r,{animate:{backgroundPosition:"0% center"},className:Q("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${o}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:t})},Th=m.memo(wh),Zr=m.createContext(null),Sh=()=>{const t=m.useContext(Zr);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},Ch=1e3,Ah=1e3,Jr=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:i,duration:r,children:o,...a})=>{const[l,u]=Xs.useControllableState({prop:n,defaultProp:s,onChange:i}),[c,d]=Xs.useControllableState({prop:r,defaultProp:0}),[f,g]=m.useState(!1),[y,v]=m.useState(null);m.useEffect(()=>{e?y===null&&v(Date.now()):y!==null&&(d(Math.ceil((Date.now()-y)/Ah)),v(null))},[e,y,d]),m.useEffect(()=>{if(s&&!e&&l&&!f){const x=setTimeout(()=>{u(!1),g(!0)},Ch);return()=>clearTimeout(x)}},[e,l,s,u,f]);const w=x=>{u(x)};return h.jsx(Zr.Provider,{value:{isStreaming:e,isOpen:l,setIsOpen:u,duration:c},children:h.jsx(gh,{className:Q("not-prose mb-4",t),onOpenChange:w,open:l,...a,children:o})})}),Ph=(t,e)=>t||e===0?h.jsx(Th,{duration:1,children:"Thinking..."}):e===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",e," seconds"]}),Qr=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:i,duration:r}=Sh();return h.jsx(yh,{className:Q("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",t),...n,children:e??h.jsxs(h.Fragment,{children:[h.jsx(q.BrainIcon,{className:"size-4"}),Ph(s,r),h.jsx(q.ChevronDownIcon,{className:Q("size-4 transition-transform",i?"rotate-180":"rotate-0")})]})})}),ta=m.memo(({className:t,children:e,...n})=>h.jsx(xh,{className:Q("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",t),...n,children:h.jsx(Rs,{className:"grid gap-2",children:e})}));Jr.displayName="Reasoning";Qr.displayName="ReasoningTrigger";ta.displayName="ReasoningContent";function Mh({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:i="Chat",logo:r=void 0,defaultWidth:o=384,minWidth:a=300,maxWidth:l=800,initiallyExpanded:u=!1,tools:c=[],safeTools:d=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:y="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:w}){const[x,S]=m.useState(null),b=m.useRef(null),[k,A]=m.useState(null),[V,R]=m.useState(null),P=m.useRef(null),[N,W]=m.useState(u),[U,wt]=m.useState(o),[At,dt]=m.useState(600),[st,pt]=m.useState(!1),[E,G]=m.useState(!1),[X,ot]=m.useState(!1),[_,ue]=m.useState({x:100,y:100}),[Xt,kt]=m.useState(!1),[de,Rt]=m.useState({x:0,y:0}),[he,rn]=m.useState(!1),fe=m.useRef(null),Yt=m.useRef(null),[Nt,me]=m.useState(""),[j,M]=m.useState(null),[L,Z]=m.useState("Thinking..."),[K,rt]=m.useState(new Set),[ea,na]=m.useState(""),[It,sa]=m.useState([]),[an,Ns]=m.useState(!1),[ln,Is]=m.useState([]),[Ls,cn]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[Gt,Re]=m.useState(!1),[Dh,Ne]=m.useState(!1),[Vh,Ie]=m.useState([]),gt=m.useMemo(()=>[...c,...d],[c,d]),Os=m.useMemo(()=>qr(gt,f),[gt,f]),Fs=m.useMemo(()=>new Set(gt.map(p=>p.name)),[gt]),un=m.useMemo(()=>Os.filter(p=>Fs.has(p.name)),[Os,Fs]),Bs=m.useMemo(()=>{const p=new Map;return gt.forEach(T=>p.set(T.name,T)),p},[gt]),$s=m.useMemo(()=>new Set(d.map(p=>p.name)),[d]),zs=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];m.useEffect(()=>{if(typeof window<"u"){const p=localStorage.getItem("arcten-sidebar-expanded");p&&W(JSON.parse(p));const T=localStorage.getItem("arcten-sidebar-width");T&&wt(parseInt(T));const I=localStorage.getItem("arcten-sidebar-height");I&&dt(parseInt(I));const C=localStorage.getItem("arcten-sidebar-detached");C&&G(JSON.parse(C));const B=localStorage.getItem("arcten-sidebar-position");if(B){const Pt=JSON.parse(B),xt=50,Mt=Math.max(xt-o,Math.min(Pt.x,window.innerWidth-xt)),tt=Math.max(0,Math.min(Pt.y,window.innerHeight-xt));ue({x:Mt,y:tt})}const O=localStorage.getItem("arcten-sidebar-minimized");O&&ot(JSON.parse(O)),rn(!0)}},[]),m.useEffect(()=>((async()=>{try{const T=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:w})});if(!T.ok)throw new Error("Failed to fetch token");const I=await T.json();S(I.clientToken),b.current=I.clientToken,R(I.expiresAt),A(null)}catch(T){A(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{P.current&&clearTimeout(P.current)}),[y,w]),m.useEffect(()=>{if(!V)return;P.current&&clearTimeout(P.current);const p=Math.floor(Date.now()/1e3),T=V-p,C=Math.max(0,T-5);return console.log(`Token expires at ${new Date(V*1e3).toISOString()}`),console.log(`Scheduling token refresh in ${C} seconds`),P.current=setTimeout(async()=>{console.log("Refreshing token...");try{const B=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:w})});if(!B.ok)throw new Error("Failed to refresh token");const O=await B.json();S(O.clientToken),b.current=O.clientToken,R(O.expiresAt),A(null),console.log("Token refreshed successfully")}catch(B){console.error("Token refresh failed:",B),A(B instanceof Error?B.message:"Failed to refresh token")}},C*1e3),()=>{P.current&&clearTimeout(P.current)}},[V,y,w]),m.useEffect(()=>{(async()=>{if(gt.length!==0)try{const T=gt.map(C=>({name:C.name,code:C.toString()})),I=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:T})});if(I.ok){const C=await I.json();sa(C.tools)}}catch(T){console.error("Failed to fetch tool descriptions:",T)}})()},[gt]),m.useEffect(()=>{Promise.resolve().then(()=>bh).then(p=>{M(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{na(window.location.pathname)};p(),window.addEventListener("popstate",p);const T=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(T)}},[]);async function Us(){if(!(!w?.id||!x)){Ne(!0);try{const T=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${x}`}})).json();Is(T.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{Ne(!1)}}}m.useEffect(()=>{w?.id&&x&&Us()},[w,x]);function ia(p){const T=Math.floor((Date.now()-p)/1e3);return T<60?"now":T<3600?`${Math.floor(T/60)}m`:T<86400?`${Math.floor(T/3600)}h`:`${Math.floor(T/86400)}d`}function oa(){const p=crypto.randomUUID();cn(p),Oe([]),Ie([]),Re(!1)}async function ra(p){if(x)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${x}`}}),Is(ln.filter(T=>T._id!==p)),p===Ls&&oa()}catch(T){console.error("Failed to delete conversation:",T)}}async function aa(p){cn(p.chatId),Re(!1),Ne(!0);try{const T=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${b.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const C=(await T.json()).messages||[];Oe(C),Ie(C)}catch(T){console.error("Failed to load conversation messages:",T);const I=p.messages||[];Oe(I),Ie(I)}finally{Ne(!1)}}const la=async(p,T={})=>{const I=T.headers?new Headers(T.headers):new Headers;return I.delete("user-agent"),I.delete("User-Agent"),fetch(p,{...T,headers:I})},{messages:pe,sendMessage:ca,status:yt,error:_s,stop:Le,addToolResult:ge,setMessages:Oe}=uo.useChat({id:Ls||void 0,transport:new Ye.DefaultChatTransport({api:`${v}/chat`,fetch:la,headers:()=>{const p={};return b.current&&(p.Authorization=`Bearer ${b.current}`),p},body:()=>{const p=un.map(T=>({name:T.name,description:T.description,inputSchema:T.jsonSchema}));return process.env.NODE_ENV==="development"&&console.log("[ArctenAgent] Sending tools to API:",{totalTools:p.length,toolNames:p.map(T=>T.name),allToolNames:gt.map(T=>T.name),filteredToolNames:un.map(T=>T.name)}),{tools:p,systemPrompt:g,currentRoute:ea}}}),sendAutomaticallyWhen:Ye.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{N&&Yt.current&&Yt.current.focus()},[N,pe]);function ua(){W(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function da(){W(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[N]),m.useEffect(()=>{fe.current&&fe.current.scrollIntoView({behavior:"smooth"})},[pe]),m.useEffect(()=>{function p(T){T.key==="Escape"&&(yt==="streaming"||yt==="submitted")&&(T.preventDefault(),Le())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[yt,Le]);function ha(){const p=crypto.randomUUID();cn(p),Oe([]),Ie([]),Re(!1)}function Ws(p){if(p.preventDefault(),!Nt.trim())return;(yt==="streaming"||yt==="submitted")&&Le();const T=zs[Math.floor(Math.random()*zs.length)]||"Thinking...";Z(T),ca({text:Nt}),me("")}function fa(p){const T=p.target.value;me(T)}m.useEffect(()=>{if(!st)return;function p(I){if(E){const C=I.clientX-_.x,B=I.clientY-_.y;C>=a&&C<=l&&wt(C),B>=400&&B<=1e3&&dt(B)}else{const C=window.innerWidth-I.clientX;C>=a&&C<=l&&wt(C)}}function T(){pt(!1),localStorage.setItem("arcten-sidebar-width",U.toString()),localStorage.setItem("arcten-sidebar-height",At.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",T),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",T)}},[st,U,At,E,_,a,l]);function ma(p){p.preventDefault(),pt(!0)}function pa(){G(!0),ot(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function ga(){G(!1),ot(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ks(){ot(!X),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!X))}function ya(p){E&&(kt(!0),Rt({x:p.clientX-_.x,y:p.clientY-_.y}))}return m.useEffect(()=>{if(!E)return;function p(){ue(T=>{const C=window.innerWidth-50,B=window.innerHeight-50,O=50-U,Pt=0,xt=Math.max(O,Math.min(T.x,C)),Mt=Math.max(Pt,Math.min(T.y,B));if(xt!==T.x||Mt!==T.y){const tt={x:xt,y:Mt};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(tt)),tt}return T})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[E,U]),m.useEffect(()=>{if(!Xt)return;function p(I){const C=I.clientX-de.x,B=I.clientY-de.y,O=50,Pt=window.innerWidth-O,xt=window.innerHeight-O,Mt=O-U,tt=0,vt=Math.max(Mt,Math.min(C,Pt)),Lt=Math.max(tt,Math.min(B,xt));ue({x:vt,y:Lt})}function T(){kt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(_))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",T),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",T)}},[Xt,de,_,U]),he?k?h.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:h.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",k]})}):x?h.jsx(Lc,{features:hh,children:h.jsx(Ue,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:E?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:E?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
19
19
  ${E?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
20
20
  ${N?"bg-stone-50 dark:bg-stone-900":"bg-stone-100 dark:bg-stone-800 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors duration-200"}
21
21
  ${E?"border border-border":"border-l border-border"}
package/dist/index.mjs CHANGED
@@ -5028,19 +5028,24 @@ Please:
5028
5028
  useAgent({ tools: [...], toolMetadata: toolMetadata.functions })
5029
5029
  `
5030
5030
  );
5031
- return t.map((n) => {
5032
- if (typeof n != "function")
5031
+ const n = /* @__PURE__ */ new Set(), s = Object.values(e);
5032
+ return t.map((i) => {
5033
+ if (typeof i != "function")
5033
5034
  return null;
5034
- const s = n.name;
5035
- return !s || s.trim() === "" ? null : e[s] ? {
5036
- name: s,
5037
- description: e[s].description,
5038
- jsonSchema: e[s].parameters
5035
+ const r = i.name;
5036
+ if (!r || r.trim() === "")
5037
+ return null;
5038
+ let o = e[r];
5039
+ return o && !n.has(o.name) ? n.add(o.name) : (o = s.find((a) => !n.has(a.name)), o && n.add(o.name)), o ? {
5040
+ name: o.name,
5041
+ // Use original name from metadata, not minified fn.name
5042
+ description: o.description,
5043
+ jsonSchema: o.parameters
5039
5044
  } : (typeof process < "u" && (process.env.NODE_ENV === "development" || process.env.NODE_ENV !== "production") && typeof console < "u" && console.warn && console.warn(
5040
- `⚠️ [@arcteninc/core] No metadata found for tool "${s}". This tool will be excluded.
5041
- To fix: Run "arcten-extract-types ." and ensure "${s}" is used in ArctenAgent/useAgent.`
5045
+ `⚠️ [@arcteninc/core] No metadata found for tool "${r}". This tool will be excluded.
5046
+ To fix: Run "arcten-extract-types ." and ensure "${r}" is used in ArctenAgent/useAgent.`
5042
5047
  ), null);
5043
- }).filter((n) => n !== null);
5048
+ }).filter((i) => i !== null);
5044
5049
  }
5045
5050
  function jh({
5046
5051
  toolName: t,
@@ -1 +1 @@
1
- {"version":3,"file":"extract-tool-metadata.d.ts","sourceRoot":"","sources":["../../src/utils/extract-tool-metadata.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,GAAG,CAAC;CACjB;AAGD,UAAU,yBAAyB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,GAAG,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,QAAQ,EAAE,EACrB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,GAAG,IAAI,GAC/D,YAAY,EAAE,CAoDhB"}
1
+ {"version":3,"file":"extract-tool-metadata.d.ts","sourceRoot":"","sources":["../../src/utils/extract-tool-metadata.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,GAAG,CAAC;CACjB;AAGD,UAAU,yBAAyB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,GAAG,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,QAAQ,EAAE,EACrB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,GAAG,IAAI,GAC/D,YAAY,EAAE,CA0EhB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcteninc/core",
3
- "version": "0.0.40",
3
+ "version": "0.0.41",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",