@applica-software-guru/persona-sdk 0.1.85 → 0.1.86

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/README.md CHANGED
@@ -251,13 +251,7 @@ import { PersonaRuntimeProvider, InMemoryMessageStorage } from '@applica-softwar
251
251
 
252
252
  const storage = new InMemoryMessageStorage();
253
253
 
254
- <PersonaRuntimeProvider
255
- apiKey="your-api-key"
256
- agentId="your-agent-id"
257
- protocols={{ rest: true }}
258
- enableThreads={true}
259
- messageStorage={storage}
260
- >
254
+ <PersonaRuntimeProvider apiKey="your-api-key" agentId="your-agent-id" protocols={{ rest: true }} threads={true} messageStorage={storage}>
261
255
  {/* Your app */}
262
256
  </PersonaRuntimeProvider>;
263
257
  ```
@@ -271,13 +265,7 @@ import { PersonaRuntimeProvider, LocalStorageMessageStorage } from '@applica-sof
271
265
 
272
266
  const storage = new LocalStorageMessageStorage('my_app_messages_');
273
267
 
274
- <PersonaRuntimeProvider
275
- apiKey="your-api-key"
276
- agentId="your-agent-id"
277
- protocols={{ rest: true }}
278
- enableThreads={true}
279
- messageStorage={storage}
280
- >
268
+ <PersonaRuntimeProvider apiKey="your-api-key" agentId="your-agent-id" protocols={{ rest: true }} threads={true} messageStorage={storage}>
281
269
  {/* Your app */}
282
270
  </PersonaRuntimeProvider>;
283
271
  ```
@@ -331,7 +319,7 @@ const customStorage = new CustomMessageStorage();
331
319
 
332
320
  ### How It Works
333
321
 
334
- When thread management is enabled (`enableThreads={true}`):
322
+ When thread management is enabled (`threads={true}`):
335
323
 
336
324
  - Each thread has its own session ID
337
325
  - Messages are automatically saved to storage when updated
@@ -24,5 +24,5 @@ __p += '`),H&&(x+=`' +
24
24
  function print() { __p += __j.call(arguments, '') }
25
25
  `:`;
26
26
  `)+x+`return __p
