@cuadra-ai/uikit 0.1.10 → 0.1.13

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.
@@ -1 +1 @@
1
- {"version":3,"file":"chatModelAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/chatModelAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAuB,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAiC,MAAM,yBAAyB,CAAC;AAG1F,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACzC,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;CAC5B;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,gBAAgB,EACxB,OAAO,EAAE,uBAAuB,GAC/B,gBAAgB,CAkHlB"}
1
+ {"version":3,"file":"chatModelAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/chatModelAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAuB,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAiC,MAAM,yBAAyB,CAAC;AAG1F,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACzC,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;CAC5B;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,gBAAgB,EACxB,OAAO,EAAE,uBAAuB,GAC/B,gBAAgB,CA4GlB"}
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";var At=Object.defineProperty;var St=(e,r,t)=>r in e?At(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var re=(e,r,t)=>St(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),w=require("react"),Le=require("react-dom"),T=require("@assistant-ui/react"),ke=require("@assistant-ui/react-markdown");var fe=typeof document<"u"?document.currentScript:null;const It=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Nt=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(r,t,n)=>n?n.toUpperCase():t.toLowerCase()),Pe=e=>{const r=Nt(e);return r.charAt(0).toUpperCase()+r.slice(1)},Ve=(...e)=>e.filter((r,t,n)=>!!r&&r.trim()!==""&&n.indexOf(r)===t).join(" ").trim(),Mt=e=>{for(const r in e)if(r.startsWith("aria-")||r==="role"||r==="title")return!0};var Lt={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Pt=w.forwardRef(({color:e="currentColor",size:r=24,strokeWidth:t=2,absoluteStrokeWidth:n,className:i="",children:o,iconNode:a,...l},s)=>w.createElement("svg",{ref:s,...Lt,width:r,height:r,stroke:e,strokeWidth:n?Number(t)*24/Number(r):t,className:Ve("lucide",i),...!o&&!Mt(l)&&{"aria-hidden":"true"},...l},[...a.map(([c,f])=>w.createElement(c,f)),...Array.isArray(o)?o:[o]]));const F=(e,r)=>{const t=w.forwardRef(({className:n,...i},o)=>w.createElement(Pt,{ref:o,iconNode:r,className:Ve(`lucide-${It(Pe(e))}`,`lucide-${e}`,n),...i}));return t.displayName=Pe(e),t};const Dt=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Et=F("arrow-up",Dt);const Rt=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],_t=F("check",Rt);const Ft=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zt=F("chevron-down",Ft);const $t=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]],Ot=F("contrast",$t);const Ut=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Bt=F("copy",Ut);const Wt=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Ht=F("ellipsis-vertical",Wt);const qt=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Ge=F("loader-circle",qt);const Kt=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Vt=F("menu",Kt);const Gt=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Zt=F("plus",Gt);class Ze{constructor(r,t,n=!1){re(this,"baseUrl");re(this,"sessionToken",null);re(this,"isProxyMode",!1);this.baseUrl=r.replace(/\/$/,""),this.isProxyMode=n,t&&(this.sessionToken=t)}setSessionToken(r){this.sessionToken=r}getUrl(r){if(this.isProxyMode){const t=`${this.baseUrl}${r.replace("/v1","")}`;return t.startsWith("/")||t.startsWith("./"),t}return`${this.baseUrl}${r}`}async createOrContinueChat(r,t){const n=this.getUrl("/v1/chats"),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const a={...r,stream:!0},l=await fetch(n,{method:"POST",headers:o,body:JSON.stringify(a),signal:t});if(!l.ok){const s=await l.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${l.status} ${l.statusText}`)}if(!l.body)throw new Error("Response body is null");return l.body}async getChat(r){const t=this.getUrl(`/v1/chats/${r}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:n});if(!i.ok){const o=await i.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async listChats(r){const t=this.getUrl("/v1/chats"),n=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&n.searchParams.set("limit",r.limit.toString()),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(a=>{n.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(n.toString(),{method:"GET",headers:i});if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}generateIdempotencyKey(){try{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID()}catch{}const r=n=>Array.from({length:n},()=>Math.floor(Math.random()*16).toString(16)).join(""),t=()=>{const n=["8","9","a","b"];return n[Math.floor(Math.random()*n.length)]};return`${r(8)}-${r(4)}-4${r(3)}-${t()}${r(3)}-${r(12)}`}async updateChat(r,t){const n=`/v1/chats/${r}`,i=this.getUrl(n),o=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),l={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(l.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(o.toString(),{method:"PATCH",headers:l,body:JSON.stringify(t)});if(!s.ok){const f=await s.text();let u={};try{u=JSON.parse(f)}catch{u={detail:f}}throw new Error(u.detail||u.message||`API error: ${s.status} ${s.statusText}`)}if(s.status===204)return{};const c=await s.text();if(!c)return{};try{return JSON.parse(c)}catch{return{}}}async deleteChat(r){const t=`/v1/chats/${r}`,n=this.getUrl(t),i=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),a={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const l=await fetch(i.toString(),{method:"DELETE",headers:a});if(!l.ok){const s=await l.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${l.status} ${l.statusText}`)}}async listModels(r){const t=this.getUrl("/v1/models"),n=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&n.searchParams.set("limit",r.limit.toString()),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(a=>{n.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(n.toString(),{method:"GET",headers:i});if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}async getModel(r){const t=this.getUrl(`/v1/models/${r}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:n});if(!i.ok){const o=await i.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}}async function*Jt(e,r){const t=e.getReader(),n=new TextDecoder;let i="";try{for(;;){if(r?.aborted){t.cancel();break}const{done:o,value:a}=await t.read();if(o)break;i+=n.decode(a,{stream:!0});const l=i.split(`
2
2
 
