@arcteninc/core 0.0.82 → 0.0.83
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/components/ArctenAgent.d.ts +1 -0
- package/dist/components/ArctenAgent.d.ts.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.mjs +102 -98
- package/dist/lib/useAgent.d.ts.map +1 -1
- package/dist/types/use-agent.d.ts +1 -0
- package/dist/types/use-agent.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ArctenAgent.d.ts","sourceRoot":"","sources":["../../src/components/ArctenAgent.tsx"],"names":[],"mappings":"AA4LA,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAEnD,MAAM,WAAW,SAAS;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;KACjB,CAAC;CACH;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAClC,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,sBAAsB,GAAG,eAAe,GAAG,cAAc,CAAC;IAC3E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,KAAK,CAAC,EAAE,YAAY,EAAE,CAAC;IACvB,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;IAC3B,YAAY,CAAC,EAAE,GAAG,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;IAE1C,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;IACrD,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,wBAAgB,WAAW,CAAC,EAC1B,KAAc,EACd,MAAkB,EAClB,KAAc,EACd,QAAe,EACf,KAAc,EACd,IAAgB,EAChB,YAAkB,EAClB,QAAc,EACd,QAAc,EACd,iBAAyB,EACzB,KAAU,EACV,SAAc,EACd,YAAY,EACZ,YAAiB,EACjB,aAAmC,EACnC,UAAqC,EACrC,IAAI,EACJ,KAAK,EACL,aAAa,EACb,eAAsB,EACtB,OAAO,EACP,SAAS,EACT,aAAoB,GACrB,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"ArctenAgent.d.ts","sourceRoot":"","sources":["../../src/components/ArctenAgent.tsx"],"names":[],"mappings":"AA4LA,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAEnD,MAAM,WAAW,SAAS;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;KACjB,CAAC;CACH;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAClC,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,sBAAsB,GAAG,eAAe,GAAG,cAAc,CAAC;IAC3E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,KAAK,CAAC,EAAE,YAAY,EAAE,CAAC;IACvB,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;IAC3B,YAAY,CAAC,EAAE,GAAG,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;IAE1C,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;IACrD,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,wBAAgB,WAAW,CAAC,EAC1B,KAAc,EACd,MAAkB,EAClB,KAAc,EACd,QAAe,EACf,KAAc,EACd,IAAgB,EAChB,YAAkB,EAClB,QAAc,EACd,QAAc,EACd,iBAAyB,EACzB,KAAU,EACV,SAAc,EACd,YAAY,EACZ,YAAiB,EACjB,aAAmC,EACnC,UAAqC,EACrC,IAAI,EACJ,KAAK,EACL,aAAa,EACb,eAAsB,EACtB,OAAO,EACP,SAAS,EACT,aAAoB,GACrB,EAAE,gBAAgB,kDAumElB"}
|
package/dist/index.cjs
CHANGED
|
@@ -16,9 +16,9 @@ Please:
|
|
|
16
16
|
useAgent({ tools: [...], toolMetadata: toolMetadata })
|
|
17
17
|
(Pass the full object for better minification support, or toolMetadata.functions for backward compatibility)
|
|
18
18
|
`);if("functions"in e&&typeof e.functions=="object"){const o=e;n=o.functions,s=o.toolOrder}else n=e,s=void 0;const r=new Set;return t.map(o=>{const i=Hh(o,n,r,s);if(!i){const a=o.name,l=o[zt]||a||"unnamed";return 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 "${l}". This tool will be excluded.
|
|
19
|
-
To fix: Run "arcten-extract-types ." and ensure "${l}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function Xh({toolName:t,description:e,args:n,onApprove:s,onDeny:r}){const o=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})}),o&&h.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,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:[i,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),h.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[h.jsxs(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(dt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:h.jsx(dt.X,{className:"h-3 w-3"})})]})]})})}function Gh({toolName:t,args:e,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(t==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];t==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([l])=>!i.includes(l))),c=Object.keys(a).length>0;return h.jsxs("div",{className:"my-1",children:[h.jsxs("button",{onClick:()=>c&&o(!r),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"} ${c?"cursor-pointer hover:bg-opacity-80":""}`,children:[c&&h.jsx("span",{className:"transition-transform duration-200",children:r?h.jsx(dt.ChevronDown,{className:"h-3 w-3"}):h.jsx(dt.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(dt.X,{className:"h-3 w-3"}):s?h.jsx(dt.Zap,{className:"h-3 w-3"}):h.jsx(dt.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),r&&c&&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(([l,u])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[l,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof u=="string"?u:JSON.stringify(u)})]},l))})})]})}function Yh({...t}){return h.jsx(Os.Root,{"data-slot":"collapsible",...t})}function Jh({...t}){return h.jsx(Os.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function Zh({...t}){return h.jsx(Os.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const Qh=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),xr=m.memo(({className:t,...e})=>typeof window>"u"?null:h.jsx(m.Suspense,{fallback:null,children:h.jsx(Qh,{className:ht("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);xr.displayName="Response";const tf=Object.freeze(Object.defineProperty({__proto__:null,Response:xr},Symbol.toStringTag,{value:"Module"})),ef=({children:t,as:e="p",className:n,duration:s=2,spread:r=2})=>{const o=_h.create(e),i=m.useMemo(()=>(t?.length??0)*r,[t,r]);return h.jsx(o,{animate:{backgroundPosition:"0% center"},className:ht("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":`${i}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})},nf=m.memo(ef),Da=m.createContext(null),sf=()=>{const t=m.useContext(Da);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},rf=1e3,of=1e3,Va=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,l]=Pr.useControllableState({prop:n,defaultProp:s,onChange:r}),[u,d]=Pr.useControllableState({prop:o,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)/of)),v(null))},[e,y,d]),m.useEffect(()=>{if(s&&!e&&c&&!f){const x=setTimeout(()=>{l(!1),g(!0)},rf);return()=>clearTimeout(x)}},[e,c,s,l,f]);const C=x=>{l(x)};return h.jsx(Da.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:l,duration:u},children:h.jsx(Yh,{className:ht("not-prose mb-4",t),onOpenChange:C,open:c,...a,children:i})})}),af=(t,e)=>t||e===0?h.jsx(nf,{duration:1,children:"Thinking..."}):e===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",e," seconds"]}),Na=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=sf();return h.jsx(Jh,{className:ht("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(dt.BrainIcon,{className:"size-4"}),af(s,o),h.jsx(dt.ChevronDownIcon,{className:ht("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ra=m.memo(({className:t,children:e,...n})=>h.jsx(Zh,{className:ht("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(xr,{className:"grid gap-2",children:e})}));Va.displayName="Reasoning";Na.displayName="ReasoningTrigger";Ra.displayName="ReasoningContent";function _i(t){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(t)}&sz=16`}function cf({sources:t,citationNumber:e,className:n}){const s=t.find(o=>o.number===e);if(!s)return null;const r=_i(s.domain);return h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsxs("button",{className:ht("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[h.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),h.jsx("span",{className:"leading-none",children:s.domain})]})}),h.jsx(ee,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:h.jsxs("div",{className:"space-y-1.5",children:[h.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",t.length]}),t.map(o=>h.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ht("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:i=>i.stopPropagation(),children:[h.jsx("img",{src:_i(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:i=>{const a=i.target;a.style.display="none"}}),h.jsx("span",{className:"text-xs flex-1 truncate",children:o.domain})]},o.number))]})})]})}function lf({text:t,citations:e,citationMap:n,referencesText:s,ResponseComponent:r,className:o,showCitations:i=!0}){const a=m.useRef(null),[c,l]=m.useState([]);m.useEffect(()=>{if(!i||!a.current||e.length===0||n.size===0){(n.size===0||!i)&&l([]);return}const d=a.current;let f,g=!1;const y=new WeakSet,v=()=>{if(!a.current||g)return;g=!0;const x=a.current,w=/\[(\d+)\]/g,S=document.createTreeWalker(x,NodeFilter.SHOW_TEXT,null),P=[];let V;for(;V=S.nextNode();)if(V.nodeType===Node.TEXT_NODE&&!y.has(V)){const k=V,N=k.textContent||"";let $=k.parentElement,L=!1;for(;$&&$!==x;){if($.tagName==="A"||$.tagName==="CODE"||$.tagName==="PRE"){L=!0;break}$=$.parentElement}if(!L){const Y=Array.from(N.matchAll(w)).filter(mt=>{if(!mt[1])return!1;const Vt=parseInt(mt[1],10);return n.has(Vt)});Y.length>0&&P.push({node:k,matches:Y})}}if(P.length===0){g=!1;return}const I=[];P.forEach(({node:k,matches:N})=>{y.add(k);const $=k.textContent||"",L=document.createDocumentFragment();let Z=0;N.forEach(Y=>{if(!Y[1])return;Y.index!==void 0&&Y.index>Z&&L.appendChild(document.createTextNode($.slice(Z,Y.index)));const mt=document.createElement("span");mt.className="inline-flex items-center citation-button-container";const Vt=parseInt(Y[1],10);mt.setAttribute("data-citation",Y[1]),L.appendChild(mt),I.push({element:mt,citationNum:Vt}),Z=(Y.index||0)+Y[0].length}),Z<$.length&&L.appendChild(document.createTextNode($.slice(Z))),k.parentNode&&k.parentNode.replaceChild(L,k)}),I.length>0&&l(k=>{const N=new Set(k.map(Z=>Z.element)),$=k.filter(Z=>Z.element.isConnected),L=I.filter(Z=>!N.has(Z.element));return[...$,...L]}),g=!1},C=new MutationObserver(()=>{clearTimeout(f),f=setTimeout(v,100)});return C.observe(d,{childList:!0,subtree:!0,characterData:!0}),f=setTimeout(v,200),()=>{C.disconnect(),clearTimeout(f)}},[t,e,n,i]);const u=i&&s?h.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[h.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-2",children:"References"}),h.jsx("div",{className:"text-xs text-stone-600 dark:text-stone-400 space-y-1",children:Array.from(n.entries()).sort(([d],[f])=>d-f).map(([d,f])=>h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("span",{className:"font-medium",children:["[",d,"]"]}),h.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:f})]},d))})]}):null;return h.jsxs("div",{className:o,children:[h.jsx("div",{ref:a,children:h.jsx(r,{children:t})}),i&&c.filter(({element:d})=>d.isConnected).map(({element:d,citationNum:f},g)=>e.find(v=>v.number===f)?oc.createPortal(h.jsx(cf,{sources:e.map(v=>({number:v.number,url:v.url,domain:uf(v.url)})),citationNumber:f},`citation-${f}-${d}`),d,`citation-${f}-${g}`):null),u]})}function uf(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function df(t){let e=t.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=e.match(n),r=new Map,o=[];if(s&&s[1]){const g=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let v;for(;(v=y.exec(g))!==null;)if(v[1]&&v[2]){const C=parseInt(v[1],10),x=v[2].replace(/[.,;:!?]+$/,"");r.set(C,x),o.push({number:C,url:x})}}let i,a=e;s&&s[0]&&(i=s[0],a=e.replace(n,""));const c=[];let l=0;const u=/```[\s\S]*?```|`[^`]+`/g;let d;for(;(d=u.exec(a))!==null;)d.index>l&&c.push({type:"text",content:a.slice(l,d.index),start:l,end:d.index}),c.push({type:"code",content:d[0],start:d.index,end:d.index+d[0].length}),l=d.index+d[0].length;return l<a.length&&c.push({type:"text",content:a.slice(l),start:l,end:a.length}),{processedText:c.map(g=>{if(g.type==="code")return g.content;let y=g.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(C,x,w)=>{const S=parseInt(x,10);return r.has(S)||(r.set(S,w),o.push({number:S,url:w})),`[${S}]`}),y}).join(""),citations:o.sort((g,y)=>g.number-y.number),citationMap:r,referencesText:i}}function en(t){if(typeof t=="string")try{const e=JSON.parse(t);return en(e)}catch{return t}if(Array.isArray(t))return t.map(en);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=en(s);return e}return t}function ds(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return en(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?en(t):{}}function hf({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:l=!1,tools:u=[],safeTools:d=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:y="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:C,state:x,onStateChange:w,allowStateEdits:S=!0,sources:P,ragConfig:V,showCitations:I=!0}){const k=m.useMemo(()=>V!==void 0?V:P&&P.length>0?{enabled:!0,organizationId:P[0],filters:void 0}:{enabled:!1},[P,V]),[N,$]=m.useState(null),L=m.useRef(null),[Z,Y]=m.useState(null),[mt,Vt]=m.useState(null),gt=m.useRef(null),Q=x!==void 0,[ot,ct]=m.useState({}),et=m.useRef({});Q&&x?et.current=x:Q||(et.current=ot);const[ut,oe]=m.useState(!1),[_n,we]=m.useState(null),Nt=m.useRef(!1),[vt,ae]=m.useState(l),[bt,Ft]=m.useState(i),[Rt,$t]=m.useState(600),[ce,Ct]=m.useState(!1),[J,Te]=m.useState(!1),[Pt,Ht]=m.useState(!1),[wt,Be]=m.useState({x:100,y:100}),[ze,jt]=m.useState(!1),[Ue,Se]=m.useState({x:0,y:0}),[_e,Wn]=m.useState(!1),Xt=m.useRef(null),Gt=m.useRef(null),[Ae,We]=m.useState(""),[mn,pn]=m.useState(null),[Kn,qn]=m.useState("Thinking..."),[Ke,Yt]=m.useState(new Set),[j,A]=m.useState(""),[M,F]=m.useState([]),[z,U]=m.useState(!1),[q,yt]=m.useState([]),[nt,At]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[X,tt]=m.useState(!1),[Ce,le]=m.useState(!1),[pf,gn]=m.useState([]),vr=m.useCallback(async(p,b=3)=>{if(!nt||!L.current)return;const E=async()=>{const D=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:nt,updates:p},format:"json"})});if(!R.ok){if(R.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const K=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${K}`)}};for(let T=0;T<b;T++)try{await E(),we(null);return}catch(D){if(T===b-1){const K=D instanceof Error?D:new Error(String(D));throw we(K),console.error("Failed to sync state to Convex after retries:",D),K}await new Promise(K=>setTimeout(K,Math.pow(2,T)*100))}},[nt,v,L]),qe=m.useMemo(()=>function(){return et.current},[]),He=m.useMemo(()=>async function(b){const E={...et.current,...b};et.current=E,Q||ct(E),w&&w(E);try{await vr(b)}catch(T){throw T}},[vr,w,Q]);m.useEffect(()=>{Q&&x&&(et.current=x)},[Q,x]);const ue=m.useMemo(()=>k?.enabled?async function(b,E=20,T){if(P&&P.length>1){const K=P.map(_=>fetch(`${v}/search`,{method:"POST",headers:{"Content-Type":"application/json",...L.current?{Authorization:`Bearer ${L.current}`}:{}},body:JSON.stringify({q:b,k:Math.min(E,100),organizationId:_,...Object.keys(R).length>0?{filters:R}:{}})}).then(W=>W.ok?W.json():null)),B=await Promise.all(K),G=[];for(const _ of B)_?.candidates&&G.push(..._.candidates);G.sort((_,W)=>{const Tt=_.scores?.rerank||_.scores?.dense||0;return(W.scores?.rerank||W.scores?.dense||0)-Tt});const H=G.slice(0,E).map((_,W)=>{const Tt=_.citation||_.url;return{rank:W+1,doc_id:_.doc_id,block_id:_.block_id,url:_.url,citation:Tt,title:_.title||"Untitled",snippet:_.snippet,score:_.scores?.rerank||_.scores?.dense||0,metadata:{site:_.metadata?.site,lang:_.metadata?.lang,contentType:_.metadata?.content_type}}});return{success:!0,query:b,total:G.length,results:H,summary:`Found ${G.length} relevant results across ${P.length} source(s) for "${b}". Top result: ${H[0]?.title||"N/A"}`}}const D=k.organizationId&&k.organizationId!=="default"?k.organizationId:void 0,R={...k.filters,...T};try{const K={q:b,k:Math.min(E,100)};D&&(K.organizationId=D),Object.keys(R).length>0&&(K.filters=R);const B={"Content-Type":"application/json"};L.current&&(B.Authorization=`Bearer ${L.current}`);const G=await fetch(`${v}/search`,{method:"POST",headers:B,body:JSON.stringify(K)});if(!G.ok){const W=await G.text();return{success:!1,error:`Search failed: ${G.status} ${W}`}}const H=await G.json(),_=H.candidates.map((W,Tt)=>{const wn=W.citation||W.url;return{rank:Tt+1,doc_id:W.doc_id,block_id:W.block_id,url:W.url,citation:wn,title:W.title||"Untitled",snippet:W.snippet,score:W.scores?.rerank||W.scores?.dense||0,metadata:{site:W.metadata?.site,lang:W.metadata?.lang,contentType:W.metadata?.content_type}}});return{success:!0,query:H.query,total:H.total,results:_,summary:`Found ${H.total} relevant results for "${b}". Top result: ${_[0]?.title||"N/A"}`}}catch(K){return{success:!1,error:K instanceof Error?K.message:"Unknown error occurred"}}}:null,[V,v,L]),de=m.useMemo(()=>k?.enabled?async function(b,E){const T=k.organizationId&&k.organizationId!=="default"?k.organizationId:P&&P.length>0?P[0]:void 0;try{const D={"Content-Type":"application/json"};L.current&&(D.Authorization=`Bearer ${L.current}`);const R=await fetch(`${v}/fetch`,{method:"POST",headers:D,body:JSON.stringify({doc_id:b,block_ids:E,...T?{organizationId:T}:{}})});if(!R.ok){const B=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${B}`}}const K=await R.json();return{success:!0,blocks:K.blocks||[],fullContent:K.fullContent||"",pageUrl:K.pageUrl||"",pageTitle:K.pageTitle||"",summary:`Fetched ${K.blocks?.length||0} blocks from ${K.pageTitle||b}`}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Unknown error occurred"}}}:null,[V,v,L]),he=m.useMemo(()=>{const p=[...u,...d,qe];return(!Q||S)&&p.push(He),k?.enabled&&(ue&&p.push(ue),de&&p.push(de)),p},[u,d,qe,He,ue,de,Q,S,k]),Hn=m.useMemo(()=>Ea(he,f),[he,f]),_t=m.useMemo(()=>{const p=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!Q||S)&&p.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 b=[];return k?.enabled&&b.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"]}}),[...Hn,...p,...b]},[Hn,Q,S,k]),br=m.useMemo(()=>new Set(_t.map(p=>p.name)),[_t]),yn=m.useMemo(()=>_t.filter(p=>p.name==="getState"?!0:p.name==="setState"?!Q||S:br.has(p.name)),[_t,br,Q,S]),xn=m.useMemo(()=>{const p=new Map,b=new Map(Hn.map(E=>[E.name,E]));return p.set("getState",qe),(!Q||S)&&p.set("setState",He),k?.enabled&&(ue&&p.set("searchDocs",ue),de&&p.set("fetchDocContent",de)),he.forEach(E=>{if(E===qe||E===He||E===ue||E===de)return;const T=E[zt];if(T){const R=b.get(T);if(R){p.set(R.name,E);return}}const D=_t.find(R=>R.name===E.name);D&&p.set(D.name,E)}),p},[he,_t,qe,He,ue,de,Q,S,k]),Xe=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),k?.enabled&&(p.add("searchDocs"),p.add("fetchDocContent"));const b=new Map(_t.map(E=>[E.name,E]));return d.forEach(E=>{const T=E[zt];if(T&&b.has(T))p.add(T);else{const D=_t.find(R=>R.name===E.name);D&&p.add(D.name)}}),p},[d,_t,k]),wr=["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&&ae(JSON.parse(p));const b=localStorage.getItem("arcten-sidebar-width");b&&Ft(parseInt(b));const E=localStorage.getItem("arcten-sidebar-height");E&&$t(parseInt(E));const T=localStorage.getItem("arcten-sidebar-detached");T&&Te(JSON.parse(T));const D=localStorage.getItem("arcten-sidebar-position");if(D){const K=JSON.parse(D),B=50,G=Math.max(B-i,Math.min(K.x,window.innerWidth-B)),H=Math.max(0,Math.min(K.y,window.innerHeight-B));Be({x:G,y:H})}const R=localStorage.getItem("arcten-sidebar-minimized");R&&Ht(JSON.parse(R)),Wn(!0)}},[]);const Jt=m.useMemo(()=>C,[C?.id]);m.useEffect(()=>((async()=>{try{const b=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!b.ok)throw new Error("Failed to fetch token");const E=await b.json();$(E.clientToken),L.current=E.clientToken,Vt(E.expiresAt),Y(null)}catch(b){Y(b instanceof Error?b.message:"Failed to fetch token")}})(),()=>{gt.current&&clearTimeout(gt.current)}),[y,Jt]),m.useEffect(()=>{if(!mt)return;gt.current&&clearTimeout(gt.current);const p=Math.floor(Date.now()/1e3),b=mt-p,T=Math.max(0,b-5);return gt.current=setTimeout(async()=>{try{const D=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!D.ok)throw new Error("Failed to refresh token");const R=await D.json();$(R.clientToken),L.current=R.clientToken,Vt(R.expiresAt),Y(null)}catch(D){console.error("Token refresh failed:",D),Y(D instanceof Error?D.message:"Failed to refresh token")}},T*1e3),()=>{gt.current&&clearTimeout(gt.current)}},[mt,y,Jt]),m.useEffect(()=>{(async()=>{if(he.length!==0)try{const b=he.map(T=>({name:T.name,code:T.toString()})),E=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:b})});if(E.ok){const T=await E.json();F(T.tools)}}catch(b){console.error("Failed to fetch tool descriptions:",b)}})()},[he]),m.useEffect(()=>{Promise.resolve().then(()=>tf).then(p=>{pn(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{A(window.location.pathname)};p(),window.addEventListener("popstate",p);const b=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(b)}},[]);const Xn=m.useCallback(async()=>{if(!(!Jt?.id||!N)){le(!0);try{const b=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${N}`}})).json();yt(b.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{le(!1)}}},[Jt?.id,N,v]);m.useEffect(()=>{Jt?.id&&N&&Xn()},[Jt?.id,N,Xn]);function Ia(p){const b=Math.floor((Date.now()-p)/1e3);return b<60?"now":b<3600?`${Math.floor(b/60)}m`:b<86400?`${Math.floor(b/3600)}h`:`${Math.floor(b/86400)}d`}function Oa(){const p=crypto.randomUUID();At(p),bn([]),gn([]),tt(!1);const b=Q?x||{}:{};et.current=b,Q||ct(b),w&&w(b),Nt.current=!1}async function La(p){if(N)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${N}`}}),yt(q.filter(b=>b._id!==p)),p===nt&&Oa()}catch(b){console.error("Failed to delete conversation:",b)}}async function Fa(p){At(p.chatId),tt(!1),le(!0);try{const b=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${L.current}`}});if(!b.ok)throw new Error(`Failed to fetch messages: ${b.statusText}`);const T=(await b.json()).messages||[];bn(T),gn(T)}catch(b){console.error("Failed to load conversation messages:",b);const E=p.messages||[];bn(E),gn(E)}finally{le(!1)}}const $a=async(p,b={})=>{const E=b.headers?new Headers(b.headers):new Headers;return E.delete("user-agent"),E.delete("User-Agent"),fetch(p,{...b,headers:E})},{messages:Zt,sendMessage:Ba,status:Bt,error:Tr,stop:vn,addToolResult:fe,setMessages:bn}=Wi.useChat({id:nt||void 0,transport:new Vn.DefaultChatTransport({api:`${v}/chat`,fetch:$a,headers:()=>{const p={};return L.current&&(p.Authorization=`Bearer ${L.current}`),p},body:()=>({tools:yn.map(b=>({name:b.name,description:b.description,inputSchema:b.jsonSchema})),systemPrompt:g,currentRoute:j,state:et.current})}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Zt[Zt.length-1];if(!p||p.role!=="assistant")return;const b=p.parts?.filter(E=>E.type?.startsWith("tool-")&&E.state==="input-available"&&typeof E.toolCallId=="string"&&E.input!==void 0)||[];for(const E of b){const T=E,D=T.type?.replace("tool-","")||"",R=T.toolCallId;if(Xe.has(D)){if(Ke.has(R))continue;Yt(B=>B.has(R)?B:new Set(B).add(R)),(async()=>{try{const B=xn.get(D);if(!B){console.warn(`[ArctenAgent] Tool ${D} not found in toolsMap. Available tools:`,Array.from(xn.keys())),fe({toolCallId:R,tool:D,output:`Error: Tool ${D} not found`}),Yt(W=>{const Tt=new Set(W);return Tt.delete(R),Tt});return}const G=ds(T.input),H=yn.find(W=>W.name===D);let _;if(H&&H.jsonSchema?.properties){const Tt=Object.keys(H.jsonSchema.properties).map(wn=>G[wn]);console.log(`[ArctenAgent] Executing safe tool ${D} with args:`,Tt),_=await B(...Tt)}else if(D==="getState")_=B();else if(D==="setState"){const W=G.updates||G;_=await B(W)}else _=await B(...Object.values(G));console.log(`[ArctenAgent] Tool ${D} completed, result:`,_),fe({toolCallId:R,tool:D,output:_}),Yt(W=>{const Tt=new Set(W);return Tt.delete(R),Tt})}catch(B){console.error(`[ArctenAgent] Error executing safe tool ${D}:`,B),fe({toolCallId:R,tool:D,output:`Error: ${B instanceof Error?B.message:String(B)}`}),Yt(G=>{const H=new Set(G);return H.delete(R),H})}})()}}},[Zt,Xe,xn,yn,fe]),m.useEffect(()=>{if(!nt||!L.current)return;(async()=>{oe(!0),we(null);try{const E=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,T=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:nt},format:"json"})});if(!T.ok){if(T.status===404||T.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${T.status}), using empty state`);const H=Q?x||{}:{};et.current=H,Q||ct(H),w&&w(H),Nt.current=!0,oe(!1);return}const G=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${G}`)}const R=(await T.json())?.value||{},K=!Nt.current;let B;K?(B={...Q?x||{}:{},...R},Nt.current=!0):B=R,et.current=B,Q||ct(B),w&&w(B)}catch(b){b instanceof TypeError&&b.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",b):console.error("[ArctenAgent] Failed to fetch state:",b);const T=b instanceof Error?b:new Error(String(b));if(we(T),!Nt.current){const D=Q?x||{}:{};et.current=D,Q||ct(D),w&&w(D),Nt.current=!0}}finally{oe(!1)}})()},[nt,v,Q,x,w]),m.useEffect(()=>{vt&&Gt.current&&Gt.current.focus()},[vt,Zt]);function za(){ae(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ua(){ae(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[vt]),m.useEffect(()=>{Xt.current&&Xt.current.scrollIntoView({behavior:"smooth"})},[Zt]),m.useEffect(()=>{function p(b){b.key==="Escape"&&(Bt==="streaming"||Bt==="submitted")&&(b.preventDefault(),vn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Bt,vn]);function _a(){const p=crypto.randomUUID();At(p),bn([]),gn([]),tt(!1)}function Sr(p){if(p.preventDefault(),!Ae.trim())return;(Bt==="streaming"||Bt==="submitted")&&vn();const b=wr[Math.floor(Math.random()*wr.length)]||"Thinking...";qn(b),Ba({text:Ae}),We("")}function Wa(p){const b=p.target.value;We(b)}m.useEffect(()=>{if(!ce)return;function p(E){if(J){const T=E.clientX-wt.x,D=E.clientY-wt.y;T>=a&&T<=c&&Ft(T),D>=400&&D<=1e3&&$t(D)}else{const T=window.innerWidth-E.clientX;T>=a&&T<=c&&Ft(T)}}function b(){Ct(!1),localStorage.setItem("arcten-sidebar-width",bt.toString()),localStorage.setItem("arcten-sidebar-height",Rt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ce,bt,Rt,J,wt,a,c]);function Ka(p){p.preventDefault(),Ct(!0)}function qa(){Te(!0),Ht(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ha(){Te(!1),Ht(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ar(){Ht(!Pt),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Pt))}function Xa(p){J&&(jt(!0),Se({x:p.clientX-wt.x,y:p.clientY-wt.y}))}return m.useEffect(()=>{if(!J)return;function p(){Be(b=>{const T=window.innerWidth-50,D=window.innerHeight-50,R=50-bt,K=0,B=Math.max(R,Math.min(b.x,T)),G=Math.max(K,Math.min(b.y,D));if(B!==b.x||G!==b.y){const H={x:B,y:G};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(H)),H}return b})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[J,bt]),m.useEffect(()=>{if(!ze)return;function p(E){const T=E.clientX-Ue.x,D=E.clientY-Ue.y,R=50,K=window.innerWidth-R,B=window.innerHeight-R,G=R-bt,H=0,_=Math.max(G,Math.min(T,K)),W=Math.max(H,Math.min(D,B));Be({x:_,y:W})}function b(){jt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(wt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ze,Ue,wt,bt]),_e?Z?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: ",Z]})}):N?h.jsx(mu,{features:Wh,children:h.jsx(Pn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:J?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:J?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
|
|
19
|
+
To fix: Run "arcten-extract-types ." and ensure "${l}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}function Xh({toolName:t,description:e,args:n,onApprove:s,onDeny:r}){const o=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})}),o&&h.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,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:[i,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),h.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[h.jsxs(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[h.jsx(dt.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),h.jsx(Nn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:h.jsx(dt.X,{className:"h-3 w-3"})})]})]})})}function Gh({toolName:t,args:e,isDenied:n,isSafe:s}){const[r,o]=m.useState(!1);if(t==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];t==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(e).filter(([l])=>!i.includes(l))),c=Object.keys(a).length>0;return h.jsxs("div",{className:"my-1",children:[h.jsxs("button",{onClick:()=>c&&o(!r),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"} ${c?"cursor-pointer hover:bg-opacity-80":""}`,children:[c&&h.jsx("span",{className:"transition-transform duration-200",children:r?h.jsx(dt.ChevronDown,{className:"h-3 w-3"}):h.jsx(dt.ChevronRight,{className:"h-3 w-3"})}),n?h.jsx(dt.X,{className:"h-3 w-3"}):s?h.jsx(dt.Zap,{className:"h-3 w-3"}):h.jsx(dt.Check,{className:"h-3 w-3"}),h.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",t]})]}),r&&c&&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(([l,u])=>h.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[h.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[l,":"]}),h.jsx("span",{className:"font-mono text-foreground",children:typeof u=="string"?u:JSON.stringify(u)})]},l))})})]})}function Yh({...t}){return h.jsx(Os.Root,{"data-slot":"collapsible",...t})}function Jh({...t}){return h.jsx(Os.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...t})}function Zh({...t}){return h.jsx(Os.CollapsibleContent,{"data-slot":"collapsible-content",...t})}const Qh=m.lazy(()=>import("streamdown").then(t=>({default:t.Streamdown}))),xr=m.memo(({className:t,...e})=>typeof window>"u"?null:h.jsx(m.Suspense,{fallback:null,children:h.jsx(Qh,{className:ht("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",t),...e})}),(t,e)=>t.children===e.children);xr.displayName="Response";const tf=Object.freeze(Object.defineProperty({__proto__:null,Response:xr},Symbol.toStringTag,{value:"Module"})),ef=({children:t,as:e="p",className:n,duration:s=2,spread:r=2})=>{const o=_h.create(e),i=m.useMemo(()=>(t?.length??0)*r,[t,r]);return h.jsx(o,{animate:{backgroundPosition:"0% center"},className:ht("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":`${i}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})},nf=m.memo(ef),Da=m.createContext(null),sf=()=>{const t=m.useContext(Da);if(!t)throw new Error("Reasoning components must be used within Reasoning");return t},rf=1e3,of=1e3,Va=m.memo(({className:t,isStreaming:e=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[c,l]=Pr.useControllableState({prop:n,defaultProp:s,onChange:r}),[u,d]=Pr.useControllableState({prop:o,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)/of)),v(null))},[e,y,d]),m.useEffect(()=>{if(s&&!e&&c&&!f){const x=setTimeout(()=>{l(!1),g(!0)},rf);return()=>clearTimeout(x)}},[e,c,s,l,f]);const C=x=>{l(x)};return h.jsx(Da.Provider,{value:{isStreaming:e,isOpen:c,setIsOpen:l,duration:u},children:h.jsx(Yh,{className:ht("not-prose mb-4",t),onOpenChange:C,open:c,...a,children:i})})}),af=(t,e)=>t||e===0?h.jsx(nf,{duration:1,children:"Thinking..."}):e===void 0?h.jsx("p",{children:"Thought for a few seconds"}):h.jsxs("p",{children:["Thought for ",e," seconds"]}),Na=m.memo(({className:t,children:e,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=sf();return h.jsx(Jh,{className:ht("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(dt.BrainIcon,{className:"size-4"}),af(s,o),h.jsx(dt.ChevronDownIcon,{className:ht("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),Ra=m.memo(({className:t,children:e,...n})=>h.jsx(Zh,{className:ht("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(xr,{className:"grid gap-2",children:e})}));Va.displayName="Reasoning";Na.displayName="ReasoningTrigger";Ra.displayName="ReasoningContent";function _i(t){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(t)}&sz=16`}function cf({sources:t,citationNumber:e,className:n}){const s=t.find(o=>o.number===e);if(!s)return null;const r=_i(s.domain);return h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsxs("button",{className:ht("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[h.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),h.jsx("span",{className:"leading-none",children:s.domain})]})}),h.jsx(ee,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:h.jsxs("div",{className:"space-y-1.5",children:[h.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",t.length]}),t.map(o=>h.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ht("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:i=>i.stopPropagation(),children:[h.jsx("img",{src:_i(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:i=>{const a=i.target;a.style.display="none"}}),h.jsx("span",{className:"text-xs flex-1 truncate",children:o.domain})]},o.number))]})})]})}function lf({text:t,citations:e,citationMap:n,referencesText:s,ResponseComponent:r,className:o,showCitations:i=!0}){const a=m.useRef(null),[c,l]=m.useState([]);m.useEffect(()=>{if(!i||!a.current||e.length===0||n.size===0){(n.size===0||!i)&&l([]);return}const d=a.current;let f,g=!1;const y=new WeakSet,v=()=>{if(!a.current||g)return;g=!0;const x=a.current,w=/\[(\d+)\]/g,S=document.createTreeWalker(x,NodeFilter.SHOW_TEXT,null),P=[];let V;for(;V=S.nextNode();)if(V.nodeType===Node.TEXT_NODE&&!y.has(V)){const k=V,N=k.textContent||"";let $=k.parentElement,L=!1;for(;$&&$!==x;){if($.tagName==="A"||$.tagName==="CODE"||$.tagName==="PRE"){L=!0;break}$=$.parentElement}if(!L){const Y=Array.from(N.matchAll(w)).filter(mt=>{if(!mt[1])return!1;const Vt=parseInt(mt[1],10);return n.has(Vt)});Y.length>0&&P.push({node:k,matches:Y})}}if(P.length===0){g=!1;return}const I=[];P.forEach(({node:k,matches:N})=>{y.add(k);const $=k.textContent||"",L=document.createDocumentFragment();let Z=0;N.forEach(Y=>{if(!Y[1])return;Y.index!==void 0&&Y.index>Z&&L.appendChild(document.createTextNode($.slice(Z,Y.index)));const mt=document.createElement("span");mt.className="inline-flex items-center citation-button-container";const Vt=parseInt(Y[1],10);mt.setAttribute("data-citation",Y[1]),L.appendChild(mt),I.push({element:mt,citationNum:Vt}),Z=(Y.index||0)+Y[0].length}),Z<$.length&&L.appendChild(document.createTextNode($.slice(Z))),k.parentNode&&k.parentNode.replaceChild(L,k)}),I.length>0&&l(k=>{const N=new Set(k.map(Z=>Z.element)),$=k.filter(Z=>Z.element.isConnected),L=I.filter(Z=>!N.has(Z.element));return[...$,...L]}),g=!1},C=new MutationObserver(()=>{clearTimeout(f),f=setTimeout(v,100)});return C.observe(d,{childList:!0,subtree:!0,characterData:!0}),f=setTimeout(v,200),()=>{C.disconnect(),clearTimeout(f)}},[t,e,n,i]);const u=i&&s?h.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[h.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-2",children:"References"}),h.jsx("div",{className:"text-xs text-stone-600 dark:text-stone-400 space-y-1",children:Array.from(n.entries()).sort(([d],[f])=>d-f).map(([d,f])=>h.jsxs("div",{className:"flex items-start gap-2",children:[h.jsxs("span",{className:"font-medium",children:["[",d,"]"]}),h.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:underline break-all",children:f})]},d))})]}):null;return h.jsxs("div",{className:o,children:[h.jsx("div",{ref:a,children:h.jsx(r,{children:t})}),i&&c.filter(({element:d})=>d.isConnected).map(({element:d,citationNum:f},g)=>e.find(v=>v.number===f)?oc.createPortal(h.jsx(cf,{sources:e.map(v=>({number:v.number,url:v.url,domain:uf(v.url)})),citationNumber:f},`citation-${f}-${d}`),d,`citation-${f}-${g}`):null),u]})}function uf(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function df(t){let e=t.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=e.match(n),r=new Map,o=[];if(s&&s[1]){const g=s[1],y=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let v;for(;(v=y.exec(g))!==null;)if(v[1]&&v[2]){const C=parseInt(v[1],10),x=v[2].replace(/[.,;:!?]+$/,"");r.set(C,x),o.push({number:C,url:x})}}let i,a=e;s&&s[0]&&(i=s[0],a=e.replace(n,""));const c=[];let l=0;const u=/```[\s\S]*?```|`[^`]+`/g;let d;for(;(d=u.exec(a))!==null;)d.index>l&&c.push({type:"text",content:a.slice(l,d.index),start:l,end:d.index}),c.push({type:"code",content:d[0],start:d.index,end:d.index+d[0].length}),l=d.index+d[0].length;return l<a.length&&c.push({type:"text",content:a.slice(l),start:l,end:a.length}),{processedText:c.map(g=>{if(g.type==="code")return g.content;let y=g.content;return y=y.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(C,x,w)=>{const S=parseInt(x,10);return r.has(S)||(r.set(S,w),o.push({number:S,url:w})),`[${S}]`}),y}).join(""),citations:o.sort((g,y)=>g.number-y.number),citationMap:r,referencesText:i}}function en(t){if(typeof t=="string")try{const e=JSON.parse(t);return en(e)}catch{return t}if(Array.isArray(t))return t.map(en);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=en(s);return e}return t}function ds(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return en(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?en(t):{}}function hf({theme:t="auto",layout:e="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:c=800,initiallyExpanded:l=!1,tools:u=[],safeTools:d=[],toolMetadata:f,systemPrompt:g="",tokenEndpoint:y="/api/arcten/token",apiBaseUrl:v="https://api.arcten.com",user:C,state:x,onStateChange:w,allowStateEdits:S=!0,sources:P,ragConfig:V,showCitations:I=!0}){const k=m.useMemo(()=>V!==void 0?V:P&&P.length>0?{enabled:!0,organizationId:P[0],autoExecute:!0,filters:void 0}:{enabled:!1},[P,V]),[N,$]=m.useState(null),L=m.useRef(null),[Z,Y]=m.useState(null),[mt,Vt]=m.useState(null),gt=m.useRef(null),Q=x!==void 0,[ot,ct]=m.useState({}),et=m.useRef({});Q&&x?et.current=x:Q||(et.current=ot);const[ut,oe]=m.useState(!1),[_n,we]=m.useState(null),Nt=m.useRef(!1),[vt,ae]=m.useState(l),[bt,Ft]=m.useState(i),[Rt,$t]=m.useState(600),[ce,Ct]=m.useState(!1),[J,Te]=m.useState(!1),[Pt,Ht]=m.useState(!1),[wt,Be]=m.useState({x:100,y:100}),[ze,jt]=m.useState(!1),[Ue,Se]=m.useState({x:0,y:0}),[_e,Wn]=m.useState(!1),Xt=m.useRef(null),Gt=m.useRef(null),[Ae,We]=m.useState(""),[mn,pn]=m.useState(null),[Kn,qn]=m.useState("Thinking..."),[Ke,Yt]=m.useState(new Set),[j,A]=m.useState(""),[E,F]=m.useState([]),[z,U]=m.useState(!1),[q,yt]=m.useState([]),[nt,At]=m.useState(()=>typeof window<"u"?crypto.randomUUID():null),[X,tt]=m.useState(!1),[Ce,le]=m.useState(!1),[pf,gn]=m.useState([]),vr=m.useCallback(async(p,b=3)=>{if(!nt||!L.current)return;const M=async()=>{const D=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:nt,updates:p},format:"json"})});if(!R.ok){if(R.status===404){console.warn("[ArctenAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const K=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${K}`)}};for(let T=0;T<b;T++)try{await M(),we(null);return}catch(D){if(T===b-1){const K=D instanceof Error?D:new Error(String(D));throw we(K),console.error("Failed to sync state to Convex after retries:",D),K}await new Promise(K=>setTimeout(K,Math.pow(2,T)*100))}},[nt,v,L]),qe=m.useMemo(()=>function(){return et.current},[]),He=m.useMemo(()=>async function(b){const M={...et.current,...b};et.current=M,Q||ct(M),w&&w(M);try{await vr(b)}catch(T){throw T}},[vr,w,Q]);m.useEffect(()=>{Q&&x&&(et.current=x)},[Q,x]);const ue=m.useMemo(()=>k?.enabled?async function(b,M=20,T){if(P&&P.length>1){const K=P.map(_=>fetch(`${v}/search`,{method:"POST",headers:{"Content-Type":"application/json",...L.current?{Authorization:`Bearer ${L.current}`}:{}},body:JSON.stringify({q:b,k:Math.min(M,100),organizationId:_,...Object.keys(R).length>0?{filters:R}:{}})}).then(W=>W.ok?W.json():null)),B=await Promise.all(K),G=[];for(const _ of B)_?.candidates&&G.push(..._.candidates);G.sort((_,W)=>{const Tt=_.scores?.rerank||_.scores?.dense||0;return(W.scores?.rerank||W.scores?.dense||0)-Tt});const H=G.slice(0,M).map((_,W)=>{const Tt=_.citation||_.url;return{rank:W+1,doc_id:_.doc_id,block_id:_.block_id,url:_.url,citation:Tt,title:_.title||"Untitled",snippet:_.snippet,score:_.scores?.rerank||_.scores?.dense||0,metadata:{site:_.metadata?.site,lang:_.metadata?.lang,contentType:_.metadata?.content_type}}});return{success:!0,query:b,total:G.length,results:H,summary:`Found ${G.length} relevant results across ${P.length} source(s) for "${b}". Top result: ${H[0]?.title||"N/A"}`}}const D=k.organizationId&&k.organizationId!=="default"?k.organizationId:void 0,R={...k.filters,...T};try{const K={q:b,k:Math.min(M,100)};D&&(K.organizationId=D),Object.keys(R).length>0&&(K.filters=R);const B={"Content-Type":"application/json"};L.current&&(B.Authorization=`Bearer ${L.current}`);const G=await fetch(`${v}/search`,{method:"POST",headers:B,body:JSON.stringify(K)});if(!G.ok){const W=await G.text();return{success:!1,error:`Search failed: ${G.status} ${W}`}}const H=await G.json(),_=H.candidates.map((W,Tt)=>{const wn=W.citation||W.url;return{rank:Tt+1,doc_id:W.doc_id,block_id:W.block_id,url:W.url,citation:wn,title:W.title||"Untitled",snippet:W.snippet,score:W.scores?.rerank||W.scores?.dense||0,metadata:{site:W.metadata?.site,lang:W.metadata?.lang,contentType:W.metadata?.content_type}}});return{success:!0,query:H.query,total:H.total,results:_,summary:`Found ${H.total} relevant results for "${b}". Top result: ${_[0]?.title||"N/A"}`}}catch(K){return{success:!1,error:K instanceof Error?K.message:"Unknown error occurred"}}}:null,[V,v,L]),de=m.useMemo(()=>k?.enabled?async function(b,M){const T=k.organizationId&&k.organizationId!=="default"?k.organizationId:P&&P.length>0?P[0]:void 0;try{const D={"Content-Type":"application/json"};L.current&&(D.Authorization=`Bearer ${L.current}`);const R=await fetch(`${v}/fetch`,{method:"POST",headers:D,body:JSON.stringify({doc_id:b,block_ids:M,...T?{organizationId:T}:{}})});if(!R.ok){const B=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${B}`}}const K=await R.json();return{success:!0,blocks:K.blocks||[],fullContent:K.fullContent||"",pageUrl:K.pageUrl||"",pageTitle:K.pageTitle||"",summary:`Fetched ${K.blocks?.length||0} blocks from ${K.pageTitle||b}`}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Unknown error occurred"}}}:null,[V,v,L]),he=m.useMemo(()=>{const p=[...u,...d,qe];return(!Q||S)&&p.push(He),k?.enabled&&(ue&&p.push(ue),de&&p.push(de)),p},[u,d,qe,He,ue,de,Q,S,k]),Hn=m.useMemo(()=>Ea(he,f),[he,f]),_t=m.useMemo(()=>{const p=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}];(!Q||S)&&p.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 b=[];return k?.enabled&&b.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"]}}),[...Hn,...p,...b]},[Hn,Q,S,k]),br=m.useMemo(()=>new Set(_t.map(p=>p.name)),[_t]),yn=m.useMemo(()=>_t.filter(p=>p.name==="getState"?!0:p.name==="setState"?!Q||S:br.has(p.name)),[_t,br,Q,S]),xn=m.useMemo(()=>{const p=new Map,b=new Map(Hn.map(M=>[M.name,M]));return p.set("getState",qe),(!Q||S)&&p.set("setState",He),k?.enabled&&(ue&&p.set("searchDocs",ue),de&&p.set("fetchDocContent",de)),he.forEach(M=>{if(M===qe||M===He||M===ue||M===de)return;const T=M[zt];if(T){const R=b.get(T);if(R){p.set(R.name,M);return}}const D=_t.find(R=>R.name===M.name);D&&p.set(D.name,M)}),p},[he,_t,qe,He,ue,de,Q,S,k]),Xe=m.useMemo(()=>{const p=new Set;p.add("getState"),p.add("setState"),k?.enabled&&k.autoExecute!==!1&&(p.add("searchDocs"),p.add("fetchDocContent"));const b=new Map(_t.map(M=>[M.name,M]));return d.forEach(M=>{const T=M[zt];if(T&&b.has(T))p.add(T);else{const D=_t.find(R=>R.name===M.name);D&&p.add(D.name)}}),p},[d,_t,k]),wr=["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&&ae(JSON.parse(p));const b=localStorage.getItem("arcten-sidebar-width");b&&Ft(parseInt(b));const M=localStorage.getItem("arcten-sidebar-height");M&&$t(parseInt(M));const T=localStorage.getItem("arcten-sidebar-detached");T&&Te(JSON.parse(T));const D=localStorage.getItem("arcten-sidebar-position");if(D){const K=JSON.parse(D),B=50,G=Math.max(B-i,Math.min(K.x,window.innerWidth-B)),H=Math.max(0,Math.min(K.y,window.innerHeight-B));Be({x:G,y:H})}const R=localStorage.getItem("arcten-sidebar-minimized");R&&Ht(JSON.parse(R)),Wn(!0)}},[]);const Jt=m.useMemo(()=>C,[C?.id]);m.useEffect(()=>((async()=>{try{const b=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!b.ok)throw new Error("Failed to fetch token");const M=await b.json();$(M.clientToken),L.current=M.clientToken,Vt(M.expiresAt),Y(null)}catch(b){Y(b instanceof Error?b.message:"Failed to fetch token")}})(),()=>{gt.current&&clearTimeout(gt.current)}),[y,Jt]),m.useEffect(()=>{if(!mt)return;gt.current&&clearTimeout(gt.current);const p=Math.floor(Date.now()/1e3),b=mt-p,T=Math.max(0,b-5);return gt.current=setTimeout(async()=>{try{const D=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:Jt})});if(!D.ok)throw new Error("Failed to refresh token");const R=await D.json();$(R.clientToken),L.current=R.clientToken,Vt(R.expiresAt),Y(null)}catch(D){console.error("Token refresh failed:",D),Y(D instanceof Error?D.message:"Failed to refresh token")}},T*1e3),()=>{gt.current&&clearTimeout(gt.current)}},[mt,y,Jt]),m.useEffect(()=>{(async()=>{if(he.length!==0)try{const b=he.map(T=>({name:T.name,code:T.toString()})),M=await fetch(`${v}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:b})});if(M.ok){const T=await M.json();F(T.tools)}}catch(b){console.error("Failed to fetch tool descriptions:",b)}})()},[he]),m.useEffect(()=>{Promise.resolve().then(()=>tf).then(p=>{pn(()=>p.Response)})},[]),m.useEffect(()=>{const p=()=>{A(window.location.pathname)};p(),window.addEventListener("popstate",p);const b=setInterval(p,500);return()=>{window.removeEventListener("popstate",p),clearInterval(b)}},[]);const Xn=m.useCallback(async()=>{if(!(!Jt?.id||!N)){le(!0);try{const b=await(await fetch(`${v}/conversations`,{headers:{Authorization:`Bearer ${N}`}})).json();yt(b.conversations||[])}catch(p){console.error("Failed to fetch conversations:",p)}finally{le(!1)}}},[Jt?.id,N,v]);m.useEffect(()=>{Jt?.id&&N&&Xn()},[Jt?.id,N,Xn]);function Ia(p){const b=Math.floor((Date.now()-p)/1e3);return b<60?"now":b<3600?`${Math.floor(b/60)}m`:b<86400?`${Math.floor(b/3600)}h`:`${Math.floor(b/86400)}d`}function Oa(){const p=crypto.randomUUID();At(p),bn([]),gn([]),tt(!1);const b=Q?x||{}:{};et.current=b,Q||ct(b),w&&w(b),Nt.current=!1}async function La(p){if(N)try{await fetch(`${v}/conversations/${p}`,{method:"DELETE",headers:{Authorization:`Bearer ${N}`}}),yt(q.filter(b=>b._id!==p)),p===nt&&Oa()}catch(b){console.error("Failed to delete conversation:",b)}}async function Fa(p){At(p.chatId),tt(!1),le(!0);try{const b=await fetch(`${v}/conversations/${p.chatId}/messages`,{headers:{Authorization:`Bearer ${L.current}`}});if(!b.ok)throw new Error(`Failed to fetch messages: ${b.statusText}`);const T=(await b.json()).messages||[];bn(T),gn(T)}catch(b){console.error("Failed to load conversation messages:",b);const M=p.messages||[];bn(M),gn(M)}finally{le(!1)}}const $a=async(p,b={})=>{const M=b.headers?new Headers(b.headers):new Headers;return M.delete("user-agent"),M.delete("User-Agent"),fetch(p,{...b,headers:M})},{messages:Zt,sendMessage:Ba,status:Bt,error:Tr,stop:vn,addToolResult:fe,setMessages:bn}=Wi.useChat({id:nt||void 0,transport:new Vn.DefaultChatTransport({api:`${v}/chat`,fetch:$a,headers:()=>{const p={};return L.current&&(p.Authorization=`Bearer ${L.current}`),p},body:()=>({tools:yn.map(b=>({name:b.name,description:b.description,inputSchema:b.jsonSchema})),systemPrompt:g,currentRoute:j,state:et.current})}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{const p=Zt[Zt.length-1];if(!p||p.role!=="assistant")return;const b=p.parts?.filter(M=>M.type?.startsWith("tool-")&&M.state==="input-available"&&typeof M.toolCallId=="string"&&M.input!==void 0)||[];for(const M of b){const T=M,D=T.type?.replace("tool-","")||"",R=T.toolCallId;if(Xe.has(D)){if(Ke.has(R))continue;Yt(B=>B.has(R)?B:new Set(B).add(R)),(async()=>{try{const B=xn.get(D);if(!B){console.warn(`[ArctenAgent] Tool ${D} not found in toolsMap. Available tools:`,Array.from(xn.keys())),fe({toolCallId:R,tool:D,output:`Error: Tool ${D} not found`}),Yt(W=>{const Tt=new Set(W);return Tt.delete(R),Tt});return}const G=ds(T.input),H=yn.find(W=>W.name===D);let _;if(H&&H.jsonSchema?.properties){const Tt=Object.keys(H.jsonSchema.properties).map(wn=>G[wn]);console.log(`[ArctenAgent] Executing safe tool ${D} with args:`,Tt),_=await B(...Tt)}else if(D==="getState")_=B();else if(D==="setState"){const W=G.updates||G;_=await B(W)}else _=await B(...Object.values(G));console.log(`[ArctenAgent] Tool ${D} completed, result:`,_),fe({toolCallId:R,tool:D,output:_}),Yt(W=>{const Tt=new Set(W);return Tt.delete(R),Tt})}catch(B){console.error(`[ArctenAgent] Error executing safe tool ${D}:`,B),fe({toolCallId:R,tool:D,output:`Error: ${B instanceof Error?B.message:String(B)}`}),Yt(G=>{const H=new Set(G);return H.delete(R),H})}})()}}},[Zt,Xe,xn,yn,fe]),m.useEffect(()=>{if(!nt||!L.current)return;(async()=>{oe(!0),we(null);try{const M=`${v.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,T=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:nt},format:"json"})});if(!T.ok){if(T.status===404||T.status>=500){console.warn(`[ArctenAgent] Convex API endpoint not available (${T.status}), using empty state`);const H=Q?x||{}:{};et.current=H,Q||ct(H),w&&w(H),Nt.current=!0,oe(!1);return}const G=await T.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${T.status} ${G}`)}const R=(await T.json())?.value||{},K=!Nt.current;let B;K?(B={...Q?x||{}:{},...R},Nt.current=!0):B=R,et.current=B,Q||ct(B),w&&w(B)}catch(b){b instanceof TypeError&&b.message.includes("fetch")?console.warn("[ArctenAgent] Network error fetching state (likely Convex endpoint not available), using fallback state:",b):console.error("[ArctenAgent] Failed to fetch state:",b);const T=b instanceof Error?b:new Error(String(b));if(we(T),!Nt.current){const D=Q?x||{}:{};et.current=D,Q||ct(D),w&&w(D),Nt.current=!0}}finally{oe(!1)}})()},[nt,v,Q,x,w]),m.useEffect(()=>{vt&&Gt.current&&Gt.current.focus()},[vt,Zt]);function za(){ae(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Ua(){ae(!1),localStorage.setItem("arcten-sidebar-expanded","false")}m.useEffect(()=>{},[vt]),m.useEffect(()=>{Xt.current&&Xt.current.scrollIntoView({behavior:"smooth"})},[Zt]),m.useEffect(()=>{function p(b){b.key==="Escape"&&(Bt==="streaming"||Bt==="submitted")&&(b.preventDefault(),vn())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[Bt,vn]);function _a(){const p=crypto.randomUUID();At(p),bn([]),gn([]),tt(!1)}function Sr(p){if(p.preventDefault(),!Ae.trim())return;(Bt==="streaming"||Bt==="submitted")&&vn();const b=wr[Math.floor(Math.random()*wr.length)]||"Thinking...";qn(b),Ba({text:Ae}),We("")}function Wa(p){const b=p.target.value;We(b)}m.useEffect(()=>{if(!ce)return;function p(M){if(J){const T=M.clientX-wt.x,D=M.clientY-wt.y;T>=a&&T<=c&&Ft(T),D>=400&&D<=1e3&&$t(D)}else{const T=window.innerWidth-M.clientX;T>=a&&T<=c&&Ft(T)}}function b(){Ct(!1),localStorage.setItem("arcten-sidebar-width",bt.toString()),localStorage.setItem("arcten-sidebar-height",Rt.toString())}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ce,bt,Rt,J,wt,a,c]);function Ka(p){p.preventDefault(),Ct(!0)}function qa(){Te(!0),Ht(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ha(){Te(!1),Ht(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Ar(){Ht(!Pt),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Pt))}function Xa(p){J&&(jt(!0),Se({x:p.clientX-wt.x,y:p.clientY-wt.y}))}return m.useEffect(()=>{if(!J)return;function p(){Be(b=>{const T=window.innerWidth-50,D=window.innerHeight-50,R=50-bt,K=0,B=Math.max(R,Math.min(b.x,T)),G=Math.max(K,Math.min(b.y,D));if(B!==b.x||G!==b.y){const H={x:B,y:G};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(H)),H}return b})}return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[J,bt]),m.useEffect(()=>{if(!ze)return;function p(M){const T=M.clientX-Ue.x,D=M.clientY-Ue.y,R=50,K=window.innerWidth-R,B=window.innerHeight-R,G=R-bt,H=0,_=Math.max(G,Math.min(T,K)),W=Math.max(H,Math.min(D,B));Be({x:_,y:W})}function b(){jt(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(wt))}return window.addEventListener("mousemove",p),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)}},[ze,Ue,wt,bt]),_e?Z?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: ",Z]})}):N?h.jsx(mu,{features:Wh,children:h.jsx(Pn,{id:"arcten-sidebar","data-theme":t,"data-layout":e,"data-model":n,initial:J?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:J?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
|
|
20
20
|
${J?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
|
|
21
21
|
${vt?"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
|
${J?"border border-border":"border-l border-border"}
|
|
23
23
|
${vt?"":"w-[30px]"}
|
|
24
|
-
`,style:vt?J?{width:`${bt}px`,height:Pt?"auto":`${Rt}px`,left:`${wt.x}px`,top:`${wt.y}px`}:{width:`${bt}px`}:void 0,onClick:vt?void 0:za,children:vt?h.jsxs(h.Fragment,{children:[!J&&h.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:Ka,children:h.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),J&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Ct(!0)}}),h.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),jt(!0),Se({x:p.clientX-wt.x,y:p.clientY-wt.y})},children:h.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"})}),h.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Ct(!0)}})]}),h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${J?"cursor-move":""}`,onMouseDown:J?Xa:void 0,children:[h.jsx("h2",{className:`text-base font-semibold ${J&&Pt?"cursor-pointer":""}`,onClick:J&&Pt?p=>{p.stopPropagation(),Ar()}:void 0,children:r}),h.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:_a,"aria-label":"New chat",children:h.jsx(dt.Plus,{className:"h-4 w-4"})})}),h.jsx(ee,{children:"Start a new conversation"})]}),h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ha:qa,"aria-label":J?"Dock sidebar":"Float sidebar",children:J?h.jsx(dt.Dock,{className:"h-4 w-4"}):h.jsx(dt.PictureInPicture2,{className:"h-4 w-4"})})}),h.jsx(ee,{children:J?"Dock to sidebar":"Undock to floating window"})]}),h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ar:Ua,"aria-label":J?Pt?"Maximize":"Minimize":"Close sidebar",children:J?Pt?h.jsx(dt.Maximize2,{className:"h-4 w-4"}):h.jsx(dt.Minimize2,{className:"h-4 w-4"}):h.jsx(dt.X,{className:"h-4 w-4"})})}),h.jsx(ee,{children:J?Pt?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Pt&&h.jsxs(h.Fragment,{children:[C&&q.length>0&&h.jsxs("div",{className:`border-b border-border ${X?"flex flex-col flex-1":""}`,children:[h.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[h.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),h.jsx(Nn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{X||Xn(),tt(!X)},children:X?"Show less":"View all"})]}),h.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${X?"flex-1 overflow-y-auto":""}`,children:q.slice(0,X?void 0:3).map(p=>h.jsxs("div",{className:"group relative",children:[h.jsxs("button",{type:"button",className:ht(pe({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Fa(p),children:[h.jsx("span",{className:"text-xs truncate",children:p.title}),h.jsx("div",{className:"ml-2 flex items-center",children:h.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Ia(p.updatedAt)})})]}),h.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:b=>{b.stopPropagation(),La(p._id)},"aria-label":"Delete conversation",children:h.jsx(dt.X,{className:"h-3 w-3"})})]},p._id))})]}),h.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[h.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Zt.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&h.jsx("div",{className:"mb-6",children:o}),h.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),M.length>0&&h.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:h.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(z?M:M.slice(0,10)).map(p=>h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{We(p.sampleUsage),Gt.current?.focus()},children:p.friendlyName})}),h.jsx(ee,{children:h.jsxs("div",{className:"max-w-xs",children:[h.jsx("p",{className:"font-medium",children:p.description}),h.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[h.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&h.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[h.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),M.length>10&&!z&&h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsxs(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>U(!0),children:["+",M.length-10," more"]})}),h.jsx(ee,{children:h.jsxs("div",{className:"max-w-xs",children:[h.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),h.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:M.slice(10).map(p=>h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),h.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),h.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),z&&M.length>10&&h.jsx(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>U(!1),children:"Show less"})]})})]}):h.jsxs(h.Fragment,{children:[Zt.map(p=>{const E=p.parts.filter(T=>T.type==="text").map(T=>T.text).join("");return h.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:h.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?h.jsx(Kh,{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:E}):h.jsx("div",{className:"space-y-2",children:p.parts.map((T,D)=>{if(T.type?.startsWith("tool-")){const R=T.type?.replace("tool-","")||"",K=yn.find(H=>H.name===R),B=T.state==="input-available",G=T.state==="output-available";if(B&&Xe.has(R),B){if(Xe.has(R))return null;const H=ds(T.input);return h.jsx(Pn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:h.jsx(Xh,{toolName:R,description:K?.description||"",args:H,onApprove:async()=>{if(Ke.has(T.toolCallId))return;Yt(W=>new Set(W).add(T.toolCallId));const _=xn.get(R);if(_)try{const W=await _(...Object.values(H));fe({toolCallId:T.toolCallId,tool:R,output:W})}catch(W){fe({toolCallId:T.toolCallId,tool:R,output:`Error: ${W}`})}},onDeny:async()=>{Ke.has(T.toolCallId)||(Yt(_=>new Set(_).add(T.toolCallId)),fe({toolCallId:T.toolCallId,tool:R,output:"User denied tool execution"}))}})},`${T.toolCallId}-${D}`)}else if(G){const H=T.output==="User denied tool execution",_=ds(T.input);return h.jsx(Gh,{toolName:R,args:_,isDenied:H,isSafe:Xe.has(R)},`${T.toolCallId}-${D}`)}return null}if(T.type==="text"&&T.text&&mn){const{processedText:R,citations:K,citationMap:B,referencesText:G}=df(T.text);return h.jsx(lf,{text:R,citations:K,citationMap:B,referencesText:G,ResponseComponent:mn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:I},`${p.id}-${D}`)}return T.type==="reasoning"&&T.text?h.jsxs(Va,{className:"w-full",isStreaming:Bt==="streaming"&&D===p.parts.length-1&&p.id===Zt.at(-1)?.id,children:[h.jsx(Na,{}),h.jsx(Ra,{children:T.text})]},`${p.id}-${D}`):null})})})},p.id)}),h.jsx("div",{ref:Xt})]})}),Tr&&h.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Tr.message]}),h.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[h.jsx(fu,{mode:"wait",children:(Bt==="streaming"||Bt==="submitted")&&h.jsxs(Pn,{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:[h.jsx(Pn,{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]}}),h.jsx("p",{className:"text-xs text-muted-foreground",children:Kn})]})}),h.jsxs("form",{onSubmit:Sr,className:"relative",children:[h.jsx(Hi,{ref:Gt,value:Ae,onChange:Wa,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),Sr(p))}}),Bt==="streaming"||Bt==="submitted"?h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:vn,children:h.jsx(dt.Square,{className:"h-4 w-4"})})}),h.jsxs(ee,{children:[h.jsx(jr,{children:"Escape"})," to stop"]})]}):h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"submit",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Ae.trim(),children:h.jsx(dt.ArrowRight,{className:"h-4 w-4"})})}),h.jsxs(ee,{children:[h.jsx(jr,{children:"Enter"})," to send"]})]})]})]})]}),h.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:[h.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),h.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),h.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):h.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[h.jsx(dt.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),h.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):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.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function nn(t){if(typeof t=="string")try{const e=JSON.parse(t);return nn(e)}catch{return t}if(Array.isArray(t))return t.map(nn);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=nn(s);return e}return t}function ff(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return nn(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?nn(t):{}}function mf({apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:e="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:l=[],conversationId:u,initialState:d={},onToolCall:f,onFinish:g,sources:y,ragConfig:v,ragFilters:C}={}){const x=m.useMemo(()=>v!==void 0?v:C?{enabled:!0,filters:C}:y&&y.length>0?{enabled:!0,organizationId:y[0],filters:void 0}:{enabled:!1},[y,v,C]),[w,S]=m.useState(n||null),P=m.useRef(n||null),[V,I]=m.useState(null),[k,N]=m.useState(null),$=m.useRef(null),[L,Z]=m.useState([]),[Y,mt]=m.useState(u||(typeof window<"u"?crypto.randomUUID():null)),[Vt,gt]=m.useState(!1),[Q,ot]=m.useState(new Set),[ct,et]=m.useState(d),ut=m.useRef(d),[oe,_n]=m.useState(!1),[we,Nt]=m.useState(null),vt=m.useRef(!1),ae=m.useCallback(async(j,A=3)=>{if(!Y||!P.current)return;const M=async()=>{const z=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Y,updates:j},format:"json"})});if(!U.ok){if(U.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const q=await U.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${U.status} ${q}`)}};for(let F=0;F<A;F++)try{await M(),Nt(null);return}catch(z){if(F===A-1){const q=z instanceof Error?z:new Error(String(z));throw Nt(q),console.error("Failed to sync state to Convex after retries:",z),q}await new Promise(q=>setTimeout(q,Math.pow(2,F)*100))}},[Y,t,P]),bt=m.useMemo(()=>function(){return ut.current},[]),Ft=m.useMemo(()=>async function(A){const M={...ut.current,...A};ut.current=M,et(M);try{await ae(A)}catch(F){throw F}},[ae]),Rt=m.useMemo(()=>x?.enabled?async function(A,M=20,F){const z={...x.filters,...F};if(y&&y.length>1){const q=y.map(X=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...P.current?{Authorization:`Bearer ${P.current}`}:{}},body:JSON.stringify({q:A,k:Math.min(M,100),organizationId:X,...Object.keys(z).length>0?{filters:z}:{}})}).then(tt=>tt.ok?tt.json():null)),yt=await Promise.all(q),nt=[];for(const X of yt)X?.candidates&&nt.push(...X.candidates);nt.sort((X,tt)=>{const Ce=X.scores?.rerank||X.scores?.dense||0;return(tt.scores?.rerank||tt.scores?.dense||0)-Ce});const At=nt.slice(0,M).map((X,tt)=>{const Ce=X.citation||X.url;return{rank:tt+1,doc_id:X.doc_id,block_id:X.block_id,url:X.url,citation:Ce,title:X.title||"Untitled",snippet:X.snippet,score:X.scores?.rerank||X.scores?.dense||0,metadata:{site:X.metadata?.site,lang:X.metadata?.lang,contentType:X.metadata?.content_type}}});return{success:!0,query:A,total:nt.length,results:At,summary:`Found ${nt.length} relevant results across ${y.length} source(s) for "${A}". Top result: ${At[0]?.title||"N/A"}`}}const U=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const q={q:A,k:Math.min(M,100)};U&&(q.organizationId=U),Object.keys(z).length>0&&(q.filters=z);const yt={"Content-Type":"application/json"};P.current&&(yt.Authorization=`Bearer ${P.current}`);const nt=await fetch(`${t}/search`,{method:"POST",headers:yt,body:JSON.stringify(q)});if(!nt.ok){const tt=await nt.text();return{success:!1,error:`Search failed: ${nt.status} ${tt}`}}const At=await nt.json(),X=At.candidates.map((tt,Ce)=>{const le=tt.citation||tt.url;return{rank:Ce+1,doc_id:tt.doc_id,block_id:tt.block_id,url:tt.url,citation:le,title:tt.title||"Untitled",snippet:tt.snippet,score:tt.scores?.rerank||tt.scores?.dense||0,metadata:{site:tt.metadata?.site,lang:tt.metadata?.lang,contentType:tt.metadata?.content_type}}});return{success:!0,query:At.query,total:At.total,results:X,summary:`Found ${At.total} relevant results for "${A}". Top result: ${X[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[x,t,P]),$t=m.useMemo(()=>x?.enabled?async function(A,M){const F=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const z={"Content-Type":"application/json"};P.current&&(z.Authorization=`Bearer ${P.current}`);const U=await fetch(`${t}/fetch`,{method:"POST",headers:z,body:JSON.stringify({doc_id:A,block_ids:M,...F?{organizationId:F}:{}})});if(!U.ok){const yt=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${yt}`}}const q=await U.json();return{success:!0,blocks:q.blocks||[],fullContent:q.fullContent||"",pageUrl:q.pageUrl||"",pageTitle:q.pageTitle||"",summary:`Fetched ${q.blocks?.length||0} blocks from ${q.pageTitle||A}`}}catch(z){return{success:!1,error:z instanceof Error?z.message:"Unknown error occurred"}}}:null,[x,t,P]),ce=m.useMemo(()=>{const j=[...o,...i,bt,Ft];return x?.enabled&&(Rt&&j.push(Rt),$t&&j.push($t)),j},[o,i,bt,Ft,Rt,$t,x]),Ct=m.useMemo(()=>Ea(ce,a),[ce,a]),J=m.useMemo(()=>{const j=new Map,A=new Map(Ct.map(M=>[M.name,M]));return j.set("getState",bt),j.set("setState",Ft),x?.enabled&&(Rt&&j.set("searchDocs",Rt),$t&&j.set("fetchDocContent",$t)),ce.forEach(M=>{if(M===bt||M===Ft||M===Rt||M===$t)return;const F=M[zt];if(F){const U=A.get(F);if(U){j.set(U.name,M);return}}const z=Ct.find(U=>U.name===M.name);z&&j.set(z.name,M)}),j},[ce,Ct,bt,Ft,Rt,$t,x]),Te=m.useMemo(()=>new Set(Ct.map(j=>j.name)),[Ct]),Pt=m.useMemo(()=>{const j=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}},{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"]}}],A=[];return x?.enabled&&A.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"]}}),[...Ct,...j,...A]},[Ct,x]),Ht=m.useMemo(()=>Pt.filter(j=>j.name==="getState"||j.name==="setState"?!0:Te.has(j.name)),[Pt,Te]),wt=m.useMemo(()=>{const j=new Set;return j.add("getState"),j.add("setState"),x?.enabled&&(j.add("searchDocs"),j.add("fetchDocContent")),i.forEach(A=>{for(const[M,F]of J.entries())if(F===A){j.add(M);break}}),j},[i,J]);m.useEffect(()=>s||n?void 0:((async()=>{try{const A=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!A.ok)throw new Error("Failed to fetch token");const M=await A.json();S(M.clientToken),P.current=M.clientToken,N(M.expiresAt),I(null)}catch(A){console.error("[useAgent] Token fetch failed:",A),I(A instanceof Error?A.message:"Failed to fetch token")}})(),()=>{$.current&&clearTimeout($.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!k||s||n)return;$.current&&clearTimeout($.current);const j=Math.floor(Date.now()/1e3),A=k-j,F=Math.max(0,A-5);return $.current=setTimeout(async()=>{try{const z=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!z.ok)throw new Error("Failed to refresh token");const U=await z.json();S(U.clientToken),P.current=U.clientToken,N(U.expiresAt),I(null)}catch(z){console.error("[useAgent] Token refresh failed:",z),I(z instanceof Error?z.message:"Failed to refresh token")}},F*1e3),()=>{$.current&&clearTimeout($.current)}},[k,e,JSON.stringify(r),s,n]);const Be=async(j,A={})=>{const M=A.headers?new Headers(A.headers):new Headers;M.delete("user-agent"),M.delete("User-Agent"),console.log("[useAgent] Making request to:",j),console.log("[useAgent] Method:",A.method||"GET"),console.log("[useAgent] Has Authorization header:",M.has("Authorization")),console.log("[useAgent] Client token available:",!!P.current);try{const F=await fetch(j,{...A,headers:M});if(!F.ok){console.error("[useAgent] Request failed:",F.status,F.statusText);const z=await F.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",z)}return F}catch(F){throw console.error("[useAgent] Fetch error:",F),F}},ze=`${t}/chat`;console.log("[useAgent] Chat API URL:",ze);const{messages:jt,sendMessage:Ue,status:Se,error:_e,stop:Wn,addToolResult:Xt,setMessages:Gt}=Wi.useChat({id:Y||void 0,messages:l,transport:new Vn.DefaultChatTransport({api:ze,fetch:Be,headers:()=>{const j={};return P.current?(j.Authorization=`Bearer ${P.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),j},body:()=>{const j=Ht.map(M=>({name:M.name,description:M.description,inputSchema:M.jsonSchema})),A=j.filter(M=>M.name==="getState"||M.name==="setState").map(M=>M.name);return A.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",A),{tools:j,systemPrompt:c,state:ut.current,...C&&{ragFilters:C}}}}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{jt.forEach(j=>{j.role==="assistant"&&j.parts.forEach(A=>{if(!A.type?.startsWith("tool-")||A.state!=="input-available")return;const M=A.type.replace("tool-",""),F=A.toolCallId;if(Q.has(F))return;ot(U=>new Set(U).add(F));const z=ff(A.input);if(wt.has(M)){const U=J.get(M);U?(async()=>{try{const q=Ht.find(nt=>nt.name===M);let yt;if(q&&q.jsonSchema?.properties){const At=Object.keys(q.jsonSchema.properties).map(X=>z[X]);yt=await U(...At)}else if(M==="getState")yt=U();else if(M==="setState"){const nt=z.updates||z;yt=await U(nt)}else yt=await U(...Object.values(z));Xt({toolCallId:F,tool:M,output:yt})}catch(q){console.error(`[useAgent] Error executing tool ${M}:`,q),Xt({toolCallId:F,tool:M,output:`Error: ${q}`})}})():console.warn(`[useAgent] Tool ${M} not found in toolsMap`)}else f&&f({toolCall:{toolCallId:F,toolName:M,args:z}})})})},[jt,wt,J,f,Xt,Q,Ft,Ht]),m.useEffect(()=>{if(Se==="ready"&&jt.length>0&&g){const j=jt[jt.length-1];j&&j.role==="assistant"&&g({message:j,messages:jt,isAbort:!1,isDisconnect:!1,isError:!!_e})}},[Se,jt,_e,g]);async function Ae(){if(!(!r?.id||!w)){gt(!0);try{const A=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${w}`}})).json();Z(A.conversations||[])}catch(j){console.error("Failed to fetch conversations:",j)}finally{gt(!1)}}}m.useEffect(()=>{r?.id&&w&&Ae()},[JSON.stringify(r),w,t]),m.useEffect(()=>{if(!Y||!P.current)return;(async()=>{_n(!0),Nt(null);try{const A=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Y},format:"json"})});if(!A.ok){const q=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${q}`)}const F=(await A.json())?.value||{},z=!vt.current;let U;z?(U={...d,...F},vt.current=!0):U=F,ut.current=U,et(U)}catch(A){console.error("Failed to fetch state:",A);const M=A instanceof Error?A:new Error(String(A));Nt(M),vt.current||(ut.current=d,et(d),vt.current=!0)}finally{_n(!1)}})()},[Y,t]);async function We(j){mt(j),gt(!0);try{const A=await fetch(`${t}/conversations/${j}/messages`,{headers:{Authorization:`Bearer ${P.current}`}});if(!A.ok)throw new Error(`Failed to fetch messages: ${A.statusText}`);const F=(await A.json()).messages||[];Gt(F)}catch(A){console.error("Failed to load conversation messages:",A)}finally{gt(!1)}}async function mn(j){if(w)try{await fetch(`${t}/conversations/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${w}`}}),Z(L.filter(A=>A._id!==j)),j===Y&&pn()}catch(A){console.error("Failed to delete conversation:",A)}}function pn(){const j=crypto.randomUUID();mt(j),Gt([]),ot(new Set),ut.current=d,et(d),vt.current=!1}function Kn(j){Xt(j)}async function qn(j){const A={...ut.current,...j};ut.current=A,et(A);try{await ae(j)}catch(M){throw M}}async function Ke(){if(!r?.id||!P.current)throw new Error("User authentication required to share state");const j=`shared_${crypto.randomUUID()}`;try{return await fetch(`${t.replace("/chat","")}/convex/api/mutation`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"sharedStates:create",args:{stateId:j,state:ut.current,projectId:"default",createdBy:r.id},format:"json"})}),j}catch(A){throw console.error("Failed to share state:",A),A}}async function Yt(j){if(!P.current)throw new Error("Authentication required to import state");try{const A=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"sharedStates:getByStateId",args:{stateId:j},format:"json"})});if(!A.ok)throw new Error("Failed to fetch shared state");const F=(await A.json())?.value||{};ut.current=F,et(F)}catch(A){throw console.error("Failed to import state:",A),A}}return{id:Y,messages:jt,status:Se,error:_e,sendMessage:Ue,stop:Wn,addToolOutput:Kn,setMessages:Gt,conversations:L,loadConversation:We,deleteConversation:mn,startNewConversation:pn,isLoadingConversations:Vt,clientToken:w,tokenError:V,state:ct,setState:qn,shareState:Ke,importState:Yt,isStateLoading:oe,stateError:we}}exports.verifyToken=ac.verifyToken;exports.ARCTEN_ORIGINAL_NAME=zt;exports.ArctenAgent=hf;exports.preserveToolName=qh;exports.useAgent=mf;
|
|
24
|
+
`,style:vt?J?{width:`${bt}px`,height:Pt?"auto":`${Rt}px`,left:`${wt.x}px`,top:`${wt.y}px`}:{width:`${bt}px`}:void 0,onClick:vt?void 0:za,children:vt?h.jsxs(h.Fragment,{children:[!J&&h.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:Ka,children:h.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),J&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:p=>{p.preventDefault(),Ct(!0)}}),h.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),jt(!0),Se({x:p.clientX-wt.x,y:p.clientY-wt.y})},children:h.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"})}),h.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:p=>{p.preventDefault(),Ct(!0)}})]}),h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${J?"cursor-move":""}`,onMouseDown:J?Xa:void 0,children:[h.jsx("h2",{className:`text-base font-semibold ${J&&Pt?"cursor-pointer":""}`,onClick:J&&Pt?p=>{p.stopPropagation(),Ar()}:void 0,children:r}),h.jsxs("div",{className:"flex items-center gap-1",onClick:p=>p.stopPropagation(),children:[h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:_a,"aria-label":"New chat",children:h.jsx(dt.Plus,{className:"h-4 w-4"})})}),h.jsx(ee,{children:"Start a new conversation"})]}),h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ha:qa,"aria-label":J?"Dock sidebar":"Float sidebar",children:J?h.jsx(dt.Dock,{className:"h-4 w-4"}):h.jsx(dt.PictureInPicture2,{className:"h-4 w-4"})})}),h.jsx(ee,{children:J?"Dock to sidebar":"Undock to floating window"})]}),h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:J?Ar:Ua,"aria-label":J?Pt?"Maximize":"Minimize":"Close sidebar",children:J?Pt?h.jsx(dt.Maximize2,{className:"h-4 w-4"}):h.jsx(dt.Minimize2,{className:"h-4 w-4"}):h.jsx(dt.X,{className:"h-4 w-4"})})}),h.jsx(ee,{children:J?Pt?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Pt&&h.jsxs(h.Fragment,{children:[C&&q.length>0&&h.jsxs("div",{className:`border-b border-border ${X?"flex flex-col flex-1":""}`,children:[h.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[h.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),h.jsx(Nn,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{X||Xn(),tt(!X)},children:X?"Show less":"View all"})]}),h.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${X?"flex-1 overflow-y-auto":""}`,children:q.slice(0,X?void 0:3).map(p=>h.jsxs("div",{className:"group relative",children:[h.jsxs("button",{type:"button",className:ht(pe({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal"),onClick:()=>Fa(p),children:[h.jsx("span",{className:"text-xs truncate",children:p.title}),h.jsx("div",{className:"ml-2 flex items-center",children:h.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Ia(p.updatedAt)})})]}),h.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:b=>{b.stopPropagation(),La(p._id)},"aria-label":"Delete conversation",children:h.jsx(dt.X,{className:"h-3 w-3"})})]},p._id))})]}),h.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[h.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Zt.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&h.jsx("div",{className:"mb-6",children:o}),h.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),E.length>0&&h.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:h.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(z?E:E.slice(0,10)).map(p=>h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{We(p.sampleUsage),Gt.current?.focus()},children:p.friendlyName})}),h.jsx(ee,{children:h.jsxs("div",{className:"max-w-xs",children:[h.jsx("p",{className:"font-medium",children:p.description}),h.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[h.jsx("span",{className:"font-medium",children:"Example:"}),' "',p.sampleUsage,'"']}),p.paramCount>0&&h.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[h.jsx("span",{className:"font-medium",children:"Parameters:"})," ",p.params.join(", ")]})]})})]},p.name)),E.length>10&&!z&&h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsxs(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>U(!0),children:["+",E.length-10," more"]})}),h.jsx(ee,{children:h.jsxs("div",{className:"max-w-xs",children:[h.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),h.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:E.slice(10).map(p=>h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-xs",children:[p.friendlyName,":"]}),h.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:p.description})]},p.name))}),h.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),z&&E.length>10&&h.jsx(Gn,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>U(!1),children:"Show less"})]})})]}):h.jsxs(h.Fragment,{children:[Zt.map(p=>{const M=p.parts.filter(T=>T.type==="text").map(T=>T.text).join("");return h.jsx("div",{className:`${p.role==="user"?"flex justify-end":"w-full"}`,children:h.jsx("div",{className:`${p.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:p.role==="user"?h.jsx(Kh,{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:M}):h.jsx("div",{className:"space-y-2",children:p.parts.map((T,D)=>{if(T.type?.startsWith("tool-")){const R=T.type?.replace("tool-","")||"",K=yn.find(H=>H.name===R),B=T.state==="input-available",G=T.state==="output-available";if(B&&Xe.has(R),B){if(Xe.has(R))return null;const H=ds(T.input);return h.jsx(Pn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:h.jsx(Xh,{toolName:R,description:K?.description||"",args:H,onApprove:async()=>{if(Ke.has(T.toolCallId))return;Yt(W=>new Set(W).add(T.toolCallId));const _=xn.get(R);if(_)try{const W=await _(...Object.values(H));fe({toolCallId:T.toolCallId,tool:R,output:W})}catch(W){fe({toolCallId:T.toolCallId,tool:R,output:`Error: ${W}`})}},onDeny:async()=>{Ke.has(T.toolCallId)||(Yt(_=>new Set(_).add(T.toolCallId)),fe({toolCallId:T.toolCallId,tool:R,output:"User denied tool execution"}))}})},`${T.toolCallId}-${D}`)}else if(G){const H=T.output==="User denied tool execution",_=ds(T.input);return h.jsx(Gh,{toolName:R,args:_,isDenied:H,isSafe:Xe.has(R)},`${T.toolCallId}-${D}`)}return null}if(T.type==="text"&&T.text&&mn){const{processedText:R,citations:K,citationMap:B,referencesText:G}=df(T.text);return h.jsx(lf,{text:R,citations:K,citationMap:B,referencesText:G,ResponseComponent:mn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:I},`${p.id}-${D}`)}return T.type==="reasoning"&&T.text?h.jsxs(Va,{className:"w-full",isStreaming:Bt==="streaming"&&D===p.parts.length-1&&p.id===Zt.at(-1)?.id,children:[h.jsx(Na,{}),h.jsx(Ra,{children:T.text})]},`${p.id}-${D}`):null})})})},p.id)}),h.jsx("div",{ref:Xt})]})}),Tr&&h.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Tr.message]}),h.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[h.jsx(fu,{mode:"wait",children:(Bt==="streaming"||Bt==="submitted")&&h.jsxs(Pn,{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:[h.jsx(Pn,{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]}}),h.jsx("p",{className:"text-xs text-muted-foreground",children:Kn})]})}),h.jsxs("form",{onSubmit:Sr,className:"relative",children:[h.jsx(Hi,{ref:Gt,value:Ae,onChange:Wa,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),Sr(p))}}),Bt==="streaming"||Bt==="submitted"?h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"button",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:vn,children:h.jsx(dt.Square,{className:"h-4 w-4"})})}),h.jsxs(ee,{children:[h.jsx(jr,{children:"Escape"})," to stop"]})]}):h.jsxs(Qt,{children:[h.jsx(te,{asChild:!0,children:h.jsx("button",{type:"submit",className:ht(pe({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Ae.trim(),children:h.jsx(dt.ArrowRight,{className:"h-4 w-4"})})}),h.jsxs(ee,{children:[h.jsx(jr,{children:"Enter"})," to send"]})]})]})]})]}),h.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:[h.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),h.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),h.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):h.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[h.jsx(dt.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),h.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):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.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function nn(t){if(typeof t=="string")try{const e=JSON.parse(t);return nn(e)}catch{return t}if(Array.isArray(t))return t.map(nn);if(t&&typeof t=="object"){const e={};for(const[n,s]of Object.entries(t))e[n]=nn(s);return e}return t}function ff(t){if(typeof t=="string"){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return nn(e)}catch{}return{}}return t&&typeof t=="object"&&!Array.isArray(t)?nn(t):{}}function mf({apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:e="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],toolMetadata:a,systemPrompt:c="",initialMessages:l=[],conversationId:u,initialState:d={},onToolCall:f,onFinish:g,sources:y,ragConfig:v,ragFilters:C}={}){const x=m.useMemo(()=>v!==void 0?v:C?{enabled:!0,filters:C}:y&&y.length>0?{enabled:!0,organizationId:y[0],autoExecute:!0,filters:void 0}:{enabled:!1},[y,v,C]),[w,S]=m.useState(n||null),P=m.useRef(n||null),[V,I]=m.useState(null),[k,N]=m.useState(null),$=m.useRef(null),[L,Z]=m.useState([]),[Y,mt]=m.useState(u||(typeof window<"u"?crypto.randomUUID():null)),[Vt,gt]=m.useState(!1),[Q,ot]=m.useState(new Set),[ct,et]=m.useState(d),ut=m.useRef(d),[oe,_n]=m.useState(!1),[we,Nt]=m.useState(null),vt=m.useRef(!1),ae=m.useCallback(async(j,A=3)=>{if(!Y||!P.current)return;const E=async()=>{const z=`${t.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,U=await fetch(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Y,updates:j},format:"json"})});if(!U.ok){if(U.status===404){console.warn("[useAgent] Convex API endpoint not available (404), state changes will not be persisted");return}const q=await U.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${U.status} ${q}`)}};for(let F=0;F<A;F++)try{await E(),Nt(null);return}catch(z){if(F===A-1){const q=z instanceof Error?z:new Error(String(z));throw Nt(q),console.error("Failed to sync state to Convex after retries:",z),q}await new Promise(q=>setTimeout(q,Math.pow(2,F)*100))}},[Y,t,P]),bt=m.useMemo(()=>function(){return ut.current},[]),Ft=m.useMemo(()=>async function(A){const E={...ut.current,...A};ut.current=E,et(E);try{await ae(A)}catch(F){throw F}},[ae]),Rt=m.useMemo(()=>x?.enabled?async function(A,E=20,F){const z={...x.filters,...F};if(y&&y.length>1){const q=y.map(X=>fetch(`${t}/search`,{method:"POST",headers:{"Content-Type":"application/json",...P.current?{Authorization:`Bearer ${P.current}`}:{}},body:JSON.stringify({q:A,k:Math.min(E,100),organizationId:X,...Object.keys(z).length>0?{filters:z}:{}})}).then(tt=>tt.ok?tt.json():null)),yt=await Promise.all(q),nt=[];for(const X of yt)X?.candidates&&nt.push(...X.candidates);nt.sort((X,tt)=>{const Ce=X.scores?.rerank||X.scores?.dense||0;return(tt.scores?.rerank||tt.scores?.dense||0)-Ce});const At=nt.slice(0,E).map((X,tt)=>{const Ce=X.citation||X.url;return{rank:tt+1,doc_id:X.doc_id,block_id:X.block_id,url:X.url,citation:Ce,title:X.title||"Untitled",snippet:X.snippet,score:X.scores?.rerank||X.scores?.dense||0,metadata:{site:X.metadata?.site,lang:X.metadata?.lang,contentType:X.metadata?.content_type}}});return{success:!0,query:A,total:nt.length,results:At,summary:`Found ${nt.length} relevant results across ${y.length} source(s) for "${A}". Top result: ${At[0]?.title||"N/A"}`}}const U=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const q={q:A,k:Math.min(E,100)};U&&(q.organizationId=U),Object.keys(z).length>0&&(q.filters=z);const yt={"Content-Type":"application/json"};P.current&&(yt.Authorization=`Bearer ${P.current}`);const nt=await fetch(`${t}/search`,{method:"POST",headers:yt,body:JSON.stringify(q)});if(!nt.ok){const tt=await nt.text();return{success:!1,error:`Search failed: ${nt.status} ${tt}`}}const At=await nt.json(),X=At.candidates.map((tt,Ce)=>{const le=tt.citation||tt.url;return{rank:Ce+1,doc_id:tt.doc_id,block_id:tt.block_id,url:tt.url,citation:le,title:tt.title||"Untitled",snippet:tt.snippet,score:tt.scores?.rerank||tt.scores?.dense||0,metadata:{site:tt.metadata?.site,lang:tt.metadata?.lang,contentType:tt.metadata?.content_type}}});return{success:!0,query:At.query,total:At.total,results:X,summary:`Found ${At.total} relevant results for "${A}". Top result: ${X[0]?.title||"N/A"}`}}catch(q){return{success:!1,error:q instanceof Error?q.message:"Unknown error occurred"}}}:null,[x,t,P]),$t=m.useMemo(()=>x?.enabled?async function(A,E){const F=x.organizationId&&x.organizationId!=="default"?x.organizationId:y&&y.length>0?y[0]:void 0;try{const z={"Content-Type":"application/json"};P.current&&(z.Authorization=`Bearer ${P.current}`);const U=await fetch(`${t}/fetch`,{method:"POST",headers:z,body:JSON.stringify({doc_id:A,block_ids:E,...F?{organizationId:F}:{}})});if(!U.ok){const yt=await U.text();return{success:!1,error:`Fetch failed: ${U.status} ${yt}`}}const q=await U.json();return{success:!0,blocks:q.blocks||[],fullContent:q.fullContent||"",pageUrl:q.pageUrl||"",pageTitle:q.pageTitle||"",summary:`Fetched ${q.blocks?.length||0} blocks from ${q.pageTitle||A}`}}catch(z){return{success:!1,error:z instanceof Error?z.message:"Unknown error occurred"}}}:null,[x,t,P]),ce=m.useMemo(()=>{const j=[...o,...i,bt,Ft];return x?.enabled&&(Rt&&j.push(Rt),$t&&j.push($t)),j},[o,i,bt,Ft,Rt,$t,x]),Ct=m.useMemo(()=>Ea(ce,a),[ce,a]),J=m.useMemo(()=>{const j=new Map,A=new Map(Ct.map(E=>[E.name,E]));return j.set("getState",bt),j.set("setState",Ft),x?.enabled&&(Rt&&j.set("searchDocs",Rt),$t&&j.set("fetchDocContent",$t)),ce.forEach(E=>{if(E===bt||E===Ft||E===Rt||E===$t)return;const F=E[zt];if(F){const U=A.get(F);if(U){j.set(U.name,E);return}}const z=Ct.find(U=>U.name===E.name);z&&j.set(z.name,E)}),j},[ce,Ct,bt,Ft,Rt,$t,x]),Te=m.useMemo(()=>new Set(Ct.map(j=>j.name)),[Ct]),Pt=m.useMemo(()=>{const j=[{name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}},{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"]}}],A=[];return x?.enabled&&A.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"]}}),[...Ct,...j,...A]},[Ct,x]),Ht=m.useMemo(()=>Pt.filter(j=>j.name==="getState"||j.name==="setState"?!0:Te.has(j.name)),[Pt,Te]),wt=m.useMemo(()=>{const j=new Set;return j.add("getState"),j.add("setState"),x?.enabled&&x.autoExecute!==!1&&(j.add("searchDocs"),j.add("fetchDocContent")),i.forEach(A=>{for(const[E,F]of J.entries())if(F===A){j.add(E);break}}),j},[i,J,x]);m.useEffect(()=>s||n?void 0:((async()=>{try{const A=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!A.ok)throw new Error("Failed to fetch token");const E=await A.json();S(E.clientToken),P.current=E.clientToken,N(E.expiresAt),I(null)}catch(A){console.error("[useAgent] Token fetch failed:",A),I(A instanceof Error?A.message:"Failed to fetch token")}})(),()=>{$.current&&clearTimeout($.current)}),[e,JSON.stringify(r),s,n]),m.useEffect(()=>{if(!k||s||n)return;$.current&&clearTimeout($.current);const j=Math.floor(Date.now()/1e3),A=k-j,F=Math.max(0,A-5);return $.current=setTimeout(async()=>{try{const z=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!z.ok)throw new Error("Failed to refresh token");const U=await z.json();S(U.clientToken),P.current=U.clientToken,N(U.expiresAt),I(null)}catch(z){console.error("[useAgent] Token refresh failed:",z),I(z instanceof Error?z.message:"Failed to refresh token")}},F*1e3),()=>{$.current&&clearTimeout($.current)}},[k,e,JSON.stringify(r),s,n]);const Be=async(j,A={})=>{const E=A.headers?new Headers(A.headers):new Headers;E.delete("user-agent"),E.delete("User-Agent"),console.log("[useAgent] Making request to:",j),console.log("[useAgent] Method:",A.method||"GET"),console.log("[useAgent] Has Authorization header:",E.has("Authorization")),console.log("[useAgent] Client token available:",!!P.current);try{const F=await fetch(j,{...A,headers:E});if(!F.ok){console.error("[useAgent] Request failed:",F.status,F.statusText);const z=await F.text().catch(()=>"Unable to read error response");console.error("[useAgent] Error response:",z)}return F}catch(F){throw console.error("[useAgent] Fetch error:",F),F}},ze=`${t}/chat`;console.log("[useAgent] Chat API URL:",ze);const{messages:jt,sendMessage:Ue,status:Se,error:_e,stop:Wn,addToolResult:Xt,setMessages:Gt}=Wi.useChat({id:Y||void 0,messages:l,transport:new Vn.DefaultChatTransport({api:ze,fetch:Be,headers:()=>{const j={};return P.current?(j.Authorization=`Bearer ${P.current}`,console.log("[useAgent] Adding Authorization header with token")):console.warn("[useAgent] No client token available - request may fail"),j},body:()=>{const j=Ht.map(E=>({name:E.name,description:E.description,inputSchema:E.jsonSchema})),A=j.filter(E=>E.name==="getState"||E.name==="setState").map(E=>E.name);return A.length>0&&console.log("[useAgent] State tools included in tools list sent to AI SDK:",A),{tools:j,systemPrompt:c,state:ut.current,...C&&{ragFilters:C}}}}),sendAutomaticallyWhen:Vn.lastAssistantMessageIsCompleteWithToolCalls});m.useEffect(()=>{jt.forEach(j=>{j.role==="assistant"&&j.parts.forEach(A=>{if(!A.type?.startsWith("tool-")||A.state!=="input-available")return;const E=A.type.replace("tool-",""),F=A.toolCallId;if(Q.has(F))return;ot(U=>new Set(U).add(F));const z=ff(A.input);if(wt.has(E)){const U=J.get(E);U?(async()=>{try{const q=Ht.find(nt=>nt.name===E);let yt;if(q&&q.jsonSchema?.properties){const At=Object.keys(q.jsonSchema.properties).map(X=>z[X]);yt=await U(...At)}else if(E==="getState")yt=U();else if(E==="setState"){const nt=z.updates||z;yt=await U(nt)}else yt=await U(...Object.values(z));Xt({toolCallId:F,tool:E,output:yt})}catch(q){console.error(`[useAgent] Error executing tool ${E}:`,q),Xt({toolCallId:F,tool:E,output:`Error: ${q}`})}})():console.warn(`[useAgent] Tool ${E} not found in toolsMap`)}else f&&f({toolCall:{toolCallId:F,toolName:E,args:z}})})})},[jt,wt,J,f,Xt,Q,Ft,Ht]),m.useEffect(()=>{if(Se==="ready"&&jt.length>0&&g){const j=jt[jt.length-1];j&&j.role==="assistant"&&g({message:j,messages:jt,isAbort:!1,isDisconnect:!1,isError:!!_e})}},[Se,jt,_e,g]);async function Ae(){if(!(!r?.id||!w)){gt(!0);try{const A=await(await fetch(`${t}/conversations`,{headers:{Authorization:`Bearer ${w}`}})).json();Z(A.conversations||[])}catch(j){console.error("Failed to fetch conversations:",j)}finally{gt(!1)}}}m.useEffect(()=>{r?.id&&w&&Ae()},[JSON.stringify(r),w,t]),m.useEffect(()=>{if(!Y||!P.current)return;(async()=>{_n(!0),Nt(null);try{const A=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Y},format:"json"})});if(!A.ok){const q=await A.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${A.status} ${q}`)}const F=(await A.json())?.value||{},z=!vt.current;let U;z?(U={...d,...F},vt.current=!0):U=F,ut.current=U,et(U)}catch(A){console.error("Failed to fetch state:",A);const E=A instanceof Error?A:new Error(String(A));Nt(E),vt.current||(ut.current=d,et(d),vt.current=!0)}finally{_n(!1)}})()},[Y,t]);async function We(j){mt(j),gt(!0);try{const A=await fetch(`${t}/conversations/${j}/messages`,{headers:{Authorization:`Bearer ${P.current}`}});if(!A.ok)throw new Error(`Failed to fetch messages: ${A.statusText}`);const F=(await A.json()).messages||[];Gt(F)}catch(A){console.error("Failed to load conversation messages:",A)}finally{gt(!1)}}async function mn(j){if(w)try{await fetch(`${t}/conversations/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${w}`}}),Z(L.filter(A=>A._id!==j)),j===Y&&pn()}catch(A){console.error("Failed to delete conversation:",A)}}function pn(){const j=crypto.randomUUID();mt(j),Gt([]),ot(new Set),ut.current=d,et(d),vt.current=!1}function Kn(j){Xt(j)}async function qn(j){const A={...ut.current,...j};ut.current=A,et(A);try{await ae(j)}catch(E){throw E}}async function Ke(){if(!r?.id||!P.current)throw new Error("User authentication required to share state");const j=`shared_${crypto.randomUUID()}`;try{return await fetch(`${t.replace("/chat","")}/convex/api/mutation`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"sharedStates:create",args:{stateId:j,state:ut.current,projectId:"default",createdBy:r.id},format:"json"})}),j}catch(A){throw console.error("Failed to share state:",A),A}}async function Yt(j){if(!P.current)throw new Error("Authentication required to import state");try{const A=await fetch(`${t.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.current}`},body:JSON.stringify({path:"sharedStates:getByStateId",args:{stateId:j},format:"json"})});if(!A.ok)throw new Error("Failed to fetch shared state");const F=(await A.json())?.value||{};ut.current=F,et(F)}catch(A){throw console.error("Failed to import state:",A),A}}return{id:Y,messages:jt,status:Se,error:_e,sendMessage:Ue,stop:Wn,addToolOutput:Kn,setMessages:Gt,conversations:L,loadConversation:We,deleteConversation:mn,startNewConversation:pn,isLoadingConversations:Vt,clientToken:w,tokenError:V,state:ct,setState:qn,shareState:Ke,importState:Yt,isStateLoading:oe,stateError:we}}exports.verifyToken=ac.verifyToken;exports.ARCTEN_ORIGINAL_NAME=zt;exports.ArctenAgent=hf;exports.preserveToolName=qh;exports.useAgent=mf;
|
package/dist/index.mjs
CHANGED
|
@@ -5651,14 +5651,16 @@ function qf({
|
|
|
5651
5651
|
enabled: !0,
|
|
5652
5652
|
organizationId: P[0],
|
|
5653
5653
|
// Use first source as default
|
|
5654
|
+
autoExecute: !0,
|
|
5655
|
+
// Default to auto-execute when sources are provided
|
|
5654
5656
|
filters: void 0
|
|
5655
5657
|
// Can be extended later if needed
|
|
5656
5658
|
} : { enabled: !1 }, [P, N]), [R, B] = F(null), L = ft(null), [et, Q] = F(null), [vt, Ot] = F(null), bt = ft(null), nt = y !== void 0, [lt, dt] = F({}), rt = ft({});
|
|
5657
5659
|
nt && y ? rt.current = y : nt || (rt.current = lt);
|
|
5658
|
-
const [mt, ue] = F(!1), [Jn, Ce] = F(null), Lt = ft(!1), [St, de] = F(l), [At, Ut] = F(i), [Ft, _t] = F(600), [he, Dt] = F(!1), [tt, ke] = F(!1), [Et, Jt] = F(!1), [Pt, He] = F({ x: 100, y: 100 }), [Ge, Vt] = F(!1), [Xe, Me] = F({ x: 0, y: 0 }), [Ye, Zn] = F(!1), Zt = ft(null), Qt = ft(null), [De, qe] = F(""), [Tn, Sn] = F(null), [Qn, ts] = F("Thinking..."), [Je, te] = F(/* @__PURE__ */ new Set()), [C, S] = F(""), [
|
|
5660
|
+
const [mt, ue] = F(!1), [Jn, Ce] = F(null), Lt = ft(!1), [St, de] = F(l), [At, Ut] = F(i), [Ft, _t] = F(600), [he, Dt] = F(!1), [tt, ke] = F(!1), [Et, Jt] = F(!1), [Pt, He] = F({ x: 100, y: 100 }), [Ge, Vt] = F(!1), [Xe, Me] = F({ x: 0, y: 0 }), [Ye, Zn] = F(!1), Zt = ft(null), Qt = ft(null), [De, qe] = F(""), [Tn, Sn] = F(null), [Qn, ts] = F("Thinking..."), [Je, te] = F(/* @__PURE__ */ new Set()), [C, S] = F(""), [D, $] = F([]), [U, _] = F(!1), [G, wt] = F([]), [it, Mt] = F(() => typeof window < "u" ? crypto.randomUUID() : null), [q, st] = F(!1), [Ee, fe] = F(!1), [Of, An] = F([]), kr = un(async (f, x = 3) => {
|
|
5659
5661
|
if (!it || !L.current)
|
|
5660
5662
|
return;
|
|
5661
|
-
const
|
|
5663
|
+
const M = async () => {
|
|
5662
5664
|
const E = `${v.replace("/chat", "").replace(/\/$/, "")}/convex/api/mutation`, I = await fetch(E, {
|
|
5663
5665
|
method: "POST",
|
|
5664
5666
|
headers: {
|
|
@@ -5682,7 +5684,7 @@ function qf({
|
|
|
5682
5684
|
};
|
|
5683
5685
|
for (let w = 0; w < x; w++)
|
|
5684
5686
|
try {
|
|
5685
|
-
await
|
|
5687
|
+
await M(), Ce(null);
|
|
5686
5688
|
return;
|
|
5687
5689
|
} catch (E) {
|
|
5688
5690
|
if (w === x - 1) {
|
|
@@ -5694,8 +5696,8 @@ function qf({
|
|
|
5694
5696
|
}, [it, v, L]), Ze = Y(() => function() {
|
|
5695
5697
|
return rt.current;
|
|
5696
5698
|
}, []), Qe = Y(() => async function(x) {
|
|
5697
|
-
const
|
|
5698
|
-
rt.current =
|
|
5699
|
+
const M = { ...rt.current, ...x };
|
|
5700
|
+
rt.current = M, nt || dt(M), b && b(M);
|
|
5699
5701
|
try {
|
|
5700
5702
|
await kr(x);
|
|
5701
5703
|
} catch (w) {
|
|
@@ -5705,7 +5707,7 @@ function qf({
|
|
|
5705
5707
|
Z(() => {
|
|
5706
5708
|
nt && y && (rt.current = y);
|
|
5707
5709
|
}, [nt, y]);
|
|
5708
|
-
const me = Y(() => k?.enabled ? async function(x,
|
|
5710
|
+
const me = Y(() => k?.enabled ? async function(x, M = 20, w) {
|
|
5709
5711
|
if (P && P.length > 1) {
|
|
5710
5712
|
const H = P.map(
|
|
5711
5713
|
(W) => fetch(`${v}/search`, {
|
|
@@ -5716,7 +5718,7 @@ function qf({
|
|
|
5716
5718
|
},
|
|
5717
5719
|
body: JSON.stringify({
|
|
5718
5720
|
q: x,
|
|
5719
|
-
k: Math.min(
|
|
5721
|
+
k: Math.min(M, 100),
|
|
5720
5722
|
organizationId: W,
|
|
5721
5723
|
...Object.keys(I).length > 0 ? { filters: I } : {}
|
|
5722
5724
|
})
|
|
@@ -5728,7 +5730,7 @@ function qf({
|
|
|
5728
5730
|
const Ct = W.scores?.rerank || W.scores?.dense || 0;
|
|
5729
5731
|
return (K.scores?.rerank || K.scores?.dense || 0) - Ct;
|
|
5730
5732
|
});
|
|
5731
|
-
const X = J.slice(0,
|
|
5733
|
+
const X = J.slice(0, M).map((W, K) => {
|
|
5732
5734
|
const Ct = W.citation || W.url;
|
|
5733
5735
|
return {
|
|
5734
5736
|
rank: K + 1,
|
|
@@ -5761,7 +5763,7 @@ function qf({
|
|
|
5761
5763
|
try {
|
|
5762
5764
|
const H = {
|
|
5763
5765
|
q: x,
|
|
5764
|
-
k: Math.min(
|
|
5766
|
+
k: Math.min(M, 100)
|
|
5765
5767
|
// Cap at 100 results
|
|
5766
5768
|
};
|
|
5767
5769
|
E && (H.organizationId = E), Object.keys(I).length > 0 && (H.filters = I);
|
|
@@ -5812,7 +5814,7 @@ function qf({
|
|
|
5812
5814
|
error: H instanceof Error ? H.message : "Unknown error occurred"
|
|
5813
5815
|
};
|
|
5814
5816
|
}
|
|
5815
|
-
} : null, [N, v, L]), pe = Y(() => k?.enabled ? async function(x,
|
|
5817
|
+
} : null, [N, v, L]), pe = Y(() => k?.enabled ? async function(x, M) {
|
|
5816
5818
|
const w = k.organizationId && k.organizationId !== "default" ? k.organizationId : P && P.length > 0 ? P[0] : void 0;
|
|
5817
5819
|
try {
|
|
5818
5820
|
const E = {
|
|
@@ -5824,7 +5826,7 @@ function qf({
|
|
|
5824
5826
|
headers: E,
|
|
5825
5827
|
body: JSON.stringify({
|
|
5826
5828
|
doc_id: x,
|
|
5827
|
-
block_ids:
|
|
5829
|
+
block_ids: M,
|
|
5828
5830
|
...w ? { organizationId: w } : {}
|
|
5829
5831
|
})
|
|
5830
5832
|
});
|
|
@@ -5936,31 +5938,31 @@ function qf({
|
|
|
5936
5938
|
}
|
|
5937
5939
|
), [...es, ...f, ...x];
|
|
5938
5940
|
}, [es, nt, T, k]), Mr = Y(() => new Set(Ht.map((f) => f.name)), [Ht]), Pn = Y(() => Ht.filter((f) => f.name === "getState" ? !0 : f.name === "setState" ? !nt || T : Mr.has(f.name)), [Ht, Mr, nt, T]), Cn = Y(() => {
|
|
5939
|
-
const f = /* @__PURE__ */ new Map(), x = new Map(es.map((
|
|
5940
|
-
return f.set("getState", Ze), (!nt || T) && f.set("setState", Qe), k?.enabled && (me && f.set("searchDocs", me), pe && f.set("fetchDocContent", pe)), ge.forEach((
|
|
5941
|
-
if (
|
|
5941
|
+
const f = /* @__PURE__ */ new Map(), x = new Map(es.map((M) => [M.name, M]));
|
|
5942
|
+
return f.set("getState", Ze), (!nt || T) && f.set("setState", Qe), k?.enabled && (me && f.set("searchDocs", me), pe && f.set("fetchDocContent", pe)), ge.forEach((M) => {
|
|
5943
|
+
if (M === Ze || M === Qe || M === me || M === pe)
|
|
5942
5944
|
return;
|
|
5943
|
-
const w =
|
|
5945
|
+
const w = M[Gt];
|
|
5944
5946
|
if (w) {
|
|
5945
5947
|
const I = x.get(w);
|
|
5946
5948
|
if (I) {
|
|
5947
|
-
f.set(I.name,
|
|
5949
|
+
f.set(I.name, M);
|
|
5948
5950
|
return;
|
|
5949
5951
|
}
|
|
5950
5952
|
}
|
|
5951
|
-
const E = Ht.find((I) => I.name ===
|
|
5952
|
-
E && f.set(E.name,
|
|
5953
|
+
const E = Ht.find((I) => I.name === M.name);
|
|
5954
|
+
E && f.set(E.name, M);
|
|
5953
5955
|
}), f;
|
|
5954
5956
|
}, [ge, Ht, Ze, Qe, me, pe, nt, T, k]), tn = Y(() => {
|
|
5955
5957
|
const f = /* @__PURE__ */ new Set();
|
|
5956
|
-
f.add("getState"), f.add("setState"), k?.enabled && (f.add("searchDocs"), f.add("fetchDocContent"));
|
|
5957
|
-
const x = new Map(Ht.map((
|
|
5958
|
-
return d.forEach((
|
|
5959
|
-
const w =
|
|
5958
|
+
f.add("getState"), f.add("setState"), k?.enabled && k.autoExecute !== !1 && (f.add("searchDocs"), f.add("fetchDocContent"));
|
|
5959
|
+
const x = new Map(Ht.map((M) => [M.name, M]));
|
|
5960
|
+
return d.forEach((M) => {
|
|
5961
|
+
const w = M[Gt];
|
|
5960
5962
|
if (w && x.has(w))
|
|
5961
5963
|
f.add(w);
|
|
5962
5964
|
else {
|
|
5963
|
-
const E = Ht.find((I) => I.name ===
|
|
5965
|
+
const E = Ht.find((I) => I.name === M.name);
|
|
5964
5966
|
E && f.add(E.name);
|
|
5965
5967
|
}
|
|
5966
5968
|
}), f;
|
|
@@ -6034,8 +6036,8 @@ function qf({
|
|
|
6034
6036
|
f && de(JSON.parse(f));
|
|
6035
6037
|
const x = localStorage.getItem("arcten-sidebar-width");
|
|
6036
6038
|
x && Ut(parseInt(x));
|
|
6037
|
-
const
|
|
6038
|
-
|
|
6039
|
+
const M = localStorage.getItem("arcten-sidebar-height");
|
|
6040
|
+
M && _t(parseInt(M));
|
|
6039
6041
|
const w = localStorage.getItem("arcten-sidebar-detached");
|
|
6040
6042
|
w && ke(JSON.parse(w));
|
|
6041
6043
|
const E = localStorage.getItem("arcten-sidebar-position");
|
|
@@ -6068,8 +6070,8 @@ function qf({
|
|
|
6068
6070
|
});
|
|
6069
6071
|
if (!x.ok)
|
|
6070
6072
|
throw new Error("Failed to fetch token");
|
|
6071
|
-
const
|
|
6072
|
-
B(
|
|
6073
|
+
const M = await x.json();
|
|
6074
|
+
B(M.clientToken), L.current = M.clientToken, Ot(M.expiresAt), Q(null);
|
|
6073
6075
|
} catch (x) {
|
|
6074
6076
|
Q(x instanceof Error ? x.message : "Failed to fetch token");
|
|
6075
6077
|
}
|
|
@@ -6107,13 +6109,13 @@ function qf({
|
|
|
6107
6109
|
const x = ge.map((w) => ({
|
|
6108
6110
|
name: w.name,
|
|
6109
6111
|
code: w.toString()
|
|
6110
|
-
})),
|
|
6112
|
+
})), M = await fetch(`${v}/tools/describe`, {
|
|
6111
6113
|
method: "POST",
|
|
6112
6114
|
headers: { "Content-Type": "application/json" },
|
|
6113
6115
|
body: JSON.stringify({ tools: x })
|
|
6114
6116
|
});
|
|
6115
|
-
if (
|
|
6116
|
-
const w = await
|
|
6117
|
+
if (M.ok) {
|
|
6118
|
+
const w = await M.json();
|
|
6117
6119
|
$(w.tools);
|
|
6118
6120
|
}
|
|
6119
6121
|
} catch (x) {
|
|
@@ -6191,17 +6193,17 @@ function qf({
|
|
|
6191
6193
|
Mn(w), An(w);
|
|
6192
6194
|
} catch (x) {
|
|
6193
6195
|
console.error("Failed to load conversation messages:", x);
|
|
6194
|
-
const
|
|
6195
|
-
Mn(
|
|
6196
|
+
const M = f.messages || [];
|
|
6197
|
+
Mn(M), An(M);
|
|
6196
6198
|
} finally {
|
|
6197
6199
|
fe(!1);
|
|
6198
6200
|
}
|
|
6199
6201
|
}
|
|
6200
6202
|
const Ja = async (f, x = {}) => {
|
|
6201
|
-
const
|
|
6202
|
-
return
|
|
6203
|
+
const M = x.headers ? new Headers(x.headers) : new Headers();
|
|
6204
|
+
return M.delete("user-agent"), M.delete("User-Agent"), fetch(f, {
|
|
6203
6205
|
...x,
|
|
6204
|
-
headers:
|
|
6206
|
+
headers: M
|
|
6205
6207
|
});
|
|
6206
6208
|
}, { messages: ne, sendMessage: Za, status: Wt, error: Er, stop: kn, addToolResult: ye, setMessages: Mn } = to({
|
|
6207
6209
|
id: it || void 0,
|
|
@@ -6235,9 +6237,9 @@ function qf({
|
|
|
6235
6237
|
Z(() => {
|
|
6236
6238
|
const f = ne[ne.length - 1];
|
|
6237
6239
|
if (!f || f.role !== "assistant") return;
|
|
6238
|
-
const x = f.parts?.filter((
|
|
6239
|
-
for (const
|
|
6240
|
-
const w =
|
|
6240
|
+
const x = f.parts?.filter((M) => M.type?.startsWith("tool-") && M.state === "input-available" && typeof M.toolCallId == "string" && M.input !== void 0) || [];
|
|
6241
|
+
for (const M of x) {
|
|
6242
|
+
const w = M, E = w.type?.replace("tool-", "") || "", I = w.toolCallId;
|
|
6241
6243
|
if (tn.has(E)) {
|
|
6242
6244
|
if (Je.has(I))
|
|
6243
6245
|
continue;
|
|
@@ -6293,7 +6295,7 @@ function qf({
|
|
|
6293
6295
|
(async () => {
|
|
6294
6296
|
ue(!0), Ce(null);
|
|
6295
6297
|
try {
|
|
6296
|
-
const
|
|
6298
|
+
const M = `${v.replace("/chat", "").replace(/\/$/, "")}/convex/api/query`, w = await fetch(M, {
|
|
6297
6299
|
method: "POST",
|
|
6298
6300
|
headers: {
|
|
6299
6301
|
"Content-Type": "application/json",
|
|
@@ -6363,12 +6365,12 @@ function qf({
|
|
|
6363
6365
|
}
|
|
6364
6366
|
Z(() => {
|
|
6365
6367
|
if (!he) return;
|
|
6366
|
-
function f(
|
|
6368
|
+
function f(M) {
|
|
6367
6369
|
if (tt) {
|
|
6368
|
-
const w =
|
|
6370
|
+
const w = M.clientX - Pt.x, E = M.clientY - Pt.y;
|
|
6369
6371
|
w >= a && w <= c && Ut(w), E >= 400 && E <= 1e3 && _t(E);
|
|
6370
6372
|
} else {
|
|
6371
|
-
const w = window.innerWidth -
|
|
6373
|
+
const w = window.innerWidth - M.clientX;
|
|
6372
6374
|
w >= a && w <= c && Ut(w);
|
|
6373
6375
|
}
|
|
6374
6376
|
}
|
|
@@ -6412,8 +6414,8 @@ function qf({
|
|
|
6412
6414
|
return window.addEventListener("resize", f), () => window.removeEventListener("resize", f);
|
|
6413
6415
|
}, [tt, At]), Z(() => {
|
|
6414
6416
|
if (!Ge) return;
|
|
6415
|
-
function f(
|
|
6416
|
-
const w =
|
|
6417
|
+
function f(M) {
|
|
6418
|
+
const w = M.clientX - Xe.x, E = M.clientY - Xe.y, I = 50, H = window.innerWidth - I, z = window.innerHeight - I, J = I - At, X = 0, W = Math.max(J, Math.min(w, H)), K = Math.max(X, Math.min(E, z));
|
|
6417
6419
|
He({ x: W, y: K });
|
|
6418
6420
|
}
|
|
6419
6421
|
function x() {
|
|
@@ -6598,8 +6600,8 @@ function qf({
|
|
|
6598
6600
|
/* @__PURE__ */ m("div", { className: "flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth", children: ne.length === 0 ? /* @__PURE__ */ V("div", { className: "flex flex-col items-center justify-center h-full", children: [
|
|
6599
6601
|
o && /* @__PURE__ */ m("div", { className: "mb-6", children: o }),
|
|
6600
6602
|
/* @__PURE__ */ m("h3", { className: "text-lg font-semibold text-center mb-2", children: "How can I help you?" }),
|
|
6601
|
-
|
|
6602
|
-
(U ?
|
|
6603
|
+
D.length > 0 && /* @__PURE__ */ m("div", { className: "mt-4 px-4 max-w-md mx-auto", children: /* @__PURE__ */ V("div", { className: "flex flex-wrap gap-2 justify-center", children: [
|
|
6604
|
+
(U ? D : D.slice(0, 10)).map((f) => /* @__PURE__ */ V(se, { children: [
|
|
6603
6605
|
/* @__PURE__ */ m(re, { asChild: !0, children: /* @__PURE__ */ m(
|
|
6604
6606
|
ss,
|
|
6605
6607
|
{
|
|
@@ -6626,7 +6628,7 @@ function qf({
|
|
|
6626
6628
|
] })
|
|
6627
6629
|
] }) })
|
|
6628
6630
|
] }, f.name)),
|
|
6629
|
-
|
|
6631
|
+
D.length > 10 && !U && /* @__PURE__ */ V(se, { children: [
|
|
6630
6632
|
/* @__PURE__ */ m(re, { asChild: !0, children: /* @__PURE__ */ V(
|
|
6631
6633
|
ss,
|
|
6632
6634
|
{
|
|
@@ -6635,14 +6637,14 @@ function qf({
|
|
|
6635
6637
|
onClick: () => _(!0),
|
|
6636
6638
|
children: [
|
|
6637
6639
|
"+",
|
|
6638
|
-
|
|
6640
|
+
D.length - 10,
|
|
6639
6641
|
" more"
|
|
6640
6642
|
]
|
|
6641
6643
|
}
|
|
6642
6644
|
) }),
|
|
6643
6645
|
/* @__PURE__ */ m(ie, { children: /* @__PURE__ */ V("div", { className: "max-w-xs", children: [
|
|
6644
6646
|
/* @__PURE__ */ m("p", { className: "font-medium mb-2", children: "Additional tools:" }),
|
|
6645
|
-
/* @__PURE__ */ m("div", { className: "space-y-1 max-h-64 overflow-y-auto pr-2", children:
|
|
6647
|
+
/* @__PURE__ */ m("div", { className: "space-y-1 max-h-64 overflow-y-auto pr-2", children: D.slice(10).map((f) => /* @__PURE__ */ V("div", { children: [
|
|
6646
6648
|
/* @__PURE__ */ V("span", { className: "font-medium text-xs", children: [
|
|
6647
6649
|
f.friendlyName,
|
|
6648
6650
|
":"
|
|
@@ -6652,7 +6654,7 @@ function qf({
|
|
|
6652
6654
|
/* @__PURE__ */ m("p", { className: "text-xs text-muted-foreground mt-2 italic", children: "Click to show all tools" })
|
|
6653
6655
|
] }) })
|
|
6654
6656
|
] }),
|
|
6655
|
-
U &&
|
|
6657
|
+
U && D.length > 10 && /* @__PURE__ */ m(
|
|
6656
6658
|
ss,
|
|
6657
6659
|
{
|
|
6658
6660
|
variant: "secondary",
|
|
@@ -6664,7 +6666,7 @@ function qf({
|
|
|
6664
6666
|
] }) })
|
|
6665
6667
|
] }) : /* @__PURE__ */ V(Ve, { children: [
|
|
6666
6668
|
ne.map((f) => {
|
|
6667
|
-
const
|
|
6669
|
+
const M = f.parts.filter((w) => w.type === "text").map((w) => w.text).join("");
|
|
6668
6670
|
return /* @__PURE__ */ m(
|
|
6669
6671
|
"div",
|
|
6670
6672
|
{
|
|
@@ -6680,7 +6682,7 @@ function qf({
|
|
|
6680
6682
|
animate: { opacity: 1, filter: "blur(0px)" },
|
|
6681
6683
|
transition: { duration: 0.3, ease: "easeOut" },
|
|
6682
6684
|
className: "text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",
|
|
6683
|
-
children:
|
|
6685
|
+
children: M
|
|
6684
6686
|
}
|
|
6685
6687
|
) : /* @__PURE__ */ m("div", { className: "space-y-2", children: f.parts.map((w, E) => {
|
|
6686
6688
|
if (w.type?.startsWith("tool-")) {
|
|
@@ -6949,13 +6951,15 @@ function Jf({
|
|
|
6949
6951
|
enabled: !0,
|
|
6950
6952
|
organizationId: g[0],
|
|
6951
6953
|
// Use first source as default
|
|
6954
|
+
autoExecute: !0,
|
|
6955
|
+
// Default to auto-execute when sources are provided
|
|
6952
6956
|
filters: void 0
|
|
6953
6957
|
} : { enabled: !1 }, [g, v, A]), [b, T] = F(n || null), P = ft(n || null), [N, j] = F(null), [k, R] = F(null), B = ft(null), [L, et] = F([]), [Q, vt] = F(
|
|
6954
6958
|
u || (typeof window < "u" ? crypto.randomUUID() : null)
|
|
6955
6959
|
), [Ot, bt] = F(!1), [nt, lt] = F(/* @__PURE__ */ new Set()), [dt, rt] = F(d), mt = ft(d), [ue, Jn] = F(!1), [Ce, Lt] = F(null), St = ft(!1), de = un(async (C, S = 3) => {
|
|
6956
6960
|
if (!Q || !P.current)
|
|
6957
6961
|
return;
|
|
6958
|
-
const
|
|
6962
|
+
const D = async () => {
|
|
6959
6963
|
const U = `${t.replace("/chat", "").replace(/\/$/, "")}/convex/api/mutation`, _ = await fetch(U, {
|
|
6960
6964
|
method: "POST",
|
|
6961
6965
|
headers: {
|
|
@@ -6979,7 +6983,7 @@ function Jf({
|
|
|
6979
6983
|
};
|
|
6980
6984
|
for (let $ = 0; $ < S; $++)
|
|
6981
6985
|
try {
|
|
6982
|
-
await
|
|
6986
|
+
await D(), Lt(null);
|
|
6983
6987
|
return;
|
|
6984
6988
|
} catch (U) {
|
|
6985
6989
|
if ($ === S - 1) {
|
|
@@ -6991,14 +6995,14 @@ function Jf({
|
|
|
6991
6995
|
}, [Q, t, P]), At = Y(() => function() {
|
|
6992
6996
|
return mt.current;
|
|
6993
6997
|
}, []), Ut = Y(() => async function(S) {
|
|
6994
|
-
const
|
|
6995
|
-
mt.current =
|
|
6998
|
+
const D = { ...mt.current, ...S };
|
|
6999
|
+
mt.current = D, rt(D);
|
|
6996
7000
|
try {
|
|
6997
7001
|
await de(S);
|
|
6998
7002
|
} catch ($) {
|
|
6999
7003
|
throw $;
|
|
7000
7004
|
}
|
|
7001
|
-
}, [de]), Ft = Y(() => y?.enabled ? async function(S,
|
|
7005
|
+
}, [de]), Ft = Y(() => y?.enabled ? async function(S, D = 20, $) {
|
|
7002
7006
|
const U = {
|
|
7003
7007
|
...y.filters,
|
|
7004
7008
|
...$
|
|
@@ -7013,7 +7017,7 @@ function Jf({
|
|
|
7013
7017
|
},
|
|
7014
7018
|
body: JSON.stringify({
|
|
7015
7019
|
q: S,
|
|
7016
|
-
k: Math.min(
|
|
7020
|
+
k: Math.min(D, 100),
|
|
7017
7021
|
organizationId: q,
|
|
7018
7022
|
...Object.keys(U).length > 0 ? { filters: U } : {}
|
|
7019
7023
|
})
|
|
@@ -7025,7 +7029,7 @@ function Jf({
|
|
|
7025
7029
|
const Ee = q.scores?.rerank || q.scores?.dense || 0;
|
|
7026
7030
|
return (st.scores?.rerank || st.scores?.dense || 0) - Ee;
|
|
7027
7031
|
});
|
|
7028
|
-
const Mt = it.slice(0,
|
|
7032
|
+
const Mt = it.slice(0, D).map((q, st) => {
|
|
7029
7033
|
const Ee = q.citation || q.url;
|
|
7030
7034
|
return {
|
|
7031
7035
|
rank: st + 1,
|
|
@@ -7055,7 +7059,7 @@ function Jf({
|
|
|
7055
7059
|
try {
|
|
7056
7060
|
const G = {
|
|
7057
7061
|
q: S,
|
|
7058
|
-
k: Math.min(
|
|
7062
|
+
k: Math.min(D, 100)
|
|
7059
7063
|
};
|
|
7060
7064
|
_ && (G.organizationId = _), Object.keys(U).length > 0 && (G.filters = U);
|
|
7061
7065
|
const wt = {
|
|
@@ -7105,7 +7109,7 @@ function Jf({
|
|
|
7105
7109
|
error: G instanceof Error ? G.message : "Unknown error occurred"
|
|
7106
7110
|
};
|
|
7107
7111
|
}
|
|
7108
|
-
} : null, [y, t, P]), _t = Y(() => y?.enabled ? async function(S,
|
|
7112
|
+
} : null, [y, t, P]), _t = Y(() => y?.enabled ? async function(S, D) {
|
|
7109
7113
|
const $ = y.organizationId && y.organizationId !== "default" ? y.organizationId : g && g.length > 0 ? g[0] : void 0;
|
|
7110
7114
|
try {
|
|
7111
7115
|
const U = {
|
|
@@ -7117,7 +7121,7 @@ function Jf({
|
|
|
7117
7121
|
headers: U,
|
|
7118
7122
|
body: JSON.stringify({
|
|
7119
7123
|
doc_id: S,
|
|
7120
|
-
block_ids:
|
|
7124
|
+
block_ids: D,
|
|
7121
7125
|
...$ ? { organizationId: $ } : {}
|
|
7122
7126
|
})
|
|
7123
7127
|
});
|
|
@@ -7152,20 +7156,20 @@ function Jf({
|
|
|
7152
7156
|
];
|
|
7153
7157
|
return y?.enabled && (Ft && C.push(Ft), _t && C.push(_t)), C;
|
|
7154
7158
|
}, [o, i, At, Ut, Ft, _t, y]), Dt = Y(() => Ua(he, a), [he, a]), tt = Y(() => {
|
|
7155
|
-
const C = /* @__PURE__ */ new Map(), S = new Map(Dt.map((
|
|
7156
|
-
return C.set("getState", At), C.set("setState", Ut), y?.enabled && (Ft && C.set("searchDocs", Ft), _t && C.set("fetchDocContent", _t)), he.forEach((
|
|
7157
|
-
if (
|
|
7159
|
+
const C = /* @__PURE__ */ new Map(), S = new Map(Dt.map((D) => [D.name, D]));
|
|
7160
|
+
return C.set("getState", At), C.set("setState", Ut), y?.enabled && (Ft && C.set("searchDocs", Ft), _t && C.set("fetchDocContent", _t)), he.forEach((D) => {
|
|
7161
|
+
if (D === At || D === Ut || D === Ft || D === _t)
|
|
7158
7162
|
return;
|
|
7159
|
-
const $ =
|
|
7163
|
+
const $ = D[Gt];
|
|
7160
7164
|
if ($) {
|
|
7161
7165
|
const _ = S.get($);
|
|
7162
7166
|
if (_) {
|
|
7163
|
-
C.set(_.name,
|
|
7167
|
+
C.set(_.name, D);
|
|
7164
7168
|
return;
|
|
7165
7169
|
}
|
|
7166
7170
|
}
|
|
7167
|
-
const U = Dt.find((_) => _.name ===
|
|
7168
|
-
U && C.set(U.name,
|
|
7171
|
+
const U = Dt.find((_) => _.name === D.name);
|
|
7172
|
+
U && C.set(U.name, D);
|
|
7169
7173
|
}), C;
|
|
7170
7174
|
}, [he, Dt, At, Ut, Ft, _t, y]), ke = Y(() => new Set(Dt.map((C) => C.name)), [Dt]), Et = Y(() => {
|
|
7171
7175
|
const C = [
|
|
@@ -7246,14 +7250,14 @@ function Jf({
|
|
|
7246
7250
|
), [...Dt, ...C, ...S];
|
|
7247
7251
|
}, [Dt, y]), Jt = Y(() => Et.filter((C) => C.name === "getState" || C.name === "setState" ? !0 : ke.has(C.name)), [Et, ke]), Pt = Y(() => {
|
|
7248
7252
|
const C = /* @__PURE__ */ new Set();
|
|
7249
|
-
return C.add("getState"), C.add("setState"), y?.enabled && (C.add("searchDocs"), C.add("fetchDocContent")), i.forEach((S) => {
|
|
7250
|
-
for (const [
|
|
7253
|
+
return C.add("getState"), C.add("setState"), y?.enabled && y.autoExecute !== !1 && (C.add("searchDocs"), C.add("fetchDocContent")), i.forEach((S) => {
|
|
7254
|
+
for (const [D, $] of tt.entries())
|
|
7251
7255
|
if ($ === S) {
|
|
7252
|
-
C.add(
|
|
7256
|
+
C.add(D);
|
|
7253
7257
|
break;
|
|
7254
7258
|
}
|
|
7255
7259
|
}), C;
|
|
7256
|
-
}, [i, tt]);
|
|
7260
|
+
}, [i, tt, y]);
|
|
7257
7261
|
Z(() => s || n ? void 0 : ((async () => {
|
|
7258
7262
|
try {
|
|
7259
7263
|
const S = await fetch(e, {
|
|
@@ -7267,8 +7271,8 @@ function Jf({
|
|
|
7267
7271
|
});
|
|
7268
7272
|
if (!S.ok)
|
|
7269
7273
|
throw new Error("Failed to fetch token");
|
|
7270
|
-
const
|
|
7271
|
-
T(
|
|
7274
|
+
const D = await S.json();
|
|
7275
|
+
T(D.clientToken), P.current = D.clientToken, R(D.expiresAt), j(null);
|
|
7272
7276
|
} catch (S) {
|
|
7273
7277
|
console.error("[useAgent] Token fetch failed:", S), j(S instanceof Error ? S.message : "Failed to fetch token");
|
|
7274
7278
|
}
|
|
@@ -7302,12 +7306,12 @@ function Jf({
|
|
|
7302
7306
|
};
|
|
7303
7307
|
}, [k, e, JSON.stringify(r), s, n]);
|
|
7304
7308
|
const He = async (C, S = {}) => {
|
|
7305
|
-
const
|
|
7306
|
-
|
|
7309
|
+
const D = S.headers ? new Headers(S.headers) : new Headers();
|
|
7310
|
+
D.delete("user-agent"), D.delete("User-Agent"), console.log("[useAgent] Making request to:", C), console.log("[useAgent] Method:", S.method || "GET"), console.log("[useAgent] Has Authorization header:", D.has("Authorization")), console.log("[useAgent] Client token available:", !!P.current);
|
|
7307
7311
|
try {
|
|
7308
7312
|
const $ = await fetch(C, {
|
|
7309
7313
|
...S,
|
|
7310
|
-
headers:
|
|
7314
|
+
headers: D
|
|
7311
7315
|
});
|
|
7312
7316
|
if (!$.ok) {
|
|
7313
7317
|
console.error("[useAgent] Request failed:", $.status, $.statusText);
|
|
@@ -7331,12 +7335,12 @@ function Jf({
|
|
|
7331
7335
|
return P.current ? (C.Authorization = `Bearer ${P.current}`, console.log("[useAgent] Adding Authorization header with token")) : console.warn("[useAgent] No client token available - request may fail"), C;
|
|
7332
7336
|
},
|
|
7333
7337
|
body: () => {
|
|
7334
|
-
const C = Jt.map((
|
|
7335
|
-
name:
|
|
7336
|
-
description:
|
|
7337
|
-
inputSchema:
|
|
7338
|
+
const C = Jt.map((D) => ({
|
|
7339
|
+
name: D.name,
|
|
7340
|
+
description: D.description,
|
|
7341
|
+
inputSchema: D.jsonSchema
|
|
7338
7342
|
// JSON Schema format from build-time
|
|
7339
|
-
})), S = C.filter((
|
|
7343
|
+
})), S = C.filter((D) => D.name === "getState" || D.name === "setState").map((D) => D.name);
|
|
7340
7344
|
return S.length > 0 && console.log("[useAgent] State tools included in tools list sent to AI SDK:", S), {
|
|
7341
7345
|
tools: C,
|
|
7342
7346
|
systemPrompt: c,
|
|
@@ -7352,42 +7356,42 @@ function Jf({
|
|
|
7352
7356
|
Vt.forEach((C) => {
|
|
7353
7357
|
C.role === "assistant" && C.parts.forEach((S) => {
|
|
7354
7358
|
if (!S.type?.startsWith("tool-") || S.state !== "input-available") return;
|
|
7355
|
-
const
|
|
7359
|
+
const D = S.type.replace("tool-", ""), $ = S.toolCallId;
|
|
7356
7360
|
if (nt.has($)) return;
|
|
7357
7361
|
lt((_) => new Set(_).add($));
|
|
7358
7362
|
const U = jf(S.input);
|
|
7359
|
-
if (Pt.has(
|
|
7360
|
-
const _ = tt.get(
|
|
7363
|
+
if (Pt.has(D)) {
|
|
7364
|
+
const _ = tt.get(D);
|
|
7361
7365
|
_ ? (async () => {
|
|
7362
7366
|
try {
|
|
7363
|
-
const G = Jt.find((it) => it.name ===
|
|
7367
|
+
const G = Jt.find((it) => it.name === D);
|
|
7364
7368
|
let wt;
|
|
7365
7369
|
if (G && G.jsonSchema?.properties) {
|
|
7366
7370
|
const Mt = Object.keys(G.jsonSchema.properties).map((q) => U[q]);
|
|
7367
7371
|
wt = await _(...Mt);
|
|
7368
|
-
} else if (
|
|
7372
|
+
} else if (D === "getState")
|
|
7369
7373
|
wt = _();
|
|
7370
|
-
else if (
|
|
7374
|
+
else if (D === "setState") {
|
|
7371
7375
|
const it = U.updates || U;
|
|
7372
7376
|
wt = await _(it);
|
|
7373
7377
|
} else
|
|
7374
7378
|
wt = await _(...Object.values(U));
|
|
7375
7379
|
Zt({
|
|
7376
7380
|
toolCallId: $,
|
|
7377
|
-
tool:
|
|
7381
|
+
tool: D,
|
|
7378
7382
|
output: wt
|
|
7379
7383
|
});
|
|
7380
7384
|
} catch (G) {
|
|
7381
|
-
console.error(`[useAgent] Error executing tool ${
|
|
7385
|
+
console.error(`[useAgent] Error executing tool ${D}:`, G), Zt({
|
|
7382
7386
|
toolCallId: $,
|
|
7383
|
-
tool:
|
|
7387
|
+
tool: D,
|
|
7384
7388
|
output: `Error: ${G}`
|
|
7385
7389
|
});
|
|
7386
7390
|
}
|
|
7387
|
-
})() : console.warn(`[useAgent] Tool ${
|
|
7391
|
+
})() : console.warn(`[useAgent] Tool ${D} not found in toolsMap`);
|
|
7388
7392
|
} else h && h({ toolCall: {
|
|
7389
7393
|
toolCallId: $,
|
|
7390
|
-
toolName:
|
|
7394
|
+
toolName: D,
|
|
7391
7395
|
args: U
|
|
7392
7396
|
} });
|
|
7393
7397
|
});
|
|
@@ -7449,8 +7453,8 @@ function Jf({
|
|
|
7449
7453
|
U ? (_ = { ...d, ...$ }, St.current = !0) : _ = $, mt.current = _, rt(_);
|
|
7450
7454
|
} catch (S) {
|
|
7451
7455
|
console.error("Failed to fetch state:", S);
|
|
7452
|
-
const
|
|
7453
|
-
Lt(
|
|
7456
|
+
const D = S instanceof Error ? S : new Error(String(S));
|
|
7457
|
+
Lt(D), St.current || (mt.current = d, rt(d), St.current = !0);
|
|
7454
7458
|
} finally {
|
|
7455
7459
|
Jn(!1);
|
|
7456
7460
|
}
|
|
@@ -7499,8 +7503,8 @@ function Jf({
|
|
|
7499
7503
|
mt.current = S, rt(S);
|
|
7500
7504
|
try {
|
|
7501
7505
|
await de(C);
|
|
7502
|
-
} catch (
|
|
7503
|
-
throw
|
|
7506
|
+
} catch (D) {
|
|
7507
|
+
throw D;
|
|
7504
7508
|
}
|
|
7505
7509
|
}
|
|
7506
7510
|
async function Je() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAgent.d.ts","sourceRoot":"","sources":["../../src/lib/useAgent.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,eAAe,EACf,cAAc,EAIf,MAAM,oBAAoB,CAAC;AAoE5B,wBAAgB,QAAQ,CAAC,EACvB,UAAqC,EACrC,aAAmC,EACnC,WAAW,EAAE,aAAa,EAC1B,cAAsB,EACtB,IAAI,EACJ,KAAU,EACV,SAAc,EACd,YAAY,EACZ,YAAiB,EACjB,eAAoB,EACpB,cAAc,EAAE,qBAAqB,EACrC,YAAiB,EACjB,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,UAAU,GACX,GAAE,eAAoB,GAAG,cAAc,
|
|
1
|
+
{"version":3,"file":"useAgent.d.ts","sourceRoot":"","sources":["../../src/lib/useAgent.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,eAAe,EACf,cAAc,EAIf,MAAM,oBAAoB,CAAC;AAoE5B,wBAAgB,QAAQ,CAAC,EACvB,UAAqC,EACrC,aAAmC,EACnC,WAAW,EAAE,aAAa,EAC1B,cAAsB,EACtB,IAAI,EACJ,KAAU,EACV,SAAc,EACd,YAAY,EACZ,YAAiB,EACjB,eAAoB,EACpB,cAAc,EAAE,qBAAqB,EACrC,YAAiB,EACjB,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,UAAU,GACX,GAAE,eAAoB,GAAG,cAAc,CAilCvC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-agent.d.ts","sourceRoot":"","sources":["../../src/types/use-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAEnD,MAAM,WAAW,QAAQ;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,SAAS,CAAC;IACnB,QAAQ,EAAE,SAAS,EAAE,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,SAAS,EAAE,CAAC;CACxB;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;KACjB,CAAC;CACH;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,IAAI,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;IAC1C,KAAK,CAAC,EAAE,YAAY,EAAE,CAAC;IACvB,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;IAC3B,YAAY,CAAC,EAAE,GAAG,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,SAAS,EAAE,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACnC,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC;IAC9C,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,UAAU,CAAC,EAAE;QACX,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;KACjB,CAAC;CACH;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAClB,QAAQ,EAAE,SAAS,EAAE,CAAC;IACtB,MAAM,EAAE,OAAO,GAAG,WAAW,GAAG,WAAW,GAAG,OAAO,CAAC;IACtD,KAAK,EAAE,KAAK,GAAG,SAAS,CAAC;IACzB,WAAW,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IACjD,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,aAAa,EAAE,CAAC,MAAM,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAE,KAAK,IAAI,CAAC;IACnF,WAAW,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC7C,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,gBAAgB,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,kBAAkB,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,oBAAoB,EAAE,MAAM,IAAI,CAAC;IACjC,sBAAsB,EAAE,OAAO,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC3B,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAClC,WAAW,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtD,cAAc,EAAE,OAAO,CAAC;IACxB,UAAU,EAAE,KAAK,GAAG,IAAI,CAAC;CAC1B"}
|
|
1
|
+
{"version":3,"file":"use-agent.d.ts","sourceRoot":"","sources":["../../src/types/use-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAEnD,MAAM,WAAW,QAAQ;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,SAAS,CAAC;IACnB,QAAQ,EAAE,SAAS,EAAE,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,SAAS,EAAE,CAAC;CACxB;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;KACjB,CAAC;CACH;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,IAAI,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;IAC1C,KAAK,CAAC,EAAE,YAAY,EAAE,CAAC;IACvB,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;IAC3B,YAAY,CAAC,EAAE,GAAG,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,SAAS,EAAE,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACnC,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC;IAC9C,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,UAAU,CAAC,EAAE;QACX,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;KACjB,CAAC;CACH;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAClB,QAAQ,EAAE,SAAS,EAAE,CAAC;IACtB,MAAM,EAAE,OAAO,GAAG,WAAW,GAAG,WAAW,GAAG,OAAO,CAAC;IACtD,KAAK,EAAE,KAAK,GAAG,SAAS,CAAC;IACzB,WAAW,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IACjD,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,aAAa,EAAE,CAAC,MAAM,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAE,KAAK,IAAI,CAAC;IACnF,WAAW,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC7C,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,gBAAgB,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,kBAAkB,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,oBAAoB,EAAE,MAAM,IAAI,CAAC;IACjC,sBAAsB,EAAE,OAAO,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC3B,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAClC,WAAW,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtD,cAAc,EAAE,OAAO,CAAC;IACxB,UAAU,EAAE,KAAK,GAAG,IAAI,CAAC;CAC1B"}
|