@runappsai/sdk 0.6.5 → 0.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/audio.d.ts +4 -1
- package/dist/audio.d.ts.map +1 -1
- package/dist/audio.js.map +1 -1
- package/dist/chat.d.ts +16 -5
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js.map +1 -1
- package/dist/image.d.ts +6 -2
- package/dist/image.d.ts.map +1 -1
- package/dist/image.js +1 -1
- package/dist/image.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/sdk.umd.js +2 -2
- package/dist/sdk.umd.js.map +1 -1
- package/dist/video.d.ts +4 -1
- package/dist/video.d.ts.map +1 -1
- package/dist/video.js.map +1 -1
- package/package.json +1 -1
- package/src/audio.ts +4 -1
- package/src/chat.ts +17 -1
- package/src/image.ts +7 -3
- package/src/index.ts +1 -0
- package/src/video.ts +4 -1
package/dist/sdk.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* @runappsai/sdk 0.6.
|
|
1
|
+
/* @runappsai/sdk 0.6.6 */
|
|
2
2
|
"use strict";var RunApps=(()=>{var ie=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Ht=Object.getOwnPropertyNames;var Jt=Object.prototype.hasOwnProperty;var zt=(n,e,t)=>e in n?ie(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Wt=(n,e)=>{for(var t in e)ie(n,t,{get:e[t],enumerable:!0})},Yt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ht(e))!Jt.call(n,s)&&s!==t&&ie(n,s,{get:()=>e[s],enumerable:!(r=Gt(e,s))||r.enumerable});return n};var Xt=n=>Yt(ie({},"__esModule",{value:!0}),n);var u=(n,e,t)=>zt(n,typeof e!="symbol"?e+"":e,t);var Vn={};Wt(Vn,{APIError:()=>C,ActivityTracker:()=>O,BrowserAuth:()=>U,Client:()=>L,FilesRemote:()=>P,RunApps:()=>L,RunJobs:()=>L,SDKEvents:()=>R,ServerTools:()=>Xe,SyncEngine:()=>I,acceptsField:()=>jt,acceptsModality:()=>ct,allowedValuesFor:()=>Nt,assistantMessage:()=>et,audioPart:()=>it,decodeMediaUrl:()=>z,defaultVoice:()=>pt,encodeImageUrl:()=>ht,getOptionsSchema:()=>te,hasCapabilityTag:()=>at,imagePart:()=>st,installIndexedDBHook:()=>Z,newRequestId:()=>J,requiresField:()=>Ut,supportsInstructText:()=>dt,supportsVoiceClone:()=>ut,systemMessage:()=>Ze,textPart:()=>rt,toolResultMessage:()=>tt,userMessage:()=>Qe,userMessageParts:()=>nt,validateRequest:()=>Kt,videoPart:()=>ot});var C=class extends Error{constructor(t,r,s){super(`runapps: ${t} ${r}: ${s}`);u(this,"statusCode");u(this,"type");this.name="APIError",this.statusCode=t,this.type=r}};var ae=class{constructor(e){u(this,"baseURL");u(this,"apiKey");u(this,"apiKeyResolver");u(this,"onUnauthorized");u(this,"fetchImpl");if(!e.apiKey&&!e.apiKeyResolver)throw new Error("RunApps: pass either `apiKey` or `apiKeyResolver` when constructing the client");this.baseURL=e.baseURL.replace(/\/+$/,""),this.apiKey=e.apiKey,this.apiKeyResolver=e.apiKeyResolver,this.onUnauthorized=e.onUnauthorized,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis)}async resolveToken(){return this.apiKeyResolver?await this.apiKeyResolver():this.apiKey??""}async fetchWithAuthRetry(e,t){let r=this.baseURL+e,s=await this.fetchImpl(r,await this.buildInit(t));if(s.status!==401||!this.onUnauthorized)return s;try{await this.onUnauthorized()}catch{return s}return s=await this.fetchImpl(r,await this.buildInit(t)),s}async buildInit(e){let t=await e();return t.cache?t:{...t,cache:"no-store"}}async postJSON(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.jsonHeaders(),body:JSON.stringify(t),signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async getJSON(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!r.ok)throw await this.parseError(r);return await r.json()}async getPublicJSON(e,t){let r=await this.fetchImpl(this.baseURL+e,{method:"GET",cache:"no-store",...t?.signal?{signal:t.signal}:{}});if(!r.ok)throw await this.parseError(r);return await r.json()}async getRaw(e,t){let r=await this.fetchWithAuthRetry(e,async()=>{let c=await this.authHeaders();return t?.ifNoneMatch&&(c["If-None-Match"]=`"${t.ifNoneMatch.replace(/"/g,"")}"`),{method:"GET",headers:c,signal:t?.signal}}),s=Qt(r.headers.get("date"));if(r.status===304){let c=(r.headers.get("etag")??"").replace(/"/g,"")||t?.ifNoneMatch;return{data:new Uint8Array(0),contentType:"",etag:c,notModified:!0,serverTime:s}}if(!r.ok)throw await this.parseError(r);let o=new Uint8Array(await r.arrayBuffer()),i=r.headers.get("content-type")??"",a=(r.headers.get("etag")??"").replace(/"/g,"")||void 0;return{data:o,contentType:i,etag:a,serverTime:s}}async postMultipart(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.authHeaders(),body:t,signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async postJSONStream(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:{...await this.jsonHeaders(),"Accept-Encoding":"identity"},body:JSON.stringify(t),signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return s}async putBytes(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>{let o={...await this.authHeaders(),"Content-Type":r?.contentType??"application/octet-stream"};return r?.headers&&Object.assign(o,r.headers),{method:"PUT",headers:o,body:t,signal:r?.signal}});if(!s.ok)throw await this.parseError(s);if(r?.parse!=="none")return await s.json()}async deletePath(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"DELETE",headers:await this.authHeaders(),signal:t?.signal}));if(!r.ok)throw await this.parseError(r);if(t?.parse!=="none")return await r.json()}async head(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"HEAD",headers:await this.authHeaders(),signal:t?.signal}));return{status:r.status,headers:r.headers}}async jsonHeaders(){return{"Content-Type":"application/json",Authorization:`Bearer ${await this.resolveToken()}`}}async authHeaders(){return{Authorization:`Bearer ${await this.resolveToken()}`}}async parseError(e){let t=await e.text(),r="error",s=t||e.statusText;try{let o=JSON.parse(t);o.type&&(r=o.type),o.message&&(s=o.message)}catch{}return new C(e.status,r,s)}};function Qt(n){if(!n)return;let e=Date.parse(n);return Number.isNaN(e)?void 0:e}var R=class{constructor(){u(this,"handlers",new Map)}on(e,t){let r=this.handlers.get(e);r||(r=new Set,this.handlers.set(e,r));let s=t;return r.add(s),()=>{this.handlers.get(e)?.delete(s)}}emit(e,t){let r=this.handlers.get(e);if(!(!r||r.size===0))for(let s of r)try{s(t)}catch(o){console.error("[runapps sdk] event listener for",e,"threw:",o)}}clear(){this.handlers.clear()}};function J(){return"req_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}async function y(n,e,t,r){let s=J(),o=Date.now();n.emit("request:start",{id:s,model:e.model,capability:e.capability,startedAt:o,streaming:!1});try{let i=await t(),a=r?r(i):{};return n.emit("request:end",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,totalTokens:a.totalTokens??0,...a.costUSD!==void 0&&{costUSD:a.costUSD},...a.finishReason!==void 0&&{finishReason:a.finishReason}}),i}catch(i){let a=i;throw n.emit("request:error",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,error:a,...typeof a.statusCode=="number"&&{statusCode:a.statusCode}}),i}}function Zt(n){return n?Math.max(1,Math.round(n.length/4)):0}async function*Ye(n,e,t,r){let s=J(),o=Date.now();n.emit("request:start",{id:s,model:e.model,capability:e.capability,startedAt:o,streaming:!0});let i=0,a,c,l;try{for await(let d of t()){let p=r(d);if(p.deltaText){let h=Zt(p.deltaText);i+=h,n.emit("request:streamDelta",{id:s,deltaTokens:h,totalTokens:i})}p.completionTokens!==void 0&&(a=p.completionTokens),p.costUSD!==void 0&&(c=p.costUSD),p.finishReason!==void 0&&(l=p.finishReason),yield d}n.emit("request:end",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,totalTokens:a??i,...c!==void 0&&{costUSD:c},...l!==void 0&&{finishReason:l}})}catch(d){let p=d;throw n.emit("request:error",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,error:p,...typeof p.statusCode=="number"&&{statusCode:p.statusCode}}),d}}var Xe={WebSearch:"web_search",WebFetch:"web_fetch",TwitterSearch:"twitter_search"},Qe=n=>({role:"user",content:n}),Ze=n=>({role:"system",content:n}),et=n=>({role:"assistant",content:n}),tt=(n,e)=>({role:"tool",tool_call_id:n,content:e}),nt=(...n)=>({role:"user",content:n}),rt=n=>({type:"text",text:n}),st=(n,e)=>({type:"image_url",image_url:e?{url:n,detail:e}:{url:n}}),ot=n=>({type:"video_url",video_url:{url:n}}),it=n=>({type:"audio_url",audio_url:{url:n}}),ce=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async create(e,t){let r={...e,stream:!1};return y(this.events,{model:e.model,capability:"text"},()=>this.transport.postJSON("/v1/chat/completions",r,t),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost,finishReason:s.choices?.[0]?.finish_reason}))}async*stream(e,t){let r={...e,stream:!0,stream_options:e.stream_options??{include_usage:!0}},s=async function*(){let o=await this.transport.postJSONStream("/v1/chat/completions",r,t);if(!o.body)throw new Error("runapps: streaming response had no body");yield*en(o.body)}.bind(this);yield*Ye(this.events,{model:e.model,capability:"text"},s,o=>({deltaText:o.choices?.[0]?.delta?.content??"",completionTokens:o.usage?.completion_tokens,costUSD:o.usage?.total_cost,finishReason:o.choices?.[0]?.finish_reason??void 0}))}};async function*en(n){let e=new TextDecoder,t=n.getReader(),r="";try{for(;;){let{value:s,done:o}=await t.read();if(o)break;r+=e.decode(s,{stream:!0});let i;for(;(i=r.indexOf(`
|
|
3
|
-
`))!==-1;){let a=r.slice(0,i).replace(/\r$/,"");if(r=r.slice(i+1),!a.startsWith("data: "))continue;let c=a.slice(6).trim();if(c==="[DONE]")return;if(!c)continue;let l;try{l=JSON.parse(c)}catch(p){throw new Error(`runapps: decode stream chunk: ${p.message}`)}let d=l.error;if(d)throw new C(d.code??0,d.type??"upstream_error",d.message??c);yield l}}}finally{t.releaseLock()}}var at=(n,e)=>Array.isArray(n.capability_tags)&&n.capability_tags.some(t=>t.id===e),ct=(n,e)=>Array.isArray(n.input_modalities)&&n.input_modalities.includes(e);function lt(n,e){let t=n.options?.[e];return typeof t=="boolean"?t:typeof t=="number"?t!==0:!1}var ut=n=>lt(n,"supports_voice_clone"),dt=n=>lt(n,"supports_instruct_text"),pt=n=>{let e=n.options?.default_voice;return typeof e=="string"?e:null},le=class{constructor(e){u(this,"transport",e)}async list(e={},t){let r="/v1/models";return e.capability&&(r+=`?capability=${encodeURIComponent(e.capability)}`),(await this.transport.getPublicJSON(r,t)).data}};var ue=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return y(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/images/generations",{model:e,...t},r),s=>({costUSD:s.usage?.total_cost}))}async generateAsync(e,t,r){let s=r?.pollIntervalMs??2e3,o=r?.signal;return y(this.events,{model:e,capability:"image_generation"},async()=>{let a=await this.transport.postJSON("/v1/async/images/generations",{model:e,...t},{signal:o});for(;a.status!=="succeeded"&&a.status!=="failed";)await tn(s,o),a=await this.getAsyncStatus(a.id,{signal:o});if(a.status==="failed")throw new Error(a.error??"image generation failed");return{created:a.created_at??Math.floor(Date.now()/1e3),data:a.data??[],usage:a.usage??{total_cost:0}}},i=>({costUSD:i.usage?.total_cost}))}async submitGenerate(e,t,r){return y(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/async/images/generations",{model:e,...t},r))}async getAsyncStatus(e,t){return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(e)}`,t)}async edit(e,t,r){let s=nn(e,t);return y(this.events,{model:e,capability:"image_edit"},()=>this.transport.postMultipart("/v1/images/edits",s,r),o=>({costUSD:o.usage?.total_cost}))}};function tn(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}function nn(n,e){let t=new FormData;return t.set("model",n),t.set("prompt",e.prompt),e.size&&t.set("size",e.size),e.n!==void 0&&t.set("n",String(e.n)),e.user&&t.set("user",e.user),t.set("image",ft(e.image),e.image.filename),e.mask&&t.set("mask",ft(e.mask),e.mask.filename),t}function ft(n){let e=n.contentType??rn(n.filename);return n.data instanceof Blob?n.data.type===e?n.data:new Blob([n.data],{type:e}):typeof n.data=="string"?new Blob([n.data],{type:e}):new Blob([n.data],{type:e})}function rn(n){switch(n.toLowerCase().split(".").pop()??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"webp":return"image/webp";case"gif":return"image/gif";default:return"application/octet-stream"}}function ht(n){if(n instanceof Blob)throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");let e=n instanceof Uint8Array?n:new Uint8Array(n),t=on(e),r=32768,s="";for(let i=0;i<e.length;i+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(i,i+r)));let o=globalThis.btoa?globalThis.btoa(s):Buffer.from(s,"binary").toString("base64");return`data:${t};base64,${o}`}async function z(n){if(n.startsWith("data:")){let e=n.slice(5),t=e.indexOf(";"),r=e.indexOf(",");if(t===-1||r===-1||r<t)throw new Error("decodeMediaUrl: malformed data URI");let s=e.slice(0,t),o=e.slice(r+1);return{bytes:sn(o),contentType:s}}if(n.startsWith("http://")||n.startsWith("https://")){let e=await fetch(n);if(!e.ok)throw new Error(`decodeMediaUrl: upstream ${e.status}`);let t=await e.arrayBuffer();return{bytes:new Uint8Array(t),contentType:e.headers.get("Content-Type")??""}}throw new Error(`decodeMediaUrl: unsupported url scheme: ${n.slice(0,32)}`)}function sn(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function on(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=6&&n[0]===71&&n[1]===73&&n[2]===70&&n[3]===56?"image/gif":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":"application/octet-stream"}var de=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async speech(e,t,r){return y(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/audio/speech",gt(e,t),r),{bytes:o,contentType:i}=await z(s.audio_url);return{data:o,contentType:i,usage:s.usage}},s=>({costUSD:s.usage?.total_cost}))}async speechAsync(e,t,r){return y(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/async/audio/speech",gt(e,t),r);if(!s.id)throw new Error("runapps: speech submit response missing job id");return an(this.transport,s.id,r)},s=>({costUSD:s.usage?.total_cost}))}async transcribe(e,t,r){let s=mt(e,t);return y(this.events,{model:e,capability:"speech_to_text"},()=>this.transport.postMultipart("/v1/audio/transcriptions",s,r),o=>({costUSD:o.usage?.total_cost}))}async transcribeAsync(e,t,r){return y(this.events,{model:e,capability:"speech_to_text"},async()=>{let s=mt(e,t),o=await this.transport.postMultipart("/v1/async/audio/transcriptions",s,r);if(!o.id)throw new Error("runapps: transcribe submit response missing job id");return cn(this.transport,o.id,r)},s=>({costUSD:s.usage?.total_cost}))}};async function an(n,e,t){let r=`/v1/async/audio/speech/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await pe(2e3,t?.signal);let i=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("speech poll aborted","AbortError");if(!t?.signal&&Date.now()>i)throw new Error("runapps: speech job timed out (10 min internal cap)");let a=await n.getJSON(r,t);if(a.status==="succeeded"){if(!a.audio_url)throw new Error("runapps: speech job succeeded but no audio_url returned");let{bytes:c,contentType:l}=await z(a.audio_url);return{data:c,contentType:l,usage:a.usage??{total_cost:0}}}if(a.status==="failed")throw new Error(a.error||"runapps: speech job failed");await pe(s,t?.signal)}}async function cn(n,e,t){let r=`/v1/async/audio/transcriptions/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await pe(2e3,t?.signal);let o=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("transcribe poll aborted","AbortError");if(!t?.signal&&Date.now()>o)throw new Error("runapps: transcribe job timed out (10 min internal cap)");let i=await n.getJSON(r,t);switch(i.status){case"succeeded":return ln(i);case"failed":throw new Error(i.error||"runapps: transcribe job failed");case"queued":case"running":await pe(s,t?.signal);break;default:throw new Error(`runapps: unknown transcribe job status ${JSON.stringify(i.status)}`)}}}function ln(n){let e={text:n.text??"",usage:n.usage??{total_cost:0}},t={};for(let[r,s]of Object.entries(n))r==="text"||r==="usage"||r==="id"||r==="status"||(t[r]=s);return Object.keys(t).length>0&&(e.raw=t),e}function pe(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new DOMException("aborted","AbortError"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",o,{once:!0})})}function gt(n,e){let{extra:t,...r}=e,s={model:n,...r};if(t)for(let[o,i]of Object.entries(t))o in s||(s[o]=i);return s}function mt(n,e){let t=new FormData;if(t.set("model",n),e.language&&t.set("language",e.language),e.prompt&&t.set("prompt",e.prompt),e.response_format&&t.set("response_format",e.response_format),e.timestamp_granularities)for(let o of e.timestamp_granularities)t.append("timestamp_granularities[]",o);e.user&&t.set("user",e.user);let r=e.file.contentType??un(e.file.filename),s=e.file.data instanceof Blob?e.file.data:new Blob([e.file.data],{type:r});return t.set("file",s,e.file.filename),t}function un(n){switch(n.toLowerCase().split(".").pop()??""){case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"flac":return"audio/flac";case"ogg":return"audio/ogg";case"webm":return"audio/webm";default:return"application/octet-stream"}}var fe=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return y(this.events,{model:e,capability:"video_generation"},()=>this.transport.postJSON("/v1/videos/generations",{model:e,...t},r))}async getStatus(e,t){return this.transport.getJSON(`/v1/videos/generations/${encodeURIComponent(e)}`,t)}async wait(e,t={}){let r=t.pollIntervalMs??5e3;for(;;){let s=await this.getStatus(e,{signal:t.signal});if(s.status==="succeeded"||s.status==="failed")return s;await dn(r,t.signal)}}async getContent(e,t){return this.transport.getRaw(`/v1/videos/${encodeURIComponent(e)}/content`,t)}};function dn(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}var he=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async step(e,t,r){return y(this.events,{model:e,capability:"computer_use"},()=>this.transport.postJSON("/v1/computer/step",{model:e,...t},r),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost}))}};function W(n,e){let t=e.replace(/^\/+/,"");return n+"/"+t.split("/").map(encodeURIComponent).join("/")}var Y=class{constructor(e,t,r){u(this,"transport",e);u(this,"events",r);u(this,"base");this.base=t?"/v1/p/"+encodeURIComponent(t)+"/files":"/v1/files"}run(e,t){return this.events?y(this.events,{model:e,capability:"files"},t):t()}async put(e,t,r){let s={};return r?.ifNoneMatch&&(s["If-None-Match"]="*"),r?.ifMatch&&(s["If-Match"]=`"${r.ifMatch.replace(/"/g,"")}"`),this.run("files.put",()=>this.transport.putBytes(W(this.base,e),t,{contentType:r?.contentType,headers:Object.keys(s).length?s:void 0,signal:r?.signal}))}async putString(e,t,r){return this.put(e,t,{...r,contentType:r?.contentType??"text/plain; charset=utf-8"})}async get(e,t){return(await this.read(e,t)).blob}async read(e,t){return this.run("files.read",()=>this.readRaw(e,t))}async readRaw(e,t){let{data:r,contentType:s,etag:o,notModified:i}=await this.transport.getRaw(W(this.base,e),t);return{blob:new Blob([new Uint8Array(r)],{type:s||"application/octet-stream"}),contentType:s,etag:o,...i?{notModified:!0}:{}}}async readJSON(e,t){let r;try{r=await this.read(e,t)}catch(s){if(s?.statusCode===404||s?.status===404)return{value:void 0,etag:void 0};throw s}return r.notModified?{value:void 0,etag:r.etag,notModified:!0}:{value:JSON.parse(await r.blob.text()),etag:r.etag}}async stat(e,t){let{status:r,headers:s}=await this.run("files.stat",()=>this.transport.head(W(this.base,e),t));if(r===404)throw Object.assign(new Error("not found"),{status:404});if(r>=400)throw Object.assign(new Error("stat failed"),{status:r});let o=parseInt(s.get("content-length")??"0",10);return{path:s.get("x-file-path")??e,size:o,content_type:s.get("content-type")??void 0,etag:(s.get("etag")??"").replace(/"/g,"")||void 0,url:s.get("x-file-url")??""}}async exists(e,t){let{status:r}=await this.run("files.exists",()=>this.transport.head(W(this.base,e),t));return r>=200&&r<400}async del(e,t){await this.run("files.del",()=>this.transport.deletePath(W(this.base,e),t))}async list(e){let t=new URLSearchParams;e?.prefix&&t.set("prefix",e.prefix),e?.cursor&&t.set("cursor",e.cursor),e?.limit&&t.set("limit",String(e.limit)),e?.glob&&t.set("glob",e.glob);let r=t.toString();return this.run("files.list",()=>this.transport.getJSON(this.base+(r?"?"+r:""),e?.signal?{signal:e.signal}:void 0))}async deleteMany(e,t){return this.run("files.deleteMany",()=>this.transport.postJSON(this.base+"/delete",{prefix:e.prefix??"",glob:e.glob??""},t))}async move(e,t,r){return this.run("files.move",()=>this.transport.postJSON(this.base+"/move",{from:e,to:t},r))}async copy(e,t,r){return this.run("files.copy",()=>this.transport.postJSON(this.base+"/copy",{from:e,to:t},r))}async putFromURL(e,t,r){return this.run("files.putFromURL",()=>this.transport.postJSON(this.base+"/put-url",{path:e,src_url:t,content_type:r?.contentType,if_none_match:r?.ifNoneMatch,if_match:r?.ifMatch},r?.signal?{signal:r.signal}:void 0))}async batch(e,t){return e.length===0?[]:this.run("files.batch",()=>this.batchRaw(e,t))}async batchRaw(e,t){if(e.length<=30)return(await this.transport.postJSON(this.base+"/batch",{ops:e},t)).results;let s=[];for(let o=0;o<e.length;o+=30){let i=e.slice(o,o+30),a=await this.transport.postJSON(this.base+"/batch",{ops:i},t);s.push(...a.results)}return s}};var ge=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async create(e,t,r){return y(this.events,{model:e,capability:"embedding"},()=>this.transport.postJSON("/v1/embeddings",{model:e,...t},r),s=>({totalTokens:s.usage?.total_tokens,costUSD:s.usage?.total_cost}))}};var O=class{constructor(){u(this,"active",new Map);u(this,"recent",[]);u(this,"session",{totalCalls:0,totalCostUSD:0,errorCount:0,startedAt:Date.now()});u(this,"lastErrorAt",0);u(this,"changeListeners",new Set);u(this,"sync")}attach(e){let t=[e.on("request:start",r=>{this.onStart(r),this.notify()}),e.on("request:streamDelta",r=>{this.onDelta(r),this.notify()}),e.on("request:end",r=>{this.onEnd(r),this.notify()}),e.on("request:error",r=>{this.onError(r),this.notify()}),e.on("sync:state",r=>{this.sync={...r},this.notify()})];return()=>{for(let r of t)r()}}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}notify(){for(let e of this.changeListeners)try{e()}catch(t){console.error("[runapps sdk] ActivityTracker onChange listener threw:",t)}}snapshot(){let e=Date.now();return{active:Array.from(this.active.values()),recent:this.recent.slice(),session:{...this.session},...this.sync?{sync:{...this.sync}}:{},status:e-this.lastErrorAt<3e4?"error":this.active.size>0?"active":"idle"}}onStart(e){this.active.set(e.id,{id:e.id,model:e.model,capability:e.capability,startedAt:e.startedAt,streaming:e.streaming,tokensSoFar:0,tokensPerSec:0,rateSamples:[]})}onDelta(e){let t=this.active.get(e.id);if(!t)return;t.tokensSoFar=e.totalTokens;let r=Date.now();t.rateSamples.push({t:r,tokens:e.deltaTokens});let s=r-1500;for(;t.rateSamples.length>0&&t.rateSamples[0].t<s;)t.rateSamples.shift();if(t.rateSamples.length>=2){let o=t.rateSamples.reduce((a,c)=>a+c.tokens,0),i=r-t.rateSamples[0].t;t.tokensPerSec=i>0?o*1e3/i:0}}onEnd(e){let t=this.active.get(e.id);this.active.delete(e.id),e.capability!=="files"&&(this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:e.totalTokens||t?.tokensSoFar||0,...e.costUSD!==void 0&&{costUSD:e.costUSD},...e.finishReason!==void 0&&{finishReason:e.finishReason},ok:!0,endedAt:Date.now()}),this.session.totalCalls+=1,e.costUSD!==void 0&&(this.session.totalCostUSD+=e.costUSD))}onError(e){let t=this.active.get(e.id);if(this.active.delete(e.id),e.capability==="files"){e.statusCode!==404&&(this.lastErrorAt=Date.now());return}this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:t?.tokensSoFar||0,ok:!1,errorMessage:e.error.message,endedAt:Date.now()}),this.session.totalCalls+=1,this.session.errorCount+=1,this.lastErrorAt=Date.now()}pushRecent(e){this.recent.unshift(e),this.recent.length>20&&(this.recent.length=20)}};var yt={ArrayBuffer:n=>n,Uint8Array:n=>new Uint8Array(n),Int8Array:n=>new Int8Array(n),Uint8ClampedArray:n=>new Uint8ClampedArray(n),Int16Array:n=>new Int16Array(n),Uint16Array:n=>new Uint16Array(n),Int32Array:n=>new Int32Array(n),Uint32Array:n=>new Uint32Array(n),Float32Array:n=>new Float32Array(n),Float64Array:n=>new Float64Array(n),BigInt64Array:n=>new BigInt64Array(n),BigUint64Array:n=>new BigUint64Array(n),DataView:n=>new DataView(n)};function ye(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function bt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Pe(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}async function x(n,e){if(n===void 0)return{$rt:"undef"};if(n===null)return null;switch(typeof n){case"string":case"boolean":return n;case"number":return Number.isNaN(n)?{$rt:"num",v:"NaN"}:n===1/0?{$rt:"num",v:"Infinity"}:n===-1/0?{$rt:"num",v:"-Infinity"}:Object.is(n,-0)?{$rt:"num",v:"-0"}:n;case"bigint":return{$rt:"bigint",v:n.toString()};case"function":case"symbol":throw new TypeError(`runapps sync: ${typeof n} values cannot be stored`)}if(n instanceof Date){let r=n.getTime();return{$rt:"date",v:Number.isNaN(r)?"invalid":r}}if(n instanceof RegExp)return{$rt:"re",s:n.source,f:n.flags};if(typeof Blob<"u"&&n instanceof Blob){if(!e)throw new TypeError("runapps sync: Blob values need a blob sink");let r=await e(n),s={$rt:"blob",r:r.ref,t:r.type,s:r.size},o=n;return typeof File<"u"&&n instanceof File&&(s.n=o.name,s.m=o.lastModified),s}if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ye(new Uint8Array(n))};if(ArrayBuffer.isView(n)){let r=n.constructor.name;if(!(r in yt))throw new TypeError(`runapps sync: unsupported binary type ${r}`);let s=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return{$rt:"bin",c:r,v:ye(s)}}if(n instanceof Map){let r=[];for(let[s,o]of n)r.push([await x(s,e),await x(o,e)]);return{$rt:"map",v:r}}if(n instanceof Set){let r=[];for(let s of n)r.push(await x(s,e));return{$rt:"set",v:r}}if(Array.isArray(n)){let r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=await x(n[s],e);return r}if(Pe(n)){let r=Object.prototype.hasOwnProperty.call(n,"$rt"),s={};for(let o of Object.keys(n))s[o]=await x(n[o],e);return r?{$rt:"obj",v:s}:s}let t={};for(let r of Object.keys(n))t[r]=await x(n[r],e);return t}async function k(n,e){if(n===null||typeof n!="object")return n;if(Array.isArray(n)){let o=new Array(n.length);for(let i=0;i<n.length;i++)o[i]=await k(n[i],e);return o}let t=n;if(typeof t.$rt=="string"){let o=t;switch(o.$rt){case"undef":return;case"date":return o.v==="invalid"?new Date(NaN):new Date(o.v);case"num":return o.v==="NaN"?NaN:o.v==="Infinity"?1/0:o.v==="-Infinity"?-1/0:-0;case"bigint":return BigInt(o.v);case"re":return new RegExp(o.s,o.f);case"bin":{let i=bt(o.v),a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i);let c=yt[o.c];if(!c)throw new TypeError(`runapps sync: unsupported binary type ${o.c}`);return c(a)}case"map":{let i=new Map;for(let a of o.v)i.set(await k(a[0],e),await k(a[1],e));return i}case"set":{let i=new Set;for(let a of o.v)i.add(await k(a,e));return i}case"blob":{if(!e)throw new TypeError("runapps sync: Blob values need a blob source");let i=await e({ref:o.r,type:o.t,size:o.s});return o.n!==void 0&&typeof File<"u"?new File([i],o.n,{type:o.t,lastModified:o.m??Date.now()}):i}case"obj":return k(o.v,e)}}let s={};for(let o of Object.keys(t))s[o]=await k(t[o],e);return s}function M(n){if(typeof n=="number"){if(Number.isNaN(n))throw new TypeError("runapps sync: NaN is not a valid key");return n}if(typeof n=="string")return n;if(n instanceof Date)return{$rt:"date",v:n.getTime()};if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ye(new Uint8Array(n))};if(ArrayBuffer.isView(n))return{$rt:"bin",c:"ArrayBuffer",v:ye(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))};if(Array.isArray(n))return n.map(e=>M(e));throw new TypeError("runapps sync: invalid IndexedDB key")}function X(n){if(typeof n=="number"||typeof n=="string")return n;if(Array.isArray(n))return n.map(X);if(n&&typeof n=="object"){let e=n;if(e.$rt==="date")return new Date(e.v);if(e.$rt==="bin"){let t=bt(e.v),r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),r}}throw new TypeError("runapps sync: invalid encoded key")}function be(n){return JSON.stringify(M(n))}function we(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function me(n,e){if(Object.is(n,e))return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;if(n instanceof Date||e instanceof Date)return n instanceof Date&&e instanceof Date&&Object.is(n.getTime(),e.getTime());if(typeof Blob<"u"&&(n instanceof Blob||e instanceof Blob))return!1;if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof ArrayBuffer){let s=a=>a instanceof ArrayBuffer?new Uint8Array(a):ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):null,o=s(n),i=s(e);if(!o||!i||o.length!==i.length||n.constructor!==e.constructor)return!1;for(let a=0;a<o.length;a++)if(o[a]!==i[a])return!1;return!0}if(n instanceof Map||e instanceof Map){if(!(n instanceof Map&&e instanceof Map)||n.size!==e.size)return!1;for(let[s,o]of n)if(!e.has(s)||!me(o,e.get(s)))return!1;return!0}if(n instanceof Set||e instanceof Set){if(!(n instanceof Set&&e instanceof Set)||n.size!==e.size)return!1;for(let s of n)if(!e.has(s))return!1;return!0}if(Array.isArray(n)||Array.isArray(e)){if(!(Array.isArray(n)&&Array.isArray(e))||n.length!==e.length)return!1;for(let s=0;s<n.length;s++)if(!me(n[s],e[s]))return!1;return!0}let t=Object.keys(n),r=Object.keys(e);if(t.length!==r.length)return!1;for(let s of t)if(!Object.prototype.hasOwnProperty.call(e,s)||!me(n[s],e[s]))return!1;return!0}function wt(n,e){if(!Pe(n)||!Pe(e))return;let t=[];for(let r of new Set([...Object.keys(n),...Object.keys(e)])){let s=Object.prototype.hasOwnProperty.call(n,r),o=Object.prototype.hasOwnProperty.call(e,r);(s!==o||!me(n[r],e[r]))&&t.push(r)}return t}function vt(n,e){if(e==null)return;let t=s=>{let o=n;if(s==="")return o;for(let i of s.split(".")){if(o===null||typeof o!="object")return;o=o[i]}return o};if(Array.isArray(e)){let s=e.map(t);return s.some(o=>o===void 0)?void 0:s}let r=t(e);return r===void 0?void 0:r}var St=60,xt="__runapps_auth_v1__",kt="__runjobs_auth_v1__",At="__runapps_signed_out_v1__",_t="__runjobs_signed_out_v1__";function Q(n){return n?`${xt}:${n}`:xt}function ve(n){return n?`${At}:${n}`:At}function Be(n){return n?`${kt}:${n}`:kt}function Tt(n){return n?`${_t}:${n}`:_t}var U=class{constructor(e={}){u(this,"origin");u(this,"hideBadge");u(this,"project");u(this,"events");u(this,"tracker");u(this,"badgePosition");u(this,"token",null);u(this,"expiresAt",0);u(this,"userInfo",null);u(this,"listeners",[]);u(this,"parentHandshake",null);u(this,"signingIn",!1);u(this,"getToken",async()=>{if(this.tokenIsFresh())return this.token;if(this.isSignedOut())throw new Error("RunApps: signed out \u2014 call client.signIn() to authenticate");if(this.inIframe()){try{this.parentHandshake&&(await this.parentHandshake,this.parentHandshake=null),this.tokenIsFresh()||await this.requestTokenFromParent()}catch{}if(this.tokenIsFresh())return this.token;throw new Error("RunApps: could not obtain a token from the dashboard")}return this.parentHandshake&&(await this.parentHandshake,this.tokenIsFresh())?this.token:(this.signIn(),new Promise(()=>{}))});this.origin=(e.origin??"https://www.runapps.ai").replace(/\/$/,""),this.hideBadge=!!e.hideBadge,this.project=e.project??null,this.events=e.events??null,this.badgePosition=e.badgePosition??"bottom-right",this.events&&!this.hideBadge?(this.tracker=new O,this.tracker.attach(this.events)):this.tracker=null,!(typeof window>"u")&&(this.loadPersisted(),this.consumeFragment()&&this.clearSignedOut(),this.isSignedOut()||(this.inIframe()&&!this.tokenIsFresh()?this.parentHandshake=this.requestTokenFromParent().catch(()=>{}):this.tokenIsFresh()&&this.userInfo&&!this.hideBadge&&this.renderBadge()))}onTokenChange(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}get user(){return this.userInfo}hasFreshToken(){return this.tokenIsFresh()}ownerId(){return this.tokenIsFresh()?this.userInfo?.id?this.userInfo.id:"t"+we(this.token).toString(36):null}signOut(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted(),this.markSignedOut(),this.removeBadge()}invalidate(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted()}signIn(){if(typeof window>"u"||this.signingIn)return;this.clearSignedOut(),this.signingIn=!0;let e=location.href.split("#")[0]??location.href,t=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";location.href=this.buildGrantUrl({pageOrigin:location.origin,app:location.host,redirectTo:e,scheme:t})}_buildGrantUrlForTest(e){return this.buildGrantUrl(e)}_storageKeysForTest(){return{auth:Q(this.project),signedOut:ve(this.project)}}buildGrantUrl(e){let t=new URLSearchParams;return t.set("origin",e.pageOrigin),t.set("app",e.app),t.set("redirect_to",e.redirectTo),t.set("scheme",e.scheme),this.project&&t.set("project_id",this.project),t.set("token_name","runapps_token"),this.origin+"/api/sdk/grant?"+t.toString()}nowSec(){return Math.floor(Date.now()/1e3)}tokenIsFresh(){return!!this.token&&this.nowSec()<this.expiresAt-St}inIframe(){try{return window.self!==window.top}catch{return!0}}setToken(e,t,r){this.token=e,this.expiresAt=t||this.nowSec()+3600,r&&(this.userInfo=r,this.hideBadge||this.renderBadge()),this.savePersisted();for(let s of this.listeners)try{s(e)}catch(o){console.warn("[runapps] onTokenChange handler threw",o)}}savePersisted(){if(!(typeof localStorage>"u"||!this.token))try{let e={token:this.token,expiresAt:this.expiresAt,origin:this.origin,...this.userInfo?{user:this.userInfo}:{}};localStorage.setItem(Q(this.project),JSON.stringify(e))}catch{}}loadPersisted(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem(Q(this.project));if(!e){if(e=localStorage.getItem(Be(this.project)),!e)return;localStorage.setItem(Q(this.project),e),localStorage.removeItem(Be(this.project))}let t=JSON.parse(e);if(!t.token||!t.origin||t.origin!==this.origin)return;if(typeof t.expiresAt=="number"&&t.expiresAt>0&&this.nowSec()>=t.expiresAt-St){this.clearPersisted();return}this.token=t.token,this.expiresAt=t.expiresAt??0,t.user&&(this.userInfo=t.user)}catch{this.clearPersisted()}}clearPersisted(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Q(this.project)),localStorage.removeItem(Be(this.project))}catch{}}isSignedOut(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(ve(this.project))==="1"||localStorage.getItem(Tt(this.project))==="1"}catch{return!1}}markSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.setItem(ve(this.project),"1")}catch{}}clearSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ve(this.project)),localStorage.removeItem(Tt(this.project))}catch{}}removeBadge(){typeof document>"u"||document.getElementById("__runapps_identity__")?.remove()}consumeFragment(){if(!location.hash||!/(^#|&)run(apps|jobs)_token=/.test(location.hash))return!1;let e={};location.hash.replace(/^#/,"").split("&").forEach(s=>{let o=s.indexOf("=");o>=0&&(e[decodeURIComponent(s.slice(0,o))]=decodeURIComponent(s.slice(o+1).replace(/\+/g," ")))});let t=e.runapps_token||e.runjobs_token;if(!t)return!1;let r;if(e.user)try{r=JSON.parse(e.user)}catch{}this.setToken(t,parseInt(e.expires_at??"",10)||0,r);try{history.replaceState(null,"",location.pathname+location.search)}catch{}return!0}requestTokenFromParent(){return new Promise((e,t)=>{let r=!1,s=[],o=()=>{r=!0,window.removeEventListener("message",i);for(let c of s)clearTimeout(c)},i=c=>{if(c.origin!==this.origin)return;let l=c.data;l&&(l.type==="runapps:token"||l.type==="runjobs:token")&&l.token&&(this.setToken(l.token,l.expires_at??0,l.user),o(),e())};window.addEventListener("message",i);let a=()=>{if(!r)try{window.parent.postMessage({type:"runapps:request-token"},this.origin),window.parent.postMessage({type:"runjobs:request-token"},this.origin)}catch(c){o(),t(c)}};a();for(let c of[250,750,1500,3e3])s.push(setTimeout(a,c));s.push(setTimeout(()=>{r||(o(),t(new Error("runapps: parent handshake timeout")))},5e3))})}renderBadge(){if(typeof document>"u"||!this.userInfo)return;let e="__runapps_identity__",t=`${this.origin}/dashboard`;(s=>document.body?s():document.addEventListener("DOMContentLoaded",s))(()=>{document.getElementById(e)?.remove();let s=bn({id:e,user:this.userInfo,dashboardUrl:t,tracker:this.tracker,position:this.badgePosition,onSignOut:()=>{this.signOut(),typeof window<"u"&&window.location.reload()}});document.body.appendChild(s)})}};function pn(){if(typeof document>"u"||document.getElementById("__runapps_kf__"))return;let n=document.createElement("style");n.id="__runapps_kf__",n.textContent="@keyframes __runapps_led_pulse__ { 0% { box-shadow: 0 0 0 0 rgba(59,130,246,0.7); } 70% { box-shadow: 0 0 0 6px rgba(59,130,246,0); } 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0); }}@keyframes __runapps_sync_ping__ { 0% { transform: scale(1); opacity: 0.9; } 100% { transform: scale(2.1); opacity: 0; }}",(document.head??document.documentElement).appendChild(n)}function fn(n){let e=n.startsWith("top")?"top":"bottom",t=n.endsWith("right")?"right":"left",r=e==="bottom"?"bottom:calc(100% + 8px);top:auto":"top:calc(100% + 8px);bottom:auto",s=t==="right"?"right:0;left:auto":"left:0;right:auto";return{badge:`${e}:16px;${t}:16px`,popover:`${r};${s}`}}var Dt="__runapps_badge_pos__",hn="__runjobs_badge_pos__",Et=5,j=8;function gn(){if(typeof document>"u")return null;let n=document.cookie.split(";").map(l=>l.trim()),e=Dt,t=n.find(l=>l.startsWith(e+"="));if(t||(e=hn,t=n.find(l=>l.startsWith(e+"="))),!t)return null;let s=decodeURIComponent(t.slice(e.length+1)).split(","),o=s[0],i=s[1];if(s.length!==2||o===void 0||i===void 0)return null;let a=Number.parseInt(o,10),c=Number.parseInt(i,10);return!Number.isFinite(a)||!Number.isFinite(c)?null:{x:a,y:c}}function mn(n,e){if(typeof document>"u")return;let t=3600*24*365,r=typeof window<"u"&&window.location?.protocol==="https:"?";Secure":"";document.cookie=`${Dt}=${encodeURIComponent(`${Math.round(n)},${Math.round(e)}`)};path=/;max-age=${t};SameSite=Lax${r}`}function Ct(n,e,t,r){let s=typeof window<"u"?window.innerWidth:1024,o=typeof window<"u"?window.innerHeight:768,i=Math.max(j,s-t-j),a=Math.max(j,o-r-j);return{x:Math.min(Math.max(j,n),i),y:Math.min(Math.max(j,e),a)}}function yn(n){let e=typeof window<"u"?window.innerWidth:1024,t=typeof window<"u"?window.innerHeight:768,r=n.left+n.width/2,o=n.top+n.height/2<t/2?"top:calc(100% + 8px);bottom:auto":"bottom:calc(100% + 8px);top:auto",i=r<e/2?"left:0;right:auto":"right:0;left:auto";return`${o};${i}`}function bn(n){let{id:e,user:t,dashboardUrl:r,tracker:s,position:o,onSignOut:i}=n,a=fn(o),c=a.popover;pn();let l=document.createElement("button");l.id=e,l.type="button",l.setAttribute("aria-label","RunApps activity status"),l.style.cssText=["position:fixed",a.badge,"z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:5px","border-radius:50%","font:500 12px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","color:#fff","background:rgba(15,15,20,0.55)","backdrop-filter:blur(10px) saturate(1.2)","-webkit-backdrop-filter:blur(10px) saturate(1.2)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 4px 16px rgba(0,0,0,0.15)","user-select:none","-webkit-user-select:none","touch-action:none","-webkit-touch-callout:none","overflow:visible","cursor:pointer","appearance:none","-webkit-appearance:none","transition:background-color 120ms ease-out, box-shadow 120ms ease-out"].join(";"),l.addEventListener("mouseenter",()=>{l.style.backgroundColor="rgba(30,30,40,0.7)",l.style.boxShadow="0 6px 20px rgba(0,0,0,0.22)"}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="rgba(15,15,20,0.55)",l.style.boxShadow="0 4px 16px rgba(0,0,0,0.15)"});let d=document.createElement("span");d.style.cssText=["position:relative","width:26px;height:26px","flex-shrink:0","display:inline-flex;align-items:center;justify-content:center"].join(";");let p="http://www.w3.org/2000/svg",h=document.createElementNS(p,"svg");h.setAttribute("viewBox","0 0 26 26"),h.setAttribute("width","26"),h.setAttribute("height","26"),h.style.cssText=["position:absolute;inset:0","pointer-events:none","opacity:0","transition:opacity 200ms ease-out"].join(";");let f=document.createElementNS(p,"circle");f.setAttribute("cx","13"),f.setAttribute("cy","13"),f.setAttribute("r","12"),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(255,255,255,0.08)"),f.setAttribute("stroke-width","1.5");let g=document.createElementNS(p,"circle");g.setAttribute("cx","13"),g.setAttribute("cy","13"),g.setAttribute("r","12"),g.setAttribute("fill","none"),g.setAttribute("stroke","#3b82f6"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("transform","rotate(-90 13 13)");let w=2*Math.PI*12;g.setAttribute("stroke-dasharray",String(w)),g.setAttribute("stroke-dashoffset",String(w)),h.appendChild(f),h.appendChild(g);let _=document.createElement("div");_.textContent=(t.name||"?").charAt(0).toUpperCase(),_.style.cssText=["width:22px;height:22px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff","position:relative"].join(";");let T=document.createElement("span");T.style.cssText=["position:absolute","bottom:-1px;right:-1px","width:7px;height:7px;border-radius:50%","background:rgba(255,255,255,0.2)","border:1.5px solid rgba(15,15,20,1)","box-shadow:0 0 0 0 transparent","opacity:0","transition:background-color 150ms ease-out, box-shadow 200ms ease-out, opacity 200ms ease-out","pointer-events:none"].join(";"),d.appendChild(h),d.appendChild(_),d.appendChild(T),l.appendChild(d);let v=null,S=!1,B=null,ne=null,re=null,Ee=()=>{ne!==null&&(window.clearTimeout(ne),ne=null)},K=()=>{re!==null&&(window.clearTimeout(re),re=null)},Fe=()=>{K(),re=window.setTimeout(()=>{B==="hover"&&$()},300)},Le=m=>{if(Ee(),K(),S){m==="click"&&(B="click");return}v||(v=xn(t,r,c,()=>{$(),i()}),v.addEventListener("mouseenter",K),v.addEventListener("mouseleave",()=>{B==="hover"&&Fe()})),l.appendChild(v),S=!0,B=m,oe()},$=()=>{K(),S&&(v?.remove(),S=!1,B=null)};l.addEventListener("click",m=>{m.stopPropagation(),S?$():Le("click")}),l.addEventListener("mouseenter",()=>{K(),Ee(),ne=window.setTimeout(()=>{S||Le("hover")},400)}),l.addEventListener("mouseleave",()=>{Ee(),B==="hover"&&Fe()}),document.addEventListener("click",m=>{S&&!l.contains(m.target)&&$()});let Ke=0,$e=0,Ve=0,qe=0,se=!1,V=!1,Ce=!1,De=(m,b)=>{l.style.left=`${m}px`,l.style.top=`${b}px`,l.style.right="auto",l.style.bottom="auto"},Ge=()=>{let m=l.getBoundingClientRect();if(c=yn({left:m.left,top:m.top,width:m.width,height:m.height}),v){v.style.top="",v.style.bottom="",v.style.left="",v.style.right="";for(let b of c.split(";")){let[E,H]=b.split(":");E&&H&&v.style.setProperty(E.trim(),H.trim())}}};l.addEventListener("pointerdown",m=>{if(m.button!==0)return;se=!0,V=!1,Ke=m.clientX,$e=m.clientY;let b=l.getBoundingClientRect();Ve=b.left,qe=b.top}),l.addEventListener("pointermove",m=>{if(!se)return;let b=m.clientX-Ke,E=m.clientY-$e;if(!V){if(Math.abs(b)<Et&&Math.abs(E)<Et)return;V=!0;try{l.setPointerCapture(m.pointerId)}catch{}l.style.cursor="grabbing",S&&$()}let H=l.getBoundingClientRect(),We=Ct(Ve+b,qe+E,H.width,H.height);De(We.x,We.y)});let He=m=>{if(!se||(se=!1,!V))return;V=!1,l.style.cursor="pointer";try{l.hasPointerCapture(m.pointerId)&&l.releasePointerCapture(m.pointerId)}catch{}let b=l.getBoundingClientRect();mn(b.left,b.top),Ge(),Ce=!0};l.addEventListener("pointerup",He),l.addEventListener("pointercancel",He),l.addEventListener("click",m=>{Ce&&(Ce=!1,m.stopPropagation(),m.preventDefault())},!0);let q=gn();q&&(De(q.x,q.y),requestAnimationFrame(()=>{let m=l.getBoundingClientRect(),b=Ct(q.x,q.y,m.width,m.height);De(b.x,b.y),Ge()}));let Ie=!1,G=null,Je,ze=()=>{if(Ie=!1,!s){h.style.opacity="0",T.style.background="rgba(255,255,255,0.2)",T.style.opacity="0";return}let m=s.snapshot(),b=m.sync?.lastChangeAt;b&&b!==Je&&(Je=b,vn(d,T)),wn(h,g,w,m),Sn(T,m),S&&v&&kn(v,m);let E=m.status!=="idle"||S;E&&G===null?G=window.setInterval(oe,160):!E&&G!==null&&(window.clearInterval(G),G=null)};function oe(){Ie||(Ie=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(ze):setTimeout(ze,0))}return s&&s.onChange(oe),oe(),l}function wn(n,e,t,r){if(r.active.length===0){n.style.opacity="0";return}n.style.opacity="1";let s=r.active.reduce((o,i)=>i.tokensPerSec>o.tokensPerSec?i:o,r.active[0]);if(s.streaming&&s.tokensPerSec>0){let o=Math.min(s.tokensPerSec/60,1);e.setAttribute("stroke-dashoffset",String(t*(1-o))),e.setAttribute("stroke","#3b82f6")}else r.status==="error"?(e.setAttribute("stroke-dashoffset","0"),e.setAttribute("stroke","#ef4444")):(e.setAttribute("stroke-dashoffset",String(t*.75)),e.setAttribute("stroke","#a78bfa"))}var Re=0;function vn(n,e){let t=document.createElement("span");t.style.cssText=["position:absolute;inset:0","border-radius:50%","border:2px solid #10b981","pointer-events:none","animation:__runapps_sync_ping__ 700ms ease-out forwards"].join(";"),t.addEventListener("animationend",()=>t.remove()),n.appendChild(t),setTimeout(()=>t.remove(),1e3),Re=Date.now()+1200,e.style.opacity="1",e.style.background="#10b981",e.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",e.style.animation="",setTimeout(()=>{Date.now()>=Re&&(e.style.background="rgba(255,255,255,0.2)",e.style.opacity="0",e.style.boxShadow="0 0 0 0 transparent")},1250)}function Sn(n,e){switch(n.style.opacity="1",e.status){case"idle":{let t=e.sync;Date.now()<Re?(n.style.background="#10b981",n.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",n.style.animation=""):t&&t.state==="syncing"?(n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite"):t&&(t.state==="offline"||t.state==="error")?(n.style.background="#f59e0b",n.style.boxShadow="0 0 0 2px rgba(245,158,11,0.3)",n.style.animation=""):(n.style.background="rgba(255,255,255,0.2)",n.style.opacity="0",n.style.boxShadow="0 0 0 0 transparent",n.style.animation="");break}case"active":n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite";break;case"error":n.style.background="#ef4444",n.style.boxShadow="0 0 0 2px rgba(239,68,68,0.3)",n.style.animation="";break}}function xn(n,e,t,r){let s=document.createElement("div");s.style.cssText=["position:absolute",t,"min-width:280px;max-width:340px","padding:10px 12px","border-radius:10px","background:rgba(15,15,20,0.92)","backdrop-filter:blur(20px) saturate(1.3)","-webkit-backdrop-filter:blur(20px) saturate(1.3)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 10px 30px rgba(0,0,0,0.4)","color:#fff","font:400 11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","cursor:default","text-align:left"].join(";"),s.setAttribute("data-runapps-popover","1"),s.addEventListener("click",g=>g.stopPropagation());let o=document.createElement("div");o.style.cssText=["display:flex;align-items:center;gap:8px","margin-bottom:10px;padding-bottom:8px","border-bottom:1px solid rgba(255,255,255,0.08)"].join(";");let i=document.createElement("div");i.textContent=(n.name||"?").charAt(0).toUpperCase(),i.style.cssText=["width:24px;height:24px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff"].join(";");let a=document.createElement("div");a.textContent=n.name||"Signed in",a.title=n.name||"",a.style.cssText="font-size:12px;font-weight:500;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap";let c=document.createElement("div");c.textContent="Signed in with RunApps",c.style.cssText="font-size:10px;color:rgba(255,255,255,0.5)";let l=document.createElement("div");l.style.cssText="min-width:0",l.appendChild(a),l.appendChild(c),o.appendChild(i),o.appendChild(l),s.appendChild(o);let d=document.createElement("div");d.setAttribute("data-runapps-popover-content","1"),s.appendChild(d);let p=document.createElement("div");p.style.cssText=["margin-top:10px;padding-top:8px","border-top:1px solid rgba(255,255,255,0.08)","display:flex;justify-content:space-between;align-items:center","font-size:10px;color:rgba(255,255,255,0.6)"].join(";");let h=document.createElement("a");h.textContent="Open dashboard \u2192",h.href=e,h.target="_blank",h.rel="noopener noreferrer",h.style.cssText="color:#a78bfa;text-decoration:none",p.appendChild(h);let f=document.createElement("button");return f.type="button",f.textContent="Sign out",f.style.cssText=["background:none;border:0;padding:0;margin:0","font:inherit;cursor:pointer","color:rgba(255,255,255,0.55)","transition:color 120ms ease"].join(";"),f.addEventListener("mouseenter",()=>{f.style.color="#f87171"}),f.addEventListener("mouseleave",()=>{f.style.color="rgba(255,255,255,0.55)"}),f.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),r()}),p.appendChild(f),s.appendChild(p),s}function kn(n,e){let t=n.querySelector("[data-runapps-popover-content]");if(!t)return;t.innerHTML="";let r=Date.now();t.appendChild(_n(e,r)),t.appendChild(Tn(e,r)),e.sync&&t.appendChild(An(e.sync,r)),t.appendChild(En(e.session,r))}function An(n,e){let t=document.createElement("div");t.style.marginBottom="10px";let r=n.lastSyncedAt?`synced ${Oe(e-n.lastSyncedAt)}`:"\u2014";t.appendChild(Se("Sync",r));let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0;font-size:10px";let o=document.createElement("span"),i=document.createElement("span");i.textContent="\u25CF ";let a={off:["Not signed in","rgba(255,255,255,0.4)"],idle:["Up to date","#10b981"],syncing:["Syncing\u2026","#3b82f6"],offline:["Offline","#f59e0b"],error:["Retrying","#f59e0b"]},[c,l]=a[n.state]??["","#fff"];i.style.color=l,o.style.color="#fff",o.appendChild(i),o.appendChild(document.createTextNode(c));let d=document.createElement("span");return d.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums",d.textContent=n.pending>0?`${n.pending} pending`:"",d.title=n.error??"",s.appendChild(o),s.appendChild(d),t.appendChild(s),t}function _n(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Se("Active",n.active.length>0?`${n.active.length} in flight`:"\u2014")),n.active.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="No calls in flight.",t.appendChild(r),t}for(let r of n.active){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px",o.textContent=r.model;let i=document.createElement("span");i.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let a=((e-r.startedAt)/1e3).toFixed(1),c=r.tokensPerSec>0?` \xB7 ${Math.round(r.tokensPerSec)} tok/s`:"";i.textContent=`${a}s${c}`,s.appendChild(o),s.appendChild(i),t.appendChild(s)}return t}function Tn(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Se("Recent",n.recent.length>0?`last ${Math.min(n.recent.length,5)}`:"\u2014")),n.recent.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="Nothing yet this session.",t.appendChild(r),t}for(let r of n.recent.slice(0,5)){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px";let i=document.createElement("span");i.textContent=r.ok?"\u2713 ":"\u2717 ",i.style.color=r.ok?"#10b981":"#ef4444",o.appendChild(i),o.appendChild(document.createTextNode(r.model));let a=document.createElement("span");a.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let c=`${(r.latencyMs/1e3).toFixed(1)}s`,l=r.costUSD!==void 0?` \xB7 $${r.costUSD.toFixed(4)}`:"",d=` \xB7 ${Oe(e-r.endedAt)}`;a.textContent=`${c}${l}${d}`,s.appendChild(o),s.appendChild(a),t.appendChild(s)}return t}function En(n,e){let t=document.createElement("div");t.appendChild(Se("Session",Oe(e-n.startedAt)));let r=document.createElement("div");r.style.cssText="display:flex;justify-content:space-between;gap:12px;color:rgba(255,255,255,0.85);font-size:10px";let s=document.createElement("span");s.textContent=`${n.totalCalls} call${n.totalCalls===1?"":"s"}`;let o=document.createElement("span");o.textContent=`$${n.totalCostUSD.toFixed(4)}`;let i=document.createElement("span");return i.textContent=n.errorCount>0?`${n.errorCount} error${n.errorCount===1?"":"s"}`:"0 errors",n.errorCount>0&&(i.style.color="#ef4444"),r.appendChild(s),r.appendChild(o),r.appendChild(i),t.appendChild(r),t}function Se(n,e){let t=document.createElement("div");t.style.cssText=["display:flex;justify-content:space-between;align-items:baseline","margin-bottom:4px","color:rgba(255,255,255,0.55)","font-size:10px;text-transform:uppercase;letter-spacing:0.05em"].join(";");let r=document.createElement("span");r.textContent=n;let s=document.createElement("span");return s.textContent=e,s.style.cssText="font-size:9px;letter-spacing:0",t.appendChild(r),t.appendChild(s),t}function Oe(n){return n<1500?"just now":n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}var It=new WeakMap,Me=new WeakMap,Ae=new Set,N=null;function xe(n){try{return typeof structuredClone=="function"?structuredClone(n):n}catch{return n}}function Cn(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function ke(n,e,t){let r;if(e&&typeof IDBVersionChangeEvent=="function"?r=new IDBVersionChangeEvent(n,{oldVersion:e.oldVersion,newVersion:e.newVersion??null}):(r=new Event(n,{bubbles:!1,cancelable:n==="error"}),e&&Object.assign(r,e)),t)for(let s of["target","currentTarget","srcElement"])try{Object.defineProperty(r,s,{value:t,configurable:!0})}catch{}return r}var _e=class{constructor(e,t,r){u(this,"readyState","pending");u(this,"result");u(this,"error",null);u(this,"transaction",null);u(this,"source",null);u(this,"listeners",new Map);u(this,"handlers",{success:null,error:null,blocked:null,upgradeneeded:null});e.addEventListener("upgradeneeded",s=>{let o=s;this.result=e.result,this.transaction=e.transaction,Me.set(e.result,{name:t,subs:r}),this.dispatch(ke("upgradeneeded",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("blocked",s=>{let o=s;this.dispatch(ke("blocked",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("error",()=>{this.error=e.error,this.readyState="done",this.transaction=null,this.dispatch(ke("error",void 0,this))}),e.addEventListener("success",()=>{let s=e.result;Me.set(s,{name:t,subs:r}),this.transaction=null;let o=!1,i=()=>{o||(o=!0,this.result=s,this.readyState="done",this.dispatch(ke("success",void 0,this)))},a=[],c=0;for(let d of r)try{let p=d.opts.onOpen(s,t);p&&typeof p.then=="function"&&(a.push(p.catch(()=>{})),c=Math.max(c,d.opts.openTimeoutMs))}catch{}if(a.length===0){i();return}let l=setTimeout(i,c);Promise.all(a).then(()=>{clearTimeout(l),i()})})}addEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:o=>t.handleEvent(o),s=this.listeners.get(e);s||this.listeners.set(e,s=new Set),s.add(r),t.__rtFn=r}removeEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:t.__rtFn;r&&this.listeners.get(e)?.delete(r)}dispatchEvent(e){return this.dispatch(e),!e.defaultPrevented}dispatch(e){let t=this.handlers[e.type];if(t)try{t.call(this,e)}catch(r){je(r)}for(let r of this.listeners.get(e.type)??[])try{r.call(this,e)}catch(s){je(s)}}get onsuccess(){return this.handlers.success??null}set onsuccess(e){this.handlers.success=e}get onerror(){return this.handlers.error??null}set onerror(e){this.handlers.error=e}get onblocked(){return this.handlers.blocked??null}set onblocked(e){this.handlers.blocked=e}get onupgradeneeded(){return this.handlers.upgradeneeded??null}set onupgradeneeded(e){this.handlers.upgradeneeded=e}};function je(n){setTimeout(()=>{throw n},0)}typeof IDBOpenDBRequest=="function"&&Object.setPrototypeOf(_e.prototype,IDBOpenDBRequest.prototype);function Pt(n){let e=n.source;return typeof IDBIndex=="function"&&e instanceof IDBIndex?e.objectStore:e}function Bt(n,e){if(e.startsWith("__runapps"))return[];let t=[];for(let r of Ae)(r.factory===null||r.factory===n)&&r.opts.include(e)&&t.push(r);return t}function Dn(){let n=IDBFactory.prototype,e=IDBDatabase.prototype,t=IDBObjectStore.prototype,r=IDBCursor.prototype,s=N={open:n.open,deleteDatabase:n.deleteDatabase,transaction:e.transaction,put:t.put,add:t.add,get:t.get,delete:t.delete,clear:t.clear,getAllKeys:t.getAllKeys,cursorUpdate:r.update,cursorDelete:r.delete},o=i=>It.get(i.transaction)??null;n.open=function(i,a){let c=a===void 0?s.open.call(this,i):s.open.call(this,i,a),l=Bt(this,i);return l.length===0?c:new _e(c,i,l)},n.deleteDatabase=function(i){for(let a of Bt(this,i))try{a.opts.onDeleteDatabase(i)}catch{}return s.deleteDatabase.call(this,i)},e.transaction=function(i,a,c){let l=c!==void 0?s.transaction.call(this,i,a,c):a!==void 0?s.transaction.call(this,i,a):s.transaction.call(this,i),d=Me.get(this);if(d&&l.mode==="readwrite"){let p={db:d.name,subs:d.subs,ops:[]};It.set(l,p),l.addEventListener("complete",()=>{if(p.ops.length===0)return;let h=p.ops;p.ops=[];for(let f of p.subs){let g=h.filter(w=>!f.opts.excludeStore(p.db,w.store));if(g.length!==0)try{f.opts.onCommit(p.db,g)}catch(w){je(w)}}})}return l},t.put=function(i,a){let c=o(this),l=null;if(c&&Cn(i)){let p=a!==void 0?a:vt(i,this.keyPath);if(p!==void 0)try{let h=s.get.call(this,p),f=l={value:void 0};h.addEventListener("success",()=>{f.value=h.result})}catch{l=null}}let d=a===void 0?s.put.call(this,i):s.put.call(this,i,a);if(c){let p=this.name,h=xe(i),f=l;d.addEventListener("success",()=>{c.ops.push({store:p,kind:"put",key:d.result,value:h,prior:f?.value})})}return d},t.add=function(i,a){let c=a===void 0?s.add.call(this,i):s.add.call(this,i,a),l=o(this);if(l){let d=this.name,p=xe(i);c.addEventListener("success",()=>{l.ops.push({store:d,kind:"put",key:c.result,value:p})})}return c},t.delete=function(i){let a=o(this);if(a){let c=this.name;if(typeof IDBKeyRange=="function"&&i instanceof IDBKeyRange){let l=s.getAllKeys.call(this,i);l.addEventListener("success",()=>{for(let d of l.result)a.ops.push({store:c,kind:"del",key:d})})}else a.ops.push({store:c,kind:"del",key:i})}return s.delete.call(this,i)},t.clear=function(){let i=o(this),a=s.clear.call(this);if(i){let c=this.name;a.addEventListener("success",()=>{i.ops.push({store:c,kind:"clear"})})}return a},r.update=function(i){let a=Pt(this),c=o(a),l=c?xe(this.value):void 0,d=s.cursorUpdate.call(this,i);if(c){let p=a.name,h=xe(i),f=this.primaryKey;d.addEventListener("success",()=>{c.ops.push({store:p,kind:"put",key:f,value:h,prior:l})})}return d},r.delete=function(){let i=Pt(this),a=o(i);return a&&a.ops.push({store:i.name,kind:"del",key:this.primaryKey}),s.cursorDelete.call(this)}}function In(){if(!N)return;let n=N;IDBFactory.prototype.open=n.open,IDBFactory.prototype.deleteDatabase=n.deleteDatabase,IDBDatabase.prototype.transaction=n.transaction,IDBObjectStore.prototype.put=n.put,IDBObjectStore.prototype.add=n.add,IDBObjectStore.prototype.delete=n.delete,IDBObjectStore.prototype.clear=n.clear,IDBCursor.prototype.update=n.cursorUpdate,IDBCursor.prototype.delete=n.cursorDelete,N=null}function Z(n){if(typeof indexedDB>"u"||typeof IDBFactory!="function"||typeof IDBDatabase!="function"||typeof IDBObjectStore!="function"||typeof IDBCursor!="function")return null;N||Dn();let e=N,t={opts:n,factory:n.factory??indexedDB};Ae.add(t);let r=t.factory;return{originalOpen:(s,o)=>o===void 0?e.open.call(r,s):e.open.call(r,s,o),uninstall(){Ae.delete(t),Ae.size===0&&In()}}}var Rt="__runapps_sync__";function F(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("IndexedDB request failed"))})}function D(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onabort=()=>t(n.error??new Error("IndexedDB transaction aborted")),n.onerror=()=>t(n.error??new Error("IndexedDB transaction failed"))})}var ee=class{constructor(e){u(this,"open",e);u(this,"dbPromise",null)}db(){return this.dbPromise||(this.dbPromise=new Promise((e,t)=>{let r=this.open(Rt,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains("ops")||s.createObjectStore("ops",{keyPath:"id",autoIncrement:!0}).createIndex("store",["db","store"],{unique:!1}),s.objectStoreNames.contains("meta")||s.createObjectStore("meta")},r.onsuccess=()=>{let s=r.result;s.onversionchange=()=>{s.close(),this.dbPromise=null},e(s)},r.onerror=()=>t(r.error??new Error("cannot open sync log")),r.onblocked=()=>t(new Error("sync log open blocked"))}),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}async append(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.add(o);await D(r)}async pending(){let t=(await this.db()).transaction("ops","readonly");return await F(t.objectStore("ops").getAll())}async pendingCount(){let t=(await this.db()).transaction("ops","readonly");return F(t.objectStore("ops").count())}async remove(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.delete(o);await D(r)}async clearOps(){let t=(await this.db()).transaction("ops","readwrite");t.objectStore("ops").clear(),await D(t)}async getMeta(e){let r=(await this.db()).transaction("meta","readonly");return await F(r.objectStore("meta").get(e))}async setMeta(e){let r=(await this.db()).transaction("meta","readwrite"),s=r.objectStore("meta");for(let o of Object.keys(e))e[o]===void 0?s.delete(o):s.put(e[o],o);await D(r)}async metaWithPrefix(e){let s=(await this.db()).transaction("meta","readonly").objectStore("meta"),o=IDBKeyRange.bound(e,e+"\uFFFF"),i=await F(s.getAllKeys(o)),a=await F(s.getAll(o)),c=new Map;return i.forEach((l,d)=>c.set(l,a[d])),c}async clearAll(){let t=(await this.db()).transaction(["ops","meta"],"readwrite");t.objectStore("ops").clear(),t.objectStore("meta").clear(),await D(t)}close(){this.dbPromise?.then(e=>e.close()).catch(()=>{}),this.dbPromise=null}};function Ot(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!("$rt"in n)}function Pn(n,e){return JSON.stringify(n)===JSON.stringify(e)}function Bn(n,e,t){if(!n)return e;if(e.d||n.d||!Ot(n.v)||!Ot(e.v))return e.t>=n.t?e:n;let r=n.f??{},s=t?new Set(t):null,o={},i={},a=new Set([...Object.keys(n.v),...Object.keys(e.v)]);for(let c of a){let l=c in n.v,d=c in e.v,p=r[c]??n.t;if(s?!s.has(c):l&&d&&Pn(n.v[c],e.v[c])){l&&(o[c]=n.v[c],r[c]!==void 0&&(i[c]=r[c]));continue}e.t>=p?d&&(o[c]=e.v[c],i[c]=e.t):l&&(o[c]=n.v[c],i[c]=p)}return{k:e.k,v:o,t:Math.max(n.t,e.t),f:i}}var Rn=720*3600*1e3,On=1e4,Mn=5e3,jn=5*6e4,Ne=class{constructor(){u(this,"last",0);u(this,"offset",0)}now(){let e=Date.now()+this.offset;return this.last=e>this.last?e:this.last+1,this.last}observe(e,t,r){let s=(t+r)/2,o=e-s;Math.abs(o-this.offset)>2e3&&(this.offset=o)}};function Ue(n){return encodeURIComponent(n).replace(/%2F/gi,"%2F")}var I=class{constructor(e,t={}){u(this,"deps",e);u(this,"options");u(this,"log");u(this,"hook");u(this,"clock",new Ne);u(this,"schemas",new Map);u(this,"etags",new Map);u(this,"conns",new Map);u(this,"state",{state:"off",pending:0});u(this,"paused",!1);u(this,"disposed",!1);u(this,"leader",!0);u(this,"pushTimer",null);u(this,"pushDeadline",0);u(this,"pullTimer",null);u(this,"backoffMs",0);u(this,"backoffUntil",0);u(this,"chain",Promise.resolve());u(this,"cleanup",[]);u(this,"channel",null);u(this,"metaLoaded",null);u(this,"logChain",Promise.resolve());u(this,"moved",!1);this.options={databases:t.databases??[],exclude:t.exclude??[],shards:Math.max(1,Math.min(64,t.shards??8)),pushDelayMs:t.pushDelayMs??2500,pullIntervalMs:t.pullIntervalMs??6e4,openTimeoutMs:t.openTimeoutMs??5e3,prefix:(t.prefix??"db").replace(/^\/+|\/+$/g,"")};let r=new Set(this.options.exclude.filter(i=>!i.includes("/"))),s=new Set(this.options.exclude.filter(i=>i.includes("/"))),o=new Set(this.options.databases);this.hook=Z({include:i=>(o.size===0||o.has(i))&&!r.has(i),excludeStore:(i,a)=>s.has(i+"/"+a),onCommit:(i,a)=>this.onCommit(i,a),onOpen:(i,a)=>this.onOpen(i,a),onDeleteDatabase:i=>this.onDeleteDatabase(i),openTimeoutMs:this.options.openTimeoutMs,factory:e.factory}),this.log=new ee((i,a)=>this.hook?this.hook.originalOpen(i,a):indexedDB.open(i,a)),typeof window<"u"&&this.attachBrowserTriggers(),this.cleanup.push(e.onAuthChange(()=>this.schedule("auth"))),this.refreshPending(),this.schedule("start")}status(){return{...this.state}}now(){return this.enqueue(()=>this.sync())}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule("resume")}dispose(){this.disposed=!0;for(let e of this.cleanup)e();this.pushTimer&&clearTimeout(this.pushTimer),this.pullTimer&&clearInterval(this.pullTimer),this.channel?.close();for(let e of this.conns.values())e.then(t=>t.close()).catch(()=>{});this.conns.clear(),this.log.close(),this.hook?.uninstall()}onCommit(e,t){let r=[];for(let s of t){let o=this.clock.now();s.kind==="clear"?r.push({db:e,store:s.store,kind:"clear",kid:"",ts:o}):s.kind==="del"?r.push({db:e,store:s.store,kind:"del",kid:be(s.key),key:M(s.key),ts:o}):r.push({db:e,store:s.store,kind:"put",kid:be(s.key),key:M(s.key),value:s.value,changed:s.prior===void 0?void 0:wt(s.prior,s.value),ts:o})}this.enqueueLog(r)}enqueueLog(e){this.logChain=this.logChain.then(()=>this.log.append(e)).then(()=>this.refreshPending()).catch(t=>this.fail(t)),this.schedulePush()}async onOpen(e,t){let r=new Map,s=Array.from(e.objectStoreNames);if(s.length>0){let o=e.transaction(s,"readonly");for(let i of s){let a=o.objectStore(i);r.set(i,{keyPath:a.keyPath,autoIncrement:a.autoIncrement}),a.autoIncrement&&typeof console<"u"&&console.warn(`[runapps sync] "${t}/${i}" uses autoIncrement keys: records created on two devices while offline can get the same key, and only one survives. Prefer client-generated ids (e.g. crypto.randomUUID()).`)}}this.schemas.set(t,r),this.log.setMeta({["schema:"+t]:Object.fromEntries(r)}).catch(()=>{}),!(!this.deps.userId()||this.paused||!this.leader)&&await this.enqueue(()=>this.pullDatabase(t)).catch(()=>{})}onDeleteDatabase(e){let t=this.schemas.get(e),r=t?Array.from(t.keys()):[];this.schemas.delete(e),this.conns.get(e)?.then(o=>o.close()).catch(()=>{}),this.conns.delete(e);let s=this.clock.now();this.enqueueLog(r.map(o=>({db:e,store:o,kind:"clear",kid:"",ts:s})))}attachBrowserTriggers(){let e=(r,s,o)=>{r.addEventListener(s,o),this.cleanup.push(()=>r.removeEventListener(s,o))};e(window,"online",()=>{this.backoffUntil=0,this.schedule("online")}),e(window,"focus",()=>{this.schedule("focus")}),typeof document<"u"&&e(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.schedule("visible"),this.updatePullTimer()}),this.updatePullTimer(),typeof BroadcastChannel=="function"&&(this.channel=new BroadcastChannel("__runapps_db_change__"),this.channel.onmessage=r=>{let s=r.data;s&&s.source==="remote"&&this.deps.events.emit("db:change",s)});let t=navigator.locks;t&&typeof t.request=="function"&&(this.leader=!1,t.request("__runapps_sync__",()=>(this.leader=!0,this.schedule("leader"),new Promise(()=>{}))).catch(()=>{this.leader=!0}))}updatePullTimer(){let e=typeof document>"u"||document.visibilityState!=="hidden";e&&!this.pullTimer&&this.options.pullIntervalMs>0?(this.pullTimer=setInterval(()=>{this.schedule("interval")},this.options.pullIntervalMs),this.pullTimer.unref?.()):!e&&this.pullTimer&&(clearInterval(this.pullTimer),this.pullTimer=null)}schedulePush(){if(this.disposed)return;let e=Date.now();this.pushDeadline||(this.pushDeadline=e+On);let t=Math.max(0,Math.min(this.options.pushDelayMs,this.pushDeadline-e));this.pushTimer&&clearTimeout(this.pushTimer),this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.pushDeadline=0,this.schedule("push")},t),this.pushTimer.unref?.()}schedule(e){return this.disposed||this.paused||!this.leader?Promise.resolve():this.deps.userId()?Date.now()<this.backoffUntil?Promise.resolve():this.enqueue(()=>this.sync()):(this.setState({state:"off"}),Promise.resolve())}enqueue(e){let t=this.chain.then(e,e);return this.chain=t.catch(()=>{}),t}setState(e){let t={...this.state,...e};e.state&&e.state!=="error"&&delete t.error;let r=t.state!==this.state.state||t.pending!==this.state.pending||t.lastSyncedAt!==this.state.lastSyncedAt||t.lastChangeAt!==this.state.lastChangeAt||t.error!==this.state.error;this.state=t,r&&this.deps.events.emit("sync:state",{...t})}async refreshPending(){try{let e=await this.log.pendingCount();this.setState({pending:e})}catch{}}fail(e){let t=typeof navigator<"u"&&navigator.onLine===!1,r=e instanceof Error?e.message:String(e);this.backoffMs=this.backoffMs?Math.min(this.backoffMs*2,jn):Mn,this.backoffUntil=Date.now()+this.backoffMs,this.setState({state:t?"offline":"error",error:r}),!t&&typeof console<"u"&&console.warn("[runapps sync]",r)}async loadMeta(){return this.metaLoaded||(this.metaLoaded=(async()=>{for(let[e,t]of await this.log.metaWithPrefix("etag:"))this.etags.set(e.slice(5),t);for(let[e,t]of await this.log.metaWithPrefix("schema:")){let r=e.slice(7);this.schemas.has(r)||this.schemas.set(r,new Map(Object.entries(t)))}})(),this.metaLoaded.catch(()=>{this.metaLoaded=null})),this.metaLoaded}async ensureOwner(e){let t=await this.log.getMeta("owner");if(t!==e){if(t!==void 0){for(let[r,s]of this.schemas)for(let o of s.keys())this.storeExcluded(r,o)||(await this.withStore(r,o,"readwrite",i=>{i.clear()}).catch(()=>{}),this.emitChange({db:r,store:o,keys:[],cleared:!0,source:"remote"}));await this.log.clearAll(),this.etags.clear(),this.metaLoaded=null,await this.loadMeta()}await this.log.setMeta({owner:e})}}async sync(){if(this.disposed||this.paused||!this.leader)return;let e=this.deps.userId();if(!e){this.setState({state:"off"});return}this.setState({state:"syncing"}),this.moved=!1;try{await this.loadMeta(),await this.ensureOwner(e),await this.logChain,await this.push(),await this.pull(),this.backoffMs=0,this.backoffUntil=0,await this.refreshPending();let t=Date.now();this.setState({state:"idle",lastSyncedAt:t,...this.moved?{lastChangeAt:t}:{}})}catch(t){await this.refreshPending(),this.fail(t)}}storeExcluded(e,t){return this.options.exclude.includes(e+"/"+t)||this.options.exclude.includes(e)}shardPath(e,t,r){return`${this.options.prefix}/${Ue(e)}/${Ue(t)}/${r}.json`}shardOf(e){return we(e)%this.options.shards}async readShard(e){let t=Date.now(),r=await this.deps.remote.getJSON(e);if(r.status==="ok"){r.serverTime&&this.clock.observe(r.serverTime,t,Date.now());let s=r.value,o={v:1,cleared:s?.cleared??0,r:s?.r??{}};return this.etags.set(e,r.etag),{shard:o,etag:r.etag}}return this.etags.delete(e),{shard:{v:1,cleared:0,r:{}}}}async push(){let e=await this.log.pending();if(e.length===0)return;let t=new Map;for(let o of e){let i=o.db+"\0"+o.store,a=t.get(i);a||t.set(i,a=[]),a.push(o)}let r=[],s={};for(let[,o]of t){let i=o[0].db,a=o[0].store;if(this.storeExcluded(i,a)){for(let f of o)f.id!==void 0&&r.push(f.id);continue}let c=0,l=-1;o.forEach((f,g)=>{f.kind==="clear"&&(c=Math.max(c,f.ts),l=g)});let d=o.slice(l+1),p=new Map;for(let f of d){let g=this.shardOf(f.kid),w=p.get(g);w||p.set(g,w=[]),w.push(f)}let h=c>0?Array.from({length:this.options.shards},(f,g)=>g):Array.from(p.keys());for(let f of h){let g=this.shardPath(i,a,f),w=p.get(f)??[],_=await Promise.all(w.map(v=>this.encodeOp(v))),T=await this.writeShard(g,c,_);s["etag:"+g]=T}for(let f of o)f.id!==void 0&&r.push(f.id)}await this.log.setMeta(s),await this.log.remove(r),r.length>0&&(this.moved=!0),await this.refreshPending()}async encodeOp(e){if(e.kind==="del")return{kid:e.kid,rec:{k:e.key,v:null,t:e.ts,d:1}};let t=await x(e.value,r=>this.storeBlob(r));return{kid:e.kid,rec:{k:e.key,v:t,t:e.ts},changed:e.changed}}async writeShard(e,t,r){for(let s=0;s<5;s++){let{shard:o,etag:i}=await this.readShard(e),a=this.clock.now();if(t>o.cleared){o.cleared=t;for(let d of Object.keys(o.r))o.r[d].t<=t&&delete o.r[d]}for(let{kid:d,rec:p,changed:h}of r)p.t<=o.cleared||(o.r[d]=Bn(o.r[d],p,h));for(let d of Object.keys(o.r)){let p=o.r[d];p.d&&a-p.t>Rn&&delete o.r[d]}let c=Date.now(),l=await this.deps.remote.putJSON(e,o,i?{ifMatch:i}:{ifNoneMatch:!0});if(l.status==="ok")return l.serverTime&&this.clock.observe(l.serverTime,c,Date.now()),this.etags.set(e,l.etag),l.etag;this.etags.delete(e)}throw new Error(`could not write ${e}: too many concurrent writers`)}async storeBlob(e){let t=new Uint8Array(await e.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",t),s=Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join(""),o=`${this.options.prefix}/_blobs/${s}`;return await this.deps.remote.putBlob(o,e),{ref:o,type:e.type,size:e.size}}async pull(){let e=await this.deps.remote.list(this.options.prefix+"/");await this.applyListing(e)}async pullDatabase(e){if(!this.deps.userId())return;await this.loadMeta();let t=await this.deps.remote.list(`${this.options.prefix}/${Ue(e)}/`);await this.applyListing(t)}async applyListing(e){let t=new RegExp("^"+this.options.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/([^/]+)/([^/]+)/(\\d+)\\.json$"),r=await this.log.pending(),s={};for(let o of e){let i=t.exec(o.path);if(!i)continue;let a=decodeURIComponent(i[1]),c=decodeURIComponent(i[2]);if(this.etags.get(o.path)===o.etag||this.storeExcluded(a,c))continue;let l=this.schemas.get(a);if(!l||!l.has(c))continue;let d=await this.deps.remote.getJSON(o.path,this.etags.get(o.path));if(d.status==="unchanged")continue;if(d.status==="missing"){this.etags.delete(o.path),s["etag:"+o.path]=void 0;continue}let p=d.value,h={v:1,cleared:p?.cleared??0,r:p?.r??{}};await this.applyShard(a,c,h,r),this.etags.set(o.path,d.etag),s["etag:"+o.path]=d.etag}Object.keys(s).length&&await this.log.setMeta(s)}async applyShard(e,t,r,s){let o=new Map,i=0;for(let h of s)h.db!==e||h.store!==t||(h.kind==="clear"?i=Math.max(i,h.ts):o.set(h.kid,Math.max(o.get(h.kid)??0,h.ts)));let a=`cleared:${e}/${t}`,c=await this.log.getMeta(a)??0,l=this.schemas.get(e)?.get(t),d=[],p=!1;await this.withStore(e,t,"readwrite",h=>{r.cleared>c&&r.cleared>i&&(h.clear(),p=!0);for(let f of Object.keys(r.r)){let g=r.r[f];if((o.get(f)??0)>=g.t||g.t<=i)continue;let w=X(g.k);if(d.push(w),g.d)h.delete(w);else{let _=g._decoded;l&&l.keyPath!==null?h.put(_):h.put(_,w)}}if(p)for(let f of s)f.db!==e||f.store!==t||f.kind!=="put"||f.ts<=r.cleared||(l&&l.keyPath!==null?h.put(f.value):h.put(f.value,X(f.key)))},async()=>{for(let h of Object.keys(r.r)){let f=r.r[h];f.d||(o.get(h)??0)>=f.t||f.t<=i||(f._decoded=await k(f.v,g=>this.deps.remote.getBlob(g.ref)))}}),r.cleared>c&&await this.log.setMeta({[a]:r.cleared}),(d.length>0||p)&&this.emitChange({db:e,store:t,keys:d,cleared:p,source:"remote"})}emitChange(e){this.moved=!0,this.deps.events.emit("db:change",e);try{this.channel?.postMessage(e)}catch{}}conn(e){let t=this.conns.get(e);return t||(t=new Promise((r,s)=>{let i=(this.hook?this.hook.originalOpen:a=>indexedDB.open(a))(e);i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>{a.close(),this.conns.delete(e)},r(a)},i.onerror=()=>s(i.error??new Error(`cannot open ${e}`)),i.onblocked=()=>s(new Error(`open of ${e} blocked`))}),this.conns.set(e,t),t.catch(()=>this.conns.delete(e))),t}async withStore(e,t,r,s,o){o&&await o();let i=await this.conn(e);if(!i.objectStoreNames.contains(t))return;let a=i.transaction(t,r);s(a.objectStore(t)),await D(a)}};var P=class{constructor(e){u(this,"files",e)}async list(e){let t=[],r;do{let s=await this.files.list({prefix:e,limit:1e3,...r?{cursor:r}:{}});for(let o of s.files)o.etag&&t.push({path:o.path,etag:o.etag});r=s.next_cursor}while(r);return t}async getJSON(e,t){let r=await this.files.readJSON(e,t?{ifNoneMatch:t}:void 0);return r.notModified?{status:"unchanged"}:r.value===void 0?{status:"missing"}:{status:"ok",value:r.value,etag:r.etag??""}}async putJSON(e,t,r){try{let s=await this.files.put(e,JSON.stringify(t),{contentType:"application/json",...r.ifMatch?{ifMatch:r.ifMatch}:{},...r.ifNoneMatch?{ifNoneMatch:!0}:{}});return{status:"ok",etag:s.etag??"",serverTime:s.last_modified?Date.parse(s.last_modified):void 0}}catch(s){let o=s.statusCode;if(o===412||o===409)return{status:"conflict"};throw s}}async putBlob(e,t){try{await this.files.put(e,t,{contentType:t.type||"application/octet-stream",ifNoneMatch:!0})}catch(r){if(r.statusCode!==409)throw r}}getBlob(e){return this.files.get(e)}};var Un="https://www.runapps.ai",L=class{constructor(e={}){u(this,"chat");u(this,"models");u(this,"image");u(this,"audio");u(this,"video");u(this,"computer");u(this,"files");u(this,"embeddings");u(this,"auth",null);u(this,"sync",null);u(this,"events",new R);let t=e.authProvider??(!e.apiKey&&!e.apiKeyResolver&&typeof window<"u"?"runapps":"static"),r=e.apiKeyResolver,s=e.baseURL,o;if(t==="runapps"||t==="runjobs"){s=s??"https://www.runapps.ai";let c=e.showIdentityBadge!==void 0?e.showIdentityBadge:e.hideIdentityBadge!==void 0?!e.hideIdentityBadge:!0,l=new U({origin:s,hideBadge:!c,events:this.events,...e.badgePosition!==void 0&&{badgePosition:e.badgePosition},...e.project!==void 0&&{project:e.project}});this.auth=l,r=l.getToken,o=()=>l.invalidate()}if(!e.apiKey&&!r)throw new Error("runapps: pass `apiKey` (or `apiKeyResolver`); outside a browser there is no sign-in to fall back to");let i=new ae({baseURL:s??Un,...e.apiKey!==void 0&&{apiKey:e.apiKey},...r!==void 0&&{apiKeyResolver:r},...o!==void 0&&{onUnauthorized:o},...e.fetch?{fetchImpl:e.fetch}:{}});this.chat=new ce(i,this.events),this.models=new le(i),this.image=new ue(i,this.events),this.audio=new de(i,this.events),this.video=new fe(i,this.events),this.computer=new he(i,this.events),this.files=new Y(i,e.project,this.events),this.embeddings=new ge(i,this.events);let a=e.sync??this.auth!==null;if(a&&typeof indexedDB<"u"&&this.auth){let c=this.auth,l=new I({remote:new P(new Y(i,e.project)),events:this.events,userId:()=>c.ownerId(),onAuthChange:d=>c.onTokenChange(()=>d())},typeof a=="object"?a:{});this.sync=l}}signIn(){this.auth?.signIn()}signOut(){this.auth?.signOut()}get user(){return this.auth?.user??null}};function Mt(n){return n?n.map(e=>Array.isArray(e)?{fields:e}:e):[]}function te(n){let e=n.options;return!e||typeof e!="object"?null:e}function jt(n,e){let r=te(n)?.inputs?.[e];return r?r.presence!=="forbidden":!1}function Ut(n,e){return te(n)?.inputs?.[e]?.presence==="required"}function Nt(n,e){return te(n)?.inputs?.[e]?.enum??null}function Kt(n,e={}){if(!n)return[];let t=[];if(n.inputs)for(let[r,s]of Object.entries(n.inputs)){let o=r in e,i=e[r];o&&!A(i)?t.push(...$t(r,s,i)):o&&s.min_items!==void 0&&Array.isArray(i)&&i.length<s.min_items&&t.push({field:r,reason:`at least ${s.min_items} items`}),t.push(...Vt(r,s,i,o))}for(let r of n.constraints??[])t.push(...Nn(r,e));return t}function $t(n,e,t){let r=[];if(!Fn(e.type,t))return r.push({field:n,reason:`expected type ${e.type}, got ${Te(t)}`}),r;if(e.enum&&e.enum.length>0&&!Ln(t,e.enum)&&r.push({field:n,reason:`must be one of ${JSON.stringify(e.enum)}`}),e.type==="int"||e.type==="float"){let s=qt(t);s!==null&&(e.min!==void 0&&s<e.min&&r.push({field:n,reason:`must be >= ${e.min}`}),e.max!==void 0&&s>e.max&&r.push({field:n,reason:`must be <= ${e.max}`}))}return Array.isArray(t)&&(e.max_items!==void 0&&t.length>e.max_items&&r.push({field:n,reason:`at most ${e.max_items} items`}),e.min_items!==void 0&&t.length<e.min_items&&r.push({field:n,reason:`at least ${e.min_items} items`})),e.fields&&(e.repeatable?Array.isArray(t)?t.forEach((s,o)=>{if(typeof s!="object"||s===null||Array.isArray(s)){r.push({field:`${n}[${o}]`,reason:`expected object, got ${Te(s)}`});return}r.push(...Ft(`${n}[${o}]`,e.fields,s))}):r.push({field:n,reason:`expected array of objects, got ${Te(t)}`}):typeof t!="object"||t===null||Array.isArray(t)?r.push({field:n,reason:`expected object, got ${Te(t)}`}):r.push(...Ft(n,e.fields,t))),r}function Ft(n,e,t){let r=[];for(let[s,o]of Object.entries(e)){let i=`${n}.${s}`,a=t[s],c=s in t;c&&!A(a)&&r.push(...$t(i,o,a)),r.push(...Vt(i,o,a,c))}return r}function Vt(n,e,t,r){let s=e.presence??"optional";return s==="required"&&(!r||A(t))?[{field:n,reason:"required"}]:s==="forbidden"&&r&&!A(t)?[{field:n,reason:"must not be set for this model"}]:[]}function Nn(n,e){switch(n.kind){case"any_of_required":{let t=n.fields??[];return t.some(s=>s in e&&!A(e[s]))?[]:[{field:t.join("/"),reason:`at least one of ${t.join(", ")} is required`}]}case"mutually_exclusive":{let t=n.fields??[],r=t.filter(s=>s in e&&!A(e[s]));return r.length>1?[{field:r.join("/"),reason:`at most one of ${t.join(", ")} may be set (got: ${r.join(", ")})`}]:[]}case"group_mutex":{let t=Mt(n.groups),r=[],s=[];for(let o of t){let i=o.fields.filter(a=>a in e&&!A(e[a]));i.length>0&&(r.push(o),s.push(...i))}if(r.length>1){let o=t.map(i=>`[${i.fields.join("+")}]`).join(" or ");return[{field:s.join("/"),reason:`at most one of ${o} may be used (got: ${s.join(", ")})`}]}return[]}case"requires_all":{let t=n.when;if(!t)return[];if(!(t in e&&!A(e[t])))return[];let s=(n.then??[]).filter(o=>!(o in e)||A(e[o]));return s.length===0?[]:[{field:s.join("/"),reason:`required when ${t} is set`}]}case"pixel_bounds":{let t=n.fields?.[0];if(!t)return[];let r=e[t];if(typeof r!="string"||r==="")return[];let s=$n(r);if(!s)return[{field:t,reason:`expected WxH dimensions, got "${r}"`}];let[o,i]=s,a=o*i,c=[];return n.min!==void 0&&a<n.min&&c.push({field:t,reason:`image too small: ${o}x${i} = ${a} pixels, minimum ${n.min}`}),n.max!==void 0&&a>n.max&&c.push({field:t,reason:`image too large: ${o}x${i} = ${a} pixels, maximum ${n.max}`}),c}}return[]}function Fn(n,e){switch(n){case"string":return typeof e=="string";case"int":case"float":return qt(e)!==null;case"bool":return typeof e=="boolean";case"url":return typeof e=="string"&&Lt(e);case"url[]":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&Lt(t));case"string[]":return Array.isArray(e)&&e.every(t=>typeof t=="string");case"file":return!0;default:return!0}}function Te(n){return n===null?"null":Array.isArray(n)?"array":typeof n}function qt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Lt(n){return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")}function A(n){return n==null?!0:typeof n=="string"?n==="":Array.isArray(n)?n.length===0:!1}function Ln(n,e){for(let t of e)if(Kn(n,t))return!0;return!1}function Kn(n,e){return n===e}function $n(n){for(let e of["x","X","*","\xD7"]){let t=n.indexOf(e);if(t<=0)continue;let r=parseInt(n.slice(0,t).trim(),10),s=parseInt(n.slice(t+e.length).trim(),10);if(Number.isFinite(r)&&Number.isFinite(s)&&r>0&&s>0)return[r,s]}return null}return Xt(Vn);})();
|
|
3
|
+
`))!==-1;){let a=r.slice(0,i).replace(/\r$/,"");if(r=r.slice(i+1),!a.startsWith("data: "))continue;let c=a.slice(6).trim();if(c==="[DONE]")return;if(!c)continue;let l;try{l=JSON.parse(c)}catch(p){throw new Error(`runapps: decode stream chunk: ${p.message}`)}let d=l.error;if(d)throw new C(d.code??0,d.type??"upstream_error",d.message??c);yield l}}}finally{t.releaseLock()}}var at=(n,e)=>Array.isArray(n.capability_tags)&&n.capability_tags.some(t=>t.id===e),ct=(n,e)=>Array.isArray(n.input_modalities)&&n.input_modalities.includes(e);function lt(n,e){let t=n.options?.[e];return typeof t=="boolean"?t:typeof t=="number"?t!==0:!1}var ut=n=>lt(n,"supports_voice_clone"),dt=n=>lt(n,"supports_instruct_text"),pt=n=>{let e=n.options?.default_voice;return typeof e=="string"?e:null},le=class{constructor(e){u(this,"transport",e)}async list(e={},t){let r="/v1/models";return e.capability&&(r+=`?capability=${encodeURIComponent(e.capability)}`),(await this.transport.getPublicJSON(r,t)).data}};var ue=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return y(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/images/generations",{model:e,...t},r),s=>({costUSD:s.usage?.total_cost}))}async generateAsync(e,t,r){let s=r?.pollIntervalMs??2e3,o=r?.signal;return y(this.events,{model:e,capability:"image_generation"},async()=>{let a=await this.transport.postJSON("/v1/async/images/generations",{model:e,...t},{signal:o});for(;a.status!=="succeeded"&&a.status!=="failed";)await tn(s,o),a=await this.getAsyncStatus(a.id,{signal:o});if(a.status==="failed")throw new Error(a.error??"image generation failed");return{created:a.created_at??Math.floor(Date.now()/1e3),data:a.data??[],usage:a.usage??{total_cost:0}}},i=>({costUSD:i.usage?.total_cost}))}async submitGenerate(e,t,r){return y(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/async/images/generations",{model:e,...t},r))}async getAsyncStatus(e,t){return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(e)}`,t)}async edit(e,t,r){let s=nn(e,t);return y(this.events,{model:e,capability:"image_edit"},()=>this.transport.postMultipart("/v1/images/edits",s,r),o=>({costUSD:o.usage?.total_cost}))}};function tn(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}function nn(n,e){let t=new FormData;return t.set("model",n),t.set("prompt",typeof e.prompt=="string"?e.prompt:JSON.stringify(e.prompt)),e.size&&t.set("size",e.size),e.n!==void 0&&t.set("n",String(e.n)),e.user&&t.set("user",e.user),t.set("image",ft(e.image),e.image.filename),e.mask&&t.set("mask",ft(e.mask),e.mask.filename),t}function ft(n){let e=n.contentType??rn(n.filename);return n.data instanceof Blob?n.data.type===e?n.data:new Blob([n.data],{type:e}):typeof n.data=="string"?new Blob([n.data],{type:e}):new Blob([n.data],{type:e})}function rn(n){switch(n.toLowerCase().split(".").pop()??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"webp":return"image/webp";case"gif":return"image/gif";default:return"application/octet-stream"}}function ht(n){if(n instanceof Blob)throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");let e=n instanceof Uint8Array?n:new Uint8Array(n),t=on(e),r=32768,s="";for(let i=0;i<e.length;i+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(i,i+r)));let o=globalThis.btoa?globalThis.btoa(s):Buffer.from(s,"binary").toString("base64");return`data:${t};base64,${o}`}async function z(n){if(n.startsWith("data:")){let e=n.slice(5),t=e.indexOf(";"),r=e.indexOf(",");if(t===-1||r===-1||r<t)throw new Error("decodeMediaUrl: malformed data URI");let s=e.slice(0,t),o=e.slice(r+1);return{bytes:sn(o),contentType:s}}if(n.startsWith("http://")||n.startsWith("https://")){let e=await fetch(n);if(!e.ok)throw new Error(`decodeMediaUrl: upstream ${e.status}`);let t=await e.arrayBuffer();return{bytes:new Uint8Array(t),contentType:e.headers.get("Content-Type")??""}}throw new Error(`decodeMediaUrl: unsupported url scheme: ${n.slice(0,32)}`)}function sn(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function on(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=6&&n[0]===71&&n[1]===73&&n[2]===70&&n[3]===56?"image/gif":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":"application/octet-stream"}var de=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async speech(e,t,r){return y(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/audio/speech",gt(e,t),r),{bytes:o,contentType:i}=await z(s.audio_url);return{data:o,contentType:i,usage:s.usage}},s=>({costUSD:s.usage?.total_cost}))}async speechAsync(e,t,r){return y(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/async/audio/speech",gt(e,t),r);if(!s.id)throw new Error("runapps: speech submit response missing job id");return an(this.transport,s.id,r)},s=>({costUSD:s.usage?.total_cost}))}async transcribe(e,t,r){let s=mt(e,t);return y(this.events,{model:e,capability:"speech_to_text"},()=>this.transport.postMultipart("/v1/audio/transcriptions",s,r),o=>({costUSD:o.usage?.total_cost}))}async transcribeAsync(e,t,r){return y(this.events,{model:e,capability:"speech_to_text"},async()=>{let s=mt(e,t),o=await this.transport.postMultipart("/v1/async/audio/transcriptions",s,r);if(!o.id)throw new Error("runapps: transcribe submit response missing job id");return cn(this.transport,o.id,r)},s=>({costUSD:s.usage?.total_cost}))}};async function an(n,e,t){let r=`/v1/async/audio/speech/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await pe(2e3,t?.signal);let i=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("speech poll aborted","AbortError");if(!t?.signal&&Date.now()>i)throw new Error("runapps: speech job timed out (10 min internal cap)");let a=await n.getJSON(r,t);if(a.status==="succeeded"){if(!a.audio_url)throw new Error("runapps: speech job succeeded but no audio_url returned");let{bytes:c,contentType:l}=await z(a.audio_url);return{data:c,contentType:l,usage:a.usage??{total_cost:0}}}if(a.status==="failed")throw new Error(a.error||"runapps: speech job failed");await pe(s,t?.signal)}}async function cn(n,e,t){let r=`/v1/async/audio/transcriptions/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await pe(2e3,t?.signal);let o=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("transcribe poll aborted","AbortError");if(!t?.signal&&Date.now()>o)throw new Error("runapps: transcribe job timed out (10 min internal cap)");let i=await n.getJSON(r,t);switch(i.status){case"succeeded":return ln(i);case"failed":throw new Error(i.error||"runapps: transcribe job failed");case"queued":case"running":await pe(s,t?.signal);break;default:throw new Error(`runapps: unknown transcribe job status ${JSON.stringify(i.status)}`)}}}function ln(n){let e={text:n.text??"",usage:n.usage??{total_cost:0}},t={};for(let[r,s]of Object.entries(n))r==="text"||r==="usage"||r==="id"||r==="status"||(t[r]=s);return Object.keys(t).length>0&&(e.raw=t),e}function pe(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new DOMException("aborted","AbortError"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",o,{once:!0})})}function gt(n,e){let{extra:t,...r}=e,s={model:n,...r};if(t)for(let[o,i]of Object.entries(t))o in s||(s[o]=i);return s}function mt(n,e){let t=new FormData;if(t.set("model",n),e.language&&t.set("language",e.language),e.prompt&&t.set("prompt",e.prompt),e.response_format&&t.set("response_format",e.response_format),e.timestamp_granularities)for(let o of e.timestamp_granularities)t.append("timestamp_granularities[]",o);e.user&&t.set("user",e.user);let r=e.file.contentType??un(e.file.filename),s=e.file.data instanceof Blob?e.file.data:new Blob([e.file.data],{type:r});return t.set("file",s,e.file.filename),t}function un(n){switch(n.toLowerCase().split(".").pop()??""){case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"flac":return"audio/flac";case"ogg":return"audio/ogg";case"webm":return"audio/webm";default:return"application/octet-stream"}}var fe=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return y(this.events,{model:e,capability:"video_generation"},()=>this.transport.postJSON("/v1/videos/generations",{model:e,...t},r))}async getStatus(e,t){return this.transport.getJSON(`/v1/videos/generations/${encodeURIComponent(e)}`,t)}async wait(e,t={}){let r=t.pollIntervalMs??5e3;for(;;){let s=await this.getStatus(e,{signal:t.signal});if(s.status==="succeeded"||s.status==="failed")return s;await dn(r,t.signal)}}async getContent(e,t){return this.transport.getRaw(`/v1/videos/${encodeURIComponent(e)}/content`,t)}};function dn(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}var he=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async step(e,t,r){return y(this.events,{model:e,capability:"computer_use"},()=>this.transport.postJSON("/v1/computer/step",{model:e,...t},r),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost}))}};function W(n,e){let t=e.replace(/^\/+/,"");return n+"/"+t.split("/").map(encodeURIComponent).join("/")}var Y=class{constructor(e,t,r){u(this,"transport",e);u(this,"events",r);u(this,"base");this.base=t?"/v1/p/"+encodeURIComponent(t)+"/files":"/v1/files"}run(e,t){return this.events?y(this.events,{model:e,capability:"files"},t):t()}async put(e,t,r){let s={};return r?.ifNoneMatch&&(s["If-None-Match"]="*"),r?.ifMatch&&(s["If-Match"]=`"${r.ifMatch.replace(/"/g,"")}"`),this.run("files.put",()=>this.transport.putBytes(W(this.base,e),t,{contentType:r?.contentType,headers:Object.keys(s).length?s:void 0,signal:r?.signal}))}async putString(e,t,r){return this.put(e,t,{...r,contentType:r?.contentType??"text/plain; charset=utf-8"})}async get(e,t){return(await this.read(e,t)).blob}async read(e,t){return this.run("files.read",()=>this.readRaw(e,t))}async readRaw(e,t){let{data:r,contentType:s,etag:o,notModified:i}=await this.transport.getRaw(W(this.base,e),t);return{blob:new Blob([new Uint8Array(r)],{type:s||"application/octet-stream"}),contentType:s,etag:o,...i?{notModified:!0}:{}}}async readJSON(e,t){let r;try{r=await this.read(e,t)}catch(s){if(s?.statusCode===404||s?.status===404)return{value:void 0,etag:void 0};throw s}return r.notModified?{value:void 0,etag:r.etag,notModified:!0}:{value:JSON.parse(await r.blob.text()),etag:r.etag}}async stat(e,t){let{status:r,headers:s}=await this.run("files.stat",()=>this.transport.head(W(this.base,e),t));if(r===404)throw Object.assign(new Error("not found"),{status:404});if(r>=400)throw Object.assign(new Error("stat failed"),{status:r});let o=parseInt(s.get("content-length")??"0",10);return{path:s.get("x-file-path")??e,size:o,content_type:s.get("content-type")??void 0,etag:(s.get("etag")??"").replace(/"/g,"")||void 0,url:s.get("x-file-url")??""}}async exists(e,t){let{status:r}=await this.run("files.exists",()=>this.transport.head(W(this.base,e),t));return r>=200&&r<400}async del(e,t){await this.run("files.del",()=>this.transport.deletePath(W(this.base,e),t))}async list(e){let t=new URLSearchParams;e?.prefix&&t.set("prefix",e.prefix),e?.cursor&&t.set("cursor",e.cursor),e?.limit&&t.set("limit",String(e.limit)),e?.glob&&t.set("glob",e.glob);let r=t.toString();return this.run("files.list",()=>this.transport.getJSON(this.base+(r?"?"+r:""),e?.signal?{signal:e.signal}:void 0))}async deleteMany(e,t){return this.run("files.deleteMany",()=>this.transport.postJSON(this.base+"/delete",{prefix:e.prefix??"",glob:e.glob??""},t))}async move(e,t,r){return this.run("files.move",()=>this.transport.postJSON(this.base+"/move",{from:e,to:t},r))}async copy(e,t,r){return this.run("files.copy",()=>this.transport.postJSON(this.base+"/copy",{from:e,to:t},r))}async putFromURL(e,t,r){return this.run("files.putFromURL",()=>this.transport.postJSON(this.base+"/put-url",{path:e,src_url:t,content_type:r?.contentType,if_none_match:r?.ifNoneMatch,if_match:r?.ifMatch},r?.signal?{signal:r.signal}:void 0))}async batch(e,t){return e.length===0?[]:this.run("files.batch",()=>this.batchRaw(e,t))}async batchRaw(e,t){if(e.length<=30)return(await this.transport.postJSON(this.base+"/batch",{ops:e},t)).results;let s=[];for(let o=0;o<e.length;o+=30){let i=e.slice(o,o+30),a=await this.transport.postJSON(this.base+"/batch",{ops:i},t);s.push(...a.results)}return s}};var ge=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async create(e,t,r){return y(this.events,{model:e,capability:"embedding"},()=>this.transport.postJSON("/v1/embeddings",{model:e,...t},r),s=>({totalTokens:s.usage?.total_tokens,costUSD:s.usage?.total_cost}))}};var O=class{constructor(){u(this,"active",new Map);u(this,"recent",[]);u(this,"session",{totalCalls:0,totalCostUSD:0,errorCount:0,startedAt:Date.now()});u(this,"lastErrorAt",0);u(this,"changeListeners",new Set);u(this,"sync")}attach(e){let t=[e.on("request:start",r=>{this.onStart(r),this.notify()}),e.on("request:streamDelta",r=>{this.onDelta(r),this.notify()}),e.on("request:end",r=>{this.onEnd(r),this.notify()}),e.on("request:error",r=>{this.onError(r),this.notify()}),e.on("sync:state",r=>{this.sync={...r},this.notify()})];return()=>{for(let r of t)r()}}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}notify(){for(let e of this.changeListeners)try{e()}catch(t){console.error("[runapps sdk] ActivityTracker onChange listener threw:",t)}}snapshot(){let e=Date.now();return{active:Array.from(this.active.values()),recent:this.recent.slice(),session:{...this.session},...this.sync?{sync:{...this.sync}}:{},status:e-this.lastErrorAt<3e4?"error":this.active.size>0?"active":"idle"}}onStart(e){this.active.set(e.id,{id:e.id,model:e.model,capability:e.capability,startedAt:e.startedAt,streaming:e.streaming,tokensSoFar:0,tokensPerSec:0,rateSamples:[]})}onDelta(e){let t=this.active.get(e.id);if(!t)return;t.tokensSoFar=e.totalTokens;let r=Date.now();t.rateSamples.push({t:r,tokens:e.deltaTokens});let s=r-1500;for(;t.rateSamples.length>0&&t.rateSamples[0].t<s;)t.rateSamples.shift();if(t.rateSamples.length>=2){let o=t.rateSamples.reduce((a,c)=>a+c.tokens,0),i=r-t.rateSamples[0].t;t.tokensPerSec=i>0?o*1e3/i:0}}onEnd(e){let t=this.active.get(e.id);this.active.delete(e.id),e.capability!=="files"&&(this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:e.totalTokens||t?.tokensSoFar||0,...e.costUSD!==void 0&&{costUSD:e.costUSD},...e.finishReason!==void 0&&{finishReason:e.finishReason},ok:!0,endedAt:Date.now()}),this.session.totalCalls+=1,e.costUSD!==void 0&&(this.session.totalCostUSD+=e.costUSD))}onError(e){let t=this.active.get(e.id);if(this.active.delete(e.id),e.capability==="files"){e.statusCode!==404&&(this.lastErrorAt=Date.now());return}this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:t?.tokensSoFar||0,ok:!1,errorMessage:e.error.message,endedAt:Date.now()}),this.session.totalCalls+=1,this.session.errorCount+=1,this.lastErrorAt=Date.now()}pushRecent(e){this.recent.unshift(e),this.recent.length>20&&(this.recent.length=20)}};var yt={ArrayBuffer:n=>n,Uint8Array:n=>new Uint8Array(n),Int8Array:n=>new Int8Array(n),Uint8ClampedArray:n=>new Uint8ClampedArray(n),Int16Array:n=>new Int16Array(n),Uint16Array:n=>new Uint16Array(n),Int32Array:n=>new Int32Array(n),Uint32Array:n=>new Uint32Array(n),Float32Array:n=>new Float32Array(n),Float64Array:n=>new Float64Array(n),BigInt64Array:n=>new BigInt64Array(n),BigUint64Array:n=>new BigUint64Array(n),DataView:n=>new DataView(n)};function ye(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function bt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Pe(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}async function x(n,e){if(n===void 0)return{$rt:"undef"};if(n===null)return null;switch(typeof n){case"string":case"boolean":return n;case"number":return Number.isNaN(n)?{$rt:"num",v:"NaN"}:n===1/0?{$rt:"num",v:"Infinity"}:n===-1/0?{$rt:"num",v:"-Infinity"}:Object.is(n,-0)?{$rt:"num",v:"-0"}:n;case"bigint":return{$rt:"bigint",v:n.toString()};case"function":case"symbol":throw new TypeError(`runapps sync: ${typeof n} values cannot be stored`)}if(n instanceof Date){let r=n.getTime();return{$rt:"date",v:Number.isNaN(r)?"invalid":r}}if(n instanceof RegExp)return{$rt:"re",s:n.source,f:n.flags};if(typeof Blob<"u"&&n instanceof Blob){if(!e)throw new TypeError("runapps sync: Blob values need a blob sink");let r=await e(n),s={$rt:"blob",r:r.ref,t:r.type,s:r.size},o=n;return typeof File<"u"&&n instanceof File&&(s.n=o.name,s.m=o.lastModified),s}if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ye(new Uint8Array(n))};if(ArrayBuffer.isView(n)){let r=n.constructor.name;if(!(r in yt))throw new TypeError(`runapps sync: unsupported binary type ${r}`);let s=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return{$rt:"bin",c:r,v:ye(s)}}if(n instanceof Map){let r=[];for(let[s,o]of n)r.push([await x(s,e),await x(o,e)]);return{$rt:"map",v:r}}if(n instanceof Set){let r=[];for(let s of n)r.push(await x(s,e));return{$rt:"set",v:r}}if(Array.isArray(n)){let r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=await x(n[s],e);return r}if(Pe(n)){let r=Object.prototype.hasOwnProperty.call(n,"$rt"),s={};for(let o of Object.keys(n))s[o]=await x(n[o],e);return r?{$rt:"obj",v:s}:s}let t={};for(let r of Object.keys(n))t[r]=await x(n[r],e);return t}async function k(n,e){if(n===null||typeof n!="object")return n;if(Array.isArray(n)){let o=new Array(n.length);for(let i=0;i<n.length;i++)o[i]=await k(n[i],e);return o}let t=n;if(typeof t.$rt=="string"){let o=t;switch(o.$rt){case"undef":return;case"date":return o.v==="invalid"?new Date(NaN):new Date(o.v);case"num":return o.v==="NaN"?NaN:o.v==="Infinity"?1/0:o.v==="-Infinity"?-1/0:-0;case"bigint":return BigInt(o.v);case"re":return new RegExp(o.s,o.f);case"bin":{let i=bt(o.v),a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i);let c=yt[o.c];if(!c)throw new TypeError(`runapps sync: unsupported binary type ${o.c}`);return c(a)}case"map":{let i=new Map;for(let a of o.v)i.set(await k(a[0],e),await k(a[1],e));return i}case"set":{let i=new Set;for(let a of o.v)i.add(await k(a,e));return i}case"blob":{if(!e)throw new TypeError("runapps sync: Blob values need a blob source");let i=await e({ref:o.r,type:o.t,size:o.s});return o.n!==void 0&&typeof File<"u"?new File([i],o.n,{type:o.t,lastModified:o.m??Date.now()}):i}case"obj":return k(o.v,e)}}let s={};for(let o of Object.keys(t))s[o]=await k(t[o],e);return s}function M(n){if(typeof n=="number"){if(Number.isNaN(n))throw new TypeError("runapps sync: NaN is not a valid key");return n}if(typeof n=="string")return n;if(n instanceof Date)return{$rt:"date",v:n.getTime()};if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ye(new Uint8Array(n))};if(ArrayBuffer.isView(n))return{$rt:"bin",c:"ArrayBuffer",v:ye(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))};if(Array.isArray(n))return n.map(e=>M(e));throw new TypeError("runapps sync: invalid IndexedDB key")}function X(n){if(typeof n=="number"||typeof n=="string")return n;if(Array.isArray(n))return n.map(X);if(n&&typeof n=="object"){let e=n;if(e.$rt==="date")return new Date(e.v);if(e.$rt==="bin"){let t=bt(e.v),r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),r}}throw new TypeError("runapps sync: invalid encoded key")}function be(n){return JSON.stringify(M(n))}function we(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function me(n,e){if(Object.is(n,e))return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;if(n instanceof Date||e instanceof Date)return n instanceof Date&&e instanceof Date&&Object.is(n.getTime(),e.getTime());if(typeof Blob<"u"&&(n instanceof Blob||e instanceof Blob))return!1;if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof ArrayBuffer){let s=a=>a instanceof ArrayBuffer?new Uint8Array(a):ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):null,o=s(n),i=s(e);if(!o||!i||o.length!==i.length||n.constructor!==e.constructor)return!1;for(let a=0;a<o.length;a++)if(o[a]!==i[a])return!1;return!0}if(n instanceof Map||e instanceof Map){if(!(n instanceof Map&&e instanceof Map)||n.size!==e.size)return!1;for(let[s,o]of n)if(!e.has(s)||!me(o,e.get(s)))return!1;return!0}if(n instanceof Set||e instanceof Set){if(!(n instanceof Set&&e instanceof Set)||n.size!==e.size)return!1;for(let s of n)if(!e.has(s))return!1;return!0}if(Array.isArray(n)||Array.isArray(e)){if(!(Array.isArray(n)&&Array.isArray(e))||n.length!==e.length)return!1;for(let s=0;s<n.length;s++)if(!me(n[s],e[s]))return!1;return!0}let t=Object.keys(n),r=Object.keys(e);if(t.length!==r.length)return!1;for(let s of t)if(!Object.prototype.hasOwnProperty.call(e,s)||!me(n[s],e[s]))return!1;return!0}function wt(n,e){if(!Pe(n)||!Pe(e))return;let t=[];for(let r of new Set([...Object.keys(n),...Object.keys(e)])){let s=Object.prototype.hasOwnProperty.call(n,r),o=Object.prototype.hasOwnProperty.call(e,r);(s!==o||!me(n[r],e[r]))&&t.push(r)}return t}function vt(n,e){if(e==null)return;let t=s=>{let o=n;if(s==="")return o;for(let i of s.split(".")){if(o===null||typeof o!="object")return;o=o[i]}return o};if(Array.isArray(e)){let s=e.map(t);return s.some(o=>o===void 0)?void 0:s}let r=t(e);return r===void 0?void 0:r}var St=60,xt="__runapps_auth_v1__",kt="__runjobs_auth_v1__",At="__runapps_signed_out_v1__",_t="__runjobs_signed_out_v1__";function Q(n){return n?`${xt}:${n}`:xt}function ve(n){return n?`${At}:${n}`:At}function Be(n){return n?`${kt}:${n}`:kt}function Tt(n){return n?`${_t}:${n}`:_t}var U=class{constructor(e={}){u(this,"origin");u(this,"hideBadge");u(this,"project");u(this,"events");u(this,"tracker");u(this,"badgePosition");u(this,"token",null);u(this,"expiresAt",0);u(this,"userInfo",null);u(this,"listeners",[]);u(this,"parentHandshake",null);u(this,"signingIn",!1);u(this,"getToken",async()=>{if(this.tokenIsFresh())return this.token;if(this.isSignedOut())throw new Error("RunApps: signed out \u2014 call client.signIn() to authenticate");if(this.inIframe()){try{this.parentHandshake&&(await this.parentHandshake,this.parentHandshake=null),this.tokenIsFresh()||await this.requestTokenFromParent()}catch{}if(this.tokenIsFresh())return this.token;throw new Error("RunApps: could not obtain a token from the dashboard")}return this.parentHandshake&&(await this.parentHandshake,this.tokenIsFresh())?this.token:(this.signIn(),new Promise(()=>{}))});this.origin=(e.origin??"https://www.runapps.ai").replace(/\/$/,""),this.hideBadge=!!e.hideBadge,this.project=e.project??null,this.events=e.events??null,this.badgePosition=e.badgePosition??"bottom-right",this.events&&!this.hideBadge?(this.tracker=new O,this.tracker.attach(this.events)):this.tracker=null,!(typeof window>"u")&&(this.loadPersisted(),this.consumeFragment()&&this.clearSignedOut(),this.isSignedOut()||(this.inIframe()&&!this.tokenIsFresh()?this.parentHandshake=this.requestTokenFromParent().catch(()=>{}):this.tokenIsFresh()&&this.userInfo&&!this.hideBadge&&this.renderBadge()))}onTokenChange(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}get user(){return this.userInfo}hasFreshToken(){return this.tokenIsFresh()}ownerId(){return this.tokenIsFresh()?this.userInfo?.id?this.userInfo.id:"t"+we(this.token).toString(36):null}signOut(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted(),this.markSignedOut(),this.removeBadge()}invalidate(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted()}signIn(){if(typeof window>"u"||this.signingIn)return;this.clearSignedOut(),this.signingIn=!0;let e=location.href.split("#")[0]??location.href,t=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";location.href=this.buildGrantUrl({pageOrigin:location.origin,app:location.host,redirectTo:e,scheme:t})}_buildGrantUrlForTest(e){return this.buildGrantUrl(e)}_storageKeysForTest(){return{auth:Q(this.project),signedOut:ve(this.project)}}buildGrantUrl(e){let t=new URLSearchParams;return t.set("origin",e.pageOrigin),t.set("app",e.app),t.set("redirect_to",e.redirectTo),t.set("scheme",e.scheme),this.project&&t.set("project_id",this.project),t.set("token_name","runapps_token"),this.origin+"/api/sdk/grant?"+t.toString()}nowSec(){return Math.floor(Date.now()/1e3)}tokenIsFresh(){return!!this.token&&this.nowSec()<this.expiresAt-St}inIframe(){try{return window.self!==window.top}catch{return!0}}setToken(e,t,r){this.token=e,this.expiresAt=t||this.nowSec()+3600,r&&(this.userInfo=r,this.hideBadge||this.renderBadge()),this.savePersisted();for(let s of this.listeners)try{s(e)}catch(o){console.warn("[runapps] onTokenChange handler threw",o)}}savePersisted(){if(!(typeof localStorage>"u"||!this.token))try{let e={token:this.token,expiresAt:this.expiresAt,origin:this.origin,...this.userInfo?{user:this.userInfo}:{}};localStorage.setItem(Q(this.project),JSON.stringify(e))}catch{}}loadPersisted(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem(Q(this.project));if(!e){if(e=localStorage.getItem(Be(this.project)),!e)return;localStorage.setItem(Q(this.project),e),localStorage.removeItem(Be(this.project))}let t=JSON.parse(e);if(!t.token||!t.origin||t.origin!==this.origin)return;if(typeof t.expiresAt=="number"&&t.expiresAt>0&&this.nowSec()>=t.expiresAt-St){this.clearPersisted();return}this.token=t.token,this.expiresAt=t.expiresAt??0,t.user&&(this.userInfo=t.user)}catch{this.clearPersisted()}}clearPersisted(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Q(this.project)),localStorage.removeItem(Be(this.project))}catch{}}isSignedOut(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(ve(this.project))==="1"||localStorage.getItem(Tt(this.project))==="1"}catch{return!1}}markSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.setItem(ve(this.project),"1")}catch{}}clearSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ve(this.project)),localStorage.removeItem(Tt(this.project))}catch{}}removeBadge(){typeof document>"u"||document.getElementById("__runapps_identity__")?.remove()}consumeFragment(){if(!location.hash||!/(^#|&)run(apps|jobs)_token=/.test(location.hash))return!1;let e={};location.hash.replace(/^#/,"").split("&").forEach(s=>{let o=s.indexOf("=");o>=0&&(e[decodeURIComponent(s.slice(0,o))]=decodeURIComponent(s.slice(o+1).replace(/\+/g," ")))});let t=e.runapps_token||e.runjobs_token;if(!t)return!1;let r;if(e.user)try{r=JSON.parse(e.user)}catch{}this.setToken(t,parseInt(e.expires_at??"",10)||0,r);try{history.replaceState(null,"",location.pathname+location.search)}catch{}return!0}requestTokenFromParent(){return new Promise((e,t)=>{let r=!1,s=[],o=()=>{r=!0,window.removeEventListener("message",i);for(let c of s)clearTimeout(c)},i=c=>{if(c.origin!==this.origin)return;let l=c.data;l&&(l.type==="runapps:token"||l.type==="runjobs:token")&&l.token&&(this.setToken(l.token,l.expires_at??0,l.user),o(),e())};window.addEventListener("message",i);let a=()=>{if(!r)try{window.parent.postMessage({type:"runapps:request-token"},this.origin),window.parent.postMessage({type:"runjobs:request-token"},this.origin)}catch(c){o(),t(c)}};a();for(let c of[250,750,1500,3e3])s.push(setTimeout(a,c));s.push(setTimeout(()=>{r||(o(),t(new Error("runapps: parent handshake timeout")))},5e3))})}renderBadge(){if(typeof document>"u"||!this.userInfo)return;let e="__runapps_identity__",t=`${this.origin}/dashboard`;(s=>document.body?s():document.addEventListener("DOMContentLoaded",s))(()=>{document.getElementById(e)?.remove();let s=bn({id:e,user:this.userInfo,dashboardUrl:t,tracker:this.tracker,position:this.badgePosition,onSignOut:()=>{this.signOut(),typeof window<"u"&&window.location.reload()}});document.body.appendChild(s)})}};function pn(){if(typeof document>"u"||document.getElementById("__runapps_kf__"))return;let n=document.createElement("style");n.id="__runapps_kf__",n.textContent="@keyframes __runapps_led_pulse__ { 0% { box-shadow: 0 0 0 0 rgba(59,130,246,0.7); } 70% { box-shadow: 0 0 0 6px rgba(59,130,246,0); } 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0); }}@keyframes __runapps_sync_ping__ { 0% { transform: scale(1); opacity: 0.9; } 100% { transform: scale(2.1); opacity: 0; }}",(document.head??document.documentElement).appendChild(n)}function fn(n){let e=n.startsWith("top")?"top":"bottom",t=n.endsWith("right")?"right":"left",r=e==="bottom"?"bottom:calc(100% + 8px);top:auto":"top:calc(100% + 8px);bottom:auto",s=t==="right"?"right:0;left:auto":"left:0;right:auto";return{badge:`${e}:16px;${t}:16px`,popover:`${r};${s}`}}var Dt="__runapps_badge_pos__",hn="__runjobs_badge_pos__",Et=5,j=8;function gn(){if(typeof document>"u")return null;let n=document.cookie.split(";").map(l=>l.trim()),e=Dt,t=n.find(l=>l.startsWith(e+"="));if(t||(e=hn,t=n.find(l=>l.startsWith(e+"="))),!t)return null;let s=decodeURIComponent(t.slice(e.length+1)).split(","),o=s[0],i=s[1];if(s.length!==2||o===void 0||i===void 0)return null;let a=Number.parseInt(o,10),c=Number.parseInt(i,10);return!Number.isFinite(a)||!Number.isFinite(c)?null:{x:a,y:c}}function mn(n,e){if(typeof document>"u")return;let t=3600*24*365,r=typeof window<"u"&&window.location?.protocol==="https:"?";Secure":"";document.cookie=`${Dt}=${encodeURIComponent(`${Math.round(n)},${Math.round(e)}`)};path=/;max-age=${t};SameSite=Lax${r}`}function Ct(n,e,t,r){let s=typeof window<"u"?window.innerWidth:1024,o=typeof window<"u"?window.innerHeight:768,i=Math.max(j,s-t-j),a=Math.max(j,o-r-j);return{x:Math.min(Math.max(j,n),i),y:Math.min(Math.max(j,e),a)}}function yn(n){let e=typeof window<"u"?window.innerWidth:1024,t=typeof window<"u"?window.innerHeight:768,r=n.left+n.width/2,o=n.top+n.height/2<t/2?"top:calc(100% + 8px);bottom:auto":"bottom:calc(100% + 8px);top:auto",i=r<e/2?"left:0;right:auto":"right:0;left:auto";return`${o};${i}`}function bn(n){let{id:e,user:t,dashboardUrl:r,tracker:s,position:o,onSignOut:i}=n,a=fn(o),c=a.popover;pn();let l=document.createElement("button");l.id=e,l.type="button",l.setAttribute("aria-label","RunApps activity status"),l.style.cssText=["position:fixed",a.badge,"z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:5px","border-radius:50%","font:500 12px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","color:#fff","background:rgba(15,15,20,0.55)","backdrop-filter:blur(10px) saturate(1.2)","-webkit-backdrop-filter:blur(10px) saturate(1.2)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 4px 16px rgba(0,0,0,0.15)","user-select:none","-webkit-user-select:none","touch-action:none","-webkit-touch-callout:none","overflow:visible","cursor:pointer","appearance:none","-webkit-appearance:none","transition:background-color 120ms ease-out, box-shadow 120ms ease-out"].join(";"),l.addEventListener("mouseenter",()=>{l.style.backgroundColor="rgba(30,30,40,0.7)",l.style.boxShadow="0 6px 20px rgba(0,0,0,0.22)"}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="rgba(15,15,20,0.55)",l.style.boxShadow="0 4px 16px rgba(0,0,0,0.15)"});let d=document.createElement("span");d.style.cssText=["position:relative","width:26px;height:26px","flex-shrink:0","display:inline-flex;align-items:center;justify-content:center"].join(";");let p="http://www.w3.org/2000/svg",h=document.createElementNS(p,"svg");h.setAttribute("viewBox","0 0 26 26"),h.setAttribute("width","26"),h.setAttribute("height","26"),h.style.cssText=["position:absolute;inset:0","pointer-events:none","opacity:0","transition:opacity 200ms ease-out"].join(";");let f=document.createElementNS(p,"circle");f.setAttribute("cx","13"),f.setAttribute("cy","13"),f.setAttribute("r","12"),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(255,255,255,0.08)"),f.setAttribute("stroke-width","1.5");let g=document.createElementNS(p,"circle");g.setAttribute("cx","13"),g.setAttribute("cy","13"),g.setAttribute("r","12"),g.setAttribute("fill","none"),g.setAttribute("stroke","#3b82f6"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("transform","rotate(-90 13 13)");let w=2*Math.PI*12;g.setAttribute("stroke-dasharray",String(w)),g.setAttribute("stroke-dashoffset",String(w)),h.appendChild(f),h.appendChild(g);let _=document.createElement("div");_.textContent=(t.name||"?").charAt(0).toUpperCase(),_.style.cssText=["width:22px;height:22px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff","position:relative"].join(";");let T=document.createElement("span");T.style.cssText=["position:absolute","bottom:-1px;right:-1px","width:7px;height:7px;border-radius:50%","background:rgba(255,255,255,0.2)","border:1.5px solid rgba(15,15,20,1)","box-shadow:0 0 0 0 transparent","opacity:0","transition:background-color 150ms ease-out, box-shadow 200ms ease-out, opacity 200ms ease-out","pointer-events:none"].join(";"),d.appendChild(h),d.appendChild(_),d.appendChild(T),l.appendChild(d);let v=null,S=!1,B=null,ne=null,re=null,Ee=()=>{ne!==null&&(window.clearTimeout(ne),ne=null)},K=()=>{re!==null&&(window.clearTimeout(re),re=null)},Fe=()=>{K(),re=window.setTimeout(()=>{B==="hover"&&$()},300)},Le=m=>{if(Ee(),K(),S){m==="click"&&(B="click");return}v||(v=xn(t,r,c,()=>{$(),i()}),v.addEventListener("mouseenter",K),v.addEventListener("mouseleave",()=>{B==="hover"&&Fe()})),l.appendChild(v),S=!0,B=m,oe()},$=()=>{K(),S&&(v?.remove(),S=!1,B=null)};l.addEventListener("click",m=>{m.stopPropagation(),S?$():Le("click")}),l.addEventListener("mouseenter",()=>{K(),Ee(),ne=window.setTimeout(()=>{S||Le("hover")},400)}),l.addEventListener("mouseleave",()=>{Ee(),B==="hover"&&Fe()}),document.addEventListener("click",m=>{S&&!l.contains(m.target)&&$()});let Ke=0,$e=0,Ve=0,qe=0,se=!1,V=!1,Ce=!1,De=(m,b)=>{l.style.left=`${m}px`,l.style.top=`${b}px`,l.style.right="auto",l.style.bottom="auto"},Ge=()=>{let m=l.getBoundingClientRect();if(c=yn({left:m.left,top:m.top,width:m.width,height:m.height}),v){v.style.top="",v.style.bottom="",v.style.left="",v.style.right="";for(let b of c.split(";")){let[E,H]=b.split(":");E&&H&&v.style.setProperty(E.trim(),H.trim())}}};l.addEventListener("pointerdown",m=>{if(m.button!==0)return;se=!0,V=!1,Ke=m.clientX,$e=m.clientY;let b=l.getBoundingClientRect();Ve=b.left,qe=b.top}),l.addEventListener("pointermove",m=>{if(!se)return;let b=m.clientX-Ke,E=m.clientY-$e;if(!V){if(Math.abs(b)<Et&&Math.abs(E)<Et)return;V=!0;try{l.setPointerCapture(m.pointerId)}catch{}l.style.cursor="grabbing",S&&$()}let H=l.getBoundingClientRect(),We=Ct(Ve+b,qe+E,H.width,H.height);De(We.x,We.y)});let He=m=>{if(!se||(se=!1,!V))return;V=!1,l.style.cursor="pointer";try{l.hasPointerCapture(m.pointerId)&&l.releasePointerCapture(m.pointerId)}catch{}let b=l.getBoundingClientRect();mn(b.left,b.top),Ge(),Ce=!0};l.addEventListener("pointerup",He),l.addEventListener("pointercancel",He),l.addEventListener("click",m=>{Ce&&(Ce=!1,m.stopPropagation(),m.preventDefault())},!0);let q=gn();q&&(De(q.x,q.y),requestAnimationFrame(()=>{let m=l.getBoundingClientRect(),b=Ct(q.x,q.y,m.width,m.height);De(b.x,b.y),Ge()}));let Ie=!1,G=null,Je,ze=()=>{if(Ie=!1,!s){h.style.opacity="0",T.style.background="rgba(255,255,255,0.2)",T.style.opacity="0";return}let m=s.snapshot(),b=m.sync?.lastChangeAt;b&&b!==Je&&(Je=b,vn(d,T)),wn(h,g,w,m),Sn(T,m),S&&v&&kn(v,m);let E=m.status!=="idle"||S;E&&G===null?G=window.setInterval(oe,160):!E&&G!==null&&(window.clearInterval(G),G=null)};function oe(){Ie||(Ie=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(ze):setTimeout(ze,0))}return s&&s.onChange(oe),oe(),l}function wn(n,e,t,r){if(r.active.length===0){n.style.opacity="0";return}n.style.opacity="1";let s=r.active.reduce((o,i)=>i.tokensPerSec>o.tokensPerSec?i:o,r.active[0]);if(s.streaming&&s.tokensPerSec>0){let o=Math.min(s.tokensPerSec/60,1);e.setAttribute("stroke-dashoffset",String(t*(1-o))),e.setAttribute("stroke","#3b82f6")}else r.status==="error"?(e.setAttribute("stroke-dashoffset","0"),e.setAttribute("stroke","#ef4444")):(e.setAttribute("stroke-dashoffset",String(t*.75)),e.setAttribute("stroke","#a78bfa"))}var Re=0;function vn(n,e){let t=document.createElement("span");t.style.cssText=["position:absolute;inset:0","border-radius:50%","border:2px solid #10b981","pointer-events:none","animation:__runapps_sync_ping__ 700ms ease-out forwards"].join(";"),t.addEventListener("animationend",()=>t.remove()),n.appendChild(t),setTimeout(()=>t.remove(),1e3),Re=Date.now()+1200,e.style.opacity="1",e.style.background="#10b981",e.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",e.style.animation="",setTimeout(()=>{Date.now()>=Re&&(e.style.background="rgba(255,255,255,0.2)",e.style.opacity="0",e.style.boxShadow="0 0 0 0 transparent")},1250)}function Sn(n,e){switch(n.style.opacity="1",e.status){case"idle":{let t=e.sync;Date.now()<Re?(n.style.background="#10b981",n.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",n.style.animation=""):t&&t.state==="syncing"?(n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite"):t&&(t.state==="offline"||t.state==="error")?(n.style.background="#f59e0b",n.style.boxShadow="0 0 0 2px rgba(245,158,11,0.3)",n.style.animation=""):(n.style.background="rgba(255,255,255,0.2)",n.style.opacity="0",n.style.boxShadow="0 0 0 0 transparent",n.style.animation="");break}case"active":n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite";break;case"error":n.style.background="#ef4444",n.style.boxShadow="0 0 0 2px rgba(239,68,68,0.3)",n.style.animation="";break}}function xn(n,e,t,r){let s=document.createElement("div");s.style.cssText=["position:absolute",t,"min-width:280px;max-width:340px","padding:10px 12px","border-radius:10px","background:rgba(15,15,20,0.92)","backdrop-filter:blur(20px) saturate(1.3)","-webkit-backdrop-filter:blur(20px) saturate(1.3)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 10px 30px rgba(0,0,0,0.4)","color:#fff","font:400 11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","cursor:default","text-align:left"].join(";"),s.setAttribute("data-runapps-popover","1"),s.addEventListener("click",g=>g.stopPropagation());let o=document.createElement("div");o.style.cssText=["display:flex;align-items:center;gap:8px","margin-bottom:10px;padding-bottom:8px","border-bottom:1px solid rgba(255,255,255,0.08)"].join(";");let i=document.createElement("div");i.textContent=(n.name||"?").charAt(0).toUpperCase(),i.style.cssText=["width:24px;height:24px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff"].join(";");let a=document.createElement("div");a.textContent=n.name||"Signed in",a.title=n.name||"",a.style.cssText="font-size:12px;font-weight:500;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap";let c=document.createElement("div");c.textContent="Signed in with RunApps",c.style.cssText="font-size:10px;color:rgba(255,255,255,0.5)";let l=document.createElement("div");l.style.cssText="min-width:0",l.appendChild(a),l.appendChild(c),o.appendChild(i),o.appendChild(l),s.appendChild(o);let d=document.createElement("div");d.setAttribute("data-runapps-popover-content","1"),s.appendChild(d);let p=document.createElement("div");p.style.cssText=["margin-top:10px;padding-top:8px","border-top:1px solid rgba(255,255,255,0.08)","display:flex;justify-content:space-between;align-items:center","font-size:10px;color:rgba(255,255,255,0.6)"].join(";");let h=document.createElement("a");h.textContent="Open dashboard \u2192",h.href=e,h.target="_blank",h.rel="noopener noreferrer",h.style.cssText="color:#a78bfa;text-decoration:none",p.appendChild(h);let f=document.createElement("button");return f.type="button",f.textContent="Sign out",f.style.cssText=["background:none;border:0;padding:0;margin:0","font:inherit;cursor:pointer","color:rgba(255,255,255,0.55)","transition:color 120ms ease"].join(";"),f.addEventListener("mouseenter",()=>{f.style.color="#f87171"}),f.addEventListener("mouseleave",()=>{f.style.color="rgba(255,255,255,0.55)"}),f.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),r()}),p.appendChild(f),s.appendChild(p),s}function kn(n,e){let t=n.querySelector("[data-runapps-popover-content]");if(!t)return;t.innerHTML="";let r=Date.now();t.appendChild(_n(e,r)),t.appendChild(Tn(e,r)),e.sync&&t.appendChild(An(e.sync,r)),t.appendChild(En(e.session,r))}function An(n,e){let t=document.createElement("div");t.style.marginBottom="10px";let r=n.lastSyncedAt?`synced ${Oe(e-n.lastSyncedAt)}`:"\u2014";t.appendChild(Se("Sync",r));let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0;font-size:10px";let o=document.createElement("span"),i=document.createElement("span");i.textContent="\u25CF ";let a={off:["Not signed in","rgba(255,255,255,0.4)"],idle:["Up to date","#10b981"],syncing:["Syncing\u2026","#3b82f6"],offline:["Offline","#f59e0b"],error:["Retrying","#f59e0b"]},[c,l]=a[n.state]??["","#fff"];i.style.color=l,o.style.color="#fff",o.appendChild(i),o.appendChild(document.createTextNode(c));let d=document.createElement("span");return d.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums",d.textContent=n.pending>0?`${n.pending} pending`:"",d.title=n.error??"",s.appendChild(o),s.appendChild(d),t.appendChild(s),t}function _n(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Se("Active",n.active.length>0?`${n.active.length} in flight`:"\u2014")),n.active.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="No calls in flight.",t.appendChild(r),t}for(let r of n.active){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px",o.textContent=r.model;let i=document.createElement("span");i.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let a=((e-r.startedAt)/1e3).toFixed(1),c=r.tokensPerSec>0?` \xB7 ${Math.round(r.tokensPerSec)} tok/s`:"";i.textContent=`${a}s${c}`,s.appendChild(o),s.appendChild(i),t.appendChild(s)}return t}function Tn(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Se("Recent",n.recent.length>0?`last ${Math.min(n.recent.length,5)}`:"\u2014")),n.recent.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="Nothing yet this session.",t.appendChild(r),t}for(let r of n.recent.slice(0,5)){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px";let i=document.createElement("span");i.textContent=r.ok?"\u2713 ":"\u2717 ",i.style.color=r.ok?"#10b981":"#ef4444",o.appendChild(i),o.appendChild(document.createTextNode(r.model));let a=document.createElement("span");a.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let c=`${(r.latencyMs/1e3).toFixed(1)}s`,l=r.costUSD!==void 0?` \xB7 $${r.costUSD.toFixed(4)}`:"",d=` \xB7 ${Oe(e-r.endedAt)}`;a.textContent=`${c}${l}${d}`,s.appendChild(o),s.appendChild(a),t.appendChild(s)}return t}function En(n,e){let t=document.createElement("div");t.appendChild(Se("Session",Oe(e-n.startedAt)));let r=document.createElement("div");r.style.cssText="display:flex;justify-content:space-between;gap:12px;color:rgba(255,255,255,0.85);font-size:10px";let s=document.createElement("span");s.textContent=`${n.totalCalls} call${n.totalCalls===1?"":"s"}`;let o=document.createElement("span");o.textContent=`$${n.totalCostUSD.toFixed(4)}`;let i=document.createElement("span");return i.textContent=n.errorCount>0?`${n.errorCount} error${n.errorCount===1?"":"s"}`:"0 errors",n.errorCount>0&&(i.style.color="#ef4444"),r.appendChild(s),r.appendChild(o),r.appendChild(i),t.appendChild(r),t}function Se(n,e){let t=document.createElement("div");t.style.cssText=["display:flex;justify-content:space-between;align-items:baseline","margin-bottom:4px","color:rgba(255,255,255,0.55)","font-size:10px;text-transform:uppercase;letter-spacing:0.05em"].join(";");let r=document.createElement("span");r.textContent=n;let s=document.createElement("span");return s.textContent=e,s.style.cssText="font-size:9px;letter-spacing:0",t.appendChild(r),t.appendChild(s),t}function Oe(n){return n<1500?"just now":n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}var It=new WeakMap,Me=new WeakMap,Ae=new Set,N=null;function xe(n){try{return typeof structuredClone=="function"?structuredClone(n):n}catch{return n}}function Cn(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function ke(n,e,t){let r;if(e&&typeof IDBVersionChangeEvent=="function"?r=new IDBVersionChangeEvent(n,{oldVersion:e.oldVersion,newVersion:e.newVersion??null}):(r=new Event(n,{bubbles:!1,cancelable:n==="error"}),e&&Object.assign(r,e)),t)for(let s of["target","currentTarget","srcElement"])try{Object.defineProperty(r,s,{value:t,configurable:!0})}catch{}return r}var _e=class{constructor(e,t,r){u(this,"readyState","pending");u(this,"result");u(this,"error",null);u(this,"transaction",null);u(this,"source",null);u(this,"listeners",new Map);u(this,"handlers",{success:null,error:null,blocked:null,upgradeneeded:null});e.addEventListener("upgradeneeded",s=>{let o=s;this.result=e.result,this.transaction=e.transaction,Me.set(e.result,{name:t,subs:r}),this.dispatch(ke("upgradeneeded",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("blocked",s=>{let o=s;this.dispatch(ke("blocked",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("error",()=>{this.error=e.error,this.readyState="done",this.transaction=null,this.dispatch(ke("error",void 0,this))}),e.addEventListener("success",()=>{let s=e.result;Me.set(s,{name:t,subs:r}),this.transaction=null;let o=!1,i=()=>{o||(o=!0,this.result=s,this.readyState="done",this.dispatch(ke("success",void 0,this)))},a=[],c=0;for(let d of r)try{let p=d.opts.onOpen(s,t);p&&typeof p.then=="function"&&(a.push(p.catch(()=>{})),c=Math.max(c,d.opts.openTimeoutMs))}catch{}if(a.length===0){i();return}let l=setTimeout(i,c);Promise.all(a).then(()=>{clearTimeout(l),i()})})}addEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:o=>t.handleEvent(o),s=this.listeners.get(e);s||this.listeners.set(e,s=new Set),s.add(r),t.__rtFn=r}removeEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:t.__rtFn;r&&this.listeners.get(e)?.delete(r)}dispatchEvent(e){return this.dispatch(e),!e.defaultPrevented}dispatch(e){let t=this.handlers[e.type];if(t)try{t.call(this,e)}catch(r){je(r)}for(let r of this.listeners.get(e.type)??[])try{r.call(this,e)}catch(s){je(s)}}get onsuccess(){return this.handlers.success??null}set onsuccess(e){this.handlers.success=e}get onerror(){return this.handlers.error??null}set onerror(e){this.handlers.error=e}get onblocked(){return this.handlers.blocked??null}set onblocked(e){this.handlers.blocked=e}get onupgradeneeded(){return this.handlers.upgradeneeded??null}set onupgradeneeded(e){this.handlers.upgradeneeded=e}};function je(n){setTimeout(()=>{throw n},0)}typeof IDBOpenDBRequest=="function"&&Object.setPrototypeOf(_e.prototype,IDBOpenDBRequest.prototype);function Pt(n){let e=n.source;return typeof IDBIndex=="function"&&e instanceof IDBIndex?e.objectStore:e}function Bt(n,e){if(e.startsWith("__runapps"))return[];let t=[];for(let r of Ae)(r.factory===null||r.factory===n)&&r.opts.include(e)&&t.push(r);return t}function Dn(){let n=IDBFactory.prototype,e=IDBDatabase.prototype,t=IDBObjectStore.prototype,r=IDBCursor.prototype,s=N={open:n.open,deleteDatabase:n.deleteDatabase,transaction:e.transaction,put:t.put,add:t.add,get:t.get,delete:t.delete,clear:t.clear,getAllKeys:t.getAllKeys,cursorUpdate:r.update,cursorDelete:r.delete},o=i=>It.get(i.transaction)??null;n.open=function(i,a){let c=a===void 0?s.open.call(this,i):s.open.call(this,i,a),l=Bt(this,i);return l.length===0?c:new _e(c,i,l)},n.deleteDatabase=function(i){for(let a of Bt(this,i))try{a.opts.onDeleteDatabase(i)}catch{}return s.deleteDatabase.call(this,i)},e.transaction=function(i,a,c){let l=c!==void 0?s.transaction.call(this,i,a,c):a!==void 0?s.transaction.call(this,i,a):s.transaction.call(this,i),d=Me.get(this);if(d&&l.mode==="readwrite"){let p={db:d.name,subs:d.subs,ops:[]};It.set(l,p),l.addEventListener("complete",()=>{if(p.ops.length===0)return;let h=p.ops;p.ops=[];for(let f of p.subs){let g=h.filter(w=>!f.opts.excludeStore(p.db,w.store));if(g.length!==0)try{f.opts.onCommit(p.db,g)}catch(w){je(w)}}})}return l},t.put=function(i,a){let c=o(this),l=null;if(c&&Cn(i)){let p=a!==void 0?a:vt(i,this.keyPath);if(p!==void 0)try{let h=s.get.call(this,p),f=l={value:void 0};h.addEventListener("success",()=>{f.value=h.result})}catch{l=null}}let d=a===void 0?s.put.call(this,i):s.put.call(this,i,a);if(c){let p=this.name,h=xe(i),f=l;d.addEventListener("success",()=>{c.ops.push({store:p,kind:"put",key:d.result,value:h,prior:f?.value})})}return d},t.add=function(i,a){let c=a===void 0?s.add.call(this,i):s.add.call(this,i,a),l=o(this);if(l){let d=this.name,p=xe(i);c.addEventListener("success",()=>{l.ops.push({store:d,kind:"put",key:c.result,value:p})})}return c},t.delete=function(i){let a=o(this);if(a){let c=this.name;if(typeof IDBKeyRange=="function"&&i instanceof IDBKeyRange){let l=s.getAllKeys.call(this,i);l.addEventListener("success",()=>{for(let d of l.result)a.ops.push({store:c,kind:"del",key:d})})}else a.ops.push({store:c,kind:"del",key:i})}return s.delete.call(this,i)},t.clear=function(){let i=o(this),a=s.clear.call(this);if(i){let c=this.name;a.addEventListener("success",()=>{i.ops.push({store:c,kind:"clear"})})}return a},r.update=function(i){let a=Pt(this),c=o(a),l=c?xe(this.value):void 0,d=s.cursorUpdate.call(this,i);if(c){let p=a.name,h=xe(i),f=this.primaryKey;d.addEventListener("success",()=>{c.ops.push({store:p,kind:"put",key:f,value:h,prior:l})})}return d},r.delete=function(){let i=Pt(this),a=o(i);return a&&a.ops.push({store:i.name,kind:"del",key:this.primaryKey}),s.cursorDelete.call(this)}}function In(){if(!N)return;let n=N;IDBFactory.prototype.open=n.open,IDBFactory.prototype.deleteDatabase=n.deleteDatabase,IDBDatabase.prototype.transaction=n.transaction,IDBObjectStore.prototype.put=n.put,IDBObjectStore.prototype.add=n.add,IDBObjectStore.prototype.delete=n.delete,IDBObjectStore.prototype.clear=n.clear,IDBCursor.prototype.update=n.cursorUpdate,IDBCursor.prototype.delete=n.cursorDelete,N=null}function Z(n){if(typeof indexedDB>"u"||typeof IDBFactory!="function"||typeof IDBDatabase!="function"||typeof IDBObjectStore!="function"||typeof IDBCursor!="function")return null;N||Dn();let e=N,t={opts:n,factory:n.factory??indexedDB};Ae.add(t);let r=t.factory;return{originalOpen:(s,o)=>o===void 0?e.open.call(r,s):e.open.call(r,s,o),uninstall(){Ae.delete(t),Ae.size===0&&In()}}}var Rt="__runapps_sync__";function F(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("IndexedDB request failed"))})}function D(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onabort=()=>t(n.error??new Error("IndexedDB transaction aborted")),n.onerror=()=>t(n.error??new Error("IndexedDB transaction failed"))})}var ee=class{constructor(e){u(this,"open",e);u(this,"dbPromise",null)}db(){return this.dbPromise||(this.dbPromise=new Promise((e,t)=>{let r=this.open(Rt,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains("ops")||s.createObjectStore("ops",{keyPath:"id",autoIncrement:!0}).createIndex("store",["db","store"],{unique:!1}),s.objectStoreNames.contains("meta")||s.createObjectStore("meta")},r.onsuccess=()=>{let s=r.result;s.onversionchange=()=>{s.close(),this.dbPromise=null},e(s)},r.onerror=()=>t(r.error??new Error("cannot open sync log")),r.onblocked=()=>t(new Error("sync log open blocked"))}),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}async append(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.add(o);await D(r)}async pending(){let t=(await this.db()).transaction("ops","readonly");return await F(t.objectStore("ops").getAll())}async pendingCount(){let t=(await this.db()).transaction("ops","readonly");return F(t.objectStore("ops").count())}async remove(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.delete(o);await D(r)}async clearOps(){let t=(await this.db()).transaction("ops","readwrite");t.objectStore("ops").clear(),await D(t)}async getMeta(e){let r=(await this.db()).transaction("meta","readonly");return await F(r.objectStore("meta").get(e))}async setMeta(e){let r=(await this.db()).transaction("meta","readwrite"),s=r.objectStore("meta");for(let o of Object.keys(e))e[o]===void 0?s.delete(o):s.put(e[o],o);await D(r)}async metaWithPrefix(e){let s=(await this.db()).transaction("meta","readonly").objectStore("meta"),o=IDBKeyRange.bound(e,e+"\uFFFF"),i=await F(s.getAllKeys(o)),a=await F(s.getAll(o)),c=new Map;return i.forEach((l,d)=>c.set(l,a[d])),c}async clearAll(){let t=(await this.db()).transaction(["ops","meta"],"readwrite");t.objectStore("ops").clear(),t.objectStore("meta").clear(),await D(t)}close(){this.dbPromise?.then(e=>e.close()).catch(()=>{}),this.dbPromise=null}};function Ot(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!("$rt"in n)}function Pn(n,e){return JSON.stringify(n)===JSON.stringify(e)}function Bn(n,e,t){if(!n)return e;if(e.d||n.d||!Ot(n.v)||!Ot(e.v))return e.t>=n.t?e:n;let r=n.f??{},s=t?new Set(t):null,o={},i={},a=new Set([...Object.keys(n.v),...Object.keys(e.v)]);for(let c of a){let l=c in n.v,d=c in e.v,p=r[c]??n.t;if(s?!s.has(c):l&&d&&Pn(n.v[c],e.v[c])){l&&(o[c]=n.v[c],r[c]!==void 0&&(i[c]=r[c]));continue}e.t>=p?d&&(o[c]=e.v[c],i[c]=e.t):l&&(o[c]=n.v[c],i[c]=p)}return{k:e.k,v:o,t:Math.max(n.t,e.t),f:i}}var Rn=720*3600*1e3,On=1e4,Mn=5e3,jn=5*6e4,Ne=class{constructor(){u(this,"last",0);u(this,"offset",0)}now(){let e=Date.now()+this.offset;return this.last=e>this.last?e:this.last+1,this.last}observe(e,t,r){let s=(t+r)/2,o=e-s;Math.abs(o-this.offset)>2e3&&(this.offset=o)}};function Ue(n){return encodeURIComponent(n).replace(/%2F/gi,"%2F")}var I=class{constructor(e,t={}){u(this,"deps",e);u(this,"options");u(this,"log");u(this,"hook");u(this,"clock",new Ne);u(this,"schemas",new Map);u(this,"etags",new Map);u(this,"conns",new Map);u(this,"state",{state:"off",pending:0});u(this,"paused",!1);u(this,"disposed",!1);u(this,"leader",!0);u(this,"pushTimer",null);u(this,"pushDeadline",0);u(this,"pullTimer",null);u(this,"backoffMs",0);u(this,"backoffUntil",0);u(this,"chain",Promise.resolve());u(this,"cleanup",[]);u(this,"channel",null);u(this,"metaLoaded",null);u(this,"logChain",Promise.resolve());u(this,"moved",!1);this.options={databases:t.databases??[],exclude:t.exclude??[],shards:Math.max(1,Math.min(64,t.shards??8)),pushDelayMs:t.pushDelayMs??2500,pullIntervalMs:t.pullIntervalMs??6e4,openTimeoutMs:t.openTimeoutMs??5e3,prefix:(t.prefix??"db").replace(/^\/+|\/+$/g,"")};let r=new Set(this.options.exclude.filter(i=>!i.includes("/"))),s=new Set(this.options.exclude.filter(i=>i.includes("/"))),o=new Set(this.options.databases);this.hook=Z({include:i=>(o.size===0||o.has(i))&&!r.has(i),excludeStore:(i,a)=>s.has(i+"/"+a),onCommit:(i,a)=>this.onCommit(i,a),onOpen:(i,a)=>this.onOpen(i,a),onDeleteDatabase:i=>this.onDeleteDatabase(i),openTimeoutMs:this.options.openTimeoutMs,factory:e.factory}),this.log=new ee((i,a)=>this.hook?this.hook.originalOpen(i,a):indexedDB.open(i,a)),typeof window<"u"&&this.attachBrowserTriggers(),this.cleanup.push(e.onAuthChange(()=>this.schedule("auth"))),this.refreshPending(),this.schedule("start")}status(){return{...this.state}}now(){return this.enqueue(()=>this.sync())}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule("resume")}dispose(){this.disposed=!0;for(let e of this.cleanup)e();this.pushTimer&&clearTimeout(this.pushTimer),this.pullTimer&&clearInterval(this.pullTimer),this.channel?.close();for(let e of this.conns.values())e.then(t=>t.close()).catch(()=>{});this.conns.clear(),this.log.close(),this.hook?.uninstall()}onCommit(e,t){let r=[];for(let s of t){let o=this.clock.now();s.kind==="clear"?r.push({db:e,store:s.store,kind:"clear",kid:"",ts:o}):s.kind==="del"?r.push({db:e,store:s.store,kind:"del",kid:be(s.key),key:M(s.key),ts:o}):r.push({db:e,store:s.store,kind:"put",kid:be(s.key),key:M(s.key),value:s.value,changed:s.prior===void 0?void 0:wt(s.prior,s.value),ts:o})}this.enqueueLog(r)}enqueueLog(e){this.logChain=this.logChain.then(()=>this.log.append(e)).then(()=>this.refreshPending()).catch(t=>this.fail(t)),this.schedulePush()}async onOpen(e,t){let r=new Map,s=Array.from(e.objectStoreNames);if(s.length>0){let o=e.transaction(s,"readonly");for(let i of s){let a=o.objectStore(i);r.set(i,{keyPath:a.keyPath,autoIncrement:a.autoIncrement}),a.autoIncrement&&typeof console<"u"&&console.warn(`[runapps sync] "${t}/${i}" uses autoIncrement keys: records created on two devices while offline can get the same key, and only one survives. Prefer client-generated ids (e.g. crypto.randomUUID()).`)}}this.schemas.set(t,r),this.log.setMeta({["schema:"+t]:Object.fromEntries(r)}).catch(()=>{}),!(!this.deps.userId()||this.paused||!this.leader)&&await this.enqueue(()=>this.pullDatabase(t)).catch(()=>{})}onDeleteDatabase(e){let t=this.schemas.get(e),r=t?Array.from(t.keys()):[];this.schemas.delete(e),this.conns.get(e)?.then(o=>o.close()).catch(()=>{}),this.conns.delete(e);let s=this.clock.now();this.enqueueLog(r.map(o=>({db:e,store:o,kind:"clear",kid:"",ts:s})))}attachBrowserTriggers(){let e=(r,s,o)=>{r.addEventListener(s,o),this.cleanup.push(()=>r.removeEventListener(s,o))};e(window,"online",()=>{this.backoffUntil=0,this.schedule("online")}),e(window,"focus",()=>{this.schedule("focus")}),typeof document<"u"&&e(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.schedule("visible"),this.updatePullTimer()}),this.updatePullTimer(),typeof BroadcastChannel=="function"&&(this.channel=new BroadcastChannel("__runapps_db_change__"),this.channel.onmessage=r=>{let s=r.data;s&&s.source==="remote"&&this.deps.events.emit("db:change",s)});let t=navigator.locks;t&&typeof t.request=="function"&&(this.leader=!1,t.request("__runapps_sync__",()=>(this.leader=!0,this.schedule("leader"),new Promise(()=>{}))).catch(()=>{this.leader=!0}))}updatePullTimer(){let e=typeof document>"u"||document.visibilityState!=="hidden";e&&!this.pullTimer&&this.options.pullIntervalMs>0?(this.pullTimer=setInterval(()=>{this.schedule("interval")},this.options.pullIntervalMs),this.pullTimer.unref?.()):!e&&this.pullTimer&&(clearInterval(this.pullTimer),this.pullTimer=null)}schedulePush(){if(this.disposed)return;let e=Date.now();this.pushDeadline||(this.pushDeadline=e+On);let t=Math.max(0,Math.min(this.options.pushDelayMs,this.pushDeadline-e));this.pushTimer&&clearTimeout(this.pushTimer),this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.pushDeadline=0,this.schedule("push")},t),this.pushTimer.unref?.()}schedule(e){return this.disposed||this.paused||!this.leader?Promise.resolve():this.deps.userId()?Date.now()<this.backoffUntil?Promise.resolve():this.enqueue(()=>this.sync()):(this.setState({state:"off"}),Promise.resolve())}enqueue(e){let t=this.chain.then(e,e);return this.chain=t.catch(()=>{}),t}setState(e){let t={...this.state,...e};e.state&&e.state!=="error"&&delete t.error;let r=t.state!==this.state.state||t.pending!==this.state.pending||t.lastSyncedAt!==this.state.lastSyncedAt||t.lastChangeAt!==this.state.lastChangeAt||t.error!==this.state.error;this.state=t,r&&this.deps.events.emit("sync:state",{...t})}async refreshPending(){try{let e=await this.log.pendingCount();this.setState({pending:e})}catch{}}fail(e){let t=typeof navigator<"u"&&navigator.onLine===!1,r=e instanceof Error?e.message:String(e);this.backoffMs=this.backoffMs?Math.min(this.backoffMs*2,jn):Mn,this.backoffUntil=Date.now()+this.backoffMs,this.setState({state:t?"offline":"error",error:r}),!t&&typeof console<"u"&&console.warn("[runapps sync]",r)}async loadMeta(){return this.metaLoaded||(this.metaLoaded=(async()=>{for(let[e,t]of await this.log.metaWithPrefix("etag:"))this.etags.set(e.slice(5),t);for(let[e,t]of await this.log.metaWithPrefix("schema:")){let r=e.slice(7);this.schemas.has(r)||this.schemas.set(r,new Map(Object.entries(t)))}})(),this.metaLoaded.catch(()=>{this.metaLoaded=null})),this.metaLoaded}async ensureOwner(e){let t=await this.log.getMeta("owner");if(t!==e){if(t!==void 0){for(let[r,s]of this.schemas)for(let o of s.keys())this.storeExcluded(r,o)||(await this.withStore(r,o,"readwrite",i=>{i.clear()}).catch(()=>{}),this.emitChange({db:r,store:o,keys:[],cleared:!0,source:"remote"}));await this.log.clearAll(),this.etags.clear(),this.metaLoaded=null,await this.loadMeta()}await this.log.setMeta({owner:e})}}async sync(){if(this.disposed||this.paused||!this.leader)return;let e=this.deps.userId();if(!e){this.setState({state:"off"});return}this.setState({state:"syncing"}),this.moved=!1;try{await this.loadMeta(),await this.ensureOwner(e),await this.logChain,await this.push(),await this.pull(),this.backoffMs=0,this.backoffUntil=0,await this.refreshPending();let t=Date.now();this.setState({state:"idle",lastSyncedAt:t,...this.moved?{lastChangeAt:t}:{}})}catch(t){await this.refreshPending(),this.fail(t)}}storeExcluded(e,t){return this.options.exclude.includes(e+"/"+t)||this.options.exclude.includes(e)}shardPath(e,t,r){return`${this.options.prefix}/${Ue(e)}/${Ue(t)}/${r}.json`}shardOf(e){return we(e)%this.options.shards}async readShard(e){let t=Date.now(),r=await this.deps.remote.getJSON(e);if(r.status==="ok"){r.serverTime&&this.clock.observe(r.serverTime,t,Date.now());let s=r.value,o={v:1,cleared:s?.cleared??0,r:s?.r??{}};return this.etags.set(e,r.etag),{shard:o,etag:r.etag}}return this.etags.delete(e),{shard:{v:1,cleared:0,r:{}}}}async push(){let e=await this.log.pending();if(e.length===0)return;let t=new Map;for(let o of e){let i=o.db+"\0"+o.store,a=t.get(i);a||t.set(i,a=[]),a.push(o)}let r=[],s={};for(let[,o]of t){let i=o[0].db,a=o[0].store;if(this.storeExcluded(i,a)){for(let f of o)f.id!==void 0&&r.push(f.id);continue}let c=0,l=-1;o.forEach((f,g)=>{f.kind==="clear"&&(c=Math.max(c,f.ts),l=g)});let d=o.slice(l+1),p=new Map;for(let f of d){let g=this.shardOf(f.kid),w=p.get(g);w||p.set(g,w=[]),w.push(f)}let h=c>0?Array.from({length:this.options.shards},(f,g)=>g):Array.from(p.keys());for(let f of h){let g=this.shardPath(i,a,f),w=p.get(f)??[],_=await Promise.all(w.map(v=>this.encodeOp(v))),T=await this.writeShard(g,c,_);s["etag:"+g]=T}for(let f of o)f.id!==void 0&&r.push(f.id)}await this.log.setMeta(s),await this.log.remove(r),r.length>0&&(this.moved=!0),await this.refreshPending()}async encodeOp(e){if(e.kind==="del")return{kid:e.kid,rec:{k:e.key,v:null,t:e.ts,d:1}};let t=await x(e.value,r=>this.storeBlob(r));return{kid:e.kid,rec:{k:e.key,v:t,t:e.ts},changed:e.changed}}async writeShard(e,t,r){for(let s=0;s<5;s++){let{shard:o,etag:i}=await this.readShard(e),a=this.clock.now();if(t>o.cleared){o.cleared=t;for(let d of Object.keys(o.r))o.r[d].t<=t&&delete o.r[d]}for(let{kid:d,rec:p,changed:h}of r)p.t<=o.cleared||(o.r[d]=Bn(o.r[d],p,h));for(let d of Object.keys(o.r)){let p=o.r[d];p.d&&a-p.t>Rn&&delete o.r[d]}let c=Date.now(),l=await this.deps.remote.putJSON(e,o,i?{ifMatch:i}:{ifNoneMatch:!0});if(l.status==="ok")return l.serverTime&&this.clock.observe(l.serverTime,c,Date.now()),this.etags.set(e,l.etag),l.etag;this.etags.delete(e)}throw new Error(`could not write ${e}: too many concurrent writers`)}async storeBlob(e){let t=new Uint8Array(await e.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",t),s=Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join(""),o=`${this.options.prefix}/_blobs/${s}`;return await this.deps.remote.putBlob(o,e),{ref:o,type:e.type,size:e.size}}async pull(){let e=await this.deps.remote.list(this.options.prefix+"/");await this.applyListing(e)}async pullDatabase(e){if(!this.deps.userId())return;await this.loadMeta();let t=await this.deps.remote.list(`${this.options.prefix}/${Ue(e)}/`);await this.applyListing(t)}async applyListing(e){let t=new RegExp("^"+this.options.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/([^/]+)/([^/]+)/(\\d+)\\.json$"),r=await this.log.pending(),s={};for(let o of e){let i=t.exec(o.path);if(!i)continue;let a=decodeURIComponent(i[1]),c=decodeURIComponent(i[2]);if(this.etags.get(o.path)===o.etag||this.storeExcluded(a,c))continue;let l=this.schemas.get(a);if(!l||!l.has(c))continue;let d=await this.deps.remote.getJSON(o.path,this.etags.get(o.path));if(d.status==="unchanged")continue;if(d.status==="missing"){this.etags.delete(o.path),s["etag:"+o.path]=void 0;continue}let p=d.value,h={v:1,cleared:p?.cleared??0,r:p?.r??{}};await this.applyShard(a,c,h,r),this.etags.set(o.path,d.etag),s["etag:"+o.path]=d.etag}Object.keys(s).length&&await this.log.setMeta(s)}async applyShard(e,t,r,s){let o=new Map,i=0;for(let h of s)h.db!==e||h.store!==t||(h.kind==="clear"?i=Math.max(i,h.ts):o.set(h.kid,Math.max(o.get(h.kid)??0,h.ts)));let a=`cleared:${e}/${t}`,c=await this.log.getMeta(a)??0,l=this.schemas.get(e)?.get(t),d=[],p=!1;await this.withStore(e,t,"readwrite",h=>{r.cleared>c&&r.cleared>i&&(h.clear(),p=!0);for(let f of Object.keys(r.r)){let g=r.r[f];if((o.get(f)??0)>=g.t||g.t<=i)continue;let w=X(g.k);if(d.push(w),g.d)h.delete(w);else{let _=g._decoded;l&&l.keyPath!==null?h.put(_):h.put(_,w)}}if(p)for(let f of s)f.db!==e||f.store!==t||f.kind!=="put"||f.ts<=r.cleared||(l&&l.keyPath!==null?h.put(f.value):h.put(f.value,X(f.key)))},async()=>{for(let h of Object.keys(r.r)){let f=r.r[h];f.d||(o.get(h)??0)>=f.t||f.t<=i||(f._decoded=await k(f.v,g=>this.deps.remote.getBlob(g.ref)))}}),r.cleared>c&&await this.log.setMeta({[a]:r.cleared}),(d.length>0||p)&&this.emitChange({db:e,store:t,keys:d,cleared:p,source:"remote"})}emitChange(e){this.moved=!0,this.deps.events.emit("db:change",e);try{this.channel?.postMessage(e)}catch{}}conn(e){let t=this.conns.get(e);return t||(t=new Promise((r,s)=>{let i=(this.hook?this.hook.originalOpen:a=>indexedDB.open(a))(e);i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>{a.close(),this.conns.delete(e)},r(a)},i.onerror=()=>s(i.error??new Error(`cannot open ${e}`)),i.onblocked=()=>s(new Error(`open of ${e} blocked`))}),this.conns.set(e,t),t.catch(()=>this.conns.delete(e))),t}async withStore(e,t,r,s,o){o&&await o();let i=await this.conn(e);if(!i.objectStoreNames.contains(t))return;let a=i.transaction(t,r);s(a.objectStore(t)),await D(a)}};var P=class{constructor(e){u(this,"files",e)}async list(e){let t=[],r;do{let s=await this.files.list({prefix:e,limit:1e3,...r?{cursor:r}:{}});for(let o of s.files)o.etag&&t.push({path:o.path,etag:o.etag});r=s.next_cursor}while(r);return t}async getJSON(e,t){let r=await this.files.readJSON(e,t?{ifNoneMatch:t}:void 0);return r.notModified?{status:"unchanged"}:r.value===void 0?{status:"missing"}:{status:"ok",value:r.value,etag:r.etag??""}}async putJSON(e,t,r){try{let s=await this.files.put(e,JSON.stringify(t),{contentType:"application/json",...r.ifMatch?{ifMatch:r.ifMatch}:{},...r.ifNoneMatch?{ifNoneMatch:!0}:{}});return{status:"ok",etag:s.etag??"",serverTime:s.last_modified?Date.parse(s.last_modified):void 0}}catch(s){let o=s.statusCode;if(o===412||o===409)return{status:"conflict"};throw s}}async putBlob(e,t){try{await this.files.put(e,t,{contentType:t.type||"application/octet-stream",ifNoneMatch:!0})}catch(r){if(r.statusCode!==409)throw r}}getBlob(e){return this.files.get(e)}};var Un="https://www.runapps.ai",L=class{constructor(e={}){u(this,"chat");u(this,"models");u(this,"image");u(this,"audio");u(this,"video");u(this,"computer");u(this,"files");u(this,"embeddings");u(this,"auth",null);u(this,"sync",null);u(this,"events",new R);let t=e.authProvider??(!e.apiKey&&!e.apiKeyResolver&&typeof window<"u"?"runapps":"static"),r=e.apiKeyResolver,s=e.baseURL,o;if(t==="runapps"||t==="runjobs"){s=s??"https://www.runapps.ai";let c=e.showIdentityBadge!==void 0?e.showIdentityBadge:e.hideIdentityBadge!==void 0?!e.hideIdentityBadge:!0,l=new U({origin:s,hideBadge:!c,events:this.events,...e.badgePosition!==void 0&&{badgePosition:e.badgePosition},...e.project!==void 0&&{project:e.project}});this.auth=l,r=l.getToken,o=()=>l.invalidate()}if(!e.apiKey&&!r)throw new Error("runapps: pass `apiKey` (or `apiKeyResolver`); outside a browser there is no sign-in to fall back to");let i=new ae({baseURL:s??Un,...e.apiKey!==void 0&&{apiKey:e.apiKey},...r!==void 0&&{apiKeyResolver:r},...o!==void 0&&{onUnauthorized:o},...e.fetch?{fetchImpl:e.fetch}:{}});this.chat=new ce(i,this.events),this.models=new le(i),this.image=new ue(i,this.events),this.audio=new de(i,this.events),this.video=new fe(i,this.events),this.computer=new he(i,this.events),this.files=new Y(i,e.project,this.events),this.embeddings=new ge(i,this.events);let a=e.sync??this.auth!==null;if(a&&typeof indexedDB<"u"&&this.auth){let c=this.auth,l=new I({remote:new P(new Y(i,e.project)),events:this.events,userId:()=>c.ownerId(),onAuthChange:d=>c.onTokenChange(()=>d())},typeof a=="object"?a:{});this.sync=l}}signIn(){this.auth?.signIn()}signOut(){this.auth?.signOut()}get user(){return this.auth?.user??null}};function Mt(n){return n?n.map(e=>Array.isArray(e)?{fields:e}:e):[]}function te(n){let e=n.options;return!e||typeof e!="object"?null:e}function jt(n,e){let r=te(n)?.inputs?.[e];return r?r.presence!=="forbidden":!1}function Ut(n,e){return te(n)?.inputs?.[e]?.presence==="required"}function Nt(n,e){return te(n)?.inputs?.[e]?.enum??null}function Kt(n,e={}){if(!n)return[];let t=[];if(n.inputs)for(let[r,s]of Object.entries(n.inputs)){let o=r in e,i=e[r];o&&!A(i)?t.push(...$t(r,s,i)):o&&s.min_items!==void 0&&Array.isArray(i)&&i.length<s.min_items&&t.push({field:r,reason:`at least ${s.min_items} items`}),t.push(...Vt(r,s,i,o))}for(let r of n.constraints??[])t.push(...Nn(r,e));return t}function $t(n,e,t){let r=[];if(!Fn(e.type,t))return r.push({field:n,reason:`expected type ${e.type}, got ${Te(t)}`}),r;if(e.enum&&e.enum.length>0&&!Ln(t,e.enum)&&r.push({field:n,reason:`must be one of ${JSON.stringify(e.enum)}`}),e.type==="int"||e.type==="float"){let s=qt(t);s!==null&&(e.min!==void 0&&s<e.min&&r.push({field:n,reason:`must be >= ${e.min}`}),e.max!==void 0&&s>e.max&&r.push({field:n,reason:`must be <= ${e.max}`}))}return Array.isArray(t)&&(e.max_items!==void 0&&t.length>e.max_items&&r.push({field:n,reason:`at most ${e.max_items} items`}),e.min_items!==void 0&&t.length<e.min_items&&r.push({field:n,reason:`at least ${e.min_items} items`})),e.fields&&(e.repeatable?Array.isArray(t)?t.forEach((s,o)=>{if(typeof s!="object"||s===null||Array.isArray(s)){r.push({field:`${n}[${o}]`,reason:`expected object, got ${Te(s)}`});return}r.push(...Ft(`${n}[${o}]`,e.fields,s))}):r.push({field:n,reason:`expected array of objects, got ${Te(t)}`}):typeof t!="object"||t===null||Array.isArray(t)?r.push({field:n,reason:`expected object, got ${Te(t)}`}):r.push(...Ft(n,e.fields,t))),r}function Ft(n,e,t){let r=[];for(let[s,o]of Object.entries(e)){let i=`${n}.${s}`,a=t[s],c=s in t;c&&!A(a)&&r.push(...$t(i,o,a)),r.push(...Vt(i,o,a,c))}return r}function Vt(n,e,t,r){let s=e.presence??"optional";return s==="required"&&(!r||A(t))?[{field:n,reason:"required"}]:s==="forbidden"&&r&&!A(t)?[{field:n,reason:"must not be set for this model"}]:[]}function Nn(n,e){switch(n.kind){case"any_of_required":{let t=n.fields??[];return t.some(s=>s in e&&!A(e[s]))?[]:[{field:t.join("/"),reason:`at least one of ${t.join(", ")} is required`}]}case"mutually_exclusive":{let t=n.fields??[],r=t.filter(s=>s in e&&!A(e[s]));return r.length>1?[{field:r.join("/"),reason:`at most one of ${t.join(", ")} may be set (got: ${r.join(", ")})`}]:[]}case"group_mutex":{let t=Mt(n.groups),r=[],s=[];for(let o of t){let i=o.fields.filter(a=>a in e&&!A(e[a]));i.length>0&&(r.push(o),s.push(...i))}if(r.length>1){let o=t.map(i=>`[${i.fields.join("+")}]`).join(" or ");return[{field:s.join("/"),reason:`at most one of ${o} may be used (got: ${s.join(", ")})`}]}return[]}case"requires_all":{let t=n.when;if(!t)return[];if(!(t in e&&!A(e[t])))return[];let s=(n.then??[]).filter(o=>!(o in e)||A(e[o]));return s.length===0?[]:[{field:s.join("/"),reason:`required when ${t} is set`}]}case"pixel_bounds":{let t=n.fields?.[0];if(!t)return[];let r=e[t];if(typeof r!="string"||r==="")return[];let s=$n(r);if(!s)return[{field:t,reason:`expected WxH dimensions, got "${r}"`}];let[o,i]=s,a=o*i,c=[];return n.min!==void 0&&a<n.min&&c.push({field:t,reason:`image too small: ${o}x${i} = ${a} pixels, minimum ${n.min}`}),n.max!==void 0&&a>n.max&&c.push({field:t,reason:`image too large: ${o}x${i} = ${a} pixels, maximum ${n.max}`}),c}}return[]}function Fn(n,e){switch(n){case"string":return typeof e=="string";case"int":case"float":return qt(e)!==null;case"bool":return typeof e=="boolean";case"url":return typeof e=="string"&&Lt(e);case"url[]":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&Lt(t));case"string[]":return Array.isArray(e)&&e.every(t=>typeof t=="string");case"file":return!0;default:return!0}}function Te(n){return n===null?"null":Array.isArray(n)?"array":typeof n}function qt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Lt(n){return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")}function A(n){return n==null?!0:typeof n=="string"?n==="":Array.isArray(n)?n.length===0:!1}function Ln(n,e){for(let t of e)if(Kn(n,t))return!0;return!1}function Kn(n,e){return n===e}function $n(n){for(let e of["x","X","*","\xD7"]){let t=n.indexOf(e);if(t<=0)continue;let r=parseInt(n.slice(0,t).trim(),10),s=parseInt(n.slice(t+e.length).trim(),10);if(Number.isFinite(r)&&Number.isFinite(s)&&r>0&&s>0)return[r,s]}return null}return Xt(Vn);})();
|
|
4
4
|
RunApps = Object.assign(RunApps.Client, RunApps); var RunJobs = RunApps;
|
|
5
5
|
//# sourceMappingURL=sdk.umd.js.map
|