(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,464143,e=>{"use strict";function t(e){for(var t=1;ttypeof document){"number"==typeof(n=t({},o,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in n)n[a]&&(i+="; "+a,!0!==n[a]&&(i+="="+n[a].split(";")[0]));return document.cookie=e+"="+r.write(s,e)+i}}return Object.create({set:s,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},s=0;sr])},842090,443344,e=>{"use strict";let t={"&":"&","<":"<",">":">",'"':""","'":"'"};function r(e){return e.replace(/[&<>"']/g,e=>t[e])}async function o(e){try{return[null,await e]}catch(e){return[e||Error("unknown error")]}}async function s(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,[r,n]=await o(e);return r?t>0?await s(e,t-1):r instanceof Error?[r]:[Error("unknown error")]:[null,n]}e.s(["escape",()=>r],443344),e.s(["asyncRunSafe",()=>o,"canFindTool",0,(e,t)=>e===t||e===`langgenius/${t}/${t}`||e===`langgenius/${t}_tool/${t}`,"correctModelProvider",0,e=>e?e.includes("/")?e:["google"].includes(e)?"langgenius/gemini/google":`langgenius/${e}/${e}`:"","correctToolProvider",0,(e,t)=>e?t||e.includes("/")?e:["stepfun","jina","siliconflow","gitee_ai"].includes(e)?`langgenius/${e}_tool/${e}`:`langgenius/${e}/${e}`:"","fetchWithRetry",()=>s,"getPurifyHref",0,e=>e?r(e):"","getTextWidthWithCanvas",0,(e,t)=>{let r=document.createElement("canvas").getContext("2d");return r?(r.font=t??'12px Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',Number(r.measureText(e).width.toFixed(2))):0},"sleep",0,e=>new Promise(t=>setTimeout(t,e))],842090)},367916,680173,351124,e=>{"use strict";e.s(["del",()=>eR,"delPublic",()=>eT,"get",()=>eg,"getMarketplace",()=>ey,"getPublic",()=>em,"handleStream",()=>eu,"patch",()=>ev,"patchPublic",()=>eA,"post",()=>eb,"postMarketplace",()=>ew,"postPublic",()=>e_,"put",()=>eE,"request",()=>ef,"sseGet",()=>ep,"ssePost",()=>ed,"upload",()=>eh],367916);var t=e.i(464143),r=e.i(137667),o=e.i(925521),s=e.i(842090),n=e.i(168014);e.s(["ContentType",()=>W,"base",()=>Q,"getBaseOptions",()=>Z,"postWithKeepalive",()=>Y],351124);class i extends Error{response;request;options;constructor(e,t,r){const o=e.status||0===e.status?e.status:"",s=e.statusText??"",n=`${o} ${s}`.trim(),i=n?`status code ${n}`:"an unknown error";super(`Request failed with ${i}: ${t.method} ${t.url}`),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class a extends Error{name="NonError";value;constructor(e){let t="Non-error value was thrown";try{"string"==typeof e?t=e:e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(t=e.message)}catch{}super(t),this.value=e}}class l extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(e){const t=e?.cause?e.cause instanceof Error?e.cause:new a(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:"Forced retry",t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}}let u=(()=>{let e=!1,t=!1,r="function"==typeof globalThis.Request;if("function"==typeof globalThis.ReadableStream&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(e){if(e instanceof Error&&"unsupported BodyInit type"===e.message)return!1;throw e}return e&&!t})(),c="function"==typeof globalThis.AbortController,h="function"==typeof globalThis.AbortSignal&&"function"==typeof globalThis.AbortSignal.any,d="function"==typeof globalThis.ReadableStream,p="function"==typeof globalThis.FormData,f=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},m=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,y=Symbol("stop");class b{options;constructor(e){this.options=e}}let w=e=>new b(e),_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},E={next:!0},R={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},T=(e,t,r)=>{let o,s=0;return e.pipeThrough(new TransformStream({transform(e,n){if(n.enqueue(e),o){s+=o.byteLength;let e=0===t?0:s/t;e>=1&&(e=1-Number.EPSILON),r?.({percent:e,totalBytes:Math.max(t,s),transferredBytes:s},o)}o=e},flush(){o&&(s+=o.byteLength,r?.({percent:1,totalBytes:Math.max(t,s),transferredBytes:s},o))}}))},v=e=>null!==e&&"object"==typeof e,A=function(){for(var e=arguments.length,t=Array(e),r=0;r0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=new globalThis.Headers(e),o=t instanceof globalThis.Headers;for(let[e,s]of new globalThis.Headers(t).entries())o&&"undefined"===s||void 0===s?r.delete(e):r.set(e,s);return r};function S(e,t,r){return Object.hasOwn(t,r)&&void 0===t[r]?[]:I(e[r]??[],t[r]??[])}let C=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{beforeRequest:S(e,t,"beforeRequest"),beforeRetry:S(e,t,"beforeRetry"),afterResponse:S(e,t,"afterResponse"),beforeError:S(e,t,"beforeError")}},O=(e,t)=>{let r=new URLSearchParams;for(let o of[e,t])if(void 0!==o)if(o instanceof URLSearchParams)for(let[e,t]of o.entries())r.append(e,t);else if(Array.isArray(o))for(let e of o){if(!Array.isArray(e)||2!==e.length)throw TypeError("Array search parameters must be provided in [[key, value], ...] format");r.append(String(e[0]),String(e[1]))}else if(v(o))for(let[e,t]of Object.entries(o))void 0!==t&&r.append(e,String(t));else for(let[e,t]of new URLSearchParams(o).entries())r.append(e,t);return r},I=function(){let e;for(var t=arguments.length,r=Array(t),o=0;o0&&(1===a.length?s.signal=a[0]:h?s.signal=AbortSignal.any(a):s.signal=a.at(-1)),s},j={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:1/0,backoffLimit:1/0,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},q=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("number"==typeof e)return{...j,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error("retry.methods must be an array");if(e.methods&&=e.methods.map(e=>e.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw Error("retry.statusCodes must be an array");let t=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t}));return{...j,...t}};class x extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}async function N(e,t,r,o){return new Promise((s,n)=>{let i=setTimeout(()=>{r&&r.abort(),n(new x(e))},o.timeout);o.fetch(e,t).then(s).catch(n).then(()=>{clearTimeout(i)})})}async function L(e,t){let{signal:r}=t;return new Promise((t,o)=>{function s(){clearTimeout(n),o(r.reason)}r&&(r.throwIfAborted(),r.addEventListener("abort",s,{once:!0}));let n=setTimeout(()=>{r?.removeEventListener("abort",s),t()},e)})}class D{static create(e,t){let r=new D(e,t),o=async()=>{if("number"==typeof r.#e.timeout&&r.#e.timeout>0x7fffffff)throw RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await r.#t();for(let t of r.#e.hooks.afterResponse){let o,s=r.#r(e.clone());try{o=await t(r.request,r.#o(),s,{retryCount:r.#s})}catch(t){throw r.#n(s),r.#n(e),t}if(o instanceof b)throw r.#n(s),r.#n(e),new l(o.options);let n=o instanceof globalThis.Response?o:e;s!==n&&r.#n(s),e!==n&&r.#n(e),e=n}if(r.#r(e),!e.ok&&("function"==typeof r.#e.throwHttpErrors?r.#e.throwHttpErrors(e.status):r.#e.throwHttpErrors)){let t=new i(e,r.request,r.#o());for(let e of r.#e.hooks.beforeError)t=await e(t,{retryCount:r.#s});throw t}if(r.#e.onDownloadProgress){if("function"!=typeof r.#e.onDownloadProgress)throw TypeError("The `onDownloadProgress` option must be a function");if(!d)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");let o=e.clone();r.#n(e);var t=r.#e.onDownloadProgress;if(!o.body)return o;if(204===o.status)return new Response(null,{status:o.status,statusText:o.statusText,headers:o.headers});let s=Math.max(0,Number(o.headers.get("content-length"))||0);return new Response(T(o.body,s,t),{status:o.status,statusText:o.statusText,headers:o.headers})}return e},s=r.#i(o).finally(()=>{let e=r.#a;r.#l(e?.body??void 0),r.#l(r.request.body??void 0)});for(let[e,o]of Object.entries(g))("bytes"!==e||"function"==typeof globalThis.Response?.prototype?.bytes)&&(s[e]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||o);let n=await s;if("json"===e){if(204===n.status)return"";let e=await n.text();return""===e?"":t.parseJson?t.parseJson(e):JSON.parse(e)}return n[e]()});return s}static #u(e){return!e||"object"!=typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t}))}request;#c;#s=0;#h;#e;#a;#d;#p;constructor(e,t={}){if(this.#h=e,this.#e={...t,headers:P(this.#h.headers,t.headers),hooks:C({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:(e=>f.includes(e)?e.toUpperCase():e)(t.method??this.#h.method??"GET"),prefixUrl:String(t.prefixUrl||""),retry:q(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},"string"!=typeof this.#h&&!(this.#h instanceof URL||this.#h instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this.#e.prefixUrl&&"string"==typeof this.#h){if(this.#h.startsWith("/"))throw Error("`input` must not begin with a slash when using `prefixUrl`");this.#e.prefixUrl.endsWith("/")||(this.#e.prefixUrl+="/"),this.#h=this.#e.prefixUrl+this.#h}c&&h&&(this.#d=this.#e.signal??this.#h.signal,this.#c=new globalThis.AbortController,this.#e.signal=this.#d?AbortSignal.any([this.#d,this.#c.signal]):this.#c.signal),u&&(this.#e.duplex="half"),void 0!==this.#e.json&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));const r=t.headers&&new globalThis.Headers(t.headers).has("content-type");if(this.#h instanceof globalThis.Request&&(p&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!r&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#h,this.#e),(e=>void 0!==e&&(Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:"object"==typeof e?Object.keys(e).length>0:"string"==typeof e?e.trim().length>0:!!e))(this.#e.searchParams)){const e="string"==typeof this.#e.searchParams?this.#e.searchParams.replace(/^\?/,""):new URLSearchParams(D.#u(this.#e.searchParams)).toString(),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,"?"+e);this.request=new globalThis.Request(t,this.#e)}if(this.#e.onUploadProgress){if("function"!=typeof this.#e.onUploadProgress)throw TypeError("The `onUploadProgress` option must be a function");if(!u)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#f(this.request,this.#e.body??void 0)}}#g(){let e=this.#e.retry.delay(this.#s),t=e;return!0===this.#e.retry.jitter?t=Math.random()*e:"function"==typeof this.#e.retry.jitter&&(!Number.isFinite(t=this.#e.retry.jitter(e))||t<0)&&(t=e),Math.min(this.#e.retry.backoffLimit??1/0,t)}async #m(e){if(this.#s++,this.#s>this.#e.retry.limit)throw e;let t=e instanceof Error?e:new a(e);if(t instanceof l)return t.customDelay??this.#g();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(void 0!==this.#e.retry.shouldRetry){let r=await this.#e.retry.shouldRetry({error:t,retryCount:this.#s});if(!1===r)throw e;if(!0===r)return this.#g()}if((e instanceof x||e?.name===x.name)&&!this.#e.retry.retryOnTimeout)throw e;if(e instanceof i||e?.name===i.name){if(!this.#e.retry.statusCodes.includes(e.response.status))throw e;let t=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Retry-After")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(t&&this.#e.retry.afterStatusCodes.includes(e.response.status)){let e=1e3*Number(t);Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse("2024-01-01")&&(e-=Date.now());let r=this.#e.retry.maxRetryAfter??e;return ethis.#e.parseJson(await e.text())),e}#l(e){e&&e.cancel().catch(()=>void 0)}#n(e){this.#l(e.body??void 0)}async #i(e){try{return await e()}catch(r){let t=Math.min(await this.#m(r),0x7fffffff);if(this.#s<1)throw r;if(await L(t,this.#d?{signal:this.#d}:{}),r instanceof l&&r.customRequest){let e=this.#e.signal?new globalThis.Request(r.customRequest,{signal:this.#e.signal}):new globalThis.Request(r.customRequest);this.#y(e)}for(let e of this.#e.hooks.beforeRetry){let t=await e({request:this.request,options:this.#o(),error:r,retryCount:this.#s});if(t instanceof globalThis.Request){this.#y(t);break}if(t instanceof globalThis.Response)return t;if(t===y)return}return this.#i(e)}}async #t(){for(let e of(this.#c?.signal.aborted&&(this.#c=new globalThis.AbortController,this.#e.signal=this.#d?AbortSignal.any([this.#d,this.#c.signal]):this.#c.signal,this.request=new globalThis.Request(this.request,{signal:this.#e.signal})),this.#e.hooks.beforeRequest)){let t=await e(this.request,this.#o(),{retryCount:this.#s});if(t instanceof Response)return t;if(t instanceof globalThis.Request){this.#y(t);break}}let e=((e,t)=>{let r={};for(let o in t)Object.hasOwn(t,o)&&(o in R||o in _||o in e&&!(o in E)||(r[o]=t[o]));return r})(this.request,this.#e);return(this.#a=this.request,this.request=this.#a.clone(),!1===this.#e.timeout)?this.#e.fetch(this.#a,e):N(this.#a,e,this.#c,this.#e)}#o(){if(!this.#p){let{hooks:e,...t}=this.#e;this.#p=Object.freeze(t)}return this.#p}#y(e){this.#p=void 0,this.request=this.#f(e)}#f(e,t){return this.#e.onUploadProgress&&e.body?((e,t,r)=>{if(!e.body)return e;let o=(e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,o]of e)t+=m,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+="string"==typeof o?new TextEncoder().encode(o).length:o.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if("string"==typeof e)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if("object"==typeof e&&null!==e)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{}return 0})(r??e.body);return new Request(e,{duplex:"half",body:T(e.body,o,t)})})(e,this.#e.onUploadProgress,t??this.#e.body??void 0):e}}let U=e=>{let t=(t,r)=>D.create(t,A(e,r));for(let r of f)t[r]=(t,o)=>D.create(t,A(e,o,{method:r}));return t.create=e=>U(A(e)),t.extend=t=>("function"==typeof t&&(t=t(e??{})),U(A(e,t))),t.stop=y,t.retry=w,t},M=U();function $(e){localStorage.setItem(o.ACCESS_TOKEN_LOCAL_STORAGE_NAME,e)}function k(e,t){localStorage.setItem((0,o.PASSPORT_LOCAL_STORAGE_NAME)(e),t)}function B(){return localStorage.getItem(o.ACCESS_TOKEN_LOCAL_STORAGE_NAME)||""}function H(e){return localStorage.getItem((0,o.PASSPORT_LOCAL_STORAGE_NAME)(e))||""}async function F(e,t){let r=new URLSearchParams({app_code:e});t&&r.append("user_id",t);let{logged_in:o,app_logged_in:s}=await em(`/login/status?${r.toString()}`);return{userLoggedIn:o,appLoggedIn:s}}async function z(e){localStorage.removeItem(o.ACCESS_TOKEN_LOCAL_STORAGE_NAME),localStorage.removeItem((0,o.PASSPORT_LOCAL_STORAGE_NAME)(e)),await e_("/logout")}e.s(["getWebAppAccessToken",()=>B,"getWebAppPassport",()=>H,"setWebAppAccessToken",()=>$,"setWebAppPassport",()=>k,"webAppLoginStatus",()=>F,"webAppLogout",()=>z],680173);let W={json:"application/json",stream:"text/event-stream",audio:"audio/mpeg",form:"application/x-www-form-urlencoded; charset=UTF-8",download:"application/octet-stream",downloadZip:"application/zip",upload:"multipart/form-data"},J=async(e,t,r)=>{if(204===r.status)return new Response(JSON.stringify({result:"success"}),{status:200,headers:{"Content-Type":W.json}})},K=new Set(["webapp-signin","check-code","login"]),X=e=>{let t=B();t?e.headers.set("Authorization",`Bearer ${t}`):e.headers.delete("Authorization");let r=(()=>{let e=globalThis.location.pathname.split("/").filter(Boolean).at(-1)||"";if(e&&!K.has(e))return e;let t=new URLSearchParams(globalThis.location.search).get("redirect_url");if(!t)return"";try{let e=new URL(decodeURIComponent(t),globalThis.location.origin).pathname.split("/").filter(Boolean).at(-1)||"";return K.has(e)?"":e}catch{return""}})();r&&(e.headers.set(o.WEB_APP_SHARE_CODE_HEADER_NAME,r),e.headers.set(o.PASSPORT_HEADER_NAME,H(r)))},G={afterResponse:[J]},V=M.create({hooks:G,timeout:1e5}),Z=()=>({method:"GET",mode:"cors",credentials:"include",headers:new Headers({"Content-Type":W.json}),redirect:"follow"});async function Q(e){let s,n,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{params:u,body:c,headers:h,...d}={...l.fetchCompat?{mode:"cors",credentials:"include",redirect:"follow"}:{mode:"cors",credentials:"include",headers:new Headers({"Content-Type":W.json}),method:"GET",redirect:"follow"},...a},p=new Headers(h||{}),{isPublicAPI:f=!1,isMarketplaceAPI:g=!1,bodyStringify:m=!0,needAllResponseContent:y,deleteContentType:b,getAbortController:w,fetchCompat:_=!1,request:E}=l;if(s=g?o.MARKETPLACE_API_PREFIX:f?o.PUBLIC_API_PREFIX:o.API_PREFIX,w){let e=new AbortController;w(e),a.signal=e.signal}let R=s+(e.startsWith("/")?e:`/${e}`);g||p.set(o.CSRF_HEADER_NAME,t.default.get((0,o.CSRF_COOKIE_NAME)())||""),b&&p.delete("Content-Type"),g&&p.set("X-Dify-Version",o.IS_MARKETPLACE?"999.0.0":o.APP_VERSION);let T=V.extend({hooks:{...G,beforeRequest:[...G.beforeRequest||[],f&&X].filter(e=>!!e),afterResponse:[...G.afterResponse||[],async(e,t,o)=>{if(!/^([23])\d{2}$/.test(String(o.status))){let e=await o.clone().json().then(e=>e).catch(()=>null);401!==o.status&&e&&!l.silent&&r.default.notify({type:"error",message:e.message}),403===o.status&&e?.code==="already_setup"&&(globalThis.location.href=`${globalThis.location.origin}/signin`)}}]}});try{n=await T(E||R,{...d,headers:p,credentials:g?"omit":a.credentials||"include",retry:{methods:[]},...m&&!_?{json:c}:{body:c},searchParams:_?void 0:u,fetch(e,t){if(e instanceof Request&&t){let r=new Headers(t.headers||{});e.headers.forEach((e,t)=>{r.append(t,e)}),t.headers=r}return globalThis.fetch(e,t)}})}catch(e){if(e instanceof i)throw e.response.clone();throw e}if(y||_)return n;let v=n.headers.get("content-type");return v&&[W.download,W.audio,W.downloadZip].includes(v)?await n.blob():await n.json()}function Y(e,r){let s={"Content-Type":W.json,[o.CSRF_HEADER_NAME]:t.default.get((0,o.CSRF_COOKIE_NAME)())||""},n=B();n&&(s.Authorization=`Bearer ${n}`),globalThis.fetch(e,{method:"POST",keepalive:!0,credentials:"include",headers:s,body:JSON.stringify(r)}).catch(()=>{})}let ee="is_other_tab_refreshing",et=!1;async function er(e){try{var t;let r=globalThis.localStorage.getItem(ee);if(r&&"1"===r&&(t=e,new Date().getTime()-Number.parseInt(globalThis.localStorage.getItem("last_refresh_time")||"0")<=t)||et)await new Promise(e=>{!function t(){let r=globalThis.localStorage.getItem(ee);r&&"1"===r||et?setTimeout(()=>{t()},1e3):e()}()});else{et=!0,globalThis.localStorage.setItem(ee,"1"),globalThis.localStorage.setItem("last_refresh_time",new Date().getTime().toString()),globalThis.addEventListener("beforeunload",eo);let[e,t]=await (0,s.fetchWithRetry)(globalThis.fetch(`${o.API_PREFIX}/refresh-token`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json;utf-8"}}));if(e)return Promise.reject(e);if(401===t.status)return Promise.reject(t)}}catch(e){return console.error(e),Promise.reject(e)}finally{eo()}}function eo(){et=!1,globalThis.localStorage.removeItem(ee),globalThis.localStorage.removeItem("last_refresh_time"),globalThis.removeEventListener("beforeunload",eo)}async function es(e){return Promise.race([new Promise((t,r)=>setTimeout(()=>{eo(),r(Error("request timeout"))},e)),er(e)])}function en(e){e&&new URL(e,globalThis.location.origin).pathname!==globalThis.location.pathname&&(globalThis.location.href=e)}let ei="/webapp-signin";function ea(e,t){let r=new URLSearchParams;globalThis.location.pathname!==ei&&(r.append("redirect_url",encodeURIComponent(`${globalThis.location.pathname}${globalThis.location.search}`)),e&&r.append("message",e),t&&r.append("code",String(t)),globalThis.location.href=`${globalThis.location.origin}${n.basePath}${ei}?${r.toString()}`)}function el(e,t){let r=t?o.PUBLIC_API_PREFIX:o.API_PREFIX;if(e.startsWith("http://")||e.startsWith("https://"))return e;let s=e.startsWith("/")?e:`/${e}`;return`${r}${s}`}let eu=(e,t,r,o,s,n,i,a,l,u,c,h,d,p,f,g,m,y,b,w,_,E,R,T,v,A,P,S,C,O,I,j)=>{let q;if(!e.ok)throw Error("Network response was not ok");let x=e.body?.getReader(),N=new TextDecoder("utf-8"),L="",D=!0;!function e(){let U=!1;x?.read().then(x=>{if(x.done)return void r?.();let M=(L+=N.decode(x.value,{stream:!0})).split("\n");try{M.forEach(e=>{if(e.startsWith("data: ")){try{q=JSON.parse(e.substring(6))}catch{t("",D,{conversationId:q?.conversation_id,messageId:q?.message_id});return}if(!q||"object"!=typeof q){t("",D,{conversationId:void 0,messageId:"",errorMessage:"Invalid response data",errorCode:"invalid_data"}),U=!0,r?.(!0,"Invalid response data");return}if(400===q.status||!q.event){t("",!1,{conversationId:void 0,messageId:"",errorMessage:q?.message,errorCode:q?.code}),U=!0,r?.(!0,q?.message);return}if("message"===q.event||"agent_message"===q.event){var x;t((x=q.answer)?x.replace(/\\u([0-9a-f]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16))):"",D,{conversationId:q.conversation_id,taskId:q.task_id,messageId:q.id}),D=!1}else"agent_thought"===q.event?o?.(q):"message_file"===q.event?i?.(q):"message_end"===q.event?s?.(q):"message_replace"===q.event?n?.(q):"workflow_started"===q.event?a?.(q):"workflow_finished"===q.event?l?.(q):"node_started"===q.event?u?.(q):"node_finished"===q.event?c?.(q):"iteration_started"===q.event?h?.(q):"iteration_next"===q.event?d?.(q):"iteration_completed"===q.event?p?.(q):"loop_started"===q.event?f?.(q):"loop_next"===q.event?g?.(q):"loop_completed"===q.event?m?.(q):"node_retry"===q.event?y?.(q):"parallel_branch_started"===q.event?b?.(q):"parallel_branch_finished"===q.event?w?.(q):"text_chunk"===q.event?_?.(q):"text_replace"===q.event?T?.(q):"agent_log"===q.event?v?.(q):"tts_message"===q.event?E?.(q.message_id,q.audio,q.audio_type):"tts_message_end"===q.event?R?.(q.message_id,q.audio):"human_input_required"===q.event?A?.(q):"human_input_form_filled"===q.event?P?.(q):"human_input_form_timeout"===q.event?S?.(q):"workflow_paused"===q.event?C?.(q):"datasource_processing"===q.event?O?.(q):"datasource_completed"===q.event?I?.(q):"datasource_error"===q.event?j?.(q):console.warn(`Unknown event: ${q.event}`,q)}}),L=M[M.length-1]}catch(e){t("",!1,{conversationId:void 0,messageId:"",errorMessage:`${e}`}),U=!0,r?.(!0,e);return}U||e()})}()},ec=Q,eh=async(e,r,s,n)=>{let i=r?o.PUBLIC_API_PREFIX:o.API_PREFIX,a=globalThis.location.pathname.split("/").slice(-1)[0],l={method:"POST",url:(s?`${i}${s}`:`${i}/files/upload`)+(n||""),headers:{[o.CSRF_HEADER_NAME]:t.default.get((0,o.CSRF_COOKIE_NAME)())||"",[o.PASSPORT_HEADER_NAME]:H(a),[o.WEB_APP_SHARE_CODE_HEADER_NAME]:a}},u={...l,...e,url:e.url||l.url,headers:{...l.headers,...e.headers}};return new Promise((e,t)=>{let r=u.xhr;for(let e in r.open(u.method,u.url),u.headers)r.setRequestHeader(e,u.headers[e]);r.withCredentials=!0,r.responseType="json",r.onreadystatechange=function(){4===r.readyState&&(201===r.status?e(r.response):t(r))},u.onprogress&&(r.upload.onprogress=u.onprogress),r.send(u.data)})},ed=async(e,s,n)=>{let{isPublicAPI:i=!1,onData:a,onCompleted:l,onThought:u,onFile:c,onMessageEnd:h,onMessageReplace:d,onWorkflowStarted:p,onWorkflowFinished:f,onNodeStarted:g,onNodeFinished:m,onIterationStart:y,onIterationNext:b,onIterationFinish:w,onNodeRetry:_,onParallelBranchStarted:E,onParallelBranchFinished:R,onTextChunk:T,onTTSChunk:v,onTTSEnd:A,onTextReplace:P,onAgentLog:S,onError:C,getAbortController:O,onLoopStart:I,onLoopNext:j,onLoopFinish:q,onHumanInputRequired:x,onHumanInputFormFilled:N,onHumanInputFormTimeout:L,onWorkflowPaused:D,onDataSourceNodeProcessing:U,onDataSourceNodeCompleted:M,onDataSourceNodeError:$}=n,k=new AbortController,B=Z(),F=globalThis.location.pathname.split("/").slice(-1)[0],z=Object.assign({},B,{method:"POST",signal:k.signal,headers:new Headers({[o.CSRF_HEADER_NAME]:t.default.get((0,o.CSRF_COOKIE_NAME)())||"",[o.WEB_APP_SHARE_CODE_HEADER_NAME]:F,[o.PASSPORT_HEADER_NAME]:H(F)})},s);z.headers.get("Content-Type")||z.headers.set("Content-Type",W.json),O?.(k);let J=el(e,i),{body:K}=z;K&&(z.body=JSON.stringify(K)),globalThis.fetch(J,z).then(t=>/^[23]\d{2}$/.test(String(t.status))?eu(t,(e,t,o)=>{if(o.errorMessage){C?.(o.errorMessage,o.errorCode),"AbortError: The user aborted a request."===o.errorMessage||o.errorMessage.includes("TypeError: Cannot assign to read only property")||r.default.notify({type:"error",message:o.errorMessage});return}a?.(e,t,o)},l,u,h,d,c,p,f,g,m,y,b,w,I,j,q,_,E,R,T,v,A,P,S,x,N,L,D,U,M,$):void(401===t.status?i?t.json().then(e=>{i&&("web_app_access_denied"===e.code&&ea(e.message,403),"web_sso_auth_required"===e.code&&ea(),"unauthorized"===e.code&&ea())}):es(1e5).then(()=>{ed(e,s,n)}).catch(e=>{console.error(e)}):(t.json().then(e=>{r.default.notify({type:"error",message:e.message||"Server Error"})}),C?.("Server Error")))).catch(e=>{"AbortError: The user aborted a request."===e.toString()||e.toString().errorMessage.includes("TypeError: Cannot assign to read only property")||r.default.notify({type:"error",message:e}),C?.(e)})},ep=async(e,s,n)=>{let{isPublicAPI:i=!1,onData:a,onCompleted:l,onThought:u,onFile:c,onMessageEnd:h,onMessageReplace:d,onWorkflowStarted:p,onWorkflowFinished:f,onNodeStarted:g,onNodeFinished:m,onIterationStart:y,onIterationNext:b,onIterationFinish:w,onNodeRetry:_,onParallelBranchStarted:E,onParallelBranchFinished:R,onTextChunk:T,onTTSChunk:v,onTTSEnd:A,onTextReplace:P,onAgentLog:S,onError:C,getAbortController:O,onLoopStart:I,onLoopNext:j,onLoopFinish:q,onHumanInputRequired:x,onHumanInputFormFilled:N,onHumanInputFormTimeout:L,onWorkflowPaused:D,onDataSourceNodeProcessing:U,onDataSourceNodeCompleted:M,onDataSourceNodeError:$}=n,k=new AbortController,B=Z(),F=globalThis.location.pathname.split("/").slice(-1)[0],z=Object.assign({},B,{signal:k.signal,headers:new Headers({[o.CSRF_HEADER_NAME]:t.default.get((0,o.CSRF_COOKIE_NAME)())||"",[o.WEB_APP_SHARE_CODE_HEADER_NAME]:F,[o.PASSPORT_HEADER_NAME]:H(F)})},s);z.headers.get("Content-Type")||z.headers.set("Content-Type",W.json),O?.(k),globalThis.fetch(el(e,i),z).then(t=>/^[23]\d{2}$/.test(String(t.status))?eu(t,(e,t,o)=>{if(o.errorMessage){C?.(o.errorMessage,o.errorCode),"AbortError: The user aborted a request."===o.errorMessage||o.errorMessage.includes("TypeError: Cannot assign to read only property")||r.default.notify({type:"error",message:o.errorMessage});return}a?.(e,t,o)},l,u,h,d,c,p,f,g,m,y,b,w,I,j,q,_,E,R,T,v,A,P,S,x,N,L,D,U,M,$):void(401===t.status?i?t.json().then(e=>{i&&("web_app_access_denied"===e.code&&ea(e.message,403),"web_sso_auth_required"===e.code&&ea(),"unauthorized"===e.code&&ea())}):es(1e5).then(()=>{ep(e,s,n)}).catch(e=>{console.error(e)}):(t.json().then(e=>{r.default.notify({type:"error",message:e.message||"Server Error"})}),C?.("Server Error")))).catch(e=>{"AbortError: The user aborted a request."===e.toString()||e.toString().includes("TypeError: Cannot assign to read only property")||r.default.notify({type:"error",message:e}),C?.(e)})},ef=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;try{let a=i||{},[l,u]=await (0,s.asyncRunSafe)(ec(e,t,a));if(null===l)return u;if(401!==l.status)return Promise.reject(l);{let[i,u]=await (0,s.asyncRunSafe)(l.json()),c=`${globalThis.location.origin}${n.basePath}/signin`;if(i)return globalThis.location.href=c,Promise.reject(l);if(/\/login/.test(e))return Promise.reject(u);let{code:h,message:d}=u;if("web_app_access_denied"===h)return ea(d,403),Promise.reject(l);if("web_sso_auth_required"===h)return ea(),Promise.reject(l);if("unauthorized_and_force_logout"===h)return globalThis.location.reload(),Promise.reject(l);let{isPublicAPI:p=!1,silent:f}=a;if(p&&"unauthorized"===h)return ea(),Promise.reject(l);if("init_validate_failed"===h&&o.IS_CE_EDITION&&!f)return r.default.notify({type:"error",message:d,duration:4e3}),Promise.reject(l);if("not_init_validated"===h&&o.IS_CE_EDITION)return en(`${globalThis.location.origin}${n.basePath}/init`),Promise.reject(l);if("not_setup"===h&&o.IS_CE_EDITION)return en(`${globalThis.location.origin}${n.basePath}/install`),Promise.reject(l);let[g]=await (0,s.asyncRunSafe)(es(1e5));if(null===g)return ec(e,t,a);if(location.pathname!==`${n.basePath}/signin`||!o.IS_CE_EDITION)return en(c),Promise.reject(l);if(!f)return r.default.notify({type:"error",message:d}),Promise.reject(l);return en(c),Promise.reject(l)}}catch(e){return console.error(e),Promise.reject(e)}},eg=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return ef(e,Object.assign({},t,{method:"GET"}),r)},em=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return eg(e,t,{...r,isPublicAPI:!0})},ey=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return eg(e,t,{...r,isMarketplaceAPI:!0})},eb=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return ef(e,Object.assign({},t,{method:"POST"}),r)},ew=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return eb(e,t,{...r,isMarketplaceAPI:!0})},e_=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return eb(e,t,{...r,isPublicAPI:!0})},eE=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return ef(e,Object.assign({},t,{method:"PUT"}),r)},eR=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return ef(e,Object.assign({},t,{method:"DELETE"}),r)},eT=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return eR(e,t,{...r,isPublicAPI:!0})},ev=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return ef(e,Object.assign({},t,{method:"PATCH"}),r)},eA=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return ev(e,t,{...r,isPublicAPI:!0})}}]);