@pagelines/widget 1.0.907 → 1.0.908

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.
Files changed (2) hide show
  1. package/dist/widget.js +1 -1
  2. package/package.json +2 -2
package/dist/widget.js CHANGED
@@ -91,7 +91,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
91
91
  `)}}function i6(e){if(!io(e)||(lt(e.visualType)??lt(e.kind))!=="chart")return null;let n=lt(e.chartType);if(n!=="bar"&&n!=="line"&&n!=="scatter")return null;let i=io(e.xAxis)?e.xAxis:void 0,r=lt(e.xKey)??(i?lt(i.key)??lt(i.dataKey):void 0);if(!r)return null;let o=lt(e.xAxisLabel)??(i?lt(i.label):void 0);if(!Array.isArray(e.series))return null;let a=[];for(let m of e.series){if(!io(m))return null;let h=lt(m.dataKey)??lt(m.key);if(!h)return null;let v=lt(m.label)??lt(m.name);a.push({dataKey:h,...v?{label:v}:{}})}if(a.length===0||!Array.isArray(e.data))return null;let s=e.data.filter(io),l=io(e.meta)?e.meta:e,u=lt(l.title);if(!u)return null;let d=lt(l.description)??lt(l.subtitle),p=lt(l.footer)??lt(l.source),f=lt(e.fallbackMarkdown)??[`| ${yn(o??r)} | ${a.map(m=>yn(m.label??m.dataKey)).join(" | ")} |`,`|---|${a.map(()=>"---:").join("|")}|`,...s.map(m=>`| ${yn(m[r])} | ${a.map(h=>yn(m[h.dataKey])).join(" | ")} |`)].join(`
92
92
  `);return{version:1,visualType:"chart",chartType:n,meta:{title:u,...d?{description:d}:{},...p?{footer:p}:{}},xKey:r,...o?{xAxisLabel:o}:{},series:a,data:s,fallbackMarkdown:f}}function zI(e){let t;try{t=JSON.parse(e)}catch(i){let r=e.match(/"fallbackMarkdown"\s*:\s*"((?:[^"\\]|\\.)*)"/),o;if(r)try{o=JSON.parse(`"${r[1]}"`)}catch{}return{ok:!1,reason:"invalid_json",message:i instanceof Error?i.message:"Invalid JSON",fallbackMarkdown:o}}let n=MS.safeParse(t);if(!n.success){let i=n6(t)??i6(t);if(i){let r=MS.safeParse(i);if(r.success)return{ok:!0,spec:r.data}}return{ok:!1,reason:"invalid_spec",message:n.error.issues.map(r=>r.message).join("; "),fallbackMarkdown:e6(t)}}return{ok:!0,spec:n.data}}var cA,uA,Nl,Ca,Fn,Yd,Na,dA,qd,AS,BS,fA,HS,KS,wn,SF,IF,EF,TF,NF,ao,PS,gA,so,vA,yA,wA,kA,xA,y0,_A,JS,$A,SA,IA,EA,TA,NA,Mt,CA,zA,OA,AA,DA,PA,AF,qS,YS,XS,g0,PF,RA,QS,UA,RS,jA,MA,LA,eI,LF,tI,VA,FA,BA,rI,Cl,ZA,HA,nI,KA,WA,VF,qA,FF,oI,YA,w0,XA,QA,ZF,HF,KF,WF,GF,aI,eD,tD,rD,US,oD,aD,sI,jS,lI,cD,YF,uD,cI,dD,Bn,dI,pD,pI,fI,mI,hI,fD,rB,mD,hD,k0,nB,vI,iB,oB,aB,gD,vD,sB,lB,uB,bD,dB,pB,yD,fB,mB,wD,hB,yI,kD,v0,yB,wI,xD,_B,kI,_D,xI,$B,SB,$D,IB,EB,SD,ID,Tl,x0,TB,NB,_I,rp,CB,zB,ED,TD,ND,CD,zD,OB,OD,AB,DB,PB,RB,AD,DD,PD,LD,VD,FD,b0,Zn,za,BD,EI,ZD,HD,TI,KD,$0,GD,JD,qD,YD,XD,QD,MS,OI,AI,VB,FB,BB,ZB,HB,KB,Lr,o6,a6,s6,LS,l6,c6,GB,u6,qB,YB,d6,XB,QB,e7,t7,r7,n7,i7,p6,f6,m6,h6,g6,s7,l7,c7,d7,f7,v6,b6,y6,w6,h7,k6,x6,_6,$6,S6,v7,I6,y7,k7,Qd,E6,T6,DI,N6,C6,z6,O6,PI,_7,$7,S7,I7,T7,VS,RI,FS,S0,Ol=Y(()=>{"use strict";Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();Pe();bn();bn();cA=Object.defineProperty,uA=(e,t)=>{for(var n in t)cA(e,n,{get:t[n],enumerable:!0})},Nl={appName:"pagelines-app",tagline:"More than human",zeroState:{title:"Create your first bot",action:"Get started"},defaultWorkspaceName:"My Workspace",port:3222,primaryRegion:"lax",demoBotHandle:"pagelines-demo",liveCanary:{email:"smoke-canary@pagelines.com",botHandle:"seneca"},gtmId:"GTM-WRN7DPK7",ga4MeasurementId:"G-WT51X9S6SK",urls:{app:"https://www.pagelines.com",dev:"https://dev-api.pagelines.com",appStore:"https://apps.apple.com/us/app/pagelines/id6764094785"}},Ca=globalThis.process,Fn=typeof window<"u",Yd=typeof Ca<"u"&&!Fn,Na=Fn?typeof window<"u"&&window.location&&!window.location.hostname.includes("localhost"):Yd&&typeof Ca<"u"&&Ca.env?.NODE_ENV==="production",dA=!Na,qd={error:{priority:50,color:"#FF0000",nodeColor:"\x1B[31m"},warn:{priority:40,color:"#FFA500",nodeColor:"\x1B[33m"},info:{priority:30,color:"#00ABFF",nodeColor:"\x1B[36m"},debug:{priority:20,color:"#00BD0C",nodeColor:"\x1B[32m"},trace:{priority:10,color:"#5233FF",nodeColor:"\x1B[35m"}},AS=["password","token","secret","apikey","authorization","cookie"];BS=new Set(["CONNECT_TIMEOUT","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EHOSTUNREACH","EPIPE"]),fA=new Set([...BS,"CONNECTION_CLOSED","53300"]);HS=class Xd{constructor(t={},n){this.enabledInBrowser=!1,this.context=n,this.settings={enabled:t.enabled??!0,minLevel:t.minLevel??this.getDefaultLevel(),timestamps:t.timestamps??!0},Fn&&this.initBrowserLogging()}getDefaultLevel(){if(Yd&&typeof Ca<"u"&&Ca.env?.LOG_LEVEL)return Ca.env.LOG_LEVEL;if(Fn&&typeof localStorage<"u"&&typeof localStorage.getItem=="function"){let t=localStorage.getItem("PAGELINES_LOG_LEVEL");if(t)return t}return"info"}initBrowserLogging(){if(!Fn)return;let n=typeof localStorage?.getItem=="function"&&localStorage.getItem("PAGELINES_LOG")==="true",i=window.location?.hostname||"";this.enabledInBrowser=dA||n||i==="localhost"||i.includes("127.0.0.1"),Na&&!n&&!Xd.hasShownHelp&&(console.log("%cPageLines Logger (disabled in production)","color: #888; font-size: 12px"),console.log('%cTo enable: localStorage.setItem("PAGELINES_LOG", "true")',"color: #888; font-size: 11px"),Xd.hasShownHelp=!0)}shouldLog(t){if(!this.settings.enabled||Fn&&!this.enabledInBrowser)return!1;let n=qd[t].priority,i=qd[this.settings.minLevel].priority;return n>=i}formatTimestamp(){return new Date().toLocaleTimeString("en-GB",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}formatISOTimestamp(){return new Date().toISOString()}redactSensitive(t){if(typeof t!="object"||t===null)return t;if(Array.isArray(t))return t.map(i=>this.redactSensitive(i));let n={};for(let[i,r]of Object.entries(t))pA(i)?n[i]="[REDACTED]":typeof r=="object"&&r!==null?n[i]=this.redactSensitive(r):n[i]=r;return n}formatData(t,n=5,i=0){if(i>=n)return"[Max Depth]";if(t==null)return t;if(t instanceof Error){let r=ZS(t);if(r){let a={name:t.name,code:r.code},s=mA(r);s&&(a.endpoint=s);let l=DS(t.stack)??DS(t.cause?.stack);return l&&(a.at=l),this.redactSensitive(a)}let o={name:t.name,message:t.message,stack:Na?t.stack?.split(`
93
93
  `).slice(0,3).join(`