27
- }`;var $=Ro(function(){return G(o,R+"return "+x).apply(i,a)});if($.source=x,Ui($))throw $;return $}function Rp(t){return Z(t).toLowerCase()}function Ip(t){return Z(t).toUpperCase()}function Ep(t,n,e){if(t=Z(t),t&&(e||n===i))return Fu(t);if(!t||!(n=Tt(n)))return t;var r=Zt(t),u=Zt(n),o=Nu(r,u),a=Uu(r,u)+1;return bn(r,o,a).join("")}function Tp(t,n,e){if(t=Z(t),t&&(e||n===i))return t.slice(0,Mu(t)+1);if(!t||!(n=Tt(n)))return t;var r=Zt(t),u=Uu(r,Zt(n))+1;return bn(r,0,u).join("")}function Lp(t,n,e){if(t=Z(t),t&&(e||n===i))return t.replace(Ur,"");if(!t||!(n=Tt(n)))return t;var r=Zt(t),u=Nu(r,Zt(n));return bn(r,u).join("")}function Op(t,n){var e=Re,r=Rt;if(et(n)){var u="separator"in n?n.separator:u;e="length"in n?B(n.length):e,r="omission"in n?Tt(n.omission):r}t=Z(t);var o=t.length;if(zn(t)){var a=Zt(t);o=a.length}if(e>=o)return t;var c=e-Hn(r);if(c<1)return r;var d=a?bn(a,0,c).join(""):t.slice(0,c);if(u===i)return d+r;if(a&&(c+=d.length-c),Bi(u)){if(t.slice(c).search(u)){var y,m=d;for(u.global||(u=ti(u.source,Z(ru.exec(u))+"g")),u.lastIndex=0;y=u.exec(m);)var x=y.index;d=d.slice(0,x===i?c:x)}}else if(t.indexOf(Tt(u),c)!=c){var A=d.lastIndexOf(u);A>-1&&(d=d.slice(0,A))}return d+r}function Wp(t){return t=Z(t),t&&ko.test(t)?t.replace(tu,af):t}var Dp=Vn(function(t,n,e){return t+(e?" ":"")+n.toUpperCase()}),Ki=Rs("toUpperCase");function Po(t,n,e){return t=Z(t),n=e?i:n,n===i?ef(t)?lf(t):Ja(t):t.match(n)||[]}var Ro=K(function(t,n){try{return It(t,i,n)}catch(e){return Ui(e)?e:new N(e)}}),Fp=cn(function(t,n){return Ut(n,function(e){e=en(e),an(t,e,Fi(t[e],t))}),t});function Np(t){var n=t==null?0:t.length,e=L();return t=n?nt(t,function(r){if(typeof r[1]!="function")throw new Bt(S);return[e(r[0]),r[1]]}):[],K(function(r){for(var u=-1;++u<n;){var o=t[u];if(It(o[0],this,r))return It(o[1],this,r)}})}function Up(t){return ac($t(t,P))}function qi(t){return function(){return t}}function Bp(t,n){return t==null||t!==t?n:t}var Mp=Es(),$p=Es(!0);function Ct(t){return t}function ki(t){return us(typeof t=="function"?t:$t(t,P))}function Kp(t){return os($t(t,P))}function qp(t,n){return as(t,$t(n,P))}var kp=K(function(t,n){return function(e){return ve(e,t,n)}}),zp=K(function(t,n){return function(e){return ve(t,e,n)}});function zi(t,n,e){var r=lt(n),u=nr(n,r);e==null&&!(et(n)&&(u.length||!r.length))&&(e=n,n=t,t=this,u=nr(n,lt(n)));var o=!(et(e)&&"chain"in e)||!!e.chain,a=hn(t);return Ut(u,function(c){var d=n[c];t[c]=d,a&&(t.prototype[c]=function(){var y=this.__chain__;if(o||y){var m=t(this.__wrapped__),x=m.__actions__=St(this.__actions__);return x.push({func:d,args:arguments,thisArg:t}),m.__chain__=y,m}return d.apply(t,wn([this.value()],arguments))})}),t}function Hp(){return ht._===this&&(ht._=vf),this}function Hi(){}function Gp(t){return t=B(t),K(function(n){return fs(n,t)})}var Jp=Si(nt),Zp=Si(Tu),Yp=Si(Jr);function Io(t){return Ei(t)?Zr(en(t)):Cc(t)}function Xp(t){return function(n){return t==null?i:Wn(t,n)}}var Qp=Ls(),Vp=Ls(!0);function Gi(){return[]}function Ji(){return!1}function jp(){return{}}function tg(){return""}function ng(){return!0}function eg(t,n){if(t=B(t),t<1||t>jt)return[];var e=Ft,r=pt(t,Ft);n=L(n),t-=Ft;for(var u=Qr(r,n);++e<t;)n(e);return u}function rg(t){return U(t)?nt(t,en):Lt(t)?[t]:St(Js(Z(t)))}function ig(t){var n=++gf;return Z(t)+n}var ug=or(function(t,n){return t+n},0),sg=Ai("ceil"),og=or(function(t,n){return t/n},1),ag=Ai("floor");function fg(t){return t&&t.length?tr(t,Ct,ai):i}function cg(t,n){return t&&t.length?tr(t,L(n,2),ai):i}function lg(t){return Wu(t,Ct)}function hg(t,n){return Wu(t,L(n,2))}function dg(t){return t&&t.length?tr(t,Ct,hi):i}function pg(t,n){return t&&t.length?tr(t,L(n,2),hi):i}var gg=or(function(t,n){return t*n},1),_g=Ai("round"),vg=or(function(t,n){return t-n},0);function wg(t){return t&&t.length?Xr(t,Ct):0}function yg(t,n){return t&&t.length?Xr(t,L(n,2)):0}return s.after=Kh,s.ary=io,s.assign=Id,s.assignIn=yo,s.assignInWith=mr,s.assignWith=Ed,s.at=Td,s.before=uo,s.bind=Fi,s.bindAll=Fp,s.bindKey=so,s.castArray=jh,s.chain=no,s.chunk=al,s.compact=fl,s.concat=cl,s.cond=Np,s.conforms=Up,s.constant=qi,s.countBy=wh,s.create=Ld,s.curry=oo,s.curryRight=ao,s.debounce=fo,s.defaults=Od,s.defaultsDeep=Wd,s.defer=qh,s.delay=kh,s.difference=ll,s.differenceBy=hl,s.differenceWith=dl,s.drop=pl,s.dropRight=gl,s.dropRightWhile=_l,s.dropWhile=vl,s.fill=wl,s.filter=mh,s.flatMap=Ah,s.flatMapDeep=bh,s.flatMapDepth=Ch,s.flatten=Qs,s.flattenDeep=yl,s.flattenDepth=ml,s.flip=zh,s.flow=Mp,s.flowRight=$p,s.fromPairs=xl,s.functions=$d,s.functionsIn=Kd,s.groupBy=Ph,s.initial=Al,s.intersection=bl,s.intersectionBy=Cl,s.intersectionWith=Pl,s.invert=kd,s.invertBy=zd,s.invokeMap=Ih,s.iteratee=ki,s.keyBy=Eh,s.keys=lt,s.keysIn=bt,s.map=pr,s.mapKeys=Gd,s.mapValues=Jd,s.matches=Kp,s.matchesProperty=qp,s.memoize=_r,s.merge=Zd,s.mergeWith=mo,s.method=kp,s.methodOf=zp,s.mixin=zi,s.negate=vr,s.nthArg=Gp,s.omit=Yd,s.omitBy=Xd,s.once=Hh,s.orderBy=Th,s.over=Jp,s.overArgs=Gh,s.overEvery=Zp,s.overSome=Yp,s.partial=Ni,s.partialRight=co,s.partition=Lh,s.pick=Qd,s.pickBy=xo,s.property=Io,s.propertyOf=Xp,s.pull=Tl,s.pullAll=js,s.pullAllBy=Ll,s.pullAllWith=Ol,s.pullAt=Wl,s.range=Qp,s.rangeRight=Vp,s.rearg=Jh,s.reject=Dh,s.remove=Dl,s.rest=Zh,s.reverse=Wi,s.sampleSize=Nh,s.set=jd,s.setWith=tp,s.shuffle=Uh,s.slice=Fl,s.sortBy=$h,s.sortedUniq=ql,s.sortedUniqBy=kl,s.split=Ap,s.spread=Yh,s.tail=zl,s.take=Hl,s.takeRight=Gl,s.takeRightWhile=Jl,s.takeWhile=Zl,s.tap=fh,s.throttle=Xh,s.thru=dr,s.toArray=_o,s.toPairs=So,s.toPairsIn=Ao,s.toPath=rg,s.toPlainObject=wo,s.transform=np,s.unary=Qh,s.union=Yl,s.unionBy=Xl,s.unionWith=Ql,s.uniq=Vl,s.uniqBy=jl,s.uniqWith=th,s.unset=ep,s.unzip=Di,s.unzipWith=to,s.update=rp,s.updateWith=ip,s.values=ne,s.valuesIn=up,s.without=nh,s.words=Po,s.wrap=Vh,s.xor=eh,s.xorBy=rh,s.xorWith=ih,s.zip=uh,s.zipObject=sh,s.zipObjectDeep=oh,s.zipWith=ah,s.entries=So,s.entriesIn=Ao,s.extend=yo,s.extendWith=mr,zi(s,s),s.add=ug,s.attempt=Ro,s.camelCase=fp,s.capitalize=bo,s.ceil=sg,s.clamp=sp,s.clone=td,s.cloneDeep=ed,s.cloneDeepWith=rd,s.cloneWith=nd,s.conformsTo=id,s.deburr=Co,s.defaultTo=Bp,s.divide=og,s.endsWith=cp,s.eq=Xt,s.escape=lp,s.escapeRegExp=hp,s.every=yh,s.find=xh,s.findIndex=Ys,s.findKey=Dd,s.findLast=Sh,s.findLastIndex=Xs,s.findLastKey=Fd,s.floor=ag,s.forEach=eo,s.forEachRight=ro,s.forIn=Nd,s.forInRight=Ud,s.forOwn=Bd,s.forOwnRight=Md,s.get=Mi,s.gt=ud,s.gte=sd,s.has=qd,s.hasIn=$i,s.head=Vs,s.identity=Ct,s.includes=Rh,s.indexOf=Sl,s.inRange=op,s.invoke=Hd,s.isArguments=Nn,s.isArray=U,s.isArrayBuffer=od,s.isArrayLike=At,s.isArrayLikeObject=it,s.isBoolean=ad,s.isBuffer=Cn,s.isDate=fd,s.isElement=cd,s.isEmpty=ld,s.isEqual=hd,s.isEqualWith=dd,s.isError=Ui,s.isFinite=pd,s.isFunction=hn,s.isInteger=lo,s.isLength=wr,s.isMap=ho,s.isMatch=gd,s.isMatchWith=_d,s.isNaN=vd,s.isNative=wd,s.isNil=md,s.isNull=yd,s.isNumber=po,s.isObject=et,s.isObjectLike=rt,s.isPlainObject=Ae,s.isRegExp=Bi,s.isSafeInteger=xd,s.isSet=go,s.isString=yr,s.isSymbol=Lt,s.isTypedArray=te,s.isUndefined=Sd,s.isWeakMap=Ad,s.isWeakSet=bd,s.join=Rl,s.kebabCase=dp,s.last=qt,s.lastIndexOf=Il,s.lowerCase=pp,s.lowerFirst=gp,s.lt=Cd,s.lte=Pd,s.max=fg,s.maxBy=cg,s.mean=lg,s.meanBy=hg,s.min=dg,s.minBy=pg,s.stubArray=Gi,s.stubFalse=Ji,s.stubObject=jp,s.stubString=tg,s.stubTrue=ng,s.multiply=gg,s.nth=El,s.noConflict=Hp,s.noop=Hi,s.now=gr,s.pad=_p,s.padEnd=vp,s.padStart=wp,s.parseInt=yp,s.random=ap,s.reduce=Oh,s.reduceRight=Wh,s.repeat=mp,s.replace=xp,s.result=Vd,s.round=_g,s.runInContext=l,s.sample=Fh,s.size=Bh,s.snakeCase=Sp,s.some=Mh,s.sortedIndex=Nl,s.sortedIndexBy=Ul,s.sortedIndexOf=Bl,s.sortedLastIndex=Ml,s.sortedLastIndexBy=$l,s.sortedLastIndexOf=Kl,s.startCase=bp,s.startsWith=Cp,s.subtract=vg,s.sum=wg,s.sumBy=yg,s.template=Pp,s.times=eg,s.toFinite=dn,s.toInteger=B,s.toLength=vo,s.toLower=Rp,s.toNumber=kt,s.toSafeInteger=Rd,s.toString=Z,s.toUpper=Ip,s.trim=Ep,s.trimEnd=Tp,s.trimStart=Lp,s.truncate=Op,s.unescape=Wp,s.uniqueId=ig,s.upperCase=Dp,s.upperFirst=Ki,s.each=eo,s.eachRight=ro,s.first=Vs,zi(s,function(){var t={};return tn(s,function(n,e){Y.call(s.prototype,e)||(t[e]=n)}),t}(),{chain:!1}),s.VERSION=p,Ut(["bind","bindKey","curry","curryRight","partial","partialRight"],function(t){s[t].placeholder=s}),Ut(["drop","take"],function(t,n){z.prototype[t]=function(e){e=e===i?1:at(B(e),0);var r=this.__filtered__&&!n?new z(this):this.clone();return r.__filtered__?r.__takeCount__=pt(e,r.__takeCount__):r.__views__.push({size:pt(e,Ft),type:t+(r.__dir__<0?"Right":"")}),r},z.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}}),Ut(["filter","map","takeWhile"],function(t,n){var e=n+1,r=e==re||e==br;z.prototype[t]=function(u){var o=this.clone();return o.__iteratees__.push({iteratee:L(u,3),type:e}),o.__filtered__=o.__filtered__||r,o}}),Ut(["head","last"],function(t,n){var e="take"+(n?"Right":"");z.prototype[t]=function(){return this[e](1).value()[0]}}),Ut(["initial","tail"],function(t,n){var e="drop"+(n?"":"Right");z.prototype[t]=function(){return this.__filtered__?new z(this):this[e](1)}}),z.prototype.compact=function(){return this.filter(Ct)},z.prototype.find=function(t){return this.filter(t).head()},z.prototype.findLast=function(t){return this.reverse().find(t)},z.prototype.invokeMap=K(function(t,n){return typeof t=="function"?new z(this):this.map(function(e){return ve(e,t,n)})}),z.prototype.reject=function(t){return this.filter(vr(L(t)))},z.prototype.slice=function(t,n){t=B(t);var e=this;return e.__filtered__&&(t>0||n<0)?new z(e):(t<0?e=e.takeRight(-t):t&&(e=e.drop(t)),n!==i&&(n=B(n),e=n<0?e.dropRight(-n):e.take(n-t)),e)},z.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},z.prototype.toArray=function(){return this.take(Ft)},tn(z.prototype,function(t,n){var e=/^(?:filter|find|map|reject)|While$/.test(n),r=/^(?:head|last)$/.test(n),u=s[r?"take"+(n=="last"?"Right":""):n],o=r||/^find/.test(n);u&&(s.prototype[n]=function(){var a=this.__wrapped__,c=r?[1]:arguments,d=a instanceof z,y=c[0],m=d||U(a),x=function(k){var H=u.apply(s,wn([k],c));return r&&A?H[0]:H};m&&e&&typeof y=="function"&&y.length!=1&&(d=m=!1);var A=this.__chain__,R=!!this.__actions__.length,O=o&&!A,$=d&&!R;if(!o&&m){a=$?a:new z(this);var W=t.apply(a,c);return W.__actions__.push({func:dr,args:[x],thisArg:i}),new Mt(W,A)}return O&&$?t.apply(this,c):(W=this.thru(x),O?r?W.value()[0]:W.value():W)})}),Ut(["pop","push","shift","sort","splice","unshift"],function(t){var n=Me[t],e=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);s.prototype[t]=function(){var u=arguments;if(r&&!this.__chain__){var o=this.value();return n.apply(U(o)?o:[],u)}return this[e](function(a){return n.apply(U(a)?a:[],u)})}}),tn(z.prototype,function(t,n){var e=s[n];if(e){var r=e.name+"";Y.call(Yn,r)||(Yn[r]=[]),Yn[r].push({name:n,func:e})}}),Yn[sr(i,Pt).name]=[{name:"wrapper",func:i}],z.prototype.clone=Wf,z.prototype.reverse=Df,z.prototype.value=Ff,s.prototype.at=ch,s.prototype.chain=lh,s.prototype.commit=hh,s.prototype.next=dh,s.prototype.plant=gh,s.prototype.reverse=_h,s.prototype.toJSON=s.prototype.valueOf=s.prototype.value=vh,s.prototype.first=s.prototype.head,ce&&(s.prototype[ce]=ph),s},Gn=hf();In?((In.exports=Gn)._=Gn,kr._=Gn):ht._=Gn}).call(be)})(Sr,Sr.exports);var Eg=Sr.exports;const Tg=Ig(Eg);class Lg{constructor(f){D(this,"config");this.config=f}async complete(f,i){var p;await this.persist(f,{...i,success:!0}),(p=this.config.logger)==null||p.debug("Transaction completed:",f)}async fail(f,i){var p;await this.persist(f,{...i,success:!1}),(p=this.config.logger)==null||p.debug("Transaction failed:",{...f,...i})}async persist(f,i){await fetch(`${this.config.apiUrl}/transactions/${f.id}`,{body:JSON.stringify(i),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class Og{constructor(f,i){D(this,"transaction");D(this,"manager");this.transaction=f,this.manager=i}getFunctionCall(){return this.transaction.functionCall}async invoke(f,i){var E;const p=this.transaction.functionCall;if(!p){await this.fail("No function call found");return}const _=p.name,v=p.args,S=f[_];if(!S){await this.fail(`Tool ${_} not found`);return}try{const C=Tg.get(i,"schema.config.parameters.properties",{}),I=(C&&Object.keys(C).length>0?Object.keys(C):((E=S.toString().replace(/\n/g," ").match(/^[^(]*\(([^)]*)\)/))==null?void 0:E[1].split(",").map(T=>T.trim()).filter(Boolean))||[]).map(T=>v[T]),P=await S.apply(null,I);await this.complete(P)}catch(C){await this.fail(`Error executing tool ${_}: ${C}`)}}async complete(f){await this.manager.complete(this.transaction,{success:!0,output:f,error:null})}async fail(f){await this.manager.fail(this.transaction,{success:!1,output:null,error:f})}}class To extends Ce{constructor(i){super();D(this,"status");D(this,"autostart");D(this,"session");D(this,"config");D(this,"notify",!0);D(this,"_tools");D(this,"_toolSchema",{});if(this.config=i,this.status="disconnected",this.autostart=!0,Array.isArray(i.tools)){this._tools={};for(const p of i.tools)p.schema&&p.implementation&&(this._tools[p.schema.name]=p.implementation,this._toolSchema[p.schema.name]=p)}else this._tools=i.tools}getName(){return"transaction"}getPriority(){return 0}getToolInstance(i){return this._toolSchema[i]}async connect(i){return this.setStatus("connected"),i}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(i){this.session=i}async sendPacket(i){}onTransaction(i){const p=new Lg(this.config),_=new Og(i,p);if(this.config.onTransaction)this.config.onTransaction(_);else{const v=i.functionCall?this.getToolInstance(i.functionCall.name):void 0;_.invoke(this._tools,v)}}getTools(){return this._tools}}function Wg(h,f){if(Array.isArray(h))return h;if(typeof h=="object"&&h!==null){const i=f.dev?"localhost:8000":f.baseUrl||"persona.applica.guru/api",p=f.dev?"http":"https",_=f.dev?"ws":"wss";let v=Object.keys(h).map(S=>{switch(S){case"rest":return Dg(h[S],{baseEndpointProtocol:p,baseEndpoint:i,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger});case"webrtc":return Fg(h[S],{baseWebSocketProtocol:_,baseEndpoint:i,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger});case"websocket":return Ng(h[S],{baseWebSocketProtocol:_,baseEndpoint:i,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger});default:throw new Error(`Unknown protocol: ${S}`)}}).filter(S=>S!==null);return f.tools&&v.push(new To({apiUrl:`${p}://${i}`,apiKey:f.apiKey,agentId:f.agentId,tools:f.tools,logger:f.logger})),v}throw new Error("Invalid protocols configuration")}function Dg(h,f){return h===!0?new Yi({apiUrl:`${f.baseEndpointProtocol}://${f.baseEndpoint}`,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger}):typeof h=="object"&&h!==null?new Yi(h):null}function Fg(h,f){return h===!0?new Qi({webrtcUrl:`${f.baseWebSocketProtocol}://${f.baseEndpoint}/webrtc`,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger}):typeof h=="object"&&h!==null?new Qi(h):null}function Ng(h,f){return h===!0?new Xi({webSocketUrl:`${f.baseWebSocketProtocol}://${f.baseEndpoint}/websocket`,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger}):typeof h=="object"&&h!==null?new Xi(h):null}function Ug(h,f,i,p,_){return v=>{v.type==="message"?Bg(v.payload,h,f,i,_):v.type==="reasoning"?Mg(v.payload,h,f,_):v.type==="transaction"&&$g(v.payload,h,p)}}function Bg(h,f,i,p,_){h.createdAt||(h.createdAt=new Date),(h==null?void 0:h.finishReason)==="stop"&&!(h!=null&&h.functionResponse)&&!(h!=null&&h.thought)&&p(!1),h.thought&&(h.type="reasoning"),h.protocol=f.getName(),i(v=>{const S=ee([...v,h]);return _?_(S):S})}function Mg(h,f,i,p){const _={type:"reasoning",text:h.thought,role:"assistant",finishReason:"stop",protocol:f.getName(),createdAt:new Date};i(v=>{const S=ee([...v,_]);return p?p(S):S})}function $g(h,f,i){i.filter(p=>p!==f).forEach(p=>p.onTransaction(h))}function Kg(h){return new Promise((f,i)=>{const p=new FileReader;p.readAsDataURL(h),p.onload=()=>{const v=p.result.split(";base64,")[1];f(v)},p.onerror=_=>{i(_)}})}function qg(h){const f={rest:i=>i.config.apiUrl,webrtc:i=>i.config.webrtcUrl.replace("/webrtc","").replace("ws://","http://").replace("wss://","https://"),websocket:i=>i.config.webSocketUrl.replace("/websocket","").replace("ws://","http://").replace("wss://","https://")};for(const i of h){const p=f[i.getName()];if(p)return p(i)}return null}function kg(h,f,i,p,_){return async v=>{var P;if(((P=v.content[0])==null?void 0:P.type)!=="text")throw new Error("Only text messages are supported");if(!h.some(T=>T.getName()!=="transaction"&&T.status==="connected")){f(T=>{const F={role:"assistant",type:"text",text:"No protocol is connected.",createdAt:new Date,finishReason:"stop"},J=[...T,F];return p?p(J):J});return}const C={role:"user",type:"text",text:v.content[0].text,createdAt:new Date};f(T=>{const F=ee([...T,C]);return p?p(F):F}),i(!0);const M=h.sort((T,F)=>F.getPriority()-T.getPriority()).find(T=>T.status==="connected"),I=[];if(v.attachments)for(const T of v.attachments)T.contentType.startsWith("image/")&&T.file&&I.push({role:"user",image:{contentType:T.contentType,content:await Kg(T.file)},text:"",type:"text",createdAt:new Date});v.content&&I.push({role:"user",text:v.content[0].text,type:"text",createdAt:new Date}),_==null||_.debug("Sending message:",I),await(M==null?void 0:M.sendPacket({type:"request",payload:I}))}}function zg(h,f,i,p,_,v){return async S=>{var J;if(((J=S.content[0])==null?void 0:J.type)!=="text")throw new Error("Only text messages are supported");const E=h.sort((q,_t)=>_t.getPriority()-q.getPriority()).find(q=>q.status==="connected");if(!E){v==null||v.debug("No protocol available for edit");return}const C=S.parentId;if(!C){v==null||v.debug("No parent ID provided for edit");return}const M=f.findIndex(q=>q.id===C);if(M===-1){v==null||v.debug("Parent message not found:",C);return}const I=f.slice(0,M+1),P={role:"user",text:S.content[0].text,type:"text",createdAt:new Date},T=ee([...I,P]);i(_?_(T):T),p(!0);const F=[{role:"user",text:S.content[0].text,type:"text",createdAt:new Date}];v==null||v.debug("Sending edited message:",F),await E.sendPacket({type:"request",payload:F})}}function Hg(h,f,i,p,_,v){return async(S,E)=>{const C=h.sort((J,q)=>q.getPriority()-J.getPriority()).find(J=>J.status==="connected");if(!C){v==null||v.debug("No protocol available for reload");return}const M=E.parentId??S;if(!M){v==null||v.debug("No parent ID provided for reload");return}const I=f.findIndex(J=>J.id===M);if(I===-1){v==null||v.debug("Parent message not found:",M);return}const P=f[I];i(J=>{const q=J.slice(0,I+1);return _?_(q):q});let T;if(P.role==="assistant"||P.role==="function"){for(let J=I-1;J>=0;J--)if(f[J].role==="user"){T=f[J];break}}else P.role==="user"&&(T=P);if(!T){v==null||v.debug("No user message found to regenerate from");return}p(!0);const F=[];T.image&&F.push({role:"user",image:T.image,text:"",type:"text",createdAt:new Date}),F.push({role:"user",text:T.text,type:"text",createdAt:new Date}),v==null||v.debug("Regenerating message with config:",{actualParentId:M,sourceId:E.sourceId,custom:E.runConfig.custom}),await C.sendPacket({type:"request",payload:F})}}function Gg(h,f,i,p){return()=>(i(!1),f(_=>{const v=_[_.length-1];if((v==null?void 0:v.role)==="assistant"&&!v.finishReason){const S=[..._];return S[S.length-1]={...v,finishReason:"stop",status:{type:"incomplete"}},p?p(S):S}return _}),h.forEach(_=>{_.status==="connected"&&_.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:{cancel:!0}}}).catch(()=>{})}),Promise.resolve())}const Pe=j.createContext(void 0);function Jg(){const h=j.useContext(Pe);if(!h)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return h}function Lo(h){const f=j.useContext(Pe);if(!f)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const i=f.protocols.find(_=>_.getName()===h);if(!i)return null;const p=f.protocolsStatus.get(i.getName());return{...i,connect:i.connect.bind(i),disconnect:i.disconnect.bind(i),sendPacket:i.sendPacket.bind(i),setSession:i.setSession.bind(i),addStatusChangeListener:i.addStatusChangeListener.bind(i),addPacketListener:i.addPacketListener.bind(i),getName:i.getName.bind(i),getPriority:i.getPriority.bind(i),status:p||i.status}}function Zg(){const h=j.useContext(Pe);if(!h)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");return qg(h.protocols)}function Yg(){return Lo("webrtc")}function Xg(){const h=j.useContext(Pe);if(!h)throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");return h.getMessages()}function Qg(){const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let f="";for(let i=0;i<16;i++)f+=h.charAt(Math.floor(Math.random()*h.length));return f}function Vg(h,f,i,p,_,v,S,E,C,M,I){return{threadId:h,threads:f.filter(P=>P.status==="regular").map(P=>({id:P.threadId,threadId:P.threadId,title:P.title||`Chat ${P.threadId}`,status:P.status})),archivedThreads:f.filter(P=>P.status==="archived").map(P=>({id:P.threadId,threadId:P.threadId,title:P.title||`Archived Chat ${P.threadId}`,status:P.status})),onSwitchToNewThread:()=>{const P=Qg();I==null||I.debug("Creating new thread:",P);const T={threadId:P,status:"regular",title:"New Chat"};p(F=>[T,...F]),i(P),v==null||v(P)},onSwitchToThread:P=>{I==null||I.debug("Switching to thread:",P),i(P),S==null||S(P)},onArchive:P=>{I==null||I.debug("Archiving thread:",P),p(T=>T.map(F=>F.threadId===P?{...F,status:"archived"}:F)),E==null||E(P)},onUnarchive:P=>{I==null||I.debug("Unarchiving thread:",P),p(T=>T.map(F=>F.threadId===P?{...F,status:"regular"}:F)),C==null||C(P)},onDelete:async P=>{if(I==null||I.debug("Deleting thread:",P),p(T=>T.filter(F=>F.threadId!==P)),h===P){const T=f.filter(F=>F.threadId!==P&&F.status==="regular");T.length>0&&i(T[0].threadId)}_.remove(P).then(()=>I==null?void 0:I.debug("Thread deleted from backend")).catch(T=>I==null?void 0:I.error("Failed to delete thread:",T)),M==null||M(P)}}}class Oo{constructor(f){D(this,"endpoint");D(this,"apiKey");D(this,"pageSize");D(this,"logger");this.endpoint=f.endpoint.replace(/\/$/,""),this.apiKey=f.apiKey,this.pageSize=f.pageSize??200,this.logger=f.logger}buildHeaders(){const f={"Content-Type":"application/json"};return this.apiKey&&(f["x-persona-apikey"]=this.apiKey),f}async sync(f){var p,_;if(!f)return[];const i=`${this.endpoint}/sessions/${encodeURIComponent(String(f))}/messages?page=1&size=${this.pageSize}`;try{const v=await fetch(i,{method:"GET",headers:this.buildHeaders()});if(!v.ok)return(p=this.logger)==null||p.warn("PersonaSessionStorage: failed to fetch messages",v.status,await v.text()),[];const S=await v.json();return Array.isArray(S.items)?S.items.map(C=>({id:C.id??C.messageId??void 0,protocol:C.protocol,thought:C.thought,text:C.text??"",image:C.image,type:C.type??"text",role:C.role??"assistant",file:C.file,sources:C.sources,sessionId:C.sessionId??f,finishReason:C.finishReason,functionCalls:C.functionCalls,functionResponse:C.functionResponse,status:C.status,createdAt:C.createdAt?new Date(C.createdAt):void 0,metadata:C.metadata})):[]}catch(v){return(_=this.logger)==null||_.warn("PersonaSessionStorage: error fetching messages",v),[]}}async remove(f){var p,_;if(!f)return;const i=`${this.endpoint}/sessions/${encodeURIComponent(String(f))}`;try{const v=await fetch(i,{method:"DELETE",headers:this.buildHeaders()});if(!v.ok){const S=await v.text();throw(p=this.logger)==null||p.warn("PersonaSessionStorage: failed to delete session",v.status,S),new Error(`Failed to delete session: ${v.status}`)}return}catch(v){throw(_=this.logger)==null||_.warn("PersonaSessionStorage: error deleting session",v),v}}async clearAll(){return Promise.reject(new Error("PersonaAPIMessageStorage: clearAll not supported"))}async list(f,i){var v,S;const p=new URLSearchParams({page:"1",size:"100"});i&&p.set("userId",i),f&&p.set("agentId",f);const _=`${this.endpoint}/sessions?${p.toString()}`;try{const E=await fetch(_,{method:"GET",headers:this.buildHeaders()});if(!E.ok)return(v=this.logger)==null||v.warn("PersonaSessionStorage: failed to list sessions",E.status),[];const C=await E.json();return Array.isArray(C.items)?C.items.map(I=>({threadId:I.code||I.id,title:I.title||`Session ${I.code||I.id}`,status:I.status==="archived"?"archived":"regular"})):[]}catch(E){return(S=this.logger)==null||S.warn("PersonaSessionStorage: error listing sessions",E),[]}}}function jg({dev:h=!1,baseUrl:f,protocols:i,logger:p,children:_,session:v="new",transformMessages:S,enableThreads:E=!1,sessionStorage:C,onThreadCreate:M,onThreadSwitch:I,onThreadRename:P,onThreadArchive:T,onThreadUnarchive:F,onThreadDelete:J,...q}){const[_t,Pt]=j.useState(!1),[Vt,st]=j.useState([]),[Pn,zt]=j.useState(new Map),gn=j.useRef(!1),xt=j.useRef(!1),Dt=j.useMemo(()=>C||new Oo({apiKey:q.apiKey,endpoint:f||"https://persona.applica.guru/api"}),[C,f,q.apiKey]),[Bn,Re]=j.useState([]),[Rt,Ie]=j.useState(""),Mn=j.useRef(typeof v=="string"?v:"new"),re=j.useRef(!1);j.useEffect(()=>{!E||re.current||(re.current=!0,Dt.list(q.agentId,q.userId).then(X=>{(X==null?void 0:X.length)>0&&(Re(X),Ie(X[0].threadId))}).catch(X=>p==null?void 0:p.error("Failed to load threads:",X)))},[E,Dt,q.agentId,q.userId,p]);const ft=j.useMemo(()=>Wg(i,{dev:h||!1,baseUrl:f,apiKey:q.apiKey,agentId:q.agentId,userId:q.userId,tools:q.tools,logger:p}),[i,h,f,q.apiKey,q.agentId,q.userId,q.tools,p]);j.useEffect(()=>{gn.current||(gn.current=!0,p==null||p.debug("Setting up protocols:",ft.map(X=>X.getName())),ft.forEach(X=>{X.setSession(Mn.current),X.clearListeners(),X.addStatusChangeListener(ct=>{p==null||p.debug(`${X.getName()} status: ${ct}`),zt(Ht=>{const Rn=new Map(Ht);return Rn.set(X.getName(),ct),Rn}),ct==="connected"&&!xt.current&&(q.context&&X.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:q.context}}).catch(()=>{}),q.tools&&Array.isArray(q.tools)&&X.sendPacket({type:"command",payload:{command:"set_local_tools",arguments:{tools:q.tools.map(Ht=>Ht.schema)}}}).catch(()=>{}))}),X.addPacketListener(Ug(X,st,Pt,ft,S)),X.autostart&&X.status==="disconnected"&&(p==null||p.debug(`Auto-connecting protocol: ${X.getName()}`),X.connect(Mn.current).catch(()=>{}),Pt(!1))}))},[]),j.useEffect(()=>{if(!E||!Rt){st([]);return}if(xt.current||Rt===Mn.current)return;xt.current=!0,p==null||p.info("Switching to thread:",Rt),(async()=>{try{const ct=ft.filter(vt=>vt.status==="connected");ct.length>0&&await Promise.allSettled(ct.map(vt=>vt.disconnect())),Mn.current=Rt,await Promise.allSettled(ft.map(vt=>vt.setSession(Rt)));const Ht=await Dt.sync(Rt),Rn=ee(Ht);st(S?S(Rn):Rn),p==null||p.debug(`Loaded ${Ht.length} messages for thread ${Rt}`);const _n=ft.filter(vt=>vt.autostart);_n.length>0&&await Promise.allSettled(_n.map(vt=>vt.connect(Rt)))}catch(ct){p==null||p.error("Failed to switch thread:",ct),st([])}finally{xt.current=!1}})()},[Rt,E,ft,Dt,S,p]);const br=j.useCallback(kg(ft,st,Pt,S,p),[ft,S,p]),rn=j.useCallback(zg(ft,Vt,st,Pt,S,p),[ft,Vt,S,p]),jt=j.useCallback(Hg(ft,Vt,st,Pt,S,p),[ft,Vt,S,p]),Cr=j.useCallback(Gg(ft,st,Pt,S),[ft,S]),$n=j.useCallback(X=>{const ct=ee([...X]);st(S?S(ct):ct)},[S]),Ft=j.useCallback(()=>Vt,[Vt]),Ee=j.useMemo(()=>{if(E)return Vg(Rt,Bn,Ie,Re,Dt,M,I,T,F,J,p)},[E,Rt,Bn,Dt,M,I,T,F,J,p]),Pr=xr.useExternalStoreRuntime({isRunning:_t,messages:Vt,convertMessage:Pg,setMessages:$n,onNew:br,onEdit:rn,onCancel:Cr,onReload:jt,adapters:{attachments:new xr.CompositeAttachmentAdapter([new xr.SimpleImageAttachmentAdapter]),...Ee?{threadList:Ee}:{}}});return Zi.jsx(Pe.Provider,{value:{protocols:ft,protocolsStatus:Pn,getMessages:Ft},children:Zi.jsx(xr.AssistantRuntimeProvider,{runtime:Pr,children:_})})}function t_({children:h,...f}){return Zi.jsx(jg,{...f,children:h})}class n_{constructor(){D(this,"prefix","[Persona]")}log(f,...i){console.log(`${this.prefix} - ${f}`,...i)}info(f,...i){console.info(`${this.prefix} - ${f}`,...i)}warn(f,...i){console.warn(`${this.prefix} - ${f}`,...i)}error(f,...i){console.error(`${this.prefix} - ${f}`,...i)}debug(f,...i){console.debug(`${this.prefix} - ${f}`,...i)}}function Un(h,f,i){return{type:h,description:f,...i}}function Wo(h){const f=Object.entries(h.parameters).filter(([i,p])=>p.required).map(([i])=>i);return{type:"local",name:h.name,description:h.description,config:{timeout:h.timeout||60,parameters:{type:"object",title:h.title||`${h.name} parameters`,required:f,properties:h.parameters},output:{type:"object",title:`${h.name} output`,properties:h.output}}}}function Ar(h){return{schema:Wo(h),implementation:h.implementation}}function Do(h,f,i,p,_,v){const S={name:h,description:f,title:v==null?void 0:v.title,timeout:v==null?void 0:v.timeout,parameters:p,output:_,implementation:i};return Ar(S)}const e_=Do("sum","Sum two numbers",function(f,i){return{result:f+i}},{a:Un("number","First number to sum",{required:!0}),b:Un("number","Second number to sum",{required:!0})},{result:Un("number","Sum of two numbers")}),r_=Ar({name:"navigate_to",description:"Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that",title:"Sum two numbers",timeout:60,parameters:{a:Un("number","First number to sum"),b:Un("number","Seconth number to sum")},output:{result:Un("number","Sum of two numbers")},implementation:function(f,i){return{result:f+i}}});function i_(h){const f=[],i={};return h.forEach(p=>{const{schema:_,implementation:v}=Ar(p);f.push(_),i[p.name]=v}),{schemas:f,implementations:i}}function u_(h,f){const{required:i,properties:p}=f.config.parameters;for(const _ of i)if(!(_ in h))throw new Error(`Missing required parameter: ${_}`);for(const[_,v]of Object.entries(h)){const S=p[_];if(S){if(S.type==="number"&&typeof v!="number")throw new Error(`Parameter ${_} should be a number`);if(S.type==="string"&&typeof v!="string")throw new Error(`Parameter ${_} should be a string`);if(S.type==="boolean"&&typeof v!="boolean")throw new Error(`Parameter ${_} should be a boolean`)}}return!0}exports.PersonaConsoleLogger=n_;exports.PersonaProtocolBase=Ce;exports.PersonaRESTProtocol=Yi;exports.PersonaRuntimeProvider=t_;exports.PersonaSessionStorage=Oo;exports.PersonaTransactionProtocol=To;exports.PersonaWebRTCProtocol=Qi;exports.PersonaWebSocketProtocol=Xi;exports.createParameter=Un;exports.createTool=Ar;exports.createToolFromFunction=Do;exports.createToolRegistry=i_;exports.generateToolSchema=Wo;exports.navigateToToolExample=r_;exports.sumTool=e_;exports.usePersonaRuntime=Jg;exports.usePersonaRuntimeEndpoint=Zg;exports.usePersonaRuntimeMessages=Xg;exports.usePersonaRuntimeProtocol=Lo;exports.usePersonaRuntimeWebRTCProtocol=Yg;exports.validateToolParameters=u_;
27
+ }`;var $=Ro(function(){return G(o,R+"return "+x).apply(i,a)});if($.source=x,Ui($))throw $;return $}function Rp(t){return Z(t).toLowerCase()}function Ip(t){return Z(t).toUpperCase()}function Ep(t,n,e){if(t=Z(t),t&&(e||n===i))return Fu(t);if(!t||!(n=Tt(n)))return t;var r=Zt(t),u=Zt(n),o=Nu(r,u),a=Uu(r,u)+1;return bn(r,o,a).join("")}function Tp(t,n,e){if(t=Z(t),t&&(e||n===i))return t.slice(0,Mu(t)+1);if(!t||!(n=Tt(n)))return t;var r=Zt(t),u=Uu(r,Zt(n))+1;return bn(r,0,u).join("")}function Lp(t,n,e){if(t=Z(t),t&&(e||n===i))return t.replace(Ur,"");if(!t||!(n=Tt(n)))return t;var r=Zt(t),u=Nu(r,Zt(n));return bn(r,u).join("")}function Op(t,n){var e=Re,r=Rt;if(et(n)){var u="separator"in n?n.separator:u;e="length"in n?B(n.length):e,r="omission"in n?Tt(n.omission):r}t=Z(t);var o=t.length;if(zn(t)){var a=Zt(t);o=a.length}if(e>=o)return t;var c=e-Hn(r);if(c<1)return r;var d=a?bn(a,0,c).join(""):t.slice(0,c);if(u===i)return d+r;if(a&&(c+=d.length-c),Bi(u)){if(t.slice(c).search(u)){var y,m=d;for(u.global||(u=ti(u.source,Z(ru.exec(u))+"g")),u.lastIndex=0;y=u.exec(m);)var x=y.index;d=d.slice(0,x===i?c:x)}}else if(t.indexOf(Tt(u),c)!=c){var A=d.lastIndexOf(u);A>-1&&(d=d.slice(0,A))}return d+r}function Wp(t){return t=Z(t),t&&ko.test(t)?t.replace(tu,af):t}var Dp=Vn(function(t,n,e){return t+(e?" ":"")+n.toUpperCase()}),Ki=Rs("toUpperCase");function Po(t,n,e){return t=Z(t),n=e?i:n,n===i?ef(t)?lf(t):Ja(t):t.match(n)||[]}var Ro=K(function(t,n){try{return It(t,i,n)}catch(e){return Ui(e)?e:new N(e)}}),Fp=cn(function(t,n){return Ut(n,function(e){e=en(e),an(t,e,Fi(t[e],t))}),t});function Np(t){var n=t==null?0:t.length,e=L();return t=n?nt(t,function(r){if(typeof r[1]!="function")throw new Bt(S);return[e(r[0]),r[1]]}):[],K(function(r){for(var u=-1;++u<n;){var o=t[u];if(It(o[0],this,r))return It(o[1],this,r)}})}function Up(t){return ac($t(t,P))}function qi(t){return function(){return t}}function Bp(t,n){return t==null||t!==t?n:t}var Mp=Es(),$p=Es(!0);function Ct(t){return t}function ki(t){return us(typeof t=="function"?t:$t(t,P))}function Kp(t){return os($t(t,P))}function qp(t,n){return as(t,$t(n,P))}var kp=K(function(t,n){return function(e){return ve(e,t,n)}}),zp=K(function(t,n){return function(e){return ve(t,e,n)}});function zi(t,n,e){var r=lt(n),u=nr(n,r);e==null&&!(et(n)&&(u.length||!r.length))&&(e=n,n=t,t=this,u=nr(n,lt(n)));var o=!(et(e)&&"chain"in e)||!!e.chain,a=hn(t);return Ut(u,function(c){var d=n[c];t[c]=d,a&&(t.prototype[c]=function(){var y=this.__chain__;if(o||y){var m=t(this.__wrapped__),x=m.__actions__=St(this.__actions__);return x.push({func:d,args:arguments,thisArg:t}),m.__chain__=y,m}return d.apply(t,wn([this.value()],arguments))})}),t}function Hp(){return ht._===this&&(ht._=vf),this}function Hi(){}function Gp(t){return t=B(t),K(function(n){return fs(n,t)})}var Jp=Si(nt),Zp=Si(Tu),Yp=Si(Jr);function Io(t){return Ei(t)?Zr(en(t)):Cc(t)}function Xp(t){return function(n){return t==null?i:Wn(t,n)}}var Qp=Ls(),Vp=Ls(!0);function Gi(){return[]}function Ji(){return!1}function jp(){return{}}function tg(){return""}function ng(){return!0}function eg(t,n){if(t=B(t),t<1||t>jt)return[];var e=Ft,r=pt(t,Ft);n=L(n),t-=Ft;for(var u=Qr(r,n);++e<t;)n(e);return u}function rg(t){return U(t)?nt(t,en):Lt(t)?[t]:St(Js(Z(t)))}function ig(t){var n=++gf;return Z(t)+n}var ug=or(function(t,n){return t+n},0),sg=Ai("ceil"),og=or(function(t,n){return t/n},1),ag=Ai("floor");function fg(t){return t&&t.length?tr(t,Ct,ai):i}function cg(t,n){return t&&t.length?tr(t,L(n,2),ai):i}function lg(t){return Wu(t,Ct)}function hg(t,n){return Wu(t,L(n,2))}function dg(t){return t&&t.length?tr(t,Ct,hi):i}function pg(t,n){return t&&t.length?tr(t,L(n,2),hi):i}var gg=or(function(t,n){return t*n},1),_g=Ai("round"),vg=or(function(t,n){return t-n},0);function wg(t){return t&&t.length?Xr(t,Ct):0}function yg(t,n){return t&&t.length?Xr(t,L(n,2)):0}return s.after=Kh,s.ary=io,s.assign=Id,s.assignIn=yo,s.assignInWith=mr,s.assignWith=Ed,s.at=Td,s.before=uo,s.bind=Fi,s.bindAll=Fp,s.bindKey=so,s.castArray=jh,s.chain=no,s.chunk=al,s.compact=fl,s.concat=cl,s.cond=Np,s.conforms=Up,s.constant=qi,s.countBy=wh,s.create=Ld,s.curry=oo,s.curryRight=ao,s.debounce=fo,s.defaults=Od,s.defaultsDeep=Wd,s.defer=qh,s.delay=kh,s.difference=ll,s.differenceBy=hl,s.differenceWith=dl,s.drop=pl,s.dropRight=gl,s.dropRightWhile=_l,s.dropWhile=vl,s.fill=wl,s.filter=mh,s.flatMap=Ah,s.flatMapDeep=bh,s.flatMapDepth=Ch,s.flatten=Qs,s.flattenDeep=yl,s.flattenDepth=ml,s.flip=zh,s.flow=Mp,s.flowRight=$p,s.fromPairs=xl,s.functions=$d,s.functionsIn=Kd,s.groupBy=Ph,s.initial=Al,s.intersection=bl,s.intersectionBy=Cl,s.intersectionWith=Pl,s.invert=kd,s.invertBy=zd,s.invokeMap=Ih,s.iteratee=ki,s.keyBy=Eh,s.keys=lt,s.keysIn=bt,s.map=pr,s.mapKeys=Gd,s.mapValues=Jd,s.matches=Kp,s.matchesProperty=qp,s.memoize=_r,s.merge=Zd,s.mergeWith=mo,s.method=kp,s.methodOf=zp,s.mixin=zi,s.negate=vr,s.nthArg=Gp,s.omit=Yd,s.omitBy=Xd,s.once=Hh,s.orderBy=Th,s.over=Jp,s.overArgs=Gh,s.overEvery=Zp,s.overSome=Yp,s.partial=Ni,s.partialRight=co,s.partition=Lh,s.pick=Qd,s.pickBy=xo,s.property=Io,s.propertyOf=Xp,s.pull=Tl,s.pullAll=js,s.pullAllBy=Ll,s.pullAllWith=Ol,s.pullAt=Wl,s.range=Qp,s.rangeRight=Vp,s.rearg=Jh,s.reject=Dh,s.remove=Dl,s.rest=Zh,s.reverse=Wi,s.sampleSize=Nh,s.set=jd,s.setWith=tp,s.shuffle=Uh,s.slice=Fl,s.sortBy=$h,s.sortedUniq=ql,s.sortedUniqBy=kl,s.split=Ap,s.spread=Yh,s.tail=zl,s.take=Hl,s.takeRight=Gl,s.takeRightWhile=Jl,s.takeWhile=Zl,s.tap=fh,s.throttle=Xh,s.thru=dr,s.toArray=_o,s.toPairs=So,s.toPairsIn=Ao,s.toPath=rg,s.toPlainObject=wo,s.transform=np,s.unary=Qh,s.union=Yl,s.unionBy=Xl,s.unionWith=Ql,s.uniq=Vl,s.uniqBy=jl,s.uniqWith=th,s.unset=ep,s.unzip=Di,s.unzipWith=to,s.update=rp,s.updateWith=ip,s.values=ne,s.valuesIn=up,s.without=nh,s.words=Po,s.wrap=Vh,s.xor=eh,s.xorBy=rh,s.xorWith=ih,s.zip=uh,s.zipObject=sh,s.zipObjectDeep=oh,s.zipWith=ah,s.entries=So,s.entriesIn=Ao,s.extend=yo,s.extendWith=mr,zi(s,s),s.add=ug,s.attempt=Ro,s.camelCase=fp,s.capitalize=bo,s.ceil=sg,s.clamp=sp,s.clone=td,s.cloneDeep=ed,s.cloneDeepWith=rd,s.cloneWith=nd,s.conformsTo=id,s.deburr=Co,s.defaultTo=Bp,s.divide=og,s.endsWith=cp,s.eq=Xt,s.escape=lp,s.escapeRegExp=hp,s.every=yh,s.find=xh,s.findIndex=Ys,s.findKey=Dd,s.findLast=Sh,s.findLastIndex=Xs,s.findLastKey=Fd,s.floor=ag,s.forEach=eo,s.forEachRight=ro,s.forIn=Nd,s.forInRight=Ud,s.forOwn=Bd,s.forOwnRight=Md,s.get=Mi,s.gt=ud,s.gte=sd,s.has=qd,s.hasIn=$i,s.head=Vs,s.identity=Ct,s.includes=Rh,s.indexOf=Sl,s.inRange=op,s.invoke=Hd,s.isArguments=Nn,s.isArray=U,s.isArrayBuffer=od,s.isArrayLike=At,s.isArrayLikeObject=it,s.isBoolean=ad,s.isBuffer=Cn,s.isDate=fd,s.isElement=cd,s.isEmpty=ld,s.isEqual=hd,s.isEqualWith=dd,s.isError=Ui,s.isFinite=pd,s.isFunction=hn,s.isInteger=lo,s.isLength=wr,s.isMap=ho,s.isMatch=gd,s.isMatchWith=_d,s.isNaN=vd,s.isNative=wd,s.isNil=md,s.isNull=yd,s.isNumber=po,s.isObject=et,s.isObjectLike=rt,s.isPlainObject=Ae,s.isRegExp=Bi,s.isSafeInteger=xd,s.isSet=go,s.isString=yr,s.isSymbol=Lt,s.isTypedArray=te,s.isUndefined=Sd,s.isWeakMap=Ad,s.isWeakSet=bd,s.join=Rl,s.kebabCase=dp,s.last=qt,s.lastIndexOf=Il,s.lowerCase=pp,s.lowerFirst=gp,s.lt=Cd,s.lte=Pd,s.max=fg,s.maxBy=cg,s.mean=lg,s.meanBy=hg,s.min=dg,s.minBy=pg,s.stubArray=Gi,s.stubFalse=Ji,s.stubObject=jp,s.stubString=tg,s.stubTrue=ng,s.multiply=gg,s.nth=El,s.noConflict=Hp,s.noop=Hi,s.now=gr,s.pad=_p,s.padEnd=vp,s.padStart=wp,s.parseInt=yp,s.random=ap,s.reduce=Oh,s.reduceRight=Wh,s.repeat=mp,s.replace=xp,s.result=Vd,s.round=_g,s.runInContext=l,s.sample=Fh,s.size=Bh,s.snakeCase=Sp,s.some=Mh,s.sortedIndex=Nl,s.sortedIndexBy=Ul,s.sortedIndexOf=Bl,s.sortedLastIndex=Ml,s.sortedLastIndexBy=$l,s.sortedLastIndexOf=Kl,s.startCase=bp,s.startsWith=Cp,s.subtract=vg,s.sum=wg,s.sumBy=yg,s.template=Pp,s.times=eg,s.toFinite=dn,s.toInteger=B,s.toLength=vo,s.toLower=Rp,s.toNumber=kt,s.toSafeInteger=Rd,s.toString=Z,s.toUpper=Ip,s.trim=Ep,s.trimEnd=Tp,s.trimStart=Lp,s.truncate=Op,s.unescape=Wp,s.uniqueId=ig,s.upperCase=Dp,s.upperFirst=Ki,s.each=eo,s.eachRight=ro,s.first=Vs,zi(s,function(){var t={};return tn(s,function(n,e){Y.call(s.prototype,e)||(t[e]=n)}),t}(),{chain:!1}),s.VERSION=p,Ut(["bind","bindKey","curry","curryRight","partial","partialRight"],function(t){s[t].placeholder=s}),Ut(["drop","take"],function(t,n){z.prototype[t]=function(e){e=e===i?1:at(B(e),0);var r=this.__filtered__&&!n?new z(this):this.clone();return r.__filtered__?r.__takeCount__=pt(e,r.__takeCount__):r.__views__.push({size:pt(e,Ft),type:t+(r.__dir__<0?"Right":"")}),r},z.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}}),Ut(["filter","map","takeWhile"],function(t,n){var e=n+1,r=e==re||e==br;z.prototype[t]=function(u){var o=this.clone();return o.__iteratees__.push({iteratee:L(u,3),type:e}),o.__filtered__=o.__filtered__||r,o}}),Ut(["head","last"],function(t,n){var e="take"+(n?"Right":"");z.prototype[t]=function(){return this[e](1).value()[0]}}),Ut(["initial","tail"],function(t,n){var e="drop"+(n?"":"Right");z.prototype[t]=function(){return this.__filtered__?new z(this):this[e](1)}}),z.prototype.compact=function(){return this.filter(Ct)},z.prototype.find=function(t){return this.filter(t).head()},z.prototype.findLast=function(t){return this.reverse().find(t)},z.prototype.invokeMap=K(function(t,n){return typeof t=="function"?new z(this):this.map(function(e){return ve(e,t,n)})}),z.prototype.reject=function(t){return this.filter(vr(L(t)))},z.prototype.slice=function(t,n){t=B(t);var e=this;return e.__filtered__&&(t>0||n<0)?new z(e):(t<0?e=e.takeRight(-t):t&&(e=e.drop(t)),n!==i&&(n=B(n),e=n<0?e.dropRight(-n):e.take(n-t)),e)},z.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},z.prototype.toArray=function(){return this.take(Ft)},tn(z.prototype,function(t,n){var e=/^(?:filter|find|map|reject)|While$/.test(n),r=/^(?:head|last)$/.test(n),u=s[r?"take"+(n=="last"?"Right":""):n],o=r||/^find/.test(n);u&&(s.prototype[n]=function(){var a=this.__wrapped__,c=r?[1]:arguments,d=a instanceof z,y=c[0],m=d||U(a),x=function(k){var H=u.apply(s,wn([k],c));return r&&A?H[0]:H};m&&e&&typeof y=="function"&&y.length!=1&&(d=m=!1);var A=this.__chain__,R=!!this.__actions__.length,O=o&&!A,$=d&&!R;if(!o&&m){a=$?a:new z(this);var W=t.apply(a,c);return W.__actions__.push({func:dr,args:[x],thisArg:i}),new Mt(W,A)}return O&&$?t.apply(this,c):(W=this.thru(x),O?r?W.value()[0]:W.value():W)})}),Ut(["pop","push","shift","sort","splice","unshift"],function(t){var n=Me[t],e=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);s.prototype[t]=function(){var u=arguments;if(r&&!this.__chain__){var o=this.value();return n.apply(U(o)?o:[],u)}return this[e](function(a){return n.apply(U(a)?a:[],u)})}}),tn(z.prototype,function(t,n){var e=s[n];if(e){var r=e.name+"";Y.call(Yn,r)||(Yn[r]=[]),Yn[r].push({name:n,func:e})}}),Yn[sr(i,Pt).name]=[{name:"wrapper",func:i}],z.prototype.clone=Wf,z.prototype.reverse=Df,z.prototype.value=Ff,s.prototype.at=ch,s.prototype.chain=lh,s.prototype.commit=hh,s.prototype.next=dh,s.prototype.plant=gh,s.prototype.reverse=_h,s.prototype.toJSON=s.prototype.valueOf=s.prototype.value=vh,s.prototype.first=s.prototype.head,ce&&(s.prototype[ce]=ph),s},Gn=hf();In?((In.exports=Gn)._=Gn,kr._=Gn):ht._=Gn}).call(be)})(Sr,Sr.exports);var Eg=Sr.exports;const Tg=Ig(Eg);class Lg{constructor(f){D(this,"config");this.config=f}async complete(f,i){var p;await this.persist(f,{...i,success:!0}),(p=this.config.logger)==null||p.debug("Transaction completed:",f)}async fail(f,i){var p;await this.persist(f,{...i,success:!1}),(p=this.config.logger)==null||p.debug("Transaction failed:",{...f,...i})}async persist(f,i){await fetch(`${this.config.apiUrl}/transactions/${f.id}`,{body:JSON.stringify(i),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class Og{constructor(f,i){D(this,"transaction");D(this,"manager");this.transaction=f,this.manager=i}getFunctionCall(){return this.transaction.functionCall}async invoke(f,i){var E;const p=this.transaction.functionCall;if(!p){await this.fail("No function call found");return}const _=p.name,v=p.args,S=f[_];if(!S){await this.fail(`Tool ${_} not found`);return}try{const C=Tg.get(i,"schema.config.parameters.properties",{}),I=(C&&Object.keys(C).length>0?Object.keys(C):((E=S.toString().replace(/\n/g," ").match(/^[^(]*\(([^)]*)\)/))==null?void 0:E[1].split(",").map(T=>T.trim()).filter(Boolean))||[]).map(T=>v[T]),P=await S.apply(null,I);await this.complete(P)}catch(C){await this.fail(`Error executing tool ${_}: ${C}`)}}async complete(f){await this.manager.complete(this.transaction,{success:!0,output:f,error:null})}async fail(f){await this.manager.fail(this.transaction,{success:!1,output:null,error:f})}}class To extends Ce{constructor(i){super();D(this,"status");D(this,"autostart");D(this,"session");D(this,"config");D(this,"notify",!0);D(this,"_tools");D(this,"_toolSchema",{});if(this.config=i,this.status="disconnected",this.autostart=!0,Array.isArray(i.tools)){this._tools={};for(const p of i.tools)p.schema&&p.implementation&&(this._tools[p.schema.name]=p.implementation,this._toolSchema[p.schema.name]=p)}else this._tools=i.tools}getName(){return"transaction"}getPriority(){return 0}getToolInstance(i){return this._toolSchema[i]}async connect(i){return this.setStatus("connected"),i}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(i){this.session=i}async sendPacket(i){}onTransaction(i){const p=new Lg(this.config),_=new Og(i,p);if(this.config.onTransaction)this.config.onTransaction(_);else{const v=i.functionCall?this.getToolInstance(i.functionCall.name):void 0;_.invoke(this._tools,v)}}getTools(){return this._tools}}function Wg(h,f){if(Array.isArray(h))return h;if(typeof h=="object"&&h!==null){const i=f.dev?"localhost:8000":f.baseUrl||"persona.applica.guru/api",p=f.dev?"http":"https",_=f.dev?"ws":"wss";let v=Object.keys(h).map(S=>{switch(S){case"rest":return Dg(h[S],{baseEndpointProtocol:p,baseEndpoint:i,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger});case"webrtc":return Fg(h[S],{baseWebSocketProtocol:_,baseEndpoint:i,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger});case"websocket":return Ng(h[S],{baseWebSocketProtocol:_,baseEndpoint:i,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger});default:throw new Error(`Unknown protocol: ${S}`)}}).filter(S=>S!==null);return f.tools&&v.push(new To({apiUrl:`${p}://${i}`,apiKey:f.apiKey,agentId:f.agentId,tools:f.tools,logger:f.logger})),v}throw new Error("Invalid protocols configuration")}function Dg(h,f){return h===!0?new Yi({apiUrl:`${f.baseEndpointProtocol}://${f.baseEndpoint}`,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger}):typeof h=="object"&&h!==null?new Yi(h):null}function Fg(h,f){return h===!0?new Qi({webrtcUrl:`${f.baseWebSocketProtocol}://${f.baseEndpoint}/webrtc`,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger}):typeof h=="object"&&h!==null?new Qi(h):null}function Ng(h,f){return h===!0?new Xi({webSocketUrl:`${f.baseWebSocketProtocol}://${f.baseEndpoint}/websocket`,apiKey:f.apiKey,agentId:f.agentId,userId:f.userId,logger:f.logger}):typeof h=="object"&&h!==null?new Xi(h):null}function Ug(h,f,i,p,_){return v=>{v.type==="message"?Bg(v.payload,h,f,i,_):v.type==="reasoning"?Mg(v.payload,h,f,_):v.type==="transaction"&&$g(v.payload,h,p)}}function Bg(h,f,i,p,_){h.createdAt||(h.createdAt=new Date),(h==null?void 0:h.finishReason)==="stop"&&!(h!=null&&h.functionResponse)&&!(h!=null&&h.thought)&&p(!1),h.thought&&(h.type="reasoning"),h.protocol=f.getName(),i(v=>{const S=ee([...v,h]);return _?_(S):S})}function Mg(h,f,i,p){const _={type:"reasoning",text:h.thought,role:"assistant",finishReason:"stop",protocol:f.getName(),createdAt:new Date};i(v=>{const S=ee([...v,_]);return p?p(S):S})}function $g(h,f,i){i.filter(p=>p!==f).forEach(p=>p.onTransaction(h))}function Kg(h){return new Promise((f,i)=>{const p=new FileReader;p.readAsDataURL(h),p.onload=()=>{const v=p.result.split(";base64,")[1];f(v)},p.onerror=_=>{i(_)}})}function qg(h){const f={rest:i=>i.config.apiUrl,webrtc:i=>i.config.webrtcUrl.replace("/webrtc","").replace("ws://","http://").replace("wss://","https://"),websocket:i=>i.config.webSocketUrl.replace("/websocket","").replace("ws://","http://").replace("wss://","https://")};for(const i of h){const p=f[i.getName()];if(p)return p(i)}return null}function kg(h,f,i,p,_){return async v=>{var P;if(((P=v.content[0])==null?void 0:P.type)!=="text")throw new Error("Only text messages are supported");if(!h.some(T=>T.getName()!=="transaction"&&T.status==="connected")){f(T=>{const F={role:"assistant",type:"text",text:"No protocol is connected.",createdAt:new Date,finishReason:"stop"},J=[...T,F];return p?p(J):J});return}const C={role:"user",type:"text",text:v.content[0].text,createdAt:new Date};f(T=>{const F=ee([...T,C]);return p?p(F):F}),i(!0);const M=h.sort((T,F)=>F.getPriority()-T.getPriority()).find(T=>T.status==="connected"),I=[];if(v.attachments)for(const T of v.attachments)T.contentType.startsWith("image/")&&T.file&&I.push({role:"user",image:{contentType:T.contentType,content:await Kg(T.file)},text:"",type:"text",createdAt:new Date});v.content&&I.push({role:"user",text:v.content[0].text,type:"text",createdAt:new Date}),_==null||_.debug("Sending message:",I),await(M==null?void 0:M.sendPacket({type:"request",payload:I}))}}function zg(h,f,i,p,_,v){return async S=>{var J;if(((J=S.content[0])==null?void 0:J.type)!=="text")throw new Error("Only text messages are supported");const E=h.sort((q,_t)=>_t.getPriority()-q.getPriority()).find(q=>q.status==="connected");if(!E){v==null||v.debug("No protocol available for edit");return}const C=S.parentId;if(!C){v==null||v.debug("No parent ID provided for edit");return}const M=f.findIndex(q=>q.id===C);if(M===-1){v==null||v.debug("Parent message not found:",C);return}const I=f.slice(0,M+1),P={role:"user",text:S.content[0].text,type:"text",createdAt:new Date},T=ee([...I,P]);i(_?_(T):T),p(!0);const F=[{role:"user",text:S.content[0].text,type:"text",createdAt:new Date}];v==null||v.debug("Sending edited message:",F),await E.sendPacket({type:"request",payload:F})}}function Hg(h,f,i,p,_,v){return async(S,E)=>{const C=h.sort((J,q)=>q.getPriority()-J.getPriority()).find(J=>J.status==="connected");if(!C){v==null||v.debug("No protocol available for reload");return}const M=E.parentId??S;if(!M){v==null||v.debug("No parent ID provided for reload");return}const I=f.findIndex(J=>J.id===M);if(I===-1){v==null||v.debug("Parent message not found:",M);return}const P=f[I];i(J=>{const q=J.slice(0,I+1);return _?_(q):q});let T;if(P.role==="assistant"||P.role==="function"){for(let J=I-1;J>=0;J--)if(f[J].role==="user"){T=f[J];break}}else P.role==="user"&&(T=P);if(!T){v==null||v.debug("No user message found to regenerate from");return}p(!0);const F=[];T.image&&F.push({role:"user",image:T.image,text:"",type:"text",createdAt:new Date}),F.push({role:"user",text:T.text,type:"text",createdAt:new Date}),v==null||v.debug("Regenerating message with config:",{actualParentId:M,sourceId:E.sourceId,custom:E.runConfig.custom}),await C.sendPacket({type:"request",payload:F})}}function Gg(h,f,i,p){return()=>(i(!1),f(_=>{const v=_[_.length-1];if((v==null?void 0:v.role)==="assistant"&&!v.finishReason){const S=[..._];return S[S.length-1]={...v,finishReason:"stop",status:{type:"incomplete"}},p?p(S):S}return _}),h.forEach(_=>{_.status==="connected"&&_.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:{cancel:!0}}}).catch(()=>{})}),Promise.resolve())}const Pe=j.createContext(void 0);function Jg(){const h=j.useContext(Pe);if(!h)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return h}function Lo(h){const f=j.useContext(Pe);if(!f)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const i=f.protocols.find(_=>_.getName()===h);if(!i)return null;const p=f.protocolsStatus.get(i.getName());return{...i,connect:i.connect.bind(i),disconnect:i.disconnect.bind(i),sendPacket:i.sendPacket.bind(i),setSession:i.setSession.bind(i),addStatusChangeListener:i.addStatusChangeListener.bind(i),addPacketListener:i.addPacketListener.bind(i),getName:i.getName.bind(i),getPriority:i.getPriority.bind(i),status:p||i.status}}function Zg(){const h=j.useContext(Pe);if(!h)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");return qg(h.protocols)}function Yg(){return Lo("webrtc")}function Xg(){const h=j.useContext(Pe);if(!h)throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");return h.getMessages()}function Qg(){const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let f="";for(let i=0;i<16;i++)f+=h.charAt(Math.floor(Math.random()*h.length));return f}function Vg(h,f,i,p,_,v,S,E,C,M,I){return{threadId:h,threads:f.filter(P=>P.status==="regular").map(P=>({id:P.threadId,threadId:P.threadId,title:P.title||`Chat ${P.threadId}`,status:P.status})),archivedThreads:f.filter(P=>P.status==="archived").map(P=>({id:P.threadId,threadId:P.threadId,title:P.title||`Archived Chat ${P.threadId}`,status:P.status})),onSwitchToNewThread:()=>{const P=Qg();I==null||I.debug("Creating new thread:",P);const T={threadId:P,status:"regular",title:"New Chat"};p(F=>[T,...F]),i(P),v==null||v(P)},onSwitchToThread:P=>{I==null||I.debug("Switching to thread:",P),i(P),S==null||S(P)},onArchive:P=>{I==null||I.debug("Archiving thread:",P),p(T=>T.map(F=>F.threadId===P?{...F,status:"archived"}:F)),E==null||E(P)},onUnarchive:P=>{I==null||I.debug("Unarchiving thread:",P),p(T=>T.map(F=>F.threadId===P?{...F,status:"regular"}:F)),C==null||C(P)},onDelete:async P=>{if(I==null||I.debug("Deleting thread:",P),p(T=>T.filter(F=>F.threadId!==P)),h===P){const T=f.filter(F=>F.threadId!==P&&F.status==="regular");T.length>0&&i(T[0].threadId)}_.remove(P).then(()=>I==null?void 0:I.debug("Thread deleted from backend")).catch(T=>I==null?void 0:I.error("Failed to delete thread:",T)),M==null||M(P)}}}class Oo{constructor(f){D(this,"endpoint");D(this,"apiKey");D(this,"pageSize");D(this,"logger");this.endpoint=f.endpoint.replace(/\/$/,""),this.apiKey=f.apiKey,this.pageSize=f.pageSize??200,this.logger=f.logger}buildHeaders(){const f={"Content-Type":"application/json"};return this.apiKey&&(f["x-persona-apikey"]=this.apiKey),f}async sync(f){var p,_;if(!f)return[];const i=`${this.endpoint}/sessions/${encodeURIComponent(String(f))}/messages?page=1&size=${this.pageSize}`;try{const v=await fetch(i,{method:"GET",headers:this.buildHeaders()});if(!v.ok)return(p=this.logger)==null||p.warn("PersonaSessionStorage: failed to fetch messages",v.status,await v.text()),[];const S=await v.json();return Array.isArray(S.items)?S.items.map(C=>({id:C.id??C.messageId??void 0,protocol:C.protocol,thought:C.thought,text:C.text??"",image:C.image,type:C.type??"text",role:C.role??"assistant",file:C.file,sources:C.sources,sessionId:C.sessionId??f,finishReason:C.finishReason,functionCalls:C.functionCalls,functionResponse:C.functionResponse,status:C.status,createdAt:C.createdAt?new Date(C.createdAt):void 0,metadata:C.metadata})):[]}catch(v){return(_=this.logger)==null||_.warn("PersonaSessionStorage: error fetching messages",v),[]}}async remove(f){var p,_;if(!f)return;const i=`${this.endpoint}/sessions/${encodeURIComponent(String(f))}`;try{const v=await fetch(i,{method:"DELETE",headers:this.buildHeaders()});if(!v.ok){const S=await v.text();throw(p=this.logger)==null||p.warn("PersonaSessionStorage: failed to delete session",v.status,S),new Error(`Failed to delete session: ${v.status}`)}return}catch(v){throw(_=this.logger)==null||_.warn("PersonaSessionStorage: error deleting session",v),v}}async clearAll(){return Promise.reject(new Error("PersonaAPIMessageStorage: clearAll not supported"))}async list(f,i){var v,S;const p=new URLSearchParams({page:"1",size:"100"});i&&p.set("userId",i),f&&p.set("agentId",f);const _=`${this.endpoint}/sessions?${p.toString()}`;try{const E=await fetch(_,{method:"GET",headers:this.buildHeaders()});if(!E.ok)return(v=this.logger)==null||v.warn("PersonaSessionStorage: failed to list sessions",E.status),[];const C=await E.json();return Array.isArray(C.items)?C.items.map(I=>({threadId:I.code||I.id,title:I.title||`Session ${I.code||I.id}`,status:I.status==="archived"?"archived":"regular"})):[]}catch(E){return(S=this.logger)==null||S.warn("PersonaSessionStorage: error listing sessions",E),[]}}}function jg({dev:h=!1,baseUrl:f,protocols:i,logger:p,children:_,session:v="new",transformMessages:S,threads:E=!1,sessionStorage:C,onThreadCreate:M,onThreadSwitch:I,onThreadRename:P,onThreadArchive:T,onThreadUnarchive:F,onThreadDelete:J,...q}){const[_t,Pt]=j.useState(!1),[Vt,st]=j.useState([]),[Pn,zt]=j.useState(new Map),gn=j.useRef(!1),xt=j.useRef(!1),Dt=j.useMemo(()=>C||new Oo({apiKey:q.apiKey,endpoint:f||"https://persona.applica.guru/api"}),[C,f,q.apiKey]),[Bn,Re]=j.useState([]),[Rt,Ie]=j.useState(""),Mn=j.useRef(typeof v=="string"?v:"new"),re=j.useRef(!1);j.useEffect(()=>{!E||re.current||(re.current=!0,Dt.list(q.agentId,q.userId).then(X=>{(X==null?void 0:X.length)>0&&(Re(X),Ie(X[0].threadId))}).catch(X=>p==null?void 0:p.error("Failed to load threads:",X)))},[E,Dt,q.agentId,q.userId,p]);const ft=j.useMemo(()=>Wg(i,{dev:h||!1,baseUrl:f,apiKey:q.apiKey,agentId:q.agentId,userId:q.userId,tools:q.tools,logger:p}),[i,h,f,q.apiKey,q.agentId,q.userId,q.tools,p]);j.useEffect(()=>{gn.current||(gn.current=!0,p==null||p.debug("Setting up protocols:",ft.map(X=>X.getName())),ft.forEach(X=>{X.setSession(Mn.current),X.clearListeners(),X.addStatusChangeListener(ct=>{p==null||p.debug(`${X.getName()} status: ${ct}`),zt(Ht=>{const Rn=new Map(Ht);return Rn.set(X.getName(),ct),Rn}),ct==="connected"&&!xt.current&&(q.context&&X.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:q.context}}).catch(()=>{}),q.tools&&Array.isArray(q.tools)&&X.sendPacket({type:"command",payload:{command:"set_local_tools",arguments:{tools:q.tools.map(Ht=>Ht.schema)}}}).catch(()=>{}))}),X.addPacketListener(Ug(X,st,Pt,ft,S)),X.autostart&&X.status==="disconnected"&&(p==null||p.debug(`Auto-connecting protocol: ${X.getName()}`),X.connect(Mn.current).catch(()=>{}),Pt(!1))}))},[]),j.useEffect(()=>{if(!E||!Rt){st([]);return}if(xt.current||Rt===Mn.current)return;xt.current=!0,p==null||p.info("Switching to thread:",Rt),(async()=>{try{const ct=ft.filter(vt=>vt.status==="connected");ct.length>0&&await Promise.allSettled(ct.map(vt=>vt.disconnect())),Mn.current=Rt,await Promise.allSettled(ft.map(vt=>vt.setSession(Rt)));const Ht=await Dt.sync(Rt),Rn=ee(Ht);st(S?S(Rn):Rn),p==null||p.debug(`Loaded ${Ht.length} messages for thread ${Rt}`);const _n=ft.filter(vt=>vt.autostart);_n.length>0&&await Promise.allSettled(_n.map(vt=>vt.connect(Rt)))}catch(ct){p==null||p.error("Failed to switch thread:",ct),st([])}finally{xt.current=!1}})()},[Rt,E,ft,Dt,S,p]);const br=j.useCallback(kg(ft,st,Pt,S,p),[ft,S,p]),rn=j.useCallback(zg(ft,Vt,st,Pt,S,p),[ft,Vt,S,p]),jt=j.useCallback(Hg(ft,Vt,st,Pt,S,p),[ft,Vt,S,p]),Cr=j.useCallback(Gg(ft,st,Pt,S),[ft,S]),$n=j.useCallback(X=>{const ct=ee([...X]);st(S?S(ct):ct)},[S]),Ft=j.useCallback(()=>Vt,[Vt]),Ee=j.useMemo(()=>{if(E)return Vg(Rt,Bn,Ie,Re,Dt,M,I,T,F,J,p)},[E,Rt,Bn,Dt,M,I,T,F,J,p]),Pr=xr.useExternalStoreRuntime({isRunning:_t,messages:Vt,convertMessage:Pg,setMessages:$n,onNew:br,onEdit:rn,onCancel:Cr,onReload:jt,adapters:{attachments:new xr.CompositeAttachmentAdapter([new xr.SimpleImageAttachmentAdapter]),...Ee?{threadList:Ee}:{}}});return Zi.jsx(Pe.Provider,{value:{protocols:ft,protocolsStatus:Pn,getMessages:Ft},children:Zi.jsx(xr.AssistantRuntimeProvider,{runtime:Pr,children:_})})}function t_({children:h,...f}){return Zi.jsx(jg,{...f,children:h})}class n_{constructor(){D(this,"prefix","[Persona]")}log(f,...i){console.log(`${this.prefix} - ${f}`,...i)}info(f,...i){console.info(`${this.prefix} - ${f}`,...i)}warn(f,...i){console.warn(`${this.prefix} - ${f}`,...i)}error(f,...i){console.error(`${this.prefix} - ${f}`,...i)}debug(f,...i){console.debug(`${this.prefix} - ${f}`,...i)}}function Un(h,f,i){return{type:h,description:f,...i}}function Wo(h){const f=Object.entries(h.parameters).filter(([i,p])=>p.required).map(([i])=>i);return{type:"local",name:h.name,description:h.description,config:{timeout:h.timeout||60,parameters:{type:"object",title:h.title||`${h.name} parameters`,required:f,properties:h.parameters},output:{type:"object",title:`${h.name} output`,properties:h.output}}}}function Ar(h){return{schema:Wo(h),implementation:h.implementation}}function Do(h,f,i,p,_,v){const S={name:h,description:f,title:v==null?void 0:v.title,timeout:v==null?void 0:v.timeout,parameters:p,output:_,implementation:i};return Ar(S)}const e_=Do("sum","Sum two numbers",function(f,i){return{result:f+i}},{a:Un("number","First number to sum",{required:!0}),b:Un("number","Second number to sum",{required:!0})},{result:Un("number","Sum of two numbers")}),r_=Ar({name:"navigate_to",description:"Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that",title:"Sum two numbers",timeout:60,parameters:{a:Un("number","First number to sum"),b:Un("number","Seconth number to sum")},output:{result:Un("number","Sum of two numbers")},implementation:function(f,i){return{result:f+i}}});function i_(h){const f=[],i={};return h.forEach(p=>{const{schema:_,implementation:v}=Ar(p);f.push(_),i[p.name]=v}),{schemas:f,implementations:i}}function u_(h,f){const{required:i,properties:p}=f.config.parameters;for(const _ of i)if(!(_ in h))throw new Error(`Missing required parameter: ${_}`);for(const[_,v]of Object.entries(h)){const S=p[_];if(S){if(S.type==="number"&&typeof v!="number")throw new Error(`Parameter ${_} should be a number`);if(S.type==="string"&&typeof v!="string")throw new Error(`Parameter ${_} should be a string`);if(S.type==="boolean"&&typeof v!="boolean")throw new Error(`Parameter ${_} should be a boolean`)}}return!0}exports.PersonaConsoleLogger=n_;exports.PersonaProtocolBase=Ce;exports.PersonaRESTProtocol=Yi;exports.PersonaRuntimeProvider=t_;exports.PersonaSessionStorage=Oo;exports.PersonaTransactionProtocol=To;exports.PersonaWebRTCProtocol=Qi;exports.PersonaWebSocketProtocol=Xi;exports.createParameter=Un;exports.createTool=Ar;exports.createToolFromFunction=Do;exports.createToolRegistry=i_;exports.generateToolSchema=Wo;exports.navigateToToolExample=r_;exports.sumTool=e_;exports.usePersonaRuntime=Jg;exports.usePersonaRuntimeEndpoint=Zg;exports.usePersonaRuntimeMessages=Xg;exports.usePersonaRuntimeProtocol=Lo;exports.usePersonaRuntimeWebRTCProtocol=Yg;exports.validateToolParameters=u_;
28
28
  //# sourceMappingURL=bundle.cjs.js.map