@vertesia/client 1.4.0 → 1.5.0-dev.20260713.113008Z
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 +1 -1
- package/lib/EnvironmentsApi.d.ts +3 -1
- package/lib/EnvironmentsApi.d.ts.map +1 -1
- package/lib/EnvironmentsApi.js +8 -0
- package/lib/EnvironmentsApi.js.map +1 -1
- package/lib/InternalSecretsApi.d.ts +18 -0
- package/lib/InternalSecretsApi.d.ts.map +1 -0
- package/lib/InternalSecretsApi.js +29 -0
- package/lib/InternalSecretsApi.js.map +1 -0
- package/lib/QuotaApi.d.ts +16 -0
- package/lib/QuotaApi.d.ts.map +1 -0
- package/lib/QuotaApi.js +21 -0
- package/lib/QuotaApi.js.map +1 -0
- package/lib/client.d.ts +5 -0
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +8 -0
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/store/DataApi.d.ts +2 -2
- package/lib/store/DataApi.d.ts.map +1 -1
- package/lib/store/DataApi.js +2 -2
- package/lib/store/DataApi.js.map +1 -1
- package/lib/store/EventIngestChannelsApi.d.ts +11 -0
- package/lib/store/EventIngestChannelsApi.d.ts.map +1 -0
- package/lib/store/EventIngestChannelsApi.js +40 -0
- package/lib/store/EventIngestChannelsApi.js.map +1 -0
- package/lib/store/EventSubscriptionsApi.d.ts +11 -0
- package/lib/store/EventSubscriptionsApi.d.ts.map +1 -0
- package/lib/store/EventSubscriptionsApi.js +40 -0
- package/lib/store/EventSubscriptionsApi.js.map +1 -0
- package/lib/store/EventsApi.d.ts +12 -0
- package/lib/store/EventsApi.d.ts.map +1 -0
- package/lib/store/EventsApi.js +19 -0
- package/lib/store/EventsApi.js.map +1 -0
- package/lib/store/ObjectsApi.d.ts +22 -2
- package/lib/store/ObjectsApi.d.ts.map +1 -1
- package/lib/store/ObjectsApi.js +64 -1
- package/lib/store/ObjectsApi.js.map +1 -1
- package/lib/store/client.d.ts +4 -0
- package/lib/store/client.d.ts.map +1 -1
- package/lib/store/client.js +4 -0
- package/lib/store/client.js.map +1 -1
- package/lib/store/index.d.ts +4 -0
- package/lib/store/index.d.ts.map +1 -1
- package/lib/store/index.js +4 -0
- package/lib/store/index.js.map +1 -1
- package/lib/vertesia-client.js +14 -2
- package/lib/vertesia-client.js.map +1 -1
- package/package.json +6 -9
- package/src/EnvironmentsApi.test.ts +39 -0
- package/src/EnvironmentsApi.ts +11 -0
- package/src/InternalSecretsApi.ts +63 -0
- package/src/QuotaApi.ts +24 -0
- package/src/client.ts +9 -0
- package/src/index.ts +2 -1
- package/src/store/DataApi.ts +2 -2
- package/src/store/EventIngestChannelsApi.ts +50 -0
- package/src/store/EventSubscriptionsApi.ts +50 -0
- package/src/store/EventsApi.ts +28 -0
- package/src/store/ObjectsApi.ts +113 -1
- package/src/store/client.ts +4 -0
- package/src/store/index.ts +4 -0
package/lib/vertesia-client.js
CHANGED
|
@@ -1,2 +1,14 @@
|
|
|
1
|
-
import{ExecutionRunStatus as t,AgentMessageType as e,toAgentMessage as r,parseMessage as s,DataStoreApiHeaders as n,ContentObjectApiHeaders as o,canGenerateRendition as a,WorkflowExecutionStatus as i,isWorkflowTerminalStatus as u}from"@vertesia/common";export{Permission,canGenerateRendition,getOAuthPermissionScopes,getSupportedRenditionFormats,supportsVisualRendition}from"@vertesia/common";function l(t){return null!==t&&"object"==typeof t}function c(t){if(l(t))return t.details?t.details:l(t.error)?t.error.details:void 0}class d extends Error{status;payload;request;request_info;displayDetails;original_message;constructor(t,e,r,s,n=!0){super(function(t,e,r,s,n){let o=t;if(n){o+=`\nRequest: ${e.method} ${e.url} => ${r}`;const t=c(s);if(t){const e=typeof t;"string"===e?o+=`\nDetails: ${t}`:"object"===e&&(o+=`\nDetails: ${JSON.stringify(t,void 0,2)}`)}o+="\nStack Trace: "}return o}(t,e,r,s,n)),this.original_message=t,this.request=e,this.status=r,this.payload=s,this.request_info=`${e.method} ${e.url} => ${r}`,this.displayDetails=n}get details(){return c(this.payload)}}class h extends d{constructor(t,e,r,s,n=!0){super(t,e,r,s,n)}updateDetails(t){if(t!==this.details){const e=l(this.payload)?{...this.payload,details:t}:{details:t};return new h(this.original_message,this.request,this.status,e,this.displayDetails)}return this}}class p extends d{constructor(t,e){super(`Failed to connect to server: ${e.message}`,t,0,e)}}class y extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}const g=32;function f(t){}function m(t){if("function"==typeof t)throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:e=f,onError:r=f,onRetry:s=f,onComment:n,maxBufferSize:o}=t,a=[];let i,u,l=0,c=!0,d="",h=0,p=!1;function m(){void 0!==o&&(l+d.length<=o||(p=!0,a.length=0,l=0,i=void 0,d="",h=0,u=void 0,r(new y(`Buffered data exceeded max buffer size of ${o} characters`,{type:"max-buffer-size-exceeded"}))))}function $(t){let r=0;if(-1===t.indexOf("\r")){let s=t.indexOf("\n",r);for(;-1!==s;){if(r===s){h>0&&e({id:i,event:u,data:d}),i=void 0,d="",h=0,u=void 0,r=s+1,s=t.indexOf("\n",r);continue}const n=t.charCodeAt(r);if(w(t,r,n)){const n=t.charCodeAt(r+5)===g?r+6:r+5,o=t.slice(n,s);if(0===h&&10===t.charCodeAt(s+1)){e({id:i,event:u,data:o}),i=void 0,d="",u=void 0,r=s+2,s=t.indexOf("\n",r);continue}d=0===h?o:`${d}\n${o}`,h++}else v(t,r,n)?u=t.slice(t.charCodeAt(r+6)===g?r+7:r+6,s)||void 0:b(t,r,s);r=s+1,s=t.indexOf("\n",r)}return t.slice(r)}for(;r<t.length;){const e=t.indexOf("\r",r),s=t.indexOf("\n",r);let n=-1;if(-1!==e&&-1!==s?n=e<s?e:s:-1!==e?n=e===t.length-1?-1:e:-1!==s&&(n=s),-1===n)break;b(t,r,n),r=n+1,13===t.charCodeAt(r-1)&&10===t.charCodeAt(r)&&r++}return t.slice(r)}function b(t,r,s){if(r===s)return h>0&&e({id:i,event:u,data:d}),i=void 0,d="",h=0,void(u=void 0);const o=t.charCodeAt(r);if(w(t,r,o)){const e=t.charCodeAt(r+5)===g?r+6:r+5,n=t.slice(e,s);return d=0===h?n:`${d}\n${n}`,void h++}if(v(t,r,o))return void(u=t.slice(t.charCodeAt(r+6)===g?r+7:r+6,s)||void 0);if(105===o&&100===t.charCodeAt(r+1)&&58===t.charCodeAt(r+2)){const e=t.slice(t.charCodeAt(r+3)===g?r+4:r+3,s);return void(i=e.includes("\0")?void 0:e)}if(58===o){if(n){const e=t.slice(r,s);n(e.slice(t.charCodeAt(r+1)===g?2:1))}return}const a=t.slice(r,s),l=a.indexOf(":");if(-1===l)return void S(a,"",a);const c=a.slice(0,l),p=a.charCodeAt(l+1)===g?2:1;S(c,a.slice(l+p),a)}function S(t,e,n){switch(t){case"event":u=e||void 0;break;case"data":d=0===h?e:`${d}\n${e}`,h++;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?s(parseInt(e,10)):r(new y(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:n}));break;default:r(new y(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:n}))}}return{feed:function(t){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,239===t.charCodeAt(0)&&187===t.charCodeAt(1)&&191===t.charCodeAt(2)&&(t=t.slice(3))),0===a.length){const e=$(t);return""!==e&&(a.push(e),l=e.length),void m()}if(-1===t.indexOf("\n")&&-1===t.indexOf("\r"))return a.push(t),l+=t.length,void m();a.push(t);const e=a.join("");a.length=0,l=0;const r=$(e);""!==r&&(a.push(r),l=r.length),m()},reset:function(t={}){if(t.consume&&a.length>0){const t=a.join("");b(t,0,t.length)}c=!0,i=void 0,d="",h=0,u=void 0,a.length=0,l=0,p=!1}}}function w(t,e,r){return 100===r&&97===t.charCodeAt(e+1)&&116===t.charCodeAt(e+2)&&97===t.charCodeAt(e+3)&&58===t.charCodeAt(e+4)}function v(t,e,r){return 101===r&&118===t.charCodeAt(e+1)&&101===t.charCodeAt(e+2)&&110===t.charCodeAt(e+3)&&116===t.charCodeAt(e+4)&&58===t.charCodeAt(e+5)}class $ extends TransformStream{constructor(){let t;super({start(e){t=m({onEvent(t){const r={type:"event",...t};e.enqueue(r)}})},transform(e){t.feed(e)}})}}let b;if(globalThis.TextDecoderStream&&"function"==typeof globalThis.TextDecoderStream)b=globalThis.TextDecoderStream;else{class t extends TransformStream{_options;constructor(t="utf-8",{fatal:r=!1,ignoreBOM:s=!1}={}){super(new e(new TextDecoder(t,{fatal:r,ignoreBOM:s}))),this._options={fatal:r,ignoreBOM:s,encoding:t}}get encoding(){return this._options.encoding}get fatal(){return this._options.fatal}get ignoreBOM(){return this._options.ignoreBOM}}class e{decoder;constructor(t){this.decoder=t}transform(t,e){if(!(t instanceof ArrayBuffer||ArrayBuffer.isView(t)))throw new TypeError("Input must be a compatible with: ArrayBuffer | Uint8Array");const r=this.decoder.decode(t,{stream:!0});0!==r.length&&e.enqueue(r)}flush(t){const e=this.decoder.decode();0!==e.length&&t.enqueue(e)}}b=t}function S(t){return"/"===t[t.length-1]?t.slice(0,-1):t}const _=["GET","HEAD","OPTIONS","PUT","DELETE"],x=[502,503,504];function k(t){return null!==t&&"object"==typeof t}function E(t,e,r){const s=r?function(t){const e=t.headers.get("retry-after");if(!e)return;const r=Number(e);if(Number.isFinite(r)&&r>=0)return 1e3*r;const s=Date.parse(e);return Number.isNaN(s)?void 0:Math.max(0,s-Date.now())}(r):void 0,n=s??Math.min(t.maxDelayMs,t.baseDelayMs*2**e);return t.jitter?Math.floor(Math.random()*n):n}function T(t){return t instanceof Error?t:new Error(String(t))}function R(t){const e=AbortSignal.timeout;if("function"==typeof e)return e(t);const r=new AbortController;return setTimeout(()=>r.abort(new DOMException("The operation timed out","TimeoutError")),t),r.signal}async function A(t){try{await(t.body?.cancel())}catch{}}class q{_fetch;baseUrl;errorFactory=t=>t;verboseErrors=!0;retryPolicy;defaultTimeoutMs;constructor(t,e){this.baseUrl=S(t),this._fetch=function(t){return t?Promise.resolve(t):"function"==typeof globalThis.fetch?Promise.resolve(globalThis.fetch):Promise.resolve(()=>{throw new Error("No Fetch implementation found")})}(e)}throwError(t){throw this.errorFactory(t)}withRetryPolicy(t){return this.retryPolicy=t||void 0,this}getRetryPolicy(){return this.retryPolicy}withTimeout(t){return this.defaultTimeoutMs="number"==typeof t&&t>0?t:void 0,this}getTimeout(){return this.defaultTimeoutMs}resolveTimeout(t){if("sse"===t?.reader)return;const e=t?.timeoutMs;if(!1===e||null===e)return;if("number"==typeof e)return e>0?e:void 0;const r=this.getTimeout();return r&&r>0?r:void 0}getUrl(t){return t.startsWith("http://")||t.startsWith("https://")?S(t):S((e=this.baseUrl,r=t,e.endsWith("/")?r.startsWith("/")?e+r.substring(1):e+r:r.startsWith("/")?e+r:`${e}/${r}`));var e,r}get(t,e){return this.request("GET",t,e)}del(t,e){return this.request("DELETE",t,e)}delete(t,e){return this.request("DELETE",t,e)}post(t,e){return this.request("POST",t,e)}put(t,e){return this.request("PUT",t,e)}jsonParse(t){return JSON.parse(t)}createRequest(t,e){return Promise.resolve(new Request(t,e))}handleFetchResponse(t,e){}createServerError(t,e,r){let s=`Server Error: ${e.status}`;return r&&(!function(t){return k(t)&&"Not a valid JSON payload"===t.error&&"string"==typeof t.text}(r)?k(r)&&r.message?s=String(r.message):k(r)&&r.error&&("string"==typeof r.error?s=String(r.error):k(r.error)&&"string"==typeof r.error.message&&(s=r.error.message)):(s+=e.statusText?` ${e.statusText}`:"",s+=": non-JSON response")),new h(s,t,e.status,r,this.verboseErrors)}async readJSONPayload(t){return t.text().then(e=>{if(e)try{return this.jsonParse(e)}catch(r){return{status:t.status,error:"Not a valid JSON payload",message:r instanceof Error?r.message:String(r),text:e}}}).catch(e=>{if(function(t){return"object"==typeof t&&null!==t&&"name"in t&&("TimeoutError"===t.name||"AbortError"===t.name)}(e))throw e;return{status:t.status,error:"Unable to load response content",message:e instanceof Error?e.message:String(e)}})}handleResponse(t,e,r){return r?.reader?"sse"===r.reader?async function(t){if(!t.ok){const e=await t.text(),r=new Error(`SSE error: ${t.status}. Content:\n${e}`);throw r.status=t.status,r}if(!t.body)throw new Error("No body in response");return t.body.pipeThrough(new b).pipeThrough(new $)}(e):r.reader.call(this,e):this.readJSONPayload(e).then(r=>{if(e.ok)return r;this.throwError(this.createServerError(t,e,r))})}async request(t,e,r){let s=this.getUrl(e);r?.query&&(s+=`?${function(t){const e=[];for(const r of Object.keys(t)){const s=t[r];null!=s&&e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(s))}`)}return e.join("&")}(r.query)}`);const n=this.headers?Object.assign({},this.headers):{},o=r?.headers;if(o)for(const t in o)n[t.toLowerCase()]=o[t];let a;const i=r?.payload;i&&(r&&!1===r.jsonPayload?a=i:(a="string"!=typeof i?JSON.stringify(i):i,"content-type"in n||(n["content-type"]="application/json"))),"sse"===r?.reader&&(n.accept="text/event-stream");const u=t.toUpperCase(),l=this.resolveTimeout(r),c=()=>{const t=function(t){const e=t.filter(t=>!!t);if(0===e.length)return;if(1===e.length)return e[0];const r=AbortSignal.any;if("function"==typeof r)return r(e);const s=new AbortController;for(const t of e){if(t.aborted){s.abort(t.reason);break}t.addEventListener("abort",()=>s.abort(t.reason),{once:!0})}return s.signal}([r?.signal,l?R(l):void 0]),e={method:u,headers:Object.assign({},n),body:a};return t&&(e.signal=t),e},d=this.resolveRetryPolicy(r),h=await this._fetch;if(!d){const t=await this.createRequest(s,c());let e;try{e=await h(t)}catch(e){console.error(`Failed to connect to ${s}`,e),this.throwError(new p(t,T(e)))}return this.handleFetchResponse(t,e),this.handleResponse(t,e,r)}const y=function(t){return!(t&&"undefined"!=typeof ReadableStream&&t instanceof ReadableStream)}(a);let g;for(let t=0;t<d.attempts;t++){const e=await this.createRequest(s,c());let n;g=e;try{n=await h(e)}catch(r){this.shouldRetryConnectionError(d,u,t,y)||(console.error(`Failed to connect to ${s}`,r),this.throwError(new p(e,T(r)))),await this.waitBeforeRetry(d,t);continue}if(this.handleFetchResponse(e,n),!this.shouldRetryResponse(d,u,t,y,n))return this.handleResponse(e,n,r);await A(n),await this.waitBeforeRetry(d,t,n)}throw g&&this.throwError(new p(g,new Error(`Retry attempts exhausted for ${u} ${s}`))),new Error(`Retry attempts exhausted for ${u} ${s}`)}resolveRetryPolicy(t){if("sse"===t?.reader||!1===t?.retryPolicy||null===t?.retryPolicy)return;const e=t?.retryPolicy,r=this.getRetryPolicy();if(!e&&!r)return;const s=function(t){const e=Math.max(1,Math.floor(t.attempts??3)),r=Math.max(0,t.baseDelayMs??250),s=Math.max(r,t.maxDelayMs??4e3);return{attempts:e,methods:new Set((t.methods??_).map(t=>t.toUpperCase())),statuses:new Set(t.statuses??x),retryNonJsonServerErrors:t.retryNonJsonServerErrors??!0,retryOnConnectionError:t.retryOnConnectionError??!0,baseDelayMs:r,maxDelayMs:s,jitter:t.jitter??!0}}({...r,...e});return s.attempts>1?s:void 0}shouldRetryResponse(t,e,r,s,n){const o=t.statuses.has(n.status)||t.retryNonJsonServerErrors&&function(t){return!(t.status<500)&&!(t.headers.get("content-type")??"").toLowerCase().includes("json")}(n);return r<t.attempts-1&&s&&t.methods.has(e)&&o}shouldRetryConnectionError(t,e,r,s){return r<t.attempts-1&&s&&t.retryOnConnectionError&&t.methods.has(e)}waitBeforeRetry(t,e,r){const s=E(t,e,r);return new Promise(t=>setTimeout(t,s))}async sseRequest(t,e,r,s){const n=(await this.request(t,e,{...r,reader:"sse"})).getReader();let o;try{for(;;){const{done:t,value:e}=await n.read();if(t)break;o=e,s(e)}}finally{n.releaseLock()}return o}fetch(t,e){return this._fetch.then(r=>r(t,e))}}class P extends q{headers;_auth;onRequest;onResponse;response;constructor(t,e){super(t,e),this.baseUrl="/"===t[t.length-1]?t.substring(0,t.length-1):t,this.headers=this.initialHeaders}get initialHeaders(){const t={accept:"application/json"};return function(){const t=globalThis;return void 0===t.window&&("string"==typeof t.process?.versions?.node||"string"==typeof t.process?.versions?.bun||void 0!==t.Bun)}()&&(t["accept-encoding"]="br, gzip, deflate"),t}withAuthCallback(t){return this._auth=t||void 0,this}withErrorFactory(t){return this.errorFactory=t,this}withLang(t){return t?this.headers["accept-language"]=t:delete this.headers["accept-language"],this}withHeaders(t){const e=this.headers;for(const r in t){const s=t[r];null!=s&&(e[r.toLowerCase()]=s)}return this}setHeader(t,e){e?this.headers[t.toLowerCase()]=e:delete this.headers[t.toLowerCase()]}async createRequest(t,e){if(this._auth&&(!(r=e.headers)||!("authorization"in r))){const t=e.headers?e.headers:{};e.headers=t;const r=await this._auth();r&&(e.headers.authorization=r)}var r;this.response=void 0;const s=await super.createRequest(t,e);return this.onRequest?.(s),s}handleFetchResponse(t,e){this.response=e,this.onResponse?.(e,t)}}class U extends q{client;constructor(t,e){super(t.getUrl(e),t._fetch),this.client=t,this.createServerError=t.createServerError,this.errorFactory=t.errorFactory,this.verboseErrors=t.verboseErrors}createRequest(t,e){return this.client.createRequest(t,e)}handleResponse(t,e,r){return this.client.handleResponse(t,e,r)}handleFetchResponse(t,e){this.client.handleFetchResponse(t,e)}getRetryPolicy(){return this.client.getRetryPolicy()}getTimeout(){return this.client.getTimeout()}get headers(){return this.client.headers}}class C extends U{constructor(t){super(t,"/api/v1/account")}info(){return this.get("/")}update(t){return this.put("/",{payload:t})}projects(){return this.get("/projects").then(t=>t.data)}members(){return this.get("/members")}inviteUser(t){return this.post("/invites",{payload:t})}listInvites(){return this.get("/invites")}listInvitation(t="project"){return this.get(`/invites/${t}`)}acceptInvite(t){return this.put(`/invites/${t}`)}rejectInvite(t){return this.del(`/invites/${t}`)}onboardingProgress(){return this.get("/onboarding")}getStripeBillingStatus(){return this.get("/stripe-billing-status")}}class I extends U{constructor(t){super(t,"/api/v1/accounts")}create(t){return this.post("/",{payload:{name:t}})}list(){return this.get("/")}}class j extends U{constructor(t){super(t,"/api/v1/analytics")}runsSummary(t,e){const r=new URLSearchParams;t?.start&&r.set("start",t.start),t?.end&&r.set("end",t.end),e&&r.set("environment",e);const s=r.toString();return this.get("/runs/summary"+(s?`?${s}`:""))}runsTimeSeries(t,e){const r=new URLSearchParams;t?.start&&r.set("start",t.start),t?.end&&r.set("end",t.end),e&&r.set("environment",e);const s=r.toString();return this.get("/runs/time-series"+(s?`?${s}`:""))}runsTokenUsage(t,e){const r=new URLSearchParams;t?.start&&r.set("start",t.start),t?.end&&r.set("end",t.end),e&&r.set("environment",e);const s=r.toString();return this.get("/runs/token-usage"+(s?`?${s}`:""))}}class O extends U{constructor(t){super(t,"/api/v1/apikeys")}list(t="account"){return this.get("/",{query:{level:t}})}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}retrieve(t,e=!1){return e?this.get(`/${t}`,{query:{withValue:!0}}):this.get(`/${t}`)}delete(t){return this.del(`/${t}`)}getToken(t){return this.get(`/${t}/token`)}requestPublicKey(t={}){return this.get("/pk",{query:t})}}class M extends U{constructor(t){super(t,"/api/v1/apps")}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}listAppInstallationTools(t){return this.get(`/installations/${t}/tools`)}list(){return this.get("/")}install(t,e,r,s){return this.post("/install",{payload:{app_id:t,settings:e,oauth_params:r,oauth_provider_params:s}})}uninstall(t){return this.del(`/install/${t}`)}getAppInstallationByName(t){return this.get(`/installations/name/${t}`).catch(t=>{if(404===t.status)return null;throw t})}getAppInstallationProjects(t){if(!t.id&&!t.name)throw new Error("Invalid arguments: appId or appName must be specified");const e=t.id?{id:t.id}:{name:t.name};return this.get("/installations/projects",{query:e})}getInstalledApps(t){return this.get("/installations",{query:{kind:t}})}getAllAppInstallations(){return this.get("/installations/all")}listInstallations(){return this.get("/installations/refs")}updateInstallationSettings(t){return this.put(`/installations/settings/${t.app_id}`,{payload:{app_id:t.app_id,settings:t.settings,..."access_control"in t?{access_control:t.access_control}:{}}})}updateToolAllowlist(t,e){return this.put(`/installations/${t}/tool-allowlist`,{payload:{tool_allowlist:e}})}validateUrl(t){return this.post("/validate-url",{payload:{url:t}})}}class D extends U{constructor(t){super(t,"/api/v1/audit-trail")}list(t){const e=new URLSearchParams;t?.actions?.length&&e.set("actions",t.actions.join(",")),t?.resourceTypes?.length&&e.set("resourceTypes",t.resourceTypes.join(",")),t?.resourceId&&e.set("resourceId",t.resourceId),t?.principalId&&e.set("principalId",t.principalId),t?.principalType&&e.set("principalType",t.principalType),t?.effectivePrincipalId&&e.set("effectivePrincipalId",t.effectivePrincipalId),void 0!==t?.hasEffectivePrincipal&&e.set("hasEffectivePrincipal",String(t.hasEffectivePrincipal)),t?.projectId&&e.set("projectId",t.projectId),t?.from&&e.set("from",t.from),t?.to&&e.set("to",t.to),t?.limit&&e.set("limit",String(t.limit)),t?.offset&&e.set("offset",String(t.offset));const r=e.toString();return this.get("/"+(r?`?${r}`:""))}}class F extends U{constructor(t){super(t,"/api/v1/commands")}async isNamespaceAvailable(t){return this.get(`/namespaces/${t}/is_available`).then(t=>t.available)}async initSamples(){return this.post("/onboarding/init-samples")}}class N extends U{constructor(t){super(t,"/api/v1/environments")}list(t=!1){const e=t?{all:!0}:void 0;return this.get("/",{query:e})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}updateConfig(t,e){return this.put(`/${t}/config`,{payload:e})}listModels(t,e){return this.get(`/${t}/models`,{query:e?{...e}:void 0})}listTrainableModels(t){return this.get(`/${t}/trainable-models`)}embeddings(t,e){return this.post(`/${t}/embeddings`,{payload:e})}migrateInteractions(t){return this.post("/migrate-interactions",{payload:t})}}class L extends U{constructor(t){super(t,"/groups")}list(t){return this.get("/",{query:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}listMembers(t){return this.get(`/${t}/members`)}addMember(t,e){return this.post(`/${t}/members/${e}`)}removeMember(t,e){return this.del(`/${t}/members/${e}`)}syncMembers(){return this.post("/sync-members")}}class B extends U{constructor(t){super(t,"/api/v1/iam")}aces=new z(this);roles=new H(this);groups=new L(this);getPrincipalIdentity(){return this.get("/users/identity")}}class H extends U{constructor(t){super(t,"/roles")}list(){return this.get("/")}listSystem(){return this.get("/system")}}class z extends U{constructor(t){super(t,"/aces")}list(t){return this.get("/",{query:{...t}})}listProjectAces(){return this.get("/project")}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}}const W=(()=>{const t="undefined"!=typeof process?process.env?.VERTESIA_INTERACTION_TIMEOUT_MS:void 0,e=t?Number.parseInt(t,10):NaN;return Number.isFinite(e)&&e>0?e:18e5})();async function J(){return"function"==typeof globalThis.EventSource?globalThis.EventSource:(await import("eventsource")).EventSource}async function V(e,r,s={},n){const o=!!n,a=await e.runs.create({...s,interaction:r,stream:o},{timeoutMs:o?void 0:W});if(o){if(a.status===t.failed)return a;await G(e,a.id,n)}return a}function G(t,e,r){return new Promise((s,n)=>{(async()=>{try{const o=await J(),a=new URL(`${t.runs.baseUrl}/${e}/stream`),i=t._auth?await t._auth():void 0;if(!i)throw new Error("No auth token available");{const t=i.split(" ")[1];a.searchParams.set("access_token",t)}const u=new o(a.href);u.addEventListener("message",t=>{try{const e=JSON.parse(t.data);e&&r?.(e)}catch(t){n(t)}}),u.addEventListener("close",t=>{try{u.close();const e=JSON.parse(t.data);s(e)}catch(t){n(t)}})}catch(t){n(t)}})()})}class K extends U{constructor(t){super(t,"/api/v1/interactions/catalog")}list(t={}){return this.get("/",{query:t})}listStoredInteractions(t={}){return this.get("/stored",{query:t})}listSysInteractions(t){return this.get("/sys",{query:{tag:t}})}listAppInteractions(t,e){return this.get(`/apps/${t}`,{query:{tag:e}})}listAllAppInteractions(t){return this.get("/apps",{query:{tag:t}})}resolve(t){return this.get(`/resolve/${t}`)}}const Q=Symbol("InteractionOutput");function Y(t){return t.result=Z.from(t.result),t}function X(t){return t.result=Z.from(t.result),t}class Z{results;constructor(t){this.results=t}static from(t){return t?tt(t)?t:Array.isArray(t)?et(t):et("object"==typeof t?[{type:"json",value:t}]:[{type:"text",value:String(t)}]):et([])}static isInteractionOutputArray(t){return tt(t)}get isEmpty(){return 0===this.results.length}hasObject(){return this.results.some(t=>"json"===t.type)}hasText(){return this.results.some(t=>"text"===t.type)}hasImage(){return this.results.some(t=>"image"===t.type)}text(t="\n"){return this.results.filter(t=>"text"===t.type).map(t=>t.value).join(t)}texts(){return this.results.filter(t=>"text"===t.type).map(t=>t.value)}object(){const t=this.results.find(t=>"json"===t.type);return t?t.value:function(t){let e;for(const r of t)if("text"===r.type){const t=r.value.trim();try{return JSON.parse(t)}catch(t){e=t instanceof Error?t:new Error(String(t))}}e||(e=new Error("No JSON result found and no text available to parse"));throw e}(this.results)}objects(){return this.results.filter(t=>"json"===t.type).map(t=>t.value)}objectAt(t){let e=0;for(const r of this.results)if("json"===r.type){if(e===t)return r.value;e++}throw new Error(`Object at index ${t} not found`)}image(){const t=this.results.find(t=>"image"===t.type);if(!t)throw new Error("No image result found");return t.value}images(){return this.results.filter(t=>"image"===t.type).map(t=>t.value)}stringify(t="\n",e=2){return this.results.map(t=>"json"===t.type?JSON.stringify(t.value,null,e):String(t.value)).join(t)}toString(){return this.text()}toJSON(){return this.results}}function tt(t){return!!t&&"object"==typeof t&&!0===t[Q]}function et(t){const e=new Z(t);return new Proxy(t,{get(t,r,s){if(r===Q)return!0;if(r in e){const t=Reflect.get(e,r,e);return"function"==typeof t?t.bind(e):t}return Reflect.get(t,r,s)}})}function rt(t){return!!t&&"object"==typeof t&&"id"in t&&"string"==typeof t.id}class st extends U{catalog;constructor(t){super(t,"/api/v1/interactions"),this.catalog=new K(t)}list(t={}){const e=t.query||{};return this.get("/",{query:{...e}})}listEndpoints(t){return this.post("/endpoints",{payload:t})}listVersionsByName(t){return this.get(`/versions/${t}`)}listTags(t){return this.get("/tags",{query:{...t}})}computeFacets(t){return this.post("/facets",{payload:t})}listNames(){return this.get("/names")}export(t){return this.post("/export",{payload:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t,e){const{cascade:r,query:s,...n}=e??{},o=r?{...s??{},cascade:"true"}:s??void 0;return super.delete(`/${t}`,{...n,query:o})}async execute(t,e={},r){return Y(await V(this.client,t,e,r).catch(t=>{throw t instanceof h&&rt(t.payload)?t.updateDetails({run_id:t.payload.id}):t}))}async executeByName(e,r={},s){const n=await async function(e,r,s={},n){const o=!!n,a=await e.post("/api/v1/execute",{payload:{...s,interaction:r,stream:o},timeoutMs:o?void 0:W});if(o){if(a.status===t.failed)return a;await G(e,a.id,n)}return a}(this.client,e,r,s).catch(t=>{throw t instanceof h&&rt(t.payload)?t.updateDetails({run_id:t.payload.id}):t});return Y(n)}executeAsync(t){return async function(t,e){return await t.post("/api/v1/execute/async",{payload:e})}(this.client,t)}publish(t,e){return this.post(`/${t}/publish`,{payload:e})}fork(t,e){return this.post(`/${t}/fork`,{payload:e})}generateInteraction(t,e){return this.post(`${t}/generate-interaction`,{payload:e})}generateTestData(t,e){return this.post(`${t}/generate-test-data`,{payload:e})}suggestImprovements(t,e){return this.post(`${t}/suggest-prompt-improvements`,{payload:e})}suggestPromptImprovements(t){return this.post("/improve",{payload:t})}listVersions(t){return this.get(`/${t}/versions`)}listForks(t){return this.get(`/${t}/forks`)}requestSlot(t){return async function(t,e){return await t.post("/api/v1/execute/rate-limit/request",{payload:e})}(this.client,t)}resolve(t,e){return this.get(`/resolve/${encodeURIComponent(t)}`,{query:e})}}class nt extends U{constructor(t){super(t,"/api/v1/oauth-clients")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}scopeMetadata(){return this.get("/scope-metadata")}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}remove(t){return this.del(`/${t}`)}}function ot(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,t])=>void 0!==t).map(([t,e])=>[t,String(e)]))}class at extends U{constructor(t){super(t,"/api/v1/oauth-grants")}list(t){return this.get("/",{query:ot(t)})}retrieve(t){return this.get(`/${t}`)}revoke(t,e){return this.del(`/${t}`,{query:e})}revokeBulk(t){return this.post("/revoke",{payload:t})}}class it extends U{constructor(t){super(t,"/api/v1/oauth-providers")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}remove(t){return this.del(`/${t}`)}authorize(t){return this.get(`/${t}/authorize`)}exchange(t,e){return this.post("/exchange",{payload:{code:t,state:e}})}getStatus(t){return this.get(`/${t}/status`)}connect(t){return this.post(`/${t}/connect`,{payload:{}})}getToken(t){return this.post(`/${t}/token`,{payload:{}})}disconnect(t){return this.del(`/${t}/disconnect`)}}class ut extends q{parent;constructor(t,e){super(new URL("/oauth",`${e||t.baseUrl}/`).toString(),t._fetch),this.parent=t,this.createServerError=t.createServerError,this.errorFactory=t.errorFactory,this.verboseErrors=t.verboseErrors}get headers(){return this.parent.headers}createRequest(t,e){return this.parent.createRequest(t,e)}handleResponse(t,e,r){return this.parent.handleResponse(t,e,r)}handleFetchResponse(t,e){this.parent.handleFetchResponse(t,e)}getRetryPolicy(){return this.parent.getRetryPolicy()}createAuthorizationRequest(t){return this.post("/requests",{payload:t})}createDeviceAuthorization(t){return this.post("/device_authorization",{payload:t})}retrieveDeviceRequest(t){return this.get(`/device/${encodeURIComponent(t)}`)}retrieveRequest(t){return this.get(`/requests/${t}`)}retrieveGrantableScopes(t,e){return this.get(`/requests/${t}/grantable-scopes`,{query:{project_id:e}})}approveRequest(t,e){return this.post(`/requests/${t}/approve`,{payload:e})}denyRequest(t){return this.post(`/requests/${t}/deny`,{payload:{}})}}class lt extends U{integrations;constructor(t){super(t,"/api/v1/projects"),this.integrations=new ct(this)}list(t){return this.get("/",{query:{account:t}})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}updateConfiguration(t,e){return this.put(`/${t}/configuration`,{payload:e})}getTools(t){return this.get(`/${t}/tools`)}getToolByName(t,e){return this.get(`/${t}/tools/${e}`).catch(t=>{if(404===t.status)return null;throw t})}listAppContentTypes(t,e){return this.get(`/${t}/app-types`,{query:{tag:e}})}getAppContentType(t,e){return this.get(`/${t}/app-types/${e}`)}listAppProcesses(t,e){return this.get(`/${t}/app-processes`,{query:{tag:e}})}getAppProcess(t,e){return this.get(`/${t}/app-processes/${e}`)}listAppRenderingTemplates(t,e){return this.get(`/${t}/app-templates`,{query:{tag:e}})}getAppRenderingTemplate(t,e){return this.get(`/${t}/app-templates/${e}`)}getCompositeAppConfiguration(t){return this.get(`/${t}/composite-app`)}updateCompositeAppConfiguration(t,e){return this.put(`/${t}/composite-app`,{payload:e})}}class ct extends U{constructor(t){super(t,"/")}list(t){return this.get(`/${t}/integrations`).then(t=>t.integrations)}retrieve(t,e){return this.get(`/${t}/integrations/${e}`).catch(t=>{if(404!==t.status)throw t})}update(t,e,r){return this.put(`/${t}/integrations/${e}`,{payload:r})}updatePlugins(t,e){return this.post(`/${t}/plugins`,{payload:{plugins:e}})}listPlugins(t){return this.get(`/${t}/plugins`)}}class dt extends U{constructor(t){super(t,"/api/v1/prompts")}list(t={}){const e=t.query||{};return this.get("/",{query:{...e}})}computeFacets(t){return this.post("/facets",{payload:t})}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}fork(t,e){return this.post(`/${t}/fork`,{payload:e})}render(t,e){return this.post(`/${t}/render`,{payload:e})}options(t){return this.get(`/options/${t}`)}listVersions(t){return this.get(`/${t}/versions`)}listInteractions(t){return this.get(`/${t}/interactions`)}listForks(t){return this.get(`/${t}/forks`)}}class ht extends U{constructor(t){super(t,"/api/v1/refs")}resolve(t){return this.post("/resolve",{payload:{refs:t}})}}class pt extends U{constructor(t){super(t,"/api/v1/remote-mcp-connections")}getStatus(t){return this.get(`/status/${t}`)}getCollectionStatus(t,e){return this.get(`/status/${t}/${e}`)}getMetadata(t,e){return this.get(`/metadata/${t}/${e}`)}authorize(t,e){return this.get(`/authorize/${t}/${e}`)}exchange(t,e){return this.post("/exchange",{payload:{code:t,state:e}})}connect(t,e){return this.post(`/connect/${t}/${e}`,{})}disconnect(t,e){return this.del(`/disconnect/${t}/${e}`)}getCollectionToken(t,e){return this.post("/token",{payload:{app_install_id:t,collection_id:e}})}getToken(t){return this.post("/token",{payload:{mcp_server_url:t}})}}class yt extends U{constructor(t){super(t,"/api/v1/runs")}list({limit:t,offset:e,filters:r}){const s={limit:t,offset:e,...r};return this.get("/",{query:s})}find(t){return this.post("/find",{payload:t})}async retrieve(t){return X(await this.get(`/${t}`))}retrievePopulated(t){return this.get(`/${t}`,{query:{populate:"true"}})}filterOptions(t,e){const r={...e};return this.get(`/filter-options/${t}`,{query:r})}async create(t,e){const r=this.client.sessionTags;if(r){let e=Array.isArray(r)?r:[r];Array.isArray(t.tags)?e=e.concat(t.tags):t.tags&&(e=e.concat([t.tags])),t={...t,tags:e}}return X(await this.post("/",{payload:t,timeoutMs:e?.timeoutMs,signal:e?.signal}))}sendToolResults(t){return this.post("/tool-results",{payload:t})}sendUserMessage(t){return this.post("/user-message",{payload:t})}computeFacets(t){return this.post("/facets",{payload:t})}search(t){return this.post("/search",{payload:t})}clone(t){return this.post("/clone",{payload:t})}}class gt extends U{constructor(t){super(t,"/api/v1/secrets")}list(t,e){return this.get("/",{query:{...e,project_id:t}}).then(t=>t.secrets)}retrieve(t,e,r){return this.get(`/${e}`,{query:{...r,project_id:t}}).catch(t=>{if(404!==t.status)throw t})}create(t,e){return this.post("/",{query:{project_id:t},payload:e})}update(t,e,r,s){return this.put(`/${e}`,{query:{...s,project_id:t},payload:r})}remove(t,e,r){return this.del(`/${e}`,{query:{...r,project_id:t}})}fillWebsiteCredential(t,e,r){return this.post(`/${e}/actions/fill-browser`,{query:{project_id:t},payload:r})}}class ft extends U{constructor(t){super(t,"/api/v1/skills")}findRelevant(t,e){const r={context:t,limit:e};return this.post("/find-relevant",{payload:r})}findRelevantForTask(t,e){return this.findRelevant({task_description:t,tool_names:e})}}const mt=new Set([429,500,502,503,504]),wt=4,vt=500,$t=8e3;function bt(t){return new Promise(e=>setTimeout(e,t))}function St(t,e,r,s){const n=s?function(t){const e=t.headers.get("retry-after");if(!e)return;const r=Number(e);if(Number.isFinite(r)&&r>=0)return 1e3*r;const s=Date.parse(e);return Number.isNaN(s)?void 0:Math.max(0,s-Date.now())}(s):void 0;if(void 0!==n)return Math.min(r,n);const o=Math.min(r,e*2**t);return Math.floor(Math.random()*o)}const _t=new TextEncoder;function xt(t){if("string"==typeof t)return _t.encode(t);if(t instanceof Blob)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new TypeError(`Unsupported signed-URL upload chunk of type "${typeof t}"; body streams must yield string or binary (Uint8Array/ArrayBuffer/DataView/Blob) chunks.`)}async function kt(t,e={}){const{method:r="GET",headers:s,attempts:n=wt,baseDelayMs:o=vt,maxDelayMs:a=$t,retryableStatuses:i=mt}=e,u=await async function(t){if(null!=t){if("undefined"!=typeof ReadableStream&&t instanceof ReadableStream){const e=t.getReader(),r=[];try{for(;;){const{done:t,value:s}=await e.read();if(t)break;r.push(xt(s))}}catch(t){throw await e.cancel(t).catch(()=>{}),t}finally{e.releaseLock()}return new Blob(r)}return t}}(e.body);let l;for(let e=0;e<n;e++){const c=e===n-1;try{const n=await fetch(t,{method:r,headers:s,body:u});if(n.ok||!i.has(n.status)||c)return n;await(n.body?.cancel().catch(()=>{})),await bt(St(e,o,a,n))}catch(t){if(l=t,c)throw t;await bt(St(e,o,a))}}throw l instanceof Error?l:new Error(`Failed to fetch signed URL: ${t}`)}function Et(t,e){const r=function(t){if(!t||"object"!=typeof t)return;const e=t.process_run_id;return"string"==typeof e?e:void 0}(t);return!r||r===e}function Tt(t,r){return(t.type===e.TERMINATED||t.type===e.COMPLETE&&"main"===(t.workstream_id??"main"))&&Et(t.details,r)}function Rt(t,r){return(t.t===e.TERMINATED||t.t===e.COMPLETE&&"main"===(t.w??"main"))&&Et(t.d,r)}class At extends U{constructor(t){super(t,"/api/v1/agents")}start(t){return this.post("/",{payload:t})}recordRun(t){return this.post("/record",{payload:t})}createRecord(t){return this.recordRun(t)}retrieve(t){return this.get(`/${t}`)}retrieveRun(t){return this.get(`/${t}`)}retrieveProcess(t){return this.get(`/${t}`)}list(t){return this.get("/",{query:this.buildListQueryParams(t)})}async listProcessRuns(t){return(await this.get("/",{query:this.buildListQueryParams({...t,run_kind:"process"})})).items.filter(qt)}buildListQueryParams(t){const e={};return t?.id&&(e.id=t.id),t?.status&&(e.status=Array.isArray(t.status)?t.status.join(","):t.status),t?.interaction&&(e.interaction=t.interaction),t?.started_by&&(e.started_by=t.started_by),t?.since&&(e.since=t.since.toISOString()),t?.until&&(e.until=t.until.toISOString()),t?.schedule_id&&(e.schedule_id=t.schedule_id),t?.type&&(e.type=t.type),t?.run_type&&(e.run_type=Array.isArray(t.run_type)?t.run_type.join(","):t.run_type),t?.run_kind&&(e.run_kind=t.run_kind),t?.limit&&(e.limit=String(t.limit)),t?.offset&&(e.offset=String(t.offset)),t?.cursor&&(e.cursor=t.cursor),t?.sort&&(e.sort=t.sort),t?.order&&(e.order=t.order),e}search(t){const e={};return t?.query&&(e.query=t.query),t?.status&&(e.status=Array.isArray(t.status)?t.status.join(","):t.status),t?.interaction&&(e.interaction=t.interaction),t?.started_by&&(e.started_by=t.started_by),t?.categories?.length&&(e.categories=t.categories.join(",")),t?.tags?.length&&(e.tags=t.tags.join(",")),t?.content_type_name&&(e.content_type_name=t.content_type_name),t?.since&&(e.since=t.since.toISOString()),t?.until&&(e.until=t.until.toISOString()),t?.limit&&(e.limit=String(t.limit)),t?.offset&&(e.offset=String(t.offset)),t?.sort?.length&&(e.sort=t.sort.join(",")),this.get("/search",{query:e})}terminate(t,e){const r=e?{reason:e}:void 0;return this.del(`/${t}`,{query:r})}restart(t){return this.post(`/${t}/restart`,{})}fork(t){return this.post(`/${t}/fork`,{})}getContext(t){return this.get(`/${t}/context`)}getHistory(t){return this.get(`/${t}/history`)}advance(t,e){return this.post(`/${t}/advance`,{payload:e??{}})}retryNode(t,e){return this.post(`/${t}/retry-node`,{payload:e??{}})}answerTask(t,e,r){return this.post(`/${t}/answer-task`,{payload:{task_id:e,result:r}})}updateStatus(t,e){return this.post(`/${t}/status`,{payload:e})}bindWorkflowRun(t,e){return this.post(`/${t}/workflow`,{payload:e})}sendSignal(t,e,r){return this.post(`/${t}/signal/${e}`,{payload:r})}query(t,e){return this.get(`/${t}/query/${e}`)}getActiveWorkstreams(t){return this.query(t,"ActiveWorkstreams")}async retrieveMessages(t,e){const n=e?{since:e}:void 0;return(await this.get(`/${t}/updates`,{query:n})).messages.map(e=>r(s(e),t))}postMessage(t,e){return this.post(`/${t}/updates`,{payload:e})}async streamMessages(t,e,n,o,a){let i=()=>{},u=()=>{};const l=new Promise((t,e)=>{i=t,u=e});let c=0,d=n||0;const h=Date.now();let p=!1,y=null,g=null,f=null,m=null;const w=t=>{const e=Math.min(1e3*2**t,3e4);return e+.1*Math.random()*e},v=()=>{f&&(clearTimeout(f),f=null),g&&(clearInterval(g),g=null),y&&(y.close(),y=null),o&&m&&(o.removeEventListener("abort",m),m=null)},$=t=>{p||(p=!0,v(),i(t))};if(o){if(o.aborted)return p=!0,v(),i(null),l;m=()=>{$(null)},o.addEventListener("abort",m,{once:!0})}try{if(!p){const r=await this.retrieveMessages(t,n);a?.onHistoryLoaded?.(r);let s=!1;for(let n=0;n<r.length;n++){const o=r[n];if(p)break;if(d=Math.max(d,o.timestamp||0),e&&e(o,$),p)break;s=n===r.length-1&&Tt(o,t)}if(s)return $(null),l}}catch(t){p||(a?.onHistoryError?.(t),console.warn("Failed to fetch historical messages, continuing with SSE:",t))}!p&&d<=0&&(d=Math.max(1,h-1));const b=async(n=!1)=>{if(!p)try{const o=await J();if(p)return;const a=this.client,i=new URL(`${a.agents.baseUrl}/${t}/stream`);d>0&&i.searchParams.set("since",d.toString()),i.searchParams.set("skipHistory","true");const l=a._auth?await a._auth():void 0;if(p)return;if(!l)return p=!0,v(),void u(new Error("No auth token available"));const h=l.split(" ")[1];if(i.searchParams.set("access_token",h),n&&console.log(`Reconnecting to agent stream ${t} (attempt ${c+1}/10)`),p)return;const m=new o(i.href);y=m,g=setInterval(()=>{},1e3);let S=0;m.onopen=()=>{n&&console.log(`Reconnected to agent stream ${t}`),S=Date.now()},m.onmessage=n=>{if(!p&&n.data&&!n.data.startsWith(":"))try{const o=s(n.data);if(d=o.ts?Math.max(d,o.ts):Date.now(),e){const s=r(o,t);e(s,$)}Rt(o,t)&&$(null)}catch(t){console.error("Failed to parse SSE message:",t,n.data)}},m.onerror=t=>{if(p)return;v();if((S?Date.now()-S:0)>5e3&&(c=0),c<10){const t=w(c);c++,f=setTimeout(()=>{f=null,p||b(!0)},t)}else p=!0,v(),u(new Error("SSE connection failed after 10 reconnection attempts"))}}catch(t){if(p)return;if(c<10){const t=w(c);c++,f=setTimeout(()=>{f=null,p||b(!0)},t)}else p=!0,v(),u(t)}};return b(!1),l}getInternals(t){return this.get(`/${t}/internals`)}getRunDetails(t,e){const r={};return e?.includeHistory&&(r.include_history="true"),e?.hydratePayloads&&(r.hydrate_payloads="true"),this.get(`/${t}/details`,{query:r})}async streamRunDetails(t,e,r){const s=await J(),n=this.client,o=new URL(`${n.agents.baseUrl}/${t}/details/stream`),a=n._auth?await n._auth():void 0;if(!a)throw new Error("No auth token available");const i=a.split(" ")[1];return o.searchParams.set("access_token",i),new Promise((t,n)=>{const a=new s(o.href);let i=null;const u=()=>{a.close(),r&&i&&(r.removeEventListener("abort",i),i=null)};if(r){if(r.aborted)return u(),void t();i=()=>{u(),t()},r.addEventListener("abort",i,{once:!0})}a.addEventListener("history",t=>{try{const r=JSON.parse(t.data);e&&e({type:"history",data:r})}catch(t){}}),a.addEventListener("control",r=>{try{const s=JSON.parse(r.data);e&&e({type:"control",data:s}),"type"in s&&"done"===s.type&&(u(),t())}catch(t){}}),a.addEventListener("error",t=>{try{const r=JSON.parse(t.data);e&&e({type:"error",data:r})}catch(t){}}),a.onerror=t=>{u(),n(new Error("SSE connection failed for details stream"))}})}listChildren(t){return this.get(`/${t}/children`)}getChildDetails(t,e,r){const s={};return r?.includeHistory&&(s.include_history="true"),r?.hydratePayloads&&(s.hydrate_payloads="true"),this.get(`/${t}/children/${e}/details`,{query:s})}listArtifacts(t,e){const r=e?.visibility?{visibility:e.visibility}:void 0;return this.get(`/${t}/artifacts`,{query:r})}getArtifactUrl(t,e,r,s){const n={url:"1"};return r&&(n.disposition=r),s&&(n.filename=s),this.get(`/${t}/artifacts/${e}`,{query:n})}async uploadArtifact(t,e,r,s){const n=s||"application/octet-stream",o=await this.put(`/${t}/artifacts/${e}`,{headers:{"Content-Type":n}}),a=await kt(o.url,{method:"PUT",body:r,headers:{"Content-Type":n}});if(!a.ok)throw new Error(`Failed to upload artifact: ${a.statusText}`);return o}async downloadArtifact(t,e){const{url:r}=await this.getArtifactUrl(t,e,"attachment"),s=await kt(r);if(!s.ok)throw new Error(`Failed to download artifact: ${s.statusText}`);if(!s.body)throw new Error("No body in artifact download response");return s.body}ingestEvents(t,e){const r={events:e};return this.post(`/${t}/events`,{payload:r})}getAnalyticsSummary(t={}){return this.post("/analytics/summary",{payload:t})}getTokenUsageAnalytics(t={}){return this.post("/analytics/tokens",{payload:t})}getLlmLatencyAnalytics(t={}){return this.post("/analytics/latency/llm",{payload:t})}getToolLatencyAnalytics(t={}){return this.post("/analytics/latency/tools",{payload:t})}getAgentLatencyAnalytics(t={}){return this.post("/analytics/latency/agents",{payload:t})}getErrorAnalytics(t={}){return this.post("/analytics/errors",{payload:t})}getToolAnalytics(t={}){return this.post("/analytics/tools",{payload:t})}getToolParameterAnalytics(t){return this.post("/analytics/tools/parameters",{payload:t})}getAnalyticsFilterOptions(t={}){return this.post("/analytics/filter-options",{payload:t})}getPromptSizeAnalytics(t={}){return this.post("/analytics/prompt-size",{payload:t})}getTopPrincipalsAnalytics(t={}){return this.post("/analytics/top-principals",{payload:t})}getRunsByAgentAnalytics(t={}){return this.post("/analytics/runs-by-agent",{payload:t})}getTimeToFirstResponseAnalytics(t={}){return this.post("/analytics/time-to-first-response",{payload:t})}getFirstResponseBehaviorAnalytics(t={}){return this.post("/analytics/first-response-behavior",{payload:t})}}function qt(t){return"process"===t.run_kind}class Pt extends U{constructor(t){super(t,"/api/v1/collections")}search(t){return this.post("/search",{payload:t})}computeListFacets(t){return this.post("/facets",{payload:t})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}addMembers(t,e){return this.post(`/${t}/members`,{payload:{action:"add",members:e}})}listMembers(t,e){return this.get(`/${t}/members`,{query:{...e}})}computeFacets(t,e){return this.post(`/${t}/facets`,{payload:e})}searchMembers(t,e){return this.post(`/${t}/search`,{payload:e})}deleteMembers(t,e){return this.post(`/${t}/members`,{payload:{action:"delete",members:e}})}addChildren(t,e){return this.post(`/${t}/children`,{payload:{action:"add",children:e}})}deleteChildren(t,e){return this.post(`/${t}/children`,{payload:{action:"delete",children:e}})}searchChildren(t,e={}){return this.post(`/${t}/children/search`,{payload:e})}delete(t){return this.del(`/${t}`)}updatePermissions(t,e){return this.put(`/${t}/permissions`,{payload:e})}propagatePermissions(t){return this.post(`/${t}/propagate-permissions`)}propagateSharedProperties(t){return this.post(`/${t}/propagate-shared-props`)}}class Ut extends U{constructor(t){super(t,"/api/v1/cost")}getAnalytics(t={}){return this.post("/analytics",{payload:t})}getGlobalAnalytics(t={}){return this.post("/analytics/global",{payload:t})}getModelPrices(t={}){return this.get("/model-prices",{query:{...t}})}getRunPrice(t){return this.post("/run-price",{payload:t})}getRunPriceComparison(t){return this.post("/run-price",{payload:{...t,include_comparison_pricing:!0}})}getExportUrl(t){const e=new URLSearchParams;t?.from&&e.set("from","number"==typeof t.from?new Date(t.from).toISOString():t.from),t?.to&&e.set("to","number"==typeof t.to?new Date(t.to).toISOString():t.to),t?.scope&&e.set("scope",t.scope),t?.project_id&&e.set("project_id",t.project_id),t?.workflow_id&&e.set("workflow_id",t.workflow_id);const r=e.toString();return`${this.baseUrl}/export${r?`?${r}`:""}`}}class Ct extends U{storeId;constructor(t,e){super(t,`/api/v1/data/${e}/dashboards`),this.storeId=e}storeHeaders(){return{[n.DATA_STORE_ID]:this.storeId}}list(t){const e=t?`?status=${t}`:"";return this.get(`/${e}`,{headers:this.storeHeaders()})}create(t){return this.post("/",{payload:t,headers:this.storeHeaders()})}retrieve(t){return this.get(`/${t}`,{headers:this.storeHeaders()})}update(t,e){return this.put(`/${t}`,{payload:e,headers:this.storeHeaders()})}delete(t){return this.del(`/${t}`,{headers:this.storeHeaders()})}bulkArchive(t){return this.post("/bulk/archive",{payload:{ids:t},headers:this.storeHeaders()})}bulkDelete(t){return this.post("/bulk/delete",{payload:{ids:t},headers:this.storeHeaders()})}listVersions(t,e){const r=new URLSearchParams;e?.snapshotsOnly&&r.set("snapshots_only","true"),e?.limit&&r.set("limit",String(e.limit));const s=r.toString()?`?${r}`:"";return this.get(`/${t}/versions${s}`,{headers:this.storeHeaders()})}getVersion(t,e){return this.get(`/${t}/versions/${e}`,{headers:this.storeHeaders()})}createSnapshot(t,e){return this.post(`/${t}/versions`,{payload:e,headers:this.storeHeaders()})}promoteVersion(t,e,r){return this.post(`/${t}/versions/${e}/promote`,{payload:r||{},headers:this.storeHeaders()})}setVersioningEnabled(t,e){return this.put(`/${t}/versioning`,{payload:{enabled:e},headers:this.storeHeaders()})}}class It extends U{constructor(t){super(t,"/api/v1/data")}storeHeaders(t){return{[n.DATA_STORE_ID]:t}}list(){return this.get("/")}create(t){return this.post("/",{payload:t})}retrieve(t){return this.get(`/${t}`,{headers:this.storeHeaders(t)})}delete(t){return this.del(`/${t}`,{headers:this.storeHeaders(t)})}getSchema(t,e){const r=e?`?format=${e}`:"";return this.get(`/${t}/schema${r}`,{headers:this.storeHeaders(t)})}updateSchema(t,e){return this.put(`/${t}/schema`,{payload:e,headers:this.storeHeaders(t)})}getSchemaHistory(t){return this.get(`/${t}/schema/history`,{headers:this.storeHeaders(t)})}listTables(t){return this.get(`/${t}/tables`,{headers:this.storeHeaders(t)})}createTables(t,e){return this.post(`/${t}/tables`,{payload:e,headers:this.storeHeaders(t)})}getTable(t,e,r){const s=r?"?sample=true":"";return this.get(`/${t}/tables/${e}${s}`,{headers:this.storeHeaders(t)})}alterTable(t,e,r){return this.put(`/${t}/tables/${e}`,{payload:r,headers:this.storeHeaders(t)})}dropTable(t,e){return this.del(`/${t}/tables/${e}`,{headers:this.storeHeaders(t)})}import(t,e){return this.post(`/${t}/import`,{payload:e,headers:this.storeHeaders(t)})}getImportStatus(t,e){return this.get(`/${t}/import/${e}`,{headers:this.storeHeaders(t)})}listVersions(t,e){const r=e?"?snapshots_only=true":"";return this.get(`/${t}/versions${r}`,{headers:this.storeHeaders(t)})}createSnapshot(t,e){return this.post(`/${t}/versions`,{payload:e,headers:this.storeHeaders(t)})}rollback(t,e){return this.post(`/${t}/versions/${e}/rollback`,{headers:this.storeHeaders(t)})}queryVersion(t,e,r){return this.post(`/${t}/versions/${e}/query`,{payload:r,headers:this.storeHeaders(t)})}query(t,e){return this.post(`/${t}/query`,{payload:e,headers:this.storeHeaders(t)})}queryBatch(t,e){return this.post(`/${t}/query/batch`,{payload:{queries:e},headers:this.storeHeaders(t)})}mutateRows(t,e){return this.post(`/${t}/mutate`,{payload:e,headers:this.storeHeaders(t)})}validateQueries(t,e){return this.post(`/${t}/query/validate`,{payload:{queries:e},headers:this.storeHeaders(t)})}getDownloadInfo(t,e){const r=e?`?version_id=${e}`:"";return this.get(`/${t}/download${r}`,{headers:this.storeHeaders(t)})}dashboards(t){return new Ct(this.client,t)}}class jt extends U{constructor(t){super(t,"/api/v1/email")}send(t){return this.post("/send",{payload:t})}resolveRoute(t){return this.post("/resolve-route",{payload:{route_key:t}})}createRoute(t){return this.post("/routes",{payload:t})}getRoute(t){return this.get(`/routes/${t}`)}updateRoute(t,e){return this.put(`/routes/${t}`,{payload:e})}forwardEmail(t,e){return this.post(`/routes/${t}/forward`,{payload:e})}}class Ot extends U{constructor(t,e="/api/v1/embeddings"){super(t,e)}async status(t){return this.get(`${t}/status`)}async activate(t,e){if(!e.environment)throw new Error("Invalid configuration: select environment");return this.post(`${t}/enable`,{payload:e})}async disable(t){return this.post(`${t}/disable`)}async recalculate(t){return this.post(`${t}/recalculate`)}}class Mt extends d{constructor(t,e){super(`Resource not found: ${e.message}`,t,404,e.payload)}}class Dt{stream;name;type;id;constructor(t,e,r,s){this.stream=t,this.name=e,this.type=r,this.id=s}}const Ft="memories",Nt="agents";function Lt(t){const e=t.endsWith(".tar.gz")?t:`${t}.tar.gz`;return`${Ft}/${e}`}function Bt(t,e){return`${Nt}/${t}/${e}`}class Ht extends U{constructor(t){super(t,"/api/v1/files")}async deleteFile(t,e){return this.del(`/${t}`,{query:{prefix:e}})}getMetadata(t){return this.get("/metadata",{query:{file:t}})}setFileMetadata(t,e){const r={file:t,metadata:e};return this.put("/metadata",{payload:r})}getOrCreateBucket(){return this.post("/bucket")}ensureBucketReadAccess(t){const e={principal:t};return this.post("/bucket/read-access",{payload:e})}getBucketReadAccessStatus(t){return this.get("/bucket/read-access",{query:{principal:t}})}list(t){return this.get("/list",{query:{prefix:t}})}getUploadUrl(t){return this.post("/upload-url",{payload:t})}getDownloadUrl(t,e,r){const s={file:t,name:e,disposition:r};return this.post("/download-url",{payload:s})}getDownloadUrlWithOptions(t){return this.post("/download-url",{payload:t})}bulkGetUploadUrls(t){return this.post("/bulk-upload-urls",{payload:t})}async bulkUpload(t,e=10){const r=t.map(t=>({name:t.name,mime_type:t.type,id:t instanceof Dt?t.id:void 0})),{files:s}=await this.bulkGetUploadUrls({files:r}),n=new Array(t.length);for(let r=0;r<t.length;r+=e){const o=t.slice(r,r+e);await Promise.all(o.map(async(t,e)=>{const o=r+e,{url:a,id:i,mime_type:u}=s[o],l=t instanceof Dt,c=t.type||u,d=await kt(a,{method:"PUT",body:l?t.stream:t,headers:c?{"Content-Type":c}:void 0});if(!d.ok)throw new Error(`Failed to upload file ${t.name}: ${d.statusText}`);const h=d.headers.get("etag")?.replace(/^"(.*)"$/,"$1");n[o]={source:i,name:t.name,type:c,etag:h}}))}return n}async uploadFile(t){return(await this.uploadFileWithPath(t)).id}async uploadFileWithPath(t){const e=t instanceof Dt,{url:r,id:s,path:n}=await this.getUploadUrl(t),o=await kt(r,{method:"PUT",body:e?t.stream:t,headers:{"Content-Type":t.type||"application/gzip"}}).catch(t=>{throw console.error("Failed to upload file",{err:t,url:r,id:s,path:n}),t});if(!o.ok)throw console.log(o),new Error(`Failed to upload file: ${o.statusText}`);return{id:s,path:n}}async downloadFile(t){const e=!t.startsWith("https:"),{url:r}=e?await this.getDownloadUrl(t):{url:t},s=await kt(r,{method:"GET"}).then(e=>{if(e.ok)return e;throw 404===e.status?new Error(`File at ${r} not found`):403===e.status?new Error(`File at ${r} is forbidden`):(console.log(e),new Error(`Failed to download file ${t}: ${e.statusText}`))}).catch(e=>{throw console.error(`Failed to download file ${t}.`,e),e});if(!s.body)throw new Error(`No body in response while downloading file ${t}`);return s.body}async copyFile(t,e){return(await this.post("/copy",{payload:{source:t,dest:e}})).dest}async uploadMemoryPack(t){const e=Lt(t.name),r=t.name.endsWith(".tar.gz")?t.name:`${t.name}.tar.gz`;if(t instanceof File){const s=t;return this.uploadFile(new Dt(s.stream(),r,s.type,e))}return this.uploadFile(new Dt(t.stream,r,t.type,e))}async downloadMemoryPack(t,e=!1){let r=await this.downloadFile(Lt(t));if(e){const t=new DecompressionStream("gzip");r=r.pipeThrough(t)}return r}listByPrefix(t){return this.get("/list",{query:{prefix:t}})}async uploadArtifact(t,e,r){const s=Bt(t,e);if(r instanceof File){const t=r;return this.uploadFile(new Dt(t.stream(),e,t.type,s))}return this.uploadFile(new Dt(r.stream,e,r.type,s))}async downloadArtifact(t,e){const r=Bt(t,e);return this.downloadFile(r)}getArtifactDownloadUrl(t,e,r){const s=Bt(t,e);return this.getDownloadUrl(s,e,r)}async listArtifacts(t){const e=`${Nt}/${t}/`;return(await this.listByPrefix(e)).files}}class zt extends U{constructor(t){super(t,"/api/v1/hive-memory")}list(t){const e=new URLSearchParams;t?.category&&e.set("category",t.category),t?.scope&&e.set("scope",t.scope),t?.limit&&e.set("limit",String(t.limit)),t?.offset&&e.set("offset",String(t.offset));const r=e.toString();return this.get(r?`/?${r}`:"/")}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}search(t){return this.post("/search",{payload:t})}recall(t,e){return this.post("/recall",{payload:{task_description:t,tools:e?.tools,category:e?.category,max_results:e?.maxResults}})}getFormatted(t){return this.get(`/${t}/formatted`)}recordUsage(t){return this.post(`/${t}/usage`,{})}getByCategory(t,e){const r=new URLSearchParams;e?.limit&&r.set("limit",String(e.limit)),e?.offset&&r.set("offset",String(e.offset));const s=r.toString();return this.get(`/category/${t}${s?`?${s}`:""}`)}getStats(){return this.get("/stats")}applyDecay(t){return this.post("/admin/decay",{payload:{days_threshold:t?.daysThreshold,decay_rate:t?.decayRate}})}archiveLowConfidence(t){return this.post("/admin/archive",{payload:{threshold:t}})}}class Wt extends U{constructor(t,e="/api/v1/indexing"){super(t,e)}async status(){return this.get("/status")}async reindex(t){return this.post("/reindex",{payload:t})}async reindexAgentRuns(t){return this.post("/agent-runs/reindex",{payload:t})}async analyzeDrift(){return this.post("/analyze-drift",{payload:{}})}async getDriftAnalysis(){return this.get("/drift-analysis")}async enableIndexing(){return this.post("/enable-indexing")}async disableIndexing(){return this.post("/disable-indexing")}async enableQueries(){return this.post("/enable-queries")}async disableQueries(){return this.post("/disable-queries")}index(t,e){return this.post("/internal/index",{payload:{object_id:t,document:e}})}delete(t){return this.post("/internal/delete",{payload:{object_id:t}})}bulkIndex(t,e){return this.post("/internal/bulk-index",{payload:{documents:t,target_index:e}})}ensureIndex(t){return this.post("/internal/ensure-index",{payload:{recreate:t}})}createReindexTarget(){return this.post("/internal/create-reindex-target",{payload:{}})}getStats(){return this.post("/internal/stats",{payload:{}})}fetchBatch(t,e){return this.post("/internal/fetch-batch",{payload:{cursor:t,limit:e}})}getNextIndexCursor(t,e,r){return this.post("/internal/next-cursor",{payload:{cursor:t,limit:e,count:r}})}analyzeDriftBatch(t,e){return this.post("/internal/analyze-drift-batch",{payload:{cursor:t,limit:e}})}triggerReindex(t){return this.post("/internal/trigger-reindex",{payload:t?{full_reindex:t.fullReindex,object_ids:t.objectIds,recreate_index:t.recreateIndex}:{}})}fetchDocumentsByIds(t){return this.post("/internal/fetch-by-ids",{payload:{object_ids:t}})}bulkDelete(t){return this.post("/internal/bulk-delete",{payload:{object_ids:t}})}getConfiguration(){return this.post("/internal/configuration",{payload:{}})}get zenoBulkBaseUrl(){const t=this.client.baseUrl;return t.includes("localhost:")||t.includes("127.0.0.1:")?"https://zeno-bulk-dev-main.api.dev1.vertesia.io":t.includes("zeno-server")?t.replace(/zeno-server/,"zeno-bulk"):t}zenoBulkPost(t,e){return this.client.post(this.zenoBulkBaseUrl+t,{payload:e})}computeShards(t,e,r,s){return this.zenoBulkPost("/reindex/compute-shards",{tenant_id:t,shard_size:e??25e4,updated_since:r,backend:s})}indexShard(t){return this.zenoBulkPost("/reindex/shard",{params:t})}swapAlias(t,e,r,s){return this.zenoBulkPost("/reindex/swap-alias",{tenant_id:t,target_index:e,alias:r,backend:s})}async reindexViaBulk(t,e,r,s,n,o){const a=`${this.zenoBulkBaseUrl}/reindex`,i={tenant_id:t,project_id:n,dry_run:r??!1,backend:s,shard_size:o?.shardSize,shards:o?.shards,bulk_concurrency:o?.bulkConcurrency,bulk_size_bytes:o?.bulkSizeBytes,bulk_max_docs:o?.bulkMaxDocs};if(!e)return this.client.post(a,{payload:{params:i}});let u;if(await this.client.sseRequest("POST",a,{payload:{params:i}},t=>{if(e(t),"event"===t.type&&"done"===t.event)try{u=JSON.parse(t.data)}catch{}}),!u)throw new Error("zeno-bulk SSE stream ended without a done event");return u}}class Jt extends U{objectId;constructor(t,e){super(t,`/${e}/analyze`),this.objectId=e}async start(t){return this.post("/",{payload:t})}async getStatus(){return this.get("/status")}async getResults(){return this.get("/results")}async adaptTables(t){return this.post("/adapt_tables",{payload:t})}async getAdaptedTables(t,e){const r=t?`/adapt_tables/${t}`:"/adapt_tables",s={};e?.format&&(s.format=e.format),void 0!==e?.raw&&(s.raw=e.raw);const n={query:s};return"csv"===e?.format&&(n.responseType="text"),this.get(r,n)}async getXml(){return this.get("/xml")}async getTables(t){const e={};return t&&(e.query={format:t}),this.get("/tables",e)}async getImages(){return this.get("/images")}async getAnnotated(){return this.get("/annotated")}}class Vt extends U{constructor(t){super(t,"/api/v1/objects")}analyze(t){return new Jt(this,t)}getUploadUrl(t){return this.post("/upload-url",{payload:t})}getDownloadUrl(t,e,r){return this.post("/download-url",{payload:{file:t,name:e,disposition:r}})}getDownloadUrlWithOptions(t){return this.post("/download-url",{payload:t})}getContentSource(t){return this.get(`/${t}/content-source`)}list(t={}){const e=t.limit||100,r=t.offset||0,s=t.query||{};return this.get("/",{query:{limit:e,offset:r,select:t.select,...s,all_revisions:t.all_revisions,from_root:t.from_root||void 0}})}computeFacets(t){return this.post("/facets",{payload:t})}listFolders(t="/"){throw new Error("Not implemented yet")}find(t){return this.post("/find",{payload:t})}count(t){return this.post("/count",{payload:t})}search(t){return this.post("/search",{payload:t})}retrieve(t,e){return this.get(`/${t}`,{query:{select:e}})}getObjectText(t){return this.get(`/${t}/text`)}async upload(t){const e=t instanceof Dt,{url:r,id:s,mime_type:n}=await this.getUploadUrl({id:e?t.id:void 0,name:t.name,mime_type:t.type}),o=t.type||n,a=await kt(r,{method:"PUT",body:e?t.stream:t,headers:o?{"Content-Type":o}:void 0}).catch(t=>{throw console.error("Failed to upload file",t),t});if(!a.ok)throw console.error("Failed to upload file",{status:a.status,statusText:a.statusText,url:r}),new Error(`Failed to upload file: ${a.statusText}`);const i=a.headers.get("etag")?.replace(/^"(.*)"$/,"$1");return{source:s,name:t.name,type:o,etag:i}}async create(t,e){const{content:r,...s}=t,n={...s};r instanceof Dt||r instanceof File?n.content=await this.upload(r):n.content=r;const a={};return e?.processing_priority&&(a[o.PROCESSING_PRIORITY]=e.processing_priority),e?.collection_id&&(a[o.COLLECTION_ID]=e.collection_id),await this.post("/",{payload:n,headers:a})}async createFromExternalSource(t,e={},r){const s=await this.client.files.getMetadata(t),n={...e,content:{source:t,name:s.name,type:s.contentType,etag:s.etag}},a={};return r?.processing_priority&&(a[o.PROCESSING_PRIORITY]=r.processing_priority),r?.collection_id&&(a[o.COLLECTION_ID]=r.collection_id),await this.post("/",{payload:n,headers:a})}async update(t,e,r){const{content:s,...n}=e,a={...n};s instanceof Dt||s instanceof File?a.content=await this.upload(s):a.content=s;const i={};return r?.ifMatch&&(i["if-match"]=r.ifMatch),r?.processing_priority&&(i[o.PROCESSING_PRIORITY]=r.processing_priority),r?.createRevision&&(i[o.CREATE_REVISION]="true",r.revisionLabel&&(i[o.REVISION_LABEL]=r.revisionLabel)),r?.suppressWorkflows&&(i[o.SUPPRESS_WORKFLOWS]="true"),this.put(`/${t}`,{payload:a,headers:i})}getRevisions(t){return this.get(`/${t}/revisions`)}getCollections(t){return this.get(`/${t}/collections`)}delete(t){return Array.isArray(t)?this.client.runOperation({name:"delete",ids:t,params:{}}):this.del(`/${t}`)}bulkUpdate(t){const e=Object.keys(t);return this.client.runOperation({name:"update",ids:e,params:t})}bulkCreate(t,e){return this.client.runOperation({name:"create",ids:[],params:{objects:t,...e}})}listWorkflowRuns(t){return this.get(`/${t}/workflow-runs`)}listRenditions(t){return this.get(`/${t}/renditions`)}getRendition(t,e){const r={max_hw:e.max_hw,generate_if_missing:e.generate_if_missing,sign_url:e.sign_url,block_on_generation:e.block_on_generation};return this.get(`/${t}/renditions/${e.format}`,{query:r})}getRenditionSafe(t,e,r){return a(e,r.format)?this.getRendition(t,r):Promise.resolve(null)}exportProperties(t){return this.post("/export",{payload:t})}setEmbedding(t,e,r){return this.put(`/${t}/embeddings/${e}`,{payload:r})}}class Gt extends U{constructor(t){super(t,"/api/v1/pending-asks")}register(t){return this.post("/",{payload:t})}resolve(t,e){return this.post(`/${t}/resolve`,{payload:e})}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}}class Kt extends U{constructor(t){super(t,"/api/v1/processes")}list(t){const e={};return t?.status&&(e.status=t.status),t?.process&&(e.process=t.process),null!=t?.limit&&(e.limit=String(t.limit)),null!=t?.offset&&(e.offset=String(t.offset)),t?.allVersions&&(e.all_versions="true"),this.get("/",{query:e})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}listVersions(t){return this.get(`/${t}/versions`)}publish(t,e){return this.post(`/${t}/publish`,{payload:e})}revert(t,e){return this.post(`/${t}/revert`,{payload:e})}delete(t){return this.del(`/${t}`)}}class Qt extends U{constructor(t,e="/api/v1/query"){super(t,e)}async execute(t){return this.post("/",{payload:t})}async sql(t){return this.execute({sql:t})}async esql(t){return this.execute({esql:t})}async dsl(t){return this.execute({dsl:t})}}class Yt extends U{constructor(t){super(t,"/api/v1/rendering")}start(t){return this.post("/jobs",{payload:t})}getStatus(t,e){return this.get("/jobs/status",{query:{workflow_id:t,workflow_run_id:e}})}async render(t,e={}){const r=e.pollIntervalMs??1500,s=e.timeoutMs??6e5,n=await this.start(t);if(!n.workflow_id||!n.workflow_run_id)throw new Error("Failed to start rendering workflow");const o=Date.now();for(;;){const e=await this.getStatus(n.workflow_id,n.workflow_run_id);if(e.status===i.COMPLETED){if(!e.download_url&&!e.file_uri)throw new Error(e.error||"Rendering completed but no output file was produced");return{status:"success",format:t.format,download_url:e.download_url,file_uri:e.file_uri}}if(u(e.status)){const t=i[e.status]||String(e.status);throw new Error(e.error||`Rendering failed with status: ${t}`)}if(Date.now()-o>=s)throw new Error(`Rendering timed out after ${s}ms`);await Xt(r)}}}function Xt(t){return new Promise(e=>setTimeout(e,t))}class Zt extends U{constructor(t){super(t,"/api/v1/schedules")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}trigger(t){return this.post(`/${t}/trigger`,{})}pause(t,e){return this.post(`/${t}/pause`,{payload:{note:e}})}resume(t,e){return this.post(`/${t}/resume`,{payload:{note:e}})}}class te extends U{constructor(t){super(t,"/api/v1/tasks")}list(t){const e={};return t?.status&&(e.status=Array.isArray(t.status)?t.status.join(","):t.status),t?.assignee&&(e.assignee=t.assignee),t?.run_id&&(e.run_id=t.run_id),t?.source_type&&(e.source_type=t.source_type),null!=t?.limit&&(e.limit=String(t.limit)),null!=t?.offset&&(e.offset=String(t.offset)),this.get("/",{query:e})}retrieve(t){return this.get(`/${t}`)}create(t){return this.post("/",{payload:t})}update(t,e){return this.put(`/${t}`,{payload:e})}complete(t,e){return this.post(`/${t}/complete`,{payload:e})}cancel(t){return this.post(`/${t}/cancel`,{})}delete(t){return this.del(`/${t}`)}}class ee extends U{constructor(t){super(t,"/api/v1/types/catalog")}list(t={}){return this.get("/",{query:t})}listSysTypes(t){return this.get("/sys",{query:{tag:t}})}listAppTypes(t){return this.get("/apps",{query:{tag:t}})}listStoredTypes(t={}){return this.get("/stored",{query:t})}resolve(t){const e="string"==typeof t?t:t.id;return this.get(`/resolve/${e}`)}}class re extends U{catalog;constructor(t){super(t,"/api/v1/types"),this.catalog=new ee(t)}list(t={},e){const r=t.limit||2e3,s=t.offset||0,n=t.query||{};return this.get("/",{query:{limit:r,offset:s,layout:!!e?.layout,schema:!!e?.schema,...n}})}find(t){return this.post("/find",{payload:t})}retrieve(t){return this.get(`/${t}`)}getTypeByName(t){return this.get(`/name/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}}const se="20260319",ne="x-api-version";class oe extends U{constructor(t){super(t,"/api/v1/workflows")}getActivityCatalog(){return this.get("/activity-catalog")}listRuns(t,e,r){return this.post("/runs",{payload:{documentId:t,eventName:e,ruleId:r}})}listConversations(t){return this.post("/conversations",{payload:t})}searchRuns(t){return this.post("/runs",{payload:t})}sendSignal(t,e,r,s){return this.post(`/runs/${t}/${e}/signal/${r}`,{payload:s})}getRunDetails(t,e,r){const s={};return void 0!==r?.includeHistory&&(s.include_history=r.includeHistory),void 0!==r?.historyFormat&&(s.history_format=r.historyFormat),void 0!==r?.hydratePayloads&&(s.hydrate_payloads=r.hydratePayloads),this.get(`/runs/${e}/${t}`,{query:s})}getRunInteraction(t,e){return this.get(`/runs/${t}/${e}/interaction`)}terminate(t,e,r){const s={reason:r};return this.post(`/runs/${t}/${e}/actions/terminate`,{payload:s})}cancel(t,e,r){const s={reason:r};return this.post(`/runs/${t}/${e}/actions/cancel`,{payload:s})}query(t,e,r){return this.get(`/runs/${t}/${e}/query/${r}`)}execute(t,e={}){return this.post(`/execute/${t}`,{payload:e})}postMessage(t,e){if(!t)throw new Error("runId is required");return this.post(`/runs/${t}/updates`,{payload:e})}async retrieveMessages(t,e,n){const o={since:n};return(await this.get(`/runs/${t}/${e}/updates`,{query:o})).messages.map(t=>r(s(t),e))}async streamMessages(t,n,o,a,i){return new Promise((u,l)=>{let c=0,d=a||0;const h=Date.now();let p=!1,y=null,g=null,f=null,m=null;const w=10,v=t=>{const e=Math.min(1e3*2**t,3e4);return e+.1*Math.random()*e},$=()=>{f&&(clearTimeout(f),f=null),g&&(clearInterval(g),g=null),y&&(y.close(),y=null),i&&m&&(i.removeEventListener("abort",m),m=null)},b=t=>{p||(p=!0,$(),u(t))};if(i){if(i.aborted)return void b(null);m=()=>b(null),i.addEventListener("abort",m,{once:!0})}const S=async(a=!1)=>{if(!p)try{const i=await J(),h=this.client,m=new URL(`${h.workflows.baseUrl}/runs/${t}/${n}/stream`);d>0&&m.searchParams.set("since",d.toString()),m.searchParams.set("skipHistory","true");const _=h._auth?await h._auth():void 0;if(p)return;if(!_)return p=!0,$(),void l(new Error("No auth token available"));const x=_.split(" ")[1];m.searchParams.set("access_token",x),a&&console.log(`Reconnecting to SSE stream for run ${n} (attempt ${c+1}/10)`);const k=new i(m.href);y=k,g=setInterval(()=>{},1e3),k.onopen=()=>{a&&console.log(`Successfully reconnected to SSE stream for run ${n}`),c=0},k.onmessage=t=>{if(t.data&&!t.data.startsWith(":"))try{const a=s(t.data);if(d=a.ts?Math.max(d,a.ts):Date.now(),o){const t=r(a,n);o(t,b)}Rt(a,n)?(console.log("Closing stream due to COMPLETE message from main workstream"),p||(p=!0,$(),u(null))):a.t===e.COMPLETE&&console.log(`Received COMPLETE message that does not close the root stream for run ${n}`)}catch(e){console.error("Failed to parse SSE message:",e,t.data)}else console.log("Received comment or heartbeat; ignoring it.: ",t.data)},k.onerror=t=>{if(!p)if(console.warn(`SSE stream error for run ${n}:`,t),$(),c<w){const t=v(c);console.log(`Attempting to reconnect in ${t}ms (attempt ${c+1}/10)`),c++,f=setTimeout(()=>{f=null,p||S(!0)},t)}else console.error(`Failed to reconnect to SSE stream for run ${n} after 10 attempts`),p=!0,l(new Error("SSE connection failed after 10 reconnection attempts"))}}catch(t){if(console.error("Error setting up SSE stream:",t),c<w){const t=v(c);c++,f=setTimeout(()=>{f=null,p||S(!0)},t)}else l(t)}};(async()=>{try{const e=await this.retrieveMessages(t,n,a);let r=!1;for(let t=0;t<e.length;t++){const s=e[t];d=Math.max(d,s.timestamp||0),o&&o(s,b),r=t===e.length-1&&Tt(s,n)}if(r)return void b(null)}catch(t){console.warn("Failed to fetch historical messages, continuing with SSE:",t)}!p&&d<=0&&(d=Math.max(1,h-1)),S(!1)})().catch(l)})}async streamMessagesWS(t,r,n,o){return new Promise((a,i)=>{let u=0;const l=10;let c=null,d=o||0,h=!1;const p=t=>{const e=Math.min(1e3*2**t,3e4);return e+.1*Math.random()*e},y=async()=>{if(!h)try{const o=this.client,g=new URL(`${o.workflows.baseUrl}/runs/${t}/${r}/ws`);g.protocol=g.protocol.replace("http","ws"),d>0&&g.searchParams.set("since",d.toString());const f=o._auth?await o._auth():void 0;if(!f)return void i(new Error("No auth token available"));const m=f.split(" ")[1];g.searchParams.set("access_token",m),u>0&&console.log(`Reconnecting to WebSocket for run ${r} (attempt ${u+1}/10)`),c=new WebSocket(g.href),c.onopen=()=>{u>0&&console.log(`Successfully reconnected to WebSocket for run ${r}`),u=0,h||a({cleanup:()=>{h=!0,c&&(c.close(),c=null)},sendSignal:(t,e)=>{if(c?.readyState===WebSocket.OPEN){const r={type:"signal",signalName:t,data:e,requestId:Date.now()};c.send(JSON.stringify(r))}else console.warn("WebSocket not open, cannot send signal")}})},c.onmessage=t=>{try{const r=JSON.parse(t.data);if("type"in r&&"string"==typeof r.type){if("pong"===r.type)return void console.debug("Received pong");if("ack"===r.type)return void console.debug("Signal acknowledged",r);if("error"===r.type)return void console.error("WebSocket error message",r)}const o=s(r);d=o.ts?Math.max(d,o.ts):Date.now(),n&&n(o);const a=o.w||"main";(o.t===e.TERMINATED||o.t===e.COMPLETE&&"main"===a)&&(console.log("Closing WebSocket due to workflow completion"),h=!0,c&&(c.close(),c=null))}catch(t){console.error("Failed to parse WebSocket message",t)}},c.onerror=t=>{console.error("WebSocket error",t)},c.onclose=()=>{if(!h&&u<l){const t=p(u);console.log(`WebSocket closed, reconnecting in ${t}ms (attempt ${u+1}/10)`),u++,setTimeout(y,t)}else u>=l&&i(new Error("WebSocket connection failed after 10 attempts"))}}catch(t){if(console.error("Error setting up WebSocket",t),u<l){const t=p(u);u++,setTimeout(y,t)}else i(t)}};y()})}ingestEvents(t,e,r){return this.post(`/runs/${t}/${e}/events`,{payload:{events:r}})}getAnalyticsSummary(t={}){return this.post("/analytics/summary",{payload:t})}getTokenUsageAnalytics(t={}){return this.post("/analytics/tokens",{payload:t})}getLlmLatencyAnalytics(t={}){return this.post("/analytics/latency/llm",{payload:t})}getToolLatencyAnalytics(t={}){return this.post("/analytics/latency/tools",{payload:t})}getAgentLatencyAnalytics(t={}){return this.post("/analytics/latency/agents",{payload:t})}getErrorAnalytics(t={}){return this.post("/analytics/errors",{payload:t})}getToolAnalytics(t={}){return this.post("/analytics/tools",{payload:t})}getToolParameterAnalytics(t){return this.post("/analytics/tools/parameters",{payload:t})}getAnalyticsFilterOptions(t={}){return this.post("/analytics/filter-options",{payload:t})}getPromptSizeAnalytics(t={}){return this.post("/analytics/prompt-size",{payload:t})}getTopPrincipalsAnalytics(t={}){return this.post("/analytics/top-principals",{payload:t})}getRunsByAgentAnalytics(t={}){return this.post("/analytics/runs-by-agent",{payload:t})}getTimeToFirstResponseAnalytics(t={}){return this.post("/analytics/time-to-first-response",{payload:t})}getFirstResponseBehaviorAnalytics(t={}){return this.post("/analytics/first-response-behavior",{payload:t})}rules=new ae(this);definitions=new ie(this)}class ae extends U{constructor(t){super(t,"/rules")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}execute(t,e,r){const s={objectIds:e,vars:r};return this.post(`/${t}/execute`,{payload:s})}}class ie extends U{constructor(t){super(t,"/definitions")}list(){return this.get("/")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}create(t){return this.post("/",{payload:t})}delete(t){return this.del(`/${t}`)}}class ue extends P{constructor(t={}){super(function(t){if(!t)throw new Error("zeno client serverUrl is required");return t}(t.serverUrl),t.fetch),t.apikey&&this.withApiKey(t.apikey),t.retryPolicy&&this.withRetryPolicy(t.retryPolicy),void 0!==t.timeout&&this.withTimeout(t.timeout),this.onRequest=t.onRequest,this.onResponse=t.onResponse,this.errorFactory=t=>404===t.status?new Mt(t.request,t):t}withApiVersion(t){return t?this.headers[ne]=String(t):delete this.headers[ne],this}withApiKey(t){return this.withAuthCallback(t?()=>Promise.resolve(`Bearer ${t}`):void 0)}runOperation(t){return this.post("/api/v1/operations",{payload:t})}get initialHeaders(){return{...super.initialHeaders,[ne]:se}}agents=new At(this);cost=new Ut(this);objects=new Vt(this);types=new re(this);workflows=new oe(this);schedules=new Zt(this);processes=new Kt(this);tasks=new te(this);files=new Ht(this);collections=new Pt(this);embeddings=new Ot(this);email=new jt(this);pendingAsks=new Gt(this);data=new It(this);indexing=new Wt(this);query=new Qt(this);hiveMemory=new zt(this);rendering=new Yt(this)}class le extends U{constructor(t){super(t,"/api/v1/tools")}list(t){const e={};return t?.sources?.length&&(e.sources=t.sources.join(",")),t?.exclude?.length&&(e.exclude=t.exclude.join(",")),this.get("/",{query:Object.keys(e).length>0?e:void 0})}listBuiltins(){return this.list({sources:["builtin"]})}validate(t){return this.post("/validate",{payload:{names:t}})}}class ce extends U{constructor(t){super(t,"/api/v1/training")}listSessions(t={}){return this.get("/",{query:{...t}})}listSessionNames(t={}){return this.get("/names",{query:{...t}})}createSession(t){return this.post("/",{payload:t})}getSession(t){return this.get(`/${t}`)}addToSession(t,e){return this.post(`/${t}/add`,{payload:{runs:e}})}listSessionRuns(t,e=100,r=0){return this.get(`/${t}/runs`,{query:{limit:e,offset:r}})}buildSession(t){return this.post(`/${t}/build`)}getDataUrl(t){return this.get(`/${t}/url`)}getDataUploadUrl(t,e=!1){return this.get(`/${t}/upload-url`,e?{query:{resumable:"true"}}:{})}startTraining(t){return this.post(`/${t}/start`)}cancelTraining(t){return this.post(`/${t}/cancel`)}getTrainingJob(t){return this.get(`/job/${t}`)}getAndSyncTrainingJob(t){return this.get(`/job/${t}`,{query:{sync:"true"}})}setDataset(t,e="default"){return this.post(`/${t}/dataset`,{payload:{dataset:e}})}}class de extends U{constructor(t){super(t,"/api/v1/users")}retrieve(t){return this.get(`/${t}`)}update(t,e){return this.put(`/${t}`,{payload:e})}delete(t){return this.del(`/${t}`)}}class he extends P{_jwt=null;store;sessionTags;tokenServerUrl;oauthClients;oauthGrants;oauthServer;oauthProviders;remoteMcpConnections;secrets;static async fromAuthToken(t,e,r){e||(e=ye(t));const s=r||fe(e.endpoints);return await new he({serverUrl:s.studio,storeUrl:s.store,tokenServerUrl:s.token||e.iss}).withApiKey(t)}static decodeEndpoints(){}constructor(t={site:"api.vertesia.io"}){let e,r;if(t.serverUrl)e=t.serverUrl;else{if(!t.site)throw new Error("Parameter 'site' or 'serverUrl' is required for VertesiaClient");e=`https://${t.site}`}if(t.storeUrl)r=t.storeUrl;else{if(!t.site)throw new Error("Parameter 'site' or 'storeUrl' is required for VertesiaClient");r=`https://${t.site}`}if(super(e,t.fetch),t.tokenServerUrl)this.tokenServerUrl=t.tokenServerUrl;else if(t.site){const e=t.site.replace(/^api/,"sts");this.tokenServerUrl=`https://${e}`}else if(t.serverUrl||t.storeUrl){const e=t.serverUrl||t.storeUrl||"";try{const t=new URL(e);if(t.hostname.startsWith("api")){const e=t.hostname.replace(/^api/,"sts");this.tokenServerUrl=`https://${e}`}else this.tokenServerUrl="https://sts.dev1.vertesia.io"}catch{this.tokenServerUrl="https://sts.dev1.vertesia.io"}}else this.tokenServerUrl="https://sts.dev1.vertesia.io";this.store=new ue({serverUrl:r,tokenServerUrl:this.tokenServerUrl,apikey:t.apikey,onRequest:t.onRequest,onResponse:t.onResponse,retryPolicy:t.retryPolicy,timeout:t.timeout,fetch:t.fetch}),t.retryPolicy&&this.withRetryPolicy(t.retryPolicy),void 0!==t.timeout&&this.withTimeout(t.timeout),t.apikey&&this.withApiKey(t.apikey),this.onRequest=t.onRequest,this.onResponse=t.onResponse,this.sessionTags=t.sessionTags,this.oauthClients=new nt(this),this.oauthGrants=new at(this),this.oauthServer=new ut(this,this.tokenServerUrl),this.oauthProviders=new it(this),this.remoteMcpConnections=new pt(this),this.secrets=new gt(this)}withApiVersion(t){return t?this.headers[ne]=String(t):delete this.headers[ne],this}withAuthCallback(t){return this.store.withAuthCallback(t),super.withAuthCallback(t)}withRetryPolicy(t){return this.store.withRetryPolicy(t),super.withRetryPolicy(t)}withTimeout(t){return this.store.withTimeout(t),super.withTimeout(t)}async withApiKey(t){return this.withAuthCallback(t?async()=>{if(!function(t){return t.startsWith("pk-")||t.startsWith("sk-")}(t))return`Bearer ${t}`;if(pe(this._jwt)){const e=await this.getAuthToken(t);this._jwt=e.token}return`Bearer ${this._jwt}`}:void 0)}async getRawJWT(){if(!this._jwt&&this._auth){const t=await this._auth();this._jwt||(this._jwt=t.trim().split(" ")[1])}return this._jwt||null}async getDecodedJWT(){const t=await this.getRawJWT();return t?ye(t):null}async getProject(){const t=await this.getDecodedJWT();return t?.project||null}async getAccount(){const t=await this.getDecodedJWT();return t?.account||null}get agents(){return this.store.agents}get workflows(){return this.store.workflows}get objects(){return this.store.objects}get files(){return this.store.files}get processes(){return this.store.processes}get tasks(){return this.store.tasks}get types(){return this.store.types}get data(){return this.store.data}get storeUrl(){return this.store.baseUrl}async getAuthToken(t){return this.post(`${this.tokenServerUrl}/token/issue`,{headers:{"content-type":"application/json",authorization:`Bearer ${t}`},retryPolicy:{attempts:4,methods:["POST"],statuses:[429,500,502,503,504]}}).catch(t=>{throw console.error(`Error fetching token from ${this.tokenServerUrl}:`,{error:t}),t})}get initialHeaders(){return{...super.initialHeaders,[ne]:se}}projects=new lt(this);environments=new N(this);interactions=new st(this);skills=new ft(this);prompts=new dt(this);runs=new yt(this);account=new C(this);accounts=new I(this);apikeys=new O(this);analytics=new j(this);auditTrail=new D(this);training=new ce(this);users=new de(this);iam=new B(this);refs=new ht(this);commands=new F(this);apps=new M(this);tools=new le(this)}function pe(t){if(!t)return!0;const e=ye(t).exp;return Date.now()>=1e3*e-6e4}function ye(t){const e=function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(4*Math.ceil(t.length/4),"="),r=globalThis.Buffer;if(r)return r.from(e,"base64").toString("utf-8");if("undefined"!=typeof atob&&"undefined"!=typeof TextDecoder){const t=atob(e),r=Uint8Array.from(t,t=>t.charCodeAt(0));return(new TextDecoder).decode(r)}throw new Error("No base64 decoder available")}(t.split(".")[1]);return JSON.parse(e)}function ge(){const t=globalThis.process;return t?.env?.STS_URL}function fe(t){return t?"string"==typeof t?me(t):t:me("api.vertesia.io")}function me(t){if("local"===t)return{studio:"http://localhost:8091",store:"http://localhost:8092",token:ge()??"https://sts.dev1.vertesia.io"};{const e=`https://${t}`;return{studio:e,store:e,token:e.replace("api","sts")}}}class we{id;client;constructor(t,e){this.id=t,this.client=e instanceof he?e:new he(e)}retrieve(){return this.client.interactions.retrieve(this.id)}update(t){return this.client.interactions.update(this.id,t)}render(t){throw new Error("Not implemented")}async execute(t={},e){return V(this.client,this.id,t,e)}}export{Nt as ARTIFACTS_PREFIX,At as AgentsApi,It as DataApi,jt as EmailApi,Ht as FilesApi,zt as HiveMemoryApi,Q as IS_INTERACTION_OUTPUT,Wt as IndexingApi,we as InteractionBase,Z as InteractionOutput,Ft as MEMORIES_PREFIX,nt as OAuthClientsApi,at as OAuthGrantsApi,it as OAuthProvidersApi,ut as OAuthServerApi,Vt as ObjectsApi,Gt as PendingAsksApi,Kt as ProcessApi,Qt as QueryApi,pt as RemoteMcpConnectionsApi,Yt as RenderingApi,Zt as SchedulesApi,gt as SecretsApi,Dt as StreamSource,te as TaskApi,ee as TypeCatalogApi,re as TypesApi,he as VertesiaClient,oe as WorkflowsApi,ie as WorkflowsDefinitionApi,ae as WorkflowsRulesApi,ue as ZenoClient,Mt as ZenoClientNotFoundError,et as createInteractionOutput,fe as decodeEndpoints,ye as decodeJWT,X as enhanceExecutionRun,Y as enhanceInteractionExecutionResult,kt as fetchSignedUrl,Bt as getAgentArtifactPath,Lt as getMemoryFilePath,pe as isTokenExpired};
|
|
2
|
-
|
|
1
|
+
import{AgentMessageType as e,ContentObjectApiHeaders as t,DataStoreApiHeaders as n,ExecutionRunStatus as r,Permission as i,WorkflowExecutionStatus as a,canGenerateRendition as o,getOAuthPermissionScopes as s,getSupportedRenditionFormats as c,isWorkflowTerminalStatus as l,parseMessage as u,supportsVisualRendition as d,toAgentMessage as f}from"@vertesia/common";function p(e){return typeof e==`object`&&!!e}function m(e){if(p(e))return e.details?e.details:p(e.error)?e.error.details:void 0}function h(e,t,n,r,i){let a=e;if(i){a+=`\nRequest: ${t.method} ${t.url} => ${n}`;let e=m(r);if(e){let t=typeof e;t===`string`?a+=`\nDetails: ${e}`:t===`object`&&(a+=`\nDetails: ${JSON.stringify(e,void 0,2)}`)}a+=`
|
|
2
|
+
Stack Trace: `}return a}var g=class extends Error{status;payload;request;request_info;displayDetails;original_message;constructor(e,t,n,r,i=!0){super(h(e,t,n,r,i)),this.original_message=e,this.request=t,this.status=n,this.payload=r,this.request_info=`${t.method} ${t.url} => ${n}`,this.displayDetails=i}get details(){return m(this.payload)}},_=class e extends g{constructor(e,t,n,r,i=!0){super(e,t,n,r,i)}updateDetails(t){if(t!==this.details){let n=p(this.payload)?{...this.payload,details:t}:{details:t};return new e(this.original_message,this.request,this.status,n,this.displayDetails)}else return this}},v=class extends g{constructor(e,t){super(`Failed to connect to server: ${t.message}`,e,0,t)}},y=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function b(e){}function x(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=b,onError:n=b,onRetry:r=b,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
3
|
+
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new y(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
4
|
+
`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
|
|
5
|
+
`,n);continue}let i=e.charCodeAt(n);if(S(e,n,i)){let i=e.charCodeAt(n+5)===32?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===10){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
|
|
6
|
+
`,n);continue}u=d===0?a:`${u}
|
|
7
|
+
${a}`,d++}else C(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
|
|
8
|
+
`,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
|
|
9
|
+
`,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){x();return}let r=e.charCodeAt(t);if(S(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
|
|
10
|
+
${i}`,d++;return}if(C(e,t,r)){f=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);l=r.includes(`\0`)?void 0:r;return}if(r===58){i&&i(e.slice(t,n).slice(e.charCodeAt(t+1)===32?2:1));return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
|
|
11
|
+
${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new y(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new y(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function x(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function w(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:w}}function S(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function C(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var w=class extends TransformStream{constructor(){let e;super({start(t){e=x({onEvent(e){let n={type:`event`,...e};t.enqueue(n)}})},transform(t){e.feed(t)}})}};let T;if(globalThis.TextDecoderStream&&typeof globalThis.TextDecoderStream==`function`)T=globalThis.TextDecoderStream;else{class e extends TransformStream{_options;constructor(e=`utf-8`,{fatal:n=!1,ignoreBOM:r=!1}={}){super(new t(new TextDecoder(e,{fatal:n,ignoreBOM:r}))),this._options={fatal:n,ignoreBOM:r,encoding:e}}get encoding(){return this._options.encoding}get fatal(){return this._options.fatal}get ignoreBOM(){return this._options.ignoreBOM}}class t{decoder;constructor(e){this.decoder=e}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw TypeError(`Input must be a compatible with: ArrayBuffer | Uint8Array`);let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}}T=e}async function ee(e){if(!e.ok){let t=await e.text(),n=Error(`SSE error: ${e.status}. Content:\n${t}`);throw n.status=e.status,n}if(!e.body)throw Error(`No body in response`);return e.body.pipeThrough(new T).pipeThrough(new w)}function te(e){let t=[];for(let n of Object.keys(e)){let r=e[n];r!=null&&t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`)}return t.join(`&`)}function ne(e,t){return e.endsWith(`/`)?t.startsWith(`/`)?e+t.substring(1):e+t:t.startsWith(`/`)?e+t:`${e}/${t}`}function E(e){return e[e.length-1]===`/`?e.slice(0,-1):e}function re(e){if(!(e===!1||e===null||e?.enabled===!1))return{maxWaitMs:Math.max(0,e?.maxWaitMs??3e3),attempts:Math.max(0,Math.floor(e?.attempts??2))}}const ie=[`GET`,`HEAD`,`OPTIONS`,`PUT`,`DELETE`],ae=[502,503,504];function D(e){return typeof e==`object`&&!!e}function oe(e){return e?Promise.resolve(e):typeof globalThis.fetch==`function`?Promise.resolve(globalThis.fetch):Promise.resolve(()=>{throw Error(`No Fetch implementation found`)})}function se(e){return D(e)&&e.error===`Not a valid JSON payload`&&typeof e.text==`string`}function ce(e){return!e||typeof ReadableStream>`u`||!(e instanceof ReadableStream)}function le(e){return e.status<500?!1:!(e.headers.get(`content-type`)??``).toLowerCase().includes(`json`)}function ue(e){let t=Math.max(1,Math.floor(e.attempts??3)),n=Math.max(0,e.baseDelayMs??250),r=Math.max(n,e.maxDelayMs??4e3);return{attempts:t,methods:new Set((e.methods??ie).map(e=>e.toUpperCase())),statuses:new Set(e.statuses??ae),retryNonJsonServerErrors:e.retryNonJsonServerErrors??!0,retryOnConnectionError:e.retryOnConnectionError??!0,baseDelayMs:n,maxDelayMs:r,jitter:e.jitter??!0}}function de(e){let t=e.headers.get(`retry-after`);if(!t)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function fe(e,t){if(e.status!==429||e.headers.get(`x-ratelimit-reason`)!==`pacing`)return;let n=e.headers.get(`x-ratelimit-retry-ms`),r=n?Number(n):NaN,i=Number.isFinite(r)&&r>=0?r:de(e);if(!(i===void 0||i>t.maxWaitMs))return i}function pe(e){return new Promise(t=>setTimeout(t,e))}function me(e,t,n){let r=(n?de(n):void 0)??Math.min(e.maxDelayMs,e.baseDelayMs*2**t);return e.jitter?Math.floor(Math.random()*r):r}function he(e){return e instanceof Error?e:Error(String(e))}function ge(e){return typeof e==`object`&&!!e&&`name`in e&&(e.name===`TimeoutError`||e.name===`AbortError`)}function _e(e){let t=AbortSignal.timeout;if(typeof t==`function`)return t(e);let n=new AbortController;return setTimeout(()=>n.abort(new DOMException(`The operation timed out`,`TimeoutError`)),e),n.signal}function ve(e){let t=e.filter(e=>!!e);if(t.length===0)return;if(t.length===1)return t[0];let n=AbortSignal.any;if(typeof n==`function`)return n(t);let r=new AbortController;for(let e of t){if(e.aborted){r.abort(e.reason);break}e.addEventListener(`abort`,()=>r.abort(e.reason),{once:!0})}return r.signal}async function O(e){try{await e.body?.cancel()}catch{}}var k=class{_fetch;baseUrl;errorFactory=e=>e;verboseErrors=!0;retryPolicy;pacingRetry;defaultTimeoutMs;constructor(e,t){this.baseUrl=E(e),this._fetch=oe(t)}throwError(e){throw this.errorFactory(e)}withPacingRetry(e){return this.pacingRetry=e===null?void 0:e,this}withRetryPolicy(e){return this.retryPolicy=e||void 0,this}getRetryPolicy(){return this.retryPolicy}withTimeout(e){return this.defaultTimeoutMs=typeof e==`number`&&e>0?e:void 0,this}getTimeout(){return this.defaultTimeoutMs}resolveTimeout(e){if(e?.reader===`sse`)return;let t=e?.timeoutMs;if(t===!1||t===null)return;if(typeof t==`number`)return t>0?t:void 0;let n=this.getTimeout();return n&&n>0?n:void 0}getUrl(e){return e.startsWith(`http://`)||e.startsWith(`https://`)?E(e):E(ne(this.baseUrl,e))}get(e,t){return this.request(`GET`,e,t)}del(e,t){return this.request(`DELETE`,e,t)}delete(e,t){return this.request(`DELETE`,e,t)}post(e,t){return this.request(`POST`,e,t)}put(e,t){return this.request(`PUT`,e,t)}jsonParse(e){return JSON.parse(e)}createRequest(e,t){return Promise.resolve(new Request(e,t))}handleFetchResponse(e,t){}createServerError(e,t,n){let r=`Server Error: ${t.status}`;return n&&(se(n)?(r+=t.statusText?` ${t.statusText}`:``,r+=`: non-JSON response`):D(n)&&n.message?r=String(n.message):D(n)&&n.error&&(typeof n.error==`string`?r=String(n.error):D(n.error)&&typeof n.error.message==`string`&&(r=n.error.message))),new _(r,e,t.status,n,this.verboseErrors)}async readJSONPayload(e){return e.text().then(t=>{if(t)try{return this.jsonParse(t)}catch(n){return{status:e.status,error:`Not a valid JSON payload`,message:n instanceof Error?n.message:String(n),text:t}}else return}).catch(t=>{if(ge(t))throw t;return{status:e.status,error:`Unable to load response content`,message:t instanceof Error?t.message:String(t)}})}handleResponse(e,t,n){return n?.reader?n.reader===`sse`?ee(t):n.reader.call(this,t):this.readJSONPayload(t).then(n=>{if(t.ok)return n;this.throwError(this.createServerError(e,t,n))})}async request(e,t,n){let r=this.getUrl(t);n?.query&&(r+=`?${te(n.query)}`);let i=this.headers?Object.assign({},this.headers):{},a=n?.headers;if(a)for(let e in a)i[e.toLowerCase()]=a[e];let o,s=n?.payload;s&&(n&&n.jsonPayload===!1?o=s:(o=typeof s==`string`?s:JSON.stringify(s),`content-type`in i||(i[`content-type`]=`application/json`))),n?.reader===`sse`&&(i.accept=`text/event-stream`);let c=e.toUpperCase(),l=this.resolveTimeout(n),u=()=>{let e=ve([n?.signal,l?_e(l):void 0]),t={method:c,headers:Object.assign({},i),body:o};return e&&(t.signal=e),t},d=this.resolveRetryPolicy(n),f=n?.reader===`sse`?void 0:re(n?.pacingRetry??this.pacingRetry),p=await this._fetch,m=ce(o),h=0,g=0,_;for(;;){let e=await this.createRequest(r,u());_=e;let t;try{t=await p(e)}catch(t){(!d||!this.shouldRetryConnectionError(d,c,h,m))&&(console.error(`Failed to connect to ${r}`,t),this.throwError(new v(e,he(t)))),await this.waitBeforeRetry(d,h),h++;continue}if(this.handleFetchResponse(e,t),f&&g<f.attempts&&m){let e=fe(t,f);if(e!==void 0){await O(t),await pe(e),g++;continue}}if(d&&this.shouldRetryResponse(d,c,h,m,t)){await O(t),await this.waitBeforeRetry(d,h,t),h++;continue}if(d&&h>=d.attempts)break;return this.handleResponse(e,t,n)}throw _&&this.throwError(new v(_,Error(`Retry attempts exhausted for ${c} ${r}`))),Error(`Retry attempts exhausted for ${c} ${r}`)}resolveRetryPolicy(e){if(e?.reader===`sse`||e?.retryPolicy===!1||e?.retryPolicy===null)return;let t=e?.retryPolicy,n=this.getRetryPolicy();if(!t&&!n)return;let r=ue({...n,...t});return r.attempts>1?r:void 0}shouldRetryResponse(e,t,n,r,i){let a=e.statuses.has(i.status)||e.retryNonJsonServerErrors&&le(i);return n<e.attempts-1&&r&&e.methods.has(t)&&a}shouldRetryConnectionError(e,t,n,r){return n<e.attempts-1&&r&&e.retryOnConnectionError&&e.methods.has(t)}waitBeforeRetry(e,t,n){let r=me(e,t,n);return new Promise(e=>setTimeout(e,r))}async sseRequest(e,t,n,r){let i=(await this.request(e,t,{...n,reader:`sse`})).getReader(),a;try{for(;;){let{done:e,value:t}=await i.read();if(e)break;a=t,r(t)}}finally{i.releaseLock()}return a}fetch(e,t){return this._fetch.then(n=>n(e,t))}};function ye(e){return e?`authorization`in e:!1}function be(){let e=globalThis;return e.window===void 0&&(typeof e.process?.versions?.node==`string`||typeof e.process?.versions?.bun==`string`||e.Bun!==void 0)}var A=class extends k{headers;_auth;onRequest;onResponse;response;constructor(e,t){super(e,t),this.baseUrl=e[e.length-1]===`/`?e.substring(0,e.length-1):e,this.headers=this.initialHeaders}get initialHeaders(){let e={accept:`application/json`};return be()&&(e[`accept-encoding`]=`br, gzip, deflate`),e}withAuthCallback(e){return this._auth=e||void 0,this}withErrorFactory(e){return this.errorFactory=e,this}withLang(e){return e?this.headers[`accept-language`]=e:delete this.headers[`accept-language`],this}withHeaders(e){let t=this.headers;for(let n in e){let r=e[n];r!=null&&(t[n.toLowerCase()]=r)}return this}setHeader(e,t){t?this.headers[e.toLowerCase()]=t:delete this.headers[e.toLowerCase()]}async createRequest(e,t){if(this._auth&&!ye(t.headers)){t.headers=t.headers?t.headers:{};let e=await this._auth();e&&(t.headers.authorization=e)}this.response=void 0;let n=await super.createRequest(e,t);return this.onRequest?.(n),n}handleFetchResponse(e,t){this.response=t,this.onResponse?.(t,e)}},j=class extends k{client;constructor(e,t){super(e.getUrl(t),e._fetch),this.client=e,this.createServerError=e.createServerError,this.errorFactory=e.errorFactory,this.verboseErrors=e.verboseErrors}createRequest(e,t){return this.client.createRequest(e,t)}handleResponse(e,t,n){return this.client.handleResponse(e,t,n)}handleFetchResponse(e,t){this.client.handleFetchResponse(e,t)}getRetryPolicy(){return this.client.getRetryPolicy()}getTimeout(){return this.client.getTimeout()}get headers(){return this.client.headers}},xe=class extends j{constructor(e){super(e,`/api/v1/account`)}info(){return this.get(`/`)}update(e){return this.put(`/`,{payload:e})}projects(){return this.get(`/projects`).then(e=>e.data)}members(){return this.get(`/members`)}inviteUser(e){return this.post(`/invites`,{payload:e})}listInvites(){return this.get(`/invites`)}listInvitation(e=`project`){return this.get(`/invites/${e}`)}acceptInvite(e){return this.put(`/invites/${e}`)}rejectInvite(e){return this.del(`/invites/${e}`)}onboardingProgress(){return this.get(`/onboarding`)}getStripeBillingStatus(){return this.get(`/stripe-billing-status`)}},Se=class extends j{constructor(e){super(e,`/api/v1/accounts`)}create(e){return this.post(`/`,{payload:{name:e}})}list(){return this.get(`/`)}},Ce=class extends j{constructor(e){super(e,`/api/v1/analytics`)}runsSummary(e,t){let n=new URLSearchParams;e?.start&&n.set(`start`,e.start),e?.end&&n.set(`end`,e.end),t&&n.set(`environment`,t);let r=n.toString();return this.get(`/runs/summary${r?`?${r}`:``}`)}runsTimeSeries(e,t){let n=new URLSearchParams;e?.start&&n.set(`start`,e.start),e?.end&&n.set(`end`,e.end),t&&n.set(`environment`,t);let r=n.toString();return this.get(`/runs/time-series${r?`?${r}`:``}`)}runsTokenUsage(e,t){let n=new URLSearchParams;e?.start&&n.set(`start`,e.start),e?.end&&n.set(`end`,e.end),t&&n.set(`environment`,t);let r=n.toString();return this.get(`/runs/token-usage${r?`?${r}`:``}`)}},we=class extends j{constructor(e){super(e,`/api/v1/apikeys`)}list(e=`account`){return this.get(`/`,{query:{level:e}})}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}retrieve(e,t=!1){return t?this.get(`/${e}`,{query:{withValue:!0}}):this.get(`/${e}`)}delete(e){return this.del(`/${e}`)}getToken(e){return this.get(`/${e}/token`)}requestPublicKey(e={}){return this.get(`/pk`,{query:e})}},Te=class extends j{constructor(e){super(e,`/api/v1/apps`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}listAppInstallationTools(e){return this.get(`/installations/${e}/tools`)}list(){return this.get(`/`)}install(e,t,n,r){return this.post(`/install`,{payload:{app_id:e,settings:t,oauth_params:n,oauth_provider_params:r}})}uninstall(e){return this.del(`/install/${e}`)}getAppInstallationByName(e){return this.get(`/installations/name/${e}`).catch(e=>{if(e.status===404)return null;throw e})}getAppInstallationProjects(e){if(!e.id&&!e.name)throw Error(`Invalid arguments: appId or appName must be specified`);let t=e.id?{id:e.id}:{name:e.name};return this.get(`/installations/projects`,{query:t})}getInstalledApps(e){return this.get(`/installations`,{query:{kind:e}})}getAllAppInstallations(){return this.get(`/installations/all`)}listInstallations(){return this.get(`/installations/refs`)}updateInstallationSettings(e){return this.put(`/installations/settings/${e.app_id}`,{payload:{app_id:e.app_id,settings:e.settings,...`access_control`in e?{access_control:e.access_control}:{}}})}updateToolAllowlist(e,t){return this.put(`/installations/${e}/tool-allowlist`,{payload:{tool_allowlist:t}})}validateUrl(e){return this.post(`/validate-url`,{payload:{url:e}})}},Ee=class extends j{constructor(e){super(e,`/api/v1/audit-trail`)}list(e){let t=new URLSearchParams;e?.actions?.length&&t.set(`actions`,e.actions.join(`,`)),e?.resourceTypes?.length&&t.set(`resourceTypes`,e.resourceTypes.join(`,`)),e?.resourceId&&t.set(`resourceId`,e.resourceId),e?.principalId&&t.set(`principalId`,e.principalId),e?.principalType&&t.set(`principalType`,e.principalType),e?.effectivePrincipalId&&t.set(`effectivePrincipalId`,e.effectivePrincipalId),e?.hasEffectivePrincipal!==void 0&&t.set(`hasEffectivePrincipal`,String(e.hasEffectivePrincipal)),e?.projectId&&t.set(`projectId`,e.projectId),e?.from&&t.set(`from`,e.from),e?.to&&t.set(`to`,e.to),e?.limit&&t.set(`limit`,String(e.limit)),e?.offset&&t.set(`offset`,String(e.offset));let n=t.toString();return this.get(`/${n?`?${n}`:``}`)}},De=class extends j{constructor(e){super(e,`/api/v1/commands`)}async isNamespaceAvailable(e){return this.get(`/namespaces/${e}/is_available`).then(e=>e.available)}async initSamples(){return this.post(`/onboarding/init-samples`)}},Oe=class extends j{constructor(e){super(e,`/api/v1/environments`)}list(e=!1){let t=e?{all:!0}:void 0;return this.get(`/`,{query:t})}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}updateConfig(e,t){return this.put(`/${e}/config`,{payload:t})}listModels(e,t){return this.get(`/${e}/models`,{query:t?{...t}:void 0})}enableModel(e,t){return this.post(`/${e}/models/enabled`,{payload:t})}disableModel(e,t){return this.del(`/${e}/models/enabled/${encodeURIComponent(t)}`)}listTrainableModels(e){return this.get(`/${e}/trainable-models`)}embeddings(e,t){return this.post(`/${e}/embeddings`,{payload:t})}migrateInteractions(e){return this.post(`/migrate-interactions`,{payload:e})}},ke=class extends j{constructor(e){super(e,`/groups`)}list(e){return this.get(`/`,{query:e})}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}listMembers(e){return this.get(`/${e}/members`)}addMember(e,t){return this.post(`/${e}/members/${t}`)}removeMember(e,t){return this.del(`/${e}/members/${t}`)}syncMembers(){return this.post(`/sync-members`)}},Ae=class extends j{constructor(e){super(e,`/api/v1/iam`)}aces=new Me(this);roles=new je(this);groups=new ke(this);getPrincipalIdentity(){return this.get(`/users/identity`)}},je=class extends j{constructor(e){super(e,`/roles`)}list(){return this.get(`/`)}listSystem(){return this.get(`/system`)}},Me=class extends j{constructor(e){super(e,`/aces`)}list(e){return this.get(`/`,{query:{...e}})}listProjectAces(){return this.get(`/project`)}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}};const M=(()=>{let e=typeof process<`u`?process.env?.VERTESIA_INTERACTION_TIMEOUT_MS:void 0,t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:1800*1e3})();async function N(){return typeof globalThis.EventSource==`function`?globalThis.EventSource:(await import(`eventsource`)).EventSource}async function P(e,t,n={},i){let a=!!i,o=await e.runs.create({...n,interaction:t,stream:a},{timeoutMs:a?void 0:M});if(a){if(o.status===r.failed)return o;await F(e,o.id,i)}return o}async function Ne(e,t,n={},i){let a=!!i,o=await e.post(`/api/v1/execute`,{payload:{...n,interaction:t,stream:a},timeoutMs:a?void 0:M});if(a){if(o.status===r.failed)return o;await F(e,o.id,i)}return o}function F(e,t,n){return new Promise((r,i)=>{(async()=>{try{let a=await N(),o=new URL(`${e.runs.baseUrl}/${t}/stream`),s=e._auth?await e._auth():void 0;if(s){let e=s.split(` `)[1];o.searchParams.set(`access_token`,e)}else throw Error(`No auth token available`);let c=new a(o.href);c.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);t&&n?.(t)}catch(e){i(e)}}),c.addEventListener(`close`,e=>{try{c.close(),r(JSON.parse(e.data))}catch(e){i(e)}})}catch(e){i(e)}})()})}async function Pe(e,t){return await e.post(`/api/v1/execute/async`,{payload:t})}async function Fe(e,t){return await e.post(`/api/v1/execute/rate-limit/request`,{payload:t})}var Ie=class extends j{constructor(e){super(e,`/api/v1/interactions/catalog`)}list(e={}){return this.get(`/`,{query:e})}listStoredInteractions(e={}){return this.get(`/stored`,{query:e})}listSysInteractions(e){return this.get(`/sys`,{query:{tag:e}})}listAppInteractions(e,t){return this.get(`/apps/${e}`,{query:{tag:t}})}listAllAppInteractions(e){return this.get(`/apps`,{query:{tag:e}})}resolve(e){return this.get(`/resolve/${e}`)}};const I=Symbol(`InteractionOutput`);function L(e){return e.result=z.from(e.result),e}function R(e){return e.result=z.from(e.result),e}var z=class{results;constructor(e){this.results=e}static from(e){return e?B(e)?e:V(Array.isArray(e)?e:typeof e==`object`?[{type:`json`,value:e}]:[{type:`text`,value:String(e)}]):V([])}static isInteractionOutputArray(e){return B(e)}get isEmpty(){return this.results.length===0}hasObject(){return this.results.some(e=>e.type===`json`)}hasText(){return this.results.some(e=>e.type===`text`)}hasImage(){return this.results.some(e=>e.type===`image`)}text(e=`
|
|
12
|
+
`){return this.results.filter(e=>e.type===`text`).map(e=>e.value).join(e)}texts(){return this.results.filter(e=>e.type===`text`).map(e=>e.value)}object(){let e=this.results.find(e=>e.type===`json`);return e?e.value:Le(this.results)}objects(){return this.results.filter(e=>e.type===`json`).map(e=>e.value)}objectAt(e){let t=0;for(let n of this.results)if(n.type===`json`){if(t===e)return n.value;t++}throw Error(`Object at index ${e} not found`)}image(){let e=this.results.find(e=>e.type===`image`);if(!e)throw Error(`No image result found`);return e.value}images(){return this.results.filter(e=>e.type===`image`).map(e=>e.value)}stringify(e=`
|
|
13
|
+
`,t=2){return this.results.map(e=>{switch(e.type){case`json`:return JSON.stringify(e.value,null,t);default:return String(e.value)}}).join(e)}toString(){return this.text()}toJSON(){return this.results}};function B(e){return!!e&&typeof e==`object`&&e[I]===!0}function V(e){let t=new z(e);return new Proxy(e,{get(e,n,r){if(n===I)return!0;if(n in t){let e=Reflect.get(t,n,t);return typeof e==`function`?e.bind(t):e}return Reflect.get(e,n,r)}})}function Le(e){let t;for(let n of e)if(n.type===`text`){let e=n.value.trim();try{return JSON.parse(e)}catch(e){t=e instanceof Error?e:Error(String(e))}}throw t||=Error(`No JSON result found and no text available to parse`),t}function H(e){return!!e&&typeof e==`object`&&`id`in e&&typeof e.id==`string`}var Re=class extends j{catalog;constructor(e){super(e,`/api/v1/interactions`),this.catalog=new Ie(e)}list(e={}){let t=e.query||{};return this.get(`/`,{query:{...t}})}listEndpoints(e){return this.post(`/endpoints`,{payload:e})}listVersionsByName(e){return this.get(`/versions/${e}`)}listTags(e){return this.get(`/tags`,{query:{...e}})}computeFacets(e){return this.post(`/facets`,{payload:e})}listNames(){return this.get(`/names`)}export(e){return this.post(`/export`,{payload:e})}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e,t){let{cascade:n,query:r,...i}=t??{},a=n?{...r??{},cascade:`true`}:r??void 0;return super.delete(`/${e}`,{...i,query:a})}async execute(e,t={},n){return L(await P(this.client,e,t,n).catch(e=>{throw e instanceof _&&H(e.payload)?e.updateDetails({run_id:e.payload.id}):e}))}async executeByName(e,t={},n){return L(await Ne(this.client,e,t,n).catch(e=>{throw e instanceof _&&H(e.payload)?e.updateDetails({run_id:e.payload.id}):e}))}executeAsync(e){return Pe(this.client,e)}publish(e,t){return this.post(`/${e}/publish`,{payload:t})}fork(e,t){return this.post(`/${e}/fork`,{payload:t})}generateInteraction(e,t){return this.post(`${e}/generate-interaction`,{payload:t})}generateTestData(e,t){return this.post(`${e}/generate-test-data`,{payload:t})}suggestImprovements(e,t){return this.post(`${e}/suggest-prompt-improvements`,{payload:t})}suggestPromptImprovements(e){return this.post(`/improve`,{payload:e})}listVersions(e){return this.get(`/${e}/versions`)}listForks(e){return this.get(`/${e}/forks`)}requestSlot(e){return Fe(this.client,e)}resolve(e,t){return this.get(`/resolve/${encodeURIComponent(e)}`,{query:t})}},U=class extends j{constructor(e){super(e,`/internal/secrets`)}rotateEventWebhookSigningSecret(e,t){return this.post(`/event-webhooks/${e}/rotate`,{payload:t})}deleteEventWebhookSigningSecret(e,t){return this.post(`/event-webhooks/${e}/delete`,{payload:t})}signEventWebhook(e,t){return this.post(`/event-webhooks/${e}/sign`,{payload:t})}rotateEventIngestChannelSigningSecret(e,t){return this.post(`/event-ingest-channels/${e}/rotate`,{payload:t})}deleteEventIngestChannelSigningSecret(e,t){return this.post(`/event-ingest-channels/${e}/delete`,{payload:t})}verifyEventIngestSignature(e,t){return this.post(`/event-ingest-channels/${e}/verify`,{payload:t})}mintGithubInstallationToken(e){return this.post(`/github/installation-token`,{payload:e})}},W=class extends j{constructor(e){super(e,`/api/v1/oauth-clients`)}list(){return this.get(`/`)}retrieve(e){return this.get(`/${e}`)}scopeMetadata(){return this.get(`/scope-metadata`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}remove(e){return this.del(`/${e}`)}};function ze(e){if(e)return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>[e,String(t)]))}var Be=class extends j{constructor(e){super(e,`/api/v1/oauth-grants`)}list(e){return this.get(`/`,{query:ze(e)})}retrieve(e){return this.get(`/${e}`)}revoke(e,t){return this.del(`/${e}`,{query:t})}revokeBulk(e){return this.post(`/revoke`,{payload:e})}},Ve=class extends j{constructor(e){super(e,`/api/v1/oauth-providers`)}list(){return this.get(`/`)}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}remove(e){return this.del(`/${e}`)}authorize(e){return this.get(`/${e}/authorize`)}exchange(e,t){return this.post(`/exchange`,{payload:{code:e,state:t}})}getStatus(e){return this.get(`/${e}/status`)}connect(e){return this.post(`/${e}/connect`,{payload:{}})}getToken(e){return this.post(`/${e}/token`,{payload:{}})}disconnect(e){return this.del(`/${e}/disconnect`)}},He=class extends k{parent;constructor(e,t){super(new URL(`/oauth`,`${t||e.baseUrl}/`).toString(),e._fetch),this.parent=e,this.createServerError=e.createServerError,this.errorFactory=e.errorFactory,this.verboseErrors=e.verboseErrors}get headers(){return this.parent.headers}createRequest(e,t){return this.parent.createRequest(e,t)}handleResponse(e,t,n){return this.parent.handleResponse(e,t,n)}handleFetchResponse(e,t){this.parent.handleFetchResponse(e,t)}getRetryPolicy(){return this.parent.getRetryPolicy()}createAuthorizationRequest(e){return this.post(`/requests`,{payload:e})}createDeviceAuthorization(e){return this.post(`/device_authorization`,{payload:e})}retrieveDeviceRequest(e){return this.get(`/device/${encodeURIComponent(e)}`)}retrieveRequest(e){return this.get(`/requests/${e}`)}retrieveGrantableScopes(e,t){return this.get(`/requests/${e}/grantable-scopes`,{query:{project_id:t}})}approveRequest(e,t){return this.post(`/requests/${e}/approve`,{payload:t})}denyRequest(e){return this.post(`/requests/${e}/deny`,{payload:{}})}},Ue=class extends j{integrations;constructor(e){super(e,`/api/v1/projects`),this.integrations=new We(this)}list(e){return this.get(`/`,{query:{account:e}})}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}updateConfiguration(e,t){return this.put(`/${e}/configuration`,{payload:t})}getTools(e){return this.get(`/${e}/tools`)}getToolByName(e,t){return this.get(`/${e}/tools/${t}`).catch(e=>{if(e.status===404)return null;throw e})}listAppContentTypes(e,t){return this.get(`/${e}/app-types`,{query:{tag:t}})}getAppContentType(e,t){return this.get(`/${e}/app-types/${t}`)}listAppProcesses(e,t){return this.get(`/${e}/app-processes`,{query:{tag:t}})}getAppProcess(e,t){return this.get(`/${e}/app-processes/${t}`)}listAppRenderingTemplates(e,t){return this.get(`/${e}/app-templates`,{query:{tag:t}})}getAppRenderingTemplate(e,t){return this.get(`/${e}/app-templates/${t}`)}getCompositeAppConfiguration(e){return this.get(`/${e}/composite-app`)}updateCompositeAppConfiguration(e,t){return this.put(`/${e}/composite-app`,{payload:t})}},We=class extends j{constructor(e){super(e,`/`)}list(e){return this.get(`/${e}/integrations`).then(e=>e.integrations)}retrieve(e,t){return this.get(`/${e}/integrations/${t}`).catch(e=>{if(e.status!==404)throw e})}update(e,t,n){return this.put(`/${e}/integrations/${t}`,{payload:n})}updatePlugins(e,t){return this.post(`/${e}/plugins`,{payload:{plugins:t}})}listPlugins(e){return this.get(`/${e}/plugins`)}},Ge=class extends j{constructor(e){super(e,`/api/v1/prompts`)}list(e={}){let t=e.query||{};return this.get(`/`,{query:{...t}})}computeFacets(e){return this.post(`/facets`,{payload:e})}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}fork(e,t){return this.post(`/${e}/fork`,{payload:t})}render(e,t){return this.post(`/${e}/render`,{payload:t})}options(e){return this.get(`/options/${e}`)}listVersions(e){return this.get(`/${e}/versions`)}listInteractions(e){return this.get(`/${e}/interactions`)}listForks(e){return this.get(`/${e}/forks`)}},Ke=class extends j{constructor(e){super(e,`/api/v1/quota`)}standing(){return this.get(`/standing`)}tier(){return this.get(`/tier`)}},qe=class extends j{constructor(e){super(e,`/api/v1/refs`)}resolve(e){return this.post(`/resolve`,{payload:{refs:e}})}},Je=class extends j{constructor(e){super(e,`/api/v1/remote-mcp-connections`)}getStatus(e){return this.get(`/status/${e}`)}getCollectionStatus(e,t){return this.get(`/status/${e}/${t}`)}getMetadata(e,t){return this.get(`/metadata/${e}/${t}`)}authorize(e,t){return this.get(`/authorize/${e}/${t}`)}exchange(e,t){return this.post(`/exchange`,{payload:{code:e,state:t}})}connect(e,t){return this.post(`/connect/${e}/${t}`,{})}disconnect(e,t){return this.del(`/disconnect/${e}/${t}`)}getCollectionToken(e,t){return this.post(`/token`,{payload:{app_install_id:e,collection_id:t}})}getToken(e){return this.post(`/token`,{payload:{mcp_server_url:e}})}},Ye=class extends j{constructor(e){super(e,`/api/v1/runs`)}list({limit:e,offset:t,filters:n}){let r={limit:e,offset:t,...n};return this.get(`/`,{query:r})}find(e){return this.post(`/find`,{payload:e})}async retrieve(e){return R(await this.get(`/${e}`))}retrievePopulated(e){return this.get(`/${e}`,{query:{populate:`true`}})}filterOptions(e,t){let n={...t};return this.get(`/filter-options/${e}`,{query:n})}async create(e,t){let n=this.client.sessionTags;if(n){let t=Array.isArray(n)?n:[n];Array.isArray(e.tags)?t=t.concat(e.tags):e.tags&&(t=t.concat([e.tags])),e={...e,tags:t}}return R(await this.post(`/`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal}))}sendToolResults(e){return this.post(`/tool-results`,{payload:e})}sendUserMessage(e){return this.post(`/user-message`,{payload:e})}computeFacets(e){return this.post(`/facets`,{payload:e})}search(e){return this.post(`/search`,{payload:e})}clone(e){return this.post(`/clone`,{payload:e})}},Xe=class extends j{constructor(e){super(e,`/api/v1/secrets`)}list(e,t){return this.get(`/`,{query:{...t,project_id:e}}).then(e=>e.secrets)}retrieve(e,t,n){return this.get(`/${t}`,{query:{...n,project_id:e}}).catch(e=>{if(e.status!==404)throw e})}create(e,t){return this.post(`/`,{query:{project_id:e},payload:t})}update(e,t,n,r){return this.put(`/${t}`,{query:{...r,project_id:e},payload:n})}remove(e,t,n){return this.del(`/${t}`,{query:{...n,project_id:e}})}fillWebsiteCredential(e,t,n){return this.post(`/${t}/actions/fill-browser`,{query:{project_id:e},payload:n})}},Ze=class extends j{constructor(e){super(e,`/api/v1/skills`)}findRelevant(e,t){let n={context:e,limit:t};return this.post(`/find-relevant`,{payload:n})}findRelevantForTask(e,t){return this.findRelevant({task_description:e,tool_names:t})}};const Qe=new Set([429,500,502,503,504]);function $e(e){return new Promise(t=>setTimeout(t,e))}function et(e){let t=e.headers.get(`retry-after`);if(!t)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function tt(e,t,n,r){let i=r?et(r):void 0;if(i!==void 0)return Math.min(n,i);let a=Math.min(n,t*2**e);return Math.floor(Math.random()*a)}const nt=new TextEncoder;function rt(e){if(typeof e==`string`)return nt.encode(e);if(e instanceof Blob)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw TypeError(`Unsupported signed-URL upload chunk of type "${typeof e}"; body streams must yield string or binary (Uint8Array/ArrayBuffer/DataView/Blob) chunks.`)}async function it(e){if(e!=null){if(typeof ReadableStream<`u`&&e instanceof ReadableStream){let t=e.getReader(),n=[];try{for(;;){let{done:e,value:r}=await t.read();if(e)break;n.push(rt(r))}}catch(e){throw await t.cancel(e).catch(()=>void 0),e}finally{t.releaseLock()}return new Blob(n)}return e}}async function G(e,t={}){let{method:n=`GET`,headers:r,attempts:i=4,baseDelayMs:a=500,maxDelayMs:o=8e3,retryableStatuses:s=Qe}=t,c=await it(t.body),l;for(let t=0;t<i;t++){let u=t===i-1;try{let i=await fetch(e,{method:n,headers:r,body:c});if(i.ok||!s.has(i.status)||u)return i;await i.body?.cancel().catch(()=>void 0),await $e(tt(t,a,o,i))}catch(e){if(l=e,u)throw e;await $e(tt(t,a,o))}}throw l instanceof Error?l:Error(`Failed to fetch signed URL: ${e}`)}function at(e){if(!e||typeof e!=`object`)return;let t=e.process_run_id;return typeof t==`string`?t:void 0}function ot(e,t){let n=at(e);return!n||n===t}function st(t,n){return t.type===e.TERMINATED||t.type===e.COMPLETE&&(t.workstream_id??`main`)===`main`?ot(t.details,n):!1}function ct(t,n){return t.t===e.TERMINATED||t.t===e.COMPLETE&&(t.w??`main`)===`main`?ot(t.d,n):!1}var lt=class extends j{constructor(e){super(e,`/api/v1/agents`)}start(e){return this.post(`/`,{payload:e})}recordRun(e){return this.post(`/record`,{payload:e})}createRecord(e){return this.recordRun(e)}retrieve(e){return this.get(`/${e}`)}retrieveRun(e){return this.get(`/${e}`)}retrieveProcess(e){return this.get(`/${e}`)}list(e){return this.get(`/`,{query:this.buildListQueryParams(e)})}async listProcessRuns(e){return(await this.get(`/`,{query:this.buildListQueryParams({...e,run_kind:`process`})})).items.filter(ut)}buildListQueryParams(e){let t={};return e?.id&&(t.id=e.id),e?.status&&(t.status=Array.isArray(e.status)?e.status.join(`,`):e.status),e?.interaction&&(t.interaction=e.interaction),e?.started_by&&(t.started_by=e.started_by),e?.since&&(t.since=e.since.toISOString()),e?.until&&(t.until=e.until.toISOString()),e?.schedule_id&&(t.schedule_id=e.schedule_id),e?.type&&(t.type=e.type),e?.run_type&&(t.run_type=Array.isArray(e.run_type)?e.run_type.join(`,`):e.run_type),e?.run_kind&&(t.run_kind=e.run_kind),e?.limit&&(t.limit=String(e.limit)),e?.offset&&(t.offset=String(e.offset)),e?.cursor&&(t.cursor=e.cursor),e?.sort&&(t.sort=e.sort),e?.order&&(t.order=e.order),t}search(e){let t={};return e?.query&&(t.query=e.query),e?.status&&(t.status=Array.isArray(e.status)?e.status.join(`,`):e.status),e?.interaction&&(t.interaction=e.interaction),e?.started_by&&(t.started_by=e.started_by),e?.categories?.length&&(t.categories=e.categories.join(`,`)),e?.tags?.length&&(t.tags=e.tags.join(`,`)),e?.content_type_name&&(t.content_type_name=e.content_type_name),e?.since&&(t.since=e.since.toISOString()),e?.until&&(t.until=e.until.toISOString()),e?.limit&&(t.limit=String(e.limit)),e?.offset&&(t.offset=String(e.offset)),e?.sort?.length&&(t.sort=e.sort.join(`,`)),this.get(`/search`,{query:t})}terminate(e,t){let n=t?{reason:t}:void 0;return this.del(`/${e}`,{query:n})}restart(e){return this.post(`/${e}/restart`,{})}fork(e){return this.post(`/${e}/fork`,{})}getContext(e){return this.get(`/${e}/context`)}getHistory(e){return this.get(`/${e}/history`)}advance(e,t){return this.post(`/${e}/advance`,{payload:t??{}})}retryNode(e,t){return this.post(`/${e}/retry-node`,{payload:t??{}})}answerTask(e,t,n){return this.post(`/${e}/answer-task`,{payload:{task_id:t,result:n}})}updateStatus(e,t){return this.post(`/${e}/status`,{payload:t})}bindWorkflowRun(e,t){return this.post(`/${e}/workflow`,{payload:t})}sendSignal(e,t,n){return this.post(`/${e}/signal/${t}`,{payload:n})}query(e,t){return this.get(`/${e}/query/${t}`)}getActiveWorkstreams(e){return this.query(e,`ActiveWorkstreams`)}async retrieveMessages(e,t){let n=t?{since:t}:void 0;return(await this.get(`/${e}/updates`,{query:n})).messages.map(t=>f(u(t),e))}postMessage(e,t){return this.post(`/${e}/updates`,{payload:t})}async streamMessages(e,t,n,r,i){let a=()=>{},o=()=>{},s=new Promise((e,t)=>{a=e,o=t}),c=0,l=n||0,d=Date.now(),p=!1,m=null,h=null,g=null,_=null,v=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},y=()=>{g&&=(clearTimeout(g),null),h&&=(clearInterval(h),null),m&&=(m.close(),null),r&&_&&(r.removeEventListener(`abort`,_),_=null)},b=e=>{p||(p=!0,y(),a(e))};if(r){if(r.aborted)return p=!0,y(),a(null),s;_=()=>{b(null)},r.addEventListener(`abort`,_,{once:!0})}try{if(!p){let r=await this.retrieveMessages(e,n);i?.onHistoryLoaded?.(r);let a=!1;for(let n=0;n<r.length;n++){let i=r[n];if(p||(l=Math.max(l,i.timestamp||0),t&&t(i,b),p))break;a=n===r.length-1&&st(i,e)}if(a)return b(null),s}}catch(e){p||(i?.onHistoryError?.(e),console.warn(`Failed to fetch historical messages, continuing with SSE:`,e))}!p&&l<=0&&(l=Math.max(1,d-1));let x=async(n=!1)=>{if(!p)try{let r=await N();if(p)return;let i=this.client,a=new URL(`${i.agents.baseUrl}/${e}/stream`);l>0&&a.searchParams.set(`since`,l.toString()),a.searchParams.set(`skipHistory`,`true`);let s=i._auth?await i._auth():void 0;if(p)return;if(!s){p=!0,y(),o(Error(`No auth token available`));return}let d=s.split(` `)[1];if(a.searchParams.set(`access_token`,d),n&&console.log(`Reconnecting to agent stream ${e} (attempt ${c+1}/10)`),p)return;let _=new r(a.href);m=_,h=setInterval(()=>{},1e3);let S=0;_.onopen=()=>{n&&console.log(`Reconnected to agent stream ${e}`),S=Date.now()},_.onmessage=n=>{if(!p&&!(!n.data||n.data.startsWith(`:`)))try{let r=u(n.data);l=r.ts?Math.max(l,r.ts):Date.now(),t&&t(f(r,e),b),ct(r,e)&&b(null)}catch(e){console.error(`Failed to parse SSE message:`,e,n.data)}},_.onerror=e=>{if(!p)if(y(),(S?Date.now()-S:0)>5e3&&(c=0),c<10){let e=v(c);c++,g=setTimeout(()=>{g=null,p||x(!0)},e)}else p=!0,y(),o(Error(`SSE connection failed after 10 reconnection attempts`))}}catch(e){if(p)return;if(c<10){let e=v(c);c++,g=setTimeout(()=>{g=null,p||x(!0)},e)}else p=!0,y(),o(e)}};return x(!1),s}getInternals(e){return this.get(`/${e}/internals`)}getRunDetails(e,t){let n={};return t?.includeHistory&&(n.include_history=`true`),t?.hydratePayloads&&(n.hydrate_payloads=`true`),this.get(`/${e}/details`,{query:n})}async streamRunDetails(e,t,n){let r=await N(),i=this.client,a=new URL(`${i.agents.baseUrl}/${e}/details/stream`),o=i._auth?await i._auth():void 0;if(!o)throw Error(`No auth token available`);let s=o.split(` `)[1];return a.searchParams.set(`access_token`,s),new Promise((e,i)=>{let o=new r(a.href),s=null,c=()=>{o.close(),n&&s&&(n.removeEventListener(`abort`,s),s=null)};if(n){if(n.aborted){c(),e();return}s=()=>{c(),e()},n.addEventListener(`abort`,s,{once:!0})}o.addEventListener(`history`,e=>{try{let n=JSON.parse(e.data);t&&t({type:`history`,data:n})}catch{}}),o.addEventListener(`control`,n=>{try{let r=JSON.parse(n.data);t&&t({type:`control`,data:r}),`type`in r&&r.type===`done`&&(c(),e())}catch{}}),o.addEventListener(`error`,e=>{try{let n=JSON.parse(e.data);t&&t({type:`error`,data:n})}catch{}}),o.onerror=e=>{c(),i(Error(`SSE connection failed for details stream`))}})}listChildren(e){return this.get(`/${e}/children`)}getChildDetails(e,t,n){let r={};return n?.includeHistory&&(r.include_history=`true`),n?.hydratePayloads&&(r.hydrate_payloads=`true`),this.get(`/${e}/children/${t}/details`,{query:r})}listArtifacts(e,t){let n=t?.visibility?{visibility:t.visibility}:void 0;return this.get(`/${e}/artifacts`,{query:n})}getArtifactUrl(e,t,n,r){let i={url:`1`};return n&&(i.disposition=n),r&&(i.filename=r),this.get(`/${e}/artifacts/${t}`,{query:i})}async uploadArtifact(e,t,n,r){let i=r||`application/octet-stream`,a=await this.put(`/${e}/artifacts/${t}`,{headers:{"Content-Type":i}}),o=await G(a.url,{method:`PUT`,body:n,headers:{"Content-Type":i}});if(!o.ok)throw Error(`Failed to upload artifact: ${o.statusText}`);return a}async downloadArtifact(e,t){let{url:n}=await this.getArtifactUrl(e,t,`attachment`),r=await G(n);if(!r.ok)throw Error(`Failed to download artifact: ${r.statusText}`);if(!r.body)throw Error(`No body in artifact download response`);return r.body}ingestEvents(e,t){let n={events:t};return this.post(`/${e}/events`,{payload:n})}getAnalyticsSummary(e={}){return this.post(`/analytics/summary`,{payload:e})}getTokenUsageAnalytics(e={}){return this.post(`/analytics/tokens`,{payload:e})}getLlmLatencyAnalytics(e={}){return this.post(`/analytics/latency/llm`,{payload:e})}getToolLatencyAnalytics(e={}){return this.post(`/analytics/latency/tools`,{payload:e})}getAgentLatencyAnalytics(e={}){return this.post(`/analytics/latency/agents`,{payload:e})}getErrorAnalytics(e={}){return this.post(`/analytics/errors`,{payload:e})}getToolAnalytics(e={}){return this.post(`/analytics/tools`,{payload:e})}getToolParameterAnalytics(e){return this.post(`/analytics/tools/parameters`,{payload:e})}getAnalyticsFilterOptions(e={}){return this.post(`/analytics/filter-options`,{payload:e})}getPromptSizeAnalytics(e={}){return this.post(`/analytics/prompt-size`,{payload:e})}getTopPrincipalsAnalytics(e={}){return this.post(`/analytics/top-principals`,{payload:e})}getRunsByAgentAnalytics(e={}){return this.post(`/analytics/runs-by-agent`,{payload:e})}getTimeToFirstResponseAnalytics(e={}){return this.post(`/analytics/time-to-first-response`,{payload:e})}getFirstResponseBehaviorAnalytics(e={}){return this.post(`/analytics/first-response-behavior`,{payload:e})}};function ut(e){return e.run_kind===`process`}var dt=class extends j{constructor(e){super(e,`/api/v1/collections`)}search(e){return this.post(`/search`,{payload:e})}computeListFacets(e){return this.post(`/facets`,{payload:e})}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}addMembers(e,t){return this.post(`/${e}/members`,{payload:{action:`add`,members:t}})}listMembers(e,t){return this.get(`/${e}/members`,{query:{...t}})}computeFacets(e,t){return this.post(`/${e}/facets`,{payload:t})}searchMembers(e,t){return this.post(`/${e}/search`,{payload:t})}deleteMembers(e,t){return this.post(`/${e}/members`,{payload:{action:`delete`,members:t}})}addChildren(e,t){return this.post(`/${e}/children`,{payload:{action:`add`,children:t}})}deleteChildren(e,t){return this.post(`/${e}/children`,{payload:{action:`delete`,children:t}})}searchChildren(e,t={}){return this.post(`/${e}/children/search`,{payload:t})}delete(e){return this.del(`/${e}`)}updatePermissions(e,t){return this.put(`/${e}/permissions`,{payload:t})}propagatePermissions(e){return this.post(`/${e}/propagate-permissions`)}propagateSharedProperties(e){return this.post(`/${e}/propagate-shared-props`)}},ft=class extends j{constructor(e){super(e,`/api/v1/cost`)}getAnalytics(e={}){return this.post(`/analytics`,{payload:e})}getGlobalAnalytics(e={}){return this.post(`/analytics/global`,{payload:e})}getModelPrices(e={}){return this.get(`/model-prices`,{query:{...e}})}getRunPrice(e){return this.post(`/run-price`,{payload:e})}getRunPriceComparison(e){return this.post(`/run-price`,{payload:{...e,include_comparison_pricing:!0}})}getExportUrl(e){let t=new URLSearchParams;e?.from&&t.set(`from`,typeof e.from==`number`?new Date(e.from).toISOString():e.from),e?.to&&t.set(`to`,typeof e.to==`number`?new Date(e.to).toISOString():e.to),e?.scope&&t.set(`scope`,e.scope),e?.project_id&&t.set(`project_id`,e.project_id),e?.workflow_id&&t.set(`workflow_id`,e.workflow_id);let n=t.toString();return`${this.baseUrl}/export${n?`?${n}`:``}`}},pt=class extends j{storeId;constructor(e,t){super(e,`/api/v1/data/${t}/dashboards`),this.storeId=t}storeHeaders(){return{[n.DATA_STORE_ID]:this.storeId}}list(e){let t=e?`?status=${e}`:``;return this.get(`/${t}`,{headers:this.storeHeaders()})}create(e){return this.post(`/`,{payload:e,headers:this.storeHeaders()})}retrieve(e){return this.get(`/${e}`,{headers:this.storeHeaders()})}update(e,t){return this.put(`/${e}`,{payload:t,headers:this.storeHeaders()})}delete(e){return this.del(`/${e}`,{headers:this.storeHeaders()})}bulkArchive(e){return this.post(`/bulk/archive`,{payload:{ids:e},headers:this.storeHeaders()})}bulkDelete(e){return this.post(`/bulk/delete`,{payload:{ids:e},headers:this.storeHeaders()})}listVersions(e,t){let n=new URLSearchParams;t?.snapshotsOnly&&n.set(`snapshots_only`,`true`),t?.limit&&n.set(`limit`,String(t.limit));let r=n.toString()?`?${n}`:``;return this.get(`/${e}/versions${r}`,{headers:this.storeHeaders()})}getVersion(e,t){return this.get(`/${e}/versions/${t}`,{headers:this.storeHeaders()})}createSnapshot(e,t){return this.post(`/${e}/versions`,{payload:t,headers:this.storeHeaders()})}promoteVersion(e,t,n){return this.post(`/${e}/versions/${t}/promote`,{payload:n||{},headers:this.storeHeaders()})}setVersioningEnabled(e,t){return this.put(`/${e}/versioning`,{payload:{enabled:t},headers:this.storeHeaders()})}},mt=class extends j{constructor(e){super(e,`/api/v1/data`)}storeHeaders(e){return{[n.DATA_STORE_ID]:e}}list(){return this.get(`/`)}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${e}`,{headers:this.storeHeaders(e)})}delete(e){return this.del(`/${e}`,{headers:this.storeHeaders(e)})}getSchema(e,t){let n=t?`?format=${t}`:``;return this.get(`/${e}/schema${n}`,{headers:this.storeHeaders(e)})}updateSchema(e,t){return this.put(`/${e}/schema`,{payload:t,headers:this.storeHeaders(e)})}getSchemaHistory(e){return this.get(`/${e}/schema/history`,{headers:this.storeHeaders(e)})}listTables(e){return this.get(`/${e}/tables`,{headers:this.storeHeaders(e)})}createTables(e,t){return this.post(`/${e}/tables`,{payload:t,headers:this.storeHeaders(e)})}getTable(e,t,n){let r=n?`?sample=true`:``;return this.get(`/${e}/tables/${t}${r}`,{headers:this.storeHeaders(e)})}alterTable(e,t,n){return this.put(`/${e}/tables/${t}`,{payload:n,headers:this.storeHeaders(e)})}dropTable(e,t){return this.del(`/${e}/tables/${t}`,{headers:this.storeHeaders(e)})}importData(e,t){return this.post(`/${e}/import`,{payload:t,headers:this.storeHeaders(e)})}getImportStatus(e,t){return this.get(`/${e}/import/${t}`,{headers:this.storeHeaders(e)})}listVersions(e,t){let n=t?`?snapshots_only=true`:``;return this.get(`/${e}/versions${n}`,{headers:this.storeHeaders(e)})}createSnapshot(e,t){return this.post(`/${e}/versions`,{payload:t,headers:this.storeHeaders(e)})}rollback(e,t){return this.post(`/${e}/versions/${t}/rollback`,{headers:this.storeHeaders(e)})}queryVersion(e,t,n){return this.post(`/${e}/versions/${t}/query`,{payload:n,headers:this.storeHeaders(e)})}query(e,t){return this.post(`/${e}/query`,{payload:t,headers:this.storeHeaders(e)})}queryBatch(e,t){return this.post(`/${e}/query/batch`,{payload:{queries:t},headers:this.storeHeaders(e)})}mutateRows(e,t){return this.post(`/${e}/mutate`,{payload:t,headers:this.storeHeaders(e)})}validateQueries(e,t){return this.post(`/${e}/query/validate`,{payload:{queries:t},headers:this.storeHeaders(e)})}getDownloadInfo(e,t){let n=t?`?version_id=${t}`:``;return this.get(`/${e}/download${n}`,{headers:this.storeHeaders(e)})}dashboards(e){return new pt(this.client,e)}},ht=class extends j{constructor(e){super(e,`/api/v1/email`)}send(e){return this.post(`/send`,{payload:e})}resolveRoute(e){return this.post(`/resolve-route`,{payload:{route_key:e}})}createRoute(e){return this.post(`/routes`,{payload:e})}getRoute(e){return this.get(`/routes/${e}`)}updateRoute(e,t){return this.put(`/routes/${e}`,{payload:t})}forwardEmail(e,t){return this.post(`/routes/${e}/forward`,{payload:t})}},gt=class extends j{constructor(e,t=`/api/v1/embeddings`){super(e,t)}async status(e){return this.get(`${e}/status`)}async activate(e,t){if(!t.environment)throw Error(`Invalid configuration: select environment`);return this.post(`${e}/enable`,{payload:t})}async disable(e){return this.post(`${e}/disable`)}async recalculate(e){return this.post(`${e}/recalculate`)}};function _t(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(r!=null)if(Array.isArray(r)){if(r.length===0)continue;t[n]=r.join(`,`)}else t[n]=String(r);return Object.keys(t).length?t:void 0}var vt=class extends j{constructor(e){super(e,`/api/v1/events/channels`)}list(e){return this.get(`/`,{query:_t(e)})}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}};function yt(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(r!=null)if(Array.isArray(r)){if(r.length===0)continue;t[n]=r.join(`,`)}else t[n]=String(r);return Object.keys(t).length?t:void 0}var bt=class extends j{constructor(e){super(e,`/api/v1/events/subscriptions`)}list(e){return this.get(`/`,{query:yt(e)})}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}},xt=class extends j{subscriptions;channels;constructor(e){super(e,`/api/v1/events`),this.subscriptions=new bt(e),this.channels=new vt(e)}searchDeliveries(e={}){return this.post(`/deliveries/search`,{payload:e})}queueSummary(e={}){return this.post(`/deliveries/queue-summary`,{payload:e})}},St=class extends g{constructor(e,t){super(`Resource not found: ${t.message}`,e,404,t.payload)}},K=class{stream;name;type;id;constructor(e,t,n,r){this.stream=e,this.name=t,this.type=n,this.id=r}};const Ct=`memories`,q=`agents`;function J(e){return`${Ct}/${e.endsWith(`.tar.gz`)?e:`${e}.tar.gz`}`}function Y(e,t){return`${q}/${e}/${t}`}var wt=class extends j{constructor(e){super(e,`/api/v1/files`)}async deleteFile(e,t){return this.del(`/${e}`,{query:{prefix:t}})}getMetadata(e){return this.get(`/metadata`,{query:{file:e}})}setFileMetadata(e,t){let n={file:e,metadata:t};return this.put(`/metadata`,{payload:n})}getOrCreateBucket(){return this.post(`/bucket`)}ensureBucketReadAccess(e){let t={principal:e};return this.post(`/bucket/read-access`,{payload:t})}getBucketReadAccessStatus(e){return this.get(`/bucket/read-access`,{query:{principal:e}})}list(e){return this.get(`/list`,{query:{prefix:e}})}getUploadUrl(e){return this.post(`/upload-url`,{payload:e})}getDownloadUrl(e,t,n){let r={file:e,name:t,disposition:n};return this.post(`/download-url`,{payload:r})}getDownloadUrlWithOptions(e){return this.post(`/download-url`,{payload:e})}bulkGetUploadUrls(e){return this.post(`/bulk-upload-urls`,{payload:e})}async bulkUpload(e,t=10){let n=e.map(e=>({name:e.name,mime_type:e.type,id:e instanceof K?e.id:void 0})),{files:r}=await this.bulkGetUploadUrls({files:n}),i=Array(e.length);for(let n=0;n<e.length;n+=t){let a=e.slice(n,n+t);await Promise.all(a.map(async(e,t)=>{let a=n+t,{url:o,id:s,mime_type:c}=r[a],l=e instanceof K,u=e.type||c,d=await G(o,{method:`PUT`,body:l?e.stream:e,headers:u?{"Content-Type":u}:void 0});if(!d.ok)throw Error(`Failed to upload file ${e.name}: ${d.statusText}`);let f=d.headers.get(`etag`)?.replace(/^"(.*)"$/,`$1`);i[a]={source:s,name:e.name,type:u,etag:f}}))}return i}async uploadFile(e){return(await this.uploadFileWithPath(e)).id}async uploadFileWithPath(e){let t=e instanceof K,{url:n,id:r,path:i}=await this.getUploadUrl(e),a=await G(n,{method:`PUT`,body:t?e.stream:e,headers:{"Content-Type":e.type||`application/gzip`}}).catch(e=>{throw console.error(`Failed to upload file`,{err:e,url:n,id:r,path:i}),e});if(!a.ok)throw console.log(a),Error(`Failed to upload file: ${a.statusText}`);return{id:r,path:i}}async downloadFile(e){let{url:t}=e.startsWith(`https:`)?{url:e}:await this.getDownloadUrl(e),n=await G(t,{method:`GET`}).then(n=>{if(n.ok)return n;throw n.status===404?Error(`File at ${t} not found`):n.status===403?Error(`File at ${t} is forbidden`):(console.log(n),Error(`Failed to download file ${e}: ${n.statusText}`))}).catch(t=>{throw console.error(`Failed to download file ${e}.`,t),t});if(!n.body)throw Error(`No body in response while downloading file ${e}`);return n.body}async copyFile(e,t){return(await this.post(`/copy`,{payload:{source:e,dest:t}})).dest}async uploadMemoryPack(e){let t=J(e.name),n=e.name.endsWith(`.tar.gz`)?e.name:`${e.name}.tar.gz`;if(e instanceof File){let r=e;return this.uploadFile(new K(r.stream(),n,r.type,t))}else return this.uploadFile(new K(e.stream,n,e.type,t))}async downloadMemoryPack(e,t=!1){let n=await this.downloadFile(J(e));if(t){let e=new DecompressionStream(`gzip`);n=n.pipeThrough(e)}return n}listByPrefix(e){return this.get(`/list`,{query:{prefix:e}})}async uploadArtifact(e,t,n){let r=Y(e,t);if(n instanceof File){let e=n;return this.uploadFile(new K(e.stream(),t,e.type,r))}else return this.uploadFile(new K(n.stream,t,n.type,r))}async downloadArtifact(e,t){let n=Y(e,t);return this.downloadFile(n)}getArtifactDownloadUrl(e,t,n){let r=Y(e,t);return this.getDownloadUrl(r,t,n)}async listArtifacts(e){let t=`${q}/${e}/`;return(await this.listByPrefix(t)).files}},Tt=class extends j{constructor(e){super(e,`/api/v1/hive-memory`)}list(e){let t=new URLSearchParams;e?.category&&t.set(`category`,e.category),e?.scope&&t.set(`scope`,e.scope),e?.limit&&t.set(`limit`,String(e.limit)),e?.offset&&t.set(`offset`,String(e.offset));let n=t.toString();return this.get(n?`/?${n}`:`/`)}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}search(e){return this.post(`/search`,{payload:e})}recall(e,t){return this.post(`/recall`,{payload:{task_description:e,tools:t?.tools,category:t?.category,max_results:t?.maxResults}})}getFormatted(e){return this.get(`/${e}/formatted`)}recordUsage(e){return this.post(`/${e}/usage`,{})}getByCategory(e,t){let n=new URLSearchParams;t?.limit&&n.set(`limit`,String(t.limit)),t?.offset&&n.set(`offset`,String(t.offset));let r=n.toString();return this.get(`/category/${e}${r?`?${r}`:``}`)}getStats(){return this.get(`/stats`)}applyDecay(e){return this.post(`/admin/decay`,{payload:{days_threshold:e?.daysThreshold,decay_rate:e?.decayRate}})}archiveLowConfidence(e){return this.post(`/admin/archive`,{payload:{threshold:e}})}},Et=class extends j{constructor(e,t=`/api/v1/indexing`){super(e,t)}async status(){return this.get(`/status`)}async reindex(e){return this.post(`/reindex`,{payload:e})}async reindexAgentRuns(e){return this.post(`/agent-runs/reindex`,{payload:e})}async analyzeDrift(){return this.post(`/analyze-drift`,{payload:{}})}async getDriftAnalysis(){return this.get(`/drift-analysis`)}async enableIndexing(){return this.post(`/enable-indexing`)}async disableIndexing(){return this.post(`/disable-indexing`)}async enableQueries(){return this.post(`/enable-queries`)}async disableQueries(){return this.post(`/disable-queries`)}index(e,t){return this.post(`/internal/index`,{payload:{object_id:e,document:t}})}delete(e){return this.post(`/internal/delete`,{payload:{object_id:e}})}bulkIndex(e,t){return this.post(`/internal/bulk-index`,{payload:{documents:e,target_index:t}})}ensureIndex(e){return this.post(`/internal/ensure-index`,{payload:{recreate:e}})}createReindexTarget(){return this.post(`/internal/create-reindex-target`,{payload:{}})}getStats(){return this.post(`/internal/stats`,{payload:{}})}fetchBatch(e,t){return this.post(`/internal/fetch-batch`,{payload:{cursor:e,limit:t}})}getNextIndexCursor(e,t,n){return this.post(`/internal/next-cursor`,{payload:{cursor:e,limit:t,count:n}})}analyzeDriftBatch(e,t){return this.post(`/internal/analyze-drift-batch`,{payload:{cursor:e,limit:t}})}triggerReindex(e){return this.post(`/internal/trigger-reindex`,{payload:e?{full_reindex:e.fullReindex,object_ids:e.objectIds,recreate_index:e.recreateIndex}:{}})}fetchDocumentsByIds(e){return this.post(`/internal/fetch-by-ids`,{payload:{object_ids:e}})}bulkDelete(e){return this.post(`/internal/bulk-delete`,{payload:{object_ids:e}})}getConfiguration(){return this.post(`/internal/configuration`,{payload:{}})}get zenoBulkBaseUrl(){let e=this.client.baseUrl;return e.includes(`localhost:`)||e.includes(`127.0.0.1:`)?`https://zeno-bulk-dev-main.api.dev1.vertesia.io`:e.includes(`zeno-server`)?e.replace(/zeno-server/,`zeno-bulk`):e}zenoBulkPost(e,t){return this.client.post(this.zenoBulkBaseUrl+e,{payload:t})}computeShards(e,t,n,r){return this.zenoBulkPost(`/reindex/compute-shards`,{tenant_id:e,shard_size:t??25e4,updated_since:n,backend:r})}indexShard(e){return this.zenoBulkPost(`/reindex/shard`,{params:e})}swapAlias(e,t,n,r){return this.zenoBulkPost(`/reindex/swap-alias`,{tenant_id:e,target_index:t,alias:n,backend:r})}async reindexViaBulk(e,t,n,r,i,a){let o=`${this.zenoBulkBaseUrl}/reindex`,s={tenant_id:e,project_id:i,dry_run:n??!1,backend:r,shard_size:a?.shardSize,shards:a?.shards,bulk_concurrency:a?.bulkConcurrency,bulk_size_bytes:a?.bulkSizeBytes,bulk_max_docs:a?.bulkMaxDocs};if(!t)return this.client.post(o,{payload:{params:s}});let c;if(await this.client.sseRequest(`POST`,o,{payload:{params:s}},e=>{if(t(e),e.type===`event`&&e.event===`done`)try{c=JSON.parse(e.data)}catch{}}),!c)throw Error(`zeno-bulk SSE stream ended without a done event`);return c}},Dt=class extends j{objectId;constructor(e,t){super(e,`/${t}/analyze`),this.objectId=t}async start(e){return this.post(`/`,{payload:e})}async getStatus(){return this.get(`/status`)}async getResults(){return this.get(`/results`)}async adaptTables(e){return this.post(`/adapt_tables`,{payload:e})}async getAdaptedTables(e,t){let n=e?`/adapt_tables/${e}`:`/adapt_tables`,r={};t?.format&&(r.format=t.format),t?.raw!==void 0&&(r.raw=t.raw);let i={query:r};return t?.format===`csv`&&(i.responseType=`text`),this.get(n,i)}async getXml(){return this.get(`/xml`)}async getTables(e){let t={};return e&&(t.query={format:e}),this.get(`/tables`,t)}async getImages(){return this.get(`/images`)}async getAnnotated(){return this.get(`/annotated`)}},Ot=class extends j{constructor(e){super(e,`/api/v1/objects`)}analyze(e){return new Dt(this,e)}getUploadUrl(e){return this.post(`/upload-url`,{payload:e})}getDownloadUrl(e,t,n){return this.post(`/download-url`,{payload:{file:e,name:t,disposition:n}})}getDownloadUrlWithOptions(e){return this.post(`/download-url`,{payload:e})}getContentSource(e){return this.get(`/${e}/content-source`)}list(e={}){let t=e.limit||100,n=e.offset||0,r=e.query||{};return this.get(`/`,{query:{limit:t,offset:n,select:e.select,...r,all_revisions:e.all_revisions,from_root:e.from_root||void 0}})}computeFacets(e){return this.post(`/facets`,{payload:e})}startExport(e={}){return this.post(`/export/bulk`,{payload:e})}listExports(){return this.get(`/export/bulk/artifacts`)}deleteExport(e){return this.del(`/export/bulk/artifacts/${encodeURIComponent(e)}`)}getExportStatus(e,t){return this.get(`/export/bulk/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}getExportDownloadUrl(e,t){return this.get(`/export/bulk/artifacts/${encodeURIComponent(e)}/${t}/download-url`)}async downloadExportFile(e,t){let{url:n}=await this.getExportDownloadUrl(e,t),r=await G(n,{method:`GET`}).then(e=>{if(!e.ok)throw Error(`Failed to download export file: ${e.status} ${e.statusText}`);return e});if(!r.body)throw Error(`No response body received when downloading export file`);return r.body}exportToBucketViaBulk(e,t=!1){return this.zenoBulkPost(`/export`,e,t)}planContentObjectExportViaBulk(e,t=!1){return this.zenoBulkPost(`/export/plan`,e,t)}exportContentObjectShardViaBulk(e,t=!1){return this.zenoBulkPost(`/export/shard`,e,t)}splitContentObjectExportShardViaBulk(e,t=!1){return this.zenoBulkPost(`/export/shard/split`,e,t)}composeContentObjectExportViaBulk(e,t=!1){return this.zenoBulkPost(`/export/compose`,e,t)}get zenoBulkBaseUrl(){let e=this.client.baseUrl;return e.includes(`localhost:`)||e.includes(`127.0.0.1:`)?`https://zeno-bulk-dev-main.api.dev1.vertesia.io`:e.includes(`zeno-server`)?e.replace(/zeno-server/,`zeno-bulk`):e}zenoBulkPost(e,t,n){return this.client.post(this.zenoBulkBaseUrl+e,{payload:t,timeoutMs:n})}listFolders(e=`/`){throw Error(`Not implemented yet`)}find(e){return this.post(`/find`,{payload:e})}count(e){return this.post(`/count`,{payload:e})}search(e){return this.post(`/search`,{payload:e})}retrieve(e,t){return this.get(`/${e}`,{query:{select:t}})}getObjectText(e){return this.get(`/${e}/text`)}async upload(e){let t=e instanceof K,{url:n,id:r,mime_type:i}=await this.getUploadUrl({id:t?e.id:void 0,name:e.name,mime_type:e.type}),a=e.type||i,o=await G(n,{method:`PUT`,body:t?e.stream:e,headers:a?{"Content-Type":a}:void 0}).catch(e=>{throw console.error(`Failed to upload file`,e),e});if(!o.ok)throw console.error(`Failed to upload file`,{status:o.status,statusText:o.statusText,url:n}),Error(`Failed to upload file: ${o.statusText}`);let s=o.headers.get(`etag`)?.replace(/^"(.*)"$/,`$1`);return{source:r,name:e.name,type:a,etag:s}}async create(e,n){let{content:r,...i}=e,a={...i};r instanceof K||r instanceof File?a.content=await this.upload(r):a.content=r;let o={};return n?.processing_priority&&(o[t.PROCESSING_PRIORITY]=n.processing_priority),n?.collection_id&&(o[t.COLLECTION_ID]=n.collection_id),await this.post(`/`,{payload:a,headers:o})}async createFromExternalSource(e,n={},r){let i=await this.client.files.getMetadata(e),a={...n,content:{source:e,name:i.name,type:i.contentType,etag:i.etag}},o={};return r?.processing_priority&&(o[t.PROCESSING_PRIORITY]=r.processing_priority),r?.collection_id&&(o[t.COLLECTION_ID]=r.collection_id),await this.post(`/`,{payload:a,headers:o})}async update(e,n,r){let{content:i,...a}=n,o={...a};i instanceof K||i instanceof File?o.content=await this.upload(i):o.content=i;let s={};return r?.ifMatch&&(s[`if-match`]=r.ifMatch),r?.processing_priority&&(s[t.PROCESSING_PRIORITY]=r.processing_priority),r?.createRevision&&(s[t.CREATE_REVISION]=`true`,r.revisionLabel&&(s[t.REVISION_LABEL]=r.revisionLabel)),r?.suppressWorkflows&&(s[t.SUPPRESS_WORKFLOWS]=`true`),this.put(`/${e}`,{payload:o,headers:s})}getRevisions(e){return this.get(`/${e}/revisions`)}getCollections(e){return this.get(`/${e}/collections`)}delete(e){return Array.isArray(e)?this.client.runOperation({name:`delete`,ids:e,params:{}}):this.del(`/${e}`)}bulkUpdate(e){let t=Object.keys(e);return this.client.runOperation({name:`update`,ids:t,params:e})}bulkCreate(e,t){return this.client.runOperation({name:`create`,ids:[],params:{objects:e,...t}})}listWorkflowRuns(e){return this.get(`/${e}/workflow-runs`)}listRenditions(e){return this.get(`/${e}/renditions`)}getRendition(e,t){let n={max_hw:t.max_hw,generate_if_missing:t.generate_if_missing,sign_url:t.sign_url,block_on_generation:t.block_on_generation};return this.get(`/${e}/renditions/${t.format}`,{query:n})}getRenditionSafe(e,t,n){return o(t,n.format)?this.getRendition(e,n):Promise.resolve(null)}exportProperties(e){return this.post(`/export`,{payload:e})}setEmbedding(e,t,n){return this.put(`/${e}/embeddings/${t}`,{payload:n})}},kt=class extends j{constructor(e){super(e,`/api/v1/pending-asks`)}register(e){return this.post(`/`,{payload:e})}resolve(e,t){return this.post(`/${e}/resolve`,{payload:t})}list(){return this.get(`/`)}retrieve(e){return this.get(`/${e}`)}},At=class extends j{constructor(e){super(e,`/api/v1/processes`)}list(e){let t={};return e?.status&&(t.status=e.status),e?.process&&(t.process=e.process),e?.limit!=null&&(t.limit=String(e.limit)),e?.offset!=null&&(t.offset=String(e.offset)),e?.allVersions&&(t.all_versions=`true`),this.get(`/`,{query:t})}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}listVersions(e){return this.get(`/${e}/versions`)}publish(e,t){return this.post(`/${e}/publish`,{payload:t})}revert(e,t){return this.post(`/${e}/revert`,{payload:t})}delete(e){return this.del(`/${e}`)}},jt=class extends j{constructor(e,t=`/api/v1/query`){super(e,t)}async execute(e){return this.post(`/`,{payload:e})}async sql(e){return this.execute({sql:e})}async esql(e){return this.execute({esql:e})}async dsl(e){return this.execute({dsl:e})}},Mt=class extends j{constructor(e){super(e,`/api/v1/rendering`)}start(e){return this.post(`/jobs`,{payload:e})}getStatus(e,t){return this.get(`/jobs/status`,{query:{workflow_id:e,workflow_run_id:t}})}async render(e,t={}){let n=t.pollIntervalMs??1500,r=t.timeoutMs??600*1e3,i=await this.start(e);if(!i.workflow_id||!i.workflow_run_id)throw Error(`Failed to start rendering workflow`);let o=Date.now();for(;;){let t=await this.getStatus(i.workflow_id,i.workflow_run_id);if(t.status===a.COMPLETED){if(!t.download_url&&!t.file_uri)throw Error(t.error||`Rendering completed but no output file was produced`);return{status:`success`,format:e.format,download_url:t.download_url,file_uri:t.file_uri}}if(l(t.status)){let e=a[t.status]||String(t.status);throw Error(t.error||`Rendering failed with status: ${e}`)}if(Date.now()-o>=r)throw Error(`Rendering timed out after ${r}ms`);await Nt(n)}}};function Nt(e){return new Promise(t=>setTimeout(t,e))}var Pt=class extends j{constructor(e){super(e,`/api/v1/schedules`)}list(){return this.get(`/`)}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}trigger(e){return this.post(`/${e}/trigger`,{})}pause(e,t){return this.post(`/${e}/pause`,{payload:{note:t}})}resume(e,t){return this.post(`/${e}/resume`,{payload:{note:t}})}},Ft=class extends j{constructor(e){super(e,`/api/v1/tasks`)}list(e){let t={};return e?.status&&(t.status=Array.isArray(e.status)?e.status.join(`,`):e.status),e?.assignee&&(t.assignee=e.assignee),e?.run_id&&(t.run_id=e.run_id),e?.source_type&&(t.source_type=e.source_type),e?.limit!=null&&(t.limit=String(e.limit)),e?.offset!=null&&(t.offset=String(e.offset)),this.get(`/`,{query:t})}retrieve(e){return this.get(`/${e}`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}complete(e,t){return this.post(`/${e}/complete`,{payload:t})}cancel(e){return this.post(`/${e}/cancel`,{})}delete(e){return this.del(`/${e}`)}},It=class extends j{constructor(e){super(e,`/api/v1/types/catalog`)}list(e={}){return this.get(`/`,{query:e})}listSysTypes(e){return this.get(`/sys`,{query:{tag:e}})}listAppTypes(e){return this.get(`/apps`,{query:{tag:e}})}listStoredTypes(e={}){return this.get(`/stored`,{query:e})}resolve(e){let t=typeof e==`string`?e:e.id;return this.get(`/resolve/${t}`)}},Lt=class extends j{catalog;constructor(e){super(e,`/api/v1/types`),this.catalog=new It(e)}list(e={},t){let n=e.limit||2e3,r=e.offset||0,i=e.query||{};return this.get(`/`,{query:{limit:n,offset:r,layout:!!t?.layout,schema:!!t?.schema,...i}})}find(e){return this.post(`/find`,{payload:e})}retrieve(e){return this.get(`/${e}`)}getTypeByName(e){return this.get(`/name/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}create(e){return this.post(`/`,{payload:e})}delete(e){return this.del(`/${e}`)}};const Rt=`20260319`,X=`x-api-version`;var zt=class extends j{constructor(e){super(e,`/api/v1/workflows`)}getActivityCatalog(){return this.get(`/activity-catalog`)}listRuns(e,t,n){return this.post(`/runs`,{payload:{documentId:e,eventName:t,ruleId:n}})}listConversations(e){return this.post(`/conversations`,{payload:e})}searchRuns(e){return this.post(`/runs`,{payload:e})}sendSignal(e,t,n,r){return this.post(`/runs/${e}/${t}/signal/${n}`,{payload:r})}getRunDetails(e,t,n){let r={};return n?.includeHistory!==void 0&&(r.include_history=n.includeHistory),n?.historyFormat!==void 0&&(r.history_format=n.historyFormat),n?.hydratePayloads!==void 0&&(r.hydrate_payloads=n.hydratePayloads),this.get(`/runs/${t}/${e}`,{query:r})}getRunInteraction(e,t){return this.get(`/runs/${e}/${t}/interaction`)}terminate(e,t,n){let r={reason:n};return this.post(`/runs/${e}/${t}/actions/terminate`,{payload:r})}cancel(e,t,n){let r={reason:n};return this.post(`/runs/${e}/${t}/actions/cancel`,{payload:r})}query(e,t,n){return this.get(`/runs/${e}/${t}/query/${n}`)}execute(e,t={}){return this.post(`/execute/${e}`,{payload:t})}postMessage(e,t){if(!e)throw Error(`runId is required`);return this.post(`/runs/${e}/updates`,{payload:t})}async retrieveMessages(e,t,n){let r={since:n};return(await this.get(`/runs/${e}/${t}/updates`,{query:r})).messages.map(e=>f(u(e),t))}async streamMessages(t,n,r,i,a){return new Promise((o,s)=>{let c=0,l=i||0,d=Date.now(),p=!1,m=null,h=null,g=null,_=null,v=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},y=()=>{g&&=(clearTimeout(g),null),h&&=(clearInterval(h),null),m&&=(m.close(),null),a&&_&&(a.removeEventListener(`abort`,_),_=null)},b=e=>{p||(p=!0,y(),o(e))};if(a){if(a.aborted){b(null);return}_=()=>b(null),a.addEventListener(`abort`,_,{once:!0})}let x=async(i=!1)=>{if(!p)try{let a=await N(),d=this.client,_=new URL(`${d.workflows.baseUrl}/runs/${t}/${n}/stream`);l>0&&_.searchParams.set(`since`,l.toString()),_.searchParams.set(`skipHistory`,`true`);let S=d._auth?await d._auth():void 0;if(p)return;if(!S){p=!0,y(),s(Error(`No auth token available`));return}let C=S.split(` `)[1];_.searchParams.set(`access_token`,C),i&&console.log(`Reconnecting to SSE stream for run ${n} (attempt ${c+1}/10)`);let w=new a(_.href);m=w,h=setInterval(()=>{},1e3),w.onopen=()=>{i&&console.log(`Successfully reconnected to SSE stream for run ${n}`),c=0},w.onmessage=t=>{if(!t.data||t.data.startsWith(`:`)){console.log(`Received comment or heartbeat; ignoring it.: `,t.data);return}try{let i=u(t.data);l=i.ts?Math.max(l,i.ts):Date.now(),r&&r(f(i,n),b),ct(i,n)?(console.log(`Closing stream due to COMPLETE message from main workstream`),p||(p=!0,y(),o(null))):i.t===e.COMPLETE&&console.log(`Received COMPLETE message that does not close the root stream for run ${n}`)}catch(e){console.error(`Failed to parse SSE message:`,e,t.data)}},w.onerror=e=>{if(!p)if(console.warn(`SSE stream error for run ${n}:`,e),y(),c<10){let e=v(c);console.log(`Attempting to reconnect in ${e}ms (attempt ${c+1}/10)`),c++,g=setTimeout(()=>{g=null,p||x(!0)},e)}else console.error(`Failed to reconnect to SSE stream for run ${n} after 10 attempts`),p=!0,s(Error(`SSE connection failed after 10 reconnection attempts`))}}catch(e){if(console.error(`Error setting up SSE stream:`,e),c<10){let e=v(c);c++,g=setTimeout(()=>{g=null,p||x(!0)},e)}else s(e)}};(async()=>{try{let e=await this.retrieveMessages(t,n,i),a=!1;for(let t=0;t<e.length;t++){let i=e[t];l=Math.max(l,i.timestamp||0),r&&r(i,b),a=t===e.length-1&&st(i,n)}if(a){b(null);return}}catch(e){console.warn(`Failed to fetch historical messages, continuing with SSE:`,e)}!p&&l<=0&&(l=Math.max(1,d-1)),x(!1)})().catch(s)})}async streamMessagesWS(t,n,r,i){return new Promise((a,o)=>{let s=0,c=null,l=i||0,d=!1,f=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},p=async()=>{if(!d)try{let i=this.client,m=new URL(`${i.workflows.baseUrl}/runs/${t}/${n}/ws`);m.protocol=m.protocol.replace(`http`,`ws`),l>0&&m.searchParams.set(`since`,l.toString());let h=i._auth?await i._auth():void 0;if(!h){o(Error(`No auth token available`));return}let g=h.split(` `)[1];m.searchParams.set(`access_token`,g),s>0&&console.log(`Reconnecting to WebSocket for run ${n} (attempt ${s+1}/10)`),c=new WebSocket(m.href),c.onopen=()=>{s>0&&console.log(`Successfully reconnected to WebSocket for run ${n}`),s=0,d||a({cleanup:()=>{d=!0,c&&=(c.close(),null)},sendSignal:(e,t)=>{if(c?.readyState===WebSocket.OPEN){let n={type:`signal`,signalName:e,data:t,requestId:Date.now()};c.send(JSON.stringify(n))}else console.warn(`WebSocket not open, cannot send signal`)}})},c.onmessage=t=>{try{let n=JSON.parse(t.data);if(`type`in n&&typeof n.type==`string`){if(n.type===`pong`){console.debug(`Received pong`);return}else if(n.type===`ack`){console.debug(`Signal acknowledged`,n);return}else if(n.type===`error`){console.error(`WebSocket error message`,n);return}}let i=u(n);l=i.ts?Math.max(l,i.ts):Date.now(),r&&r(i);let a=i.w||`main`;(i.t===e.TERMINATED||i.t===e.COMPLETE&&a===`main`)&&(console.log(`Closing WebSocket due to workflow completion`),d=!0,c&&=(c.close(),null))}catch(e){console.error(`Failed to parse WebSocket message`,e)}},c.onerror=e=>{console.error(`WebSocket error`,e)},c.onclose=()=>{if(!d&&s<10){let e=f(s);console.log(`WebSocket closed, reconnecting in ${e}ms (attempt ${s+1}/10)`),s++,setTimeout(p,e)}else s>=10&&o(Error(`WebSocket connection failed after 10 attempts`))}}catch(e){if(console.error(`Error setting up WebSocket`,e),s<10){let e=f(s);s++,setTimeout(p,e)}else o(e)}};p()})}ingestEvents(e,t,n){return this.post(`/runs/${e}/${t}/events`,{payload:{events:n}})}getAnalyticsSummary(e={}){return this.post(`/analytics/summary`,{payload:e})}getTokenUsageAnalytics(e={}){return this.post(`/analytics/tokens`,{payload:e})}getLlmLatencyAnalytics(e={}){return this.post(`/analytics/latency/llm`,{payload:e})}getToolLatencyAnalytics(e={}){return this.post(`/analytics/latency/tools`,{payload:e})}getAgentLatencyAnalytics(e={}){return this.post(`/analytics/latency/agents`,{payload:e})}getErrorAnalytics(e={}){return this.post(`/analytics/errors`,{payload:e})}getToolAnalytics(e={}){return this.post(`/analytics/tools`,{payload:e})}getToolParameterAnalytics(e){return this.post(`/analytics/tools/parameters`,{payload:e})}getAnalyticsFilterOptions(e={}){return this.post(`/analytics/filter-options`,{payload:e})}getPromptSizeAnalytics(e={}){return this.post(`/analytics/prompt-size`,{payload:e})}getTopPrincipalsAnalytics(e={}){return this.post(`/analytics/top-principals`,{payload:e})}getRunsByAgentAnalytics(e={}){return this.post(`/analytics/runs-by-agent`,{payload:e})}getTimeToFirstResponseAnalytics(e={}){return this.post(`/analytics/time-to-first-response`,{payload:e})}getFirstResponseBehaviorAnalytics(e={}){return this.post(`/analytics/first-response-behavior`,{payload:e})}rules=new Bt(this);definitions=new Vt(this)},Bt=class extends j{constructor(e){super(e,`/rules`)}list(){return this.get(`/`)}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}create(e){return this.post(`/`,{payload:e})}delete(e){return this.del(`/${e}`)}execute(e,t,n){let r={objectIds:t,vars:n};return this.post(`/${e}/execute`,{payload:r})}},Vt=class extends j{constructor(e){super(e,`/definitions`)}list(){return this.get(`/`)}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}create(e){return this.post(`/`,{payload:e})}delete(e){return this.del(`/${e}`)}};function Ht(e){if(!e)throw Error(`zeno client serverUrl is required`);return e}var Z=class extends A{constructor(e={}){super(Ht(e.serverUrl),e.fetch),e.apikey&&this.withApiKey(e.apikey),e.retryPolicy&&this.withRetryPolicy(e.retryPolicy),e.timeout!==void 0&&this.withTimeout(e.timeout),this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.errorFactory=e=>e.status===404?new St(e.request,e):e}withApiVersion(e){return e?this.headers[X]=String(e):delete this.headers[X],this}withApiKey(e){return this.withAuthCallback(e?()=>Promise.resolve(`Bearer ${e}`):void 0)}runOperation(e){return this.post(`/api/v1/operations`,{payload:e})}get initialHeaders(){return{...super.initialHeaders,[X]:Rt}}agents=new lt(this);cost=new ft(this);objects=new Ot(this);types=new Lt(this);workflows=new zt(this);schedules=new Pt(this);processes=new At(this);tasks=new Ft(this);files=new wt(this);collections=new dt(this);embeddings=new gt(this);email=new ht(this);events=new xt(this);eventSubscriptions=this.events.subscriptions;pendingAsks=new kt(this);data=new mt(this);indexing=new Et(this);query=new jt(this);hiveMemory=new Tt(this);rendering=new Mt(this)},Ut=class extends j{constructor(e){super(e,`/api/v1/tools`)}list(e){let t={};return e?.sources?.length&&(t.sources=e.sources.join(`,`)),e?.exclude?.length&&(t.exclude=e.exclude.join(`,`)),this.get(`/`,{query:Object.keys(t).length>0?t:void 0})}listBuiltins(){return this.list({sources:[`builtin`]})}validate(e){return this.post(`/validate`,{payload:{names:e}})}},Wt=class extends j{constructor(e){super(e,`/api/v1/training`)}listSessions(e={}){return this.get(`/`,{query:{...e}})}listSessionNames(e={}){return this.get(`/names`,{query:{...e}})}createSession(e){return this.post(`/`,{payload:e})}getSession(e){return this.get(`/${e}`)}addToSession(e,t){return this.post(`/${e}/add`,{payload:{runs:t}})}listSessionRuns(e,t=100,n=0){return this.get(`/${e}/runs`,{query:{limit:t,offset:n}})}buildSession(e){return this.post(`/${e}/build`)}getDataUrl(e){return this.get(`/${e}/url`)}getDataUploadUrl(e,t=!1){return this.get(`/${e}/upload-url`,t?{query:{resumable:`true`}}:{})}startTraining(e){return this.post(`/${e}/start`)}cancelTraining(e){return this.post(`/${e}/cancel`)}getTrainingJob(e){return this.get(`/job/${e}`)}getAndSyncTrainingJob(e){return this.get(`/job/${e}`,{query:{sync:`true`}})}setDataset(e,t=`default`){return this.post(`/${e}/dataset`,{payload:{dataset:t}})}},Gt=class extends j{constructor(e){super(e,`/api/v1/users`)}retrieve(e){return this.get(`/${e}`)}update(e,t){return this.put(`/${e}`,{payload:t})}delete(e){return this.del(`/${e}`)}},Q=class e extends A{_jwt=null;store;sessionTags;tokenServerUrl;oauthClients;oauthGrants;oauthServer;oauthProviders;remoteMcpConnections;secrets;internalSecrets;static async fromAuthToken(t,n,r){n||=$(t);let i=r||Zt(n.endpoints);return await new e({serverUrl:i.studio,storeUrl:i.store,tokenServerUrl:i.token||n.iss}).withApiKey(t)}static decodeEndpoints(){}constructor(e={site:`api.vertesia.io`}){let t,n;if(e.serverUrl)t=e.serverUrl;else if(e.site)t=`https://${e.site}`;else throw Error(`Parameter 'site' or 'serverUrl' is required for VertesiaClient`);if(e.storeUrl)n=e.storeUrl;else if(e.site)n=`https://${e.site}`;else throw Error(`Parameter 'site' or 'storeUrl' is required for VertesiaClient`);if(super(t,e.fetch),e.tokenServerUrl)this.tokenServerUrl=e.tokenServerUrl;else if(e.site){let t=e.site.replace(/^api/,`sts`);this.tokenServerUrl=`https://${t}`}else if(e.serverUrl||e.storeUrl){let t=e.serverUrl||e.storeUrl||``;try{let e=new URL(t);if(e.hostname.startsWith(`api`)){let t=e.hostname.replace(/^api/,`sts`);this.tokenServerUrl=`https://${t}`}else this.tokenServerUrl=`https://sts.dev1.vertesia.io`}catch{this.tokenServerUrl=`https://sts.dev1.vertesia.io`}}else this.tokenServerUrl=`https://sts.dev1.vertesia.io`;this.store=new Z({serverUrl:n,tokenServerUrl:this.tokenServerUrl,apikey:e.apikey,onRequest:e.onRequest,onResponse:e.onResponse,retryPolicy:e.retryPolicy,timeout:e.timeout,fetch:e.fetch}),e.retryPolicy&&this.withRetryPolicy(e.retryPolicy),e.timeout!==void 0&&this.withTimeout(e.timeout),e.apikey&&this.withApiKey(e.apikey),this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.sessionTags=e.sessionTags,this.oauthClients=new W(this),this.oauthGrants=new Be(this),this.oauthServer=new He(this,this.tokenServerUrl),this.oauthProviders=new Ve(this),this.remoteMcpConnections=new Je(this),this.secrets=new Xe(this),this.internalSecrets=new U(this)}withApiVersion(e){return e?this.headers[X]=String(e):delete this.headers[X],this}withAuthCallback(e){return this.store.withAuthCallback(e),super.withAuthCallback(e)}withRetryPolicy(e){return this.store.withRetryPolicy(e),super.withRetryPolicy(e)}withTimeout(e){return this.store.withTimeout(e),super.withTimeout(e)}async withApiKey(e){return this.withAuthCallback(e?async()=>{if(!Kt(e))return`Bearer ${e}`;if(qt(this._jwt)){let t=await this.getAuthToken(e);this._jwt=t.token}return`Bearer ${this._jwt}`}:void 0)}async getRawJWT(){if(!this._jwt&&this._auth){let e=await this._auth();this._jwt||=e.trim().split(` `)[1]}return this._jwt||null}async getDecodedJWT(){let e=await this.getRawJWT();return e?$(e):null}async getProject(){return(await this.getDecodedJWT())?.project||null}async getAccount(){return(await this.getDecodedJWT())?.account||null}get agents(){return this.store.agents}get workflows(){return this.store.workflows}get objects(){return this.store.objects}get files(){return this.store.files}get processes(){return this.store.processes}get tasks(){return this.store.tasks}get types(){return this.store.types}get data(){return this.store.data}get events(){return this.store.events}get storeUrl(){return this.store.baseUrl}async getAuthToken(e){return this.post(`${this.tokenServerUrl}/token/issue`,{headers:{"content-type":`application/json`,authorization:`Bearer ${e}`},retryPolicy:{attempts:4,methods:[`POST`],statuses:[429,500,502,503,504]}}).catch(e=>{throw console.error(`Error fetching token from ${this.tokenServerUrl}:`,{error:e}),e})}get initialHeaders(){return{...super.initialHeaders,[X]:Rt}}projects=new Ue(this);environments=new Oe(this);interactions=new Re(this);skills=new Ze(this);prompts=new Ge(this);runs=new Ye(this);account=new xe(this);accounts=new Se(this);apikeys=new we(this);analytics=new Ce(this);auditTrail=new Ee(this);training=new Wt(this);users=new Gt(this);iam=new Ae(this);refs=new qe(this);commands=new De(this);apps=new Te(this);tools=new Ut(this);quota=new Ke(this)};function Kt(e){return e.startsWith(`pk-`)||e.startsWith(`sk-`)}function qt(e){if(!e)return!0;let t=$(e).exp;return Date.now()>=t*1e3-6e4}function $(e){let t=e.split(`.`)[1],n=Xt(t);return JSON.parse(n)}function Jt(){return globalThis.Buffer}function Yt(){return globalThis.process?.env?.STS_URL}function Xt(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`),n=Jt();if(n)return n.from(t,`base64`).toString(`utf-8`);if(typeof atob<`u`&&typeof TextDecoder<`u`){let e=atob(t),n=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder().decode(n)}else throw Error(`No base64 decoder available`)}function Zt(e){return e?typeof e==`string`?Qt(e):e:Qt(`api.vertesia.io`)}function Qt(e){if(e===`local`)return{studio:`http://localhost:8091`,store:`http://localhost:8092`,token:Yt()??`https://sts.dev1.vertesia.io`};{let t=`https://${e}`;return{studio:t,store:t,token:t.replace(`api`,`sts`)}}}var $t=class{id;client;constructor(e,t){this.id=e,t instanceof Q?this.client=t:this.client=new Q(t)}retrieve(){return this.client.interactions.retrieve(this.id)}update(e){return this.client.interactions.update(this.id,e)}render(e){throw Error(`Not implemented`)}async execute(e={},t){return P(this.client,this.id,e,t)}};export{q as ARTIFACTS_PREFIX,lt as AgentsApi,mt as DataApi,ht as EmailApi,gt as EmbeddingsApi,vt as EventIngestChannelsApi,bt as EventSubscriptionsApi,xt as EventsApi,wt as FilesApi,Tt as HiveMemoryApi,I as IS_INTERACTION_OUTPUT,Et as IndexingApi,$t as InteractionBase,z as InteractionOutput,U as InternalSecretsApi,Ct as MEMORIES_PREFIX,W as OAuthClientsApi,Be as OAuthGrantsApi,Ve as OAuthProvidersApi,He as OAuthServerApi,Ot as ObjectsApi,kt as PendingAsksApi,i as Permission,At as ProcessApi,jt as QueryApi,Je as RemoteMcpConnectionsApi,Mt as RenderingApi,Pt as SchedulesApi,Xe as SecretsApi,K as StreamSource,Ft as TaskApi,It as TypeCatalogApi,Lt as TypesApi,Q as VertesiaClient,zt as WorkflowsApi,Vt as WorkflowsDefinitionApi,Bt as WorkflowsRulesApi,Z as ZenoClient,St as ZenoClientNotFoundError,o as canGenerateRendition,V as createInteractionOutput,Zt as decodeEndpoints,$ as decodeJWT,R as enhanceExecutionRun,L as enhanceInteractionExecutionResult,G as fetchSignedUrl,Y as getAgentArtifactPath,J as getMemoryFilePath,s as getOAuthPermissionScopes,c as getSupportedRenditionFormats,qt as isTokenExpired,d as supportsVisualRendition};
|
|
14
|
+
//# sourceMappingURL=vertesia-client.js.map
|