@arcteninc/core 0.0.111 → 0.0.112
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 +1 -1
- package/dist/index.mjs +1 -0
- package/dist/lib/useAgent.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -21,4 +21,4 @@ Please:
|
|
|
21
21
|
${Ue?"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"}
|
|
22
22
|
${ie?"border border-border":"border-l border-border"}
|
|
23
23
|
${Ue?"":"w-[30px]"}
|
|
24
|
-
`,style:Ue?ie?{width:`${_e}px`,height:Ve?"auto":`${Bt}px`,left:`${ue.x}px`,top:`${ue.y}px`}:{width:`${_e}px`}:void 0,onClick:Ue?void 0:vl,children:Ue?c.jsxs(c.Fragment,{children:[!ie&&c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:jl,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ie&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:g=>{g.preventDefault(),jt(!0)}}),c.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:g=>{g.preventDefault(),g.stopPropagation(),zt(!0),Ct({x:g.clientX-ue.x,y:g.clientY-ue.y})},children:c.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),c.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:g=>{g.preventDefault(),jt(!0)}})]}),c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${ie?"cursor-move":""}`,onMouseDown:ie?Al:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${ie&&Ve?"cursor-pointer":""}`,onClick:ie&&Ve?g=>{g.stopPropagation(),ri()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Tl,"aria-label":"New chat",children:c.jsx(ne.Plus,{className:"h-4 w-4"})})}),c.jsx(bt,{children:"Start a new conversation"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?Pl:Cl,"aria-label":ie?"Dock sidebar":"Float sidebar",children:ie?c.jsx(ne.Dock,{className:"h-4 w-4"}):c.jsx(ne.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?ri:wl,"aria-label":ie?Ve?"Maximize":"Minimize":"Close sidebar",children:ie?Ve?c.jsx(ne.Maximize2,{className:"h-4 w-4"}):c.jsx(ne.Minimize2,{className:"h-4 w-4"}):c.jsx(ne.X,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?Ve?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ve&&c.jsxs(c.Fragment,{children:[k&&Ie.length>0&&c.jsxs("div",{className:`border-b border-border ${ht?"flex flex-col flex-1":""}`,children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[c.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),c.jsx(Ce,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ht||Q(),ft(!ht)},children:ht?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ht?"flex-1 overflow-y-auto":""}`,children:Ie.slice(0,ht?void 0:3).map(g=>c.jsxs("div",{className:"group relative",children:[c.jsxs(Pf,{type:"button",className:re(Dt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>jn(g),children:[c.jsx("span",{className:"text-xs truncate",children:g.title}),c.jsx("div",{className:"ml-2 flex items-center",children:c.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:ae(g.updatedAt)})})]}),c.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:P=>{P.stopPropagation(),kt(g._id)},"aria-label":"Delete conversation",children:c.jsx(ne.X,{className:"h-3 w-3"})})]},g._id))})]}),c.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[c.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Ne.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&c.jsx("div",{className:"mb-6",children:o}),c.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),De.length>0&&c.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:c.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Tn?De:De.slice(0,10)).map(g=>c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{bn(g.sampleUsage),Xe.current?.focus()},children:g.friendlyName})}),c.jsx(bt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium",children:g.description}),c.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[c.jsx("span",{className:"font-medium",children:"Example:"}),' "',g.sampleUsage,'"']}),g.paramCount>0&&c.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[c.jsx("span",{className:"font-medium",children:"Parameters:"})," ",g.params.join(", ")]})]})})]},g.name)),De.length>10&&!Tn&&c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsxs(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!0),children:["+",De.length-10," more"]})}),c.jsx(bt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),c.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:De.slice(10).map(g=>c.jsxs("div",{children:[c.jsxs("span",{className:"font-medium text-xs",children:[g.friendlyName,":"]}),c.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:g.description})]},g.name))}),c.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Tn&&De.length>10&&c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[Ne.map(g=>{const R=g.parts.filter(_=>_.type==="text").map(_=>_.text).join("");let B=g.parts;g.role==="assistant"&&g.parts.some(H=>H.timestamp)&&(B=[...g.parts].sort((H,q)=>{const be=H.timestamp||0,me=q.timestamp||0;return be-me}));let O=[],U=new Map,ee=[],Z,te=!0;if(g.role==="assistant"){const _=B.filter(me=>me.type==="text"&&me.text),H=[],q=[];_.forEach(me=>{const{citations:pt,citationMap:Pe,groupedCitations:$e,referencesText:gt}=Co(me.text);O.push(...pt),H.push(Pe),$e&&q.push(...$e),gt&&(Z=gt)}),H.forEach(me=>{me.forEach((pt,Pe)=>{U.has(Pe)||U.set(Pe,pt)})}),ee=Array.from(new Map(q.map(me=>[me.url,me])).values()).sort((me,pt)=>(me.numbers[0]||0)-(pt.numbers[0]||0)),te=!(Re==="streaming"&&g.id===Ne.at(-1)?.id)}return c.jsx("div",{className:`${g.role==="user"?"flex justify-end":"w-full"}`,children:c.jsx("div",{className:`${g.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:g.role==="user"?c.jsx(Af,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:R}):c.jsx("div",{className:"space-y-2",children:B.map((_,H)=>{if(_.type?.startsWith("tool-")){const q=_.type?.replace("tool-","")||"",be=W.find(Pe=>Pe.name===q),me=_.state==="input-available",pt=_.state==="output-available";if(me&&pe.has(q),me){if(pe.has(q))return null;const Pe=Ws(_.input);return c.jsx(ls,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(Ef,{toolName:q,description:be?.description||"",args:Pe,onApprove:async()=>{if(We.has(_.toolCallId))return;Me(gt=>new Set(gt).add(_.toolCallId));const $e=J.get(q);if($e)try{const gt=await $e(...Object.values(Pe));Mt({toolCallId:_.toolCallId,tool:q,output:gt})}catch(gt){Mt({toolCallId:_.toolCallId,tool:q,output:`Error: ${gt}`})}},onDeny:async()=>{We.has(_.toolCallId)||(Me($e=>new Set($e).add(_.toolCallId)),Mt({toolCallId:_.toolCallId,tool:q,output:"User denied tool execution"}))}})},`${_.toolCallId}-${H}`)}else if(pt){const Pe=_.output==="User denied tool execution",$e=Ws(_.input);return c.jsx(Df,{toolName:q,args:$e,isDenied:Pe,isSafe:pe.has(q)},`${_.toolCallId}-${H}`)}return null}if(_.type==="text"&&_.text&&Kn){const{processedText:q}=Co(_.text),Pe=!B.slice(H+1).some($e=>$e.type==="text"&&$e.text)&&te&&U.size>0;return c.jsx(Xf,{text:q,citations:O,citationMap:U,groupedCitations:Pe?ee:void 0,referencesText:Pe?Z:void 0,ResponseComponent:Kn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:D,showReferences:Pe},`${g.id}-${H}`)}return _.type==="reasoning"&&_.text?c.jsxs(dl,{className:"w-full",isStreaming:Re==="streaming"&&H===g.parts.length-1&&g.id===Ne.at(-1)?.id,children:[c.jsx(hl,{}),c.jsx(fl,{children:_.text})]},`${g.id}-${H}`):null})})})},g.id)}),c.jsx("div",{ref:rt})]})}),ts&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",ts.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx(Ku,{mode:"wait",children:(Re==="streaming"||Re==="submitted")&&c.jsxs(ls,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[c.jsx(ls,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),c.jsx("p",{className:"text-xs text-muted-foreground",children:vn})]})}),c.jsxs("form",{onSubmit:si,className:"relative",children:[c.jsx(Mo,{ref:Xe,value:_t,onChange:Sl,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),si(g))}}),Re==="streaming"||Re==="submitted"?c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:ns,children:c.jsx(ne.Square,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{children:"Escape"})," to stop"]})]}):c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"submit",className:re(Dt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!_t.trim(),children:c.jsx(ne.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{children:"Enter"})," to send"]})]})]})]})]}),c.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[c.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),c.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),c.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[c.jsx(ne.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),c.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):c.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:c.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function tm(e){return c.jsx(gl,{children:c.jsx(em,{...e})})}const nm={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function kn(e){for(const[t,n]of Object.entries(nm))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function sm(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function rm(e,t,n){return t.length>0}function im(e,t,n,s={}){const r=[];return Object.keys(s).forEach(i=>{const a=i in n,l=n[i];if(!a){const h=s[i];if(h!=null&&h!=="")return}const u=om(s[i]),d={name:i,type:am(l||kn(i)||"text"),label:yl(i),placeholder:lm(i,l),required:!0,value:u};d.type==="password"&&(d.validation=h=>h.length<8?"Password must be at least 8 characters":null),r.push(d)}),r.sort((i,a)=>{const l=i.name in n,u=a.name in n;return l===u?0:l?1:-1}),{shouldUseForm:rm(e,t),fields:r,title:cm(e),description:um(e,r.length)}}function om(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function am(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function yl(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function lm(e,t){return t?sm(t,e).placeholder:`Enter ${yl(e).toLowerCase()}...`}function cm(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function um(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function Vn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Vn(t)}catch{return e}if(Array.isArray(e))return e.map(Vn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Vn(s);return t}return e}function dm(e,t){if(!t||Object.keys(t).length===0)return e;const n={...e};return Object.keys(t).forEach(s=>{s in n&&delete n[s]}),n}function hm(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Vn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Vn(e):{}}const ms="__secureOutput",ps="[hidden for privacy]";function fm(e){if(typeof globalThis.structuredClone=="function")return globalThis.structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn("[useAgent] Failed to clone value for redaction:",t),e}}function mm(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function pm(e,t){if(t.length===0)return e;if(!e||typeof e!="object")return;let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return n}function gm(e,t,n){if(!e||typeof e!="object"||t.length===0)return!1;let s=e;for(let o=0;o<t.length-1;o++){if(!s||typeof s!="object")return!1;const i=s,a=t[o];if(a===void 0)return!1;const l=i[a];if(l==null||typeof l!="object")return!1;s=l}if(!s)return!1;const r=t[t.length-1];return!r||!(r in s)?!1:(s[r]=n,!0)}function pr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function xl(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=pr(r),r&&typeof r=="object"&&Object.assign(n,xl(r,o))}):t&&(n[t]=pr(e)),n}function ym(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:ps,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:ps,includeFieldStatus:!1,preserve:[]};const t=e.strategy??(e.fields&&e.fields.length>0?"fields":"full");return{strategy:t,fields:t==="fields"?e.fields??[]:[],placeholder:e.placeholder??ps,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function xm(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=ym(s);r&&(t[n]=r)}return t}function bl(e,t,n){const s=n.placeholder,r={tool:e,redacted:!0,strategy:n.strategy,placeholder:s};if(n.strategy==="full"){n.includeFieldStatus&&typeof t=="object"&&t!==null&&(r.fieldStatus=xl(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(u=>{u in t&&(l[u]=t[u])}),l[ms]=r,l}if(n.fields.includes("*"))return bl(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ms]:{...r,redactedFields:n.fields}};const o=fm(t),i=[],a={};return n.fields.forEach(l=>{const u=mm(l);if(u.length===0)return;const d=pm(o,u),h=pr(d);a[l]=h,gm(o,u,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ms]=r,o}function bm({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,sensitiveParams:l,sensitiveOutputs:u,autoDetectSensitive:d=!1,autoFormGeneration:h=!1,formMode:m="auto",systemPrompt:p="",agentId:w,agentName:b,initialMessages:j=[],conversationId:y,state:k,onStateChange:v,allowStateEdits:E=!0,onToolCall:N,onFinish:$,sources:L,ragConfig:D,ragFilters:z,secureInputHandler:A}={}){const M=f.useMemo(()=>D!==void 0?D:z?{enabled:!0,filters:z}:L&&L.length>0?{enabled:!0,organizationId:L[0],autoExecute:!0,filters:void 0}:{enabled:!1},[L,D,z]),I=f.useMemo(()=>{const x={};if(l)for(const[T,S]of Object.entries(l))if(x[T]={},Array.isArray(S))for(const C of S){const V=kn(C);x[T][C]=V||"text"}else for(const[C,V]of Object.entries(S))x[T][C]=V;if(a){for(const[T,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){x[T]||(x[T]={});const C=S.sensitiveParams;if(Array.isArray(C))for(const V of C){const W=kn(V);x[T][V]=W||"text"}else if(C&&typeof C=="object")for(const[V,W]of Object.entries(C))x[T][V]=W}}return x},[l,a,d]),F=f.useMemo(()=>xm(u),[u]),K=f.useCallback((x,T)=>{const S=F[x];if(!S)return T;try{return bl(x,T,S)}catch(C){return console.error(`[useAgent] Failed to redact output for ${x}:`,C),{value:ps,[ms]:{tool:x,redacted:!0,error:String(C)}}}},[F]),[Y,le]=f.useState(n||null),X=f.useRef(n||null),[oe,we]=f.useState(null),[Te,se]=f.useState(null),tt=f.useRef(null),[ut,ke]=f.useState([]),[He,Lt]=f.useState(y||(typeof window<"u"?crypto.randomUUID():null)),[ti,nt]=f.useState(!1),[st,Ue]=f.useState(new Set),[mn,_e]=f.useState(new Map),[Ft,Bt]=f.useState(new Map),[Wn,pn]=f.useState(new Map),[jt,ie]=f.useState(new Map),ce=k!==void 0,[Ve,Je]=f.useState({}),ue=f.useRef({}),gn=ce?k||{}:Ve;ce&&k?ue.current=k:ce||(ue.current=Ve);const[qn,zt]=f.useState(!1),[yn,Ct]=f.useState(null),Ut=f.useRef(!1),xn=f.useCallback(async(x,T=3)=>{if(!He||!X.current)return;const S=async()=>{const V=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,W=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:He,updates:x},format:"json"})});if(!W.ok){if(W.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const J=await W.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${W.status} ${J}`)}};for(let C=0;C<T;C++)try{await S(),Ct(null);return}catch(V){if(C===T-1){const J=V instanceof Error?V:new Error(String(V));throw Ct(J),console.error("Failed to sync state to Convex after retries:",V),J}await new Promise(J=>setTimeout(J,Math.pow(2,C)*100))}},[He,e,X]),rt=f.useMemo(()=>function(){return ue.current},[]),Xe=f.useMemo(()=>async function(T){const S={...ue.current,...T};ue.current=S,ce||Je(S),v&&v(S);try{await xn(T)}catch(C){throw C}},[xn,v,ce]);f.useEffect(()=>{ce&&k&&(ue.current=k)},[ce,k]);const _t=f.useCallback(x=>A?A.showSecureModal(x):new Promise(T=>{_e(S=>new Map(S).set(x.id,x)),Bt(S=>new Map(S).set(x.id,T))}),[A]),bn=f.useCallback((x,T)=>{if(A)return;const S=Ft.get(x);S&&(S(T),_e(C=>{const V=new Map(C);return V.delete(x),V}),Bt(C=>{const V=new Map(C);return V.delete(x),V}))},[Ft,A]),Kn=f.useCallback(x=>A?A.showSecureForm(x):new Promise(T=>{pn(S=>new Map(S).set(x.id,x)),ie(S=>new Map(S).set(x.id,T))}),[A]),As=f.useCallback((x,T)=>{if(A)return;const S=jt.get(x);S&&(S(T),pn(C=>{const V=new Map(C);return V.delete(x),V}),ie(C=>{const V=new Map(C);return V.delete(x),V}))},[jt,A]),vn=f.useCallback((x,T)=>{const S=I[x]||{},C=Object.keys(S).length>0;if(d){const V=Object.keys(T).filter(W=>kn(W)!==null);return C||V.length>0}return C},[I,d]),Gn=f.useCallback((x,T)=>{const C={...I[x]||{}};if(d){for(const W of Object.keys(T))if(!(W in C)){const J=kn(W);J&&(C[W]=J)}}const V=Object.entries(C).filter(([W])=>Object.prototype.hasOwnProperty.call(T,W));return V.length>0?Object.fromEntries(V):C},[I,d]),We=f.useMemo(()=>M?.enabled?async function(T,S=20,C){const V={...M.filters,...C};if(L&&L.length>1){const J=L.map(Q=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...X.current?{Authorization:`Bearer ${X.current}`}:{}},body:JSON.stringify({q:T,k:Math.min(S,100),organizationId:Q,...Object.keys(V).length>0?{filters:V}:{}})}).then(ae=>ae.ok?ae.json():null)),pe=await Promise.all(J),ye=[];for(const Q of pe)Q?.candidates&&ye.push(...Q.candidates);ye.sort((Q,ae)=>{const Ze=Q.scores?.rerank||Q.scores?.dense||0;return(ae.scores?.rerank||ae.scores?.dense||0)-Ze});const xe=ye.slice(0,S).map((Q,ae)=>{const Ze=Q.citation||Q.url;return{rank:ae+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:Ze,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:T,total:ye.length,results:xe,summary:`Found ${ye.length} relevant results across ${L.length} source(s) for "${T}". Top result: ${xe[0]?.title||"N/A"}`}}const W=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const J={q:T,k:Math.min(S,100)};W&&(J.organizationId=W),Object.keys(V).length>0&&(J.filters=V);const pe={"Content-Type":"application/json"};X.current&&(pe.Authorization=`Bearer ${X.current}`);const ye=await fetch(`${e}/search`,{method:"POST",headers:pe,body:JSON.stringify(J)});if(!ye.ok){const ae=await ye.text();return{success:!1,error:`Search failed: ${ye.status} ${ae}`}}const xe=await ye.json(),Q=xe.candidates.map((ae,Ze)=>{const kt=ae.citation||ae.url;return{rank:Ze+1,doc_id:ae.doc_id,block_id:ae.block_id,url:ae.url,citation:kt,title:ae.title||"Untitled",snippet:ae.snippet,score:ae.scores?.rerank||ae.scores?.dense||0,metadata:{site:ae.metadata?.site,lang:ae.metadata?.lang,contentType:ae.metadata?.content_type}}});return{success:!0,query:xe.query,total:xe.total,results:Q,summary:`Found ${xe.total} relevant results for "${T}". Top result: ${Q[0]?.title||"N/A"}`}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error occurred"}}}:null,[M,e,X]),Me=f.useMemo(()=>M?.enabled?async function(T,S){const C=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const V={"Content-Type":"application/json"};X.current&&(V.Authorization=`Bearer ${X.current}`);const W=await fetch(`${e}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:T,block_ids:S,...C?{organizationId:C}:{}})});if(!W.ok){const pe=await W.text();return{success:!1,error:`Fetch failed: ${W.status} ${pe}`}}const J=await W.json();return{success:!0,blocks:J.blocks||[],fullContent:J.fullContent||"",pageUrl:J.pageUrl||"",pageTitle:J.pageTitle||"",summary:`Fetched ${J.blocks?.length||0} blocks from ${J.pageTitle||T}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[M,e,X]),Xt=f.useMemo(()=>{const x=[...o,...i,rt];return(!ce||E)&&x.push(Xe),M?.enabled&&(We&&x.push(We),Me&&x.push(Me)),x},[o,i,rt,Xe,We,Me,M,ce,E]),it=f.useMemo(()=>Qr(Xt,a),[Xt,a]),De=f.useMemo(()=>{const x=new Map,T=new Map(it.map(S=>[S.name,S]));return x.set("getState",rt),(!ce||E)&&x.set("setState",Xe),M?.enabled&&(We&&x.set("searchDocs",We),Me&&x.set("fetchDocContent",Me)),Xt.forEach(S=>{if(S===rt||S===Xe||S===We||S===Me)return;const C=S[Qe];if(C){const W=T.get(C);if(W){x.set(W.name,S);return}}const V=it.find(W=>W.name===S.name);V&&x.set(V.name,S)}),x},[Xt,it,rt,Xe,We,Me,M,ce,E]),Yn=f.useMemo(()=>new Set(it.map(x=>x.name)),[it]),Hn=f.useMemo(()=>{const x=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!ce||E)&&x.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const T=[];return M?.enabled&&T.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...it,...x,...T]},[it,M,ce,E]),dt=f.useMemo(()=>Hn.filter(x=>x.name==="getState"?!0:x.name==="setState"?!ce||E:M?.enabled&&(x.name==="searchDocs"||x.name==="fetchDocContent")?!0:Yn.has(x.name)),[Hn,Yn,ce,E,M]),wn=f.useMemo(()=>{const x=new Set;return x.add("getState"),x.add("setState"),M?.enabled&&M.autoExecute!==!1&&(x.add("searchDocs"),x.add("fetchDocContent")),i.forEach(T=>{for(const[S,C]of De.entries())if(C===T){x.add(S);break}}),x},[i,De,M]);f.useEffect(()=>s||n?void 0:((async()=>{try{const T=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!T.ok)throw new Error("Failed to fetch token");const S=await T.json();le(S.clientToken),X.current=S.clientToken,se(S.expiresAt),we(null)}catch(T){console.error("[useAgent] Token fetch failed:",T),we(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{tt.current&&clearTimeout(tt.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!Te||s||n)return;tt.current&&clearTimeout(tt.current);const x=Math.floor(Date.now()/1e3),T=Te-x,C=Math.max(0,T-5);return tt.current=setTimeout(async()=>{try{const V=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!V.ok)throw new Error("Failed to refresh token");const W=await V.json();le(W.clientToken),X.current=W.clientToken,se(W.expiresAt),we(null)}catch(V){console.error("[useAgent] Token refresh failed:",V),we(V instanceof Error?V.message:"Failed to refresh token")}},C*1e3),()=>{tt.current&&clearTimeout(tt.current)}},[Te,t,JSON.stringify(r),s,n]);const Tn=async(x,T={})=>{const S=T.headers?new Headers(T.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",x),console.log("[useAgent] Method:",T.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!X.current);try{const C=await fetch(x,{...T,headers:S});if(!C.ok){console.error("[useAgent] Request failed:",C.status,C.statusText);const V=await C.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",V)}return C}catch(C){throw console.error("[useAgent] Fetch error:",C),C}},Sn=`${e}/chat`;console.log("[useAgent] Chat API URL:",Sn);const{messages:Ie,sendMessage:Jn,status:Oe,error:Pt,stop:ht,addToolResult:ft,setMessages:Zn}=Po.useChat({id:He||void 0,messages:j,transport:new gs.DefaultChatTransport({api:Sn,fetch:Tn,headers:()=>{const x={};return X.current?(x.Authorization=`Bearer ${X.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),x},body:()=>{const x=dt.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),T=x.filter(C=>C.name==="getState"||C.name==="setState").map(C=>C.name),S=x.filter(C=>C.name==="searchDocs"||C.name==="fetchDocContent").map(C=>C.name);return T.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",T),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):M?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:x,...w&&{agentId:w},...b&&{agentName:b},state:ue.current,...z&&{ragFilters:z}}}}),sendAutomaticallyWhen:gs.lastAssistantMessageIsCompleteWithToolCalls}),qe=f.useCallback((x,T,S)=>{const C=K(x,S);ft({toolCallId:T,tool:x,output:C})},[ft,K]);f.useEffect(()=>{Ie.forEach(x=>{x.role==="assistant"&&x.parts.forEach(T=>{if(!T.type?.startsWith("tool-")||T.state!=="input-available")return;const S=T.type.replace("tool-",""),C=T.toolCallId;if(st.has(C))return;Ue(W=>new Set(W).add(C));const V=hm(T.input);if(vn(S,V)){const W=Gn(S,V),J=Object.entries(W).filter(([Q])=>V[Q]!==void 0),pe=J.length>0?Object.fromEntries(J):W,ye=Object.keys(V),xe=dm(V,pe);(async()=>{try{const Q=im(S,ye,pe,V),ae={id:`${C}-form`,toolName:S,toolCallId:C,title:Q.title,description:Q.description,fields:Q.fields},Ze=await Kn(ae);if(Ze===null){qe(S,C,"User cancelled secure input");return}const kt={...xe,...Ze},jn=De.get(S);if(!jn)throw new Error(`Tool ${S} not found`);let Cn;const Ne=dt.find(es=>es.name===S);if(Ne&&Ne.jsonSchema?.properties){const Re=Object.keys(Ne.jsonSchema.properties).map(ts=>kt[ts]);Cn=await jn(...Re)}else Cn=await jn(...Object.values(kt));qe(S,C,Cn)}catch(Q){console.error(`[useAgent] Error executing tool with secure input ${S}:`,Q),qe(S,C,`Error: ${Q}`)}})();return}if(wn.has(S)&&!vn(S,V)){const W=De.get(S);W?(async()=>{try{const J=dt.find(ye=>ye.name===S);let pe;if(J&&J.jsonSchema?.properties){const xe=Object.keys(J.jsonSchema.properties).map(Q=>V[Q]);pe=await W(...xe)}else if(S==="getState")pe=W();else if(S==="setState"){const ye=V.updates||V;pe=await W(ye)}else pe=await W(...Object.values(V));qe(S,C,pe)}catch(J){console.error(`[useAgent] Error executing tool ${S}:`,J),qe(S,C,`Error: ${J}`)}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else N&&N({toolCall:{toolCallId:C,toolName:S,args:V}})})})},[Ie,wn,De,N,qe,st,Xe,dt,vn,Gn,_t]),f.useEffect(()=>{if(Oe==="ready"&&Ie.length>0&&$){const x=Ie[Ie.length-1];x&&x.role==="assistant"&&$({message:x,messages:Ie,isAbort:!1,isDisconnect:!1,isError:!!Pt})}},[Oe,Ie,Pt,$]);async function ni(){if(!(!r?.id||!Y)){nt(!0);try{const T=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${Y}`}})).json();ke(T.conversations||[])}catch(x){console.error("Failed to fetch conversations:",x)}finally{nt(!1)}}}f.useEffect(()=>{r?.id&&Y&&ni()},[JSON.stringify(r),Y,e]),f.useEffect(()=>{if(!He||!X.current)return;(async()=>{zt(!0),Ct(null);try{const T=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:He},format:"json"})});if(!T.ok){const V=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${V}`)}const C=(await T.json())?.value||{};ue.current=C,ce||Je(C),v&&v(C),Ut.current=!0}catch(T){console.error("Failed to fetch state:",T);const S=T instanceof Error?T:new Error(String(T));Ct(S),Ut.current||(ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!0)}finally{zt(!1)}})()},[He,e,ce,v]);async function Wt(x){Lt(x),nt(!0);try{const T=await fetch(`${e}/conversations/${x}/messages`,{headers:{Authorization:`Bearer ${X.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const C=(await T.json()).messages||[];Zn(C)}catch(T){console.error("Failed to load conversation messages:",T)}finally{nt(!1)}}async function Qn(x){if(Y)try{await fetch(`${e}/conversations/${x}`,{method:"DELETE",headers:{Authorization:`Bearer ${Y}`}}),ke(ut.filter(T=>T._id!==x)),x===He&&mt()}catch(T){console.error("Failed to delete conversation:",T)}}function mt(){const x=crypto.randomUUID();Lt(x),Zn([]),Ue(new Set),ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!1}function At(x){const T=x.tool||"unknown-tool",S=K(T,x.output);ft({toolCallId:x.toolCallId,tool:T,output:S})}async function ot(x){const T={...ue.current,...x};ue.current=T,ce||Je(T),v&&v(T);try{await xn(x)}catch(S){throw S}}return{id:He,messages:Ie,status:Oe,error:Pt,sendMessage:Jn,stop:ht,addToolOutput:At,setMessages:Zn,conversations:ut,loadConversation:Wt,deleteConversation:Qn,startNewConversation:mt,isLoadingConversations:ti,clientToken:Y,tokenError:oe,state:gn,setState:ot,isStateLoading:qn,stateError:yn,pendingSecureInputs:Array.from(mn.values()),completeSecureInput:bn,pendingSecureForms:Array.from(Wn.values()),completeSecureForm:As}}exports.verifyToken=zl.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Qe;exports.ArctenAgent=tm;exports.SecureModalProvider=gl;exports.extractToolsMetadata=Qr;exports.preserveToolName=kf;exports.useAgent=bm;exports.useSecureModal=pl;
|
|
24
|
+
`,style:Ue?ie?{width:`${_e}px`,height:Ve?"auto":`${Bt}px`,left:`${ue.x}px`,top:`${ue.y}px`}:{width:`${_e}px`}:void 0,onClick:Ue?void 0:vl,children:Ue?c.jsxs(c.Fragment,{children:[!ie&&c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:jl,children:c.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),ie&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:g=>{g.preventDefault(),jt(!0)}}),c.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:g=>{g.preventDefault(),g.stopPropagation(),zt(!0),Ct({x:g.clientX-ue.x,y:g.clientY-ue.y})},children:c.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),c.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:g=>{g.preventDefault(),jt(!0)}})]}),c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${ie?"cursor-move":""}`,onMouseDown:ie?Al:void 0,children:[c.jsx("h2",{className:`text-base font-semibold ${ie&&Ve?"cursor-pointer":""}`,onClick:ie&&Ve?g=>{g.stopPropagation(),ri()}:void 0,children:r}),c.jsxs("div",{className:"flex items-center gap-1",onClick:g=>g.stopPropagation(),children:[c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Tl,"aria-label":"New chat",children:c.jsx(ne.Plus,{className:"h-4 w-4"})})}),c.jsx(bt,{children:"Start a new conversation"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?Pl:Cl,"aria-label":ie?"Dock sidebar":"Float sidebar",children:ie?c.jsx(ne.Dock,{className:"h-4 w-4"}):c.jsx(ne.PictureInPicture2,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?"Dock to sidebar":"Undock to floating window"})]}),c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ie?ri:wl,"aria-label":ie?Ve?"Maximize":"Minimize":"Close sidebar",children:ie?Ve?c.jsx(ne.Maximize2,{className:"h-4 w-4"}):c.jsx(ne.Minimize2,{className:"h-4 w-4"}):c.jsx(ne.X,{className:"h-4 w-4"})})}),c.jsx(bt,{children:ie?Ve?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ve&&c.jsxs(c.Fragment,{children:[k&&Ie.length>0&&c.jsxs("div",{className:`border-b border-border ${ht?"flex flex-col flex-1":""}`,children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[c.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),c.jsx(Ce,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{ht||Q(),ft(!ht)},children:ht?"Show less":"View all"})]}),c.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ht?"flex-1 overflow-y-auto":""}`,children:Ie.slice(0,ht?void 0:3).map(g=>c.jsxs("div",{className:"group relative",children:[c.jsxs(Pf,{type:"button",className:re(Dt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>jn(g),children:[c.jsx("span",{className:"text-xs truncate",children:g.title}),c.jsx("div",{className:"ml-2 flex items-center",children:c.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:ae(g.updatedAt)})})]}),c.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:P=>{P.stopPropagation(),kt(g._id)},"aria-label":"Delete conversation",children:c.jsx(ne.X,{className:"h-3 w-3"})})]},g._id))})]}),c.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[c.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Ne.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&c.jsx("div",{className:"mb-6",children:o}),c.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),De.length>0&&c.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:c.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Tn?De:De.slice(0,10)).map(g=>c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{bn(g.sampleUsage),Xe.current?.focus()},children:g.friendlyName})}),c.jsx(bt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium",children:g.description}),c.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[c.jsx("span",{className:"font-medium",children:"Example:"}),' "',g.sampleUsage,'"']}),g.paramCount>0&&c.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[c.jsx("span",{className:"font-medium",children:"Parameters:"})," ",g.params.join(", ")]})]})})]},g.name)),De.length>10&&!Tn&&c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsxs(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!0),children:["+",De.length-10," more"]})}),c.jsx(bt,{children:c.jsxs("div",{className:"max-w-xs",children:[c.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),c.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:De.slice(10).map(g=>c.jsxs("div",{children:[c.jsxs("span",{className:"font-medium text-xs",children:[g.friendlyName,":"]}),c.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:g.description})]},g.name))}),c.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Tn&&De.length>10&&c.jsx(ks,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>Sn(!1),children:"Show less"})]})})]}):c.jsxs(c.Fragment,{children:[Ne.map(g=>{const R=g.parts.filter(_=>_.type==="text").map(_=>_.text).join("");let B=g.parts;g.role==="assistant"&&g.parts.some(H=>H.timestamp)&&(B=[...g.parts].sort((H,q)=>{const be=H.timestamp||0,me=q.timestamp||0;return be-me}));let O=[],U=new Map,ee=[],Z,te=!0;if(g.role==="assistant"){const _=B.filter(me=>me.type==="text"&&me.text),H=[],q=[];_.forEach(me=>{const{citations:pt,citationMap:Pe,groupedCitations:$e,referencesText:gt}=Co(me.text);O.push(...pt),H.push(Pe),$e&&q.push(...$e),gt&&(Z=gt)}),H.forEach(me=>{me.forEach((pt,Pe)=>{U.has(Pe)||U.set(Pe,pt)})}),ee=Array.from(new Map(q.map(me=>[me.url,me])).values()).sort((me,pt)=>(me.numbers[0]||0)-(pt.numbers[0]||0)),te=!(Re==="streaming"&&g.id===Ne.at(-1)?.id)}return c.jsx("div",{className:`${g.role==="user"?"flex justify-end":"w-full"}`,children:c.jsx("div",{className:`${g.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:g.role==="user"?c.jsx(Af,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:R}):c.jsx("div",{className:"space-y-2",children:B.map((_,H)=>{if(_.type?.startsWith("tool-")){const q=_.type?.replace("tool-","")||"",be=W.find(Pe=>Pe.name===q),me=_.state==="input-available",pt=_.state==="output-available";if(me&&pe.has(q),me){if(pe.has(q))return null;const Pe=Ws(_.input);return c.jsx(ls,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:c.jsx(Ef,{toolName:q,description:be?.description||"",args:Pe,onApprove:async()=>{if(We.has(_.toolCallId))return;Me(gt=>new Set(gt).add(_.toolCallId));const $e=J.get(q);if($e)try{const gt=await $e(...Object.values(Pe));Mt({toolCallId:_.toolCallId,tool:q,output:gt})}catch(gt){Mt({toolCallId:_.toolCallId,tool:q,output:`Error: ${gt}`})}},onDeny:async()=>{We.has(_.toolCallId)||(Me($e=>new Set($e).add(_.toolCallId)),Mt({toolCallId:_.toolCallId,tool:q,output:"User denied tool execution"}))}})},`${_.toolCallId}-${H}`)}else if(pt){const Pe=_.output==="User denied tool execution",$e=Ws(_.input);return c.jsx(Df,{toolName:q,args:$e,isDenied:Pe,isSafe:pe.has(q)},`${_.toolCallId}-${H}`)}return null}if(_.type==="text"&&_.text&&Kn){const{processedText:q}=Co(_.text),Pe=!B.slice(H+1).some($e=>$e.type==="text"&&$e.text)&&te&&U.size>0;return c.jsx(Xf,{text:q,citations:O,citationMap:U,groupedCitations:Pe?ee:void 0,referencesText:Pe?Z:void 0,ResponseComponent:Kn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:D,showReferences:Pe},`${g.id}-${H}`)}return _.type==="reasoning"&&_.text?c.jsxs(dl,{className:"w-full",isStreaming:Re==="streaming"&&H===g.parts.length-1&&g.id===Ne.at(-1)?.id,children:[c.jsx(hl,{}),c.jsx(fl,{children:_.text})]},`${g.id}-${H}`):null})})})},g.id)}),c.jsx("div",{ref:rt})]})}),ts&&c.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",ts.message]}),c.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[c.jsx(Ku,{mode:"wait",children:(Re==="streaming"||Re==="submitted")&&c.jsxs(ls,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[c.jsx(ls,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),c.jsx("p",{className:"text-xs text-muted-foreground",children:vn})]})}),c.jsxs("form",{onSubmit:si,className:"relative",children:[c.jsx(Mo,{ref:Xe,value:_t,onChange:Sl,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),si(g))}}),Re==="streaming"||Re==="submitted"?c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"button",className:re(Dt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:ns,children:c.jsx(ne.Square,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{children:"Escape"})," to stop"]})]}):c.jsxs(yt,{children:[c.jsx(xt,{asChild:!0,children:c.jsx("button",{type:"submit",className:re(Dt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!_t.trim(),children:c.jsx(ne.ArrowRight,{className:"h-4 w-4"})})}),c.jsxs(bt,{children:[c.jsx(ai,{children:"Enter"})," to send"]})]})]})]})]}),c.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[c.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),c.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),c.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[c.jsx(ne.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),c.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):c.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:c.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function tm(e){return c.jsx(gl,{children:c.jsx(em,{...e})})}const nm={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function kn(e){for(const[t,n]of Object.entries(nm))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function sm(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function rm(e,t,n){return t.length>0}function im(e,t,n,s={}){const r=[];return Object.keys(s).forEach(i=>{const a=i in n,l=n[i];if(!a){const h=s[i];if(h!=null&&h!=="")return}const u=om(s[i]),d={name:i,type:am(l||kn(i)||"text"),label:yl(i),placeholder:lm(i,l),required:!0,value:u};d.type==="password"&&(d.validation=h=>h.length<8?"Password must be at least 8 characters":null),r.push(d)}),r.sort((i,a)=>{const l=i.name in n,u=a.name in n;return l===u?0:l?1:-1}),{shouldUseForm:rm(e,t),fields:r,title:cm(e),description:um(e,r.length)}}function om(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function am(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function yl(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function lm(e,t){return t?sm(t,e).placeholder:`Enter ${yl(e).toLowerCase()}...`}function cm(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function um(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function Vn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Vn(t)}catch{return e}if(Array.isArray(e))return e.map(Vn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Vn(s);return t}return e}function dm(e,t){if(!t||Object.keys(t).length===0)return e;const n={...e};return Object.keys(t).forEach(s=>{s in n&&delete n[s]}),n}function hm(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Vn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Vn(e):{}}const ms="__secureOutput",ps="[hidden for privacy]";function fm(e){if(typeof globalThis.structuredClone=="function")return globalThis.structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn("[useAgent] Failed to clone value for redaction:",t),e}}function mm(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function pm(e,t){if(t.length===0)return e;if(!e||typeof e!="object")return;let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return n}function gm(e,t,n){if(!e||typeof e!="object"||t.length===0)return!1;let s=e;for(let o=0;o<t.length-1;o++){if(!s||typeof s!="object")return!1;const i=s,a=t[o];if(a===void 0)return!1;const l=i[a];if(l==null||typeof l!="object")return!1;s=l}if(!s)return!1;const r=t[t.length-1];return!r||!(r in s)?!1:(s[r]=n,!0)}function pr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function xl(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=pr(r),r&&typeof r=="object"&&Object.assign(n,xl(r,o))}):t&&(n[t]=pr(e)),n}function ym(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:ps,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:ps,includeFieldStatus:!1,preserve:[]};const t=e.strategy??(e.fields&&e.fields.length>0?"fields":"full");return{strategy:t,fields:t==="fields"?e.fields??[]:[],placeholder:e.placeholder??ps,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function xm(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=ym(s);r&&(t[n]=r)}return t}function bl(e,t,n){const s=n.placeholder,r={tool:e,redacted:!0,strategy:n.strategy,placeholder:s};if(n.strategy==="full"){n.includeFieldStatus&&typeof t=="object"&&t!==null&&(r.fieldStatus=xl(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(u=>{u in t&&(l[u]=t[u])}),l[ms]=r,l}if(n.fields.includes("*"))return bl(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ms]:{...r,redactedFields:n.fields}};const o=fm(t),i=[],a={};return n.fields.forEach(l=>{const u=mm(l);if(u.length===0)return;const d=pm(o,u),h=pr(d);a[l]=h,gm(o,u,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ms]=r,o}function bm({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,sensitiveParams:l,sensitiveOutputs:u,autoDetectSensitive:d=!1,autoFormGeneration:h=!1,formMode:m="auto",systemPrompt:p="",agentId:w,agentName:b,initialMessages:j=[],conversationId:y,state:k,onStateChange:v,allowStateEdits:E=!0,onToolCall:N,onFinish:$,sources:L,ragConfig:D,ragFilters:z,secureInputHandler:A}={}){const M=f.useMemo(()=>D!==void 0?D:z?{enabled:!0,filters:z}:L&&L.length>0?{enabled:!0,organizationId:L[0],autoExecute:!0,filters:void 0}:{enabled:!1},[L,D,z]),I=f.useMemo(()=>{const x={};if(l)for(const[T,S]of Object.entries(l))if(x[T]={},Array.isArray(S))for(const C of S){const V=kn(C);x[T][C]=V||"text"}else for(const[C,V]of Object.entries(S))x[T][C]=V;if(a){for(const[T,S]of Object.entries(a))if(S&&typeof S=="object"&&"sensitiveParams"in S){x[T]||(x[T]={});const C=S.sensitiveParams;if(Array.isArray(C))for(const V of C){const W=kn(V);x[T][V]=W||"text"}else if(C&&typeof C=="object")for(const[V,W]of Object.entries(C))x[T][V]=W}}return x},[l,a,d]),F=f.useMemo(()=>xm(u),[u]),K=f.useCallback((x,T)=>{const S=F[x];if(!S)return T;try{return bl(x,T,S)}catch(C){return console.error(`[useAgent] Failed to redact output for ${x}:`,C),{value:ps,[ms]:{tool:x,redacted:!0,error:String(C)}}}},[F]),[Y,le]=f.useState(n||null),X=f.useRef(n||null),[oe,we]=f.useState(null),[Te,se]=f.useState(null),tt=f.useRef(null),[ut,ke]=f.useState([]),[He,Lt]=f.useState(y||(typeof window<"u"?crypto.randomUUID():null)),[ti,nt]=f.useState(!1),[st,Ue]=f.useState(new Set),[mn,_e]=f.useState(new Map),[Ft,Bt]=f.useState(new Map),[Wn,pn]=f.useState(new Map),[jt,ie]=f.useState(new Map),ce=k!==void 0,[Ve,Je]=f.useState({}),ue=f.useRef({}),gn=ce?k||{}:Ve;ce&&k?ue.current=k:ce||(ue.current=Ve);const[qn,zt]=f.useState(!1),[yn,Ct]=f.useState(null),Ut=f.useRef(!1),xn=f.useCallback(async(x,T=3)=>{if(!He||!X.current)return;const S=async()=>{const V=`${e.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,W=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:He,updates:x},format:"json"})});if(!W.ok){if(W.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const J=await W.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${W.status} ${J}`)}};for(let C=0;C<T;C++)try{await S(),Ct(null);return}catch(V){if(C===T-1){const J=V instanceof Error?V:new Error(String(V));throw Ct(J),console.error("Failed to sync state to Convex after retries:",V),J}await new Promise(J=>setTimeout(J,Math.pow(2,C)*100))}},[He,e,X]),rt=f.useMemo(()=>function(){return ue.current},[]),Xe=f.useMemo(()=>async function(T){const S={...ue.current,...T};ue.current=S,ce||Je(S),v&&v(S);try{await xn(T)}catch(C){throw C}},[xn,v,ce]);f.useEffect(()=>{ce&&k&&(ue.current=k)},[ce,k]);const _t=f.useCallback(x=>A?A.showSecureModal(x):new Promise(T=>{_e(S=>new Map(S).set(x.id,x)),Bt(S=>new Map(S).set(x.id,T))}),[A]),bn=f.useCallback((x,T)=>{if(A)return;const S=Ft.get(x);S&&(S(T),_e(C=>{const V=new Map(C);return V.delete(x),V}),Bt(C=>{const V=new Map(C);return V.delete(x),V}))},[Ft,A]),Kn=f.useCallback(x=>A?A.showSecureForm(x):new Promise(T=>{pn(S=>new Map(S).set(x.id,x)),ie(S=>new Map(S).set(x.id,T))}),[A]),As=f.useCallback((x,T)=>{if(A)return;const S=jt.get(x);S&&(S(T),pn(C=>{const V=new Map(C);return V.delete(x),V}),ie(C=>{const V=new Map(C);return V.delete(x),V}))},[jt,A]),vn=f.useCallback((x,T)=>{const S=I[x]||{},C=Object.keys(S).length>0;if(d){const V=Object.keys(T).filter(W=>kn(W)!==null);return C||V.length>0}return C},[I,d]),Gn=f.useCallback((x,T)=>{const C={...I[x]||{}};if(d){for(const W of Object.keys(T))if(!(W in C)){const J=kn(W);J&&(C[W]=J)}}const V=Object.entries(C).filter(([W])=>Object.prototype.hasOwnProperty.call(T,W));return V.length>0?Object.fromEntries(V):C},[I,d]),We=f.useMemo(()=>M?.enabled?async function(T,S=20,C){const V={...M.filters,...C};if(L&&L.length>1){const J=L.map(Q=>fetch(`${e}/search`,{method:"POST",headers:{"Content-Type":"application/json",...X.current?{Authorization:`Bearer ${X.current}`}:{}},body:JSON.stringify({q:T,k:Math.min(S,100),organizationId:Q,...Object.keys(V).length>0?{filters:V}:{}})}).then(ae=>ae.ok?ae.json():null)),pe=await Promise.all(J),ye=[];for(const Q of pe)Q?.candidates&&ye.push(...Q.candidates);ye.sort((Q,ae)=>{const Ze=Q.scores?.rerank||Q.scores?.dense||0;return(ae.scores?.rerank||ae.scores?.dense||0)-Ze});const xe=ye.slice(0,S).map((Q,ae)=>{const Ze=Q.citation||Q.url;return{rank:ae+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:Ze,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:T,total:ye.length,results:xe,summary:`Found ${ye.length} relevant results across ${L.length} source(s) for "${T}". Top result: ${xe[0]?.title||"N/A"}`}}const W=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const J={q:T,k:Math.min(S,100)};W&&(J.organizationId=W),Object.keys(V).length>0&&(J.filters=V);const pe={"Content-Type":"application/json"};X.current&&(pe.Authorization=`Bearer ${X.current}`);const ye=await fetch(`${e}/search`,{method:"POST",headers:pe,body:JSON.stringify(J)});if(!ye.ok){const ae=await ye.text();return{success:!1,error:`Search failed: ${ye.status} ${ae}`}}const xe=await ye.json(),Q=xe.candidates.map((ae,Ze)=>{const kt=ae.citation||ae.url;return{rank:Ze+1,doc_id:ae.doc_id,block_id:ae.block_id,url:ae.url,citation:kt,title:ae.title||"Untitled",snippet:ae.snippet,score:ae.scores?.rerank||ae.scores?.dense||0,metadata:{site:ae.metadata?.site,lang:ae.metadata?.lang,contentType:ae.metadata?.content_type}}});return{success:!0,query:xe.query,total:xe.total,results:Q,summary:`Found ${xe.total} relevant results for "${T}". Top result: ${Q[0]?.title||"N/A"}`}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error occurred"}}}:null,[M,e,X]),Me=f.useMemo(()=>M?.enabled?async function(T,S){const C=M.organizationId&&M.organizationId!=="default"?M.organizationId:L&&L.length>0?L[0]:void 0;try{const V={"Content-Type":"application/json"};X.current&&(V.Authorization=`Bearer ${X.current}`);const W=await fetch(`${e}/fetch`,{method:"POST",headers:V,body:JSON.stringify({doc_id:T,block_ids:S,...C?{organizationId:C}:{}})});if(!W.ok){const pe=await W.text();return{success:!1,error:`Fetch failed: ${W.status} ${pe}`}}const J=await W.json();return{success:!0,blocks:J.blocks||[],fullContent:J.fullContent||"",pageUrl:J.pageUrl||"",pageTitle:J.pageTitle||"",summary:`Fetched ${J.blocks?.length||0} blocks from ${J.pageTitle||T}`}}catch(V){return{success:!1,error:V instanceof Error?V.message:"Unknown error occurred"}}}:null,[M,e,X]),Xt=f.useMemo(()=>{const x=[...o,...i,rt];return(!ce||E)&&x.push(Xe),M?.enabled&&(We&&x.push(We),Me&&x.push(Me)),x},[o,i,rt,Xe,We,Me,M,ce,E]),it=f.useMemo(()=>Qr(Xt,a),[Xt,a]),De=f.useMemo(()=>{const x=new Map,T=new Map(it.map(S=>[S.name,S]));return x.set("getState",rt),(!ce||E)&&x.set("setState",Xe),M?.enabled&&(We&&x.set("searchDocs",We),Me&&x.set("fetchDocContent",Me)),Xt.forEach(S=>{if(S===rt||S===Xe||S===We||S===Me)return;const C=S[Qe];if(C){const W=T.get(C);if(W){x.set(W.name,S);return}}const V=it.find(W=>W.name===S.name);V&&x.set(V.name,S)}),x},[Xt,it,rt,Xe,We,Me,M,ce,E]),Yn=f.useMemo(()=>new Set(it.map(x=>x.name)),[it]),Hn=f.useMemo(()=>{const x=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!ce||E)&&x.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}});const T=[];return M?.enabled&&T.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}}),[...it,...x,...T]},[it,M,ce,E]),dt=f.useMemo(()=>Hn.filter(x=>x.name==="getState"?!0:x.name==="setState"?!ce||E:M?.enabled&&(x.name==="searchDocs"||x.name==="fetchDocContent")?!0:Yn.has(x.name)),[Hn,Yn,ce,E,M]),wn=f.useMemo(()=>{const x=new Set;return x.add("getState"),x.add("setState"),M?.enabled&&M.autoExecute!==!1&&(x.add("searchDocs"),x.add("fetchDocContent")),i.forEach(T=>{for(const[S,C]of De.entries())if(C===T){x.add(S);break}}),x},[i,De,M]);f.useEffect(()=>s||n?void 0:((async()=>{try{const T=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!T.ok)throw new Error("Failed to fetch token");const S=await T.json();le(S.clientToken),X.current=S.clientToken,se(S.expiresAt),we(null)}catch(T){console.error("[useAgent] Token fetch failed:",T),we(T instanceof Error?T.message:"Failed to fetch token")}})(),()=>{tt.current&&clearTimeout(tt.current)}),[t,JSON.stringify(r),s,n]),f.useEffect(()=>{if(!Te||s||n)return;tt.current&&clearTimeout(tt.current);const x=Math.floor(Date.now()/1e3),T=Te-x,C=Math.max(0,T-5);return tt.current=setTimeout(async()=>{try{const V=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!V.ok)throw new Error("Failed to refresh token");const W=await V.json();le(W.clientToken),X.current=W.clientToken,se(W.expiresAt),we(null)}catch(V){console.error("[useAgent] Token refresh failed:",V),we(V instanceof Error?V.message:"Failed to refresh token")}},C*1e3),()=>{tt.current&&clearTimeout(tt.current)}},[Te,t,JSON.stringify(r),s,n]);const Tn=async(x,T={})=>{const S=T.headers?new Headers(T.headers):new Headers;S.delete("user-agent"),S.delete("User-Agent"),console.log("[useAgent] Making request to:",x),console.log("[useAgent] Method:",T.method||"GET"),console.log("[useAgent] Has Authorization header:",S.has("Authorization")),console.log("[useAgent] Client token available:",!!X.current);try{const C=await fetch(x,{...T,headers:S});if(!C.ok){console.error("[useAgent] Request failed:",C.status,C.statusText);const V=await C.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",V)}return C}catch(C){throw console.error("[useAgent] Fetch error:",C),C}},Sn=`${e}/chat`;console.log("[useAgent] Chat API URL:",Sn);const{messages:Ie,sendMessage:Jn,status:Oe,error:Pt,stop:ht,addToolResult:ft,setMessages:Zn}=Po.useChat({id:He||void 0,messages:j,transport:new gs.DefaultChatTransport({api:Sn,fetch:Tn,headers:()=>{const x={};return X.current?(x.Authorization=`Bearer ${X.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),x},body:()=>{console.log("[ArctenAgent] body() agentName =",b);const x=dt.map(C=>({name:C.name,description:C.description,inputSchema:C.jsonSchema})),T=x.filter(C=>C.name==="getState"||C.name==="setState").map(C=>C.name),S=x.filter(C=>C.name==="searchDocs"||C.name==="fetchDocContent").map(C=>C.name);return T.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",T),S.length>0?console.log("[useAgent] RAG tools included in tools list sent to AI SDK:",S):M?.enabled&&console.warn("[useAgent] RAG is enabled but no RAG tools found in tools list!"),{tools:x,...w&&{agentId:w},...b&&{agentName:b},state:ue.current,...z&&{ragFilters:z}}}}),sendAutomaticallyWhen:gs.lastAssistantMessageIsCompleteWithToolCalls}),qe=f.useCallback((x,T,S)=>{const C=K(x,S);ft({toolCallId:T,tool:x,output:C})},[ft,K]);f.useEffect(()=>{Ie.forEach(x=>{x.role==="assistant"&&x.parts.forEach(T=>{if(!T.type?.startsWith("tool-")||T.state!=="input-available")return;const S=T.type.replace("tool-",""),C=T.toolCallId;if(st.has(C))return;Ue(W=>new Set(W).add(C));const V=hm(T.input);if(vn(S,V)){const W=Gn(S,V),J=Object.entries(W).filter(([Q])=>V[Q]!==void 0),pe=J.length>0?Object.fromEntries(J):W,ye=Object.keys(V),xe=dm(V,pe);(async()=>{try{const Q=im(S,ye,pe,V),ae={id:`${C}-form`,toolName:S,toolCallId:C,title:Q.title,description:Q.description,fields:Q.fields},Ze=await Kn(ae);if(Ze===null){qe(S,C,"User cancelled secure input");return}const kt={...xe,...Ze},jn=De.get(S);if(!jn)throw new Error(`Tool ${S} not found`);let Cn;const Ne=dt.find(es=>es.name===S);if(Ne&&Ne.jsonSchema?.properties){const Re=Object.keys(Ne.jsonSchema.properties).map(ts=>kt[ts]);Cn=await jn(...Re)}else Cn=await jn(...Object.values(kt));qe(S,C,Cn)}catch(Q){console.error(`[useAgent] Error executing tool with secure input ${S}:`,Q),qe(S,C,`Error: ${Q}`)}})();return}if(wn.has(S)&&!vn(S,V)){const W=De.get(S);W?(async()=>{try{const J=dt.find(ye=>ye.name===S);let pe;if(J&&J.jsonSchema?.properties){const xe=Object.keys(J.jsonSchema.properties).map(Q=>V[Q]);pe=await W(...xe)}else if(S==="getState")pe=W();else if(S==="setState"){const ye=V.updates||V;pe=await W(ye)}else pe=await W(...Object.values(V));qe(S,C,pe)}catch(J){console.error(`[useAgent] Error executing tool ${S}:`,J),qe(S,C,`Error: ${J}`)}})():console.warn(`[useAgent] Tool ${S} not found in toolsMap`)}else N&&N({toolCall:{toolCallId:C,toolName:S,args:V}})})})},[Ie,wn,De,N,qe,st,Xe,dt,vn,Gn,_t]),f.useEffect(()=>{if(Oe==="ready"&&Ie.length>0&&$){const x=Ie[Ie.length-1];x&&x.role==="assistant"&&$({message:x,messages:Ie,isAbort:!1,isDisconnect:!1,isError:!!Pt})}},[Oe,Ie,Pt,$]);async function ni(){if(!(!r?.id||!Y)){nt(!0);try{const T=await(await fetch(`${e}/conversations`,{headers:{Authorization:`Bearer ${Y}`}})).json();ke(T.conversations||[])}catch(x){console.error("Failed to fetch conversations:",x)}finally{nt(!1)}}}f.useEffect(()=>{r?.id&&Y&&ni()},[JSON.stringify(r),Y,e]),f.useEffect(()=>{if(!He||!X.current)return;(async()=>{zt(!0),Ct(null);try{const T=await fetch(`${e.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:He},format:"json"})});if(!T.ok){const V=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${V}`)}const C=(await T.json())?.value||{};ue.current=C,ce||Je(C),v&&v(C),Ut.current=!0}catch(T){console.error("Failed to fetch state:",T);const S=T instanceof Error?T:new Error(String(T));Ct(S),Ut.current||(ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!0)}finally{zt(!1)}})()},[He,e,ce,v]);async function Wt(x){Lt(x),nt(!0);try{const T=await fetch(`${e}/conversations/${x}/messages`,{headers:{Authorization:`Bearer ${X.current}`}});if(!T.ok)throw new Error(`Failed to fetch messages: ${T.statusText}`);const C=(await T.json()).messages||[];Zn(C)}catch(T){console.error("Failed to load conversation messages:",T)}finally{nt(!1)}}async function Qn(x){if(Y)try{await fetch(`${e}/conversations/${x}`,{method:"DELETE",headers:{Authorization:`Bearer ${Y}`}}),ke(ut.filter(T=>T._id!==x)),x===He&&mt()}catch(T){console.error("Failed to delete conversation:",T)}}function mt(){const x=crypto.randomUUID();Lt(x),Zn([]),Ue(new Set),ue.current={},ce?v&&v({}):(Je({}),v&&v({})),Ut.current=!1}function At(x){const T=x.tool||"unknown-tool",S=K(T,x.output);ft({toolCallId:x.toolCallId,tool:T,output:S})}async function ot(x){const T={...ue.current,...x};ue.current=T,ce||Je(T),v&&v(T);try{await xn(x)}catch(S){throw S}}return{id:He,messages:Ie,status:Oe,error:Pt,sendMessage:Jn,stop:ht,addToolOutput:At,setMessages:Zn,conversations:ut,loadConversation:Wt,deleteConversation:Qn,startNewConversation:mt,isLoadingConversations:ti,clientToken:Y,tokenError:oe,state:gn,setState:ot,isStateLoading:qn,stateError:yn,pendingSecureInputs:Array.from(mn.values()),completeSecureInput:bn,pendingSecureForms:Array.from(Wn.values()),completeSecureForm:As}}exports.verifyToken=zl.verifyToken;exports.ARCTEN_ORIGINAL_NAME=Qe;exports.ArctenAgent=tm;exports.SecureModalProvider=gl;exports.extractToolsMetadata=Qr;exports.preserveToolName=kf;exports.useAgent=bm;exports.useSecureModal=pl;
|
package/dist/index.mjs
CHANGED
|
@@ -8681,6 +8681,7 @@ function lp({
|
|
|
8681
8681
|
return W.current ? (y.Authorization = `Bearer ${W.current}`, console.log("[useAgent] Adding Authorization header with token")) : console.warn("[useAgent] No client token available - request may fail"), y;
|
|
8682
8682
|
},
|
|
8683
8683
|
body: () => {
|
|
8684
|
+
console.log("[ArctenAgent] body() agentName =", b);
|
|
8684
8685
|
const y = gt.map((P) => ({
|
|
8685
8686
|
name: P.name,
|
|
8686
8687
|
description: P.description,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAgent.d.ts","sourceRoot":"","sources":["../../src/lib/useAgent.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,eAAe,EACf,cAAc,EAKf,MAAM,oBAAoB,CAAC;AA2S5B,wBAAgB,QAAQ,CAAC,EACvB,UAAqC,EACrC,aAAmC,EACnC,WAAW,EAAE,aAAa,EAC1B,cAAsB,EACtB,IAAI,EACJ,KAAU,EACV,SAAc,EACd,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,mBAA2B,EAC3B,kBAA0B,EAC1B,QAAiB,EAEjB,YAAiB,EACjB,OAAO,EACP,SAAS,EACT,eAAoB,EACpB,cAAc,EAAE,qBAAqB,EACrC,KAAK,EAAE,eAAe,EACtB,aAAa,EACb,eAAsB,EACtB,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,UAAU,EAAE,+CAA+C;AAC3D,kBAAkB,GACnB,GAAE,eAAoB,GAAG,cAAc,
|
|
1
|
+
{"version":3,"file":"useAgent.d.ts","sourceRoot":"","sources":["../../src/lib/useAgent.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,eAAe,EACf,cAAc,EAKf,MAAM,oBAAoB,CAAC;AA2S5B,wBAAgB,QAAQ,CAAC,EACvB,UAAqC,EACrC,aAAmC,EACnC,WAAW,EAAE,aAAa,EAC1B,cAAsB,EACtB,IAAI,EACJ,KAAU,EACV,SAAc,EACd,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,mBAA2B,EAC3B,kBAA0B,EAC1B,QAAiB,EAEjB,YAAiB,EACjB,OAAO,EACP,SAAS,EACT,eAAoB,EACpB,cAAc,EAAE,qBAAqB,EACrC,KAAK,EAAE,eAAe,EACtB,aAAa,EACb,eAAsB,EACtB,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,UAAU,EAAE,+CAA+C;AAC3D,kBAAkB,GACnB,GAAE,eAAoB,GAAG,cAAc,CAq4CvC"}
|