94
- `):t.stack};for(let[a,s]of Object.entries(t))o[a]=this.formatData(s,n,i+1);return"cause"in t&&(o.cause=this.formatData(t.cause,n,i+1)),this.redactSensitive(o)}if(t instanceof Date)return t.toISOString();if(typeof t!="object")return t;if(Array.isArray(t))return t.length>20&&Na?`Array(${t.length}) [${t.slice(0,3).map(r=>this.formatData(r,n,i+1)).join(", ")}, ...]`:t.map(r=>this.formatData(r,n,i+1));try{let r={},o=Object.entries(t),a=Na?50:200;for(let[s,l]of o.slice(0,a))r[s]=this.formatData(l,n,i+1);return o.length>a&&(r["..."]=`${o.length-a} more properties`),this.redactSensitive(r)}catch{return"[Unserializable]"}}logToBrowser(t){if(!Fn||!this.shouldLog(t.level))return;let{level:n,description:i,context:r,data:o,error:a}=t,s=qd[n],u=`[${r||this.context||"www"}] ${n.toUpperCase()}:`,d=`color: ${s.color}; font-weight: bold;`;o!==void 0?console[n](`%c${u}`,d,i,this.formatData(o)):console[n](`%c${u}`,d,i),a&&(a instanceof Error?console.error(a):console.error("Error details:",a))}logToNode(t){if(!Yd||!this.shouldLog(t.level))return;let{level:n,description:i,context:r,data:o,error:a}=t,s=r||this.context||"www";if(Na){let l={timestamp:this.formatISOTimestamp(),level:n.toUpperCase(),context:s,msg:i,message:i};o!==void 0&&(l.data=this.formatData(o)),a!==void 0&&(l.error=this.formatData(a));let u=JSON.stringify(l);n==="trace"?console.log(u):console[n](u)}else{let l=qd[n],u=this.formatTimestamp(),d="\x1B[0m",p="\x1B[2m",f=l.nodeColor||"",m=`${p}${u}${d} ${f}${n.toUpperCase()} (${s}):${d} ${i}`;console[n](m),o!==void 0&&console.log(JSON.stringify(this.formatData(o),null,2)),a&&(a instanceof Error?(console.error(`\x1B[31mError:${d}`,a.message),a.stack&&console.error(`\x1B[90m${a.stack}${d}`)):console.error("Error:",a))}}log(t){Fn?this.logToBrowser(t):Yd&&this.logToNode(t)}error(t,n){this.log({level:"error",description:t,data:n,context:this.context})}warn(t,n){this.log({level:"warn",description:t,data:n,context:this.context})}info(t,n){this.log({level:"info",description:t,data:n,context:this.context})}debug(t,n){this.log({level:"debug",description:t,data:n,context:this.context})}trace(t,n){this.log({level:"trace",description:t,data:n,context:this.context})}isEnabled(){return Fn?this.enabledInBrowser:!0}setLevel(t){this.settings.minLevel=t}createContextLogger(t){let n=new Xd(this.settings,t);return{error:(i,r)=>n.error(i,r),warn:(i,r)=>n.warn(i,r),info:(i,r)=>n.info(i,r),debug:(i,r)=>n.debug(i,r),trace:(i,r)=>n.trace(i,r),isEnabled:()=>n.isEnabled(),setLevel:i=>n.setLevel(i)}}};HS.hasShownHelp=!1;KS=HS;wn=new KS,SF=wn.error.bind(wn),IF=wn.warn.bind(wn),EF=wn.info.bind(wn),TF=wn.debug.bind(wn),NF=wn.trace.bind(wn),ao=class{constructor(e,t){this.objectName=e,this.settings=t,this.logger=oo(e)}};PS={green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"}};gA=class{constructor(){this.tokenName="auth-token",this.deviceIdName="pl-device-id",this.tokenMaxAge=3600*24*90,this.fallbackStorageKey="token"}currentCookieOptions(){return hA(typeof window>"u"?void 0:window.location)}getCookie(e){if(typeof document>"u")return null;let t=document.cookie.split(";");for(let n of t){let[i,r]=n.trim().split("=");if(i===e)return decodeURIComponent(r||"")}return null}setCookie(e,t,n={}){if(typeof document>"u")return;let{secure:i=!0,sameSite:r="lax",maxAge:o=3600*24*7,domain:a,path:s="/"}=n,l=`${e}=${encodeURIComponent(t)}`;l+=`; Path=${s}`,l+=`; Max-Age=${o}`,l+=`; SameSite=${r}`,i&&(l+="; Secure"),a&&(l+=`; Domain=${a}`),document.cookie=l}removeCookie(e,t={}){this.setCookie(e,"",{...t,maxAge:0})}isLocalStorageFunctional(){return typeof window<"u"&&typeof window.localStorage?.getItem=="function"&&typeof window.localStorage?.setItem=="function"&&typeof window.localStorage?.removeItem=="function"}getAuthToken(){let e=this.getCookie(this.tokenName);if(e)return e;if(this.isLocalStorageFunctional()){let t=window.localStorage.getItem(this.fallbackStorageKey);if(t)return this.setAuthToken(t),window.localStorage.removeItem(this.fallbackStorageKey),t}return null}setAuthToken(e){let t=this.currentCookieOptions();this.setCookie(this.tokenName,e,{secure:t.secure,sameSite:"lax",maxAge:this.tokenMaxAge,domain:t.domain,path:t.path})}removeAuthToken(){let e=this.currentCookieOptions();this.removeCookie(this.tokenName,{domain:e.domain,path:e.path}),this.removeCookie(this.tokenName,{domain:".pagelines.com",path:"/"}),this.isLocalStorageFunctional()&&window.localStorage.removeItem(this.fallbackStorageKey)}getDeviceId(){return this.getCookie(this.deviceIdName)}},so=new gA,vA=["https://redirect-a.invalid","https://redirect-b.invalid"];yA=c.enum(["linkedin","x","facebook","tiktok","youtube","github","instagram","threads","email","phone","website","calendar"]),wA=c.object({platform:yA,handle:c.string(),url:c.string().optional()}),kA=c.preprocess(e=>Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.platform&&t.handle):e,c.array(wA)),xA=["image","audio","video","document"],y0=c.enum(xA),_A=["avatar","cover","general"],JS=c.enum(_A),$A=c.enum(["processing","active","failed","deleted"]),SA=c.enum(["low","standard","high"]),IA=c.enum(["jpg","jpeg","png","gif","webp","svg"]),EA=c.enum(["mp4","webm","ogg","mov","avi"]),TA=c.enum(["mp3","wav","ogg","opus","aac","flac","webm","m4a","mp4"]),NA=c.object({mediaId:c.string(),userId:c.string(),orgId:c.string(),botId:c.string().nullable().optional(),filename:c.string(),mimeType:c.string(),size:c.number(),src:c.string(),alt:c.string().optional(),context:JS.default("general"),status:$A.default("processing"),quality:SA.default("standard"),createdAt:c.string().optional(),updatedAt:c.string().optional()}),Mt=NA.extend({mediaType:y0.optional(),className:c.string().optional(),width:c.number().optional(),height:c.number().optional(),duration:c.number().optional(),blurhash:c.string().optional()}).partial(),CA=c.object({duration:c.number().optional(),thumbnail:c.string().optional(),autoplay:c.boolean().optional(),loop:c.boolean().optional(),muted:c.boolean().optional(),controls:c.boolean().optional()}),zA=c.object({duration:c.number().optional(),autoplay:c.boolean().optional(),loop:c.boolean().optional(),muted:c.boolean().optional(),controls:c.boolean().optional()}),OA=Mt.extend({mediaType:c.literal("image"),imageFormat:IA.optional()}),AA=Mt.extend({mediaType:c.literal("video"),videoFormat:EA.optional(),video:CA.optional()}),DA=Mt.extend({mediaType:c.literal("audio"),audioFormat:TA.optional(),audio:zA.optional()}),PA=Mt.extend({mediaType:c.literal("document")}),AF=c.discriminatedUnion("mediaType",[OA,AA,DA,PA]),qS=c.enum(["xxs","xs","sm","md","lg","xl"]),YS=c.enum(["primary","default","overlay","red","green","indigo","orange"]),XS=c.enum(["ghost","link","outline","solid"]),g0=c.object({key:c.string().optional(),label:c.string().optional(),href:c.string().optional(),size:qS.optional(),theme:YS.optional(),design:XS.optional(),icon:c.union([c.string(),Mt]).optional(),iconAfter:c.union([c.string(),Mt]).optional(),rounding:c.enum(["full","md","lg"]).optional(),loading:c.boolean().optional(),disabled:c.boolean().optional(),tooltip:c.string().optional(),onClick:c.any().optional(),testId:c.string().optional(),target:c.enum(["_blank","_self"]).optional(),type:c.enum(["button","submit","reset"]).optional()}),PF=c.object({buttons:c.array(g0).optional(),size:qS.optional(),theme:YS.optional(),design:XS.optional()}),RA=["COMPUTER_BOOT_FAILED","COMPUTER_CREATE_FAILED","BOT_DELETED","COMPUTER_DELETE_FAILED","COMPUTER_INACTIVE","COMPUTER_LIMIT","COMPUTER_NOT_FOUND","BOT_NOT_FOUND","COMPUTER_NOT_DEPLOYED","BOT_TOKENS_MISSING","COMPUTER_UNREACHABLE","COMPUTER_UPDATE_FAILED","COMPUTER_WAKE_TIMEOUT","ADMISSION_REQUIRED","ALREADY_MEMBER","ATTACHMENT_TYPE_UNSUPPORTED","AUTH_ACCOUNT_NOT_FOUND","AUTH_BOT_BLOCKED","AUTH_DISPOSABLE_EMAIL","AUTH_EMAIL_IN_USE","AUTH_INVALID","AUTH_INVALID_CODE","AUTH_INVALID_HANDOFF","AUTH_LOCKED_OUT","AUTH_MISSING","AUTH_PROVIDER_FAILED","AUTH_PROVIDER_NOT_CONFIGURED","AUTH_RATE_LIMITED","AUTH_REVOKED","AUTH_TURNSTILE_MISSING","AUTH_UNKNOWN","AUTH_WRONG_TYPE","ROUTINE_CHANNEL_UNAVAILABLE","ROUTINE_PURPOSE_REQUIRED","BOT_REPLY_FAILED","BILLING_BUDGET_REACHED","BILLING_DEMO_SPENT","BILLING_NO_PLAN","BILLING_PAST_DUE","BILLING_RUNAWAY_CAP","BILLING_SEAT_LIMIT","CHECKOUT_FAILED","CONFIRMATION_REQUIRED","CREATE_FAILED","CREDIT_LIMIT","DELETE_FAILED","DUPLICATE_INVITE","EMAIL_DELIVERY_FAILED","EMAIL_FAILED","EMAIL_MISMATCH","EMAIL_RATE_LIMITED","EMAIL_REASON_NOT_ELIGIBLE","EMPTY_STREAM","EMPTY_PATCH","ENV_VAR_CONFLICT","ENV_VAR_RESERVED","EXTENSION_INACTIVE","FORBIDDEN","HANDLE_TAKEN","IMAGE_GENERATION_FAILED","IMAGE_GENERATION_UNCONFIGURED","INTERNAL_ERROR","INVALID_FILE","INVALID_PRIMARY_CHANNEL","UNKNOWN_ROUTINE_CHANNEL","INVITE_CONFLICT","INVITE_EXPIRED","INVITE_INVALID","MCP_NOT_AVAILABLE","MCP_NOT_CONFIGURED","MEDIA_NOT_FOUND","MEDIA_SERVER_UNAVAILABLE","MEDIA_UPLOAD_FAILED","MEMORY_NOT_FOUND","MISSING_IDEMPOTENCY_KEY","NETWORK_ERROR","NO_WORKSPACE","NOT_A_MEMBER","NOT_AUTHORIZED","NOT_FOUND","ORG_NOT_FOUND","OVERAGE_CAP","OWNER_LOCK","PAIRING_VERIFY_FAILED","PAYMENT_FAILED","PLAN_LIMIT","PROVISIONER_UNAVAILABLE","RATE_LIMIT","RATE_LIMITED","REBUILD_FAILED","RESTART_FAILED","SEND_FAILED","STOP_FAILED","STREAM_DISCONNECT","STREAM_TIMEOUT","STRIPE_LOAD","TIMEOUT","TOKEN_ERROR","TOOL_PROTOCOL","TRIAL_ENDED","TURN_ACTIVE","UPLOAD_FAILED","VALIDATION_ERROR","VOICE_BUSY","VOICE_UNAVAILABLE","WAKE_FAILED"],QS=c.enum(RA),UA=4900,RS=`$${UA/100}/month`,jA=c.enum(["account","error"]),MA=["billing_no_plan","billing_seat_limit","billing_past_due","billing_runaway_cap","billing_budget_reached","billing_demo_spent","bot_deleted","computer_not_deployed","computer_boot_failed","computer_unreachable","computer_wake_timeout","stream_timeout","stream_disconnect","empty_stream","tool_protocol","rate_limit"],LA=c.enum(MA),eI=c.object({bucket:jA,code:LA,title:c.string(),help:c.string().optional(),actionLabel:c.string(),actionUrl:c.string()}),LF={billing_no_plan:{bucket:"account",title:"Billing needed",help:`Add a payment method to turn live replies back on. Plans start at ${RS} per active assistant, cancel anytime.`,actionLabel:"Open billing",oneLine:`The workspace needs a payment method before this assistant can reply; plans start at ${RS} per active assistant.`},billing_seat_limit:{bucket:"account",title:"Active assistant limit reached",help:"Your active assistants are all in use. Put one assistant to sleep or ask us to raise the ceiling.",actionLabel:"Open billing",oneLine:"The workspace has no unused active-assistant slots; one assistant must sleep or the limit must be raised."},billing_past_due:{bucket:"account",title:"Assistants paused",help:"Payment is overdue. Fix it and we\u2019ll bring your assistants back online.",actionLabel:"Fix payment",oneLine:"The workspace payment is overdue; its owner must fix it before assistants come back online."},billing_runaway_cap:{bucket:"account",title:"Usage limit reached",help:"Your workspace reached its usage limit. Review billing or contact support to keep your assistant running.",actionLabel:"Contact support",oneLine:"The workspace reached its usage limit; its owner can review billing or contact support."},billing_budget_reached:{bucket:"account",title:"Not enough credits",help:"Your workspace needs more included credits for another reply. Upgrade an assistant or wait for the next billing period.",actionLabel:"Review billing",oneLine:"The workspace needs more included credits; its owner can upgrade an assistant or wait for the next billing period."},billing_demo_spent:{bucket:"account",title:"Demo used up",help:"Your assistant has used the free demo. Starting a trial keeps it running around the clock, and is free for ten days.",actionLabel:"Start free trial",oneLine:"This workspace has used its free demo; starting a trial keeps the assistant running and is free for ten days."},bot_deleted:{bucket:"error",title:"Assistant deleted",help:"This chat is still here, but the assistant can no longer reply.",actionLabel:"",oneLine:"This assistant was deleted. The chat history remains, but it can no longer reply."},computer_not_deployed:{bucket:"error",title:"Assistant asleep",help:"Open the assistant profile to wake it up before chatting.",actionLabel:"Open assistant",oneLine:"This assistant needs to wake up before it can reply."},computer_boot_failed:{bucket:"error",title:"Couldn't wake up",help:"Open the assistant profile to restart it or check what failed.",actionLabel:"Open assistant",oneLine:"This assistant tried to wake up but hit an error."},computer_unreachable:{bucket:"error",title:"Not responding",help:"Open the assistant profile to check status or restart it.",actionLabel:"Open assistant",oneLine:"This assistant is not responding right now; its owner can check its status."},computer_wake_timeout:{bucket:"error",title:"Still waking",help:"Open the assistant profile to check status, or wait a minute and try again.",actionLabel:"Open assistant",oneLine:"This assistant is taking too long to wake up."},stream_timeout:{bucket:"error",title:"Reply too slow",help:"Your assistant took too long to start replying. Try your message again.",actionLabel:"Try again",oneLine:"This assistant took too long to start replying; try the message again."},stream_disconnect:{bucket:"error",title:"Connection lost",help:"The connection dropped while your assistant was replying. Send your message again to retry.",actionLabel:"Try again",oneLine:"The connection dropped while this assistant was replying; try the message again."},empty_stream:{bucket:"error",title:"Empty reply",help:"Your assistant could not generate a reply. Try your message again.",actionLabel:"Try again",oneLine:"This assistant did not return a reply; try the message again."},tool_protocol:{bucket:"error",title:"Tool call failed",help:"Your assistant tried to use a tool in a format PageLines could not run. Try the message again.",actionLabel:"Try again",oneLine:"This assistant tried to use a tool in a format PageLines could not run; try the message again."},rate_limit:{bucket:"error",title:"Slow down",help:"Too many messages at once. Wait a moment, then send your message again.",actionLabel:"Try again",oneLine:"Too many messages arrived at once; wait a moment and try again."}},tI=c.enum(["unknown","stopped","starting","running","unreachable","error"]),VA=c.enum(["wake","restart","rebuild","config_apply","setup"]),FA=c.enum(["running","coalesced","failed"]),BA=c.object({kind:VA,status:FA,startedAt:c.string().datetime(),detail:c.string().optional()}).strict(),rI=c.object({lifecycle:tI,changedAt:c.string().datetime().optional(),detail:c.string().optional(),blocker:eI.optional(),operation:BA.optional()}).strict(),Cl=Object.freeze({lifecycle:"unknown"}),ZA={running:"green",starting:"amber",unreachable:"red",error:"red",stopped:"grey",unknown:"grey"},HA=c.enum(["awake","asleep","changing","stuck"]),nI={awake:"Awake",asleep:"Asleep",changing:"Changing",stuck:"Needs attention"};KA={running:"Online",starting:"Waking up",unreachable:"Unreachable",error:"Error",stopped:"Asleep",unknown:"Checking"},WA={wake:"Waking up",restart:"Restarting",rebuild:"Rebuilding",config_apply:"Applying config",setup:"Setting up"};VF=c.enum(["wake","sleep","restart","rebuild"]);qA=c.object({key:c.string().optional(),id:c.string().optional(),label:c.string().optional(),srLabel:c.string().optional(),subLabel:c.string().optional(),value:c.union([c.string(),c.number()]).optional(),description:c.string().optional(),state:HA.optional(),count:c.number().optional(),className:c.string().optional(),media:Mt.optional(),subMedia:Mt.optional(),cover:Mt.optional(),icon:Mt.optional(),iconAfter:Mt.optional(),subIcon:c.string().optional(),href:c.string().optional(),target:c.enum(["_self","_blank"]).optional(),onClick:c.any().optional(),theme:c.enum(["primary","default"]).optional(),isActive:c.boolean().optional(),isDisabled:c.boolean().optional(),isHidden:c.boolean().optional(),priority:c.number().optional(),testId:c.string().optional(),items:c.array(c.any()).optional(),badges:c.array(g0).optional(),meta:c.array(g0).optional(),menuItems:c.array(c.any()).optional()}),FF=c.object({title:c.string().optional(),description:c.string().optional(),items:c.array(qA).optional()}),oI=c.string().trim().transform(e=>{if(!e.includes("/"))return e;try{let t=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`),[n,i]=t.pathname.split("/").filter(Boolean),r=t.hostname.toLowerCase();if((r==="linkedin.com"||r.endsWith(".linkedin.com"))&&n?.toLowerCase()==="in"&&i)return i}catch{}return e}).pipe(c.string().min(3).max(100).regex(/^[a-zA-Z0-9-]+$/,"Use a LinkedIn username or profile URL")),YA=c.string().trim().transform((e,t)=>{try{let n=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`),i=n.hostname.toLowerCase().replace(/^www\./,""),r=n.pathname.split("/").filter(Boolean)[0];if(!r||!["x.com","twitter.com","facebook.com"].includes(i))throw new Error("unsupported profile");return i==="twitter.com"?`https://x.com/${r}`:`https://${i}/${r}`}catch{return t.addIssue({code:"custom",message:"Use a LinkedIn username or an X or Facebook profile URL"}),c.NEVER}}),w0=c.string().trim().toLowerCase().pipe(c.email()),XA=c.enum(["member","pending"]),QA=c.object({lastBotId:c.string().nullable().optional(),userId:c.string(),email:c.string().optional(),handle:c.string().optional(),fullName:c.string().optional(),bio:c.string().optional(),linkedinUsername:oI.optional(),avatarId:c.string().optional(),avatar:Mt.optional(),isEmailVerified:c.boolean().optional(),primaryOrgId:c.string().optional(),lastActiveOrgId:c.string().optional(),onboarding:c.any().optional(),location:c.string().optional(),geo:c.any().optional(),systemRole:c.string().optional(),status:c.string().optional(),lastSeenAt:c.string().optional(),admittedAt:c.string().optional(),access:XA.optional(),createdAt:c.string().optional(),updatedAt:c.string().optional(),onboarded:c.boolean().optional()}),ZF=c.object({email:w0}),HF=c.object({email:w0,code:c.string().min(6,"Verification code is required"),timezone:c.string().max(64).optional()}),KF=c.object({newEmail:w0}),WF=c.object({credential:c.string().optional(),code:c.string().optional(),timezone:c.string().max(64).optional(),source:c.enum(["web","ios"]).optional()}).refine(e=>e.credential||e.code,{message:"Either credential or code must be provided"}),GF=c.object({identityToken:c.string().min(1),fullName:c.string().optional(),timezone:c.string().max(64).optional()}),aI=c.object({orgId:c.string().optional(),handle:c.string().optional(),name:c.string().optional(),email:c.string().nullable().optional(),website:c.string().url().nullable().optional(),summary:c.string().nullable().optional(),avatarId:c.string().nullable().optional(),avatar:Mt.optional(),coverId:c.string().nullable().optional(),cover:Mt.optional(),accounts:kA.nullable().optional(),ownerId:c.string().optional(),isPersonal:c.boolean().optional(),stripeCustomerIdTest:c.string().nullable().optional(),stripeCustomerIdLive:c.string().nullable().optional(),maxUsers:c.number().optional(),timezone:c.string().nullable().optional(),apiKey:c.string().nullable().optional(),syncedPlan:c.string().nullable().optional(),syncedBillingStatus:c.string().nullable().optional(),firstPaidAt:c.string().nullable().optional(),entitlementDeleteAt:c.string().nullable().optional(),billingLastSyncedAt:c.string().nullable().optional(),syncedPeriodStart:c.string().nullable().optional(),syncedPeriodEnd:c.string().nullable().optional(),onboarding:c.any().optional(),status:c.string().optional(),createdAt:c.string().optional(),updatedAt:c.string().optional()}),eD=c.object({completedAt:c.string().datetime().optional(),setupBy:c.string().optional(),billingSetup:c.boolean().optional(),teamInvitesSetup:c.boolean().optional(),brandingSetup:c.boolean().optional(),domainsSetup:c.boolean().optional()}),tD=c.object({membershipId:c.string(),orgId:c.string(),name:c.string(),handle:c.string(),avatarId:c.string().optional(),avatar:Mt.optional(),coverId:c.string().optional(),cover:Mt.optional(),role:c.enum(["owner","admin","member","observer"]),inviterName:c.string().optional(),memberCount:c.number().optional(),hasComputer:c.boolean().optional(),computerCount:c.number().optional(),joinedAt:c.string().datetime(),onboarding:eD.optional()}),rD=QA.extend({orgs:c.array(tD).optional()}),US=[["#6366f1","#8b5cf6"],["#3b82f6","#06b6d4"],["#10b981","#34d399"],["#f59e0b","#f97316"],["#ef4444","#f97316"],["#ec4899","#8b5cf6"],["#14b8a6","#3b82f6"],["#8b5cf6","#ec4899"]];oD=["[SILENT]","SILENT","NO_REPLY","NO REPLY","NO-OP","NOOP","NO_OP","NO OP","[NO-OP]","[NOOP]","[NO_OP]","[NO OP]","HEARTBEAT_OK"],aD=new Set(oD);sI={wake:300*1e3,bootGrace:420*1e3,provision:600*1e3,firstStart:120*1e3,stop:30*1e3},jS={AUTH_ACCOUNT_NOT_FOUND:"Account not found. Ask your workspace admin for an invite.",AUTH_INVALID:"Your session has expired. Sign in again to continue.",AUTH_LOCKED_OUT:"Too many failed attempts. Request a new code to try again.",AUTH_INVALID_CODE:"That code didn't match. Double-check the email and try again.",AUTH_INVALID_HANDOFF:"This link has expired. Open the dashboard from the app again.",AUTH_DISPOSABLE_EMAIL:"Please use your work email address.",AUTH_RATE_LIMITED:"Too many requests. Wait a minute and try again.",AUTH_PROVIDER_FAILED:"Sign-in failed. Try again or use email instead.",AUTH_PROVIDER_NOT_CONFIGURED:"That sign-in method isn't available right now.",ADMISSION_REQUIRED:"PageLines is invite-only. Request access to create your bot.",PLAN_LIMIT:"Your active computers are all in use. Put one computer to sleep or ask us to raise the ceiling.",CREDIT_LIMIT:"Your workspace reached its usage limit. Review billing or contact support to keep your assistant running.",STRIPE_LOAD:"Couldn't open checkout. Try again \u2014 if it persists, contact support.",CHECKOUT_FAILED:"Couldn't start checkout. Try again in a moment.",PAYMENT_FAILED:"Your payment couldn't go through. Update your card to continue.",WAKE_FAILED:"Your assistant didn't wake up. Try again in a moment.",VOICE_BUSY:"Your assistant is on another call. Try again in a moment.",VOICE_UNAVAILABLE:"Voice isn't available right now. Try again in a moment.",STOP_FAILED:"Couldn't put your assistant to sleep. Try again.",RESTART_FAILED:"Restart didn't finish. Try again \u2014 if it persists, rebuild.",REBUILD_FAILED:"Rebuild didn't finish. Try again or contact support.",CREATE_FAILED:"Couldn't create your assistant. Try again in a moment.",DELETE_FAILED:"Couldn't delete your assistant. Try again \u2014 your data is safe.",BOT_NOT_FOUND:"We couldn't find that assistant.",COMPUTER_NOT_FOUND:"We couldn't find that computer.",COMPUTER_INACTIVE:"This computer is off. Turn it on to start it.",ATTACHMENT_TYPE_UNSUPPORTED:"Your assistant can't read this file type yet.",ROUTINE_CHANNEL_UNAVAILABLE:"Your delivery channel isn't reachable. Pair it again or choose PageLines Messenger.",ROUTINE_PURPOSE_REQUIRED:"Say what the scheduled message or work should contain.",NETWORK_ERROR:"Network issue. Check your connection and try again.",TIMEOUT:"The request took too long. Try again in a moment.",FORBIDDEN:"You don't have access to this.",RATE_LIMITED:"Too many requests. Wait a moment and try again."};lI=c.enum(["active","stopped"]),cD=c.enum(["notFound","busy","rateLimited","timeout","invalidConfig","transient","fatal"]),YF=c.object({ok:c.literal(!1),error:c.string(),code:QS.optional(),issue:eI.optional(),providerErrorKind:cD.optional()}),uD=c.object({kind:c.enum(["icon","favicon","service"]),icon:c.string().min(1).optional(),domain:c.string().min(1).optional(),serviceKey:c.string().min(1).optional()}).strict(),cI=c.object({activityId:c.string().min(1),turnId:c.string().min(1),status:c.enum(["started","completed","failed"]),label:c.string().trim().min(1),kind:c.enum(["search","file","image","service","routine","handoff","other"]),toolName:c.string().min(1).optional(),serviceKey:c.string().min(1).optional(),startedAt:c.string().datetime().optional(),endedAt:c.string().datetime().optional(),durationMs:c.number().int().nonnegative().optional(),note:c.string().trim().min(1).optional(),visual:uD.optional()}).strict(),dD=cI.extend({status:c.enum(["completed","failed"])}),Bn=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(new Date(0)),!0}catch{return!1}},"Invalid IANA timezone");dI=y0,pD=c.object({kind:c.literal("inline"),offset:c.number().int().nonnegative()}),pI=c.object({type:dI,src:c.url(),filename:c.string().min(1),mimeType:c.string().min(1),mediaId:c.string().min(1).optional(),size:c.number().int().nonnegative().optional(),width:c.number().int().positive().optional(),height:c.number().int().positive().optional(),duration:c.number().nonnegative().optional(),text:c.string().optional(),placement:pD.optional()}),fI=c.object({ref:c.string().min(1).max(256)}).strict(),mI=c.enum(["handled","dismissed","deferred"]),hI=c.iso.datetime();fD=fI.extend({disposition:mI.optional(),revisitAt:hI.optional()}).superRefine(gI),rB=fI.extend({disposition:mI,revisitAt:hI.optional()}).superRefine(gI),mD=c.object({turnId:c.string().min(1).optional(),turnOutcome:c.enum(["failed","stopped"]).optional(),attachments:c.array(pI).optional(),toolActivities:c.array(dD).optional(),issue:c.object({code:c.string(),bucket:c.enum(["account","error"]),actionLabel:c.string(),actionUrl:c.string(),help:c.string().optional()}).optional(),notification:c.object({push:c.boolean().optional(),excludeUserId:c.string().min(1).optional()}).optional(),routine:c.object({run:c.object({routineRunId:c.string(),name:c.string().optional(),sourceKind:c.enum(["webhook","schedule","manual","heartbeat"]),sourceLabel:c.string().optional(),deliveryId:c.string().optional(),status:c.enum(["received","forwarded","owner_notified","needs_approval","completed","failed","dropped"])}).catchall(c.unknown())}).catchall(c.unknown()).optional(),voiceDelegated:c.literal(!0).optional(),ownerHandoff:c.literal(!0).optional(),attention:c.array(fD).max(20).optional()}).catchall(c.unknown()),hD=c.object({messageId:c.string().min(1),conversationId:c.string().min(1),role:c.enum(["user","assistant","system"]),authorParticipantId:c.string().nullable(),systemKind:c.string().nullable(),content:c.string(),sequence:c.string().min(1),clientNonce:c.string().nullable().optional(),metadata:mD.nullable().optional(),status:c.string().nullable().optional(),createdAt:c.string(),updatedAt:c.string()}),k0=c.object({type:dI,mediaId:c.string().min(1)}),nB=c.object({conversationId:c.string().min(1),content:c.string().max(1e4).default(""),clientNonce:c.string().max(64).optional(),attachments:c.array(k0).max(10).optional(),channel:c.enum(["ios","dashboard"]).optional(),actionUrls:c.object({billing:c.string().max(500),bot:c.string().max(500)}).optional(),viewerTimezone:Bn.optional()}).refine(e=>e.content.trim().length>0||(e.attachments?.length??0)>0,{path:["content"],message:"Message or attachment required"}),vI=c.object({type:c.enum(["user","bot"]),id:c.string().min(1)}).strict();iB=c.object({orgId:c.string().min(1),participants:c.array(vI).min(1).max(20)}).strict().superRefine(bI),oB=c.object({orgId:c.string().min(1),participants:c.array(vI).min(1).max(20)}).strict().superRefine((e,t)=>{bI(e,t),e.participants.some(n=>n.type==="bot")||t.addIssue({code:"custom",path:["participants"],message:"New sessions require at least one agent participant."})}),aB=c.object({category:c.string().min(1).max(30).optional(),reason:c.string().max(2e3).optional()}).strict(),gD=c.enum(["1:1","4:3","3:4","16:9","9:16"]),vD=c.enum(["1K","2K","4K"]),sB=c.object({prompt:c.string().trim().min(1).max(4e3),aspectRatio:gD.default("1:1"),outputFormat:c.enum(["png","jpeg","webp"]).default("webp"),resolution:vD.default("2K"),style:c.string().trim().max(200).optional(),altText:c.string().trim().max(500).optional(),referenceMediaIds:c.array(c.string().min(1)).max(4).optional()}).strict(),lB=c.object({mediaId:c.string().min(1),src:c.url(),filename:c.string().min(1),mimeType:c.string().min(1),width:c.number().int().positive().optional(),height:c.number().int().positive().optional(),provider:c.string().min(1).optional(),providerRequestId:c.string().min(1).optional(),media:c.string().startsWith("MEDIA:"),attachment:pI.extend({type:c.literal("image")})}),uB=c.object({identityToken:c.string().min(1),fullName:c.string().optional()}),bD=c.object({redirect:c.string(),redirectReason:c.string(),isNew:c.boolean(),deviceId:c.string()}),dB=c.object({ok:c.literal(!0),data:bD,token:c.string()}),pB=c.object({path:c.string().startsWith("/","path must be a relative dashboard path").refine(bA,"path must be a relative dashboard path")}),yD=c.object({url:c.string()}),fB=c.object({ok:c.literal(!0),data:yD}),mB=c.object({token:c.string().min(1)}),wD=c.object({redirect:c.string(),redirectReason:c.string(),deviceId:c.string()}),hB=c.object({ok:c.literal(!0),data:wD,token:c.string()}),yI=JS,kD=y0,v0=c.object({mediaId:c.string(),src:c.string(),alt:c.string().nullable().optional(),filename:c.string().optional(),displayName:c.string().nullable().optional(),mimeType:c.string().optional(),mediaType:kD.optional(),size:c.number().optional(),width:c.number().nullable().optional(),height:c.number().nullable().optional(),duration:c.number().nullable().optional(),context:yI.nullable().optional(),blurhash:c.string().nullable().optional(),quality:c.string().optional(),status:c.string().optional(),userId:c.string().optional(),orgId:c.string().optional(),botId:c.string().nullable().optional(),createdAt:c.string().optional(),updatedAt:c.string().optional()}),yB=c.object({file:c.string().describe("Binary file. multipart/form-data field \u2014 the actual upload. The server validates type + size and normalizes image uploads before storage. Audio/video/document uploads use the same uploader and are classified by MIME type."),context:yI.optional().default("general"),botId:c.string().optional(),orgId:c.string().optional(),duration:c.number().optional()}),wI=c.object({viewerTimezone:Bn.optional(),location:c.object({label:c.string().max(500),city:c.string().optional(),region:c.string().optional(),countryCode:c.string().optional(),timezone:c.string().optional(),source:c.literal("geoip"),precision:c.enum(["city","region","country"]),confidence:c.enum(["medium","low"]),vpnOrDatacenter:c.enum(["likely","unknown"])}).optional()}),xD=c.object({status:c.enum(["available","unavailable"]),user:c.string().max(16e3).optional(),memory:c.string().max(16e3).optional(),agents:c.string().max(4e3).optional()}).strict(),_B=c.object({bot:c.object({id:c.string(),name:c.string(),title:c.string().nullable().optional(),timezone:Bn}),scope:c.enum(["private","org","public"]),channel:c.string().max(120),currentTime:c.iso.datetime(),scopePrompt:c.string().optional(),observations:wI.optional(),lastObservedTimezone:Bn.optional(),lean:xD.optional()}),kI=c.enum(["woman","man"]),_D=[{key:"ava",gender:"woman",accent:"American",character:"Warm, patient and understanding",isDefault:!0},{key:"hope",gender:"woman",accent:"American",character:"Soft-spoken, smooth and kind"},{key:"lauren",gender:"woman",accent:"American",character:"Friendly, comforting and soft"},{key:"amy",gender:"woman",accent:"American",character:"Natural and sweet"},{key:"eve",gender:"woman",accent:"American",character:"Authentic, energetic and happy"},{key:"jessica",gender:"woman",accent:"British",character:"Smooth, articulate and warm"},{key:"adam",gender:"man",accent:"American",character:"Engaging, friendly and bright",isDefault:!0},{key:"jon",gender:"man",accent:"American",character:"Relaxed, deep and approachable"},{key:"joe",gender:"man",accent:"British",character:"Reflective and thoughtful"},{key:"peter",gender:"man",accent:"Australian",character:"Deep, warm and direct"}],xI=c.enum(_D.map(e=>e.key)),$B=c.object({conversationId:c.string().min(1),viewerTimezone:Bn.optional()}).strict(),SB=c.object({conversationId:c.string().min(1),botId:c.string().min(1),personaName:c.string().min(1),personaTitle:c.string().max(255).nullable().optional(),gender:kI,voiceKey:xI.nullable(),sessionScope:c.enum(["private","org","public"]),observations:wI.optional(),threadSummary:c.string(),capabilities:c.array(c.object({name:c.string().min(1),description:c.string().min(1)})).optional(),surfaceGuidance:c.string().optional(),maxDurationSeconds:c.number().int().positive().max(3600).optional(),expiresAt:c.iso.datetime()}),$D=c.literal("livekit"),IB=c.object({name:c.enum(["voice.ready","voice.first_playback","voice.failed"]),client:c.enum(["web","ios"]),botId:c.string().min(1).max(64).optional(),conversationId:c.string().min(1).max(64).optional(),provider:$D.optional(),durationMs:c.number().int().min(0).max(36e5),phase:c.enum(["idle","minting","connecting","live","ended"]).optional(),code:c.string().min(1).max(64).optional(),detail:c.string().min(1).max(300).optional(),appVersion:c.string().min(1).max(32).optional(),appBuild:c.string().min(1).max(32).optional()}).strict(),EB=c.object({provider:c.literal("livekit"),url:c.string().min(1),token:c.string().min(1),room:c.string().min(1)}).strict(),SD=c.enum(["identity","working-style","complete"]),ID=c.string().min(1).max(50).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),Tl=c.object({botId:c.string().min(1),computerId:c.string().min(1),handle:c.string().min(2).max(50),name:c.string().min(1).max(100),emoji:c.string().max(8).nullable().optional(),title:c.string().max(120).nullable().optional(),summary:c.string().max(500).nullable().optional(),avatarId:c.string().nullable().optional(),coverId:c.string().nullable().optional(),avatar:Mt.optional(),cover:Mt.optional(),email:c.email().nullable().optional(),website:c.url().nullable().optional(),accounts:c.array(c.object({platform:c.enum(["linkedin","x","facebook","tiktok","youtube","github","instagram","threads","email","phone","website"]),handle:c.string()})).nullable().optional(),gender:kI.optional(),voiceKey:xI.nullable().optional(),isPrimary:c.boolean(),collaborationEnabled:c.boolean(),publicChatEnabled:c.boolean(),status:c.enum(["active","deleted"]),onboardingStage:SD.nullable().optional(),onboardedAt:c.string().nullable().optional(),routinePrimaryChannel:ID.optional(),firstMessageAt:c.string().nullable().optional(),firstValueAt:c.string().nullable().optional(),lastMessageAt:c.string().nullable().optional(),createdAt:c.string(),updatedAt:c.string()}).strict(),x0=Tl.pick({name:!0,emoji:!0,title:!0,summary:!0,gender:!0,voiceKey:!0}).extend({handle:Tl.shape.handle.optional(),avatarPreset:c.string().min(1).max(64).optional(),avatarMediaId:c.string().optional()}).strict(),TB=x0.extend({computerId:c.string().min(1)}).strict(),NB=Tl.pick({name:!0,handle:!0,emoji:!0,title:!0,summary:!0,email:!0,website:!0,gender:!0,voiceKey:!0,routinePrimaryChannel:!0,collaborationEnabled:!0,publicChatEnabled:!0}).partial().extend({avatarMediaId:c.string().nullable().optional(),coverMediaId:c.string().nullable().optional()}).strict(),_I=c.enum(["essential","professional","business"]),rp=rI.partial().extend({computerId:c.string().min(1),ownerId:c.string().min(1),owner:c.object({userId:c.string(),fullName:c.string().optional(),avatar:v0.optional()}).optional(),orgId:c.string().min(1),name:c.string().min(1).max(100),model:c.string().nullable(),timezone:Bn,billingTier:_I,desiredStatus:lI.nullable(),status:c.enum(["active","deleted"]),lastActiveAt:c.string().nullable().optional(),createdAt:c.string(),updatedAt:c.string()}).strict(),CB=c.object({orgId:c.string().min(1),name:rp.shape.name.optional(),timezone:Bn.optional(),primaryBot:x0}).strict(),zB=rp.pick({name:!0,model:!0,timezone:!0}).partial().strict(),ED=c.enum(["none","active_assistant"]),TD=c.enum(["none","active","trial","canceling","past_due","paused"]),ND=c.object({brand:c.string(),last4:c.string(),expMonth:c.number(),expYear:c.number()}),CD=c.object({date:c.string(),amount:c.number(),status:c.string(),invoicePdf:c.string().optional()}),zD=c.object({graceEndsAt:c.string().optional(),suspended:c.boolean(),url:c.string().optional()}),OB=c.object({plan:ED,status:TD,price:c.number(),tierRates:c.record(c.string(),c.number()).optional(),maxComputers:c.number(),activeComputers:c.number(),workspaceTier:_I.optional(),upcomingAmountDue:c.number().optional(),upcomingDueDate:c.string().optional(),nextBillDate:c.string().optional(),cancelAtPeriodEnd:c.boolean().optional(),cancelAt:c.string().optional(),trialEnd:c.string().optional(),trialDaysRemaining:c.number().optional(),paymentMethod:ND.optional(),paymentRecovery:zD.optional(),invoices:c.array(CD),stripeError:c.string().optional()}),OD=c.enum(["demo_computer_exists","demo_usage_exhausted","subscription_required","plan_limit"]),AB=c.object({canCreate:c.boolean(),activeComputers:c.number().int().nonnegative(),computerLimit:c.number().int().nonnegative(),isDemo:c.boolean(),reason:OD.optional()}),DB=c.object({orgId:c.string(),computerName:c.string().optional(),runtime:c.string().optional()}),PB=c.object({created:c.number(),skipped:c.number(),errors:c.array(c.string())}),RB=c.object({updated:c.number(),errors:c.array(c.string())}),AD=rI,DD=c.object({code:QS,message:c.string(),bucket:c.enum(["account","error"]),actionLabel:c.string().optional(),actionUrl:c.string().optional(),help:c.string().optional()}),PD=c.discriminatedUnion("event",[c.object({event:c.literal("status"),data:AD}),c.object({event:c.literal("message"),data:c.object({message:hD})}),c.object({event:c.literal("message_delta"),data:c.object({delta:c.string(),turnId:c.string(),messageId:c.string().optional(),role:c.enum(["assistant","system"]).optional()})}),c.object({event:c.literal("working_state"),data:c.object({description:c.string(),turnId:c.string().optional()})}),c.object({event:c.literal("tool_activity"),data:cI}),c.object({event:c.literal("working_end"),data:c.object({turnId:c.string().optional()}).strict()}),c.object({event:c.literal("stream_end"),data:c.object({turnId:c.string().optional()}).strict()}),c.object({event:c.literal("error"),data:DD})]);LD=c.object({label:c.string().trim().min(1).max(40),reply:c.string().trim().min(1).max(500),style:c.enum(["primary","default","destructive"]).optional()}).strip(),VD=c.object({version:c.literal(1),title:c.string().trim().min(1).max(200),body:c.string().trim().min(1).max(8e3).optional(),actions:c.array(LD).min(1).max(3).optional()}).strip();FD=c.string().trim().min(1).max(240),b0=c.string().trim().min(1).max(800),Zn=c.string().trim().min(1).max(80).regex(/^[A-Za-z0-9_.:-]+$/),za=c.string().trim().min(1).max(120),BD=c.union([c.string().max(500),c.number().finite(),c.boolean(),c.null()]),EI=c.record(Zn,BD),ZD=c.enum(["compact","currency","duration","integer","percent","raw"]),HD=c.object({title:FD,description:b0.optional(),footer:b0.optional()}).strip(),TI=c.object({dataKey:Zn,label:za.optional(),axisLabel:za.optional(),valueFormat:ZD.optional(),valuePrefix:c.string().trim().max(12).optional(),valueSuffix:c.string().trim().max(12).optional()}).strip(),KD=c.object({kind:c.literal("linear"),dataKey:Zn,label:za.optional()}).strip(),$0=c.object({version:c.literal(1),meta:HD,fallbackMarkdown:c.string().trim().min(1).max(4e3)}).strip();GD=$0.extend({visualType:c.literal("chart"),chartType:c.enum(["bar","line","scatter"]),xKey:Zn,xAxisLabel:za.optional(),series:c.array(TI).min(1).max(6),data:c.array(EI).min(1).max(120),layout:c.enum(["horizontal","vertical"]).optional(),stacking:c.enum(["grouped","stacked"]).optional(),trendLine:KD.optional()}).strip().superRefine((e,t)=>{e.stacking&&e.chartType!=="bar"&&t.addIssue({code:"custom",path:["stacking"],message:"Stacking is only supported for bar charts"}),e.trendLine&&e.chartType!=="line"&&e.chartType!=="scatter"&&t.addIssue({code:"custom",path:["trendLine"],message:"Trend lines are only supported for line and scatter charts"}),NI(e.data,[{path:["xKey"],value:e.xKey},...e.series.map((n,i)=>({path:["series",i,"dataKey"],value:n.dataKey})),...e.trendLine?[{path:["trendLine","dataKey"],value:e.trendLine.dataKey}]:[]],t),CI(e.data,[...e.series.map((n,i)=>({path:["series",i,"dataKey"],value:n.dataKey})),...e.trendLine?[{path:["trendLine","dataKey"],value:e.trendLine.dataKey}]:[]],t)}),JD=$0.extend({visualType:c.literal("chart"),chartType:c.literal("pie"),nameKey:Zn,valueKey:Zn,series:c.array(TI).max(1).optional(),data:c.array(EI).min(1).max(16)}).strip().superRefine((e,t)=>{NI(e.data,[{path:["nameKey"],value:e.nameKey},{path:["valueKey"],value:e.valueKey},...(e.series??[]).map((n,i)=>({path:["series",i,"dataKey"],value:n.dataKey}))],t),CI(e.data,[{path:["valueKey"],value:e.valueKey,nonnegative:!0}],t)}),qD=c.discriminatedUnion("chartType",[GD,JD]),YD=c.object({id:Zn,label:za,detail:b0.optional(),kind:c.enum(["actor","agent","decision","event","input","output","system","task"]).optional()}).strip(),XD=c.object({from:Zn,to:Zn,label:za.optional()}).strip(),QD=$0.extend({visualType:c.literal("diagram"),diagramType:c.enum(["flow","org","sequence","state"]),layout:c.enum(["auto","left-to-right","radial","top-to-bottom"]).default("auto"),nodes:c.array(YD).min(1).max(24),edges:c.array(XD).max(48)}).strip().superRefine((e,t)=>{let n=new Set(e.nodes.map(i=>i.id));for(let[i,r]of e.edges.entries())n.has(r.from)||t.addIssue({code:"custom",path:["edges",i,"from"],message:`Unknown node id "${r.from}"`}),n.has(r.to)||t.addIssue({code:"custom",path:["edges",i,"to"],message:`Unknown node id "${r.to}"`})}),MS=c.union([qD,QD]);OI=c.object({conversationParticipantId:c.string().min(1),type:c.enum(["user","bot","anonymous"]),id:c.string(),role:c.enum(["owner","requester","member"]),status:c.enum(["active","left","deleted"]),displayName:c.string().optional(),handle:c.string().optional(),avatarUrl:c.string().optional()}).strict(),AI=c.object({messageId:c.string(),role:c.enum(["user","assistant","system"]),content:c.string(),sequence:c.string(),createdAt:c.string()}),VB=c.object({conversationId:c.string(),orgId:c.string(),kind:c.enum(["direct","group"]),updatedAt:c.string(),viewerRole:c.enum(["owner","requester","member"]),participants:c.array(OI),lastMessage:AI.nullable(),openingMessage:c.string().nullable(),unreadCount:c.number().int().nonnegative(),latestSequence:c.string().nullable()}),FB=c.object({sequence:c.string().min(1)}),BB=c.object({turnId:c.string().min(1).optional()}).strict(),ZB=c.object({cancelled:c.boolean(),cancelledTurnIds:c.array(c.string())}).strict(),HB=c.object({conversationId:c.string(),messageId:c.string(),sequence:c.string(),snippet:c.string(),createdAt:c.string(),participants:c.array(OI)}),KB=c.object({conversationId:c.string(),lastMessage:AI.nullable(),unreadCount:c.number().int().nonnegative(),latestSequence:c.string().nullable()}),Lr=c.preprocess(e=>e===void 0?null:e,c.string().nullable()),o6=c.preprocess(e=>e===void 0?null:e,tI.nullable()),a6=c.preprocess(e=>e===void 0?null:e,lI.nullable()),s6=c.preprocess(e=>e===void 0?null:e,c.enum(["user","assistant","system"]).nullable()),LS=c.preprocess(e=>e===void 0?0:e,c.number()),l6=c.object({computerId:c.string(),handle:c.string(),name:c.string(),orgId:c.string(),orgName:Lr,orgHandle:Lr,ownerEmail:Lr,ownerName:Lr,state:o6,desiredStatus:a6,runtime:c.string(),imageVersion:Lr,lastHealthyAt:Lr,lastActiveAt:Lr,lastUserMessageAt:Lr,lastMessageAt:Lr,lastMessageRole:s6,lastMessageChannel:Lr,primaryChannel:Lr,totalMessages:LS,totalSessions:LS,error:Lr,appHandle:c.string(),hostAppExists:c.boolean(),plan:c.string(),billingStatus:c.string(),billingActive:c.boolean(),createdAt:c.string(),updatedAt:c.string()}),c6=c.object({running:c.number(),stopped:c.number(),error:c.number(),starting:c.number(),unknown:c.number(),total:c.number()}),GB=c.object({computers:c.array(l6),summary:c6,orphanedApps:c.array(c.string()),dailyMessages30d:c.array(c.number().int()).optional(),hostAppCount:c.number().optional(),latestVersions:c.record(c.string(),c.string()).optional()}),u6=c.object({mediaId:c.string().optional(),src:c.string().optional(),alt:c.string().optional(),width:c.number().optional(),height:c.number().optional(),mimeType:c.string().optional(),mediaType:c.string().optional(),blurhash:c.string().optional()}),qB=c.object({membershipId:c.string(),userId:c.string(),orgId:c.string(),email:c.string(),fullName:c.string().optional(),role:c.enum(["owner","admin","member","observer"]),status:c.enum(["active","suspended"]),joinedAt:c.string(),lastSeenAt:c.string().optional(),avatar:u6.optional()}),YB=c.object({invitationId:c.string(),email:c.string(),role:c.enum(["admin","member"]),status:c.string(),expiresAt:c.string(),createdAt:c.string()}),d6=c.object({token:c.string(),email:c.string(),orgId:c.string(),orgName:c.string(),orgInitial:c.string(),inviterName:c.string().optional(),inviterEmail:c.string(),role:c.enum(["owner","admin","member","observer"]),status:c.enum(["pending","accepted","expired","revoked"]),expiresAt:c.string(),memberCount:c.number().optional()}),XB=c.object({email:c.string().email(),role:c.enum(["admin","member"]).optional(),message:c.string().max(500).optional()}).strict(),QB=c.object({role:c.enum(["admin","member"])}).strict(),e7=c.object({token:c.string().min(1)}).strict(),t7=c.object({message:c.string()}),r7=c.object({invitationId:c.string(),message:c.string()}),n7=c.object({message:c.string(),membershipId:c.string(),orgId:c.string(),role:c.enum(["owner","admin","member","observer"])}),i7=c.object({invite:d6.nullable()}),p6={};uA(p6,{zNotificationTelemetryAck:()=>g6,zNotificationTelemetryEvent:()=>h6,zRegisterDeviceRequest:()=>f6,zRegisterDeviceResponse:()=>m6});f6=c.object({deviceId:c.string().min(1).max(64),pushToken:c.string().min(1).max(200),appVersion:c.string().max(40).optional(),osVersion:c.string().max(40).optional(),model:c.string().max(80).optional()}),m6=c.object({deviceId:c.string().min(1).max(64)}),h6=c.object({deviceId:c.string().min(1).max(64),kind:c.string().min(1).max(30),action:c.enum(["displayed","tapped","dismissed"]),messageId:c.string().max(32).optional()}),g6=c.object({updated:c.boolean()}),s7=aI.pick({orgId:!0,handle:!0,name:!0,email:!0,website:!0,avatarId:!0,coverId:!0,summary:!0,timezone:!0,isPersonal:!0,status:!0,updatedAt:!0}).extend({avatar:v0.nullable().optional(),cover:v0.nullable().optional()}),l7=c.object({name:c.string().min(1).max(255),handle:c.string().min(2).max(50).optional(),timezone:Bn.optional()}).strict(),c7=aI.pick({name:!0,email:!0,website:!0,summary:!0,timezone:!0}).extend({name:c.string().min(1).max(255).optional(),email:c.preprocess(e=>e===""?null:e,c.string().email().nullable()).optional(),timezone:Bn.optional(),avatarMediaId:c.string().nullable().optional(),coverMediaId:c.string().nullable().optional()}).strict(),d7=c.object({used:c.number().int().nonnegative(),limit:c.number().int().nonnegative(),remaining:c.number().int().nonnegative(),periodEnd:c.string(),isDemo:c.boolean(),state:c.enum(["ok","warning","exhausted"])}),f7=c.object({messagesHandled:c.number().int().nonnegative(),proactiveRuns:c.number().int().nonnegative(),approvalsWaiting:c.number().int().nonnegative(),approvalConversationId:c.string().optional(),approvalBotId:c.string().optional(),dailyHandled:c.array(c.number().int().nonnegative()).length(30),messagesByAssistant:c.array(c.object({botId:c.string(),count:c.number().int().nonnegative()})),briefingsDelivered:c.number().int().nonnegative(),scheduledRuns:c.number().int().nonnegative(),prev30MessagesHandled:c.number().int().nonnegative(),prev30BriefingsDelivered:c.number().int().nonnegative(),prev30ScheduledRuns:c.number().int().nonnegative(),since:c.string()}),v6=c.enum(["success","info","warning"]),b6=c.object({orgId:c.string(),name:c.string(),avatarUrl:c.string().nullable()}),y6=c.object({key:c.string(),label:c.string(),tone:v6,status:c.string(),trialDaysRemaining:c.number().optional()}),w6=c.object({activeComputerLimit:c.number().int().nonnegative(),activeComputerCount:c.number().int().nonnegative(),computerCount:c.number().int().nonnegative()}),h7=c.object({org:b6,plan:y6,quota:w6,memberCount:c.number().int().nonnegative()}),k6=c.object({sender:c.enum(["user","agent"]),text:c.string()}),x6=c.enum(["works-now","guided-setup","coming-soon","custom-workflow"]),_6=c.object({docsUrl:c.string(),verifiedAt:c.string(),version:c.string().optional(),versionPolicy:c.enum(["date-versioned","header-versioned","path-versioned","endpoint-versioned","unversioned"]),note:c.string().optional()}),$6=c.object({key:c.string(),label:c.string(),rank:c.number()}),S6=c.object({text:c.string(),tone:c.enum(["info","warning","success","danger"])}),v7=c.object({serviceKey:c.string(),name:c.string(),description:c.string(),shortDescription:c.string(),subtitle:c.string().optional(),icon:c.string().optional(),category:c.string(),categoryLabel:c.string(),categoryRank:c.number(),featuredRank:c.number().optional(),secondaryCategories:c.array($6),badges:c.array(S6),tags:c.array(c.string()),searchAliases:c.array(c.string()),jtbd:c.string(),useCase:c.string(),demoScenario:c.string(),sampleConversation:c.array(k6),publicStatus:x6,apiVerification:_6.optional(),setupDifficulty:c.string(),risk:c.string(),price:c.string(),kind:c.string(),tier:c.string(),installLevel:c.enum(["computer","org","both"]),setupSummary:c.string().optional(),pagePath:c.string()}),I6=c.object({title:c.string().optional(),text:c.string()}),y7=c.object({content:c.string(),mediaType:c.enum(["application/json","text/plain"]),copyLabel:c.string(),action:c.object({label:c.string(),url:c.url()}),steps:c.array(I6)}),k7=c.object({fullName:c.string().min(1).max(100).optional(),bio:c.string().max(500).nullable().optional(),linkedinUsername:oI.nullable().optional(),profileUrl:YA.nullable().optional(),avatarMediaId:c.string().nullable().optional(),lastBotId:c.string().nullable().optional(),lastActiveOrgId:c.string().nullable().optional()}).strict(),Qd=8e3,E6=c.string().regex(/^[A-Z][A-Z0-9_]*$/),T6=c.object({name:c.string().trim().min(1).max(100),instructions:c.string().trim().min(1).max(Qd),credentialNames:c.array(E6).max(10)}),DI=c.object({mediaId:c.string().min(1),sha256:c.string().regex(/^[a-f0-9]{64}$/).optional(),name:c.string().min(1).max(100)}).strict(),N6=T6.extend({toolId:c.string().min(1),assets:c.array(DI)}).strict(),C6=c.object({moment:c.enum(["briefing","checkin","closeout","custom"]),name:c.string().trim().min(1).max(100),policy:c.string().trim().min(1).max(Qd),time:c.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),active:c.boolean()}).strict(),z6=c.object({serviceKey:c.string().min(1).max(50)}).strict(),O6={schemaVersion:c.literal(1),name:c.string().min(1).max(100),summary:c.string().max(500)},PI=c.object({...O6,identity:x0.pick({name:!0,emoji:!0,title:!0,summary:!0,gender:!0}).strict(),guidance:c.string().max(Qd),examples:c.array(c.string().max(Qd)),tools:c.array(N6),assets:c.array(DI),routines:c.array(C6).optional(),services:c.array(z6).optional()}).strict(),_7=c.object({templateId:c.string(),publisherId:c.string(),publisher:c.object({userId:c.string(),fullName:c.string(),avatar:c.object({src:c.string()}).strict().optional()}).strict(),name:c.string(),description:c.string(),snapshot:PI,createdAt:c.string()}).strict(),$7=c.object({reviewed:c.literal(!0),orgId:c.string().min(1),sourceBotId:c.string().min(1),snapshot:PI}).strict(),S7=c.object({templateId:c.string().min(1),destination:c.discriminatedUnion("kind",[c.object({kind:c.literal("computer"),computerId:c.string().min(1)}).strict(),c.object({kind:c.literal("first-computer"),orgId:c.string().min(1)}).strict()]),includedToolIds:c.array(c.string().min(1))}).strict(),I7=c.object({"idempotency-key":c.uuid().describe("One UUID per Add intent; reuse it for retries.")}),T7=c.object({user:rD,computers:c.array(rp),bots:c.array(Tl)}),VS=Object.keys(rp.shape),RI=class extends ao{constructor(e){super("Computer",e),this.computerId=q(this.settings.computerId),this.ownerId=q(this.settings.ownerId),this.owner=q(this.settings.owner),this.orgId=q(this.settings.orgId),this.name=q(this.settings.name),this.model=q(this.settings.model),this.timezone=q(this.settings.timezone),this.billingTier=q(this.settings.billingTier),this.desiredStatus=q(this.settings.desiredStatus),this.status=q(this.settings.status),this.lastActiveAt=q(this.settings.lastActiveAt),this.createdAt=q(this.settings.createdAt),this.updatedAt=q(this.settings.updatedAt),this.lifecycle=q(this.settings.lifecycle),this.changedAt=q(this.settings.changedAt),this.detail=q(this.settings.detail),this.blocker=q(this.settings.blocker),this.operation=q(this.settings.operation),this.ownerMarkUrl=P(()=>{let t=this.owner.value;return t?.avatar?.src||zl(t?.fullName||this.ownerId.value)}),this.state=P(()=>GA({lifecycle:this.lifecycle.value??"unknown",changedAt:this.changedAt.value,detail:this.detail.value,blocker:this.blocker.value,operation:this.operation.value},this.name.value))}merge(e){if(e.computerId!==void 0&&e.computerId!==this.computerId.value)throw new Error("Cannot change a computer identity");for(let t of VS){if(!(t in e))continue;let n=this[t];n&&typeof n=="object"&&"value"in n&&(n.value=e[t])}}toData(){let e={};for(let t of VS){let n=this[t];n&&typeof n=="object"&&"value"in n&&(e[t]=n.value)}return e}toJSON(){return this.toData()}},FS=Object.keys(Tl.shape),S0=class extends ao{constructor(e,t){if(e.computerId!==t.computerId.value)throw new Error("Bot and computer identities do not match");super("Bot",e),this.botId=q(this.settings.botId),this.computerId=q(this.settings.computerId),this.name=q(this.settings.name),this.handle=q(this.settings.handle),this.emoji=q(this.settings.emoji),this.title=q(this.settings.title),this.summary=q(this.settings.summary),this.avatarId=q(this.settings.avatarId),this.coverId=q(this.settings.coverId),this.avatar=q(this.settings.avatar),this.cover=q(this.settings.cover),this.email=q(this.settings.email),this.website=q(this.settings.website),this.accounts=q(this.settings.accounts),this.gender=q(this.settings.gender),this.voiceKey=q(this.settings.voiceKey),this.publicChatEnabled=q(this.settings.publicChatEnabled),this.isPrimary=q(this.settings.isPrimary),this.collaborationEnabled=q(this.settings.collaborationEnabled),this.status=q(this.settings.status),this.onboardingStage=q(this.settings.onboardingStage),this.onboardedAt=q(this.settings.onboardedAt),this.routinePrimaryChannel=q(this.settings.routinePrimaryChannel),this.firstMessageAt=q(this.settings.firstMessageAt),this.firstValueAt=q(this.settings.firstValueAt),this.lastMessageAt=q(this.settings.lastMessageAt),this.createdAt=q(this.settings.createdAt),this.updatedAt=q(this.settings.updatedAt),this.displayName=P(()=>this.name.value||"Unnamed"),this.avatarUrl=P(()=>this.avatar.value?.src||zl(this.name.value)),this.hasCustomHandle=P(()=>!!this.handle.value&&!/\d{13,}$/.test(this.handle.value)),this.displayHandle=P(()=>this.hasCustomHandle.value?`@${this.handle.value}`:void 0),this.hasReceivedMessage=P(()=>!!this.lastMessageAt.value),this.computer=t}get owner(){return this.computer.owner}get ownerMarkUrl(){return this.computer.ownerMarkUrl}get ownerId(){return this.computer.ownerId}get orgId(){return this.computer.orgId}get model(){return this.computer.model}get timezone(){return this.computer.timezone}get billingTier(){return this.computer.billingTier}get desiredStatus(){return this.computer.desiredStatus}get lifecycle(){return this.computer.lifecycle}get changedAt(){return this.computer.changedAt}get detail(){return this.computer.detail}get blocker(){return this.computer.blocker}get operation(){return this.computer.operation}get state(){return this.computer.state}get lastActiveAt(){return this.computer.lastActiveAt}merge(e){if(e.botId!==void 0&&e.botId!==this.botId.value)throw new Error("Cannot change a bot identity");if(e.computerId!==void 0&&e.computerId!==this.computerId.value)throw new Error("Cannot move a bot between computers");for(let t of FS){if(!(t in e))continue;let n=this[t];n&&typeof n=="object"&&"value"in n&&(n.value=e[t])}}toData(){let e={};for(let t of FS){let n=this[t];n&&typeof n=="object"&&"value"in n&&(e[t]=n.value)}return e}toJSON(){return this.toData()}}});function Hn(e,t){let n=Number(globalThis.process?.env?.PORT)||Nl.port;return e||(t?`http://localhost:${n}`:Nl.urls.app)}function A6(e,t,n){let i=Hn(e.apiBase,e.isDev);return async(r,o)=>{let a=so.getAuthToken(),s=new Headers(o?.headers);s.has("Content-Type")||s.set("Content-Type","application/json"),a&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${a}`);let l=typeof r=="string"&&r.startsWith("/")?`${i}${r}`:r,u=await fetch(l,{...o,headers:s,credentials:"include"});if(n&&u.status===401&&(await u.clone().json().catch(()=>{}))?.code==="TOKEN_ERROR"&&n(),t){let d=u.json.bind(u);u.json=async()=>{let p=await d();return typeof p=="object"&&p&&"ok"in p&&("user"in p||"token"in p)&&t(p),p}}return u}}function Dl(e){"@babel/helpers - typeof";return Dl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dl(e)}function R6(e,t){if(Dl(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t||"default");if(Dl(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function U6(e){var t=R6(e,"string");return Dl(t)=="symbol"?t:t+""}function W(e,t,n){return(t=U6(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}async function Oa(e,t){e.loading.value=!0,e.error.value=null;try{return await t()}finally{e.loading.value=!1}}function MI(e){if(e.role==="assistant"||e.role==="system")return{id:e.messageId,text:e.content,sender:e.role==="system"?"system":"bot",timestamp:e.createdAt,conversationId:e.conversationId,sequence:e.sequence,systemKind:e.systemKind,...e.metadata?.routine?{routine:e.metadata.routine}:{},...e.metadata?.turnOutcome?{turnOutcome:e.metadata.turnOutcome}:{},...e.metadata?.attachments?.length?{attachments:e.metadata.attachments}:{},...e.metadata?.toolActivities?.length?{toolActivities:e.metadata.toolActivities}:{},...e.metadata?.issue?{issue:e.metadata.issue}:{}}}var UI,Xr,Al,jI,E0,D6,P6,T0,Aa,np,ip,op,j6,M6,L6,I0,V6,F6,B6,Z6,H6,ap,Pl,N0=Y(()=>{"use strict";Tn();Ol();bn();Xr=[],Al=0,jI=null,E0=4,D6=(UI=globalThis).nanostoresGlobal||(UI.nanostoresGlobal={epoch:0}),P6=()=>{let e,t;for(;Al<Xr.length;){t=Al,Al+=E0;try{Xr[t](Xr[t+1].value,Xr[t+2],Xr[t+3])}catch(n){e=n}}if(Xr.length=Al=0,e)throw e},T0=e=>{let t=[],n={eq:Object.is,get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(i){return n.lc=t.push(i),()=>{for(let o=Al;o<Xr.length;)Xr[o]===i?Xr.splice(o,E0):o+=E0;let r=t.indexOf(i);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(i,r){D6.epoch++;let o=!Xr.length&&!0;for(let a of t)jI?.has(a)||(jI?.add(a),Xr.push(a,n,i,r));o&&P6()},off(){},set(i){let r=n.value;n.eq(r,i)||(n.value=i,n.notify(r))},subscribe(i){let r=n.listen(i);return i(n.value),r},value:e};return n};Aa=globalThis,np=Aa.__PL_AUTH_USER__??(Aa.__PL_AUTH_USER__=T0(void 0)),ip=Aa.__PL_AUTH_TOKEN__??(Aa.__PL_AUTH_TOKEN__=T0(null)),op=Aa.__PL_AUTH_DEVICE_ID__??(Aa.__PL_AUTH_DEVICE_ID__=T0(null)),j6=class{constructor(){W(this,"logger",oo("SDKStorage"))}isLocalStorageFunctional(){return typeof window<"u"&&typeof localStorage?.getItem=="function"&&typeof localStorage?.setItem=="function"&&typeof localStorage?.removeItem=="function"}syncWithGlobalStores(e){let{activeUser:t,token:n,deviceId:i}=e,r=np.get(),o=ip.get(),a=op.get();r&&(t.value=r),o&&(n.value=o),a&&(i.value=a),ft(t,s=>np.set(s),{immediate:!0}),ft(n,s=>ip.set(s),{immediate:!0}),ft(i,s=>op.set(s),{immediate:!0}),np.subscribe(s=>{s!==t.value&&(t.value=s)}),ip.subscribe(s=>{s!==n.value&&(n.value=s)}),op.subscribe(s=>{s!==i.value&&(i.value=s)})}loadFromStorage(e){if(typeof window>"u")return;let t=so.getAuthToken();t&&(e.token.value=t);let n=so.getDeviceId();if(n&&(e.deviceId.value=n),this.isLocalStorageFunctional())try{let i=localStorage.getItem("pagelines-user");i&&(e.activeUser.value=JSON.parse(i))}catch(i){this.logger.error("Failed to load user from localStorage",{data:i})}}saveToStorage(e){if(!(typeof window>"u")&&(e.token.value?so.setAuthToken(e.token.value):so.removeAuthToken(),this.isLocalStorageFunctional()))try{e.activeUser.value?localStorage.setItem("pagelines-user",JSON.stringify(e.activeUser.value)):localStorage.removeItem("pagelines-user")}catch(t){this.logger.error("Failed to save user to localStorage",{data:t})}}clearStorage(){if(!(typeof window>"u")){if(so.removeAuthToken(),this.isLocalStorageFunctional())try{localStorage.removeItem("pagelines-user")}catch(e){this.logger.error("Failed to clear user from localStorage",{data:e})}np.set(void 0),ip.set(null),op.set(null)}}getItem(e){if(!this.isLocalStorageFunctional())return null;try{return localStorage.getItem(e)}catch(t){return this.logger.error("Failed to get item from localStorage",{key:e,error:t}),null}}setItem(e,t){if(this.isLocalStorageFunctional())try{localStorage.setItem(e,t)}catch(n){this.logger.error("Failed to set item in localStorage",{key:e,error:n})}}},M6=class{constructor(e){W(this,"ctx",void 0),W(this,"computers",ba(new Map)),W(this,"bots",ba(new Map)),this.ctx=e}get(e){return this.bots.get(e)}computer(e){return this.computers.get(e)}all(){return[...this.bots.values()]}hydrate(e){for(let t of e.computers){let n=this.computers.get(t.computerId);n?n.merge(t):this.computers.set(t.computerId,new RI(t))}return e.bots.map(t=>{let n=this.computers.get(t.computerId);if(!n)throw Error("Bot references an unknown computer");let i=this.bots.get(t.botId);if(i)return i.merge(t),i;let r=new S0(t,n);return this.bots.set(t.botId,r),r})}clear(){this.bots.clear(),this.computers.clear()}async webhook(e){let t=await this.ctx.apiFetch(`/api/bot-api/webhooks/routine-triggers/${encodeURIComponent(e.triggerId)}`,{method:"POST",headers:{"Content-Type":"application/json","X-PageLines-Key":e.key},body:JSON.stringify({type:e.type,data:e.data,...e.meta?{meta:e.meta}:{}})});if(!t.ok)throw Error(`Webhook delivery failed (${t.status})`);return t.json()}},L6=class{constructor(e,t){W(this,"ctx",void 0),W(this,"registry",void 0),this.ctx=e,this.registry=t}async create(e){let t=this.ctx.token.value,n=await(await this.ctx.apiFetch("/api/computers",{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":crypto.randomUUID()},body:JSON.stringify(e)})).json();if(t!==this.ctx.token.value)throw Error("Your account changed. Try again.");if(!n.ok)throw Error(n.error||"Failed to create computer");return this.registry.hydrate({computers:[n.data.computer],bots:[n.data.bot]})[0]}async getLiveStatus(e){let t=this.ctx.token.value;try{let n=await(await this.ctx.apiFetch(`/api/computers/state?ids=${encodeURIComponent(e)}`)).json(),i=n.ok?n.data[e]??Cl:Cl;return t===this.ctx.token.value?(this.registry.computer(e)?.merge(i),i):Cl}catch(n){return this.ctx.logger.warn("Computer status unavailable",{computerId:e,error:n}),Cl}}async waitUntilReady(e){let t=Date.now(),n;for(;Date.now()-t<(e.timeoutMs??sI.wake);){let i=await this.getLiveStatus(e.computerId);if(i.lifecycle!==n&&(e.onStatus?.(i.lifecycle),n=i.lifecycle),i.lifecycle==="running")return;if(i.lifecycle==="error")throw Error("Your computer hit a problem starting");await new Promise(r=>setTimeout(r,e.pollIntervalMs??3e3))}throw Error("Your computer is taking longer than expected. Please try again.")}},I0="Signed in, but your account could not be loaded. Try again.";V6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async authenticateWithCode(e,t){let n=await(await this.ctx.apiFetch("/api/auth/verify-code",{method:"POST",body:JSON.stringify({email:e,code:t})})).json();if(!n.ok)throw Error(n.error);let i=await this.getCurrentUser();if(!i)throw Error(I0);return i}async sendCode(e){return Oa(this.ctx,async()=>{try{let t=await(await this.ctx.apiFetch("/api/auth/check-email",{method:"POST",body:JSON.stringify({email:e})})).json();if(!t.ok)throw this.ctx.error.value=t.error,Error(t.error)}catch(t){this.ctx.logger.error("Send code error",{data:t});let n=t instanceof Error?t.message:"Failed to send verification code";throw this.ctx.error.value=n,t}})}async verifyCode(e,t){return Oa(this.ctx,async()=>{try{await this.authenticateWithCode(e,t)}catch(n){this.ctx.logger.error("Verify code error",{data:n});let i=n instanceof Error?n.message:"Failed to verify code";throw this.ctx.error.value=i,n}})}async logout(){return Oa(this.ctx,async()=>{try{await this.ctx.apiFetch("/api/auth/logout",{method:"POST"})}catch(e){this.ctx.logger.error("Logout error (user still logged out locally)",{data:e})}this.ctx.activeUser.value=void 0,this.ctx.token.value=null,this.ctx.storage.clearStorage(),this.ctx.clearRoster()})}async getCurrentUser(){let e=this.ctx.token.value;if(e)return Oa(this.ctx,async()=>{try{let t=await(await this.ctx.apiFetch("/api/users/me",{method:"GET"})).json();if(e!==this.ctx.token.value)return;if(!t.ok){this.ctx.error.value=t.error,t.error.includes("Authentication")&&(this.ctx.activeUser.value=void 0,this.ctx.token.value=null,this.ctx.storage.clearStorage(),this.ctx.clearRoster());return}return this.ctx.activeUser.value=t.data.user,this.ctx.hydrateRoster(t.data),t.data.user}catch(t){this.ctx.logger.error("Get current user error",{data:t}),this.ctx.error.value=t instanceof Error?t.message:"Failed to get user info";return}})}async requestAuthCode(e){return Oa(this.ctx,async()=>{try{let t=await(await this.ctx.apiFetch("/api/auth/check-email",{method:"POST",body:JSON.stringify({email:e.email})})).json();return t.ok?(this.ctx.logger.info("Auth code requested successfully",{email:e.email}),!0):(this.ctx.error.value=t.error,this.ctx.logger.error("Failed to request auth code",{email:e.email,error:t.error}),!1)}catch(t){return this.ctx.logger.error("Request auth code error",{email:e.email,error:t}),this.ctx.error.value=t instanceof Error?t.message:"Failed to request auth code",!1}})}async loginWithCode(e){return Oa(this.ctx,async()=>{try{return await this.authenticateWithCode(e.email,e.code),this.ctx.logger.info("Login successful",{email:e.email}),!0}catch(t){return this.ctx.logger.error("Login with code error",{email:e.email,error:t}),this.ctx.error.value=t instanceof Error?t.message:"Login failed",!1}})}loginWithGoogle(e){if(typeof window>"u"){this.ctx.logger.error("loginWithGoogle: Only available in browser");return}let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=window.location.origin,i=`${t}/auth/google-popup?origin=${encodeURIComponent(n)}`,r=window.screenX+(window.outerWidth-500)/2,o=window.screenY+(window.outerHeight-600)/2,a=window.open(i,"google-auth",`width=500,height=600,left=${r},top=${o},popup=yes`);if(!a){let u="Popup was blocked. Please allow popups for this site.";this.ctx.error.value=u,e?.onError?.(u);return}let s=async u=>{let d=new URL(t).origin;if(u.origin===d){if(u.data?.type==="auth-success"){window.removeEventListener("message",s);let{token:p}=u.data;this.ctx.processApiResponse({ok:!0,data:{},token:p});let f=await this.getCurrentUser();if(!f){this.ctx.error.value=I0,this.ctx.logger.error("Google login: token accepted but user hydration failed"),e?.onError?.(I0);return}this.ctx.logger.info("Google login successful"),e?.onSuccess?.(f)}else if(u.data?.type==="auth-error"){window.removeEventListener("message",s);let p=u.data.error||"Google authentication failed";this.ctx.error.value=p,this.ctx.logger.error("Google login failed",{error:p}),e?.onError?.(p)}}};window.addEventListener("message",s);let l=setInterval(()=>{a.closed&&(clearInterval(l),window.removeEventListener("message",s))},500)}},F6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async confirmCheckout(e){if(e?.sessionId){let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=await(await fetch(`${t}/api/billing/complete-checkout`,{method:"POST",headers:{"Content-Type":"application/json",...this.ctx.token.value&&{Authorization:`Bearer ${this.ctx.token.value}`}},body:JSON.stringify({sessionId:e.sessionId})})).json();if(!n.ok){let i=n.error||"Failed to complete checkout";throw this.ctx.error.value=i,Error(i)}}return this.getStatus()}async getStatus(){let e=this.resolveOrgId(),t=Hn(this.ctx.apiBase,this.ctx.isDev),n=await(await fetch(`${t}/api/billing/details/${e}`,{headers:{...this.ctx.token.value&&{Authorization:`Bearer ${this.ctx.token.value}`}}})).json();if(!n.ok||!n.data)return{plan:void 0,status:"none",hasActiveBilling:!1,maxBots:0};let i=["active","trial","canceling"].includes(n.data.status)||n.data.status==="past_due"&&n.data.paymentRecovery?.suspended!==!0;return{plan:n.data.plan,status:n.data.status,hasActiveBilling:i,maxBots:n.data.maxBots,...n.data.trialEnd&&{trialEnd:n.data.trialEnd},...n.data.trialDaysRemaining!==void 0&&{trialDaysRemaining:n.data.trialDaysRemaining},...n.data.paymentRecovery&&{paymentRecovery:n.data.paymentRecovery}}}resolveOrgId(){let e=this.ctx.activeUser.value?.orgs?.[0]?.orgId;if(!e)throw Error("No organization found. Please sign in first.");return e}};B6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async cancelConversationTurn(e){let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=this.ctx.token.value?{Authorization:`Bearer ${this.ctx.token.value}`}:{},i=await fetch(`${t}/api/conversations/${encodeURIComponent(e.conversationId)}/cancel`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(e.turnId?{turnId:e.turnId}:{})}),r=await i.json();if(!r.ok)throw Error(r.error||`Cancel failed: HTTP ${i.status}`);return r.data}async chatStreamPublic(e){let t=`${Hn(this.ctx.apiBase,this.ctx.isDev)}/api/bots/public/${encodeURIComponent(e.handle)}/chat/stream`,n="",i=!1,r=!1,o;try{let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e.message,anonymousId:e.anonymousId,...e.attachments?.length?{attachments:e.attachments.map(({type:s,src:l,filename:u,mimeType:d,mediaId:p})=>({type:s,url:l,name:u,mimeType:d,mediaId:p}))}:{},...e.context?{context:e.context}:{}})});if(!a.ok){let s=await a.json().catch(()=>({error:"Request failed"}));e.onError(Yr("api",s.error||`HTTP ${a.status}`,s.code));return}if(n=a.headers.get("X-Conversation-Id")||"",o=a.body?.getReader(),!o){e.onError(Yr("stream-open","No response stream"));return}for await(let s of _0(o))if(s.event==="working_state")e.onStatus?.(s.data.description);else if(s.event==="tool_activity")e.onToolActivity?.(s.data);else if(s.event==="working_end")e.onWorkingEnd?.();else if(s.event==="message_delta")e.onDelta(s.data.delta,s.data.role);else if(s.event==="error"){i=!0,e.onError(s.data);break}else if(s.event==="message"&&(s.data.message.role==="assistant"||s.data.message.role==="system")){r=!0;let l=MI(s.data.message);l&&e.onMessage?.(l)}else if(s.event==="stream_end")break;!i&&r?e.onDone(n):i||e.onError(Yr("no-reply","Stream ended before reply arrived"))}catch(a){e.onError(Yr("stream-read",a instanceof Error?a.message:"Stream failed","NETWORK_ERROR"))}finally{try{await o?.cancel()}catch{}}}async chatStreamAuthenticated(e){let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=this.ctx.token.value?{Authorization:`Bearer ${this.ctx.token.value}`}:{},i=e.conversationId,r=e.latestSequence??null;if(!i)try{let l=await fetch(`${t}/api/conversations`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify({orgId:e.orgId,participants:[{type:"bot",id:e.botId}]})}),u=await l.json();if(!u.ok){e.onError(Yr("api",u.error||`Conversation failed: HTTP ${l.status}`,u.code));return}i=u.data.conversationId,r=u.data.latestSequence??null}catch(l){e.onError(Yr("api",l instanceof Error?l.message:"Conversation failed","NETWORK_ERROR"));return}let o=r?`${t}/api/conversations/${encodeURIComponent(i)}/stream?since=${encodeURIComponent(r)}`:`${t}/api/conversations/${encodeURIComponent(i)}/stream`,a=`nonce_${WS(16)}`,s=uI();await SI({streamUrl:o,sendUrl:`${t}/api/messages`,headers:n,sendBody:{conversationId:i,content:e.message,clientNonce:a,...s?{viewerTimezone:s}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{}},onStatus:e.onStatus,onDelta:e.onDelta,onToolActivity:e.onToolActivity,onWorkingEnd:e.onWorkingEnd,onMessage:l=>{let u=MI(l);u&&e.onMessage?.(u)},onDone:()=>e.onDone(i),onChatError:e.onError,onTransportError:e.onError})}},Z6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async getPublicBot(e){this.ctx.loading.value=!0,this.ctx.error.value=null;try{let t=await(await this.ctx.apiFetch(`/api/pub/bot/get-by-handle?handle=${encodeURIComponent(e.handle)}`)).json();if(!t.ok){this.ctx.error.value=t.error,this.ctx.logger.error("Failed to fetch public bot",{handle:e.handle,error:t.error});return}return this.ctx.hydrateRoster({bots:[t.data.bot],computers:[t.data.computer]})[0]}catch(t){this.ctx.logger.error("Get public bot error",{handle:e.handle,error:t}),this.ctx.error.value=t instanceof Error?t.message:"Failed to fetch bot";return}finally{this.ctx.loading.value=!1}}generateAnonId(){let e="pagelinesAnonId",t=this.ctx.storage.getItem(e);return t||(t=ep({prefix:"anon"}),this.ctx.storage.setItem(e,t)),t}track(e){try{typeof window<"u"&&window.parent!==window&&window.parent.postMessage({type:"pagelines_track",event:e.event,botId:e.botId,properties:e.properties||{}},"*"),this.ctx.logger.info("SDK event tracked",{event:e.event,botId:e.botId})}catch(t){this.ctx.logger.error("Track event error",{error:t,args:e})}}},H6=class{constructor(){W(this,"key","__PAGELINES_SDK__")}get(){if(!(typeof window>"u"))return globalThis[this.key]}set(e){typeof window<"u"&&(globalThis[this.key]=e)}delete(){typeof window<"u"&&delete globalThis[this.key]}},ap=new H6,Pl=class LI extends ao{static getInstance(t={}){return ap.get()||new LI(t)}get isDev(){return this.settings.isDev??(typeof window<"u"?window.location.hostname==="localhost"||window.location.hostname.includes("127.0.0.1"):!1)}constructor(t={}){let n=ap.get();if(n)return console.debug("[PageLinesSDK] Returning existing singleton instance"),n;super("PageLinesSDK",t),W(this,"activeUser",q()),W(this,"token",q(null)),W(this,"deviceId",q(null)),W(this,"loading",q(!1)),W(this,"error",q(null)),W(this,"apiBase",this.settings.apiBase||void 0),W(this,"storage",new j6),W(this,"sessionId",ep({prefix:"ses"})),W(this,"currentBot",P(()=>{let r=this.activeUser.value;return(r?.lastBotId?this.bot.get(r.lastBotId):void 0)??this.bot.all().find(o=>o.isPrimary.value&&o.ownerId.value===r?.userId)})),W(this,"currentOrg",P(()=>{let r=this.currentBot.value?.computer.orgId.value??this.activeUser.value?.lastActiveOrgId??this.activeUser.value?.primaryOrgId;return this.activeUser.value?.orgs?.find(o=>o.orgId===r)})),W(this,"initialized",void 0),W(this,"resolveUser",void 0),W(this,"bot",void 0),W(this,"computer",void 0),W(this,"auth",void 0),W(this,"billing",void 0),W(this,"chat",void 0),W(this,"user",void 0),W(this,"stopAccountWatch",void 0),ap.set(this);let i={apiFetch:A6({isDev:this.isDev,apiBase:this.apiBase},this.processApiResponse.bind(this),()=>this.clearSession()),apiBase:this.apiBase,isDev:this.isDev,activeUser:this.activeUser,token:this.token,loading:this.loading,error:this.error,currentBot:this.currentBot,hydrateRoster:r=>this.bot.hydrate(r),clearRoster:()=>this.bot.clear(),storage:this.storage,sessionId:this.sessionId,logger:this.logger,processApiResponse:this.processApiResponse.bind(this)};this.bot=new M6(i),this.computer=new L6(i,this.bot),this.auth=new V6(i),this.billing=new F6(i),this.chat=new B6(i),this.user=new Z6(i),this.stopAccountWatch=ft(()=>this.activeUser.value?.userId,()=>this.bot.clear(),{flush:"sync"}),this.logger.info("PageLinesSDK initialized"),this.storage.loadFromStorage(this.authRefs()),this.storage.syncWithGlobalStores(this.authRefs()),this.initialized=new Promise(r=>{this.resolveUser=r}),this.token.value&&!this.activeUser.value?this.auth.getCurrentUser().then(r=>{this.resolveUser&&(this.resolveUser(r),this.resolveUser=void 0)}).catch(r=>{this.logger.error("Auto user fetch failed",{data:r}),this.resolveUser&&(this.resolveUser(void 0),this.resolveUser=void 0)}):this.activeUser.value?this.resolveUser?.(this.activeUser.value):this.resolveUser?.(void 0)}processApiResponse(t){if(!t.ok)return;let n=!1;t.user&&(this.activeUser.value=t.user,this.logger.info("User updated from API response",{data:t.user}),n=!0),t.token&&(this.token.value!==t.token&&(this.activeUser.value=void 0,this.bot.clear()),this.token.value=t.token,this.logger.info("Token updated from API response"),n=!0);let i=t.data?.deviceId;i&&(this.deviceId.value=i,n=!0),n&&this.persistAuth(),this.resolveUser&&(this.resolveUser(t.user),this.resolveUser=void 0)}authRefs(){return{activeUser:this.activeUser,token:this.token,deviceId:this.deviceId}}persistAuth(){this.storage.saveToStorage(this.authRefs())}clearSession(){this.bot.clear(),this.logger.info("Clearing session"),this.activeUser.value=void 0,this.token.value=null,this.deviceId.value=null,this.error.value=null,this.storage.clearStorage()}clear(){this.logger.info("Clearing SDK completely"),this.clearSession(),this.loading.value=!1,this.sessionId=ep({prefix:"ses"}),this.stopAccountWatch?.(),ap.delete()}}});function G6(e,t){return w(),_("div",W6,[...t[0]||(t[0]=[k("svg",{class:"ring-circular h-full w-full origin-center",viewBox:"25 25 50 50"},[k("circle",{class:"ring-path",cx:"50",cy:"50",r:"20",fill:"none",stroke:"currentColor","stroke-width":"5","stroke-miterlimit":"30"})],-1)])])}function J6(e){let t=Math.max(0,Math.floor(e.ms/1e3));return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function q6(e){return e.mimeType.includes("mp4")||e.mimeType.includes("m4a")?"m4a":e.mimeType.includes("ogg")?"ogg":e.mimeType.includes("wav")?"wav":"webm"}function Y6(){return typeof MediaRecorder>"u"?"":["audio/webm;codecs=opus","audio/mp4","audio/webm"].find(e=>MediaRecorder.isTypeSupported?.(e))||""}function e3(e){return e.turnOutcome==="failed"?"failed":e.turnOutcome==="stopped"?"stopped":e.sender==="system"?"failed":"completed"}function mp(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Ma(e){return mp(e.endedAt)??mp(e.startedAt)??0}function L0(e,t){return Ma(e)-Ma(t)}function Ll(e,t){let n=e.filter(r=>r.status==="completed"||r.status==="failed"&&!!r.note).filter(r=>!t.has(r.activityId)).slice().sort(L0),i=[];for(let r of n){let o=r.status==="completed"?"done":"failed",a=i[i.length-1];if(o==="done"&&a?.tone==="done"&&a.label===r.label&&Ma(r)-a.lastMs<=t3){a.count+=1,a.lastMs=Ma(r);continue}i.push({id:r.activityId,tone:o,label:r.label,note:r.note,count:1,lastMs:Ma(r)})}return i.map(r=>({id:r.id,tone:r.tone,label:r.count>1?`${r.label} \xB7 ${r.count}`:r.label,...r.note?{note:r.note}:{}}))}function pp(e){return e.length<=C0?{visibleRows:e,hiddenRows:[]}:{visibleRows:e.slice(e.length-C0),hiddenRows:e.slice(0,e.length-C0)}}function V0(e){let{activities:t,outcome:n,nowMs:i,canNotifyOnCompletion:r,lastVisibleProgressAtMs:o,includeFailureNote:a=!0}=e;if(n==="completed")return{outcome:n,visibleRows:[],hiddenRows:Ll(t,new Set),terminal:{id:"work-complete",tone:"completed",label:co.completed}};if(n==="failed"){let E=t.filter(X=>X.status==="failed").sort(L0).pop(),M=new Set;E&&M.add(E.activityId);let{visibleRows:z,hiddenRows:D}=pp(Ll(t,M));return{outcome:n,visibleRows:z,hiddenRows:D,terminal:{id:"work-failed",tone:"failed",label:co.failed,...a&&E?.note?{note:E.note}:{}}}}if(n==="stopped"){let{visibleRows:E,hiddenRows:M}=pp(Ll(t,new Set));return{outcome:n,visibleRows:E,hiddenRows:M,terminal:{id:"work-stopped",tone:"stopped",label:co.stopped}}}let{visibleRows:s,hiddenRows:l}=pp(Ll(t,new Set)),u=t.filter(E=>E.status==="started").sort(L0).pop(),d=t.reduce((E,M)=>Math.max(E,Ma(M)),o??-1/0),p=Number.isFinite(d)?d:i,f=t.reduce((E,M)=>{let z=mp(M.startedAt)??mp(M.endedAt);return z===void 0?E:Math.min(E,z)},1/0),m=p+h2,h=(Number.isFinite(f)?f:p)+r3,v=i>=m,x=u||v?{id:u?.activityId??"work-active",tone:"active",label:u?.label??co.finishing}:void 0,A=v&&i>=h?r?co.notifyHint:co.leaveHint:void 0,I=[m,h].filter(E=>E>i).sort((E,M)=>E-M)[0];return{outcome:n,visibleRows:s,hiddenRows:l,...x?{terminal:x}:{},...A?{hint:A}:{},...I===void 0?{}:{nextBoundaryAtMs:I}}}function n3(e){let{segments:t,activities:n,nowMs:i,canNotifyOnCompletion:r,lastVisibleProgressAtMs:o}=e,a=new Map(n.map(m=>[m.activityId,m])),s=m=>V0({activities:m,outcome:"running",nowMs:i,canNotifyOnCompletion:r,...o===void 0?{}:{lastVisibleProgressAtMs:o}}),l=m=>{let{visibleRows:h,hiddenRows:v}=pp(Ll(m,new Set));if(h.length!==0||v.length!==0)return{outcome:"running",visibleRows:h,hiddenRows:v}},u=[],d=new Set(t.flatMap(m=>m.kind==="work"?m.activityIds:[])),p=l(n.filter(m=>!d.has(m.activityId)));p&&u.push({kind:"work",id:"work-unsegmented",journal:p}),t.forEach((m,h)=>{if(m.kind==="text"){m.content&&u.push({kind:"text",id:`text-${h}`,content:m.content});return}let v=m.activityIds.map(A=>a.get(A)).filter(A=>A!==void 0);if(v.length===0)return;let x=l(v);x&&u.push({kind:"work",id:`work-${m.activityIds[0]??h}`,journal:x})});let f=s(n);return f.terminal||f.hint?u.push({kind:"work",id:"work-tail",journal:{outcome:"running",visibleRows:[],hiddenRows:[],...f.terminal?{terminal:f.terminal}:{},...f.hint?{hint:f.hint}:{},...f.nextBoundaryAtMs===void 0?{}:{nextBoundaryAtMs:f.nextBoundaryAtMs}}}):u.push({kind:"loading",id:"work-tail"}),u}function sp(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function i3(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof RTCPeerConnection<"u"}function VI(e){return e?typeof e=="string"?e:e.src||"":""}function g2(e){return VI(e.cover)||VI(e.avatar)||zl(e.name)}function Bl(e){let t=e.target;t.dataset.fallbackUsed||(t.dataset.fallbackUsed="true",t.src=zl())}function v2(e){let{template:t,bot:n}=e;return t.replace(/{name}/g,n.name||"Assistant").replace(/{title}/g,n.title||"").replace(/{handle}/g,n.handle||"")}function FI(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function S3(e){if(Array.isArray(e))return e}function I3(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var i,r,o,a,s=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(i=o.call(n)).done)&&(s.push(i.value),s.length!==t);l=!0);}catch(d){u=!0,r=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return s}}function E3(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
94
+ `):t.stack};for(let[a,s]of Object.entries(t))o[a]=this.formatData(s,n,i+1);return"cause"in t&&(o.cause=this.formatData(t.cause,n,i+1)),this.redactSensitive(o)}if(t instanceof Date)return t.toISOString();if(typeof t!="object")return t;if(Array.isArray(t))return t.length>20&&Na?`Array(${t.length}) [${t.slice(0,3).map(r=>this.formatData(r,n,i+1)).join(", ")}, ...]`:t.map(r=>this.formatData(r,n,i+1));try{let r={},o=Object.entries(t),a=Na?50:200;for(let[s,l]of o.slice(0,a))r[s]=this.formatData(l,n,i+1);return o.length>a&&(r["..."]=`${o.length-a} more properties`),this.redactSensitive(r)}catch{return"[Unserializable]"}}logToBrowser(t){if(!Fn||!this.shouldLog(t.level))return;let{level:n,description:i,context:r,data:o,error:a}=t,s=qd[n],u=`[${r||this.context||"www"}] ${n.toUpperCase()}:`,d=`color: ${s.color}; font-weight: bold;`;o!==void 0?console[n](`%c${u}`,d,i,this.formatData(o)):console[n](`%c${u}`,d,i),a&&(a instanceof Error?console.error(a):console.error("Error details:",a))}logToNode(t){if(!Yd||!this.shouldLog(t.level))return;let{level:n,description:i,context:r,data:o,error:a}=t,s=r||this.context||"www";if(Na){let l={timestamp:this.formatISOTimestamp(),level:n.toUpperCase(),context:s,msg:i,message:i};o!==void 0&&(l.data=this.formatData(o)),a!==void 0&&(l.error=this.formatData(a));let u=JSON.stringify(l);n==="trace"?console.log(u):console[n](u)}else{let l=qd[n],u=this.formatTimestamp(),d="\x1B[0m",p="\x1B[2m",f=l.nodeColor||"",m=`${p}${u}${d} ${f}${n.toUpperCase()} (${s}):${d} ${i}`;console[n](m),o!==void 0&&console.log(JSON.stringify(this.formatData(o),null,2)),a&&(a instanceof Error?(console.error(`\x1B[31mError:${d}`,a.message),a.stack&&console.error(`\x1B[90m${a.stack}${d}`)):console.error("Error:",a))}}log(t){Fn?this.logToBrowser(t):Yd&&this.logToNode(t)}error(t,n){this.log({level:"error",description:t,data:n,context:this.context})}warn(t,n){this.log({level:"warn",description:t,data:n,context:this.context})}info(t,n){this.log({level:"info",description:t,data:n,context:this.context})}debug(t,n){this.log({level:"debug",description:t,data:n,context:this.context})}trace(t,n){this.log({level:"trace",description:t,data:n,context:this.context})}isEnabled(){return Fn?this.enabledInBrowser:!0}setLevel(t){this.settings.minLevel=t}createContextLogger(t){let n=new Xd(this.settings,t);return{error:(i,r)=>n.error(i,r),warn:(i,r)=>n.warn(i,r),info:(i,r)=>n.info(i,r),debug:(i,r)=>n.debug(i,r),trace:(i,r)=>n.trace(i,r),isEnabled:()=>n.isEnabled(),setLevel:i=>n.setLevel(i)}}};HS.hasShownHelp=!1;KS=HS;wn=new KS,SF=wn.error.bind(wn),IF=wn.warn.bind(wn),EF=wn.info.bind(wn),TF=wn.debug.bind(wn),NF=wn.trace.bind(wn),ao=class{constructor(e,t){this.objectName=e,this.settings=t,this.logger=oo(e)}};PS={green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"}};gA=class{constructor(){this.tokenName="auth-token",this.deviceIdName="pl-device-id",this.tokenMaxAge=3600*24*90,this.fallbackStorageKey="token"}currentCookieOptions(){return hA(typeof window>"u"?void 0:window.location)}getCookie(e){if(typeof document>"u")return null;let t=document.cookie.split(";");for(let n of t){let[i,r]=n.trim().split("=");if(i===e)return decodeURIComponent(r||"")}return null}setCookie(e,t,n={}){if(typeof document>"u")return;let{secure:i=!0,sameSite:r="lax",maxAge:o=3600*24*7,domain:a,path:s="/"}=n,l=`${e}=${encodeURIComponent(t)}`;l+=`; Path=${s}`,l+=`; Max-Age=${o}`,l+=`; SameSite=${r}`,i&&(l+="; Secure"),a&&(l+=`; Domain=${a}`),document.cookie=l}removeCookie(e,t={}){this.setCookie(e,"",{...t,maxAge:0})}isLocalStorageFunctional(){return typeof window<"u"&&typeof window.localStorage?.getItem=="function"&&typeof window.localStorage?.setItem=="function"&&typeof window.localStorage?.removeItem=="function"}getAuthToken(){let e=this.getCookie(this.tokenName);if(e)return e;if(this.isLocalStorageFunctional()){let t=window.localStorage.getItem(this.fallbackStorageKey);if(t)return this.setAuthToken(t),window.localStorage.removeItem(this.fallbackStorageKey),t}return null}setAuthToken(e){let t=this.currentCookieOptions();this.setCookie(this.tokenName,e,{secure:t.secure,sameSite:"lax",maxAge:this.tokenMaxAge,domain:t.domain,path:t.path})}removeAuthToken(){let e=this.currentCookieOptions();this.removeCookie(this.tokenName,{domain:e.domain,path:e.path}),this.removeCookie(this.tokenName,{domain:".pagelines.com",path:"/"}),this.isLocalStorageFunctional()&&window.localStorage.removeItem(this.fallbackStorageKey)}getDeviceId(){return this.getCookie(this.deviceIdName)}},so=new gA,vA=["https://redirect-a.invalid","https://redirect-b.invalid"];yA=c.enum(["linkedin","x","facebook","tiktok","youtube","github","instagram","threads","email","phone","website","calendar"]),wA=c.object({platform:yA,handle:c.string(),url:c.string().optional()}),kA=c.preprocess(e=>Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.platform&&t.handle):e,c.array(wA)),xA=["image","audio","video","document"],y0=c.enum(xA),_A=["avatar","cover","general"],JS=c.enum(_A),$A=c.enum(["processing","active","failed","deleted"]),SA=c.enum(["low","standard","high"]),IA=c.enum(["jpg","jpeg","png","gif","webp","svg"]),EA=c.enum(["mp4","webm","ogg","mov","avi"]),TA=c.enum(["mp3","wav","ogg","opus","aac","flac","webm","m4a","mp4"]),NA=c.object({mediaId:c.string(),userId:c.string(),orgId:c.string(),botId:c.string().nullable().optional(),filename:c.string(),mimeType:c.string(),size:c.number(),src:c.string(),alt:c.string().optional(),context:JS.default("general"),status:$A.default("processing"),quality:SA.default("standard"),createdAt:c.string().optional(),updatedAt:c.string().optional()}),Mt=NA.extend({mediaType:y0.optional(),className:c.string().optional(),width:c.number().optional(),height:c.number().optional(),duration:c.number().optional(),blurhash:c.string().optional()}).partial(),CA=c.object({duration:c.number().optional(),thumbnail:c.string().optional(),autoplay:c.boolean().optional(),loop:c.boolean().optional(),muted:c.boolean().optional(),controls:c.boolean().optional()}),zA=c.object({duration:c.number().optional(),autoplay:c.boolean().optional(),loop:c.boolean().optional(),muted:c.boolean().optional(),controls:c.boolean().optional()}),OA=Mt.extend({mediaType:c.literal("image"),imageFormat:IA.optional()}),AA=Mt.extend({mediaType:c.literal("video"),videoFormat:EA.optional(),video:CA.optional()}),DA=Mt.extend({mediaType:c.literal("audio"),audioFormat:TA.optional(),audio:zA.optional()}),PA=Mt.extend({mediaType:c.literal("document")}),AF=c.discriminatedUnion("mediaType",[OA,AA,DA,PA]),qS=c.enum(["xxs","xs","sm","md","lg","xl"]),YS=c.enum(["primary","default","overlay","red","green","indigo","orange"]),XS=c.enum(["ghost","link","outline","solid"]),g0=c.object({key:c.string().optional(),label:c.string().optional(),href:c.string().optional(),size:qS.optional(),theme:YS.optional(),design:XS.optional(),icon:c.union([c.string(),Mt]).optional(),iconAfter:c.union([c.string(),Mt]).optional(),rounding:c.enum(["full","md","lg"]).optional(),loading:c.boolean().optional(),disabled:c.boolean().optional(),tooltip:c.string().optional(),onClick:c.any().optional(),testId:c.string().optional(),target:c.enum(["_blank","_self"]).optional(),type:c.enum(["button","submit","reset"]).optional()}),PF=c.object({buttons:c.array(g0).optional(),size:qS.optional(),theme:YS.optional(),design:XS.optional()}),RA=["COMPUTER_BOOT_FAILED","COMPUTER_CREATE_FAILED","BOT_DELETED","COMPUTER_DELETE_FAILED","COMPUTER_INACTIVE","COMPUTER_LIMIT","COMPUTER_NOT_FOUND","BOT_NOT_FOUND","COMPUTER_NOT_DEPLOYED","BOT_TOKENS_MISSING","COMPUTER_UNREACHABLE","COMPUTER_UPDATE_FAILED","COMPUTER_WAKE_TIMEOUT","ADMISSION_REQUIRED","ALREADY_MEMBER","ATTACHMENT_TYPE_UNSUPPORTED","AUTH_ACCOUNT_NOT_FOUND","AUTH_BOT_BLOCKED","AUTH_DISPOSABLE_EMAIL","AUTH_EMAIL_IN_USE","AUTH_INVALID","AUTH_INVALID_CODE","AUTH_INVALID_HANDOFF","AUTH_LOCKED_OUT","AUTH_MISSING","AUTH_PROVIDER_FAILED","AUTH_PROVIDER_NOT_CONFIGURED","AUTH_RATE_LIMITED","AUTH_REVOKED","AUTH_TURNSTILE_MISSING","AUTH_UNKNOWN","AUTH_WRONG_TYPE","ROUTINE_CHANNEL_UNAVAILABLE","ROUTINE_PURPOSE_REQUIRED","BOT_REPLY_FAILED","BILLING_BUDGET_REACHED","BILLING_DEMO_SPENT","BILLING_NO_PLAN","BILLING_PAST_DUE","BILLING_RUNAWAY_CAP","BILLING_SEAT_LIMIT","CHECKOUT_FAILED","CONFIRMATION_REQUIRED","CREATE_FAILED","CREDIT_LIMIT","DELETE_FAILED","DUPLICATE_INVITE","EMAIL_DELIVERY_FAILED","EMAIL_FAILED","EMAIL_MISMATCH","EMAIL_RATE_LIMITED","EMAIL_REASON_NOT_ELIGIBLE","EMPTY_STREAM","EMPTY_PATCH","ENV_VAR_CONFLICT","ENV_VAR_RESERVED","EXTENSION_INACTIVE","FORBIDDEN","HANDLE_TAKEN","IMAGE_GENERATION_FAILED","IMAGE_GENERATION_UNCONFIGURED","INTERNAL_ERROR","INVALID_FILE","INVALID_PRIMARY_CHANNEL","UNKNOWN_ROUTINE_CHANNEL","INVITE_CONFLICT","INVITE_EXPIRED","INVITE_INVALID","MCP_NOT_AVAILABLE","MCP_NOT_CONFIGURED","MEDIA_NOT_FOUND","MEDIA_SERVER_UNAVAILABLE","MEDIA_UPLOAD_FAILED","MEMORY_NOT_FOUND","MISSING_IDEMPOTENCY_KEY","NETWORK_ERROR","NO_WORKSPACE","NOT_A_MEMBER","NOT_AUTHORIZED","NOT_FOUND","ORG_NOT_FOUND","OVERAGE_CAP","OWNER_LOCK","PAIRING_VERIFY_FAILED","PAYMENT_FAILED","PLAN_LIMIT","PROVISIONER_UNAVAILABLE","RATE_LIMIT","RATE_LIMITED","REBUILD_FAILED","RESTART_FAILED","SEND_FAILED","STOP_FAILED","STREAM_DISCONNECT","STREAM_TIMEOUT","STRIPE_LOAD","TIMEOUT","TOKEN_ERROR","TOOL_PROTOCOL","TRIAL_ENDED","TURN_ACTIVE","UPLOAD_FAILED","VALIDATION_ERROR","VOICE_BUSY","VOICE_UNAVAILABLE","WAKE_FAILED"],QS=c.enum(RA),UA=4900,RS=`$${UA/100}/month`,jA=c.enum(["account","error"]),MA=["billing_no_plan","billing_seat_limit","billing_past_due","billing_runaway_cap","billing_budget_reached","billing_demo_spent","bot_deleted","computer_not_deployed","computer_boot_failed","computer_unreachable","computer_wake_timeout","stream_timeout","stream_disconnect","empty_stream","tool_protocol","rate_limit"],LA=c.enum(MA),eI=c.object({bucket:jA,code:LA,title:c.string(),help:c.string().optional(),actionLabel:c.string(),actionUrl:c.string()}),LF={billing_no_plan:{bucket:"account",title:"Billing needed",help:`Add a payment method to turn live replies back on. Plans start at ${RS} per active assistant, cancel anytime.`,actionLabel:"Open billing",oneLine:`The workspace needs a payment method before this assistant can reply; plans start at ${RS} per active assistant.`},billing_seat_limit:{bucket:"account",title:"Active assistant limit reached",help:"Your active assistants are all in use. Put one assistant to sleep or ask us to raise the ceiling.",actionLabel:"Open billing",oneLine:"The workspace has no unused active-assistant slots; one assistant must sleep or the limit must be raised."},billing_past_due:{bucket:"account",title:"Assistants paused",help:"Payment is overdue. Fix it and we\u2019ll bring your assistants back online.",actionLabel:"Fix payment",oneLine:"The workspace payment is overdue; its owner must fix it before assistants come back online."},billing_runaway_cap:{bucket:"account",title:"Usage limit reached",help:"Your workspace reached its usage limit. Review billing or contact support to keep your assistant running.",actionLabel:"Contact support",oneLine:"The workspace reached its usage limit; its owner can review billing or contact support."},billing_budget_reached:{bucket:"account",title:"Not enough credits",help:"Your workspace needs more included credits for another reply. Upgrade an assistant or wait for the next billing period.",actionLabel:"Review billing",oneLine:"The workspace needs more included credits; its owner can upgrade an assistant or wait for the next billing period."},billing_demo_spent:{bucket:"account",title:"Demo used up",help:"Your assistant has used the free demo. Starting a trial keeps it running around the clock, and is free for ten days.",actionLabel:"Start free trial",oneLine:"This workspace has used its free demo; starting a trial keeps the assistant running and is free for ten days."},bot_deleted:{bucket:"error",title:"Assistant deleted",help:"This chat is still here, but the assistant can no longer reply.",actionLabel:"",oneLine:"This assistant was deleted. The chat history remains, but it can no longer reply."},computer_not_deployed:{bucket:"error",title:"Assistant asleep",help:"Open the assistant profile to wake it up before chatting.",actionLabel:"Open assistant",oneLine:"This assistant needs to wake up before it can reply."},computer_boot_failed:{bucket:"error",title:"Couldn't wake up",help:"Open the assistant profile to restart it or check what failed.",actionLabel:"Open assistant",oneLine:"This assistant tried to wake up but hit an error."},computer_unreachable:{bucket:"error",title:"Not responding",help:"Open the assistant profile to check status or restart it.",actionLabel:"Open assistant",oneLine:"This assistant is not responding right now; its owner can check its status."},computer_wake_timeout:{bucket:"error",title:"Still waking",help:"Open the assistant profile to check status, or wait a minute and try again.",actionLabel:"Open assistant",oneLine:"This assistant is taking too long to wake up."},stream_timeout:{bucket:"error",title:"Reply too slow",help:"Your assistant took too long to start replying. Try your message again.",actionLabel:"Try again",oneLine:"This assistant took too long to start replying; try the message again."},stream_disconnect:{bucket:"error",title:"Connection lost",help:"The connection dropped while your assistant was replying. Send your message again to retry.",actionLabel:"Try again",oneLine:"The connection dropped while this assistant was replying; try the message again."},empty_stream:{bucket:"error",title:"Empty reply",help:"Your assistant could not generate a reply. Try your message again.",actionLabel:"Try again",oneLine:"This assistant did not return a reply; try the message again."},tool_protocol:{bucket:"error",title:"Tool call failed",help:"Your assistant tried to use a tool in a format PageLines could not run. Try the message again.",actionLabel:"Try again",oneLine:"This assistant tried to use a tool in a format PageLines could not run; try the message again."},rate_limit:{bucket:"error",title:"Slow down",help:"Too many messages at once. Wait a moment, then send your message again.",actionLabel:"Try again",oneLine:"Too many messages arrived at once; wait a moment and try again."}},tI=c.enum(["unknown","stopped","starting","running","unreachable","error"]),VA=c.enum(["wake","restart","rebuild","config_apply","setup"]),FA=c.enum(["running","coalesced","failed"]),BA=c.object({kind:VA,status:FA,startedAt:c.string().datetime(),detail:c.string().optional()}).strict(),rI=c.object({lifecycle:tI,changedAt:c.string().datetime().optional(),detail:c.string().optional(),blocker:eI.optional(),operation:BA.optional()}).strict(),Cl=Object.freeze({lifecycle:"unknown"}),ZA={running:"green",starting:"amber",unreachable:"red",error:"red",stopped:"grey",unknown:"grey"},HA=c.enum(["awake","asleep","changing","stuck"]),nI={awake:"Awake",asleep:"Asleep",changing:"Changing",stuck:"Needs attention"};KA={running:"Online",starting:"Waking up",unreachable:"Unreachable",error:"Error",stopped:"Asleep",unknown:"Checking"},WA={wake:"Waking up",restart:"Restarting",rebuild:"Rebuilding",config_apply:"Applying config",setup:"Setting up"};VF=c.enum(["wake","sleep","restart","rebuild"]);qA=c.object({key:c.string().optional(),id:c.string().optional(),label:c.string().optional(),srLabel:c.string().optional(),subLabel:c.string().optional(),value:c.union([c.string(),c.number()]).optional(),description:c.string().optional(),state:HA.optional(),count:c.number().optional(),className:c.string().optional(),media:Mt.optional(),subMedia:Mt.optional(),cover:Mt.optional(),icon:Mt.optional(),iconAfter:Mt.optional(),subIcon:c.string().optional(),href:c.string().optional(),target:c.enum(["_self","_blank"]).optional(),onClick:c.any().optional(),theme:c.enum(["primary","default"]).optional(),isActive:c.boolean().optional(),isDisabled:c.boolean().optional(),isHidden:c.boolean().optional(),priority:c.number().optional(),testId:c.string().optional(),items:c.array(c.any()).optional(),badges:c.array(g0).optional(),meta:c.array(g0).optional(),menuItems:c.array(c.any()).optional()}),FF=c.object({title:c.string().optional(),description:c.string().optional(),items:c.array(qA).optional()}),oI=c.string().trim().transform(e=>{if(!e.includes("/"))return e;try{let t=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`),[n,i]=t.pathname.split("/").filter(Boolean),r=t.hostname.toLowerCase();if((r==="linkedin.com"||r.endsWith(".linkedin.com"))&&n?.toLowerCase()==="in"&&i)return i}catch{}return e}).pipe(c.string().min(3).max(100).regex(/^[a-zA-Z0-9-]+$/,"Use a LinkedIn username or profile URL")),YA=c.string().trim().transform((e,t)=>{try{let n=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`),i=n.hostname.toLowerCase().replace(/^www\./,""),r=n.pathname.split("/").filter(Boolean)[0];if(!r||!["x.com","twitter.com","facebook.com"].includes(i))throw new Error("unsupported profile");return i==="twitter.com"?`https://x.com/${r}`:`https://${i}/${r}`}catch{return t.addIssue({code:"custom",message:"Use a LinkedIn username or an X or Facebook profile URL"}),c.NEVER}}),w0=c.string().trim().toLowerCase().pipe(c.email()),XA=c.enum(["member","pending"]),QA=c.object({lastBotId:c.string().nullable().optional(),userId:c.string(),email:c.string().optional(),handle:c.string().optional(),fullName:c.string().optional(),bio:c.string().optional(),linkedinUsername:oI.optional(),avatarId:c.string().optional(),avatar:Mt.optional(),isEmailVerified:c.boolean().optional(),primaryOrgId:c.string().optional(),lastActiveOrgId:c.string().optional(),onboarding:c.any().optional(),location:c.string().optional(),geo:c.any().optional(),systemRole:c.string().optional(),status:c.string().optional(),lastSeenAt:c.string().optional(),admittedAt:c.string().optional(),access:XA.optional(),createdAt:c.string().optional(),updatedAt:c.string().optional(),onboarded:c.boolean().optional()}),ZF=c.object({email:w0}),HF=c.object({email:w0,code:c.string().min(6,"Verification code is required"),timezone:c.string().max(64).optional()}),KF=c.object({newEmail:w0}),WF=c.object({credential:c.string().optional(),code:c.string().optional(),timezone:c.string().max(64).optional(),source:c.enum(["web","ios"]).optional()}).refine(e=>e.credential||e.code,{message:"Either credential or code must be provided"}),GF=c.object({identityToken:c.string().min(1),fullName:c.string().optional(),timezone:c.string().max(64).optional()}),aI=c.object({orgId:c.string().optional(),handle:c.string().optional(),name:c.string().optional(),email:c.string().nullable().optional(),website:c.string().url().nullable().optional(),summary:c.string().nullable().optional(),avatarId:c.string().nullable().optional(),avatar:Mt.optional(),coverId:c.string().nullable().optional(),cover:Mt.optional(),accounts:kA.nullable().optional(),ownerId:c.string().optional(),isPersonal:c.boolean().optional(),stripeCustomerIdTest:c.string().nullable().optional(),stripeCustomerIdLive:c.string().nullable().optional(),maxUsers:c.number().optional(),timezone:c.string().nullable().optional(),apiKey:c.string().nullable().optional(),syncedPlan:c.string().nullable().optional(),syncedBillingStatus:c.string().nullable().optional(),firstPaidAt:c.string().nullable().optional(),entitlementDeleteAt:c.string().nullable().optional(),billingLastSyncedAt:c.string().nullable().optional(),syncedPeriodStart:c.string().nullable().optional(),syncedPeriodEnd:c.string().nullable().optional(),onboarding:c.any().optional(),status:c.string().optional(),createdAt:c.string().optional(),updatedAt:c.string().optional()}),eD=c.object({completedAt:c.string().datetime().optional(),setupBy:c.string().optional(),billingSetup:c.boolean().optional(),teamInvitesSetup:c.boolean().optional(),brandingSetup:c.boolean().optional(),domainsSetup:c.boolean().optional()}),tD=c.object({membershipId:c.string(),orgId:c.string(),name:c.string(),handle:c.string(),avatarId:c.string().optional(),avatar:Mt.optional(),coverId:c.string().optional(),cover:Mt.optional(),role:c.enum(["owner","admin","member","observer"]),inviterName:c.string().optional(),memberCount:c.number().optional(),hasComputer:c.boolean().optional(),computerCount:c.number().optional(),joinedAt:c.string().datetime(),onboarding:eD.optional()}),rD=QA.extend({orgs:c.array(tD).optional()}),US=[["#6366f1","#8b5cf6"],["#3b82f6","#06b6d4"],["#10b981","#34d399"],["#f59e0b","#f97316"],["#ef4444","#f97316"],["#ec4899","#8b5cf6"],["#14b8a6","#3b82f6"],["#8b5cf6","#ec4899"]];oD=["[SILENT]","SILENT","NO_REPLY","NO REPLY","NO-OP","NOOP","NO_OP","NO OP","[NO-OP]","[NOOP]","[NO_OP]","[NO OP]","HEARTBEAT_OK"],aD=new Set(oD);sI={wake:300*1e3,bootGrace:420*1e3,provision:600*1e3,firstStart:45*1e3,stop:30*1e3},jS={AUTH_ACCOUNT_NOT_FOUND:"Account not found. Ask your workspace admin for an invite.",AUTH_INVALID:"Your session has expired. Sign in again to continue.",AUTH_LOCKED_OUT:"Too many failed attempts. Request a new code to try again.",AUTH_INVALID_CODE:"That code didn't match. Double-check the email and try again.",AUTH_INVALID_HANDOFF:"This link has expired. Open the dashboard from the app again.",AUTH_DISPOSABLE_EMAIL:"Please use your work email address.",AUTH_RATE_LIMITED:"Too many requests. Wait a minute and try again.",AUTH_PROVIDER_FAILED:"Sign-in failed. Try again or use email instead.",AUTH_PROVIDER_NOT_CONFIGURED:"That sign-in method isn't available right now.",ADMISSION_REQUIRED:"PageLines is invite-only. Request access to create your bot.",PLAN_LIMIT:"Your active computers are all in use. Put one computer to sleep or ask us to raise the ceiling.",CREDIT_LIMIT:"Your workspace reached its usage limit. Review billing or contact support to keep your assistant running.",STRIPE_LOAD:"Couldn't open checkout. Try again \u2014 if it persists, contact support.",CHECKOUT_FAILED:"Couldn't start checkout. Try again in a moment.",PAYMENT_FAILED:"Your payment couldn't go through. Update your card to continue.",WAKE_FAILED:"Your assistant didn't wake up. Try again in a moment.",VOICE_BUSY:"Your assistant is on another call. Try again in a moment.",VOICE_UNAVAILABLE:"Voice isn't available right now. Try again in a moment.",STOP_FAILED:"Couldn't put your assistant to sleep. Try again.",RESTART_FAILED:"Restart didn't finish. Try again \u2014 if it persists, rebuild.",REBUILD_FAILED:"Rebuild didn't finish. Try again or contact support.",CREATE_FAILED:"Couldn't create your assistant. Try again in a moment.",DELETE_FAILED:"Couldn't delete your assistant. Try again \u2014 your data is safe.",BOT_NOT_FOUND:"We couldn't find that assistant.",COMPUTER_NOT_FOUND:"We couldn't find that computer.",COMPUTER_INACTIVE:"This computer is off. Turn it on to start it.",ATTACHMENT_TYPE_UNSUPPORTED:"Your assistant can't read this file type yet.",ROUTINE_CHANNEL_UNAVAILABLE:"Your delivery channel isn't reachable. Pair it again or choose PageLines Messenger.",ROUTINE_PURPOSE_REQUIRED:"Say what the scheduled message or work should contain.",NETWORK_ERROR:"Network issue. Check your connection and try again.",TIMEOUT:"The request took too long. Try again in a moment.",FORBIDDEN:"You don't have access to this.",RATE_LIMITED:"Too many requests. Wait a moment and try again."};lI=c.enum(["active","stopped"]),cD=c.enum(["notFound","busy","rateLimited","timeout","invalidConfig","transient","fatal"]),YF=c.object({ok:c.literal(!1),error:c.string(),code:QS.optional(),issue:eI.optional(),providerErrorKind:cD.optional()}),uD=c.object({kind:c.enum(["icon","favicon","service"]),icon:c.string().min(1).optional(),domain:c.string().min(1).optional(),serviceKey:c.string().min(1).optional()}).strict(),cI=c.object({activityId:c.string().min(1),turnId:c.string().min(1),status:c.enum(["started","completed","failed"]),label:c.string().trim().min(1),kind:c.enum(["search","file","image","service","routine","handoff","other"]),toolName:c.string().min(1).optional(),serviceKey:c.string().min(1).optional(),startedAt:c.string().datetime().optional(),endedAt:c.string().datetime().optional(),durationMs:c.number().int().nonnegative().optional(),note:c.string().trim().min(1).optional(),visual:uD.optional()}).strict(),dD=cI.extend({status:c.enum(["completed","failed"])}),Bn=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(new Date(0)),!0}catch{return!1}},"Invalid IANA timezone");dI=y0,pD=c.object({kind:c.literal("inline"),offset:c.number().int().nonnegative()}),pI=c.object({type:dI,src:c.url(),filename:c.string().min(1),mimeType:c.string().min(1),mediaId:c.string().min(1).optional(),size:c.number().int().nonnegative().optional(),width:c.number().int().positive().optional(),height:c.number().int().positive().optional(),duration:c.number().nonnegative().optional(),text:c.string().optional(),placement:pD.optional()}),fI=c.object({ref:c.string().min(1).max(256)}).strict(),mI=c.enum(["handled","dismissed","deferred"]),hI=c.iso.datetime();fD=fI.extend({disposition:mI.optional(),revisitAt:hI.optional()}).superRefine(gI),rB=fI.extend({disposition:mI,revisitAt:hI.optional()}).superRefine(gI),mD=c.object({turnId:c.string().min(1).optional(),turnOutcome:c.enum(["failed","stopped"]).optional(),attachments:c.array(pI).optional(),toolActivities:c.array(dD).optional(),issue:c.object({code:c.string(),bucket:c.enum(["account","error"]),actionLabel:c.string(),actionUrl:c.string(),help:c.string().optional()}).optional(),notification:c.object({push:c.boolean().optional(),excludeUserId:c.string().min(1).optional()}).optional(),routine:c.object({run:c.object({routineRunId:c.string(),name:c.string().optional(),sourceKind:c.enum(["webhook","schedule","manual","heartbeat"]),sourceLabel:c.string().optional(),deliveryId:c.string().optional(),status:c.enum(["received","forwarded","owner_notified","needs_approval","completed","failed","dropped"])}).catchall(c.unknown())}).catchall(c.unknown()).optional(),voiceDelegated:c.literal(!0).optional(),ownerHandoff:c.literal(!0).optional(),attention:c.array(fD).max(20).optional()}).catchall(c.unknown()),hD=c.object({messageId:c.string().min(1),conversationId:c.string().min(1),role:c.enum(["user","assistant","system"]),authorParticipantId:c.string().nullable(),systemKind:c.string().nullable(),content:c.string(),sequence:c.string().min(1),clientNonce:c.string().nullable().optional(),metadata:mD.nullable().optional(),status:c.string().nullable().optional(),createdAt:c.string(),updatedAt:c.string()}),k0=c.object({type:dI,mediaId:c.string().min(1)}),nB=c.object({conversationId:c.string().min(1),content:c.string().max(1e4).default(""),clientNonce:c.string().max(64).optional(),attachments:c.array(k0).max(10).optional(),channel:c.enum(["ios","dashboard"]).optional(),actionUrls:c.object({billing:c.string().max(500),bot:c.string().max(500)}).optional(),viewerTimezone:Bn.optional()}).refine(e=>e.content.trim().length>0||(e.attachments?.length??0)>0,{path:["content"],message:"Message or attachment required"}),vI=c.object({type:c.enum(["user","bot"]),id:c.string().min(1)}).strict();iB=c.object({orgId:c.string().min(1),participants:c.array(vI).min(1).max(20)}).strict().superRefine(bI),oB=c.object({orgId:c.string().min(1),participants:c.array(vI).min(1).max(20)}).strict().superRefine((e,t)=>{bI(e,t),e.participants.some(n=>n.type==="bot")||t.addIssue({code:"custom",path:["participants"],message:"New sessions require at least one agent participant."})}),aB=c.object({category:c.string().min(1).max(30).optional(),reason:c.string().max(2e3).optional()}).strict(),gD=c.enum(["1:1","4:3","3:4","16:9","9:16"]),vD=c.enum(["1K","2K","4K"]),sB=c.object({prompt:c.string().trim().min(1).max(4e3),aspectRatio:gD.default("1:1"),outputFormat:c.enum(["png","jpeg","webp"]).default("webp"),resolution:vD.default("2K"),style:c.string().trim().max(200).optional(),altText:c.string().trim().max(500).optional(),referenceMediaIds:c.array(c.string().min(1)).max(4).optional()}).strict(),lB=c.object({mediaId:c.string().min(1),src:c.url(),filename:c.string().min(1),mimeType:c.string().min(1),width:c.number().int().positive().optional(),height:c.number().int().positive().optional(),provider:c.string().min(1).optional(),providerRequestId:c.string().min(1).optional(),media:c.string().startsWith("MEDIA:"),attachment:pI.extend({type:c.literal("image")})}),uB=c.object({identityToken:c.string().min(1),fullName:c.string().optional()}),bD=c.object({redirect:c.string(),redirectReason:c.string(),isNew:c.boolean(),deviceId:c.string()}),dB=c.object({ok:c.literal(!0),data:bD,token:c.string()}),pB=c.object({path:c.string().startsWith("/","path must be a relative dashboard path").refine(bA,"path must be a relative dashboard path")}),yD=c.object({url:c.string()}),fB=c.object({ok:c.literal(!0),data:yD}),mB=c.object({token:c.string().min(1)}),wD=c.object({redirect:c.string(),redirectReason:c.string(),deviceId:c.string()}),hB=c.object({ok:c.literal(!0),data:wD,token:c.string()}),yI=JS,kD=y0,v0=c.object({mediaId:c.string(),src:c.string(),alt:c.string().nullable().optional(),filename:c.string().optional(),displayName:c.string().nullable().optional(),mimeType:c.string().optional(),mediaType:kD.optional(),size:c.number().optional(),width:c.number().nullable().optional(),height:c.number().nullable().optional(),duration:c.number().nullable().optional(),context:yI.nullable().optional(),blurhash:c.string().nullable().optional(),quality:c.string().optional(),status:c.string().optional(),userId:c.string().optional(),orgId:c.string().optional(),botId:c.string().nullable().optional(),createdAt:c.string().optional(),updatedAt:c.string().optional()}),yB=c.object({file:c.string().describe("Binary file. multipart/form-data field \u2014 the actual upload. The server validates type + size and normalizes image uploads before storage. Audio/video/document uploads use the same uploader and are classified by MIME type."),context:yI.optional().default("general"),botId:c.string().optional(),orgId:c.string().optional(),duration:c.number().optional()}),wI=c.object({viewerTimezone:Bn.optional(),location:c.object({label:c.string().max(500),city:c.string().optional(),region:c.string().optional(),countryCode:c.string().optional(),timezone:c.string().optional(),source:c.literal("geoip"),precision:c.enum(["city","region","country"]),confidence:c.enum(["medium","low"]),vpnOrDatacenter:c.enum(["likely","unknown"])}).optional()}),xD=c.object({status:c.enum(["available","unavailable"]),user:c.string().max(16e3).optional(),memory:c.string().max(16e3).optional(),agents:c.string().max(4e3).optional()}).strict(),_B=c.object({bot:c.object({id:c.string(),name:c.string(),title:c.string().nullable().optional(),timezone:Bn}),scope:c.enum(["private","org","public"]),channel:c.string().max(120),currentTime:c.iso.datetime(),scopePrompt:c.string().optional(),observations:wI.optional(),lastObservedTimezone:Bn.optional(),lean:xD.optional()}),kI=c.enum(["woman","man"]),_D=[{key:"ava",gender:"woman",accent:"American",character:"Warm, patient and understanding",isDefault:!0},{key:"hope",gender:"woman",accent:"American",character:"Soft-spoken, smooth and kind"},{key:"lauren",gender:"woman",accent:"American",character:"Friendly, comforting and soft"},{key:"amy",gender:"woman",accent:"American",character:"Natural and sweet"},{key:"eve",gender:"woman",accent:"American",character:"Authentic, energetic and happy"},{key:"jessica",gender:"woman",accent:"British",character:"Smooth, articulate and warm"},{key:"adam",gender:"man",accent:"American",character:"Engaging, friendly and bright",isDefault:!0},{key:"jon",gender:"man",accent:"American",character:"Relaxed, deep and approachable"},{key:"joe",gender:"man",accent:"British",character:"Reflective and thoughtful"},{key:"peter",gender:"man",accent:"Australian",character:"Deep, warm and direct"}],xI=c.enum(_D.map(e=>e.key)),$B=c.object({conversationId:c.string().min(1),viewerTimezone:Bn.optional()}).strict(),SB=c.object({conversationId:c.string().min(1),botId:c.string().min(1),personaName:c.string().min(1),personaTitle:c.string().max(255).nullable().optional(),gender:kI,voiceKey:xI.nullable(),sessionScope:c.enum(["private","org","public"]),observations:wI.optional(),threadSummary:c.string(),capabilities:c.array(c.object({name:c.string().min(1),description:c.string().min(1)})).optional(),surfaceGuidance:c.string().optional(),maxDurationSeconds:c.number().int().positive().max(3600).optional(),expiresAt:c.iso.datetime()}),$D=c.literal("livekit"),IB=c.object({name:c.enum(["voice.ready","voice.first_playback","voice.failed"]),client:c.enum(["web","ios"]),botId:c.string().min(1).max(64).optional(),conversationId:c.string().min(1).max(64).optional(),provider:$D.optional(),durationMs:c.number().int().min(0).max(36e5),phase:c.enum(["idle","minting","connecting","live","ended"]).optional(),code:c.string().min(1).max(64).optional(),detail:c.string().min(1).max(300).optional(),appVersion:c.string().min(1).max(32).optional(),appBuild:c.string().min(1).max(32).optional()}).strict(),EB=c.object({provider:c.literal("livekit"),url:c.string().min(1),token:c.string().min(1),room:c.string().min(1)}).strict(),SD=c.enum(["identity","working-style","complete"]),ID=c.string().min(1).max(50).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),Tl=c.object({botId:c.string().min(1),computerId:c.string().min(1),handle:c.string().min(2).max(50),name:c.string().min(1).max(100),emoji:c.string().max(8).nullable().optional(),title:c.string().max(120).nullable().optional(),summary:c.string().max(500).nullable().optional(),avatarId:c.string().nullable().optional(),coverId:c.string().nullable().optional(),avatar:Mt.optional(),cover:Mt.optional(),email:c.email().nullable().optional(),website:c.url().nullable().optional(),accounts:c.array(c.object({platform:c.enum(["linkedin","x","facebook","tiktok","youtube","github","instagram","threads","email","phone","website"]),handle:c.string()})).nullable().optional(),gender:kI.optional(),voiceKey:xI.nullable().optional(),isPrimary:c.boolean(),collaborationEnabled:c.boolean(),publicChatEnabled:c.boolean(),status:c.enum(["active","deleted"]),onboardingStage:SD.nullable().optional(),onboardedAt:c.string().nullable().optional(),routinePrimaryChannel:ID.optional(),firstMessageAt:c.string().nullable().optional(),firstValueAt:c.string().nullable().optional(),lastMessageAt:c.string().nullable().optional(),createdAt:c.string(),updatedAt:c.string()}).strict(),x0=Tl.pick({name:!0,emoji:!0,title:!0,summary:!0,gender:!0,voiceKey:!0}).extend({handle:Tl.shape.handle.optional(),avatarPreset:c.string().min(1).max(64).optional(),avatarMediaId:c.string().optional()}).strict(),TB=x0.extend({computerId:c.string().min(1)}).strict(),NB=Tl.pick({name:!0,handle:!0,emoji:!0,title:!0,summary:!0,email:!0,website:!0,gender:!0,voiceKey:!0,routinePrimaryChannel:!0,collaborationEnabled:!0,publicChatEnabled:!0}).partial().extend({avatarMediaId:c.string().nullable().optional(),coverMediaId:c.string().nullable().optional()}).strict(),_I=c.enum(["essential","professional","business"]),rp=rI.partial().extend({computerId:c.string().min(1),ownerId:c.string().min(1),owner:c.object({userId:c.string(),fullName:c.string().optional(),avatar:v0.optional()}).optional(),orgId:c.string().min(1),name:c.string().min(1).max(100),model:c.string().nullable(),timezone:Bn,billingTier:_I,desiredStatus:lI.nullable(),status:c.enum(["active","deleted"]),lastActiveAt:c.string().nullable().optional(),createdAt:c.string(),updatedAt:c.string()}).strict(),CB=c.object({orgId:c.string().min(1),name:rp.shape.name.optional(),timezone:Bn.optional(),primaryBot:x0}).strict(),zB=rp.pick({name:!0,model:!0,timezone:!0}).partial().strict(),ED=c.enum(["none","active_assistant"]),TD=c.enum(["none","active","trial","canceling","past_due","paused"]),ND=c.object({brand:c.string(),last4:c.string(),expMonth:c.number(),expYear:c.number()}),CD=c.object({date:c.string(),amount:c.number(),status:c.string(),invoicePdf:c.string().optional()}),zD=c.object({graceEndsAt:c.string().optional(),suspended:c.boolean(),url:c.string().optional()}),OB=c.object({plan:ED,status:TD,price:c.number(),tierRates:c.record(c.string(),c.number()).optional(),maxComputers:c.number(),activeComputers:c.number(),workspaceTier:_I.optional(),upcomingAmountDue:c.number().optional(),upcomingDueDate:c.string().optional(),nextBillDate:c.string().optional(),cancelAtPeriodEnd:c.boolean().optional(),cancelAt:c.string().optional(),trialEnd:c.string().optional(),trialDaysRemaining:c.number().optional(),paymentMethod:ND.optional(),paymentRecovery:zD.optional(),invoices:c.array(CD),stripeError:c.string().optional()}),OD=c.enum(["demo_computer_exists","demo_usage_exhausted","subscription_required","plan_limit"]),AB=c.object({canCreate:c.boolean(),activeComputers:c.number().int().nonnegative(),computerLimit:c.number().int().nonnegative(),isDemo:c.boolean(),reason:OD.optional()}),DB=c.object({orgId:c.string(),computerName:c.string().optional(),runtime:c.string().optional()}),PB=c.object({created:c.number(),skipped:c.number(),errors:c.array(c.string())}),RB=c.object({updated:c.number(),errors:c.array(c.string())}),AD=rI,DD=c.object({code:QS,message:c.string(),bucket:c.enum(["account","error"]),actionLabel:c.string().optional(),actionUrl:c.string().optional(),help:c.string().optional()}),PD=c.discriminatedUnion("event",[c.object({event:c.literal("status"),data:AD}),c.object({event:c.literal("message"),data:c.object({message:hD})}),c.object({event:c.literal("message_delta"),data:c.object({delta:c.string(),turnId:c.string(),messageId:c.string().optional(),role:c.enum(["assistant","system"]).optional()})}),c.object({event:c.literal("working_state"),data:c.object({description:c.string(),turnId:c.string().optional()})}),c.object({event:c.literal("tool_activity"),data:cI}),c.object({event:c.literal("working_end"),data:c.object({turnId:c.string().optional()}).strict()}),c.object({event:c.literal("stream_end"),data:c.object({turnId:c.string().optional()}).strict()}),c.object({event:c.literal("error"),data:DD})]);LD=c.object({label:c.string().trim().min(1).max(40),reply:c.string().trim().min(1).max(500),style:c.enum(["primary","default","destructive"]).optional()}).strip(),VD=c.object({version:c.literal(1),title:c.string().trim().min(1).max(200),body:c.string().trim().min(1).max(8e3).optional(),actions:c.array(LD).min(1).max(3).optional()}).strip();FD=c.string().trim().min(1).max(240),b0=c.string().trim().min(1).max(800),Zn=c.string().trim().min(1).max(80).regex(/^[A-Za-z0-9_.:-]+$/),za=c.string().trim().min(1).max(120),BD=c.union([c.string().max(500),c.number().finite(),c.boolean(),c.null()]),EI=c.record(Zn,BD),ZD=c.enum(["compact","currency","duration","integer","percent","raw"]),HD=c.object({title:FD,description:b0.optional(),footer:b0.optional()}).strip(),TI=c.object({dataKey:Zn,label:za.optional(),axisLabel:za.optional(),valueFormat:ZD.optional(),valuePrefix:c.string().trim().max(12).optional(),valueSuffix:c.string().trim().max(12).optional()}).strip(),KD=c.object({kind:c.literal("linear"),dataKey:Zn,label:za.optional()}).strip(),$0=c.object({version:c.literal(1),meta:HD,fallbackMarkdown:c.string().trim().min(1).max(4e3)}).strip();GD=$0.extend({visualType:c.literal("chart"),chartType:c.enum(["bar","line","scatter"]),xKey:Zn,xAxisLabel:za.optional(),series:c.array(TI).min(1).max(6),data:c.array(EI).min(1).max(120),layout:c.enum(["horizontal","vertical"]).optional(),stacking:c.enum(["grouped","stacked"]).optional(),trendLine:KD.optional()}).strip().superRefine((e,t)=>{e.stacking&&e.chartType!=="bar"&&t.addIssue({code:"custom",path:["stacking"],message:"Stacking is only supported for bar charts"}),e.trendLine&&e.chartType!=="line"&&e.chartType!=="scatter"&&t.addIssue({code:"custom",path:["trendLine"],message:"Trend lines are only supported for line and scatter charts"}),NI(e.data,[{path:["xKey"],value:e.xKey},...e.series.map((n,i)=>({path:["series",i,"dataKey"],value:n.dataKey})),...e.trendLine?[{path:["trendLine","dataKey"],value:e.trendLine.dataKey}]:[]],t),CI(e.data,[...e.series.map((n,i)=>({path:["series",i,"dataKey"],value:n.dataKey})),...e.trendLine?[{path:["trendLine","dataKey"],value:e.trendLine.dataKey}]:[]],t)}),JD=$0.extend({visualType:c.literal("chart"),chartType:c.literal("pie"),nameKey:Zn,valueKey:Zn,series:c.array(TI).max(1).optional(),data:c.array(EI).min(1).max(16)}).strip().superRefine((e,t)=>{NI(e.data,[{path:["nameKey"],value:e.nameKey},{path:["valueKey"],value:e.valueKey},...(e.series??[]).map((n,i)=>({path:["series",i,"dataKey"],value:n.dataKey}))],t),CI(e.data,[{path:["valueKey"],value:e.valueKey,nonnegative:!0}],t)}),qD=c.discriminatedUnion("chartType",[GD,JD]),YD=c.object({id:Zn,label:za,detail:b0.optional(),kind:c.enum(["actor","agent","decision","event","input","output","system","task"]).optional()}).strip(),XD=c.object({from:Zn,to:Zn,label:za.optional()}).strip(),QD=$0.extend({visualType:c.literal("diagram"),diagramType:c.enum(["flow","org","sequence","state"]),layout:c.enum(["auto","left-to-right","radial","top-to-bottom"]).default("auto"),nodes:c.array(YD).min(1).max(24),edges:c.array(XD).max(48)}).strip().superRefine((e,t)=>{let n=new Set(e.nodes.map(i=>i.id));for(let[i,r]of e.edges.entries())n.has(r.from)||t.addIssue({code:"custom",path:["edges",i,"from"],message:`Unknown node id "${r.from}"`}),n.has(r.to)||t.addIssue({code:"custom",path:["edges",i,"to"],message:`Unknown node id "${r.to}"`})}),MS=c.union([qD,QD]);OI=c.object({conversationParticipantId:c.string().min(1),type:c.enum(["user","bot","anonymous"]),id:c.string(),role:c.enum(["owner","requester","member"]),status:c.enum(["active","left","deleted"]),displayName:c.string().optional(),handle:c.string().optional(),avatarUrl:c.string().optional()}).strict(),AI=c.object({messageId:c.string(),role:c.enum(["user","assistant","system"]),content:c.string(),sequence:c.string(),createdAt:c.string()}),VB=c.object({conversationId:c.string(),orgId:c.string(),kind:c.enum(["direct","group"]),updatedAt:c.string(),viewerRole:c.enum(["owner","requester","member"]),participants:c.array(OI),lastMessage:AI.nullable(),openingMessage:c.string().nullable(),unreadCount:c.number().int().nonnegative(),latestSequence:c.string().nullable()}),FB=c.object({sequence:c.string().min(1)}),BB=c.object({turnId:c.string().min(1).optional()}).strict(),ZB=c.object({cancelled:c.boolean(),cancelledTurnIds:c.array(c.string())}).strict(),HB=c.object({conversationId:c.string(),messageId:c.string(),sequence:c.string(),snippet:c.string(),createdAt:c.string(),participants:c.array(OI)}),KB=c.object({conversationId:c.string(),lastMessage:AI.nullable(),unreadCount:c.number().int().nonnegative(),latestSequence:c.string().nullable()}),Lr=c.preprocess(e=>e===void 0?null:e,c.string().nullable()),o6=c.preprocess(e=>e===void 0?null:e,tI.nullable()),a6=c.preprocess(e=>e===void 0?null:e,lI.nullable()),s6=c.preprocess(e=>e===void 0?null:e,c.enum(["user","assistant","system"]).nullable()),LS=c.preprocess(e=>e===void 0?0:e,c.number()),l6=c.object({computerId:c.string(),handle:c.string(),name:c.string(),orgId:c.string(),orgName:Lr,orgHandle:Lr,ownerEmail:Lr,ownerName:Lr,state:o6,desiredStatus:a6,runtime:c.string(),imageVersion:Lr,lastHealthyAt:Lr,lastActiveAt:Lr,lastUserMessageAt:Lr,lastMessageAt:Lr,lastMessageRole:s6,lastMessageChannel:Lr,primaryChannel:Lr,totalMessages:LS,totalSessions:LS,error:Lr,appHandle:c.string(),hostAppExists:c.boolean(),plan:c.string(),billingStatus:c.string(),billingActive:c.boolean(),createdAt:c.string(),updatedAt:c.string()}),c6=c.object({running:c.number(),stopped:c.number(),error:c.number(),starting:c.number(),unknown:c.number(),total:c.number()}),GB=c.object({computers:c.array(l6),summary:c6,orphanedApps:c.array(c.string()),dailyMessages30d:c.array(c.number().int()).optional(),hostAppCount:c.number().optional(),latestVersions:c.record(c.string(),c.string()).optional()}),u6=c.object({mediaId:c.string().optional(),src:c.string().optional(),alt:c.string().optional(),width:c.number().optional(),height:c.number().optional(),mimeType:c.string().optional(),mediaType:c.string().optional(),blurhash:c.string().optional()}),qB=c.object({membershipId:c.string(),userId:c.string(),orgId:c.string(),email:c.string(),fullName:c.string().optional(),role:c.enum(["owner","admin","member","observer"]),status:c.enum(["active","suspended"]),joinedAt:c.string(),lastSeenAt:c.string().optional(),avatar:u6.optional()}),YB=c.object({invitationId:c.string(),email:c.string(),role:c.enum(["admin","member"]),status:c.string(),expiresAt:c.string(),createdAt:c.string()}),d6=c.object({token:c.string(),email:c.string(),orgId:c.string(),orgName:c.string(),orgInitial:c.string(),inviterName:c.string().optional(),inviterEmail:c.string(),role:c.enum(["owner","admin","member","observer"]),status:c.enum(["pending","accepted","expired","revoked"]),expiresAt:c.string(),memberCount:c.number().optional()}),XB=c.object({email:c.string().email(),role:c.enum(["admin","member"]).optional(),message:c.string().max(500).optional()}).strict(),QB=c.object({role:c.enum(["admin","member"])}).strict(),e7=c.object({token:c.string().min(1)}).strict(),t7=c.object({message:c.string()}),r7=c.object({invitationId:c.string(),message:c.string()}),n7=c.object({message:c.string(),membershipId:c.string(),orgId:c.string(),role:c.enum(["owner","admin","member","observer"])}),i7=c.object({invite:d6.nullable()}),p6={};uA(p6,{zNotificationTelemetryAck:()=>g6,zNotificationTelemetryEvent:()=>h6,zRegisterDeviceRequest:()=>f6,zRegisterDeviceResponse:()=>m6});f6=c.object({deviceId:c.string().min(1).max(64),pushToken:c.string().min(1).max(200),appVersion:c.string().max(40).optional(),osVersion:c.string().max(40).optional(),model:c.string().max(80).optional()}),m6=c.object({deviceId:c.string().min(1).max(64)}),h6=c.object({deviceId:c.string().min(1).max(64),kind:c.string().min(1).max(30),action:c.enum(["displayed","tapped","dismissed"]),messageId:c.string().max(32).optional()}),g6=c.object({updated:c.boolean()}),s7=aI.pick({orgId:!0,handle:!0,name:!0,email:!0,website:!0,avatarId:!0,coverId:!0,summary:!0,timezone:!0,isPersonal:!0,status:!0,updatedAt:!0}).extend({avatar:v0.nullable().optional(),cover:v0.nullable().optional()}),l7=c.object({name:c.string().min(1).max(255),handle:c.string().min(2).max(50).optional(),timezone:Bn.optional()}).strict(),c7=aI.pick({name:!0,email:!0,website:!0,summary:!0,timezone:!0}).extend({name:c.string().min(1).max(255).optional(),email:c.preprocess(e=>e===""?null:e,c.string().email().nullable()).optional(),timezone:Bn.optional(),avatarMediaId:c.string().nullable().optional(),coverMediaId:c.string().nullable().optional()}).strict(),d7=c.object({used:c.number().int().nonnegative(),limit:c.number().int().nonnegative(),remaining:c.number().int().nonnegative(),periodEnd:c.string(),isDemo:c.boolean(),state:c.enum(["ok","warning","exhausted"])}),f7=c.object({messagesHandled:c.number().int().nonnegative(),proactiveRuns:c.number().int().nonnegative(),approvalsWaiting:c.number().int().nonnegative(),approvalConversationId:c.string().optional(),approvalBotId:c.string().optional(),dailyHandled:c.array(c.number().int().nonnegative()).length(30),messagesByAssistant:c.array(c.object({botId:c.string(),count:c.number().int().nonnegative()})),briefingsDelivered:c.number().int().nonnegative(),scheduledRuns:c.number().int().nonnegative(),prev30MessagesHandled:c.number().int().nonnegative(),prev30BriefingsDelivered:c.number().int().nonnegative(),prev30ScheduledRuns:c.number().int().nonnegative(),since:c.string()}),v6=c.enum(["success","info","warning"]),b6=c.object({orgId:c.string(),name:c.string(),avatarUrl:c.string().nullable()}),y6=c.object({key:c.string(),label:c.string(),tone:v6,status:c.string(),trialDaysRemaining:c.number().optional()}),w6=c.object({activeComputerLimit:c.number().int().nonnegative(),activeComputerCount:c.number().int().nonnegative(),computerCount:c.number().int().nonnegative()}),h7=c.object({org:b6,plan:y6,quota:w6,memberCount:c.number().int().nonnegative()}),k6=c.object({sender:c.enum(["user","agent"]),text:c.string()}),x6=c.enum(["works-now","guided-setup","coming-soon","custom-workflow"]),_6=c.object({docsUrl:c.string(),verifiedAt:c.string(),version:c.string().optional(),versionPolicy:c.enum(["date-versioned","header-versioned","path-versioned","endpoint-versioned","unversioned"]),note:c.string().optional()}),$6=c.object({key:c.string(),label:c.string(),rank:c.number()}),S6=c.object({text:c.string(),tone:c.enum(["info","warning","success","danger"])}),v7=c.object({serviceKey:c.string(),name:c.string(),description:c.string(),shortDescription:c.string(),subtitle:c.string().optional(),icon:c.string().optional(),category:c.string(),categoryLabel:c.string(),categoryRank:c.number(),featuredRank:c.number().optional(),secondaryCategories:c.array($6),badges:c.array(S6),tags:c.array(c.string()),searchAliases:c.array(c.string()),jtbd:c.string(),useCase:c.string(),demoScenario:c.string(),sampleConversation:c.array(k6),publicStatus:x6,apiVerification:_6.optional(),setupDifficulty:c.string(),risk:c.string(),price:c.string(),kind:c.string(),tier:c.string(),installLevel:c.enum(["computer","org","both"]),setupSummary:c.string().optional(),pagePath:c.string()}),I6=c.object({title:c.string().optional(),text:c.string()}),y7=c.object({content:c.string(),mediaType:c.enum(["application/json","text/plain"]),copyLabel:c.string(),action:c.object({label:c.string(),url:c.url()}),steps:c.array(I6)}),k7=c.object({fullName:c.string().min(1).max(100).optional(),bio:c.string().max(500).nullable().optional(),linkedinUsername:oI.nullable().optional(),profileUrl:YA.nullable().optional(),avatarMediaId:c.string().nullable().optional(),lastBotId:c.string().nullable().optional(),lastActiveOrgId:c.string().nullable().optional()}).strict(),Qd=8e3,E6=c.string().regex(/^[A-Z][A-Z0-9_]*$/),T6=c.object({name:c.string().trim().min(1).max(100),instructions:c.string().trim().min(1).max(Qd),credentialNames:c.array(E6).max(10)}),DI=c.object({mediaId:c.string().min(1),sha256:c.string().regex(/^[a-f0-9]{64}$/).optional(),name:c.string().min(1).max(100)}).strict(),N6=T6.extend({toolId:c.string().min(1),assets:c.array(DI)}).strict(),C6=c.object({moment:c.enum(["briefing","checkin","closeout","custom"]),name:c.string().trim().min(1).max(100),policy:c.string().trim().min(1).max(Qd),time:c.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),active:c.boolean()}).strict(),z6=c.object({serviceKey:c.string().min(1).max(50)}).strict(),O6={schemaVersion:c.literal(1),name:c.string().min(1).max(100),summary:c.string().max(500)},PI=c.object({...O6,identity:x0.pick({name:!0,emoji:!0,title:!0,summary:!0,gender:!0}).strict(),guidance:c.string().max(Qd),examples:c.array(c.string().max(Qd)),tools:c.array(N6),assets:c.array(DI),routines:c.array(C6).optional(),services:c.array(z6).optional()}).strict(),_7=c.object({templateId:c.string(),publisherId:c.string(),publisher:c.object({userId:c.string(),fullName:c.string(),avatar:c.object({src:c.string()}).strict().optional()}).strict(),name:c.string(),description:c.string(),snapshot:PI,createdAt:c.string()}).strict(),$7=c.object({reviewed:c.literal(!0),orgId:c.string().min(1),sourceBotId:c.string().min(1),snapshot:PI}).strict(),S7=c.object({templateId:c.string().min(1),destination:c.discriminatedUnion("kind",[c.object({kind:c.literal("computer"),computerId:c.string().min(1)}).strict(),c.object({kind:c.literal("first-computer"),orgId:c.string().min(1)}).strict()]),includedToolIds:c.array(c.string().min(1))}).strict(),I7=c.object({"idempotency-key":c.uuid().describe("One UUID per Add intent; reuse it for retries.")}),T7=c.object({user:rD,computers:c.array(rp),bots:c.array(Tl)}),VS=Object.keys(rp.shape),RI=class extends ao{constructor(e){super("Computer",e),this.computerId=q(this.settings.computerId),this.ownerId=q(this.settings.ownerId),this.owner=q(this.settings.owner),this.orgId=q(this.settings.orgId),this.name=q(this.settings.name),this.model=q(this.settings.model),this.timezone=q(this.settings.timezone),this.billingTier=q(this.settings.billingTier),this.desiredStatus=q(this.settings.desiredStatus),this.status=q(this.settings.status),this.lastActiveAt=q(this.settings.lastActiveAt),this.createdAt=q(this.settings.createdAt),this.updatedAt=q(this.settings.updatedAt),this.lifecycle=q(this.settings.lifecycle),this.changedAt=q(this.settings.changedAt),this.detail=q(this.settings.detail),this.blocker=q(this.settings.blocker),this.operation=q(this.settings.operation),this.ownerMarkUrl=P(()=>{let t=this.owner.value;return t?.avatar?.src||zl(t?.fullName||this.ownerId.value)}),this.state=P(()=>GA({lifecycle:this.lifecycle.value??"unknown",changedAt:this.changedAt.value,detail:this.detail.value,blocker:this.blocker.value,operation:this.operation.value},this.name.value))}merge(e){if(e.computerId!==void 0&&e.computerId!==this.computerId.value)throw new Error("Cannot change a computer identity");for(let t of VS){if(!(t in e))continue;let n=this[t];n&&typeof n=="object"&&"value"in n&&(n.value=e[t])}}toData(){let e={};for(let t of VS){let n=this[t];n&&typeof n=="object"&&"value"in n&&(e[t]=n.value)}return e}toJSON(){return this.toData()}},FS=Object.keys(Tl.shape),S0=class extends ao{constructor(e,t){if(e.computerId!==t.computerId.value)throw new Error("Bot and computer identities do not match");super("Bot",e),this.botId=q(this.settings.botId),this.computerId=q(this.settings.computerId),this.name=q(this.settings.name),this.handle=q(this.settings.handle),this.emoji=q(this.settings.emoji),this.title=q(this.settings.title),this.summary=q(this.settings.summary),this.avatarId=q(this.settings.avatarId),this.coverId=q(this.settings.coverId),this.avatar=q(this.settings.avatar),this.cover=q(this.settings.cover),this.email=q(this.settings.email),this.website=q(this.settings.website),this.accounts=q(this.settings.accounts),this.gender=q(this.settings.gender),this.voiceKey=q(this.settings.voiceKey),this.publicChatEnabled=q(this.settings.publicChatEnabled),this.isPrimary=q(this.settings.isPrimary),this.collaborationEnabled=q(this.settings.collaborationEnabled),this.status=q(this.settings.status),this.onboardingStage=q(this.settings.onboardingStage),this.onboardedAt=q(this.settings.onboardedAt),this.routinePrimaryChannel=q(this.settings.routinePrimaryChannel),this.firstMessageAt=q(this.settings.firstMessageAt),this.firstValueAt=q(this.settings.firstValueAt),this.lastMessageAt=q(this.settings.lastMessageAt),this.createdAt=q(this.settings.createdAt),this.updatedAt=q(this.settings.updatedAt),this.displayName=P(()=>this.name.value||"Unnamed"),this.avatarUrl=P(()=>this.avatar.value?.src||zl(this.name.value)),this.hasCustomHandle=P(()=>!!this.handle.value&&!/\d{13,}$/.test(this.handle.value)),this.displayHandle=P(()=>this.hasCustomHandle.value?`@${this.handle.value}`:void 0),this.hasReceivedMessage=P(()=>!!this.lastMessageAt.value),this.computer=t}get owner(){return this.computer.owner}get ownerMarkUrl(){return this.computer.ownerMarkUrl}get ownerId(){return this.computer.ownerId}get orgId(){return this.computer.orgId}get model(){return this.computer.model}get timezone(){return this.computer.timezone}get billingTier(){return this.computer.billingTier}get desiredStatus(){return this.computer.desiredStatus}get lifecycle(){return this.computer.lifecycle}get changedAt(){return this.computer.changedAt}get detail(){return this.computer.detail}get blocker(){return this.computer.blocker}get operation(){return this.computer.operation}get state(){return this.computer.state}get lastActiveAt(){return this.computer.lastActiveAt}merge(e){if(e.botId!==void 0&&e.botId!==this.botId.value)throw new Error("Cannot change a bot identity");if(e.computerId!==void 0&&e.computerId!==this.computerId.value)throw new Error("Cannot move a bot between computers");for(let t of FS){if(!(t in e))continue;let n=this[t];n&&typeof n=="object"&&"value"in n&&(n.value=e[t])}}toData(){let e={};for(let t of FS){let n=this[t];n&&typeof n=="object"&&"value"in n&&(e[t]=n.value)}return e}toJSON(){return this.toData()}}});function Hn(e,t){let n=Number(globalThis.process?.env?.PORT)||Nl.port;return e||(t?`http://localhost:${n}`:Nl.urls.app)}function A6(e,t,n){let i=Hn(e.apiBase,e.isDev);return async(r,o)=>{let a=so.getAuthToken(),s=new Headers(o?.headers);s.has("Content-Type")||s.set("Content-Type","application/json"),a&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${a}`);let l=typeof r=="string"&&r.startsWith("/")?`${i}${r}`:r,u=await fetch(l,{...o,headers:s,credentials:"include"});if(n&&u.status===401&&(await u.clone().json().catch(()=>{}))?.code==="TOKEN_ERROR"&&n(),t){let d=u.json.bind(u);u.json=async()=>{let p=await d();return typeof p=="object"&&p&&"ok"in p&&("user"in p||"token"in p)&&t(p),p}}return u}}function Dl(e){"@babel/helpers - typeof";return Dl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dl(e)}function R6(e,t){if(Dl(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t||"default");if(Dl(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function U6(e){var t=R6(e,"string");return Dl(t)=="symbol"?t:t+""}function W(e,t,n){return(t=U6(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}async function Oa(e,t){e.loading.value=!0,e.error.value=null;try{return await t()}finally{e.loading.value=!1}}function MI(e){if(e.role==="assistant"||e.role==="system")return{id:e.messageId,text:e.content,sender:e.role==="system"?"system":"bot",timestamp:e.createdAt,conversationId:e.conversationId,sequence:e.sequence,systemKind:e.systemKind,...e.metadata?.routine?{routine:e.metadata.routine}:{},...e.metadata?.turnOutcome?{turnOutcome:e.metadata.turnOutcome}:{},...e.metadata?.attachments?.length?{attachments:e.metadata.attachments}:{},...e.metadata?.toolActivities?.length?{toolActivities:e.metadata.toolActivities}:{},...e.metadata?.issue?{issue:e.metadata.issue}:{}}}var UI,Xr,Al,jI,E0,D6,P6,T0,Aa,np,ip,op,j6,M6,L6,I0,V6,F6,B6,Z6,H6,ap,Pl,N0=Y(()=>{"use strict";Tn();Ol();bn();Xr=[],Al=0,jI=null,E0=4,D6=(UI=globalThis).nanostoresGlobal||(UI.nanostoresGlobal={epoch:0}),P6=()=>{let e,t;for(;Al<Xr.length;){t=Al,Al+=E0;try{Xr[t](Xr[t+1].value,Xr[t+2],Xr[t+3])}catch(n){e=n}}if(Xr.length=Al=0,e)throw e},T0=e=>{let t=[],n={eq:Object.is,get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(i){return n.lc=t.push(i),()=>{for(let o=Al;o<Xr.length;)Xr[o]===i?Xr.splice(o,E0):o+=E0;let r=t.indexOf(i);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(i,r){D6.epoch++;let o=!Xr.length&&!0;for(let a of t)jI?.has(a)||(jI?.add(a),Xr.push(a,n,i,r));o&&P6()},off(){},set(i){let r=n.value;n.eq(r,i)||(n.value=i,n.notify(r))},subscribe(i){let r=n.listen(i);return i(n.value),r},value:e};return n};Aa=globalThis,np=Aa.__PL_AUTH_USER__??(Aa.__PL_AUTH_USER__=T0(void 0)),ip=Aa.__PL_AUTH_TOKEN__??(Aa.__PL_AUTH_TOKEN__=T0(null)),op=Aa.__PL_AUTH_DEVICE_ID__??(Aa.__PL_AUTH_DEVICE_ID__=T0(null)),j6=class{constructor(){W(this,"logger",oo("SDKStorage"))}isLocalStorageFunctional(){return typeof window<"u"&&typeof localStorage?.getItem=="function"&&typeof localStorage?.setItem=="function"&&typeof localStorage?.removeItem=="function"}syncWithGlobalStores(e){let{activeUser:t,token:n,deviceId:i}=e,r=np.get(),o=ip.get(),a=op.get();r&&(t.value=r),o&&(n.value=o),a&&(i.value=a),ft(t,s=>np.set(s),{immediate:!0}),ft(n,s=>ip.set(s),{immediate:!0}),ft(i,s=>op.set(s),{immediate:!0}),np.subscribe(s=>{s!==t.value&&(t.value=s)}),ip.subscribe(s=>{s!==n.value&&(n.value=s)}),op.subscribe(s=>{s!==i.value&&(i.value=s)})}loadFromStorage(e){if(typeof window>"u")return;let t=so.getAuthToken();t&&(e.token.value=t);let n=so.getDeviceId();if(n&&(e.deviceId.value=n),this.isLocalStorageFunctional())try{let i=localStorage.getItem("pagelines-user");i&&(e.activeUser.value=JSON.parse(i))}catch(i){this.logger.error("Failed to load user from localStorage",{data:i})}}saveToStorage(e){if(!(typeof window>"u")&&(e.token.value?so.setAuthToken(e.token.value):so.removeAuthToken(),this.isLocalStorageFunctional()))try{e.activeUser.value?localStorage.setItem("pagelines-user",JSON.stringify(e.activeUser.value)):localStorage.removeItem("pagelines-user")}catch(t){this.logger.error("Failed to save user to localStorage",{data:t})}}clearStorage(){if(!(typeof window>"u")){if(so.removeAuthToken(),this.isLocalStorageFunctional())try{localStorage.removeItem("pagelines-user")}catch(e){this.logger.error("Failed to clear user from localStorage",{data:e})}np.set(void 0),ip.set(null),op.set(null)}}getItem(e){if(!this.isLocalStorageFunctional())return null;try{return localStorage.getItem(e)}catch(t){return this.logger.error("Failed to get item from localStorage",{key:e,error:t}),null}}setItem(e,t){if(this.isLocalStorageFunctional())try{localStorage.setItem(e,t)}catch(n){this.logger.error("Failed to set item in localStorage",{key:e,error:n})}}},M6=class{constructor(e){W(this,"ctx",void 0),W(this,"computers",ba(new Map)),W(this,"bots",ba(new Map)),this.ctx=e}get(e){return this.bots.get(e)}computer(e){return this.computers.get(e)}all(){return[...this.bots.values()]}hydrate(e){for(let t of e.computers){let n=this.computers.get(t.computerId);n?n.merge(t):this.computers.set(t.computerId,new RI(t))}return e.bots.map(t=>{let n=this.computers.get(t.computerId);if(!n)throw Error("Bot references an unknown computer");let i=this.bots.get(t.botId);if(i)return i.merge(t),i;let r=new S0(t,n);return this.bots.set(t.botId,r),r})}clear(){this.bots.clear(),this.computers.clear()}async webhook(e){let t=await this.ctx.apiFetch(`/api/bot-api/webhooks/routine-triggers/${encodeURIComponent(e.triggerId)}`,{method:"POST",headers:{"Content-Type":"application/json","X-PageLines-Key":e.key},body:JSON.stringify({type:e.type,data:e.data,...e.meta?{meta:e.meta}:{}})});if(!t.ok)throw Error(`Webhook delivery failed (${t.status})`);return t.json()}},L6=class{constructor(e,t){W(this,"ctx",void 0),W(this,"registry",void 0),this.ctx=e,this.registry=t}async create(e){let t=this.ctx.token.value,n=await(await this.ctx.apiFetch("/api/computers",{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":crypto.randomUUID()},body:JSON.stringify(e)})).json();if(t!==this.ctx.token.value)throw Error("Your account changed. Try again.");if(!n.ok)throw Error(n.error||"Failed to create computer");return this.registry.hydrate({computers:[n.data.computer],bots:[n.data.bot]})[0]}async getLiveStatus(e){let t=this.ctx.token.value;try{let n=await(await this.ctx.apiFetch(`/api/computers/state?ids=${encodeURIComponent(e)}`)).json(),i=n.ok?n.data[e]??Cl:Cl;return t===this.ctx.token.value?(this.registry.computer(e)?.merge(i),i):Cl}catch(n){return this.ctx.logger.warn("Computer status unavailable",{computerId:e,error:n}),Cl}}async waitUntilReady(e){let t=Date.now(),n;for(;Date.now()-t<(e.timeoutMs??sI.wake);){let i=await this.getLiveStatus(e.computerId);if(i.lifecycle!==n&&(e.onStatus?.(i.lifecycle),n=i.lifecycle),i.lifecycle==="running")return;if(i.lifecycle==="error")throw Error("Your computer hit a problem starting");await new Promise(r=>setTimeout(r,e.pollIntervalMs??3e3))}throw Error("Your computer is taking longer than expected. Please try again.")}},I0="Signed in, but your account could not be loaded. Try again.";V6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async authenticateWithCode(e,t){let n=await(await this.ctx.apiFetch("/api/auth/verify-code",{method:"POST",body:JSON.stringify({email:e,code:t})})).json();if(!n.ok)throw Error(n.error);let i=await this.getCurrentUser();if(!i)throw Error(I0);return i}async sendCode(e){return Oa(this.ctx,async()=>{try{let t=await(await this.ctx.apiFetch("/api/auth/check-email",{method:"POST",body:JSON.stringify({email:e})})).json();if(!t.ok)throw this.ctx.error.value=t.error,Error(t.error)}catch(t){this.ctx.logger.error("Send code error",{data:t});let n=t instanceof Error?t.message:"Failed to send verification code";throw this.ctx.error.value=n,t}})}async verifyCode(e,t){return Oa(this.ctx,async()=>{try{await this.authenticateWithCode(e,t)}catch(n){this.ctx.logger.error("Verify code error",{data:n});let i=n instanceof Error?n.message:"Failed to verify code";throw this.ctx.error.value=i,n}})}async logout(){return Oa(this.ctx,async()=>{try{await this.ctx.apiFetch("/api/auth/logout",{method:"POST"})}catch(e){this.ctx.logger.error("Logout error (user still logged out locally)",{data:e})}this.ctx.activeUser.value=void 0,this.ctx.token.value=null,this.ctx.storage.clearStorage(),this.ctx.clearRoster()})}async getCurrentUser(){let e=this.ctx.token.value;if(e)return Oa(this.ctx,async()=>{try{let t=await(await this.ctx.apiFetch("/api/users/me",{method:"GET"})).json();if(e!==this.ctx.token.value)return;if(!t.ok){this.ctx.error.value=t.error,t.error.includes("Authentication")&&(this.ctx.activeUser.value=void 0,this.ctx.token.value=null,this.ctx.storage.clearStorage(),this.ctx.clearRoster());return}return this.ctx.activeUser.value=t.data.user,this.ctx.hydrateRoster(t.data),t.data.user}catch(t){this.ctx.logger.error("Get current user error",{data:t}),this.ctx.error.value=t instanceof Error?t.message:"Failed to get user info";return}})}async requestAuthCode(e){return Oa(this.ctx,async()=>{try{let t=await(await this.ctx.apiFetch("/api/auth/check-email",{method:"POST",body:JSON.stringify({email:e.email})})).json();return t.ok?(this.ctx.logger.info("Auth code requested successfully",{email:e.email}),!0):(this.ctx.error.value=t.error,this.ctx.logger.error("Failed to request auth code",{email:e.email,error:t.error}),!1)}catch(t){return this.ctx.logger.error("Request auth code error",{email:e.email,error:t}),this.ctx.error.value=t instanceof Error?t.message:"Failed to request auth code",!1}})}async loginWithCode(e){return Oa(this.ctx,async()=>{try{return await this.authenticateWithCode(e.email,e.code),this.ctx.logger.info("Login successful",{email:e.email}),!0}catch(t){return this.ctx.logger.error("Login with code error",{email:e.email,error:t}),this.ctx.error.value=t instanceof Error?t.message:"Login failed",!1}})}loginWithGoogle(e){if(typeof window>"u"){this.ctx.logger.error("loginWithGoogle: Only available in browser");return}let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=window.location.origin,i=`${t}/auth/google-popup?origin=${encodeURIComponent(n)}`,r=window.screenX+(window.outerWidth-500)/2,o=window.screenY+(window.outerHeight-600)/2,a=window.open(i,"google-auth",`width=500,height=600,left=${r},top=${o},popup=yes`);if(!a){let u="Popup was blocked. Please allow popups for this site.";this.ctx.error.value=u,e?.onError?.(u);return}let s=async u=>{let d=new URL(t).origin;if(u.origin===d){if(u.data?.type==="auth-success"){window.removeEventListener("message",s);let{token:p}=u.data;this.ctx.processApiResponse({ok:!0,data:{},token:p});let f=await this.getCurrentUser();if(!f){this.ctx.error.value=I0,this.ctx.logger.error("Google login: token accepted but user hydration failed"),e?.onError?.(I0);return}this.ctx.logger.info("Google login successful"),e?.onSuccess?.(f)}else if(u.data?.type==="auth-error"){window.removeEventListener("message",s);let p=u.data.error||"Google authentication failed";this.ctx.error.value=p,this.ctx.logger.error("Google login failed",{error:p}),e?.onError?.(p)}}};window.addEventListener("message",s);let l=setInterval(()=>{a.closed&&(clearInterval(l),window.removeEventListener("message",s))},500)}},F6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async confirmCheckout(e){if(e?.sessionId){let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=await(await fetch(`${t}/api/billing/complete-checkout`,{method:"POST",headers:{"Content-Type":"application/json",...this.ctx.token.value&&{Authorization:`Bearer ${this.ctx.token.value}`}},body:JSON.stringify({sessionId:e.sessionId})})).json();if(!n.ok){let i=n.error||"Failed to complete checkout";throw this.ctx.error.value=i,Error(i)}}return this.getStatus()}async getStatus(){let e=this.resolveOrgId(),t=Hn(this.ctx.apiBase,this.ctx.isDev),n=await(await fetch(`${t}/api/billing/details/${e}`,{headers:{...this.ctx.token.value&&{Authorization:`Bearer ${this.ctx.token.value}`}}})).json();if(!n.ok||!n.data)return{plan:void 0,status:"none",hasActiveBilling:!1,maxBots:0};let i=["active","trial","canceling"].includes(n.data.status)||n.data.status==="past_due"&&n.data.paymentRecovery?.suspended!==!0;return{plan:n.data.plan,status:n.data.status,hasActiveBilling:i,maxBots:n.data.maxBots,...n.data.trialEnd&&{trialEnd:n.data.trialEnd},...n.data.trialDaysRemaining!==void 0&&{trialDaysRemaining:n.data.trialDaysRemaining},...n.data.paymentRecovery&&{paymentRecovery:n.data.paymentRecovery}}}resolveOrgId(){let e=this.ctx.activeUser.value?.orgs?.[0]?.orgId;if(!e)throw Error("No organization found. Please sign in first.");return e}};B6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async cancelConversationTurn(e){let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=this.ctx.token.value?{Authorization:`Bearer ${this.ctx.token.value}`}:{},i=await fetch(`${t}/api/conversations/${encodeURIComponent(e.conversationId)}/cancel`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(e.turnId?{turnId:e.turnId}:{})}),r=await i.json();if(!r.ok)throw Error(r.error||`Cancel failed: HTTP ${i.status}`);return r.data}async chatStreamPublic(e){let t=`${Hn(this.ctx.apiBase,this.ctx.isDev)}/api/bots/public/${encodeURIComponent(e.handle)}/chat/stream`,n="",i=!1,r=!1,o;try{let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e.message,anonymousId:e.anonymousId,...e.attachments?.length?{attachments:e.attachments.map(({type:s,src:l,filename:u,mimeType:d,mediaId:p})=>({type:s,url:l,name:u,mimeType:d,mediaId:p}))}:{},...e.context?{context:e.context}:{}})});if(!a.ok){let s=await a.json().catch(()=>({error:"Request failed"}));e.onError(Yr("api",s.error||`HTTP ${a.status}`,s.code));return}if(n=a.headers.get("X-Conversation-Id")||"",o=a.body?.getReader(),!o){e.onError(Yr("stream-open","No response stream"));return}for await(let s of _0(o))if(s.event==="working_state")e.onStatus?.(s.data.description);else if(s.event==="tool_activity")e.onToolActivity?.(s.data);else if(s.event==="working_end")e.onWorkingEnd?.();else if(s.event==="message_delta")e.onDelta(s.data.delta,s.data.role);else if(s.event==="error"){i=!0,e.onError(s.data);break}else if(s.event==="message"&&(s.data.message.role==="assistant"||s.data.message.role==="system")){r=!0;let l=MI(s.data.message);l&&e.onMessage?.(l)}else if(s.event==="stream_end")break;!i&&r?e.onDone(n):i||e.onError(Yr("no-reply","Stream ended before reply arrived"))}catch(a){e.onError(Yr("stream-read",a instanceof Error?a.message:"Stream failed","NETWORK_ERROR"))}finally{try{await o?.cancel()}catch{}}}async chatStreamAuthenticated(e){let t=Hn(this.ctx.apiBase,this.ctx.isDev),n=this.ctx.token.value?{Authorization:`Bearer ${this.ctx.token.value}`}:{},i=e.conversationId,r=e.latestSequence??null;if(!i)try{let l=await fetch(`${t}/api/conversations`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify({orgId:e.orgId,participants:[{type:"bot",id:e.botId}]})}),u=await l.json();if(!u.ok){e.onError(Yr("api",u.error||`Conversation failed: HTTP ${l.status}`,u.code));return}i=u.data.conversationId,r=u.data.latestSequence??null}catch(l){e.onError(Yr("api",l instanceof Error?l.message:"Conversation failed","NETWORK_ERROR"));return}let o=r?`${t}/api/conversations/${encodeURIComponent(i)}/stream?since=${encodeURIComponent(r)}`:`${t}/api/conversations/${encodeURIComponent(i)}/stream`,a=`nonce_${WS(16)}`,s=uI();await SI({streamUrl:o,sendUrl:`${t}/api/messages`,headers:n,sendBody:{conversationId:i,content:e.message,clientNonce:a,...s?{viewerTimezone:s}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{}},onStatus:e.onStatus,onDelta:e.onDelta,onToolActivity:e.onToolActivity,onWorkingEnd:e.onWorkingEnd,onMessage:l=>{let u=MI(l);u&&e.onMessage?.(u)},onDone:()=>e.onDone(i),onChatError:e.onError,onTransportError:e.onError})}},Z6=class{constructor(e){W(this,"ctx",void 0),this.ctx=e}async getPublicBot(e){this.ctx.loading.value=!0,this.ctx.error.value=null;try{let t=await(await this.ctx.apiFetch(`/api/pub/bot/get-by-handle?handle=${encodeURIComponent(e.handle)}`)).json();if(!t.ok){this.ctx.error.value=t.error,this.ctx.logger.error("Failed to fetch public bot",{handle:e.handle,error:t.error});return}return this.ctx.hydrateRoster({bots:[t.data.bot],computers:[t.data.computer]})[0]}catch(t){this.ctx.logger.error("Get public bot error",{handle:e.handle,error:t}),this.ctx.error.value=t instanceof Error?t.message:"Failed to fetch bot";return}finally{this.ctx.loading.value=!1}}generateAnonId(){let e="pagelinesAnonId",t=this.ctx.storage.getItem(e);return t||(t=ep({prefix:"anon"}),this.ctx.storage.setItem(e,t)),t}track(e){try{typeof window<"u"&&window.parent!==window&&window.parent.postMessage({type:"pagelines_track",event:e.event,botId:e.botId,properties:e.properties||{}},"*"),this.ctx.logger.info("SDK event tracked",{event:e.event,botId:e.botId})}catch(t){this.ctx.logger.error("Track event error",{error:t,args:e})}}},H6=class{constructor(){W(this,"key","__PAGELINES_SDK__")}get(){if(!(typeof window>"u"))return globalThis[this.key]}set(e){typeof window<"u"&&(globalThis[this.key]=e)}delete(){typeof window<"u"&&delete globalThis[this.key]}},ap=new H6,Pl=class LI extends ao{static getInstance(t={}){return ap.get()||new LI(t)}get isDev(){return this.settings.isDev??(typeof window<"u"?window.location.hostname==="localhost"||window.location.hostname.includes("127.0.0.1"):!1)}constructor(t={}){let n=ap.get();if(n)return console.debug("[PageLinesSDK] Returning existing singleton instance"),n;super("PageLinesSDK",t),W(this,"activeUser",q()),W(this,"token",q(null)),W(this,"deviceId",q(null)),W(this,"loading",q(!1)),W(this,"error",q(null)),W(this,"apiBase",this.settings.apiBase||void 0),W(this,"storage",new j6),W(this,"sessionId",ep({prefix:"ses"})),W(this,"currentBot",P(()=>{let r=this.activeUser.value;return(r?.lastBotId?this.bot.get(r.lastBotId):void 0)??this.bot.all().find(o=>o.isPrimary.value&&o.ownerId.value===r?.userId)})),W(this,"currentOrg",P(()=>{let r=this.currentBot.value?.computer.orgId.value??this.activeUser.value?.lastActiveOrgId??this.activeUser.value?.primaryOrgId;return this.activeUser.value?.orgs?.find(o=>o.orgId===r)})),W(this,"initialized",void 0),W(this,"resolveUser",void 0),W(this,"bot",void 0),W(this,"computer",void 0),W(this,"auth",void 0),W(this,"billing",void 0),W(this,"chat",void 0),W(this,"user",void 0),W(this,"stopAccountWatch",void 0),ap.set(this);let i={apiFetch:A6({isDev:this.isDev,apiBase:this.apiBase},this.processApiResponse.bind(this),()=>this.clearSession()),apiBase:this.apiBase,isDev:this.isDev,activeUser:this.activeUser,token:this.token,loading:this.loading,error:this.error,currentBot:this.currentBot,hydrateRoster:r=>this.bot.hydrate(r),clearRoster:()=>this.bot.clear(),storage:this.storage,sessionId:this.sessionId,logger:this.logger,processApiResponse:this.processApiResponse.bind(this)};this.bot=new M6(i),this.computer=new L6(i,this.bot),this.auth=new V6(i),this.billing=new F6(i),this.chat=new B6(i),this.user=new Z6(i),this.stopAccountWatch=ft(()=>this.activeUser.value?.userId,()=>this.bot.clear(),{flush:"sync"}),this.logger.info("PageLinesSDK initialized"),this.storage.loadFromStorage(this.authRefs()),this.storage.syncWithGlobalStores(this.authRefs()),this.initialized=new Promise(r=>{this.resolveUser=r}),this.token.value&&!this.activeUser.value?this.auth.getCurrentUser().then(r=>{this.resolveUser&&(this.resolveUser(r),this.resolveUser=void 0)}).catch(r=>{this.logger.error("Auto user fetch failed",{data:r}),this.resolveUser&&(this.resolveUser(void 0),this.resolveUser=void 0)}):this.activeUser.value?this.resolveUser?.(this.activeUser.value):this.resolveUser?.(void 0)}processApiResponse(t){if(!t.ok)return;let n=!1;t.user&&(this.activeUser.value=t.user,this.logger.info("User updated from API response",{data:t.user}),n=!0),t.token&&(this.token.value!==t.token&&(this.activeUser.value=void 0,this.bot.clear()),this.token.value=t.token,this.logger.info("Token updated from API response"),n=!0);let i=t.data?.deviceId;i&&(this.deviceId.value=i,n=!0),n&&this.persistAuth(),this.resolveUser&&(this.resolveUser(t.user),this.resolveUser=void 0)}authRefs(){return{activeUser:this.activeUser,token:this.token,deviceId:this.deviceId}}persistAuth(){this.storage.saveToStorage(this.authRefs())}clearSession(){this.bot.clear(),this.logger.info("Clearing session"),this.activeUser.value=void 0,this.token.value=null,this.deviceId.value=null,this.error.value=null,this.storage.clearStorage()}clear(){this.logger.info("Clearing SDK completely"),this.clearSession(),this.loading.value=!1,this.sessionId=ep({prefix:"ses"}),this.stopAccountWatch?.(),ap.delete()}}});function G6(e,t){return w(),_("div",W6,[...t[0]||(t[0]=[k("svg",{class:"ring-circular h-full w-full origin-center",viewBox:"25 25 50 50"},[k("circle",{class:"ring-path",cx:"50",cy:"50",r:"20",fill:"none",stroke:"currentColor","stroke-width":"5","stroke-miterlimit":"30"})],-1)])])}function J6(e){let t=Math.max(0,Math.floor(e.ms/1e3));return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function q6(e){return e.mimeType.includes("mp4")||e.mimeType.includes("m4a")?"m4a":e.mimeType.includes("ogg")?"ogg":e.mimeType.includes("wav")?"wav":"webm"}function Y6(){return typeof MediaRecorder>"u"?"":["audio/webm;codecs=opus","audio/mp4","audio/webm"].find(e=>MediaRecorder.isTypeSupported?.(e))||""}function e3(e){return e.turnOutcome==="failed"?"failed":e.turnOutcome==="stopped"?"stopped":e.sender==="system"?"failed":"completed"}function mp(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Ma(e){return mp(e.endedAt)??mp(e.startedAt)??0}function L0(e,t){return Ma(e)-Ma(t)}function Ll(e,t){let n=e.filter(r=>r.status==="completed"||r.status==="failed"&&!!r.note).filter(r=>!t.has(r.activityId)).slice().sort(L0),i=[];for(let r of n){let o=r.status==="completed"?"done":"failed",a=i[i.length-1];if(o==="done"&&a?.tone==="done"&&a.label===r.label&&Ma(r)-a.lastMs<=t3){a.count+=1,a.lastMs=Ma(r);continue}i.push({id:r.activityId,tone:o,label:r.label,note:r.note,count:1,lastMs:Ma(r)})}return i.map(r=>({id:r.id,tone:r.tone,label:r.count>1?`${r.label} \xB7 ${r.count}`:r.label,...r.note?{note:r.note}:{}}))}function pp(e){return e.length<=C0?{visibleRows:e,hiddenRows:[]}:{visibleRows:e.slice(e.length-C0),hiddenRows:e.slice(0,e.length-C0)}}function V0(e){let{activities:t,outcome:n,nowMs:i,canNotifyOnCompletion:r,lastVisibleProgressAtMs:o,includeFailureNote:a=!0}=e;if(n==="completed")return{outcome:n,visibleRows:[],hiddenRows:Ll(t,new Set),terminal:{id:"work-complete",tone:"completed",label:co.completed}};if(n==="failed"){let E=t.filter(X=>X.status==="failed").sort(L0).pop(),M=new Set;E&&M.add(E.activityId);let{visibleRows:z,hiddenRows:D}=pp(Ll(t,M));return{outcome:n,visibleRows:z,hiddenRows:D,terminal:{id:"work-failed",tone:"failed",label:co.failed,...a&&E?.note?{note:E.note}:{}}}}if(n==="stopped"){let{visibleRows:E,hiddenRows:M}=pp(Ll(t,new Set));return{outcome:n,visibleRows:E,hiddenRows:M,terminal:{id:"work-stopped",tone:"stopped",label:co.stopped}}}let{visibleRows:s,hiddenRows:l}=pp(Ll(t,new Set)),u=t.filter(E=>E.status==="started").sort(L0).pop(),d=t.reduce((E,M)=>Math.max(E,Ma(M)),o??-1/0),p=Number.isFinite(d)?d:i,f=t.reduce((E,M)=>{let z=mp(M.startedAt)??mp(M.endedAt);return z===void 0?E:Math.min(E,z)},1/0),m=p+h2,h=(Number.isFinite(f)?f:p)+r3,v=i>=m,x=u||v?{id:u?.activityId??"work-active",tone:"active",label:u?.label??co.finishing}:void 0,A=v&&i>=h?r?co.notifyHint:co.leaveHint:void 0,I=[m,h].filter(E=>E>i).sort((E,M)=>E-M)[0];return{outcome:n,visibleRows:s,hiddenRows:l,...x?{terminal:x}:{},...A?{hint:A}:{},...I===void 0?{}:{nextBoundaryAtMs:I}}}function n3(e){let{segments:t,activities:n,nowMs:i,canNotifyOnCompletion:r,lastVisibleProgressAtMs:o}=e,a=new Map(n.map(m=>[m.activityId,m])),s=m=>V0({activities:m,outcome:"running",nowMs:i,canNotifyOnCompletion:r,...o===void 0?{}:{lastVisibleProgressAtMs:o}}),l=m=>{let{visibleRows:h,hiddenRows:v}=pp(Ll(m,new Set));if(h.length!==0||v.length!==0)return{outcome:"running",visibleRows:h,hiddenRows:v}},u=[],d=new Set(t.flatMap(m=>m.kind==="work"?m.activityIds:[])),p=l(n.filter(m=>!d.has(m.activityId)));p&&u.push({kind:"work",id:"work-unsegmented",journal:p}),t.forEach((m,h)=>{if(m.kind==="text"){m.content&&u.push({kind:"text",id:`text-${h}`,content:m.content});return}let v=m.activityIds.map(A=>a.get(A)).filter(A=>A!==void 0);if(v.length===0)return;let x=l(v);x&&u.push({kind:"work",id:`work-${m.activityIds[0]??h}`,journal:x})});let f=s(n);return f.terminal||f.hint?u.push({kind:"work",id:"work-tail",journal:{outcome:"running",visibleRows:[],hiddenRows:[],...f.terminal?{terminal:f.terminal}:{},...f.hint?{hint:f.hint}:{},...f.nextBoundaryAtMs===void 0?{}:{nextBoundaryAtMs:f.nextBoundaryAtMs}}}):u.push({kind:"loading",id:"work-tail"}),u}function sp(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function i3(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof RTCPeerConnection<"u"}function VI(e){return e?typeof e=="string"?e:e.src||"":""}function g2(e){return VI(e.cover)||VI(e.avatar)||zl(e.name)}function Bl(e){let t=e.target;t.dataset.fallbackUsed||(t.dataset.fallbackUsed="true",t.src=zl())}function v2(e){let{template:t,bot:n}=e;return t.replace(/{name}/g,n.name||"Assistant").replace(/{title}/g,n.title||"").replace(/{handle}/g,n.handle||"")}function FI(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function S3(e){if(Array.isArray(e))return e}function I3(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var i,r,o,a,s=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(i=o.call(n)).done)&&(s.push(i.value),s.length!==t);l=!0);}catch(d){u=!0,r=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return s}}function E3(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
95
95
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function T3(e,t){return S3(e)||I3(e,t)||N3(e,t)||E3()}function N3(e,t){if(e){if(typeof e=="string")return FI(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?FI(e,t):void 0}}function Ct(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return B0(e,t,n)}}function j3(e){return function(){return Z0(e,[...arguments])}}function Ze(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Vl;if(BI&&BI(e,null),!ki(t))return e;let i=t.length;for(;i--;){let r=t[i];if(typeof r=="string"){let o=n(r);o!==r&&(C3(t)||(t[i]=o),r=o)}e[r]=!0}return e}function M3(e){for(let t=0;t<e.length;t++)Vt(e,t)||(e[t]=null);return e}function mr(e){let t=Ua(null);for(let i of b2(e)){var n=T3(i,2);let r=n[0],o=n[1];Vt(e,r)&&(t[r]=ki(o)?M3(o):o&&typeof o=="object"&&o.constructor===Object?mr(o):o)}return t}function L3(e){switch(typeof e){case"string":return e;case"number":return R3(e);case"boolean":return U3(e);case"bigint":return WI?WI(e):"0";case"symbol":return GI?GI(e):"Symbol()";case"undefined":return Ul(e);case"function":case"object":{if(e===null)return Ul(e);let t=e,n=kn(t,"toString");if(typeof n=="function"){let i=n(t);return typeof i=="string"?i:Ul(i)}return Ul(e)}default:return Ul(e)}}function kn(e,t){for(;e!==null;){let i=O3(e,t);if(i){if(i.get)return Ct(i.get);if(typeof i.value=="function")return Ct(i.value)}e=z3(e)}function n(){return null}return n}function V3(e){try{return Lt(e,""),!0}catch{return!1}}function w2(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:t5(),t=ce=>w2(ce);if(t.version="3.4.12",t.removed=[],!e||!e.document||e.document.nodeType!==Tr.document||!e.Element)return t.isSupported=!1,t;let n=e.document,i=n,r=i.currentScript;e.DocumentFragment;let o=e.HTMLTemplateElement,a=e.Node,s=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let u=e.DOMParser,d=e.trustedTypes,p=s.prototype,f=kn(p,"cloneNode"),m=kn(p,"remove"),h=kn(p,"nextSibling"),v=kn(p,"childNodes"),x=kn(p,"parentNode"),A=kn(p,"shadowRoot"),I=kn(p,"attributes"),E=a&&a.prototype?kn(a.prototype,"nodeType"):null,M=a&&a.prototype?kn(a.prototype,"nodeName"):null;if(typeof o=="function"){let ce=n.createElement("template");ce.content&&ce.content.ownerDocument&&(n=ce.content.ownerDocument)}let z,D="",X,le=!1,ie=0,Q=function(){if(ie>0)throw lo('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},ae=function(g){Q(),ie++;try{return z.createHTML(g)}finally{ie--}},ne=function(g){Q(),ie++;try{return z.createScriptURL(g)}finally{ie--}},ve=function(){return le||(X=r5(d,r),le=!0),X},Le=n,mt=Le.implementation,ht=Le.createNodeIterator,je=Le.createDocumentFragment,Me=Le.getElementsByTagName,Rt=i.importNode,Je=r2();t.isSupported=typeof b2=="function"&&typeof x=="function"&&mt&&mt.createHTMLDocument!==void 0;let Cr=Z3,wt=H3,xt=K3,Fr=W3,Tt=G3,Wn=J3,Nt=q3,Ft=X3,er=QI,Ye=null,tr=Ze({},[...JI,...A0,...D0,...P0,...qI]),Ve=null,zr=Ze({},[...YI,...R0,...XI,...lp]),b=Object.seal(Ua(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),S=null,L=null,J=Object.seal(Ua(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),$=!0,T=!0,y=!1,R=!0,O=!1,U=!0,se=!1,te=!1,pe=null,he=null,$e=!1,Te=!1,Ne=!1,qe=!1,Xe=!0,zt=!1,St="user-content-",rr=!0,be=!1,ct={},it=null,$n=Ze({},"annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp".split(".")),Sn=null,Jl=Ze({},["audio","video","img","source","image","track"]),Za=null,ql=Ze({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),vo="http://www.w3.org/1998/Math/MathML",bo="http://www.w3.org/2000/svg",Or="http://www.w3.org/1999/xhtml",Gn=Or,yo=!1,In=null,En=Ze({},[vo,bo,Or],O0),xi=Jt(["mi","mo","mn","ms","mtext"]),Ha=Ze({},xi),Yl=Jt(["annotation-xml"]),Ka=Ze({},Yl),Tp=Ze({},["title","style","font","a","script"]),_i=null,Xl=["application/xhtml+xml","text/html"],gt=null,F=null,Z=n.createElement("form"),G=function(g){return g instanceof RegExp||g instanceof Function},ot=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(F&&F===g)return;(!g||typeof g!="object")&&(g={}),g=mr(g),_i=Xl.indexOf(g.PARSER_MEDIA_TYPE)===-1?"text/html":g.PARSER_MEDIA_TYPE,gt=_i==="application/xhtml+xml"?O0:Vl,Ye=yi(g,"ALLOWED_TAGS",tr,{transform:gt}),Ve=yi(g,"ALLOWED_ATTR",zr,{transform:gt}),In=yi(g,"ALLOWED_NAMESPACES",En,{transform:O0}),Za=yi(g,"ADD_URI_SAFE_ATTR",ql,{transform:gt,base:ql}),Sn=yi(g,"ADD_DATA_URI_TAGS",Jl,{transform:gt,base:Jl}),it=yi(g,"FORBID_CONTENTS",$n,{transform:gt}),S=yi(g,"FORBID_TAGS",mr({}),{transform:gt}),L=yi(g,"FORBID_ATTR",mr({}),{transform:gt}),ct=Vt(g,"USE_PROFILES")?g.USE_PROFILES&&typeof g.USE_PROFILES=="object"?mr(g.USE_PROFILES):g.USE_PROFILES:!1,$=g.ALLOW_ARIA_ATTR!==!1,T=g.ALLOW_DATA_ATTR!==!1,y=g.ALLOW_UNKNOWN_PROTOCOLS||!1,R=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,O=g.SAFE_FOR_TEMPLATES||!1,U=g.SAFE_FOR_XML!==!1,se=g.WHOLE_DOCUMENT||!1,Te=g.RETURN_DOM||!1,Ne=g.RETURN_DOM_FRAGMENT||!1,qe=g.RETURN_TRUSTED_TYPE||!1,$e=g.FORCE_BODY||!1,Xe=g.SANITIZE_DOM!==!1,zt=g.SANITIZE_NAMED_PROPS||!1,rr=g.KEEP_CONTENT!==!1,be=g.IN_PLACE||!1,er=V3(g.ALLOWED_URI_REGEXP)?g.ALLOWED_URI_REGEXP:QI,Gn=typeof g.NAMESPACE=="string"?g.NAMESPACE:Or,Ha=Vt(g,"MATHML_TEXT_INTEGRATION_POINTS")&&g.MATHML_TEXT_INTEGRATION_POINTS&&typeof g.MATHML_TEXT_INTEGRATION_POINTS=="object"?mr(g.MATHML_TEXT_INTEGRATION_POINTS):Ze({},xi),Ka=Vt(g,"HTML_INTEGRATION_POINTS")&&g.HTML_INTEGRATION_POINTS&&typeof g.HTML_INTEGRATION_POINTS=="object"?mr(g.HTML_INTEGRATION_POINTS):Ze({},Yl);let j=Vt(g,"CUSTOM_ELEMENT_HANDLING")&&g.CUSTOM_ELEMENT_HANDLING&&typeof g.CUSTOM_ELEMENT_HANDLING=="object"?mr(g.CUSTOM_ELEMENT_HANDLING):Ua(null);if(b=Ua(null),Vt(j,"tagNameCheck")&&G(j.tagNameCheck)&&(b.tagNameCheck=j.tagNameCheck),Vt(j,"attributeNameCheck")&&G(j.attributeNameCheck)&&(b.attributeNameCheck=j.attributeNameCheck),Vt(j,"allowCustomizedBuiltInElements")&&typeof j.allowCustomizedBuiltInElements=="boolean"&&(b.allowCustomizedBuiltInElements=j.allowCustomizedBuiltInElements),qt(b),O&&(T=!1),Ne&&(Te=!0),ct&&(Ye=Ze({},qI),Ve=Ua(null),ct.html===!0&&(Ze(Ye,JI),Ze(Ve,YI)),ct.svg===!0&&(Ze(Ye,A0),Ze(Ve,R0),Ze(Ve,lp)),ct.svgFilters===!0&&(Ze(Ye,D0),Ze(Ve,R0),Ze(Ve,lp)),ct.mathMl===!0&&(Ze(Ye,P0),Ze(Ve,XI),Ze(Ve,lp))),J.tagCheck=null,J.attributeCheck=null,Vt(g,"ADD_TAGS")&&(typeof g.ADD_TAGS=="function"?J.tagCheck=g.ADD_TAGS:ki(g.ADD_TAGS)&&(Ye===tr&&(Ye=mr(Ye)),Ze(Ye,g.ADD_TAGS,gt))),Vt(g,"ADD_ATTR")&&(typeof g.ADD_ATTR=="function"?J.attributeCheck=g.ADD_ATTR:ki(g.ADD_ATTR)&&(Ve===zr&&(Ve=mr(Ve)),Ze(Ve,g.ADD_ATTR,gt))),Vt(g,"ADD_URI_SAFE_ATTR")&&ki(g.ADD_URI_SAFE_ATTR)&&Ze(Za,g.ADD_URI_SAFE_ATTR,gt),Vt(g,"FORBID_CONTENTS")&&ki(g.FORBID_CONTENTS)&&(it===$n&&(it=mr(it)),Ze(it,g.FORBID_CONTENTS,gt)),Vt(g,"ADD_FORBID_CONTENTS")&&ki(g.ADD_FORBID_CONTENTS)&&(it===$n&&(it=mr(it)),Ze(it,g.ADD_FORBID_CONTENTS,gt)),rr&&(Ye["#text"]=!0),se&&Ze(Ye,["html","head","body"]),Ye.table&&(Ze(Ye,["tbody"]),delete S.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw lo('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw lo('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let re=z;z=g.TRUSTED_TYPES_POLICY;try{D=ae("")}catch(me){throw z=re,me}}else g.TRUSTED_TYPES_POLICY===null?(z=void 0,D=""):(z===void 0&&(z=ve()),z&&typeof D=="string"&&(D=ae("")));Jt&&Jt(g),F=g},ke=Ze({},[...A0,...D0,...F3]),vt=Ze({},[...P0,...B3]),Jn=function(g,j,re){return j.namespaceURI===Or?g==="svg":j.namespaceURI===vo?g==="svg"&&(re==="annotation-xml"||Ha[re]):!!ke[g]},H2=function(g,j,re){return j.namespaceURI===Or?g==="math":j.namespaceURI===bo?g==="math"&&Ka[re]:!!vt[g]},K2=function(g,j,re){return j.namespaceURI===bo&&!Ka[re]||j.namespaceURI===vo&&!Ha[re]?!1:!vt[g]&&(Tp[g]||!ke[g])},W2=function(g){let j=x(g);(!j||!j.tagName)&&(j={namespaceURI:Gn,tagName:"template"});let re=Vl(g.tagName),me=Vl(j.tagName);return In[g.namespaceURI]?g.namespaceURI===bo?Jn(re,j,me):g.namespaceURI===vo?H2(re,j,me):g.namespaceURI===Or?K2(re,j,me):!!(_i==="application/xhtml+xml"&&In[g.namespaceURI]):!1},$i=function(g){Pa(t.removed,{element:g});try{x(g).removeChild(g)}catch{if(m(g),!x(g))throw lo("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ql=function(g){Np(g);let j=v(g);if(j){let me=[];Da(j,De=>{Pa(me,De)}),Da(me,De=>{try{m(De)}catch{}})}let re=I(g);if(re)for(let me=re.length-1;me>=0;--me){let De=re[me],Be=De&&De.name;if(typeof Be=="string")try{g.removeAttribute(Be)}catch{}}},Si=function(g,j){try{Pa(t.removed,{attribute:j.getAttributeNode(g),from:j})}catch{Pa(t.removed,{attribute:null,from:j})}if(j.removeAttribute(g),g==="is")if(Te||Ne)try{$i(j)}catch{}else try{j.setAttribute(g,"")}catch{}},G2=function(g){let j=I(g);if(j)for(let re=j.length-1;re>=0;--re){let me=j[re],De=me&&me.name;if(!(typeof De!="string"||Ve[gt(De)]))try{g.removeAttribute(De)}catch{}}},Np=function(g){let j=[g];for(;j.length>0;){let re=j.pop();(E?E(re):re.nodeType)===Tr.element&&G2(re);let me=v(re);if(me)for(let De=me.length-1;De>=0;--De)j.push(me[De])}},J2=function(g){if(!U)return;let j=[g];for(;j.length>0;){let re=j.pop(),me=E?E(re):re.nodeType;if(me===Tr.processingInstruction||me===Tr.comment&&Lt(t2,re.data)){try{m(re)}catch{}continue}if(me===Tr.element){let Be=re,ut=gt(M?M(re):re.nodeName);try{Be.hasAttribute&&Be.hasAttribute("patchsrc")&&Be.removeAttribute("patchsrc"),Be.hasAttribute&&Be.hasAttribute("for")&&ut!=="label"&&ut!=="output"&&Be.removeAttribute("for")}catch{}}let De=v(re);if(De)for(let Be=De.length-1;Be>=0;--Be)j.push(De[Be])}},iy=function(g){let j=null,re=null;if($e)g="<remove></remove>"+g;else{let Be=HI(g,/^[\r\n\t ]+/);re=Be&&Be[0]}_i==="application/xhtml+xml"&&Gn===Or&&(g='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+g+"</body></html>");let me=z?ae(g):g;if(Gn===Or)try{j=new u().parseFromString(me,_i)}catch{}if(!j||!j.documentElement){j=mt.createDocument(Gn,"template",null);try{j.documentElement.innerHTML=yo?D:me}catch{}}let De=j.body||j.documentElement;return g&&re&&De.insertBefore(n.createTextNode(re),De.childNodes[0]||null),Gn===Or?Me.call(j,se?"html":"body")[0]:se?j.documentElement:De},oy=function(g){return ht.call(g.ownerDocument||g,g,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ec=function(g){return g=Rl(g,Cr," "),g=Rl(g,wt," "),g=Rl(g,xt," "),g},Cp=function(g){g.normalize();let j=ht.call(g.ownerDocument||g,g,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),re=j.nextNode();for(;re;)re.data=ec(re.data),re=j.nextNode();let me=g.querySelectorAll?.call(g,"template");me&&Da(me,De=>{wo(De.content)&&Cp(De.content)})},tc=function(g){let j=M?M(g):null;return typeof j!="string"||gt(j)!=="form"?!1:typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||g.attributes!==I(g)||typeof g.removeAttribute!="function"||typeof g.setAttribute!="function"||typeof g.namespaceURI!="string"||typeof g.insertBefore!="function"||typeof g.hasChildNodes!="function"||g.nodeType!==E(g)||g.childNodes!==v(g)},wo=function(g){if(!E||typeof g!="object"||!g)return!1;try{return E(g)===Tr.documentFragment}catch{return!1}},Wa=function(g){if(!E||typeof g!="object"||!g)return!1;try{return typeof E(g)=="number"}catch{return!1}};function tn(ce,g,j){ce.length!==0&&Da(ce,re=>{re.call(t,g,j,F)})}let q2=function(g,j){return!!(U&&g.hasChildNodes()&&!Wa(g.firstElementChild)&&Lt(e2,g.textContent)&&Lt(e2,g.innerHTML)||U&&g.namespaceURI===Or&&j==="style"&&Wa(g.firstElementChild)||g.nodeType===Tr.processingInstruction||U&&g.nodeType===Tr.comment&&Lt(t2,g.data))},Y2=function(g,j){if(!S[j]&&ly(j)&&(b.tagNameCheck instanceof RegExp&&Lt(b.tagNameCheck,j)||b.tagNameCheck instanceof Function&&b.tagNameCheck(j)))return!1;if(rr&&!it[j]){let re=x(g),me=v(g);if(me&&re){let De=me.length;for(let Be=De-1;Be>=0;--Be){let ut=be?me[Be]:f(me[Be],!0);re.insertBefore(ut,h(g))}}}return $i(g),!0},ay=function(g,j){if(tn(Je.beforeSanitizeElements,g,null),g!==j&&x(g)===null)return!0;if(tc(g))return $i(g),!0;let re=gt(M?M(g):g.nodeName);if(tn(Je.uponSanitizeElement,g,{tagName:re,allowedTags:Ye}),g!==j&&x(g)===null)return!0;if(q2(g,re))return $i(g),!0;if(S[re]||!(J.tagCheck instanceof Function&&J.tagCheck(re))&&!Ye[re]){let me=Y2(g,re);return me===!1&&tn(Je.afterSanitizeElements,g,null),me}if((E?E(g):g.nodeType)===Tr.element&&!W2(g)||(re==="noscript"||re==="noembed"||re==="noframes")&&Lt(Q3,g.innerHTML))return $i(g),!0;if(O&&g.nodeType===Tr.text){let me=ec(g.textContent);g.textContent!==me&&(Pa(t.removed,{element:g.cloneNode()}),g.textContent=me)}return tn(Je.afterSanitizeElements,g,null),!1},sy=function(g,j,re){if(L[j]||U&&j==="patchsrc"||U&&j==="for"&&g!=="label"&&g!=="output"||Xe&&(j==="id"||j==="name")&&(re in n||re in Z))return!1;let me=Ve[j]||J.attributeCheck instanceof Function&&J.attributeCheck(j,g);if(!(T&&Lt(Fr,j))&&!($&&Lt(Tt,j))){if(me){if(!Za[j]&&!Lt(er,Rl(re,Nt,""))&&(j!=="src"&&j!=="xlink:href"&&j!=="href"||g==="script"||KI(re,"data:")!==0||!Sn[g])&&(!y||Lt(Wn,Rl(re,Nt,"")))&&re)return!1}else if(!(ly(g)&&(b.tagNameCheck instanceof RegExp&&Lt(b.tagNameCheck,g)||b.tagNameCheck instanceof Function&&b.tagNameCheck(g))&&(b.attributeNameCheck instanceof RegExp&&Lt(b.attributeNameCheck,j)||b.attributeNameCheck instanceof Function&&b.attributeNameCheck(j,g))||j==="is"&&b.allowCustomizedBuiltInElements&&(b.tagNameCheck instanceof RegExp&&Lt(b.tagNameCheck,re)||b.tagNameCheck instanceof Function&&b.tagNameCheck(re))))return!1}return!0},X2=Ze({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ly=function(g){return!X2[Vl(g)]&&Lt(Ft,g)},Q2=function(g,j,re,me){if(z&&typeof d=="object"&&typeof d.getAttributeType=="function"&&!re)switch(d.getAttributeType(g,j)){case"TrustedHTML":return ae(me);case"TrustedScriptURL":return ne(me)}return me},eE=function(g,j,re,me){try{re?g.setAttributeNS(re,j,me):g.setAttribute(j,me),tc(g)?$i(g):ZI(t.removed)}catch{Si(j,g)}},cy=function(g){tn(Je.beforeSanitizeAttributes,g,null);let j=g.attributes;if(!j||tc(g))return;let re={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ve,forceKeepAttr:void 0},me=j.length,De=gt(g.nodeName);for(;me--;){let Be=j[me],ut=Be.name,Ii=Be.namespaceURI,qn=Be.value,hr=gt(ut),Br=qn,nr=ut==="value"?Br:P3(Br);if(re.attrName=hr,re.attrValue=nr,re.keepAttr=!0,re.forceKeepAttr=void 0,tn(Je.uponSanitizeAttribute,g,re),nr=re.attrValue,zt&&(hr==="id"||hr==="name")&&KI(nr,St)!==0&&(Si(ut,g),nr=St+nr),U&&Lt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,nr)){Si(ut,g);continue}if(hr==="attributename"&&HI(nr,"href")){Si(ut,g);continue}if(!re.forceKeepAttr){if(!re.keepAttr){Si(ut,g);continue}if(!R&&Lt(e5,nr)){Si(ut,g);continue}if(O&&(nr=ec(nr)),!sy(De,hr,nr)){Si(ut,g);continue}nr=Q2(De,hr,Ii,nr),nr!==Br&&eE(g,ut,Ii,nr)}}tn(Je.afterSanitizeAttributes,g,null)},rc=function(g){let j=null,re=oy(g);for(tn(Je.beforeSanitizeShadowDOM,g,null);j=re.nextNode();)if(tn(Je.uponSanitizeShadowNode,j,null),ay(j,g),cy(j),wo(j.content)&&rc(j.content),(E?E(j):j.nodeType)===Tr.element){let me=A(j);wo(me)&&(zp(me),rc(me))}tn(Je.afterSanitizeShadowDOM,g,null)},zp=function(g){let j=[{node:g,shadow:null}];for(;j.length>0;){let re=j.pop();if(re.shadow){rc(re.shadow);continue}let me=re.node,De=(E?E(me):me.nodeType)===Tr.element,Be=v(me);if(Be)for(let ut=Be.length-1;ut>=0;--ut)j.push({node:Be[ut],shadow:null});if(De){let ut=M?M(me):null;if(typeof ut=="string"&&gt(ut)==="template"){let Ii=me.content;wo(Ii)&&j.push({node:Ii,shadow:null})}}if(De){let ut=A(me);wo(ut)&&j.push({node:null,shadow:ut},{node:ut,shadow:null})}}};return t.sanitize=function(ce){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},j=null,re=null,me=null,De=null;if(yo=!ce,yo&&(ce="<!-->"),typeof ce!="string"&&!Wa(ce)&&(ce=L3(ce),typeof ce!="string"))throw lo("dirty is not a string, aborting");if(!t.isSupported)return ce;te?(Ye=pe,Ve=he):ot(g),(Je.uponSanitizeElement.length>0||Je.uponSanitizeAttribute.length>0)&&(Ye=mr(Ye)),Je.uponSanitizeAttribute.length>0&&(Ve=mr(Ve)),t.removed=[];let Be=be&&typeof ce!="string"&&Wa(ce);if(Be){J2(ce);let hr=M?M(ce):ce.nodeName;if(typeof hr=="string"){let Br=gt(hr);if(!Ye[Br]||S[Br])throw Ql(ce),lo("root node is forbidden and cannot be sanitized in-place")}if(tc(ce))throw Ql(ce),lo("root node is clobbered and cannot be sanitized in-place");try{zp(ce)}catch(Br){throw Ql(ce),Br}}else if(Wa(ce))j=iy("<!---->"),re=j.ownerDocument.importNode(ce,!0),re.nodeType===Tr.element&&re.nodeName==="BODY"||re.nodeName==="HTML"?j=re:j.appendChild(re),zp(re);else{if(!Te&&!O&&!se&&ce.indexOf("<")===-1)return z&&qe?ae(ce):ce;if(j=iy(ce),!j)return Te?null:qe?D:""}j&&$e&&$i(j.firstChild);let ut=Be?ce:j,Ii=oy(ut);try{for(;me=Ii.nextNode();)ay(me,ut),cy(me),wo(me.content)&&rc(me.content)}catch(hr){throw Be&&(Ql(ce),Da(t.removed,Br=>{Br.element&&Np(Br.element)})),hr}if(Be)return Da(t.removed,hr=>{hr.element&&Np(hr.element)}),O&&Cp(ce),ce;if(Te){if(O&&Cp(j),Ne)for(De=je.call(j.ownerDocument);j.firstChild;)De.appendChild(j.firstChild);else De=j;return(Ve.shadowroot||Ve.shadowrootmode)&&(De=Rt.call(i,De,!0)),De}let qn=se?j.outerHTML:j.innerHTML;return se&&Ye["!doctype"]&&j.ownerDocument&&j.ownerDocument.doctype&&j.ownerDocument.doctype.name&&Lt(Y3,j.ownerDocument.doctype.name)&&(qn="<!DOCTYPE "+j.ownerDocument.doctype.name+`>
96
96
  `+qn),O&&(qn=ec(qn)),z&&qe?ae(qn):qn},t.setConfig=function(){let ce=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ot(ce),te=!0,pe=Ye,he=Ve},t.clearConfig=function(){F=null,te=!1,pe=null,he=null,z=X,D=""},t.isValidAttribute=function(ce,g,j){F||ot({});let re=gt(ce),me=gt(g);return sy(re,me,j)},t.addHook=function(ce,g){typeof g=="function"&&Vt(Je,ce)&&Pa(Je[ce],g)},t.removeHook=function(ce,g){if(Vt(Je,ce)){if(g!==void 0){let j=A3(Je[ce],g);return j===-1?void 0:D3(Je[ce],j,1)[0]}return ZI(Je[ce])}},t.removeHooks=function(ce){Vt(Je,ce)&&(Je[ce]=[])},t.removeAllHooks=function(){Je=r2()},t}function G0(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function x2(e){fo=e}function Ra(e){let t=[];return n=>{let i=Math.max(0,Math.min(3,n-1)),r=t[i];return r||(r=e(i),t[i]=r),r}}function Ae(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(r,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(Qt.caret,"$1"),n=n.replace(r,a),i},getRegex:()=>new RegExp(n,t)};return i}function Nr(e,t){if(t){if(Qt.escapeTest.test(e))return e.replace(Qt.escapeReplace,a2)}else if(Qt.escapeTestNoEncode.test(e))return e.replace(Qt.escapeReplaceNoEncode,a2);return e}function s2(e){try{e=encodeURI(e).replace(Qt.percentDecode,"%")}catch{return null}return e}function l2(e,t){let n=e.replace(Qt.findPipe,(r,o,a)=>{let s=!1,l=o;for(;--l>=0&&a[l]==="\\";)s=!s;return s?"|":" |"}).split(Qt.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(Qt.slashPipe,"|");return n}function wi(e,t,n){let i=e.length;if(i===0)return"";let r=0;for(;r<i;){let o=e.charAt(i-r-1);if(o===t&&!n)r++;else if(o!==t&&n)r++;else break}return e.slice(0,i-r)}function c2(e){let t=e.split(`
97
97
  `),n=t.length-1;for(;n>=0&&Qt.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pagelines/widget",
3
- "version": "1.0.907",
3
+ "version": "1.0.908",
4
4
  "description": "Embeddable PageLines agent widget for any website",
5
5
  "type": "module",
6
6
  "main": "./dist/widget.js",
@@ -45,7 +45,7 @@
45
45
  "vue-tsc": "^3.3.11"
46
46
  },
47
47
  "dependencies": {
48
- "@pagelines/sdk": "1.0.907"
48
+ "@pagelines/sdk": "1.0.908"
49
49
  },
50
50
  "scripts": {
51
51
  "dev": "vite --config vite.config.widget.ts",