webdaemon 26.4.0 → 27.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,34 +1,39 @@
1
- async function Nt(n,t=0){let e=new TextEncoder().encode(n);if(!crypto.subtle)throw"Requires secure origin (localhost or https:)";let o=await crypto.subtle.digest("SHA-1",e),r=new Uint8Array(o),s=String.fromCodePoint(...r),a=btoa(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return t?a.substring(0,t):a}async function Me(n,t=0){let e=new TextEncoder().encode(n);if(!crypto.subtle)throw"Requires secure origin (localhost or https:)";let o=await crypto.subtle.digest("SHA-1",e),s=Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("");return t?s.substring(0,t):s}async function k(n){return typeof n=="string"&&(n=new URL(n)),await Nt(String(n),8)}var E={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},tt=/https?:\/\/[^\/]+$/,It=/^\/issuer\/[a-f0-9]{32}$/,Mt=1e3*30,g=class n{static Source={PARTY_CONTROL:"party:control"};static Counterparty={PUBLIC:"public"};static Capability={OPEN:"open",CLOSE:"close",GRANT:"grant",REVOKE:"revoke",OFFER:"offer",RETRACT:"retract",DELETE:"delete",CATALOG:"catalog",ALIAS:"alias",UNALIAS:"unalias",GET_ITEM:"getitem",SET_ITEM:"setitem",ALERT:"alert",LOG:"log",CHAT:"chat",READ_MEMORY:"read_memory",WRITE_MEMORY:"write_memory",READ:"read",WRITE:"write"};static DEFAULT_EXPIRY_MILLIS=1e3*60*60*24;static TOKEN_HEADER="x-tabserver-token";static SCOPE_SEPARATOR=/[\s,;\|]+/;static#t=1e3*60;static#e=2048;static#o=new Map;static#s=new Map;#n=null;#r=null;#l;#h;#u;#a;constructor(t){let e=null;if(typeof t=="object")e=t;else if(typeof t=="string")try{e=JSON.parse(atob(t))}catch{throw"Invalid token format"}else throw`Cannot construct token from ${typeof t}`;this.#r=e.sig,delete e.sig,this.#n=e;let{iss:o,aud:r,sub:s,src:i,scope:a,iat:l,exp:c}=e;if(!o||!r||!s||!i||!a||!l||!c)throw"Token must include iss, aud, sub, src, scope, iat and exp";if(!r.match(tt)||!s.match(tt))throw"The aud and sub attributes must be origins";if(this.#l=new URL(r),this.#h=new URL(s),this.#u=new URL(i),this.#u.hash)throw"The src attribute must have no fragment component.";this.#n=e}async signWith(t){if(this.#n==null)throw"No payload to sign";let e=await t,o=await crypto.subtle.importKey("jwk",e,E,!0,["sign"]),r=JSON.stringify(this.#n),s=new TextEncoder().encode(r).buffer,i=new Uint8Array(s),a=await crypto.subtle.sign(E,o,i),l=n.bytesToBase64(new Uint8Array(a));return this.#r=l,l}async verifySignatory(){let t=String(this.getIssuer()),{signatory:e,publicKey:o}=await n.#i(t);this.#a=e,this.#f(),await this.#p(o)}async fetchSignatory(){let t=String(this.getIssuer());this.#a=await n.#m(t),this.#f()}async checkSignature(t){if(!this.#n||!this.#r)throw"checkSignature: no payload or signatureBase64";let e=await t,o=await n.#T(e,String(this.getIssuer()));await this.#p(o)}async#p(t){if(!this.#n||!this.#r)throw"checkSignature: no payload or signatureBase64";let e=JSON.stringify(this.#n),o=new TextEncoder().encode(e),r=n.base64ToBytes(this.#r);if(!await crypto.subtle.verify(E,t,r,o))throw`Signature rejected by issuer ${this.getIssuer()}`}#f(){if(!this.#a)throw"validateSignatory: no signatory";let t=this.#a.src,e=this.getSrc(),o=this.getIssuer();if(o.origin!==this.getSub())throw`Token issuer origin '${o.origin}' should be token sub '${this.getSub()}'`;if(e===n.Source.PARTY_CONTROL){if(t!==n.Source.PARTY_CONTROL)throw`Token src '${e}' cannot be signed by signatory src '${t}'`}else if(this.#u.protocol==="http:"||this.#u.protocol==="https:"){if(t!==e&&t!==n.Source.PARTY_CONTROL)throw`Token src '${e}' cannot be signed by signatory src '${t}'`}else throw`Unsupported token src '${e}'`;if(t===n.Source.PARTY_CONTROL){if(!o.pathname.startsWith("/device/"))throw`Party control signatory issuer path '${o.pathname}' must start with /device/`;return}let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")throw`Invalid signatory src '${t}'`;if(!It.test(o.pathname))throw`App signatory issuer path '${o.pathname}' must match /issuer/<appId>`}static async#i(t){let e=n.#y(t);if(e)return e;let o=n.#s.get(t);if(o)return await o;let r=(async()=>{let s=await n.#m(t),i=await n.#T(s.jwk,t),a={signatory:s,publicKey:i,expiresAt:Date.now()+n.#t};return n.#w(t,a),a})();n.#s.set(t,r);try{return await r}finally{n.#s.delete(t)}}static#y(t){let e=n.#o.get(t);return e?e.expiresAt<=Date.now()?(n.#o.delete(t),null):(n.#o.delete(t),n.#o.set(t,e),e):null}static#w(t,e){for(n.#o.has(t)&&n.#o.delete(t),n.#o.set(t,e);n.#o.size>n.#e;){let o=n.#o.keys().next().value;if(!o)break;console.log("Evicting token signatory cache entry due max size",{issuer:t,entryExpiresAt:e.expiresAt,cacheMaxEntries:n.#e}),n.#o.delete(o)}}static async#m(t){try{let o=await(await fetch(t,{headers:{"content-type":"application/json"}})).json();if("error"in o)throw o.error;let r=o.ok;if(!r||typeof r!="object"||!r.jwk||typeof r.jwk!="object")throw"Invalid signatory response";if(typeof r.src!="string")throw"Invalid signatory src";return r}catch(e){throw`Failed to read signatory at ${t}: ${e}`}}static async#T(t,e){if(!t||typeof t!="object"||"error"in t)throw`Missing or invalid public JWK at issuer ${e}`;try{return await crypto.subtle.importKey("jwk",t,E,!0,["verify"])}catch{throw`Missing or invalid public JWK at issuer ${e}`}}getSignedPayload(){if(!this.#r||!this.#n)throw"getSignedPayload: no signatureBase64 or payload";return{...this.#n,sig:this.#r}}getPayload(){if(!this.#n)throw"getPayload: no payload";return this.#n}getAud(){return this.#l.origin}getParty(){return this.#l.host}getSub(){return this.#h.origin}getSrc(){return String(this.#u)}getCounterparty(){return this.#h.host}getSignatorySrc(){if(!this.#a)throw"getSignatorySrc: no signatory";return this.#a.src}getSourceUrl(){return this.#u}getIssuer(){return new URL(this.getPayload().iss)}getSources(){if(!this.#n)throw"getSources: no payload";let t=[];for(let e in this.#n.scope)t.push(e);return t}getCapabilities(t){if(!this.#n)throw"getCapabilities: no payload";let e=this.#n.scope;if(!(t in e))throw`Source '${t}' not in scope`;return e[t].split(n.SCOPE_SEPARATOR)}hasCapability(t,e){return this.getCapabilities(t).includes(e)}checkPeriod(){if(!this.#n)throw"checkPeriod: no payload";let{iat:t,exp:e}=this.#n,o=Date.now();if(o<t-Mt)throw"Token is not yet valid";if(o>e)throw"Token has expired"}asSignedBase64(){return btoa(JSON.stringify(this.getSignedPayload()))}static bytesToBase64(t){let e=Array.from(t,o=>String.fromCodePoint(o)).join("");return btoa(e)}static base64ToBytes(t){let e=atob(t);return Uint8Array.from(e,o=>o.codePointAt(0)??0)}static from(t){let e=t.headers.get(n.TOKEN_HEADER);return e?new n(e):null}static toSearchString(t){let e=new URLSearchParams;for(let o in t){let s=t[o].asSignedBase64();e.append(o,s)}return e.toString()}};var Jt=/^[\w\-.:]+(?:\/[\w\-.:]+)*$/,$t=/^[\w\-.:%_]+(?:\/[\w\-.:%_]+)*$/,C=class{#t;constructor(t){this.#t=t}getItem(t){return Dt(this.#t,t)}getItemsLike(t){return Gt(this.#t,t)}setItem(t,e){return jt(this.#t,t,e)}removeItem(t){return Ft(this.#t,t)}};function B(n){if(n.match(Jt)==null)throw`DaemonStorage: Invalid key: '${n}`}function Ut(n){if(n.match($t)==null)throw`DaemonStorage: Invalid like key: ${n}`}function Lt(n){try{return JSON.stringify(n)}catch{throw"DaemonStorage: Invalid value"}}async function jt(n,t,e){B(t);let o=Lt(e),r=`${n.getAud()}/storage/${t}`;return(await fetch(r,{method:"PUT",headers:{"X-Tabserver-Token":n.asSignedBase64(),"Content-Type":"application/json"},body:o})).json()}async function Dt(n,t){B(t);let e=`${n.getAud()}/storage/${t}`;return(await fetch(e,{method:"GET",headers:{"X-Tabserver-Token":n.asSignedBase64()}})).json()}async function Gt(n,t){Ut(t);let e=new URL(`${n.getAud()}/storage`);return e.searchParams.append("like",t),await(await fetch(e,{method:"GET",headers:{"X-Tabserver-Token":n.asSignedBase64()}})).json()}async function Ft(n,t){B(t);let e=`${n.getAud()}/storage/${t}`;return(await fetch(e,{method:"DELETE",headers:{"X-Tabserver-Token":n.asSignedBase64()}})).json()}var et={Ash:"\xE6",Hash:"#"},_t={Ash:encodeURIComponent("\xE6")},N=class{params=new URLSearchParams;extractHash(t){t=t.startsWith(et.Hash)?t.substring(1):t;let e=t.indexOf(_t.Ash);if(e===-1)return t;let o=new URLSearchParams(t.slice(e));return this.extract(o),t.slice(0,e)}extractQuery(t){let e=new URLSearchParams(t);return this.extract(e),e.toString()}extract(t){let e=Array.from(t.keys());for(let o of e)o.startsWith(et.Ash)&&(this.params.set(o.substring(1),t.get(o)??""),t.delete(o))}getParams(){return this.params}};var I="party",ot="prefix",Kt="lastKnownDaemon",y=class n{static#t;#e;#o;#s;#n;static async getInstance(t=void 0){if(!t&&!n.#t)throw"Must provide app name";if(t&&n.#t&&t!==n.#t.#e)throw`Cannot change app name from ${n.#t.#e} to ${t}`;if(t&&!n.#t&&(n.#t=new n(t),await n.#t.init()),!n.#t)throw"No instance of BrowserApp";return n.#t}constructor(t){this.#e=t,this.#o=`${t}Party`,this.#s=`${t}Tokens`,this.#n=`${t}AppUrl`}async init(){let t=new URL(globalThis.location.href),e=new N,o=e.extractHash(t.hash),r=e.extractQuery(t.search),s=e.getParams();if(s.has(I)){sessionStorage[this.#s]=s.toString();let i=this.getToken();await i.verifySignatory(),sessionStorage[this.#o]=i.getParty(),localStorage.setItem(Kt,i.getParty());let a=i.getSourceUrl();if(a.origin!==t.origin||a.pathname!==t.pathname||a.search!==t.search)throw`Party token is for different app: ${a}`}return t.hash=o,t.search=r,(s.has(I)||sessionStorage[this.#n]===void 0)&&(sessionStorage[this.#n]=t.toString()),globalThis.history.replaceState(null,"",t.toString()),this}isOrphan(){return sessionStorage[this.#o]===void 0||sessionStorage[this.#s]===void 0}getAppName(){return this.#e}getAppUrl(){return sessionStorage[this.#n]}getParty(){return sessionStorage[this.#o]}getPartyOrigin(){return`${globalThis.location.protocol}//${this.getParty()}`}getDefaultPrefix(t=null){t||(t=this.getAppUrl());let e=new URL(t);return e.hash="",k(e)}getPrefix(){return this.hasParam(ot)?Promise.resolve(this.getParam(ot)??""):this.getDefaultPrefix()}async getAgentUrl(t){let e=this.getPartyOrigin(),o=await this.getPrefix(),r=`${e}/tab/${o}`;return t?`${r}/${t}`:r}async getAgentEndpoint(t){let{party:e=this.getParty(),appUrl:o=this.getAppUrl(),prefix:r=await this.getDefaultPrefix(o),tab:s}=t,a=`${new URL(o).protocol}//${e}/tab/${r}`;return s?`${a}/${s}`:a}getTokenBase64(t=I){let e=sessionStorage[this.#s],r=new URLSearchParams(e).get(t);if(!r)throw`No token for ${t}, check 'audience' in YML`;return r}getToken(t=I){let e=this.getTokenBase64(t);return new g(e)}getParam(t){let e=new URL(globalThis.location.href).searchParams;for(let[r,s]of e)if(t.toLowerCase()==r.toLowerCase())return s;return document.querySelector("link[rel=webdaemon]")?.getAttribute(t)??null}hasParam(t){return new URL(globalThis.location.href).searchParams.has(t)?!0:document.querySelector("link[rel=webdaemon]")?.hasAttribute(t)??!1}async getLaunchAlert(){let t=this.getPartyOrigin(),e=new URL(`${t}/catalog`);e.searchParams.append("alert","");let r=await(await fetch(e,{headers:{"X-Tabserver-Token":this.getTokenBase64(),Accept:"application/json"}})).json();if("error"in r)throw r.error;return r.ok.alert.find(i=>i.type=="LAUNCH"&&i.sourceUrl==new URL(this.getAppUrl()))||null}async resolveLaunchAlert(){let t=this.getPartyOrigin(),e=new URL(`${t}/resolve`),r=await(await fetch(e,{method:"POST",headers:{"X-Tabserver-Token":this.getTokenBase64(),"Content-Type":"application/json"},body:JSON.stringify({type:"LAUNCH",source:this.getAppUrl()})})).json();if("error"in r)throw r.error}async rejectLaunchAlert(){let t=this.getPartyOrigin(),e=new URL(`${t}/reject`),r=await(await fetch(e,{method:"POST",headers:{"X-Tabserver-Token":this.getTokenBase64(),"Content-Type":"application/json"},body:JSON.stringify({type:"LAUNCH",source:this.getAppUrl()})})).json();if("error"in r)throw r.error}getStorage(){return new C(this.getToken())}};var Bt="agent",M=class{#t=new Map;register(t,e,o){return this.#t.set(t,{descriptor:e,execute:o}),this}descriptors(){return[...this.#t.values()].map(t=>t.descriptor)}async executeToolCalls(t,e={}){let o=[];for(let r of t){let s=this.#t.get(r.name);if(!s){o.push({toolCallId:r.id,name:r.name,content:`No client tool named ${r.name}`,isError:!0});continue}try{let i=await s.execute(r.input||{},e);o.push({toolCallId:r.id,name:r.name,content:JSON.stringify(i)})}catch(i){o.push({toolCallId:r.id,name:r.name,content:String(i),isError:!0})}}return o}},nt=class{#t;#e;#o;#s=null;#n;constructor(t={}){this.#t=t.app,this.#e=t.appName,this.#o=t.agentTab??Bt,this.#n=t.clientTools??new M}get app(){return this.#t??null}get agentUrl(){return this.#s}get clientTools(){return this.#n}async init(){return this.#t??=await y.getInstance(this.#e),this.#t.isOrphan()||(this.#s=await this.#t.getAgentUrl(this.#o)),this}isOrphan(){return!!this.#t?.isOrphan()}getParty(){return this.#r().getParty()}listChats({targetParty:t}){return this.postAgent("/chats",{targetParty:t})}listModels({targetParty:t}){return this.postAgent("/models",{targetParty:t})}createSession(t){return this.postAgent("/session",{targetParty:t.targetParty,...t.chatId?{chatId:t.chatId}:{},systemPrompt:t.systemPrompt,temperature:t.temperature,...t.model?{model:t.model}:{},clientTools:this.#n.descriptors()})}async sendMessage(t){let e=t.onEvent,o=e?await this.postAgentStream("/send",{targetParty:t.targetParty,chatId:t.chatId,message:t.message,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails},e):await this.postAgent("/send",{targetParty:t.targetParty,chatId:t.chatId,message:t.message,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails});for(await t.onConversationResult?.(o);o.clientToolCalls?.length;){await t.onClientToolCalls?.(o.clientToolCalls);let r=await this.#n.executeToolCalls(o.clientToolCalls,{targetParty:t.targetParty});o=await this.sendClientToolResults({targetParty:t.targetParty,chatId:t.chatId,toolResults:r,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails,onEvent:e}),await t.onConversationResult?.(o)}return o}sendClientToolResults(t){let e={targetParty:t.targetParty,chatId:t.chatId,toolResults:t.toolResults,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails};return t.onEvent?this.postAgentStream("/client-tool-results",e,t.onEvent):this.postAgent("/client-tool-results",e)}closeChat({targetParty:t,chatId:e}){return this.postAgent("/close",{targetParty:t,chatId:e})}deleteChat({targetParty:t,chatId:e}){return this.postAgent("/delete",{targetParty:t,chatId:e})}async postAgent(t,e){if(!this.#s)throw"Agent URL is not available";let r=await(await fetch(`${this.#s}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-Tabserver-Token":this.#r().getTokenBase64()},body:JSON.stringify(e)})).json();if("error"in r)throw r.error;return r.ok}async postAgentStream(t,e,o){if(!this.#s)throw"Agent URL is not available";let r=await fetch(`${this.#s}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson","X-Tabserver-Token":this.#r().getTokenBase64()},body:JSON.stringify(e)});if(!r.body)throw"Streaming response has no body";let s={events:[]},i=async u=>{let h=u.trim();if(!h)return;let p=JSON.parse(h);if(p.type==="event")s.events?.push(p.event),await o?.(p.event);else if(p.type==="done")p.clientToolCalls?.length&&(s.clientToolCalls=p.clientToolCalls);else if(p.type==="error")throw p.message},a=r.body.getReader(),l=new TextDecoder,c="";for(;;){let{value:u,done:h}=await a.read();if(h)break;c+=l.decode(u,{stream:!0});let p;for(;(p=c.indexOf(`
2
- `))>=0;){let x=c.slice(0,p);c=c.slice(p+1),await i(x)}}return c+=l.decode(),await i(c),s}normalizeTargetParty(t){let e=String(t??"").trim();if(!e)throw"Daemon host is required";try{let o=e.includes("://")?new URL(e):new URL(`${globalThis.location.protocol}//${e}`);if(!o.host)throw"missing host";return o.host}catch{throw`Invalid daemon host: ${t}`}}#r(){if(!this.#t)throw"Browser app is not initialised";return this.#t}};function Be(n=void 0){let t=new M;return t.register("browser_daemon_identity",{type:"function",name:"browser_daemon_identity",execution:"client",description:"Get the active chat daemon and the counterparty it is talking to, derived from the browser launch token and active chat target.",parameters:{type:"object",properties:{},additionalProperties:!1}},async(e,o={})=>{let s=(n??await y.getInstance()).getToken(),i=o.targetParty||s.getParty();return{aud:o.targetAud||`${globalThis.location.protocol}//${i}`,sub:s.getSub(),party:i,counterparty:s.getCounterparty(),src:s.getSrc()}}),t.register("browser_language",{type:"function",name:"browser_language",execution:"client",description:"Get the browser language preferences for this page.",parameters:{type:"object",properties:{},additionalProperties:!1}},()=>({language:navigator.language,languages:Array.from(navigator.languages??[])})),t.register("browser_time",{type:"function",name:"browser_time",execution:"client",description:"Get the current timezone and local time from the browser.",parameters:{type:"object",properties:{},additionalProperties:!1}},()=>{let e=new Date,o=Intl.DateTimeFormat().resolvedOptions().timeZone;return{timeZone:o,isoTime:e.toISOString(),localTime:e.toLocaleString(void 0,{timeZone:o}),offsetMinutes:-e.getTimezoneOffset()}}),t}var Ht={name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},rt=class{#t;#e;constructor(t=Ht){if(this.#t=t,!crypto.subtle)throw"Crypto.subtle requires secure environment"}async generate(){this.#e=await crypto.subtle.generateKey(this.#t,!0,["sign","verify"])}async publicJwk(){if(!this.#e)throw"Must generate keypair";let t=this.#e.publicKey;return await crypto.subtle.exportKey("jwk",t)}async privateJwk(){if(!this.#e)throw"Must generate keypair";let t=this.#e.privateKey;return await crypto.subtle.exportKey("jwk",t)}async publicPem(){if(!this.#e)throw"Must generate keypair";let t=this.#e.publicKey,e=await crypto.subtle.exportKey("spki",t);return`-----BEGIN PUBLIC KEY-----
1
+ async function It(n,t=0){let e=new TextEncoder().encode(n);if(!crypto.subtle)throw"Requires secure origin (localhost or https:)";let o=await crypto.subtle.digest("SHA-1",e),r=new Uint8Array(o),s=String.fromCodePoint(...r),a=btoa(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return t?a.substring(0,t):a}async function je(n,t=0){let e=new TextEncoder().encode(n);if(!crypto.subtle)throw"Requires secure origin (localhost or https:)";let o=await crypto.subtle.digest("SHA-1",e),s=Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("");return t?s.substring(0,t):s}async function E(n){return typeof n=="string"&&(n=new URL(n)),await It(String(n),8)}var N={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},Q=/https?:\/\/[^\/]+$/,$t=/^\/issuer\/[a-f0-9]{32}$/,Mt=1e3*30,d=class n{static Source={PARTY_CONTROL:"party:control"};static Counterparty={PUBLIC:"public"};static Capability={OPEN:"open",CLOSE:"close",GRANT:"grant",REVOKE:"revoke",OFFER:"offer",RETRACT:"retract",DELETE:"delete",CATALOG:"catalog",ALIAS:"alias",UNALIAS:"unalias",GET_ITEM:"getitem",SET_ITEM:"setitem",ALERT:"alert",LOG:"log",CHAT:"chat",READ_MEMORY:"read_memory",WRITE_MEMORY:"write_memory",READ:"read",WRITE:"write"};static DEFAULT_EXPIRY_MILLIS=1e3*60*60*24;static TOKEN_HEADER="x-tabserver-token";static SCOPE_SEPARATOR=/[\s,;\|]+/;static#t=1e3*60;static#e=2048;static#n=new Map;static#s=new Map;#o=null;#r=null;#l;#p;#h;#a;constructor(t){let e=null;if(typeof t=="object")e=t;else if(typeof t=="string")try{e=JSON.parse(atob(t))}catch{throw"Invalid token format"}else throw`Cannot construct token from ${typeof t}`;this.#r=e.sig,delete e.sig,this.#o=e;let{iss:o,aud:r,sub:s,src:i,scope:a,iat:l,exp:c,pre:u}=e;if(!o||!r||!s||!i||!a||!l||!c)throw"Token must include iss, aud, sub, src, scope, iat and exp";if(u!==void 0){if(!Array.isArray(u))throw"The pre attribute must be an array of principals";for(let h of u)if(!h||typeof h.counterparty!="string"||typeof h.src!="string")throw"Each pre principal must have a counterparty and src"}if(!r.match(Q)||!s.match(Q))throw"The aud and sub attributes must be origins";if(this.#l=new URL(r),this.#p=new URL(s),this.#h=new URL(i),this.#h.hash)throw"The src attribute must have no fragment component.";this.#o=e}async signWith(t){if(this.#o==null)throw"No payload to sign";let e=await t,o=await crypto.subtle.importKey("jwk",e,N,!0,["sign"]),r=JSON.stringify(this.#o),s=new TextEncoder().encode(r).buffer,i=new Uint8Array(s),a=await crypto.subtle.sign(N,o,i),l=n.bytesToBase64(new Uint8Array(a));return this.#r=l,l}async verifySignatory(){let t=String(this.getIssuer()),{signatory:e,publicKey:o}=await n.#i(t);this.#a=e,this.#f(),await this.#u(o)}async fetchSignatory(){let t=String(this.getIssuer());this.#a=await n.#m(t),this.#f()}async checkSignature(t){if(!this.#o||!this.#r)throw"checkSignature: no payload or signatureBase64";let e=await t,o=await n.#T(e,String(this.getIssuer()));await this.#u(o)}async#u(t){if(!this.#o||!this.#r)throw"checkSignature: no payload or signatureBase64";let e=JSON.stringify(this.#o),o=new TextEncoder().encode(e),r=n.base64ToBytes(this.#r);if(!await crypto.subtle.verify(N,t,r,o))throw`Signature rejected by issuer ${this.getIssuer()}`}#f(){if(!this.#a)throw"validateSignatory: no signatory";let t=this.#a.src,e=this.getSrc(),o=this.getIssuer();if(o.origin!==this.getSub())throw`Token issuer origin '${o.origin}' should be token sub '${this.getSub()}'`;if(e===n.Source.PARTY_CONTROL){if(t!==n.Source.PARTY_CONTROL)throw`Token src '${e}' cannot be signed by signatory src '${t}'`}else if(this.#h.protocol==="http:"||this.#h.protocol==="https:"){if(t!==e&&t!==n.Source.PARTY_CONTROL)throw`Token src '${e}' cannot be signed by signatory src '${t}'`}else throw`Unsupported token src '${e}'`;if(t===n.Source.PARTY_CONTROL){if(!o.pathname.startsWith("/device/"))throw`Party control signatory issuer path '${o.pathname}' must start with /device/`;return}let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")throw`Invalid signatory src '${t}'`;if(!$t.test(o.pathname))throw`App signatory issuer path '${o.pathname}' must match /issuer/<appId>`}static async#i(t){let e=n.#y(t);if(e)return e;let o=n.#s.get(t);if(o)return await o;let r=(async()=>{let s=await n.#m(t),i=await n.#T(s.jwk,t),a={signatory:s,publicKey:i,expiresAt:Date.now()+n.#t};return n.#w(t,a),a})();n.#s.set(t,r);try{return await r}finally{n.#s.delete(t)}}static#y(t){let e=n.#n.get(t);return e?e.expiresAt<=Date.now()?(n.#n.delete(t),null):(n.#n.delete(t),n.#n.set(t,e),e):null}static#w(t,e){for(n.#n.has(t)&&n.#n.delete(t),n.#n.set(t,e);n.#n.size>n.#e;){let o=n.#n.keys().next().value;if(!o)break;console.log("Evicting token signatory cache entry due max size",{issuer:t,entryExpiresAt:e.expiresAt,cacheMaxEntries:n.#e}),n.#n.delete(o)}}static async#m(t){try{let o=await(await fetch(t,{headers:{"content-type":"application/json"}})).json();if("error"in o)throw o.error;let r=o.ok;if(!r||typeof r!="object"||!r.jwk||typeof r.jwk!="object")throw"Invalid signatory response";if(typeof r.src!="string")throw"Invalid signatory src";return r}catch(e){throw`Failed to read signatory at ${t}: ${e}`}}static async#T(t,e){if(!t||typeof t!="object"||"error"in t)throw`Missing or invalid public JWK at issuer ${e}`;try{return await crypto.subtle.importKey("jwk",t,N,!0,["verify"])}catch{throw`Missing or invalid public JWK at issuer ${e}`}}getSignedPayload(){if(!this.#r||!this.#o)throw"getSignedPayload: no signatureBase64 or payload";return{...this.#o,sig:this.#r}}getPayload(){if(!this.#o)throw"getPayload: no payload";return this.#o}getAud(){return this.#l.origin}getParty(){return this.#l.host}getSub(){return this.#p.origin}getSrc(){return String(this.#h)}getCounterparty(){return this.#p.host}getPre(){return this.#o?.pre??[]}getSignatorySrc(){if(!this.#a)throw"getSignatorySrc: no signatory";return this.#a.src}getSourceUrl(){return this.#h}getIssuer(){return new URL(this.getPayload().iss)}getSources(){if(!this.#o)throw"getSources: no payload";let t=[];for(let e in this.#o.scope)t.push(e);return t}getCapabilities(t){if(!this.#o)throw"getCapabilities: no payload";let e=this.#o.scope;if(!(t in e))throw`Source '${t}' not in scope`;return e[t].split(n.SCOPE_SEPARATOR)}hasCapability(t,e){return this.getCapabilities(t).includes(e)}checkPeriod(){if(!this.#o)throw"checkPeriod: no payload";let{iat:t,exp:e}=this.#o,o=Date.now();if(o<t-Mt)throw"Token is not yet valid";if(o>e)throw"Token has expired"}asSignedBase64(){return btoa(JSON.stringify(this.getSignedPayload()))}static bytesToBase64(t){let e=Array.from(t,o=>String.fromCodePoint(o)).join("");return btoa(e)}static base64ToBytes(t){let e=atob(t);return Uint8Array.from(e,o=>o.codePointAt(0)??0)}static from(t){let e=t.headers.get(n.TOKEN_HEADER);return e?new n(e):null}static toSearchString(t){let e=new URLSearchParams;for(let o in t){let s=t[o].asSignedBase64();e.append(o,s)}return e.toString()}};var Jt=/^[\w\-.:]+(?:\/[\w\-.:]+)*$/,Ut=/^[\w\-.:%_]+(?:\/[\w\-.:%_]+)*$/,P=class{#t;constructor(t){this.#t=t}getItem(t){return Gt(this.#t,t)}getItemsLike(t){return Ft(this.#t,t)}setItem(t,e){return Dt(this.#t,t,e)}removeItem(t){return Kt(this.#t,t)}};function V(n){if(n.match(Jt)==null)throw`DaemonStorage: Invalid key: '${n}`}function Lt(n){if(n.match(Ut)==null)throw`DaemonStorage: Invalid like key: ${n}`}function jt(n){try{return JSON.stringify(n)}catch{throw"DaemonStorage: Invalid value"}}async function Dt(n,t,e){V(t);let o=jt(e),r=`${n.getAud()}/storage/${t}`;return(await fetch(r,{method:"PUT",headers:{"X-Tabserver-Token":n.asSignedBase64(),"Content-Type":"application/json"},body:o})).json()}async function Gt(n,t){V(t);let e=`${n.getAud()}/storage/${t}`;return(await fetch(e,{method:"GET",headers:{"X-Tabserver-Token":n.asSignedBase64()}})).json()}async function Ft(n,t){Lt(t);let e=new URL(`${n.getAud()}/storage`);return e.searchParams.append("like",t),await(await fetch(e,{method:"GET",headers:{"X-Tabserver-Token":n.asSignedBase64()}})).json()}async function Kt(n,t){V(t);let e=`${n.getAud()}/storage/${t}`;return(await fetch(e,{method:"DELETE",headers:{"X-Tabserver-Token":n.asSignedBase64()}})).json()}var Z={Ash:"\xE6",Hash:"#"},Bt={Ash:encodeURIComponent("\xE6")},I=class{params=new URLSearchParams;extractHash(t){t=t.startsWith(Z.Hash)?t.substring(1):t;let e=t.indexOf(Bt.Ash);if(e===-1)return t;let o=new URLSearchParams(t.slice(e));return this.extract(o),t.slice(0,e)}extractQuery(t){let e=new URLSearchParams(t);return this.extract(e),e.toString()}extract(t){let e=Array.from(t.keys());for(let o of e)o.startsWith(Z.Ash)&&(this.params.set(o.substring(1),t.get(o)??""),t.delete(o))}getParams(){return this.params}};var $="party",tt="prefix",_t="lastKnownDaemon",R=class n{static#t;#e;#n;#s;#o;static async getInstance(t=void 0){if(!t&&!n.#t)throw"Must provide app name";if(t&&n.#t&&t!==n.#t.#e)throw`Cannot change app name from ${n.#t.#e} to ${t}`;if(t&&!n.#t&&(n.#t=new n(t),await n.#t.init()),!n.#t)throw"No instance of BrowserApp";return n.#t}constructor(t){this.#e=t,this.#n=`${t}Party`,this.#s=`${t}Tokens`,this.#o=`${t}AppUrl`}async init(){let t=new URL(globalThis.location.href),e=new I,o=e.extractHash(t.hash),r=e.extractQuery(t.search),s=e.getParams();if(s.has($)){sessionStorage[this.#s]=s.toString();let i=this.getToken();await i.verifySignatory(),sessionStorage[this.#n]=i.getParty(),localStorage.setItem(_t,i.getParty());let a=i.getSourceUrl();if(a.origin!==t.origin||a.pathname!==t.pathname||a.search!==t.search)throw`Party token is for different app: ${a}`}return t.hash=o,t.search=r,(s.has($)||sessionStorage[this.#o]===void 0)&&(sessionStorage[this.#o]=t.toString()),globalThis.history.replaceState(null,"",t.toString()),this}isOrphan(){return sessionStorage[this.#n]===void 0||sessionStorage[this.#s]===void 0}getAppName(){return this.#e}getAppUrl(){return sessionStorage[this.#o]}getParty(){return sessionStorage[this.#n]}getPartyOrigin(){return`${globalThis.location.protocol}//${this.getParty()}`}getDefaultPrefix(t=null){t||(t=this.getAppUrl());let e=new URL(t);return e.hash="",E(e)}getPrefix(){return this.hasParam(tt)?Promise.resolve(this.getParam(tt)??""):this.getDefaultPrefix()}async getAgentUrl(t){let e=this.getPartyOrigin(),o=await this.getPrefix(),r=`${e}/tab/${o}`;return t?`${r}/${t}`:r}async getAgentEndpoint(t){let{party:e=this.getParty(),appUrl:o=this.getAppUrl(),prefix:r=await this.getDefaultPrefix(o),tab:s}=t,a=`${new URL(o).protocol}//${e}/tab/${r}`;return s?`${a}/${s}`:a}getTokenBase64(t=$){let e=sessionStorage[this.#s],r=new URLSearchParams(e).get(t);if(!r)throw`No token for ${t}, check 'audience' in YML`;return r}getToken(t=$){let e=this.getTokenBase64(t);return new d(e)}getParam(t){let e=new URL(globalThis.location.href).searchParams;for(let[r,s]of e)if(t.toLowerCase()==r.toLowerCase())return s;return document.querySelector("link[rel=webdaemon]")?.getAttribute(t)??null}hasParam(t){return new URL(globalThis.location.href).searchParams.has(t)?!0:document.querySelector("link[rel=webdaemon]")?.hasAttribute(t)??!1}async getLaunchAlert(){let t=this.getPartyOrigin(),e=new URL(`${t}/catalog`);e.searchParams.append("alert","");let r=await(await fetch(e,{headers:{"X-Tabserver-Token":this.getTokenBase64(),Accept:"application/json"}})).json();if("error"in r)throw r.error;return r.ok.alert.find(i=>i.type=="LAUNCH"&&i.sourceUrl==new URL(this.getAppUrl()))||null}async resolveLaunchAlert(){let t=this.getPartyOrigin(),e=new URL(`${t}/resolve`),r=await(await fetch(e,{method:"POST",headers:{"X-Tabserver-Token":this.getTokenBase64(),"Content-Type":"application/json"},body:JSON.stringify({type:"LAUNCH",source:this.getAppUrl()})})).json();if("error"in r)throw r.error}async rejectLaunchAlert(){let t=this.getPartyOrigin(),e=new URL(`${t}/reject`),r=await(await fetch(e,{method:"POST",headers:{"X-Tabserver-Token":this.getTokenBase64(),"Content-Type":"application/json"},body:JSON.stringify({type:"LAUNCH",source:this.getAppUrl()})})).json();if("error"in r)throw r.error}getStorage(){return new P(this.getToken())}};var Vt="agent",M=class{#t=new Map;register(t,e,o){return this.#t.set(t,{descriptor:e,execute:o}),this}descriptors(){return[...this.#t.values()].map(t=>t.descriptor)}async executeToolCalls(t,e={}){let o=[];for(let r of t){let s=this.#t.get(r.name);if(!s){o.push({toolCallId:r.id,name:r.name,content:`No client tool named ${r.name}`,isError:!0});continue}try{let i=await s.execute(r.input||{},e);o.push({toolCallId:r.id,name:r.name,content:JSON.stringify(i)})}catch(i){o.push({toolCallId:r.id,name:r.name,content:String(i),isError:!0})}}return o}},et=class{#t;#e;#n;#s=null;#o;constructor(t={}){this.#t=t.app,this.#e=t.appName,this.#n=t.agentTab??Vt,this.#o=t.clientTools??new M}get app(){return this.#t??null}get agentUrl(){return this.#s}get clientTools(){return this.#o}async init(){return this.#t??=await R.getInstance(this.#e),this.#t.isOrphan()||(this.#s=await this.#t.getAgentUrl(this.#n)),this}isOrphan(){return!!this.#t?.isOrphan()}getParty(){return this.#r().getParty()}listChats({targetParty:t}){return this.postAgent("/chats",{targetParty:t})}listModels({targetParty:t}){return this.postAgent("/models",{targetParty:t})}createSession(t){return this.postAgent("/session",{targetParty:t.targetParty,...t.chatId?{chatId:t.chatId}:{},systemPrompt:t.systemPrompt,temperature:t.temperature,...t.model?{model:t.model}:{},clientTools:this.#o.descriptors()})}async sendMessage(t){let e=t.onEvent,o=e?await this.postAgentStream("/send",{targetParty:t.targetParty,chatId:t.chatId,message:t.message,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails},e):await this.postAgent("/send",{targetParty:t.targetParty,chatId:t.chatId,message:t.message,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails});for(await t.onConversationResult?.(o);o.clientToolCalls?.length;){await t.onClientToolCalls?.(o.clientToolCalls);let r=await this.#o.executeToolCalls(o.clientToolCalls,{targetParty:t.targetParty});o=await this.sendClientToolResults({targetParty:t.targetParty,chatId:t.chatId,toolResults:r,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails,onEvent:e}),await t.onConversationResult?.(o)}return o}sendClientToolResults(t){let e={targetParty:t.targetParty,chatId:t.chatId,toolResults:t.toolResults,temperature:t.temperature,toolsEnabled:t.toolsEnabled,toolDetails:t.toolDetails};return t.onEvent?this.postAgentStream("/client-tool-results",e,t.onEvent):this.postAgent("/client-tool-results",e)}closeChat({targetParty:t,chatId:e}){return this.postAgent("/close",{targetParty:t,chatId:e})}deleteChat({targetParty:t,chatId:e}){return this.postAgent("/delete",{targetParty:t,chatId:e})}async postAgent(t,e){if(!this.#s)throw"Agent URL is not available";let r=await(await fetch(`${this.#s}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-Tabserver-Token":this.#r().getTokenBase64()},body:JSON.stringify(e)})).json();if("error"in r)throw r.error;return r.ok}async postAgentStream(t,e,o){if(!this.#s)throw"Agent URL is not available";let r=await fetch(`${this.#s}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson","X-Tabserver-Token":this.#r().getTokenBase64()},body:JSON.stringify(e)});if(!r.body)throw"Streaming response has no body";let s={events:[]},i=async u=>{let h=u.trim();if(!h)return;let p=JSON.parse(h);if(p.type==="event")s.events?.push(p.event),await o?.(p.event);else if(p.type==="done")p.clientToolCalls?.length&&(s.clientToolCalls=p.clientToolCalls);else if(p.type==="error")throw p.message},a=r.body.getReader(),l=new TextDecoder,c="";for(;;){let{value:u,done:h}=await a.read();if(h)break;c+=l.decode(u,{stream:!0});let p;for(;(p=c.indexOf(`
2
+ `))>=0;){let y=c.slice(0,p);c=c.slice(p+1),await i(y)}}return c+=l.decode(),await i(c),s}normalizeTargetParty(t){let e=String(t??"").trim();if(!e)throw"Daemon host is required";try{let o=e.includes("://")?new URL(e):new URL(`${globalThis.location.protocol}//${e}`);if(!o.host)throw"missing host";return o.host}catch{throw`Invalid daemon host: ${t}`}}#r(){if(!this.#t)throw"Browser app is not initialised";return this.#t}};function qe(n=void 0){let t=new M;return t.register("browser_daemon_identity",{type:"function",name:"browser_daemon_identity",execution:"client",description:"Get the active chat daemon and the counterparty it is talking to, derived from the browser launch token and active chat target.",parameters:{type:"object",properties:{},additionalProperties:!1}},async(e,o={})=>{let s=(n??await R.getInstance()).getToken(),i=o.targetParty||s.getParty();return{aud:o.targetAud||`${globalThis.location.protocol}//${i}`,sub:s.getSub(),party:i,counterparty:s.getCounterparty(),src:s.getSrc()}}),t.register("browser_language",{type:"function",name:"browser_language",execution:"client",description:"Get the browser language preferences for this page.",parameters:{type:"object",properties:{},additionalProperties:!1}},()=>({language:navigator.language,languages:Array.from(navigator.languages??[])})),t.register("browser_time",{type:"function",name:"browser_time",execution:"client",description:"Get the current timezone and local time from the browser.",parameters:{type:"object",properties:{},additionalProperties:!1}},()=>{let e=new Date,o=Intl.DateTimeFormat().resolvedOptions().timeZone;return{timeZone:o,isoTime:e.toISOString(),localTime:e.toLocaleString(void 0,{timeZone:o}),offsetMinutes:-e.getTimezoneOffset()}}),t}var Ht={name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},nt=class{#t;#e;constructor(t=Ht){if(this.#t=t,!crypto.subtle)throw"Crypto.subtle requires secure environment"}async generate(){this.#e=await crypto.subtle.generateKey(this.#t,!0,["sign","verify"])}async publicJwk(){if(!this.#e)throw"Must generate keypair";let t=this.#e.publicKey;return await crypto.subtle.exportKey("jwk",t)}async privateJwk(){if(!this.#e)throw"Must generate keypair";let t=this.#e.privateKey;return await crypto.subtle.exportKey("jwk",t)}async publicPem(){if(!this.#e)throw"Must generate keypair";let t=this.#e.publicKey,e=await crypto.subtle.exportKey("spki",t);return`-----BEGIN PUBLIC KEY-----
3
3
  ${btoa(String.fromCharCode(...new Uint8Array(e))).match(/.{1,64}/g)?.join(`
4
4
  `)??""}
5
5
  -----END PUBLIC KEY-----`}async privatePem(){if(!this.#e)throw"Must generate keypair";let t=this.#e.privateKey,e=await crypto.subtle.exportKey("pkcs8",t);return`-----BEGIN PRIVATE KEY-----
6
6
  ${btoa(String.fromCharCode(...new Uint8Array(e))).match(/.{1,64}/g)?.join(`
7
7
  `)??""}
8
- -----END PRIVATE KEY-----`}};async function We(){let n=await y.getInstance(),t=n.getPartyOrigin(),e=new URL(`${t}/catalog`);e.searchParams.append("alert","");let r=await(await fetch(e,{headers:{"X-Tabserver-Token":n.getTokenBase64(),Accept:"application/json"}})).json();if("error"in r)throw r.error;return r.ok.alert.find(i=>i.type=="LAUNCH"&&i.sourceUrl==new URL(n.getAppUrl()))||null}var st=class{#t;#e;#o;#s;#n;#r;#l;async initWithKey(t,e,o,r){this.#e=e.startsWith("https:")?"https:":"http:",this.#o=t,this.#n=e,this.#t=o,this.#s=r,await this.#h()}async checkActivate(){if(!this.#r)throw"checkActivate: No token";let t=new URL(`${this.#r.getAud()}/activate`),e=this.#r.asSignedBase64(),o={},r;try{r=await fetch(t,{method:"POST",headers:{"x-tabserver-token":e,"content-type":"application/json"},body:JSON.stringify(o)});let{ok:s,error:i}=await r.json();if(i)throw i;return!!s.isNew}catch(s){throw console.error(s),`Cannot activate ${this.#r.getParty()}`}}async makeOffer(t,e=null){let{type:o="TRANSIENT",ttl:r=300,expiry:s=30,payload:i}=e??{};if(!this.#r)throw"makeOffer: No token";let a=new URL(`${this.#r.getAud()}/offer`),l=this.#r.asSignedBase64(),c={role:"party",type:o,ttl:r,description:`Offered by ${this.#r.getCounterparty()}`,payload:i,expiry:new Date(Date.now()+1e3*s),flow:t},h=await(await fetch(a,{method:"POST",headers:{"x-tabserver-token":l,"content-type":"application/json"},body:JSON.stringify(c)})).json();if("error"in h)throw h.error;let{claimCode:p,_checkState:x}=h.ok;return this.#l=p,h.ok}async checkState(){if(!this.#r||!this.#l)throw"checkState: No token or claimCode";let t=new URL(`${this.#r.getAud()}/offer/check`);t.searchParams.append("claimCode",this.#l);let e=this.#r.asSignedBase64(),r=await(await fetch(t,{headers:{"x-tabserver-token":e}})).json();if("error"in r)throw r.error;return r.ok.checkState}async confirmClaim(t){if(!this.#r||!this.#l)throw"confirmClaim: No token or claimCode";let e=new URL(`${this.#r.getAud()}/offer/confirm`),o=await this.#r.asSignedBase64(),r={claimCode:this.#l,checkCode:t},i=await(await fetch(e,{method:"POST",headers:{"x-tabserver-token":o,"content-type":"application/json"},body:JSON.stringify(r)})).json();if("error"in i)throw i.error;return i.ok}getChild(){if(!this.#o)throw"getChild: no child";return this.#o}getChildOrigin(){if(!this.#s||!this.#o)throw"getDaemonUrl: no issUrl or daemon";return`${this.#e}//${this.#o}`}async#h(){if(!this.#s||!this.#o||!this.#t)throw"buildToken: missing iss, child or privateJwk";let t=this.#s,e=this.getChildOrigin(),o=new URL(this.#s).origin,r;if(this.#n){let a=new URL(this.#n);r=`${a.origin}${a.pathname}${a.search}`}else r="party:control";let s={iss:t,aud:e,sub:o,src:r,scope:{"party:control":"offer"},iat:Date.now(),exp:Date.now()+1e3*60*3},i=new g(s);await i.signWith(Promise.resolve(this.#t)),this.#r=i}};var Vt="qrcode",it=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}generate(){let t=qrcode(0,"L");t.addData(this.#e),t.make();let e=t.createDataURL();return this.#t.classList.add(Vt),this.#t.src=e,new Promise((o,r)=>{this.#t.onload=o,this.#t.onerror=r})}};function at(n){if(n===null)return n;if(Array.isArray(n))return n.map(at);if(typeof n=="object"){let t={};for(let[e,o]of Object.entries(n))t[e]=at(o);return t}return n}function Ze(n){return n!==null}function to(n){return n!==void 0}function d(n,t){if("ok"in n){let i=JSON.stringify(n);return new Response(i,{status:200,headers:{...t,"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}let e=n.error,[,o,r]=e.match(/^(\d{3})\s(.+)/)??[null,"200",e],s=JSON.stringify({error:r});return new Response(s,{status:Number(o),headers:{...t,"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}function oo(n={error:"404 Not Found"}){let t=JSON.stringify(n);return new Response(t,{status:404,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}function no(n,t=[]){return new Response(null,{status:302,headers:{Location:n.toString(),"Access-Control-Allow-Origin":"*",...t}})}function ro(n){let{name:t,value:e,domain:o,sameSite:r,path:s="/",expires:i,secure:a=!0,httpOnly:l=!0}=n,c=[];return c.push(`${encodeURIComponent(t)}=${encodeURIComponent(e)}`),o&&c.push(`Domain=${o}`),r&&c.push(`SameSite=${r}`),c.push(`Path=${s}`),i&&c.push(`Expires=${i.toUTCString()}`),a&&c.push("Secure"),l&&c.push("HttpOnly"),c.join("; ")}var ct="daemon",Yt="config",Wt="event",lt={Config:"config"},ut="config",Xt=1e3*60*60,m=class n extends EventTarget{static#t=new n;static Ev=lt;static getInstance(){return this.#t}static shouldHandle(t){return n.isConfig(t)||n.isEvent(t)}static isConfig(t){let e=new URL(t.url);return t.method=="POST"&&e.pathname==`/${ct}/${Yt}`&&t.headers.get("Content-Type")=="application/json"}static isEvent(t){let e=new URL(t.url);return t.method=="POST"&&e.pathname==`/${ct}/${Wt}`&&t.headers.get("Content-Type")=="application/json"}async handler(t){return n.isConfig(t)?await this.handleConfig(t):n.isEvent(t)?await this.handleEvent(t):d({error:"Invalid daemon request"})}async handleConfig(t){let e=await t.json();return sessionStorage.setItem(ut,JSON.stringify(e)),this.dispatchEvent(new CustomEvent(lt.Config,{detail:e})),d({ok:!0})}async handleEvent(t){let{type:e,payload:o}=await t.json();return this.dispatchEvent(new CustomEvent(e,{detail:o})),d({ok:!0})}static getConfig(){let t=sessionStorage.getItem(ut);if(!t)throw"DaemonConfig not ready";return JSON.parse(t)}static getPrivateKey(){let{system:{privateJwk:t}}=n.getConfig();return Promise.resolve(t)}static async getTokenFor(t,e=null,o=null,r=Xt){let s=n.getConfig();if(!s)throw"Lifecycle configuration not yet available";let{system:{protocol:i,party:a,issuer:l,source:c}}=s,u=new URL(c),h=e?`${i}//${e}`:`${i}//${a}`,p=`${i}//${a}`,x=Date.now(),Et={iss:l,aud:h,sub:p,src:o??`${u.origin}${u.pathname}${u.search}`,scope:t,iat:x,exp:x+r},Z=new g(Et);return await Z.signWith(n.getPrivateKey()),Z}static async getStorage(){let t=await n.getStorageToken();return new C(t)}static getStorageToken(){let{system:{party:t}}=n.getConfig(),e={[g.Source.PARTY_CONTROL]:`${g.Capability.GET_ITEM} ${g.Capability.SET_ITEM}`};return n.getTokenFor(e,t)}};var P=class{#t;#e=1;constructor(t){if(t.post){this.#t=t.post;return}if(!t.url)throw new Error("JsonRpcMcpClient requires post or url");let e=t.fetch??fetch;this.#t=async o=>{let r=typeof t.headers=="function"?await t.headers():t.headers??{};return await(await e(t.url,{method:"POST",headers:zt(r),body:JSON.stringify(o)})).json()}}async listTools(){let e=(await this.#o("tools/list",{}))?.tools;return Array.isArray(e)?e:[]}async callTool(t,e={}){let o=await this.#o("tools/call",{name:t,arguments:e});if(o?.isError)throw qt(o);return o?.structuredContent??null}async#o(t,e){let o=await this.#t({jsonrpc:"2.0",id:this.#e++,method:t,params:e});if(o.error)throw o.error.message??JSON.stringify(o.error);return o.result}};function qt(n){let t=n?.content;if(Array.isArray(t)){let e=t[0];if(typeof e?.text=="string")return e.text}return"MCP tool failed"}function zt(n){let t=new Headers(n);return t.set("Content-Type","application/json"),t}var J=class{#t;#e;#o=[];#s=new Map;#n=new Map;constructor(t){this.#t=t.postParty,this.#e=t.postPartyRaw}get toolCatalog(){return this.#o}async refreshCatalog(){let t=await this.#t("/ai/tools/catalog",{});this.setCatalog(t.tools)}setCatalog(t){let e=Array.isArray(t)?t:[];this.#o=e,this.#s=new Map(this.#o.filter(o=>o.tool?.name&&o.route).map(o=>[o.tool.name,o.route])),this.#n.clear()}chatTools(t={}){return[...this.#o.map(Zt).filter(ht),...t.clientTools??[]]}async executeToolCalls(t){let e=[];for(let o of t)try{e.push({toolCallId:o.id,name:o.name,content:await this.executeToolCall(o)})}catch(r){e.push({toolCallId:o.id,name:o.name,content:String(r),isError:!0})}return e}async executeToolCall(t){let e=this.#s.get(t.name);if(!e)throw new Error(`No discovered tool named ${t.name}`);if(e.method!=="POST"||!e.path)throw new Error(`Unsupported route for tool ${t.name}`);if(e.kind==="platform"){let o=await this.#t(e.path,t.input);return JSON.stringify(o)}if(e.kind==="mcp")return await this.#r(e,t);throw new Error(`Unsupported route kind for tool ${t.name}`)}async#r(t,e){let o=this.#n.get(t.path);o||(o=new P({post:s=>this.#e(t.path,s)}),this.#n.set(t.path,o));let r=await o.callTool(t.mcpToolName||e.name,{...e.input});return JSON.stringify(r)}},$=class{#t;#e=new Map;constructor(t){this.#t=t}async refreshCatalog(){await Promise.all(this.#t.map(t=>t.runtime.refreshCatalog()))}chatTools(t={}){this.#e.clear();let e=this.#t.map(s=>s.runtime.chatTools().filter(i=>i.execution==="server"&&this.#o(s,i.name))),o=new Map;for(let s of e)for(let i of s)o.set(i.name,(o.get(i.name)??0)+1);let r=[];return this.#t.forEach((s,i)=>{for(let a of e[i]){let c=(o.get(a.name)??0)>1?`${i}__${a.name}`:a.name;this.#e.set(c,{provider:s,realName:a.name}),r.push({...a,name:c})}}),[...r,...t.clientTools??[]]}async executeToolCall(t){let e=this.#e.get(t.name);if(!e)throw new Error(`No discovered tool named ${t.name}`);return await e.provider.runtime.executeToolCall({...t,name:e.realName})}#o(t,e){return!t.allowedTools||t.allowedTools.has(e)}},U=class{#t;#e=[];constructor(t){this.#t=new P({post:t.postRpc})}async refreshCatalog(){let t=await this.#t.listTools();this.#e=t.map(Qt).filter(ht)}chatTools(t={}){return[...this.#e,...t.clientTools??[]]}async executeToolCall(t){let e=await this.#t.callTool(t.name,{...t.input});return JSON.stringify(e)}};function Qt(n){let t=n;return t?.name?{type:"function",name:t.name,execution:"server",description:t.description,parameters:t.inputSchema}:null}function Zt(n){return n?.tool?.name?{type:"function",name:n.tool.name,execution:"server",description:n.tool.description,parameters:n.tool.inputSchema}:null}function go(n,t){return!t||t===n?n:n?`${t}
8
+ -----END PRIVATE KEY-----`}};async function Ze(){let n=await R.getInstance(),t=n.getPartyOrigin(),e=new URL(`${t}/catalog`);e.searchParams.append("alert","");let r=await(await fetch(e,{headers:{"X-Tabserver-Token":n.getTokenBase64(),Accept:"application/json"}})).json();if("error"in r)throw r.error;return r.ok.alert.find(i=>i.type=="LAUNCH"&&i.sourceUrl==new URL(n.getAppUrl()))||null}var ot=class{#t;#e;#n;#s;#o;#r;#l;async initWithKey(t,e,o,r){this.#e=e.startsWith("https:")?"https:":"http:",this.#n=t,this.#o=e,this.#t=o,this.#s=r,await this.#p()}async checkActivate(){if(!this.#r)throw"checkActivate: No token";let t=new URL(`${this.#r.getAud()}/activate`),e=this.#r.asSignedBase64(),o={},r;try{r=await fetch(t,{method:"POST",headers:{"x-tabserver-token":e,"content-type":"application/json"},body:JSON.stringify(o)});let{ok:s,error:i}=await r.json();if(i)throw i;return!!s.isNew}catch(s){throw console.error(s),`Cannot activate ${this.#r.getParty()}`}}async makeOffer(t,e=null){let{type:o="TRANSIENT",ttl:r=300,expiry:s=30,payload:i}=e??{};if(!this.#r)throw"makeOffer: No token";let a=new URL(`${this.#r.getAud()}/offer`),l=this.#r.asSignedBase64(),c={role:"party",type:o,ttl:r,description:`Offered by ${this.#r.getCounterparty()}`,payload:i,expiry:new Date(Date.now()+1e3*s),flow:t},h=await(await fetch(a,{method:"POST",headers:{"x-tabserver-token":l,"content-type":"application/json"},body:JSON.stringify(c)})).json();if("error"in h)throw h.error;let{claimCode:p,_checkState:y}=h.ok;return this.#l=p,h.ok}async checkState(){if(!this.#r||!this.#l)throw"checkState: No token or claimCode";let t=new URL(`${this.#r.getAud()}/offer/check`);t.searchParams.append("claimCode",this.#l);let e=this.#r.asSignedBase64(),r=await(await fetch(t,{headers:{"x-tabserver-token":e}})).json();if("error"in r)throw r.error;return r.ok.checkState}async confirmClaim(t){if(!this.#r||!this.#l)throw"confirmClaim: No token or claimCode";let e=new URL(`${this.#r.getAud()}/offer/confirm`),o=await this.#r.asSignedBase64(),r={claimCode:this.#l,checkCode:t},i=await(await fetch(e,{method:"POST",headers:{"x-tabserver-token":o,"content-type":"application/json"},body:JSON.stringify(r)})).json();if("error"in i)throw i.error;return i.ok}getChild(){if(!this.#n)throw"getChild: no child";return this.#n}getChildOrigin(){if(!this.#s||!this.#n)throw"getDaemonUrl: no issUrl or daemon";return`${this.#e}//${this.#n}`}async#p(){if(!this.#s||!this.#n||!this.#t)throw"buildToken: missing iss, child or privateJwk";let t=this.#s,e=this.getChildOrigin(),o=new URL(this.#s).origin,r;if(this.#o){let a=new URL(this.#o);r=`${a.origin}${a.pathname}${a.search}`}else r="party:control";let s={iss:t,aud:e,sub:o,src:r,scope:{"party:control":"offer"},iat:Date.now(),exp:Date.now()+1e3*60*3},i=new d(s);await i.signWith(Promise.resolve(this.#t)),this.#r=i}};var Yt="qrcode",rt=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}generate(){let t=qrcode(0,"L");t.addData(this.#e),t.make();let e=t.createDataURL();return this.#t.classList.add(Yt),this.#t.src=e,new Promise((o,r)=>{this.#t.onload=o,this.#t.onerror=r})}};function st(n){if(n===null)return n;if(Array.isArray(n))return n.map(st);if(typeof n=="object"){let t={};for(let[e,o]of Object.entries(n))t[e]=st(o);return t}return n}function rn(n){return n!==null}function sn(n){return n!==void 0}function g(n,t){if("ok"in n){let i=JSON.stringify(n);return new Response(i,{status:200,headers:{...t,"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}let e=n.error,[,o,r]=e.match(/^(\d{3})\s(.+)/)??[null,"200",e],s=JSON.stringify({error:r});return new Response(s,{status:Number(o),headers:{...t,"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}function cn(n={error:"404 Not Found"}){let t=JSON.stringify(n);return new Response(t,{status:404,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}function ln(n,t=[]){return new Response(null,{status:302,headers:{Location:n.toString(),"Access-Control-Allow-Origin":"*",...t}})}function un(n){let{name:t,value:e,domain:o,sameSite:r,path:s="/",expires:i,secure:a=!0,httpOnly:l=!0}=n,c=[];return c.push(`${encodeURIComponent(t)}=${encodeURIComponent(e)}`),o&&c.push(`Domain=${o}`),r&&c.push(`SameSite=${r}`),c.push(`Path=${s}`),i&&c.push(`Expires=${i.toUTCString()}`),a&&c.push("Secure"),l&&c.push("HttpOnly"),c.join("; ")}var it="daemon",Wt="config",qt="event",at={Config:"config"},ct="config",Xt=1e3*60*60,m=class n extends EventTarget{static#t=new n;static Ev=at;static getInstance(){return this.#t}static shouldHandle(t){return n.isConfig(t)||n.isEvent(t)}static isConfig(t){let e=new URL(t.url);return t.method=="POST"&&e.pathname==`/${it}/${Wt}`&&t.headers.get("Content-Type")=="application/json"}static isEvent(t){let e=new URL(t.url);return t.method=="POST"&&e.pathname==`/${it}/${qt}`&&t.headers.get("Content-Type")=="application/json"}async handler(t){return n.isConfig(t)?await this.handleConfig(t):n.isEvent(t)?await this.handleEvent(t):g({error:"Invalid daemon request"})}async handleConfig(t){let e=await t.json();return sessionStorage.setItem(ct,JSON.stringify(e)),this.dispatchEvent(new CustomEvent(at.Config,{detail:e})),g({ok:!0})}async handleEvent(t){let{type:e,payload:o}=await t.json();return this.dispatchEvent(new CustomEvent(e,{detail:o})),g({ok:!0})}static getConfig(){let t=sessionStorage.getItem(ct);if(!t)throw"DaemonConfig not ready";return JSON.parse(t)}static getPrivateKey(){let{system:{privateJwk:t}}=n.getConfig();return Promise.resolve(t)}static async getTokenFor(t,e=null,o=null,r=Xt,s=[]){let i=n.getConfig();if(!i)throw"Lifecycle configuration not yet available";let{system:{protocol:a,party:l,issuer:c,source:u}}=i,h=new URL(u),p=e?`${a}//${e}`:`${a}//${l}`,y=`${a}//${l}`,S=Date.now(),f={iss:c,aud:p,sub:y,src:o??`${h.origin}${h.pathname}${h.search}`,scope:t,iat:S,exp:S+r,...s.length?{pre:s.map(({counterparty:Et,src:Nt})=>({counterparty:Et,src:Nt}))}:{}},_=new d(f);return await _.signWith(n.getPrivateKey()),_}static async getStorage(){let t=await n.getStorageToken();return new P(t)}static getStorageToken(){let{system:{party:t}}=n.getConfig(),e={[d.Source.PARTY_CONTROL]:`${d.Capability.GET_ITEM} ${d.Capability.SET_ITEM}`};return n.getTokenFor(e,t)}};var v=class{#t;#e=1;constructor(t){if(t.post){this.#t=t.post;return}if(!t.url)throw new Error("JsonRpcMcpClient requires post or url");let e=t.fetch??fetch;this.#t=async o=>{let r=typeof t.headers=="function"?await t.headers():t.headers??{};return await(await e(t.url,{method:"POST",headers:Qt(r),body:JSON.stringify(o)})).json()}}async listTools(){let e=(await this.#n("tools/list",{}))?.tools;return Array.isArray(e)?e:[]}async callTool(t,e={}){let o=await this.#n("tools/call",{name:t,arguments:e});if(o?.isError)throw zt(o);return o?.structuredContent??null}async#n(t,e){let o=await this.#t({jsonrpc:"2.0",id:this.#e++,method:t,params:e});if(o.error)throw o.error.message??JSON.stringify(o.error);return o.result}};function zt(n){let t=n?.content;if(Array.isArray(t)){let e=t[0];if(typeof e?.text=="string")return e.text}return"MCP tool failed"}function Qt(n){let t=new Headers(n);return t.set("Content-Type","application/json"),t}var J=class{#t;#e;#n=[];#s=new Map;#o=new Map;constructor(t){this.#t=t.postParty,this.#e=t.postPartyRaw}get toolCatalog(){return this.#n}async refreshCatalog(){let t=await this.#t("/ai/tools/catalog",{});this.setCatalog(t.tools)}setCatalog(t){let e=Array.isArray(t)?t:[];this.#n=e,this.#s=new Map(this.#n.filter(o=>o.tool?.name&&o.route).map(o=>[o.tool.name,o.route])),this.#o.clear()}chatTools(t={}){return[...this.#n.map(te).filter(lt),...t.clientTools??[]]}async executeToolCalls(t){let e=[];for(let o of t)try{e.push({toolCallId:o.id,name:o.name,content:await this.executeToolCall(o)})}catch(r){e.push({toolCallId:o.id,name:o.name,content:String(r),isError:!0})}return e}async executeToolCall(t){let e=this.#s.get(t.name);if(!e)throw new Error(`No discovered tool named ${t.name}`);if(e.method!=="POST"||!e.path)throw new Error(`Unsupported route for tool ${t.name}`);if(e.kind==="platform"){let o=await this.#t(e.path,t.input);return JSON.stringify(o)}if(e.kind==="mcp")return await this.#r(e,t);throw new Error(`Unsupported route kind for tool ${t.name}`)}async#r(t,e){let o=this.#o.get(t.path);o||(o=new v({post:s=>this.#e(t.path,s)}),this.#o.set(t.path,o));let r=await o.callTool(t.mcpToolName||e.name,{...e.input});return JSON.stringify(r)}},U=class{#t;#e=new Map;constructor(t){this.#t=t}async refreshCatalog(){await Promise.all(this.#t.map(t=>t.runtime.refreshCatalog()))}chatTools(t={}){this.#e.clear();let e=this.#t.map(s=>s.runtime.chatTools().filter(i=>i.execution==="server"&&this.#n(s,i.name))),o=new Map;for(let s of e)for(let i of s)o.set(i.name,(o.get(i.name)??0)+1);let r=[];return this.#t.forEach((s,i)=>{for(let a of e[i]){let c=(o.get(a.name)??0)>1?`${i}__${a.name}`:a.name;this.#e.set(c,{provider:s,realName:a.name}),r.push({...a,name:c})}}),[...r,...t.clientTools??[]]}async executeToolCall(t){let e=this.#e.get(t.name);if(!e)throw new Error(`No discovered tool named ${t.name}`);return await e.provider.runtime.executeToolCall({...t,name:e.realName})}#n(t,e){return!t.allowedTools||t.allowedTools.has(e)}},L=class{#t;#e=[];constructor(t){this.#t=new v({post:t.postRpc})}async refreshCatalog(){let t=await this.#t.listTools();this.#e=t.map(Zt).filter(lt)}chatTools(t={}){return[...this.#e,...t.clientTools??[]]}async executeToolCall(t){let e=await this.#t.callTool(t.name,{...t.input});return JSON.stringify(e)}};function Zt(n){let t=n;return t?.name?{type:"function",name:t.name,execution:"server",description:t.description,parameters:t.inputSchema}:null}function te(n){return n?.tool?.name?{type:"function",name:n.tool.name,execution:"server",description:n.tool.description,parameters:n.tool.inputSchema}:null}function Tn(n,t){return!t||t===n?n:n?`${t}
9
9
 
10
- ${n}`:t}function ht(n){return n!=null}var te="2025-06-18",D={"Access-Control-Allow-Origin":"*"},ee="POST, GET",pt=class{#t;constructor(t){this.#t=t}listTools(){return this.#t.map(t=>({name:t.name,...t.title===void 0?{}:{title:t.title},description:t.description,inputSchema:t.inputSchema,...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.annotations===void 0?{}:{annotations:t.annotations}}))}async callTool(t,e,o){let r=this.#t.find(s=>s.name===t);if(!r)throw new f(-32602,`Unknown tool: ${t}`);return await r.call(e,o)}},j=class{#t;#e;#o;constructor(t,e){this.#t=t,typeof e=="function"?(this.#e=e,this.#o={name:"mcp-server",version:"1"}):(this.#e=e.context,this.#o=e.serverInfo??{name:"mcp-server",version:"1"})}async handle(t){if(t.method==="GET")return ne(t);if(t.method==="DELETE"||t.method!=="POST")return dt();let e;try{e=await t.json()}catch{return b(L(null,-32700,"Parse error"))}let o=re(e.id);if(e.jsonrpc!=="2.0"||typeof e.method!="string")return b(L(o,-32600,"Invalid Request"));if(e.id===void 0)return oe();try{let r=await this.#s(e.method,e.params,t);return b({jsonrpc:"2.0",id:o,result:r})}catch(r){return r instanceof f?b(L(o,r.code,r.message)):b(L(o,-32603,String(r)))}}async#s(t,e,o){switch(t){case"initialize":return{protocolVersion:te,capabilities:{tools:{listChanged:!1}},serverInfo:this.#o};case"notifications/initialized":return{};case"tools/list":return{tools:await this.#t.listTools(this.#e(o))};case"tools/call":return await this.#n(e,o);default:throw new f(-32601,`Method not found: ${t}`)}}async#n(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new f(-32602,"tools/call params must be an object");let{name:o,arguments:r={}}=t;if(typeof o!="string"||!r||typeof r!="object"||Array.isArray(r))throw new f(-32602,"Invalid tools/call params");try{let s=await this.#t.callTool(o,r,this.#e(e));return gt(s)}catch(s){if(s instanceof f)throw s;return gt({error:String(s)},!0)}}},f=class extends Error{code;constructor(t,e){super(e),this.code=t}};function gt(n,t=!1){return{content:[{type:"text",text:typeof n=="string"?n:JSON.stringify(n)}],structuredContent:n,isError:t}}function L(n,t,e){return{jsonrpc:"2.0",id:n,error:{code:t,message:e}}}function b(n){return new Response(JSON.stringify(n),{headers:{...D,"Content-Type":"application/json"}})}function oe(){return new Response(null,{status:202,headers:D})}function ne(n){let t=new URL(n.url);return new Response(`event: endpoint
10
+ ${n}`:t}function lt(n){return n!=null}var ee="2025-06-18",G={"Access-Control-Allow-Origin":"*"},ne="POST, GET",ut=class{#t;constructor(t){this.#t=t}listTools(){return this.#t.map(t=>({name:t.name,...t.title===void 0?{}:{title:t.title},description:t.description,inputSchema:t.inputSchema,...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.annotations===void 0?{}:{annotations:t.annotations}}))}async callTool(t,e,o){let r=this.#t.find(s=>s.name===t);if(!r)throw new w(-32602,`Unknown tool: ${t}`);return await r.call(e,o)}},D=class{#t;#e;#n;constructor(t,e){this.#t=t,typeof e=="function"?(this.#e=e,this.#n={name:"mcp-server",version:"1"}):(this.#e=e.context,this.#n=e.serverInfo??{name:"mcp-server",version:"1"})}async handle(t){if(t.method==="GET")return re(t);if(t.method==="DELETE"||t.method!=="POST")return pt();let e;try{e=await t.json()}catch{return A(j(null,-32700,"Parse error"))}let o=se(e.id);if(e.jsonrpc!=="2.0"||typeof e.method!="string")return A(j(o,-32600,"Invalid Request"));if(e.id===void 0)return oe();try{let r=await this.#s(e.method,e.params,t);return A({jsonrpc:"2.0",id:o,result:r})}catch(r){return r instanceof w?A(j(o,r.code,r.message)):A(j(o,-32603,String(r)))}}async#s(t,e,o){switch(t){case"initialize":return{protocolVersion:ee,capabilities:{tools:{listChanged:!1}},serverInfo:this.#n};case"notifications/initialized":return{};case"tools/list":return{tools:await this.#t.listTools(this.#e(o))};case"tools/call":return await this.#o(e,o);default:throw new w(-32601,`Method not found: ${t}`)}}async#o(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new w(-32602,"tools/call params must be an object");let{name:o,arguments:r={}}=t;if(typeof o!="string"||!r||typeof r!="object"||Array.isArray(r))throw new w(-32602,"Invalid tools/call params");try{let s=await this.#t.callTool(o,r,this.#e(e));return ht(s)}catch(s){if(s instanceof w)throw s;return ht({error:String(s)},!0)}}},w=class extends Error{code;constructor(t,e){super(e),this.code=t}};function ht(n,t=!1){return{content:[{type:"text",text:typeof n=="string"?n:JSON.stringify(n)}],structuredContent:n,isError:t}}function j(n,t,e){return{jsonrpc:"2.0",id:n,error:{code:t,message:e}}}function A(n){return new Response(JSON.stringify(n),{headers:{...G,"Content-Type":"application/json"}})}function oe(){return new Response(null,{status:202,headers:G})}function re(n){let t=new URL(n.url);return new Response(`event: endpoint
11
11
  data: ${t.pathname}
12
12
 
13
- `,{headers:{...D,"Content-Type":"text/event-stream","Cache-Control":"no-cache"}})}function dt(){return new Response(null,{status:405,headers:{...D,Allow:ee}})}function re(n){return typeof n=="string"||typeof n=="number"||n===null?n:null}var H="application/x-ndjson",G=class extends Array{#t;constructor(t){super(),this.#t=t}static get[Symbol.species](){return Array}push(...t){for(let e of t)this.#t?.(e);return super.push(...t)}};function V(n,t){se(n,t.reasoning),t.content?n.push({role:"assistant",content:t.content}):t.toolCalls?.length||n.push({role:"assistant",content:""})}function se(n,t){for(let e of t??[])e.redacted||!e.text||n.push({role:"thinking",content:e.text})}function Y(n,t){return`${t?"Client tool call":"Agent tool call"}: ${n.name}
14
- ${JSON.stringify(n.input,null,2)}`}function A(n,t,e,o,r=!1){o&&n.push({role:"tool-result",content:ie(t,e,r),...r?{error:!0}:{}})}function ie(n,t,e=!1){return`${e?"Tool error":"Tool result"}: ${n}
15
- ${t}`}function mt(n,t={}){let e=t.toolDetails??!0,o=t.clientToolNames,r=[];for(let s of n)if(s.role==="assistant"){if(V(r,s),e)for(let i of s.toolCalls??[])r.push({role:"tool",content:Y(i,o?.has(i.name)??!1)})}else if(s.role==="tool")for(let i of s.toolResults??[])A(r,i.name??"tool",i.content,e,i.isError);else s.role==="user"&&s.content&&r.push({role:"user",content:s.content});return r}var ae="useTools",wt=/[\s,;\|]+/,F=class{#t;constructor(t){this.#t=t}hasCapability(t,e){return(this.#t.scope[t]??"").split(wt).includes(e)}getParty(){return this.#t.party??""}getCounterparty(){return this.#t.counterparty}getSourceUrl(){return new URL(this.#t.src)}getSrc(){return this.#t.src}};function Tt(n){let{token:t,providerSource:e,toolName:o,capability:r,providerYaml:s}=n;if(!t)return!1;if(ft(t,e,r))return!0;if(!s)return!1;let i=String(t.getSourceUrl());return ft(t,i,ae)&&ce(s,o,r)&&le(s.grant,t.getCounterparty(),t.getSrc(),r)}function ft(n,t,e){try{return n.hasCapability(t,e)}catch{return!1}}function ce(n,t,e){return!!n.mcp?.tools.some(o=>o.name===t&&o.capability===e)}function le(n,t,e,o){for(let r in n??{}){if(!yt(t.toLowerCase(),r.toLowerCase()))continue;let s=n[r];if(Array.isArray(s)){if(s.includes(o))return!0;continue}for(let i in s)if(yt(e,i)&&ue(s[i]).includes(o))return!0}return!1}function ue(n){return n.split(wt).filter(t=>t.length>0)}function yt(n,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(n)}var Ct="x-forwarded-host",St="x-forwarded-proto",Rt="x-forwarded-pathname",v="x-tabserver-oauth-context",W="x-tabserver-counterparty",_="x-tabserver-continuation";function he(n){return n.headers.has(St)?n.headers.get(St)+":":new URL(n.url).protocol}function pe(n){return n.headers.has(Ct)?n.headers.get(Ct)||"":new URL(n.url).host}function ge(n){return n.headers.has(Rt)?n.headers.get(Rt)||"":new URL(n.url).pathname}function de(n){let t=he(n),e=pe(n),o=ge(n);return new URL(`${t}//${e}${o}`)}function To(n){let t=new URL(n.url),e=de(n);return e.search=t.search,e.hash=t.hash,e}function Co(n){return new URL(n.url).pathname}function So(n,t){let e=me(n);return t in e?e[t]:null}function me(n){let t={},e=n.headers.get("Cookie");if(e)for(let o of e.split("; ")){let[r,s]=o.split("=");t[r]=s}return t}var fe=4,ye=.2,xt=g.TOKEN_HEADER,Q="expert_ask",Pt="expertAsk",bt=class{#t;#e;#o;#s;#n;#r;#l;#h;#u;#a=new Map;#p=new Map;#f=new m;#i;#y;constructor(t){this.#t=t.targetScope,this.#e=t.defaultSystemPrompt,this.#o=t.defaultTemperature??ye,this.#s=t.defaultModel,this.#n=t.maxToolRounds??fe,this.#r=t.mcpPath??"/rpc",this.#l=t.resolveToolProviders,this.#h=t.resolveMemorySelection,this.#u=t.resolveStructuredMemorySelection,this.#i={temperature:this.#o,toolsEnabled:!0,toolDetails:!0,thinking:t.defaultThinking??!1},this.#y=new j(new q(this),{context:ve,serverInfo:{name:"ai-chat-expert",version:"1"}})}async handler(t){if(m.shouldHandle(t))return await this.#f.handler(t);try{if(t.method!=="POST")throw"405 Method Not Allowed";let e=new URL(t.url);if(e.pathname===this.#r)return await this.#y.handle(t);switch(e.pathname){case"/session":return d({ok:await this.#_(t)});case"/settings":return d({ok:await this.#K(t)});case"/models":return d({ok:await this.#B(t)});case"/chats":return d({ok:await this.#H(t)});case"/send":return this.#w(t)?this.#m(o=>this.#I(t,o)):d({ok:await this.#I(t,[])});case"/client-tool-results":return this.#w(t)?this.#m(o=>this.#J(t,o)):d({ok:await this.#J(t,[])});case"/close":return d({ok:await this.#V(t)});case"/delete":return d({ok:await this.#Y(t)});default:throw"404 Not Found"}}catch(e){return console.error(e),d({error:String(e)})}}#w(t){return t.headers.get("Accept")?.includes(H)??!1}#m(t){let e=new TextEncoder,o=new ReadableStream({start:async r=>{let s=a=>r.enqueue(e.encode(`${JSON.stringify(a)}
16
- `)),i=new G(a=>s({type:"event",event:a}));try{let a=await t(i);s({type:"done",...a.clientToolCalls?.length?{clientToolCalls:a.clientToolCalls}:{}})}catch(a){console.error(a),s({type:"error",message:String(a)})}finally{r.close()}}});return new Response(o,{status:200,headers:{"Content-Type":H,"Cache-Control":"no-cache","Access-Control-Allow-Origin":"*"}})}async askExpert(t,e){let o=e.trim();if(!o)throw"Question is required";let r=this.#G(void 0),s=T(t),i=await this.#k(r,{expert:!0},s),a=this.#i.temperature,l=t.headers.get(_),c=l?Se(t,l):null;if(c)return await this.#T(t,r,s,c,i,a,o);let u=await this.#d(t,r,void 0,i,a);try{return{answer:await this.#S(u,o,a)}}finally{this.#a.delete(w(t,u.targetParty,u.chatId)),await this.#c(u.targetParty,"/ai/chat/close",{chatId:u.chatId},u.forward).catch(h=>console.error(h))}}async#T(t,e,o,r,s,i,a){let l=this.#p.get(r);try{let c=await this.#d(t,e,l,s,i);return l||this.#p.set(r,c.chatId),{answer:await this.#S(c,a,i)}}catch(c){if(l&&await this.#U(e,l,o)){this.#p.delete(r),this.#a.delete(w(t,e,l));let u=await this.#d(t,e,void 0,s,i);return this.#p.set(r,u.chatId),{answer:await this.#S(u,a,i)}}throw c}finally{let c=this.#p.get(r);c&&this.#a.delete(w(t,e,c))}}async#S(t,e,o){X(t),t.toolRounds=0,await this.#C(t);let r=[],s=await this.#c(t.targetParty,"/ai/chat/send",{chatId:t.chatId,message:e,options:this.#b(t,this.#i.toolsEnabled,o)},t.forward),i=await this.#R(t,s.message,this.#i.toolsEnabled,!1,o,r);if(i.clientToolCalls?.length)throw"Expert MCP cannot execute browser client tools";let a=ke(i.events);if(!a)throw"Expert did not return an answer";return a}async#I(t,e){let o=await At(t);if(typeof o.message!="string"||!o.message.trim())throw"Message is required";let r=o.message.trim(),s=this.#D(o),i=this.#O(o),a=this.#v(o),l=this.#g(o),c=O(o),u=await this.#d(t,l,c,void 0,a,this.#j(o));return X(u),u.toolRounds=0,vt(u,o),s&&await this.#C(u),await this.#M(e,async()=>{let h=await this.#c(u.targetParty,"/ai/chat/send",{chatId:u.chatId,message:r,options:this.#b(u,s,a)},u.forward);return await this.#R(u,h.message,s,i,a,e)})}async#M(t,e){try{return await e()}catch(o){return t.push({role:"assistant",content:String(o),error:!0}),{events:t}}}async#J(t,e){let o=await At(t),r=this.#D(o),s=this.#O(o),i=this.#v(o),a=this.#g(o),l=O(o),c=await this.#d(t,a,l,void 0,i);vt(c,o);let u=Te(c,o.toolResults);for(let p of u)A(e,p.name??"client_tool",p.content,s,p.isError);let h=[...c.pendingToolResults,...u];return X(c),await this.#M(e,()=>this.#$(c,h,r,s,i,e))}async#R(t,e,o,r,s,i){let a=e;for(;;){V(i,a);let l=a.toolCalls??[];if(!l.length)return{events:i};if(t.toolRounds>=this.#n)return i.push({role:"tool-result",content:"Stopped after too many tool rounds.",error:!0}),{events:i};let{toolResults:c,clientToolCalls:u}=await Pe(t,l,r,i);if(u.length)return t.pendingClientToolCalls=new Map(u.map(p=>[p.id,p])),t.pendingToolResults=c,{events:i,clientToolCalls:u};let h=await this.#$(t,c,o,r,s,i);return h.clientToolCalls?.length,h}}async#$(t,e,o,r,s,i){if(t.toolRounds>=this.#n)return i.push({role:"tool-result",content:"Stopped after too many tool rounds.",error:!0}),{events:i};t.toolRounds++;let a=await this.#c(t.targetParty,"/ai/chat/send",{chatId:t.chatId,message:{role:"user",content:"",toolResults:e},options:this.#b(t,o,s)},t.forward);return await this.#R(t,a.message,o,r,s,i)}async#_(t){let e=await S(t),o=this.#g(e),r=O(e),s=T(t),i=await this.#d(t,o,r,r?void 0:await this.#Q(e,o,s),this.#v(e),this.#j(e));Ot(i,e.clientTools),await this.#C(i);let a=await this.#W(i);return{chatId:i.chatId,history:a,historyEvents:mt(a,{toolDetails:this.#O(e),clientToolNames:i.clientToolNames}),closed:r?await this.#U(o,r,s):null}}async#K(t){let e=await S(t);return Object.keys(e).length&&this.#nt(e),this.#ot()}async#B(t){let e=await S(t),o=this.#g(e),r=await this.#c(o,"/ai/chat/models",{},T(t));return{models:Array.isArray(r.models)?r.models:[]}}async#H(t){let e=await S(t),o=this.#g(e),r=await this.#c(o,"/ai/chat/list",{},T(t));return{chats:Array.isArray(r.chats)?r.chats:[]}}async#V(t){let e=await S(t),o=this.#g(e),r=O(e);if(!r)throw"chatId is required";let s=T(t),i=w(t,o,r),a=this.#a.get(i);return a?(await this.#c(a.targetParty,"/ai/chat/close",{chatId:a.chatId},a.forward),this.#a.delete(i),!0):(await this.#c(o,"/ai/chat/close",{chatId:r},s),!0)}async#Y(t){let e=await S(t),o=this.#g(e),r=O(e);if(!r)throw"chatId is required";let s=w(t,o,r);return await this.#c(o,"/ai/chat/delete",{chatId:r},T(t)),this.#a.delete(s),!0}async#d(t,e,o,r,s=this.#o,i=this.#s){let a=w(t,e,o);if(o){let h=this.#a.get(a);if(h)return h}let l=T(t),c=o?{id:o}:await this.#c(e,"/ai/chat/create",{system:r??await this.#k(e,{expert:!1},l),temperature:s,...i?{model:i}:{}},l);l.continuation??=String(c.id),a=w(t,e,String(c.id));let u={chatId:String(c.id),targetParty:e,forward:l,toolRuntime:await this.#q(e,l),clientTools:[],clientToolNames:new Set,pendingClientToolCalls:new Map,pendingToolResults:[],toolRounds:0};return await this.#C(u),this.#a.set(a,u),u}async#W(t){let e=await this.#c(t.targetParty,"/ai/chat/history",{chatId:t.chatId},t.forward);return Array.isArray(e.messages)?e.messages:[]}async#U(t,e,o){let r=await this.#c(t,"/ai/chat/list",{},o),i=(Array.isArray(r.chats)?r.chats:[]).find(a=>a.id===e);return typeof i?.closed=="string"?i.closed:null}#L(t,e,o,r,s){return new J({postParty:(i,a)=>this.#c(t,i,this.#X(i,a,r,s),e,o),postPartyRaw:(i,a)=>this.#A(t,i,a,e,o)})}#X(t,e,o,r){if(t!=="/ai/memory/catalog")return e;let s=e.kind==="structured"?r:o;return s?{...e,collections:s}:e}async#x(t,e){if(this.#h&&t===m.getConfig().system.party)return await this.#h(t,e??{oauthContext:null,counterpartyContext:null,continuation:null})}async#P(t,e){if(this.#u&&t===m.getConfig().system.party)return await this.#u(t,e??{oauthContext:null,counterpartyContext:null,continuation:null})}async#q(t,e){let o=await this.#l?.(t,e);if(!o?.length)return this.#L(t,e,void 0,await this.#x(t,e),await this.#P(t,e));let r=m.getConfig().system.party;return new $(await Promise.all(o.map(async s=>({key:s.party,runtime:s.party===r?this.#L(s.party,e,s.scope,await this.#x(s.party,e),await this.#P(s.party,e)):this.#z(s.party,e),allowedTools:s.tools?new Set(s.tools):void 0}))))}#z(t,e){return new U({postRpc:o=>this.#A(t,"/mcp/rpc",o,e)})}async#C(t){await t.toolRuntime.refreshCatalog()}#b(t,e,o){let r=this.#i.thinking,s={temperature:o,thinking:r};if(!e)return s;let i=t.toolRuntime.chatTools({clientTools:t.clientTools});return i.length?{...s,tools:i,toolChoice:"auto"}:s}async#c(t,e,o,r,s){let i=await this.#A(t,e,o,r,s);if("error"in i)throw i.error;return i.ok}async#A(t,e,o,r,s){let i=m.getConfig(),a=await m.getTokenFor({[i.system.source]:s??this.#t},t),l=`${i.system.protocol}//${t}${e}`,c={"Content-Type":"application/json","X-Tabserver-Token":a.asSignedBase64()};return r?.oauthContext&&(c[v]=r.oauthContext),r?.counterpartyContext&&(c[W]=r.counterpartyContext),r?.continuation&&(c[_]=r.continuation),await(await fetch(l,{method:"POST",headers:c,body:JSON.stringify(o)})).json()}async#Q(t,e,o){let r=typeof t.systemPrompt=="string"&&t.systemPrompt.trim()?t.systemPrompt.trim():this.#N();return await this.#k(e,{basePrompt:r,expert:!1},o)}#j(t){return typeof t.model=="string"&&t.model.trim()?t.model.trim():void 0}#v(t){return typeof t.temperature=="number"&&Number.isFinite(t.temperature)&&t.temperature>=0&&t.temperature<=2?Math.round(t.temperature*10)/10:this.#i.temperature}#D(t){return typeof t.toolsEnabled=="boolean"?t.toolsEnabled:this.#i.toolsEnabled}#O(t){return typeof t.toolDetails=="boolean"?t.toolDetails:this.#i.toolDetails}#g(t){return this.#G(t.targetParty)}#G(t){let{system:{party:e,protocol:o}}=m.getConfig();if(t==null||t==="")return e;if(typeof t!="string")throw"targetParty must be a string";let r=t.trim();if(!r)return e;try{let s=r.includes("://")?new URL(r):new URL(`${o}//${r}`);if(!s.host)throw"missing host";return s.host}catch{throw`Invalid targetParty: ${t}`}}async#k(t,e,o){let r=e.basePrompt??this.#N(),s=await Ie(),i=e.expert&&s?`
17
- When answering expert MCP questions, prefer semantic and structured memory under root "${s}" when looking up remembered information.`:"",a=await this.#Z(t,o),l=await this.#et(t,o);return`${r}${i}${a}${l}`}async#Z(t,e){try{let o=await this.#x(t,e),r=z(),s=r?await this.#tt(t,r,e,o):await this.#E(t,{collections:o},e);return Ee(s)}catch{return`
13
+ `,{headers:{...G,"Content-Type":"text/event-stream","Cache-Control":"no-cache"}})}function pt(){return new Response(null,{status:405,headers:{...G,Allow:ne}})}function se(n){return typeof n=="string"||typeof n=="number"||n===null?n:null}var H="application/x-ndjson",F=class extends Array{#t;constructor(t){super(),this.#t=t}static get[Symbol.species](){return Array}push(...t){for(let e of t)this.#t?.(e);return super.push(...t)}};function Y(n,t){ie(n,t.reasoning),t.content?n.push({role:"assistant",content:t.content}):t.toolCalls?.length||n.push({role:"assistant",content:""})}function ie(n,t){for(let e of t??[])e.redacted||!e.text||n.push({role:"thinking",content:e.text})}function W(n,t){return`${t?"Client tool call":"Agent tool call"}: ${n.name}
14
+ ${JSON.stringify(n.input,null,2)}`}function O(n,t,e,o,r=!1){o&&n.push({role:"tool-result",content:ae(t,e,r),...r?{error:!0}:{}})}function ae(n,t,e=!1){return`${e?"Tool error":"Tool result"}: ${n}
15
+ ${t}`}function dt(n,t={}){let e=t.toolDetails??!0,o=t.clientToolNames,r=[];for(let s of n)if(s.role==="assistant"){if(Y(r,s),e)for(let i of s.toolCalls??[])r.push({role:"tool",content:W(i,o?.has(i.name)??!1)})}else if(s.role==="tool")for(let i of s.toolResults??[])O(r,i.name??"tool",i.content,e,i.isError);else s.role==="user"&&s.content&&r.push({role:"user",content:s.content});return r}var ce="useTools",le=/[\s,;\|]+/;function ft(n){let{token:t,providerSource:e,toolName:o,capability:r,providerYaml:s}=n;if(!t)return!1;if(gt(t,e,r))return!0;if(!s)return!1;let i=String(t.getSourceUrl());return gt(t,i,ce)&&ue(s,o,r)&&he(s.grant,t.getCounterparty(),t.getSrc(),r)}function gt(n,t,e){try{return n.hasCapability(t,e)}catch{return!1}}function ue(n,t,e){return!!n.mcp?.tools.some(o=>o.name===t&&o.capability===e)}function he(n,t,e,o){for(let r in n??{}){if(!mt(t.toLowerCase(),r.toLowerCase()))continue;let s=n[r];if(Array.isArray(s)){if(s.includes(o))return!0;continue}for(let i in s)if(mt(e,i)&&pe(s[i]).includes(o))return!0}return!1}function pe(n){return n.split(le).filter(t=>t.length>0)}function mt(n,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(n)}var yt="x-forwarded-host",wt="x-forwarded-proto",Tt="x-forwarded-pathname",K="x-tabserver-continuation";function de(n){return n.headers.has(wt)?n.headers.get(wt)+":":new URL(n.url).protocol}function ge(n){return n.headers.has(yt)?n.headers.get(yt)||"":new URL(n.url).host}function me(n){return n.headers.has(Tt)?n.headers.get(Tt)||"":new URL(n.url).pathname}function fe(n){let t=de(n),e=ge(n),o=me(n);return new URL(`${t}//${e}${o}`)}function xn(n){let t=new URL(n.url),e=fe(n);return e.search=t.search,e.hash=t.hash,e}function bn(n){return new URL(n.url).pathname}function vn(n,t){let e=ye(n);return t in e?e[t]:null}function ye(n){let t={},e=n.headers.get("Cookie");if(e)for(let o of e.split("; ")){let[r,s]=o.split("=");t[r]=s}return t}var we=4,Te=.2,Ct=d.TOKEN_HEADER,St=class{#t;#e;#n;#s;#o;#r;#l;#p;#h;#a=new Map;#u=new Map;#f=new m;#i;#y;constructor(t){this.#t=t.targetScope,this.#e=t.defaultSystemPrompt,this.#n=t.defaultTemperature??Te,this.#s=t.defaultModel,this.#o=t.maxToolRounds??we,this.#r=t.mcpPath??"/rpc",this.#l=t.resolveToolProviders,this.#p=t.resolveMemorySelection,this.#h=t.resolveStructuredMemorySelection,this.#i={temperature:this.#n,toolsEnabled:!0,toolDetails:!0,thinking:t.defaultThinking??!1},this.#y=new D(new X(this),{context:Ie,serverInfo:{name:"ai-chat-expert",version:"1"}})}async handler(t){if(m.shouldHandle(t))return await this.#f.handler(t);try{if(t.method!=="POST")throw"405 Method Not Allowed";let e=new URL(t.url);if(e.pathname===this.#r)return await this.#y.handle(t);switch(e.pathname){case"/session":return g({ok:await this.#K(t)});case"/settings":return g({ok:await this.#B(t)});case"/models":return g({ok:await this.#_(t)});case"/chats":return g({ok:await this.#V(t)});case"/send":return this.#w(t)?this.#m(o=>this.#M(t,o)):g({ok:await this.#M(t,[])});case"/client-tool-results":return this.#w(t)?this.#m(o=>this.#U(t,o)):g({ok:await this.#U(t,[])});case"/close":return g({ok:await this.#H(t)});case"/delete":return g({ok:await this.#Y(t)});default:throw"404 Not Found"}}catch(e){return console.error(e),g({error:String(e)})}}#w(t){return t.headers.get("Accept")?.includes(H)??!1}#m(t){let e=new TextEncoder,o=new ReadableStream({start:async r=>{let s=a=>r.enqueue(e.encode(`${JSON.stringify(a)}
16
+ `)),i=new F(a=>s({type:"event",event:a}));try{let a=await t(i);s({type:"done",...a.clientToolCalls?.length?{clientToolCalls:a.clientToolCalls}:{}})}catch(a){console.error(a),s({type:"error",message:String(a)})}finally{r.close()}}});return new Response(o,{status:200,headers:{"Content-Type":H,"Cache-Control":"no-cache","Access-Control-Allow-Origin":"*"}})}async askExpert(t,e){let o=e.trim();if(!o)throw"Question is required";let r=this.#N(void 0),s=C(t),i=await this.#R(r,{expert:!0},s),a=this.#i.temperature,l=t.headers.get(K),c=l?Pe(t,l):null;if(c)return await this.#T(t,r,s,c,i,a,o);let u=await this.#d(t,r,void 0,i,a);try{return{answer:await this.#C(u,o,a)}}finally{this.#a.delete(T(t,u.targetParty,u.chatId)),await this.#c(u.targetParty,"/ai/chat/close",{chatId:u.chatId},u.forward).catch(h=>console.error(h))}}async#T(t,e,o,r,s,i,a){let l=this.#u.get(r);try{let c=await this.#d(t,e,l,s,i);return l||this.#u.set(r,c.chatId),{answer:await this.#C(c,a,i)}}catch(c){if(l&&await this.#x(e,l,o)){this.#u.delete(r),this.#a.delete(T(t,e,l));let u=await this.#d(t,e,void 0,s,i);return this.#u.set(r,u.chatId),{answer:await this.#C(u,a,i)}}throw c}finally{let c=this.#u.get(r);c&&this.#a.delete(T(t,e,c))}}async askExpertConversation(t,e,o,r){let s=e.trim();if(!s)throw"Question is required";let i=this.#N(void 0),a=C(t),l=await this.#R(i,{expert:!0},a),c=this.#i.temperature,u=a.continuation,h=u?bt(o,u):r?xt(o,r):null,p=h?this.#u.get(h):void 0,y=async S=>{let f=await this.#d(t,i,S,l,c);this.#u.set(xt(o,f.chatId),f.chatId),u&&this.#u.set(bt(o,u),f.chatId);try{return{answer:await this.#C(f,s,c),conversationId:f.chatId}}finally{this.#a.delete(T(t,i,f.chatId))}};try{return await y(p)}catch(S){if(p&&await this.#x(i,p,a))return h&&this.#u.delete(h),this.#a.delete(T(t,i,p)),await y(void 0);throw S}}async#C(t,e,o){q(t),t.toolRounds=0,await this.#S(t);let r=[],s=await this.#c(t.targetParty,"/ai/chat/send",{chatId:t.chatId,message:e,options:this.#A(t,this.#i.toolsEnabled,o)},t.forward),i=await this.#P(t,s.message,this.#i.toolsEnabled,!1,o,r);if(i.clientToolCalls?.length)throw"Expert MCP cannot execute browser client tools";let a=Me(i.events);if(!a)throw"Expert did not return an answer";return a}async#M(t,e){let o=await Rt(t);if(typeof o.message!="string"||!o.message.trim())throw"Message is required";let r=o.message.trim(),s=this.#G(o),i=this.#E(o),a=this.#k(o),l=this.#g(o),c=k(o),u=await this.#d(t,l,c,void 0,a,this.#D(o));return q(u),u.toolRounds=0,Pt(u,o),s&&await this.#S(u),await this.#J(e,async()=>{let h=await this.#c(u.targetParty,"/ai/chat/send",{chatId:u.chatId,message:r,options:this.#A(u,s,a)},u.forward);return await this.#P(u,h.message,s,i,a,e)})}async#J(t,e){try{return await e()}catch(o){return t.push({role:"assistant",content:String(o),error:!0}),{events:t}}}async#U(t,e){let o=await Rt(t),r=this.#G(o),s=this.#E(o),i=this.#k(o),a=this.#g(o),l=k(o),c=await this.#d(t,a,l,void 0,i);Pt(c,o);let u=Se(c,o.toolResults);for(let p of u)O(e,p.name??"client_tool",p.content,s,p.isError);let h=[...c.pendingToolResults,...u];return q(c),await this.#J(e,()=>this.#L(c,h,r,s,i,e))}async#P(t,e,o,r,s,i){let a=e;for(;;){Y(i,a);let l=a.toolCalls??[];if(!l.length)return{events:i};if(t.toolRounds>=this.#o)return i.push({role:"tool-result",content:"Stopped after too many tool rounds.",error:!0}),{events:i};let{toolResults:c,clientToolCalls:u}=await ke(t,l,r,i);if(u.length)return t.pendingClientToolCalls=new Map(u.map(p=>[p.id,p])),t.pendingToolResults=c,{events:i,clientToolCalls:u};let h=await this.#L(t,c,o,r,s,i);return h.clientToolCalls?.length,h}}async#L(t,e,o,r,s,i){if(t.toolRounds>=this.#o)return i.push({role:"tool-result",content:"Stopped after too many tool rounds.",error:!0}),{events:i};t.toolRounds++;let a=await this.#c(t.targetParty,"/ai/chat/send",{chatId:t.chatId,message:{role:"user",content:"",toolResults:e},options:this.#A(t,o,s)},t.forward);return await this.#P(t,a.message,o,r,s,i)}async#K(t){let e=await x(t),o=this.#g(e),r=k(e),s=C(t),i=await this.#d(t,o,r,r?void 0:await this.#Q(e,o,s),this.#k(e),this.#D(e));Ot(i,e.clientTools),await this.#S(i);let a=await this.#W(i);return{chatId:i.chatId,history:a,historyEvents:dt(a,{toolDetails:this.#E(e),clientToolNames:i.clientToolNames}),closed:r?await this.#x(o,r,s):null}}async#B(t){let e=await x(t);return Object.keys(e).length&&this.#ot(e),this.#nt()}async#_(t){let e=await x(t),o=this.#g(e),r=await this.#c(o,"/ai/chat/models",{},C(t));return{models:Array.isArray(r.models)?r.models:[]}}async#V(t){let e=await x(t),o=this.#g(e),r=await this.#c(o,"/ai/chat/list",{},C(t));return{chats:Array.isArray(r.chats)?r.chats:[]}}async#H(t){let e=await x(t),o=this.#g(e),r=k(e);if(!r)throw"chatId is required";let s=C(t),i=T(t,o,r),a=this.#a.get(i);return a?(await this.#c(a.targetParty,"/ai/chat/close",{chatId:a.chatId},a.forward),this.#a.delete(i),!0):(await this.#c(o,"/ai/chat/close",{chatId:r},s),!0)}async#Y(t){let e=await x(t),o=this.#g(e),r=k(e);if(!r)throw"chatId is required";let s=T(t,o,r);return await this.#c(o,"/ai/chat/delete",{chatId:r},C(t)),this.#a.delete(s),!0}async#d(t,e,o,r,s=this.#n,i=this.#s){let a=T(t,e,o);if(o){let h=this.#a.get(a);if(h)return h}let l=C(t),c=o?{id:o}:await this.#c(e,"/ai/chat/create",{system:r??await this.#R(e,{expert:!1},l),temperature:s,...i?{model:i}:{}},l);l.continuation??=String(c.id),a=T(t,e,String(c.id));let u={chatId:String(c.id),targetParty:e,forward:l,toolRuntime:await this.#X(e,l),clientTools:[],clientToolNames:new Set,pendingClientToolCalls:new Map,pendingToolResults:[],toolRounds:0};return await this.#S(u),this.#a.set(a,u),u}async#W(t){let e=await this.#c(t.targetParty,"/ai/chat/history",{chatId:t.chatId},t.forward);return Array.isArray(e.messages)?e.messages:[]}async#x(t,e,o){let r=await this.#c(t,"/ai/chat/list",{},o),i=(Array.isArray(r.chats)?r.chats:[]).find(a=>a.id===e);return typeof i?.closed=="string"?i.closed:null}#j(t,e,o,r,s){return new J({postParty:(i,a)=>this.#c(t,i,this.#q(i,a,r,s),e,o),postPartyRaw:(i,a)=>this.#O(t,i,a,e,o)})}#q(t,e,o,r){if(t!=="/ai/memory/catalog")return e;let s=e.kind==="structured"?r:o;return s?{...e,collections:s}:e}async#b(t,e){if(this.#p&&t===m.getConfig().system.party)return await this.#p(t,e??{pre:[],continuation:null})}async#v(t,e){if(this.#h&&t===m.getConfig().system.party)return await this.#h(t,e??{pre:[],continuation:null})}async#X(t,e){let o=await this.#l?.(t,e);if(!o?.length)return this.#j(t,e,void 0,await this.#b(t,e),await this.#v(t,e));let r=m.getConfig().system.party;return new U(await Promise.all(o.map(async s=>({key:s.party,runtime:s.party===r?this.#j(s.party,e,s.scope,await this.#b(s.party,e),await this.#v(s.party,e)):this.#z(s.party,e),allowedTools:s.tools?new Set(s.tools):void 0}))))}#z(t,e){return new L({postRpc:o=>this.#O(t,"/mcp/rpc",o,e)})}async#S(t){await t.toolRuntime.refreshCatalog()}#A(t,e,o){let r=this.#i.thinking,s={temperature:o,thinking:r};if(!e)return s;let i=t.toolRuntime.chatTools({clientTools:t.clientTools});return i.length?{...s,tools:i,toolChoice:"auto"}:s}async#c(t,e,o,r,s){let i=await this.#O(t,e,o,r,s);if("error"in i)throw i.error;return i.ok}async#O(t,e,o,r,s){let i=m.getConfig(),a=new URL(i.system.source),l=`${a.origin}${a.pathname}${a.search}`,c=new URL(`${i.system.protocol}//${i.system.party}`).host,u=(r?.pre??[]).filter(f=>!(f.counterparty===c&&f.src===l)),h=await m.getTokenFor({[i.system.source]:s??this.#t},t,null,void 0,u),p=`${i.system.protocol}//${t}${e}`,y={"Content-Type":"application/json","X-Tabserver-Token":h.asSignedBase64()};return r?.continuation&&(y[K]=r.continuation),await(await fetch(p,{method:"POST",headers:y,body:JSON.stringify(o)})).json()}async#Q(t,e,o){let r=typeof t.systemPrompt=="string"&&t.systemPrompt.trim()?t.systemPrompt.trim():this.#$();return await this.#R(e,{basePrompt:r,expert:!1},o)}#D(t){return typeof t.model=="string"&&t.model.trim()?t.model.trim():void 0}#k(t){return typeof t.temperature=="number"&&Number.isFinite(t.temperature)&&t.temperature>=0&&t.temperature<=2?Math.round(t.temperature*10)/10:this.#i.temperature}#G(t){return typeof t.toolsEnabled=="boolean"?t.toolsEnabled:this.#i.toolsEnabled}#E(t){return typeof t.toolDetails=="boolean"?t.toolDetails:this.#i.toolDetails}#g(t){return this.#N(t.targetParty)}#N(t){let{system:{party:e,protocol:o}}=m.getConfig();if(t==null||t==="")return e;if(typeof t!="string")throw"targetParty must be a string";let r=t.trim();if(!r)return e;try{let s=r.includes("://")?new URL(r):new URL(`${o}//${r}`);if(!s.host)throw"missing host";return s.host}catch{throw`Invalid targetParty: ${t}`}}async#R(t,e,o){let r=e.basePrompt??this.#$(),s=await Le(),i=e.expert&&s?`
17
+ When answering expert MCP questions, prefer semantic and structured memory under root "${s}" when looking up remembered information.`:"",a=await this.#Z(t,o),l=await this.#et(t,o);return`${r}${i}${a}${l}`}async#Z(t,e){try{let o=await this.#b(t,e),r=z(),s=r?await this.#tt(t,r,e,o):await this.#I(t,{collections:o},e);return Je(s)}catch{return`
18
18
 
19
- Semantic memory catalog is unavailable for this session.`}}async#tt(t,e,o,r){let s=await this.#E(t,{root:e,collections:r},o);return s.length?s:await this.#E(t,{collections:r},o)}async#E(t,e,o){let r=await this.#c(t,"/ai/memory/catalog",{kind:"semantic",...e.root?{root:e.root}:{},...e.collections?{collections:e.collections}:{}},o);return Array.isArray(r.resources)?r.resources:[]}async#et(t,e){try{let o=await this.#P(t,e),r=z(),s=r?await this.#F(t,{root:r,collections:o},e):[],i=r&&s.length?s:await this.#F(t,{collections:o},e);return Ne(i)}catch{return`
19
+ Semantic memory catalog is unavailable for this session.`}}async#tt(t,e,o,r){let s=await this.#I(t,{root:e,collections:r},o);return s.length?s:await this.#I(t,{collections:r},o)}async#I(t,e,o){let r=await this.#c(t,"/ai/memory/catalog",{kind:"semantic",...e.root?{root:e.root}:{},...e.collections?{collections:e.collections}:{}},o);return Array.isArray(r.resources)?r.resources:[]}async#et(t,e){try{let o=await this.#v(t,e),r=z(),s=r?await this.#F(t,{root:r,collections:o},e):[],i=r&&s.length?s:await this.#F(t,{collections:o},e);return Ue(i)}catch{return`
20
20
 
21
- Structured memory catalog is unavailable for this session.`}}async#F(t,e,o){let r=await this.#c(t,"/ai/memory/catalog",{kind:"structured",...e.root?{root:e.root}:{},...e.collections?{collections:e.collections}:{}},o);return Array.isArray(r.resources)?r.resources:[]}#N(){return this.#i.systemPrompt??this.#e}#ot(){return{...this.#i,systemPrompt:this.#N()}}#nt(t){if(t.systemPrompt!==void 0){if(typeof t.systemPrompt!="string")throw"systemPrompt must be a string";this.#i.systemPrompt=t.systemPrompt.trim()?t.systemPrompt:this.#e}if(t.temperature!==void 0){if(typeof t.temperature!="number"||!Number.isFinite(t.temperature)||t.temperature<0||t.temperature>2)throw"temperature must be between 0 and 2";this.#i.temperature=Math.round(t.temperature*10)/10}if(t.toolsEnabled!==void 0){if(typeof t.toolsEnabled!="boolean")throw"toolsEnabled must be a boolean";this.#i.toolsEnabled=t.toolsEnabled}if(t.toolDetails!==void 0){if(typeof t.toolDetails!="boolean")throw"toolDetails must be a boolean";this.#i.toolDetails=t.toolDetails}if(t.thinking!==void 0){if(typeof t.thinking!="boolean")throw"thinking must be a boolean";this.#i.thinking=t.thinking}}};async function At(n){if(!n.headers.get("Content-Type")?.startsWith("application/json"))throw"Content-Type must be 'application/json'";let t=await n.json();if(!t||typeof t!="object"||Array.isArray(t))throw"Request body must be an object";return t}async function S(n){if(!n.headers.get("Content-Type")?.startsWith("application/json"))return{};let t=await n.json();return!t||typeof t!="object"||Array.isArray(t)?{}:t}function vt(n,t){Object.hasOwn(t,"clientTools")&&Ot(n,t.clientTools)}function Ot(n,t){let e=Array.isArray(t)?t.filter(we):[];n.clientTools=e,n.clientToolNames=new Set(e.map(o=>o.name))}function we(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&typeof n.name=="string"&&n.execution==="client"}function Te(n,t){if(!Array.isArray(t))throw"toolResults must be an array";let e=new Set(n.pendingClientToolCalls.keys());if(!e.size)throw"No pending client tool calls";let o=[];for(let r of t){if(!Ce(r))throw"Invalid client tool result";if(!e.delete(r.toolCallId))throw`Unexpected client tool result: ${r.toolCallId}`;if(n.pendingClientToolCalls.get(r.toolCallId)?.name!==r.name)throw`Client tool result name mismatch: ${r.toolCallId}`;o.push(r)}if(e.size)throw`Missing client tool results: ${[...e].join(", ")}`;return o}function Ce(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.toolCallId=="string"&&typeof n.name=="string"&&typeof n.content=="string"&&(n.isError===void 0||typeof n.isError=="boolean")}function X(n){n.pendingClientToolCalls.clear(),n.pendingToolResults=[]}function O(n){if(!(n.chatId===void 0||n.chatId===null||n.chatId==="")){if(typeof n.chatId!="string")throw"chatId must be a string";return n.chatId}}function w(n,t,e){return`${Re(n)}
21
+ Structured memory catalog is unavailable for this session.`}}async#F(t,e,o){let r=await this.#c(t,"/ai/memory/catalog",{kind:"structured",...e.root?{root:e.root}:{},...e.collections?{collections:e.collections}:{}},o);return Array.isArray(r.resources)?r.resources:[]}#$(){return this.#i.systemPrompt??this.#e}#nt(){return{...this.#i,systemPrompt:this.#$()}}#ot(t){if(t.systemPrompt!==void 0){if(typeof t.systemPrompt!="string")throw"systemPrompt must be a string";this.#i.systemPrompt=t.systemPrompt.trim()?t.systemPrompt:this.#e}if(t.temperature!==void 0){if(typeof t.temperature!="number"||!Number.isFinite(t.temperature)||t.temperature<0||t.temperature>2)throw"temperature must be between 0 and 2";this.#i.temperature=Math.round(t.temperature*10)/10}if(t.toolsEnabled!==void 0){if(typeof t.toolsEnabled!="boolean")throw"toolsEnabled must be a boolean";this.#i.toolsEnabled=t.toolsEnabled}if(t.toolDetails!==void 0){if(typeof t.toolDetails!="boolean")throw"toolDetails must be a boolean";this.#i.toolDetails=t.toolDetails}if(t.thinking!==void 0){if(typeof t.thinking!="boolean")throw"thinking must be a boolean";this.#i.thinking=t.thinking}}};async function Rt(n){if(!n.headers.get("Content-Type")?.startsWith("application/json"))throw"Content-Type must be 'application/json'";let t=await n.json();if(!t||typeof t!="object"||Array.isArray(t))throw"Request body must be an object";return t}async function x(n){if(!n.headers.get("Content-Type")?.startsWith("application/json"))return{};let t=await n.json();return!t||typeof t!="object"||Array.isArray(t)?{}:t}function Pt(n,t){Object.hasOwn(t,"clientTools")&&Ot(n,t.clientTools)}function Ot(n,t){let e=Array.isArray(t)?t.filter(Ce):[];n.clientTools=e,n.clientToolNames=new Set(e.map(o=>o.name))}function Ce(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&typeof n.name=="string"&&n.execution==="client"}function Se(n,t){if(!Array.isArray(t))throw"toolResults must be an array";let e=new Set(n.pendingClientToolCalls.keys());if(!e.size)throw"No pending client tool calls";let o=[];for(let r of t){if(!Re(r))throw"Invalid client tool result";if(!e.delete(r.toolCallId))throw`Unexpected client tool result: ${r.toolCallId}`;if(n.pendingClientToolCalls.get(r.toolCallId)?.name!==r.name)throw`Client tool result name mismatch: ${r.toolCallId}`;o.push(r)}if(e.size)throw`Missing client tool results: ${[...e].join(", ")}`;return o}function Re(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.toolCallId=="string"&&typeof n.name=="string"&&typeof n.content=="string"&&(n.isError===void 0||typeof n.isError=="boolean")}function q(n){n.pendingClientToolCalls.clear(),n.pendingToolResults=[]}function k(n){if(!(n.chatId===void 0||n.chatId===null||n.chatId==="")){if(typeof n.chatId!="string")throw"chatId must be a string";return n.chatId}}function T(n,t,e){return`${ve(n)}
22
22
  ${t}
23
- ${e??"default"}`}function Se(n,t){try{let e=g.from(n);return e?`${e.getSub()}
23
+ ${e??"default"}`}function Pe(n,t){try{let e=d.from(n);return e?`${e.getSub()}
24
24
  ${e.getSrc()}
25
- ${t}`:null}catch{return null}}function Re(n){let t=n.headers.get(xt);if(t)return t;let e=n.headers.get(v);if(e)return e;throw`This request must provide a token in '${xt}'`}function T(n){let t=n.headers.get(v);return{oauthContext:t,counterpartyContext:xe(n,t),continuation:n.headers.get(_)}}function xe(n,t){let e=n.headers.get(W);if(e)return e;if(t)return null;try{let o=g.from(n);return o?JSON.stringify({counterparty:o.getCounterparty(),src:o.getSrc()}):null}catch{return null}}async function Pe(n,t,e,o){let r=[],s=[];for(let i of t){let a=n.clientToolNames.has(i.name);if(e&&o.push({role:"tool",content:Y(i,a)}),a){s.push(i);continue}try{let l=await n.toolRuntime.executeToolCall(i);A(o,i.name,l,e),r.push({toolCallId:i.id,name:i.name,content:l})}catch(l){let c=String(l);A(o,i.name,c,e,!0),r.push({toolCallId:i.id,name:i.name,content:c,isError:!0})}}return{toolResults:r,clientToolCalls:s}}var q=class{#t;constructor(t){this.#t=t}listTools(){return[be()]}async callTool(t,e,o){if(t!==Q)throw new f(-32602,`Unknown tool: ${t}`);if(Ae(o),typeof e.question!="string"||!e.question.trim())throw"question is required";return await this.#t.askExpert(o.request,e.question)}};function be(){return{name:Q,title:"Ask Expert",description:"Ask this AI Chat expert a question. The expert may use its configured memory and tools before answering.",inputSchema:{type:"object",properties:{question:{type:"string",description:"Question to ask the expert."}},required:["question"],additionalProperties:!1},outputSchema:{type:"object",properties:{answer:{type:"string"}},required:["answer"],additionalProperties:!1},annotations:{readOnlyHint:!0,destructiveHint:!1}}}function Ae(n){if(!Tt({token:n.token,providerSource:n.source,toolName:Q,capability:Pt,providerYaml:n.yaml}))throw`Missing capability: ${Pt}`}function ve(n){let{system:{party:t,source:e,protocol:o,sourcePrefix:r},content:{yaml:s}}=m.getConfig();return{party:t,source:e,protocol:o,sourcePrefix:r,yaml:s,token:Oe(n),request:n}}function Oe(n){let t=g.from(n);if(t)return t;let e=n.headers.get(v);return e?new F(JSON.parse(e)):null}function ke(n){for(let t=n.length-1;t>=0;t--){let e=n[t];if(e.role==="assistant"&&!e.error)return e.content}return null}function Ee(n){if(!n.length)return`
25
+ ${t}`:null}catch{return null}}function xt(n,t){return`${n}
26
+ ${t}`}function bt(n,t){return`${n}
27
+ continuation
28
+ ${t}`}function xe(n){if(!n)return null;try{let t=n.getCounterparty();return t?`${t}
29
+ ${n.getSrc()}`:null}catch{return null}}function be(n){return vt(n.outputSchema)||vt(n.inputSchema)}function vt(n){let t=n?.properties;return!!(t&&"conversationId"in t)}function ve(n){let t=n.headers.get(Ct);if(t)return t;throw`This request must provide a token in '${Ct}'`}function C(n){return{pre:Ae(n),continuation:n.headers.get(K)}}function Ae(n){let t=[];try{let e=d.from(n);if(e){t.push({counterparty:e.getCounterparty(),src:e.getSrc()});for(let o of e.getPre())t.push({counterparty:o.counterparty,src:o.src})}}catch{}return Oe(t)}function Oe(n){let t=new Set,e=[];for(let o of n){let r=`${o.counterparty}
30
+ ${o.src}`;t.has(r)||(t.add(r),e.push(o))}return e}async function ke(n,t,e,o){let r=[],s=[];for(let i of t){let a=n.clientToolNames.has(i.name);if(e&&o.push({role:"tool",content:W(i,a)}),a){s.push(i);continue}try{let l=await n.toolRuntime.executeToolCall(i);O(o,i.name,l,e),r.push({toolCallId:i.id,name:i.name,content:l})}catch(l){let c=String(l);O(o,i.name,c,e,!0),r.push({toolCallId:i.id,name:i.name,content:c,isError:!0})}}return{toolResults:r,clientToolCalls:s}}var X=class{#t;constructor(t){this.#t=t}listTools(t){return At(t).map(Ee)}async callTool(t,e,o){let r=At(o).find(i=>i.name===t);if(!r)throw new w(-32602,`Unknown tool: ${t}`);if(Ne(o,r),typeof e.question!="string"||!e.question.trim())throw"question is required";let s=be(r)?xe(o.token):null;if(s){let i=typeof e.conversationId=="string"&&e.conversationId?e.conversationId:null;return await this.#t.askExpertConversation(o.request,e.question,s,i)}return await this.#t.askExpert(o.request,e.question)}};function At(n){return n?.yaml?.mcp?.tools??[]}function Ee(n){return{name:n.name,...n.title===void 0?{}:{title:n.title},description:n.description,inputSchema:n.inputSchema,...n.outputSchema===void 0?{}:{outputSchema:n.outputSchema},...n.annotations===void 0?{}:{annotations:n.annotations}}}function Ne(n,t){let e=t.capability;if(!e)throw`Tool '${t.name}' declares no capability`;if(!ft({token:n.token,providerSource:n.source,toolName:t.name,capability:e,providerYaml:n.yaml}))throw`Missing capability: ${e}`}function Ie(n){let{system:{party:t,source:e,protocol:o,sourcePrefix:r},content:{yaml:s}}=m.getConfig();return{party:t,source:e,protocol:o,sourcePrefix:r,yaml:s,token:$e(n),request:n}}function $e(n){return d.from(n)}function Me(n){for(let t=n.length-1;t>=0;t--){let e=n[t];if(e.role==="assistant"&&!e.error)return e.content}return null}function Je(n){if(!n.length)return`
26
31
 
27
32
  Available semantic memories:
28
- None discovered.`;let t=["","","Available semantic memories:","Use semantic_query with the exact root and collection when these memories are relevant."];for(let e of n){let o=R(e.root),r=R(e.collection);if(!o||!r)continue;t.push(`- root: ${o}`),t.push(` collection: ${r}`);let s=R(e.description);s&&t.push(` description: ${s}`);let i=K(e.schema),a=kt(i?.textProperties);a.length&&t.push(` textProperties: ${a.join(", ")}`);let l=K(i?.propertyTypes);l&&t.push(` propertyTypes: ${JSON.stringify(l)}`),t.push(` query with: semantic_query({ root: ${JSON.stringify(o)}, collection: ${JSON.stringify(r)}, query: { text: "<search text>", limit: 5 } })`)}return t.join(`
29
- `)}function Ne(n){if(!n.length)return`
33
+ None discovered.`;let t=["","","Available semantic memories:","Use semantic_query with the exact root and collection when these memories are relevant."];for(let e of n){let o=b(e.root),r=b(e.collection);if(!o||!r)continue;t.push(`- root: ${o}`),t.push(` collection: ${r}`);let s=b(e.description);s&&t.push(` description: ${s}`);let i=B(e.schema),a=kt(i?.textProperties);a.length&&t.push(` textProperties: ${a.join(", ")}`);let l=B(i?.propertyTypes);l&&t.push(` propertyTypes: ${JSON.stringify(l)}`),t.push(` query with: semantic_query({ root: ${JSON.stringify(o)}, collection: ${JSON.stringify(r)}, query: { text: "<search text>", limit: 5 } })`)}return t.join(`
34
+ `)}function Ue(n){if(!n.length)return`
30
35
 
31
36
  Available structured memories:
32
- None discovered.`;let t=["","","Available structured memories:","Use structured_query with the exact root and collection when these memories are relevant."];for(let e of n){let o=R(e.root),r=R(e.collection);if(!o||!r)continue;t.push(`- root: ${o}`),t.push(` collection: ${r}`);let s=R(e.description);s&&t.push(` description: ${s}`);let i=K(e.schema),a=kt(i?.textProperties);a.length&&t.push(` textProperties: ${a.join(", ")}`);let l=K(i?.propertyTypes);l&&t.push(` propertyTypes: ${JSON.stringify(l)}`),t.push(` query with: structured_query({ root: ${JSON.stringify(o)}, collection: ${JSON.stringify(r)}, query: { limit: 5 } })`)}return t.join(`
33
- `)}function R(n){return typeof n=="string"?n:""}function K(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function kt(n){return Array.isArray(n)?n.filter(t=>typeof t=="string"):[]}function z(){let{system:{source:n}}=m.getConfig();return new URL(n).searchParams.get("root")?.trim().replace(/^\/+|\/+$/g,"")||void 0}async function Ie(){let{system:{source:n}}=m.getConfig(),t=new URL(n),e=z();return e||(t.hash="",await k(t))}export{J as AgentToolRuntime,$ as AggregateToolRuntime,y as BrowserApp,Yt as CONFIG_PATH,_ as CONTINUATION_HEADER,W as COUNTERPARTY_CONTEXT_HEADER,M as ClientToolRegistry,ct as DAEMON_PREFIX,Wt as EVENT_PATH,U as GatewayToolRuntime,bt as GenerativeChatAgent,nt as GenerativeChatClient,Vt as ImgClass,P as JsonRpcMcpClient,j as JsonRpcMcpServer,rt as KeyPair,m as Lifecycle,pt as McpToolRegistry,v as OAUTH_CONTEXT_HEADER,F as OAuthMcpToken,st as ParentHelper,f as ProtocolError,it as QrCode,H as RENDER_STREAM_CONTENT_TYPE,G as RenderEventStream,C as Storage,g as Token,ae as USE_TOOLS_CAPABILITY,V as appendAssistantEvent,se as appendReasoningEvents,A as appendToolResultEvent,ro as buildCookie,at as cloneJSONValue,go as composeToolDescription,Be as createDefaultBrowserChatTools,k as getAppId,pe as getClientHost,ge as getClientPathname,he as getClientProtocol,To as getClientUrl,de as getClientUrlPhp,So as getCookie,me as getCookies,Dt as getItem,Gt as getItemsLike,We as getLaunchAlert,Co as getPathname,Tt as hasMcpToolCapability,mt as historyToRenderEvents,to as isDefined,qt as mcpToolErrorMessage,gt as mcpToolResult,Ze as notNull,Ft as removeItem,d as response,no as response302,oo as response404,jt as setItem,Me as shortHexDigest,Nt as shortSafeDigest,Zt as toChatTool,ft as tokenHasCapability,Y as toolCallMessage,ie as toolResultMessage,ce as yamlDeclaresMcpToolCapability,le as yamlGrantsCapability};
37
+ None discovered.`;let t=["","","Available structured memories:","Use structured_query with the exact root and collection when these memories are relevant."];for(let e of n){let o=b(e.root),r=b(e.collection);if(!o||!r)continue;t.push(`- root: ${o}`),t.push(` collection: ${r}`);let s=b(e.description);s&&t.push(` description: ${s}`);let i=B(e.schema),a=kt(i?.textProperties);a.length&&t.push(` textProperties: ${a.join(", ")}`);let l=B(i?.propertyTypes);l&&t.push(` propertyTypes: ${JSON.stringify(l)}`),t.push(` query with: structured_query({ root: ${JSON.stringify(o)}, collection: ${JSON.stringify(r)}, query: { limit: 5 } })`)}return t.join(`
38
+ `)}function b(n){return typeof n=="string"?n:""}function B(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function kt(n){return Array.isArray(n)?n.filter(t=>typeof t=="string"):[]}function z(){let{system:{source:n}}=m.getConfig();return new URL(n).searchParams.get("root")?.trim().replace(/^\/+|\/+$/g,"")||void 0}async function Le(){let{system:{source:n}}=m.getConfig(),t=new URL(n),e=z();return e||(t.hash="",await E(t))}export{J as AgentToolRuntime,U as AggregateToolRuntime,R as BrowserApp,Wt as CONFIG_PATH,K as CONTINUATION_HEADER,M as ClientToolRegistry,it as DAEMON_PREFIX,qt as EVENT_PATH,L as GatewayToolRuntime,St as GenerativeChatAgent,et as GenerativeChatClient,Yt as ImgClass,v as JsonRpcMcpClient,D as JsonRpcMcpServer,nt as KeyPair,m as Lifecycle,ut as McpToolRegistry,ot as ParentHelper,w as ProtocolError,rt as QrCode,H as RENDER_STREAM_CONTENT_TYPE,F as RenderEventStream,P as Storage,d as Token,ce as USE_TOOLS_CAPABILITY,Y as appendAssistantEvent,ie as appendReasoningEvents,O as appendToolResultEvent,un as buildCookie,st as cloneJSONValue,Tn as composeToolDescription,qe as createDefaultBrowserChatTools,E as getAppId,ge as getClientHost,me as getClientPathname,de as getClientProtocol,xn as getClientUrl,fe as getClientUrlPhp,vn as getCookie,ye as getCookies,Gt as getItem,Ft as getItemsLike,Ze as getLaunchAlert,bn as getPathname,ft as hasMcpToolCapability,dt as historyToRenderEvents,sn as isDefined,zt as mcpToolErrorMessage,ht as mcpToolResult,rn as notNull,Kt as removeItem,g as response,ln as response302,cn as response404,Dt as setItem,je as shortHexDigest,It as shortSafeDigest,te as toChatTool,gt as tokenHasCapability,W as toolCallMessage,ae as toolResultMessage,ue as yamlDeclaresMcpToolCapability,he as yamlGrantsCapability};
34
39
  //# sourceMappingURL=index.js.map