3
- `);i=l.pop()||"";for(const s of l)if(s.startsWith("data: ")){const c=s.slice(6);if(c.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(c)}catch{}}}}finally{t.releaseLock()}}function Qt(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const n=r.content.find(i=>i.type==="text");n&&typeof n=="object"&&"text"in n&&(t=n.text)}return{role:r.role,content:t}})}function Xt(e,r){const{modelId:t,systemPrompt:n,ephemeral:i,onChatCreated:o,onUserMessage:a}=r;return{async*run(l){const{messages:s,abortSignal:c}=l;s.length>0&&s[s.length-1].role==="user"&&a?.();const u={messages:Qt(s),chatId:null,systemPrompt:n,ephemeral:i,stream:!0};t&&t.trim()!==""&&(u.modelId=t);const p=await e.createOrContinueChat(u,c);let g="",h;for await(const b of Jt(p,c)){if(c?.aborted)throw new Error("Request aborted");const x=b.id;x&&!h&&(h=x,o?.(x));const k=b.delta;if(k!=null&&(g+=k),b.type==="message"||b.content){const C=b.content||"";g+=C}if(b.message&&(g+=b.message.content||""),b.tool_calls,b.finished){g&&(yield{content:[{type:"text",text:g}]});break}g&&(yield{content:[{type:"text",text:g}]})}g&&(yield{content:[{type:"text",text:g}]})}}}const De=new Map;function Yt(e,r){return{async list(){const t=[];let i,o=0;do{const l=await e.listChats({limit:50,cursor:i}),s=l.items||[];Array.isArray(s)&&s.length>0&&t.push(...s),i=l.nextCursor||void 0,o++}while(i&&o<50);return{threads:t.map(l=>{const s=l.id;return!s||l.deletedAt?null:{status:"regular",remoteId:s,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}},async initialize(t){return{remoteId:De.get(t)||t,externalId:void 0}},async rename(t,n){await e.updateChat(t,{title:n})},async archive(t){},async unarchive(t){},async delete(t){await e.deleteChat(t)},async generateTitle(t,n){return new ReadableStream},async fetch(t){try{const n=await e.getChat(t);return{status:"regular",remoteId:n.id||t,title:n.title||"Chat",createdAt:n.createdAt?new Date(n.createdAt):new Date,updatedAt:n.updatedAt?new Date(n.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,n){De.set(t,n),r?.(t,n)}}}function er({children:e,baseUrl:r,sessionToken:t,isProxyMode:n=!1,mode:i="multiChat",modelId:o,onModelChange:a,ephemeral:l=!1,systemPrompt:s,initialThreadId:c,onError:f,onChatCreated:u,onUserMessage:p,onThreadIdUpdate:g,onChatsLoaded:h}){const b=w.useMemo(()=>new Ze(r,t||void 0,n),[r,t,n]),[x,k]=w.useState(o||null);w.useEffect(()=>{o&&k(o)},[o]);const y=w.useCallback(v=>{u?.(v)},[u]),C=w.useCallback((v,N)=>{g?.(v,N)},[g]),A=w.useMemo(()=>Xt(b,{modelId:x||void 0,systemPrompt:s,ephemeral:l,onChatCreated:y,onUserMessage:p}),[b,x,s,l,y,p]),j=T.useLocalRuntime(A);return i==="singleChat"?d.jsx(T.AssistantRuntimeProvider,{runtime:j,children:e}):d.jsx(tr,{client:b,modelAdapter:A,initialThreadId:c,onChatsLoaded:h,onThreadIdUpdate:C,onError:f,children:e})}function tr({client:e,modelAdapter:r,initialThreadId:t,onChatsLoaded:n,onThreadIdUpdate:i,onError:o,children:a}){const l=w.useMemo(()=>Yt(e,(u,p)=>{i?.(u,p)}),[e,i]),s=w.useMemo(()=>({...l,async list(){const u=await l.list();return n?.(),u}}),[l,n]);w.useEffect(()=>{window.__cuadraThreadListAdapter=s,window.__cuadraThreadListRuntime=null},[s]);const c=w.useCallback(()=>T.useLocalRuntime(r),[r]),f=T.unstable_useRemoteThreadListRuntime({adapter:s,runtimeHook:c});return w.useEffect(()=>{window.__cuadraThreadListRuntime=f},[f]),d.jsx(T.AssistantRuntimeProvider,{runtime:f,children:a})}function Ee(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let n=0,i=t.indexOf(r);for(;i!==-1;)n++,i=t.indexOf(r,i+r.length);return n}const Q=le(/[A-Za-z]/),Ce=le(/[\dA-Za-z]/);function rr(e){return e!==null&&(e<32||e===127)}function K(e){return e!==null&&e<-2}function M(e){return e!==null&&(e<0||e===32)}function R(e){return e===-2||e===-1||e===32}const se=le(/\p{P}|\p{S}/u),U=le(/\s/);function le(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function nr(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const ue=(function(e){if(e==null)return sr;if(typeof e=="function")return ce(e);if(typeof e=="object")return Array.isArray(e)?ar(e):ir(e);if(typeof e=="string")return or(e);throw new Error("Expected function, string, or object as test")});function ar(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=ue(e[t]);return ce(n);function n(...i){let o=-1;for(;++o<r.length;)if(r[o].apply(this,i))return!0;return!1}}function ir(e){const r=e;return ce(t);function t(n){const i=n;let o;for(o in e)if(i[o]!==r[o])return!1;return!0}}function or(e){return ce(r);function r(t){return t&&t.type===e}}function ce(e){return r;function r(t,n,i){return!!(lr(t)&&e.call(this,t,typeof n=="number"?n:void 0,i||void 0))}}function sr(){return!0}function lr(e){return e!==null&&typeof e=="object"&&"type"in e}const Je=[],ur=!0,we=!1,cr="skip";function Qe(e,r,t,n){let i;typeof r=="function"&&typeof t!="function"?(n=t,t=r):i=r;const o=ue(i),a=n?-1:1;l(e,void 0,[])();function l(s,c,f){const u=s&&typeof s=="object"?s:{};if(typeof u.type=="string"){const g=typeof u.tagName=="string"?u.tagName:typeof u.name=="string"?u.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(s.type+(g?"<"+g+">":""))+")"})}return p;function p(){let g=Je,h,b,x;if((!r||o(s,c,f[f.length-1]||void 0))&&(g=dr(t(s,f)),g[0]===we))return g;if("children"in s&&s.children){const k=s;if(k.children&&g[0]!==cr)for(b=(n?k.children.length:-1)+a,x=f.concat(k);b>-1&&b<k.children.length;){const y=k.children[b];if(h=l(y,b,x)(),h[0]===we)return h;b=typeof h[1]=="number"?h[1]:b+a}}return g}}}function dr(e){return Array.isArray(e)?e:typeof e=="number"?[ur,e]:e==null?Je:[e]}function fr(e,r,t){const i=ue((t||{}).ignore||[]),o=hr(r);let a=-1;for(;++a<o.length;)Qe(e,"text",l);function l(c,f){let u=-1,p;for(;++u<f.length;){const g=f[u],h=p?p.children:void 0;if(i(g,h?h.indexOf(g):void 0,p))return;p=g}if(p)return s(c,f)}function s(c,f){const u=f[f.length-1],p=o[a][0],g=o[a][1];let h=0;const x=u.children.indexOf(c);let k=!1,y=[];p.lastIndex=0;let C=p.exec(c.value);for(;C;){const A=C.index,j={index:C.index,input:C.input,stack:[...f,c]};let v=g(...C,j);if(typeof v=="string"&&(v=v.length>0?{type:"text",value:v}:void 0),v===!1?p.lastIndex=A+1:(h!==A&&y.push({type:"text",value:c.value.slice(h,A)}),Array.isArray(v)?y.push(...v):v&&y.push(v),h=A+C[0].length,k=!0),!p.global)break;C=p.exec(c.value)}return k?(h<c.value.length&&y.push({type:"text",value:c.value.slice(h)}),u.children.splice(x,1,...y)):y=[c],x+y.length}}function hr(e){const r=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const t=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<t.length;){const i=t[n];r.push([mr(i[0]),pr(i[1])])}return r}function mr(e){return typeof e=="string"?new RegExp(nr(e),"g"):e}function pr(e){return typeof e=="function"?e:function(){return e}}const he="phrasing",me=["autolink","link","image","label"];function gr(){return{transforms:[vr],enter:{literalAutolink:br,literalAutolinkEmail:pe,literalAutolinkHttp:pe,literalAutolinkWww:pe},exit:{literalAutolink:Cr,literalAutolinkEmail:yr,literalAutolinkHttp:kr,literalAutolinkWww:wr}}}function xr(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:he,notInConstruct:me},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:he,notInConstruct:me},{character:":",before:"[ps]",after:"\\/",inConstruct:he,notInConstruct:me}]}}function br(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function pe(e){this.config.enter.autolinkProtocol.call(this,e)}function kr(e){this.config.exit.autolinkProtocol.call(this,e)}function wr(e){this.config.exit.data.call(this,e);const r=this.stack[this.stack.length-1];r.type,r.url="http://"+this.sliceSerialize(e)}function yr(e){this.config.exit.autolinkEmail.call(this,e)}function Cr(e){this.exit(e)}function vr(e){fr(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,jr],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Tr]],{ignore:["link","linkReference"]})}function jr(e,r,t,n,i){let o="";if(!Xe(i)||(/^w/i.test(r)&&(t=r+t,r="",o="http://"),!Ar(t)))return!1;const a=Sr(t+n);if(!a[0])return!1;const l={type:"link",title:null,url:o+r+a[0],children:[{type:"text",value:r+a[0]}]};return a[1]?[l,{type:"text",value:a[1]}]:l}function Tr(e,r,t,n){return!Xe(n,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function Ar(e){const r=e.split(".");return!(r.length<2||r[r.length-1]&&(/_/.test(r[r.length-1])||!/[a-zA-Z\d]/.test(r[r.length-1]))||r[r.length-2]&&(/_/.test(r[r.length-2])||!/[a-zA-Z\d]/.test(r[r.length-2])))}function Sr(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],n=t.indexOf(")");const i=Ee(e,"(");let o=Ee(e,")");for(;n!==-1&&i>o;)e+=t.slice(0,n+1),t=t.slice(n+1),n=t.indexOf(")"),o++;return[e,t]}function Xe(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||U(t)||se(t))&&(!r||t!==47)}function Y(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Ye.peek=_r;function Ir(){this.buffer()}function Nr(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Mr(){this.buffer()}function Lr(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Pr(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=Y(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Dr(e){this.exit(e)}function Er(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=Y(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Rr(e){this.exit(e)}function _r(){return"["}function Ye(e,r,t,n){const i=t.createTracker(n);let o=i.move("[^");const a=t.enter("footnoteReference"),l=t.enter("reference");return o+=i.move(t.safe(t.associationId(e),{after:"]",before:o})),l(),a(),o+=i.move("]"),o}function Fr(){return{enter:{gfmFootnoteCallString:Ir,gfmFootnoteCall:Nr,gfmFootnoteDefinitionLabelString:Mr,gfmFootnoteDefinition:Lr},exit:{gfmFootnoteCallString:Pr,gfmFootnoteCall:Dr,gfmFootnoteDefinitionLabelString:Er,gfmFootnoteDefinition:Rr}}}function zr(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:Ye},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(n,i,o,a){const l=o.createTracker(a);let s=l.move("[^");const c=o.enter("footnoteDefinition"),f=o.enter("label");return s+=l.move(o.safe(o.associationId(n),{before:s,after:"]"})),f(),s+=l.move("]:"),n.children&&n.children.length>0&&(l.shift(4),s+=l.move((r?`
3
+ `);i=l.pop()||"";for(const s of l)if(s.startsWith("data: ")){const c=s.slice(6);if(c.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(c)}catch{}}}}finally{t.releaseLock()}}function Qt(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const n=r.content.find(i=>i.type==="text");n&&typeof n=="object"&&"text"in n&&(t=n.text)}return{role:r.role,content:t}})}function Xt(e,r){const{modelId:t,systemPrompt:n,ephemeral:i,onChatCreated:o,onUserMessage:a}=r;return{async*run(l){const{messages:s,abortSignal:c}=l;a?.();const u={messages:Qt(s),chatId:null,systemPrompt:n,ephemeral:i,stream:!0};t&&t.trim()!==""&&(u.modelId=t);const p=await e.createOrContinueChat(u,c);let g="",h;for await(const b of Jt(p,c)){if(c?.aborted)throw new Error("Request aborted");const x=b.id;x&&!h&&(h=x,o?.(x));const k=b.delta;if(k!=null&&(g+=k),b.type==="message"||b.content){const C=b.content||"";g+=C}if(b.message&&(g+=b.message.content||""),b.tool_calls,b.finished){g&&(yield{content:[{type:"text",text:g}]});break}g&&(yield{content:[{type:"text",text:g}]})}g&&(yield{content:[{type:"text",text:g}]})}}}const De=new Map;function Yt(e,r){return{async list(){const t=[];let i,o=0;do{const l=await e.listChats({limit:50,cursor:i}),s=l.items||[];Array.isArray(s)&&s.length>0&&t.push(...s),i=l.nextCursor||void 0,o++}while(i&&o<50);return{threads:t.map(l=>{const s=l.id;return!s||l.deletedAt?null:{status:"regular",remoteId:s,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}},async initialize(t){return{remoteId:De.get(t)||t,externalId:void 0}},async rename(t,n){await e.updateChat(t,{title:n})},async archive(t){},async unarchive(t){},async delete(t){await e.deleteChat(t)},async generateTitle(t,n){return new ReadableStream},async fetch(t){try{const n=await e.getChat(t);return{status:"regular",remoteId:n.id||t,title:n.title||"Chat",createdAt:n.createdAt?new Date(n.createdAt):new Date,updatedAt:n.updatedAt?new Date(n.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,n){De.set(t,n),r?.(t,n)}}}function er({children:e,baseUrl:r,sessionToken:t,isProxyMode:n=!1,mode:i="multiChat",modelId:o,onModelChange:a,ephemeral:l=!1,systemPrompt:s,initialThreadId:c,onError:f,onChatCreated:u,onUserMessage:p,onThreadIdUpdate:g,onChatsLoaded:h}){const b=w.useMemo(()=>new Ze(r,t||void 0,n),[r,t,n]),[x,k]=w.useState(o||null);w.useEffect(()=>{o&&k(o)},[o]);const y=w.useCallback(v=>{u?.(v)},[u]),C=w.useCallback((v,N)=>{g?.(v,N)},[g]),A=w.useMemo(()=>Xt(b,{modelId:x||void 0,systemPrompt:s,ephemeral:l,onChatCreated:y,onUserMessage:p}),[b,x,s,l,y,p]),j=T.useLocalRuntime(A);return i==="singleChat"?d.jsx(T.AssistantRuntimeProvider,{runtime:j,children:e}):d.jsx(tr,{client:b,modelAdapter:A,initialThreadId:c,onChatsLoaded:h,onThreadIdUpdate:C,onError:f,children:e})}function tr({client:e,modelAdapter:r,initialThreadId:t,onChatsLoaded:n,onThreadIdUpdate:i,onError:o,children:a}){const l=w.useMemo(()=>Yt(e,(u,p)=>{i?.(u,p)}),[e,i]),s=w.useMemo(()=>({...l,async list(){const u=await l.list();return n?.(),u}}),[l,n]);w.useEffect(()=>{window.__cuadraThreadListAdapter=s,window.__cuadraThreadListRuntime=null},[s]);const c=w.useCallback(()=>T.useLocalRuntime(r),[r]),f=T.unstable_useRemoteThreadListRuntime({adapter:s,runtimeHook:c});return w.useEffect(()=>{window.__cuadraThreadListRuntime=f},[f]),d.jsx(T.AssistantRuntimeProvider,{runtime:f,children:a})}function Ee(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let n=0,i=t.indexOf(r);for(;i!==-1;)n++,i=t.indexOf(r,i+r.length);return n}const Q=le(/[A-Za-z]/),Ce=le(/[\dA-Za-z]/);function rr(e){return e!==null&&(e<32||e===127)}function K(e){return e!==null&&e<-2}function M(e){return e!==null&&(e<0||e===32)}function R(e){return e===-2||e===-1||e===32}const se=le(/\p{P}|\p{S}/u),U=le(/\s/);function le(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function nr(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const ue=(function(e){if(e==null)return sr;if(typeof e=="function")return ce(e);if(typeof e=="object")return Array.isArray(e)?ar(e):ir(e);if(typeof e=="string")return or(e);throw new Error("Expected function, string, or object as test")});function ar(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=ue(e[t]);return ce(n);function n(...i){let o=-1;for(;++o<r.length;)if(r[o].apply(this,i))return!0;return!1}}function ir(e){const r=e;return ce(t);function t(n){const i=n;let o;for(o in e)if(i[o]!==r[o])return!1;return!0}}function or(e){return ce(r);function r(t){return t&&t.type===e}}function ce(e){return r;function r(t,n,i){return!!(lr(t)&&e.call(this,t,typeof n=="number"?n:void 0,i||void 0))}}function sr(){return!0}function lr(e){return e!==null&&typeof e=="object"&&"type"in e}const Je=[],ur=!0,we=!1,cr="skip";function Qe(e,r,t,n){let i;typeof r=="function"&&typeof t!="function"?(n=t,t=r):i=r;const o=ue(i),a=n?-1:1;l(e,void 0,[])();function l(s,c,f){const u=s&&typeof s=="object"?s:{};if(typeof u.type=="string"){const g=typeof u.tagName=="string"?u.tagName:typeof u.name=="string"?u.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(s.type+(g?"<"+g+">":""))+")"})}return p;function p(){let g=Je,h,b,x;if((!r||o(s,c,f[f.length-1]||void 0))&&(g=dr(t(s,f)),g[0]===we))return g;if("children"in s&&s.children){const k=s;if(k.children&&g[0]!==cr)for(b=(n?k.children.length:-1)+a,x=f.concat(k);b>-1&&b<k.children.length;){const y=k.children[b];if(h=l(y,b,x)(),h[0]===we)return h;b=typeof h[1]=="number"?h[1]:b+a}}return g}}}function dr(e){return Array.isArray(e)?e:typeof e=="number"?[ur,e]:e==null?Je:[e]}function fr(e,r,t){const i=ue((t||{}).ignore||[]),o=hr(r);let a=-1;for(;++a<o.length;)Qe(e,"text",l);function l(c,f){let u=-1,p;for(;++u<f.length;){const g=f[u],h=p?p.children:void 0;if(i(g,h?h.indexOf(g):void 0,p))return;p=g}if(p)return s(c,f)}function s(c,f){const u=f[f.length-1],p=o[a][0],g=o[a][1];let h=0;const x=u.children.indexOf(c);let k=!1,y=[];p.lastIndex=0;let C=p.exec(c.value);for(;C;){const A=C.index,j={index:C.index,input:C.input,stack:[...f,c]};let v=g(...C,j);if(typeof v=="string"&&(v=v.length>0?{type:"text",value:v}:void 0),v===!1?p.lastIndex=A+1:(h!==A&&y.push({type:"text",value:c.value.slice(h,A)}),Array.isArray(v)?y.push(...v):v&&y.push(v),h=A+C[0].length,k=!0),!p.global)break;C=p.exec(c.value)}return k?(h<c.value.length&&y.push({type:"text",value:c.value.slice(h)}),u.children.splice(x,1,...y)):y=[c],x+y.length}}function hr(e){const r=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const t=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<t.length;){const i=t[n];r.push([mr(i[0]),pr(i[1])])}return r}function mr(e){return typeof e=="string"?new RegExp(nr(e),"g"):e}function pr(e){return typeof e=="function"?e:function(){return e}}const he="phrasing",me=["autolink","link","image","label"];function gr(){return{transforms:[vr],enter:{literalAutolink:br,literalAutolinkEmail:pe,literalAutolinkHttp:pe,literalAutolinkWww:pe},exit:{literalAutolink:Cr,literalAutolinkEmail:yr,literalAutolinkHttp:kr,literalAutolinkWww:wr}}}function xr(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:he,notInConstruct:me},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:he,notInConstruct:me},{character:":",before:"[ps]",after:"\\/",inConstruct:he,notInConstruct:me}]}}function br(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function pe(e){this.config.enter.autolinkProtocol.call(this,e)}function kr(e){this.config.exit.autolinkProtocol.call(this,e)}function wr(e){this.config.exit.data.call(this,e);const r=this.stack[this.stack.length-1];r.type,r.url="http://"+this.sliceSerialize(e)}function yr(e){this.config.exit.autolinkEmail.call(this,e)}function Cr(e){this.exit(e)}function vr(e){fr(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,jr],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Tr]],{ignore:["link","linkReference"]})}function jr(e,r,t,n,i){let o="";if(!Xe(i)||(/^w/i.test(r)&&(t=r+t,r="",o="http://"),!Ar(t)))return!1;const a=Sr(t+n);if(!a[0])return!1;const l={type:"link",title:null,url:o+r+a[0],children:[{type:"text",value:r+a[0]}]};return a[1]?[l,{type:"text",value:a[1]}]:l}function Tr(e,r,t,n){return!Xe(n,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function Ar(e){const r=e.split(".");return!(r.length<2||r[r.length-1]&&(/_/.test(r[r.length-1])||!/[a-zA-Z\d]/.test(r[r.length-1]))||r[r.length-2]&&(/_/.test(r[r.length-2])||!/[a-zA-Z\d]/.test(r[r.length-2])))}function Sr(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],n=t.indexOf(")");const i=Ee(e,"(");let o=Ee(e,")");for(;n!==-1&&i>o;)e+=t.slice(0,n+1),t=t.slice(n+1),n=t.indexOf(")"),o++;return[e,t]}function Xe(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||U(t)||se(t))&&(!r||t!==47)}function Y(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Ye.peek=_r;function Ir(){this.buffer()}function Nr(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Mr(){this.buffer()}function Lr(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Pr(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=Y(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Dr(e){this.exit(e)}function Er(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=Y(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Rr(e){this.exit(e)}function _r(){return"["}function Ye(e,r,t,n){const i=t.createTracker(n);let o=i.move("[^");const a=t.enter("footnoteReference"),l=t.enter("reference");return o+=i.move(t.safe(t.associationId(e),{after:"]",before:o})),l(),a(),o+=i.move("]"),o}function Fr(){return{enter:{gfmFootnoteCallString:Ir,gfmFootnoteCall:Nr,gfmFootnoteDefinitionLabelString:Mr,gfmFootnoteDefinition:Lr},exit:{gfmFootnoteCallString:Pr,gfmFootnoteCall:Dr,gfmFootnoteDefinitionLabelString:Er,gfmFootnoteDefinition:Rr}}}function zr(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:Ye},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(n,i,o,a){const l=o.createTracker(a);let s=l.move("[^");const c=o.enter("footnoteDefinition"),f=o.enter("label");return s+=l.move(o.safe(o.associationId(n),{before:s,after:"]"})),f(),s+=l.move("]:"),n.children&&n.children.length>0&&(l.shift(4),s+=l.move((r?`
4
4
  `:" ")+o.indentLines(o.containerFlow(n,l.current()),r?et:$r))),c(),s}}function $r(e,r,t){return r===0?e:et(e,r,t)}function et(e,r,t){return(t?"":" ")+e}const Or=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];tt.peek=qr;function Ur(){return{canContainEols:["delete"],enter:{strikethrough:Wr},exit:{strikethrough:Hr}}}function Br(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Or}],handlers:{delete:tt}}}function Wr(e){this.enter({type:"delete",children:[]},e)}function Hr(e){this.exit(e)}function tt(e,r,t,n){const i=t.createTracker(n),o=t.enter("strikethrough");let a=i.move("~~");return a+=t.containerPhrasing(e,{...i.current(),before:a,after:"~"}),a+=i.move("~~"),o(),a}function qr(){return"~"}function Kr(e){return e.length}function Vr(e,r){const t=r||{},n=(t.align||[]).concat(),i=t.stringLength||Kr,o=[],a=[],l=[],s=[];let c=0,f=-1;for(;++f<e.length;){const b=[],x=[];let k=-1;for(e[f].length>c&&(c=e[f].length);++k<e[f].length;){const y=Gr(e[f][k]);if(t.alignDelimiters!==!1){const C=i(y);x[k]=C,(s[k]===void 0||C>s[k])&&(s[k]=C)}b.push(y)}a[f]=b,l[f]=x}let u=-1;if(typeof n=="object"&&"length"in n)for(;++u<c;)o[u]=Re(n[u]);else{const b=Re(n);for(;++u<c;)o[u]=b}u=-1;const p=[],g=[];for(;++u<c;){const b=o[u];let x="",k="";b===99?(x=":",k=":"):b===108?x=":":b===114&&(k=":");let y=t.alignDelimiters===!1?1:Math.max(1,s[u]-x.length-k.length);const C=x+"-".repeat(y)+k;t.alignDelimiters!==!1&&(y=x.length+y+k.length,y>s[u]&&(s[u]=y),g[u]=y),p[u]=C}a.splice(1,0,p),l.splice(1,0,g),f=-1;const h=[];for(;++f<a.length;){const b=a[f],x=l[f];u=-1;const k=[];for(;++u<c;){const y=b[u]||"";let C="",A="";if(t.alignDelimiters!==!1){const j=s[u]-(x[u]||0),v=o[u];v===114?C=" ".repeat(j):v===99?j%2?(C=" ".repeat(j/2+.5),A=" ".repeat(j/2-.5)):(C=" ".repeat(j/2),A=C):A=" ".repeat(j)}t.delimiterStart!==!1&&!u&&k.push("|"),t.padding!==!1&&!(t.alignDelimiters===!1&&y==="")&&(t.delimiterStart!==!1||u)&&k.push(" "),t.alignDelimiters!==!1&&k.push(C),k.push(y),t.alignDelimiters!==!1&&k.push(A),t.padding!==!1&&k.push(" "),(t.delimiterEnd!==!1||u!==c-1)&&k.push("|")}h.push(t.delimiterEnd===!1?k.join("").replace(/ +$/,""):k.join(""))}return h.join(`
5
5
  `)}function Gr(e){return e==null?"":String(e)}function Re(e){const r=typeof e=="string"?e.codePointAt(0):0;return r===67||r===99?99:r===76||r===108?108:r===82||r===114?114:0}function Zr(e,r,t,n){const i=t.enter("blockquote"),o=t.createTracker(n);o.move("> "),o.shift(2);const a=t.indentLines(t.containerFlow(e,o.current()),Jr);return i(),a}function Jr(e,r,t){return">"+(t?"":" ")+e}function Qr(e,r){return _e(e,r.inConstruct,!0)&&!_e(e,r.notInConstruct,!1)}function _e(e,r,t){if(typeof r=="string"&&(r=[r]),!r||r.length===0)return t;let n=-1;for(;++n<r.length;)if(e.includes(r[n]))return!0;return!1}function Fe(e,r,t,n){let i=-1;for(;++i<t.unsafe.length;)if(t.unsafe[i].character===`
6
6
  `&&Qr(t.stack,t.unsafe[i]))return/[ \t]/.test(n.before)?"":" ";return`\\