@vertesia/client 1.5.0-dev.20260807.073259Z → 1.5.0-dev.20260901.005903Z

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/lib/AppsApi.d.ts +9 -8
  2. package/lib/AppsApi.d.ts.map +1 -1
  3. package/lib/AppsApi.js +11 -4
  4. package/lib/AppsApi.js.map +1 -1
  5. package/lib/GroupsApi.d.ts +4 -11
  6. package/lib/GroupsApi.d.ts.map +1 -1
  7. package/lib/GroupsApi.js.map +1 -1
  8. package/lib/InteractionBase.d.ts +114 -0
  9. package/lib/InteractionBase.d.ts.map +1 -1
  10. package/lib/InteractionCatalogApi.d.ts +3 -3
  11. package/lib/InteractionCatalogApi.d.ts.map +1 -1
  12. package/lib/InteractionCatalogApi.js +1 -1
  13. package/lib/InteractionOutput.d.ts +13 -3
  14. package/lib/InteractionOutput.d.ts.map +1 -1
  15. package/lib/InteractionOutput.js +33 -3
  16. package/lib/InteractionOutput.js.map +1 -1
  17. package/lib/OAuthServerApi.d.ts +1 -1
  18. package/lib/OAuthServerApi.d.ts.map +1 -1
  19. package/lib/OAuthServerApi.js +9 -2
  20. package/lib/OAuthServerApi.js.map +1 -1
  21. package/lib/ProjectsApi.d.ts +3 -3
  22. package/lib/ProjectsApi.d.ts.map +1 -1
  23. package/lib/ProjectsApi.js.map +1 -1
  24. package/lib/RunsApi.d.ts +6 -28
  25. package/lib/RunsApi.d.ts.map +1 -1
  26. package/lib/RunsApi.js +3 -3
  27. package/lib/RunsApi.js.map +1 -1
  28. package/lib/ToolsApi.d.ts +2 -1
  29. package/lib/ToolsApi.d.ts.map +1 -1
  30. package/lib/ToolsApi.js +9 -0
  31. package/lib/ToolsApi.js.map +1 -1
  32. package/lib/ViewsApi.d.ts +1 -1
  33. package/lib/ViewsApi.js +1 -1
  34. package/lib/client.d.ts +1 -0
  35. package/lib/client.d.ts.map +1 -1
  36. package/lib/client.js +3 -0
  37. package/lib/client.js.map +1 -1
  38. package/lib/execute.js +2 -2
  39. package/lib/execute.js.map +1 -1
  40. package/lib/store/AgentsApi.d.ts +4 -1
  41. package/lib/store/AgentsApi.d.ts.map +1 -1
  42. package/lib/store/AgentsApi.js +6 -4
  43. package/lib/store/AgentsApi.js.map +1 -1
  44. package/lib/store/CollectionsApi.d.ts +5 -2
  45. package/lib/store/CollectionsApi.d.ts.map +1 -1
  46. package/lib/store/CollectionsApi.js.map +1 -1
  47. package/lib/store/EmailApi.d.ts +9 -107
  48. package/lib/store/EmailApi.d.ts.map +1 -1
  49. package/lib/store/EmailApi.js.map +1 -1
  50. package/lib/store/FilesApi.d.ts +3 -1
  51. package/lib/store/FilesApi.d.ts.map +1 -1
  52. package/lib/store/FilesApi.js +7 -0
  53. package/lib/store/FilesApi.js.map +1 -1
  54. package/lib/store/ObjectsApi.d.ts +29 -4
  55. package/lib/store/ObjectsApi.d.ts.map +1 -1
  56. package/lib/store/ObjectsApi.js +0 -2
  57. package/lib/store/ObjectsApi.js.map +1 -1
  58. package/lib/store/PendingAsksApi.d.ts +2 -53
  59. package/lib/store/PendingAsksApi.d.ts.map +1 -1
  60. package/lib/store/PendingAsksApi.js.map +1 -1
  61. package/lib/store/ProcessApi.d.ts +15 -8
  62. package/lib/store/ProcessApi.d.ts.map +1 -1
  63. package/lib/store/ProcessApi.js +27 -1
  64. package/lib/store/ProcessApi.js.map +1 -1
  65. package/lib/store/ProcessTestRunApi.d.ts +26 -0
  66. package/lib/store/ProcessTestRunApi.d.ts.map +1 -0
  67. package/lib/store/ProcessTestRunApi.js +36 -0
  68. package/lib/store/ProcessTestRunApi.js.map +1 -0
  69. package/lib/store/QueryApi.d.ts +9 -51
  70. package/lib/store/QueryApi.d.ts.map +1 -1
  71. package/lib/store/QueryApi.js.map +1 -1
  72. package/lib/store/WorkflowsApi.d.ts +3 -3
  73. package/lib/store/WorkflowsApi.d.ts.map +1 -1
  74. package/lib/store/WorkflowsApi.js.map +1 -1
  75. package/lib/store/client.d.ts +2 -2
  76. package/lib/store/client.d.ts.map +1 -1
  77. package/lib/store/client.js +2 -2
  78. package/lib/store/client.js.map +1 -1
  79. package/lib/store/index.d.ts +1 -1
  80. package/lib/store/index.d.ts.map +1 -1
  81. package/lib/store/index.js +1 -1
  82. package/lib/store/index.js.map +1 -1
  83. package/lib/store/stream-termination.d.ts +2 -2
  84. package/lib/store/stream-termination.d.ts.map +1 -1
  85. package/lib/store/stream-termination.js +6 -4
  86. package/lib/store/stream-termination.js.map +1 -1
  87. package/lib/vertesia-client.js +8 -9
  88. package/lib/vertesia-client.js.map +1 -1
  89. package/package.json +7 -7
  90. package/src/AppsApi.ts +22 -8
  91. package/src/GroupsApi.ts +4 -10
  92. package/src/InteractionCatalogApi.ts +3 -3
  93. package/src/InteractionOutput.test.ts +41 -5
  94. package/src/InteractionOutput.ts +39 -3
  95. package/src/OAuthServerApi.test.ts +56 -0
  96. package/src/OAuthServerApi.ts +12 -2
  97. package/src/ProjectsApi.ts +4 -2
  98. package/src/RunsApi.ts +15 -14
  99. package/src/ToolsApi.ts +10 -0
  100. package/src/ViewsApi.test.ts +3 -1
  101. package/src/ViewsApi.ts +1 -1
  102. package/src/client.ts +4 -0
  103. package/src/execute.ts +2 -2
  104. package/src/store/AgentsApi.stream.test.ts +56 -0
  105. package/src/store/AgentsApi.ts +8 -4
  106. package/src/store/CollectionsApi.ts +8 -1
  107. package/src/store/EmailApi.ts +25 -107
  108. package/src/store/FilesApi.ts +12 -0
  109. package/src/store/ObjectsApi.ts +28 -4
  110. package/src/store/PendingAsksApi.ts +15 -57
  111. package/src/store/ProcessApi.test.ts +24 -0
  112. package/src/store/ProcessApi.ts +49 -8
  113. package/src/store/ProcessTestRunApi.ts +41 -0
  114. package/src/store/QueryApi.ts +9 -45
  115. package/src/store/WorkflowsApi.ts +4 -3
  116. package/src/store/client.ts +2 -2
  117. package/src/store/index.ts +1 -1
  118. package/src/store/stream-termination.test.ts +24 -0
  119. package/src/store/stream-termination.ts +10 -4
  120. package/lib/store/HiveMemoryApi.d.ts +0 -161
  121. package/lib/store/HiveMemoryApi.d.ts.map +0 -1
  122. package/lib/store/HiveMemoryApi.js +0 -170
  123. package/lib/store/HiveMemoryApi.js.map +0 -1
  124. package/src/store/HiveMemoryApi.ts +0 -220
@@ -1,14 +1,13 @@
1
1
  import{APP_VERSION_HEADER as e,APP_VERSION_HEADER as t,AgentMessageType as n,CURRENT_API_VERSION_HEADER_VALUE as r,ContentObjectApiHeaders as i,DataStoreApiHeaders as a,ExecutionRunStatus as o,Permission as s,VERSION_HEADER as c,WorkflowExecutionStatus as l,canGenerateRendition as u,getOAuthPermissionScopes as d,getSupportedRenditionFormats as f,isWorkflowTerminalStatus as p,parseMessage as m,supportsVisualRendition as h,toAgentMessage as g}from"@vertesia/common";function _(e){return typeof e==`object`&&!!e}function v(e){if(_(e))return e.details?e.details:_(e.error)?e.error.details:void 0}function y(e,t,n,r,i){let a=e;if(i){a+=`\nRequest: ${t.method} ${t.url} => ${n}`;let e=v(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 b=class extends Error{status;payload;request;request_info;displayDetails;original_message;rateLimit;retryAfterMs;constructor(e,t,n,r,i=!0,a,o){super(y(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,this.rateLimit=a,this.retryAfterMs=o}get details(){return v(this.payload)}},x=class e extends b{constructor(e,t,n,r,i=!0,a,o){super(e,t,n,r,i,a,o)}updateDetails(t){if(t!==this.details){let n=_(this.payload)?{...this.payload,details:t}:{details:t};return new e(this.original_message,this.request,this.status,n,this.displayDetails,this.rateLimit,this.retryAfterMs)}else return this}},S=class extends b{constructor(e,t){super(`Failed to connect to server: ${t.message}`,e,0,t)}},C=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 w(e){}function T(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=w,onError:n=w,onRetry:r=w,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 C(`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(`
2
+ Stack Trace: `}return a}var b=class extends Error{status;payload;request;request_info;displayDetails;original_message;rateLimit;retryAfterMs;constructor(e,t,n,r,i=!0,a,o){super(y(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,this.rateLimit=a,this.retryAfterMs=o}get details(){return v(this.payload)}},x=class e extends b{constructor(e,t,n,r,i=!0,a,o){super(e,t,n,r,i,a,o)}updateDetails(t){if(t!==this.details){let n=_(this.payload)?{...this.payload,details:t}:{details:t};return new e(this.original_message,this.request,this.status,n,this.displayDetails,this.rateLimit,this.retryAfterMs)}return this}},S=class extends b{constructor(e,t){super(`Failed to connect to server: ${t.message}`,e,0,t)}},C=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 w(e){}function T(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=w,onError:n=w,onRetry:r=w,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1,m=!1,h=!1;function g(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)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(m||h)&&(e=_(e),!e))return;if(!o.length){let t=x(e);t!==``&&v(t),b();return}if(e.indexOf(`
3
+ `)===-1&&e.indexOf(`\r`)===-1){if(s<6&&!y(o.join(``)+e.slice(0,6-s))){o.length=0,s=0,m=!0;return}o.push(e),s+=e.length,b();return}o.push(e);let t=o.join(``);o.length=0,s=0,v(x(t)),b()}function _(e){if(e.length===0)return e;if(h)return h=!1,e.charCodeAt(0)===10?e.slice(1):e;let t=e.indexOf(`\r`),n=e.indexOf(`
4
+ `),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===13?(m=!1,h=!0,``):(m=!1,e.slice(r+(e.charCodeAt(r)===13&&e.charCodeAt(r+1)===10?2:1)))}function v(e){if(e){if(e.charCodeAt(e.length-1)===13){S(e,0,e.length-1),h=!0;return}if(y(e)){o.push(e),s=e.length;return}m=!0}}function y(e){let t=e.charCodeAt(0);return t===58&&!!i||t===100&&O(e,`data`)||t===101&&O(e,`event`)||t===105&&O(e,`id`)||t===114&&O(e,`retry`)}function b(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,m=!1,h=!1,n(new C(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function x(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
4
5
  `,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
6
  `,n);continue}let i=e.charCodeAt(n);if(E(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 D(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(`
7
+ `,n);continue}u=d===0?a:`${u}\n${a}`,d++}else D(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:S(e,n,r);n=r+1,r=e.indexOf(`
8
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){y();return}let r=e.charCodeAt(t);if(E(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(D(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){if(i){let r=e.slice(t,n);i(r.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 C(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new C(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(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:b}}function E(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 D(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 O=class extends TransformStream{constructor(){let e;super({start(t){e=T({onEvent(e){let n={type:`event`,...e};t.enqueue(n)}})},transform(t){e.feed(t)}})}};let k;if(globalThis.TextDecoderStream&&typeof globalThis.TextDecoderStream==`function`)k=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)}}k=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 k).pipeThrough(new O)}function A(e){let t=[];for(let n of Object.keys(e)){let r=e[n];if(r==null)continue;let i=encodeURIComponent(n);for(let e of Array.isArray(r)?r:[r])e!=null&&t.push(`${i}=${encodeURIComponent(String(e))}`)}return t.join(`&`)}function j(e,t){return e.endsWith(`/`)?t.startsWith(`/`)?e+t.substring(1):e+t:t.startsWith(`/`)?e+t:`${e}/${t}`}function M(e){return e[e.length-1]===`/`?e.slice(0,-1):e}const te=`x-ratelimit-reason`,ne=`x-ratelimit-retry-ms`;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 N(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 N(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 P(e){let t=e.headers.get(`x-retry-after-ms`);if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return e}let n=e.headers.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r)&&r>=0)return r*1e3;let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}function de(e,t){if(e.status!==429||e.headers.get(te)!==`pacing`)return;let n=e.headers.get(ne),r=n?Number(n):NaN,i=Number.isFinite(r)&&r>=0?r:P(e);if(!(i===void 0||i>t.maxWaitMs))return i}function fe(e){if(e.status!==429)return;let t=e.headers.get(te);if(t!==`pacing`&&t!==`quota`)return;let n=e.headers.get(ne),r=n?Number(n):NaN,i=Number.isFinite(r)&&r>=0?r:P(e);if(i!==void 0)return{reason:t,retryAfterMs:i,resource:e.headers.get(`x-ratelimit-resource`)??void 0,window:e.headers.get(`x-ratelimit-window`)??void 0}}function pe(e){return new Promise(t=>setTimeout(t,e))}function me(e,t,n){let r=(n?P(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 ye(e){try{await e.body?.cancel()}catch{}}var F=class{_fetch;baseUrl;errorFactory=e=>e;verboseErrors=!0;retryPolicy;pacingRetry;defaultTimeoutMs;constructor(e,t){this.baseUrl=M(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://`)?M(e):M(j(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`):N(n)&&n.message?r=String(n.message):N(n)&&n.error&&(typeof n.error==`string`?r=String(n.error):N(n.error)&&typeof n.error.message==`string`&&(r=n.error.message))),new x(r,e,t.status,n,this.verboseErrors,fe(t),P(t))}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+=`?${A(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 S(e,he(t)))),await this.waitBeforeRetry(d,h),h++;continue}if(this.handleFetchResponse(e,t),f&&g<f.attempts&&m){let e=de(t,f);if(e!==void 0){await ye(t),await pe(e),g++;continue}}if(d&&this.shouldRetryResponse(d,c,h,m,t)){await ye(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 S(_,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 be(e){return e?`authorization`in e:!1}function xe(){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 Se=class extends F{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 xe()&&(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&&!be(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)}},I=class extends F{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}},Ce=class extends I{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`)}},we=class extends I{constructor(e){super(e,`/api/v1/accounts`)}create(e){return this.post(`/`,{payload:{name:e}})}list(){return this.get(`/`)}},Te=class extends I{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}`:``}`)}},Ee=class extends I{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})}},De=class extends I{constructor(e){super(e,`/api/v1/apps`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}previewDelete(e){return this.del(`/${e}`)}setMcpCollectionApiKey(e,t,n){return this.put(`/${encodeURIComponent(e)}/collections/${encodeURIComponent(t)}/api-key`,{payload:{api_key:n}})}getMcpCollectionApiKeyStatus(e,t){return this.get(`/${encodeURIComponent(e)}/collections/${encodeURIComponent(t)}/api-key`)}deleteMcpCollectionApiKey(e,t){return this.del(`/${encodeURIComponent(e)}/collections/${encodeURIComponent(t)}/api-key`)}deleteApp(e){return this.del(`/${e}`,{query:{confirm:`true`}})}listVersions(e){return this.get(`/versions`,{query:{...e?.app_id&&{app_id:e.app_id},...e?.kind&&{kind:e.kind},...e?.include_expired!==void 0&&{include_expired:e.include_expired},...e?.limit!==void 0&&{limit:e.limit}}})}upsertVersion(e){return this.post(`/versions`,{payload:e})}getVersion(e){return this.get(`/versions/${e}`)}promoteVersion(e){return this.post(`/versions/${e}/promote`)}rebuildVersion(e){return this.post(`/versions/${e}/rebuild`)}deleteVersion(e){return this.del(`/versions/${e}`)}startBuild(e,t){return this.post(`/${encodeURIComponent(e)}/builds`,{payload:t})}getBuildProgress(e,t,n){return this.get(`/${encodeURIComponent(e)}/builds/${encodeURIComponent(t)}/${encodeURIComponent(n)}/progress`)}startScaffold(e){return this.post(`/scaffolds`,{payload:e})}getScaffoldProgress(e,t){return this.get(`/scaffolds/${encodeURIComponent(e)}/${encodeURIComponent(t)}/progress`)}listAppInstallationTools(e){return this.get(`/installations/${e}/tools`)}inspect(e){return this.get(`/${e}/inspect`)}getRepoTree(e,t){return this.get(`/${encodeURIComponent(e)}/repo/tree`,{query:{prefix:t?.prefix,ref:t?.ref}})}async getRepoFile(e,t,n){let r=`/${encodeURIComponent(e)}/repo/file`,i=await this.get(r,{query:{path:t,ref:n?.ref},reader:e=>e});if(!i.ok){let e=await this.readJSONPayload(i),t=await this.createRequest(i.url||this.getUrl(r),{method:`GET`});throw this.createServerError(t,i,e)}return i}commitRepoDocuments(e,t,n){let r=new FormData,i={ref:n.ref,expected_head:n.expectedHead,message:n.message||`Upload documentation`,files:t.map((e,t)=>({field:`file_${t}`,path:e.path}))};return r.append(`metadata`,JSON.stringify(i)),t.forEach((e,t)=>{r.append(`file_${t}`,e.content,e.fileName||e.path.split(`/`).pop()||`document`)}),this.post(`/${encodeURIComponent(e)}/repo/documents`,{payload:r,jsonPayload:!1,timeoutMs:12e4})}getRepoCommits(e,t,n){return this.get(`/${encodeURIComponent(e)}/repo/commits`,{query:{path:t,ref:n?.ref,limit:n?.limit,cursor:n?.cursor}})}getRepoRefs(e){return this.get(`/${encodeURIComponent(e)}/repo/refs`)}listDevelopmentTasks(e){return this.get(`/${encodeURIComponent(e)}/development-tasks`)}getDevelopmentTask(e,t){return this.get(`/${encodeURIComponent(e)}/development-tasks/${encodeURIComponent(t)}`)}createRepoBranch(e,t){return this.post(`/${encodeURIComponent(e)}/repo/branches`,{payload:t})}getAppPackage(e,t=`all`){return this.get(`/${encodeURIComponent(e)}/package`,{query:{scope:Array.isArray(t)?t.join(`,`):t}})}getAppInstallationPackage(e,t=`all`){return this.get(`/installations/${e}/package`,{query:{scope:Array.isArray(t)?t.join(`,`):t}})}getSystemToolsPackage(e=`tools`){return this.get(`/studio-tools/package`,{query:{scope:e}})}list(){return this.get(`/`)}install(e,t,n,r,i){return this.post(`/install`,{payload:{app_id:e,settings:t,oauth_params:n,oauth_provider_params:r,api_key_params:i}})}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}})}},Oe=class extends I{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}`:``}`)}aggregate(e){return this.post(`/aggregate`,{payload:e})}},ke=class extends I{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`)}},Ae=class extends I{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})}},je=class extends I{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`)}},Me=class extends I{constructor(e){super(e,`/api/v1/iam`)}aces=new Pe(this);roles=new Ne(this);groups=new je(this);getPrincipalIdentity(){return this.get(`/users/identity`)}},Ne=class extends I{constructor(e){super(e,`/roles`)}list(){return this.get(`/`)}listSystem(){return this.get(`/system`)}},Pe=class extends I{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 Fe=(()=>{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 L(){return typeof globalThis.EventSource==`function`?globalThis.EventSource:(await import(`eventsource`)).EventSource}async function Ie(e,t,n={},r){let i=!!r,a=await e.runs.create({...n,interaction:t,stream:i},{timeoutMs:i?void 0:Fe});if(i){if(a.status===o.failed)return a;await Re(e,a.id,r)}return a}async function Le(e,t,n={},r){let i=!!r,a=await e.post(`/api/v1/execute`,{payload:{...n,interaction:t,stream:i},timeoutMs:i?void 0:Fe});if(i){if(a.status===o.failed)return a;await Re(e,a.id,r)}return a}function Re(e,t,n){return new Promise((r,i)=>{(async()=>{try{let a=await L(),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 ze(e,t){return await e.post(`/api/v1/execute/async`,{payload:t})}async function Be(e,t){return await e.post(`/api/v1/execute/rate-limit/request`,{payload:t})}var Ve=class extends I{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 R=Symbol(`InteractionOutput`);function z(e){return e.result=V.from(e.result),e}function B(e){return e.result=V.from(e.result),e}var V=class{results;constructor(e){this.results=e}static from(e){return e?He(e)?e:H(Array.isArray(e)?e:typeof e==`object`?[{type:`json`,value:e}]:[{type:`text`,value:String(e)}]):H([])}static isInteractionOutputArray(e){return He(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:Ue(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 He(e){return!!e&&typeof e==`object`&&e[R]===!0}function H(e){let t=new V(e);return new Proxy(e,{get(e,n,r){if(n===R)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 Ue(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 We(e){return!!e&&typeof e==`object`&&`id`in e&&typeof e.id==`string`}var Ge=class extends I{catalog;constructor(e){super(e,`/api/v1/interactions`),this.catalog=new Ve(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 z(await Ie(this.client,e,t,n).catch(e=>{throw e instanceof x&&We(e.payload)?e.updateDetails({run_id:e.payload.id}):e}))}async executeByName(e,t={},n){return z(await Le(this.client,e,t,n).catch(e=>{throw e instanceof x&&We(e.payload)?e.updateDetails({run_id:e.payload.id}):e}))}executeAsync(e){return ze(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 Be(this.client,e)}resolve(e,t){return this.get(`/resolve/${encodeURIComponent(e)}`,{query:t})}},Ke=class extends I{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})}},qe=class extends I{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 Je(e){if(e)return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>[e,String(t)]))}var Ye=class extends I{constructor(e){super(e,`/api/v1/oauth-grants`)}list(e){return this.get(`/`,{query:Je(e)})}retrieve(e){return this.get(`/${e}`)}revoke(e,t){return this.del(`/${e}`,{query:t})}revokeBulk(e){return this.post(`/revoke`,{payload:e})}},Xe=class extends I{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`)}},Ze=class extends F{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:{}})}},Qe=class extends I{integrations;constructor(e){super(e,`/api/v1/projects`),this.integrations=new $e(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(`/${encodeURIComponent(e)}/app-types`,{query:{tag:t}})}getAppContentType(e,t){return this.get(`/${encodeURIComponent(e)}/app-types/${encodeURIComponent(t)}`)}listAppProcesses(e,t){return this.get(`/${encodeURIComponent(e)}/app-processes`,{query:{tag:t}})}getAppProcess(e,t){return this.get(`/${encodeURIComponent(e)}/app-processes/${encodeURIComponent(t)}`)}listAppViews(e,t){return this.get(`/${encodeURIComponent(e)}/app-views`,{query:{tag:t}})}getAppView(e,t){return this.get(`/${encodeURIComponent(e)}/app-views/${encodeURIComponent(t)}`)}listAppRenderingTemplates(e,t){return this.get(`/${encodeURIComponent(e)}/app-templates`,{query:{tag:t}})}getAppRenderingTemplate(e,t){return this.get(`/${encodeURIComponent(e)}/app-templates/${encodeURIComponent(t)}`)}getCompositeAppConfiguration(e){return this.get(`/${encodeURIComponent(e)}/composite-app`)}updateCompositeAppConfiguration(e,t){return this.put(`/${encodeURIComponent(e)}/composite-app`,{payload:t})}},$e=class extends I{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`)}},et=class extends I{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`)}},tt=class extends I{constructor(e){super(e,`/api/v1/quota`)}standing(){return this.get(`/standing`)}tier(){return this.get(`/tier`)}},nt=class extends I{constructor(e){super(e,`/api/v1/refs`)}resolve(e){return this.post(`/resolve`,{payload:{refs:e}})}},rt=class extends I{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}})}},it=class extends I{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 B(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 B(await this.post(`/`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal}))}sendToolResults(e,t){return this.post(`/tool-results`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal})}sendUserMessage(e,t){return this.post(`/user-message`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal})}computeFacets(e){return this.post(`/facets`,{payload:e})}search(e){return this.post(`/search`,{payload:e})}clone(e){return this.post(`/clone`,{payload:e})}},at=class extends I{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})}},ot=class extends I{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 st=new Set([429,500,502,503,504]);function ct(e){return new Promise(t=>setTimeout(t,e))}function lt(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 ut(e,t,n,r){let i=r?lt(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 dt=new TextEncoder;function ft(e){if(typeof e==`string`)return dt.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 pt(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(ft(r))}}catch(e){throw await t.cancel(e).catch(()=>void 0),e}finally{t.releaseLock()}return new Blob(n)}return e}}async function U(e,t={}){let{method:n=`GET`,headers:r,attempts:i=4,baseDelayMs:a=500,maxDelayMs:o=8e3,retryableStatuses:s=st}=t,c=await pt(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 ct(ut(t,a,o,i))}catch(e){if(l=e,u)throw e;await ct(ut(t,a,o))}}throw l instanceof Error?l:Error(`Failed to fetch signed URL: ${e}`)}function mt(e){if(!e||typeof e!=`object`)return;let t=e.process_run_id;return typeof t==`string`?t:void 0}function ht(e,t){let n=mt(e);return!n||n===t}function W(e,t){return e.type===n.TERMINATED||e.type===n.COMPLETE&&(e.workstream_id??`main`)===`main`?ht(e.details,t):!1}function gt(e,t){return e.t===n.TERMINATED||e.t===n.COMPLETE&&(e.w??`main`)===`main`?ht(e.d,t):!1}var _t=class extends I{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(vt)}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),e?.until&&(t.until=e.until),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),e?.until&&(t.until=e.until),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=>g(m(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,u=Date.now(),d=!1,f=null,p=null,h=null,_=null,v=null,y=!1,b=0,x=null,S=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},C=()=>{y=!1,_&&=(clearTimeout(_),null),v&&=(clearTimeout(v),null)},w=()=>{h&&=(clearTimeout(h),null),C(),p&&=(clearInterval(p),null),f&&=(f.close(),null),r&&x&&(r.removeEventListener(`abort`,x),x=null)},T=e=>{d||(d=!0,w(),a(e))},E=e=>typeof e==`string`&&[`completed`,`failed`,`cancelled`].includes(e),D=(t,n)=>{b++,console.warn(`Agent stream ${e}: ${t} failed while polling (consecutive failures: ${b}); retrying in 5s:`,n instanceof Error?n.message:n)},O=async()=>{if(d||!y)return;let n=!1;try{let r=await this.retrieveMessages(e,l||void 0);n=!0;for(let n of r){if(d)return;let r=n.timestamp||0;if(!(r<=l)){if(l=r,t&&t(n,T),d)return;if(W(n,e)){T(null);return}}}}catch(e){D(`GET /updates`,e)}if(!(d||!y)){try{let t=await this.get(`/${e}`);if(E(t?.status)){T(null);return}n&&(b=0)}catch(e){D(`run status check`,e)}d||!y||(_=setTimeout(()=>{_=null,O()},5e3))}},k=()=>{v=null,!(d||!y)&&(C(),c=0,console.log(`Agent stream ${e}: retrying the SSE connection after the polling fallback.`),j(`resume`))},ee=t=>{d||y||(w(),y=!0,b=0,console.warn(`Agent stream ${e}: SSE unavailable after 10 attempts; falling back to GET /updates polling every 5s (SSE retried every 60s).`,t instanceof Error?t.message:t),v=setTimeout(k,6e4),O())},A=e=>{if(d)return;if(c>=10){ee(e);return}let t=S(c);c++,h=setTimeout(()=>{h=null,d||j(`reconnect`)},t)};if(r){if(r.aborted)return d=!0,w(),a(null),s;x=()=>{T(null)},r.addEventListener(`abort`,x,{once:!0})}try{if(!d){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(d||(l=Math.max(l,i.timestamp||0),t&&t(i,T),d))break;a=n===r.length-1&&W(i,e)}if(a)return T(null),s}}catch(e){d||(i?.onHistoryError?.(e),console.warn(`Failed to fetch historical messages, continuing with SSE:`,e))}!d&&l<=0&&(l=Math.max(1,u-1));let j=async(n=`initial`)=>{if(!d)try{let r=await L();if(d)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(d)return;if(!s){d=!0,w(),o(Error(`No auth token available`));return}let u=s.split(` `)[1];if(a.searchParams.set(`access_token`,u),n===`reconnect`&&console.log(`Reconnecting to agent stream ${e} (attempt ${c}/10)`),d)return;let h=new r(a.href);f=h,p=setInterval(()=>{},1e3);let _=0;h.onopen=()=>{n!==`initial`&&console.log(`Reconnected to agent stream ${e}`),_=Date.now()},h.onmessage=n=>{if(!d&&!(!n.data||n.data.startsWith(`:`)))try{let r=m(n.data);l=r.ts?Math.max(l,r.ts):Date.now(),t&&t(g(r,e),T),gt(r,e)&&T(null)}catch(e){console.error(`Failed to parse SSE message:`,e,n.data)}},h.onerror=e=>{d||(w(),(_?Date.now()-_:0)>5e3&&(c=0),A(Error(`SSE connection failed after 10 reconnection attempts`)))}}catch(e){if(d)return;A(e)}};return j(`initial`),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 L(),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})}getArtifactContent(e,t){return this.get(`/${e}/artifact-content/${t}`)}updateArtifactContent(e,t,n){return this.put(`/${e}/artifact-content/${t}`,{payload: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 U(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 U(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 vt(e){return e.run_kind===`process`}var yt=class extends I{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`)}},bt=class extends I{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}`:``}`}},xt=class extends I{storeId;constructor(e,t){super(e,`/api/v1/data/${t}/dashboards`),this.storeId=t}storeHeaders(){return{[a.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()})}},St=class extends I{constructor(e){super(e,`/api/v1/data`)}storeHeaders(e){return{[a.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 xt(this.client,e)}},Ct=class extends I{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})}},wt=class extends I{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 Tt(e){return JSON.parse(e)}function Et(e,t,n){let r=Math.min(t*2**e,n);return r+Math.random()*.1*r}function Dt(e,t){if(!t)return;let n=t.startsWith(`Bearer `)?t.slice(7):t;e.searchParams.set(`access_token`,n)}async function Ot(e){let t=typeof e==`function`?await e():e;return t instanceof URL?new URL(t.href):new URL(t)}function kt(e){let t=e.event_types?.length?e.event_types:[`message`],n=e.max_reconnect_attempts??10,r=e.base_reconnect_delay_ms??1e3,i=e.max_reconnect_delay_ms??3e4,a=e.parse??Tt,o=!1,s=0,c=null,l=null,u=null,d=0,f,p=t=>{e.on_status?.(t)},m=()=>{c&&=(c.close(),null),l&&=(clearTimeout(l),null)},h=()=>{o||(o=!0,m(),e.signal&&u&&(e.signal.removeEventListener(`abort`,u),u=null),p(`closed`))},g=t=>{if(o)return;if(m(),(d?Date.now()-d:0)>5e3&&(s=0),s>=n){h(),e.on_error?.(t);return}let a=Et(s,r,i);s+=1,p(`reconnecting`),l=setTimeout(()=>{l=null,v(!0)},a)},_=(t,n)=>{if(!(o||!n.data||String(n.data).startsWith(`:`)))try{let r=a(String(n.data),t),i=e.get_cursor?.(r);f=n.lastEventId||i||f,e.on_event({data:r,event_type:t,event_id:n.lastEventId||i})}catch(t){e.on_error?.(t)}},v=async n=>{if(!o)try{p(n?`reconnecting`:`connecting`);let r=await L();if(o)return;let i=await Ot(e.url);if(f&&e.last_event_id_query_param&&!i.searchParams.has(e.last_event_id_query_param)&&i.searchParams.set(e.last_event_id_query_param,f),Dt(i,await e.get_access_token?.()),o)return;let a=new r(i.href);c=a,d=0,a.onopen=()=>{d=Date.now(),p(`open`)};for(let e of t)a.addEventListener(e,t=>_(e,t));a.onerror=e=>{g(e)}}catch(e){g(e)}};if(e.signal){if(e.signal.aborted)return o=!0,p(`closed`),{get closed(){return o},close:h};u=h,e.signal.addEventListener(`abort`,u,{once:!0})}return v(!1),{get closed(){return o},close:h}}function At(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 jt=class extends I{constructor(e){super(e,`/api/v1/events/channels`)}list(e){return this.get(`/`,{query:At(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 Mt(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 Nt=class extends I{constructor(e){super(e,`/api/v1/events/subscriptions`)}list(e){return this.get(`/`,{query:Mt(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}`)}},Pt=class extends I{subscriptions;channels;constructor(e){super(e,`/api/v1/events`),this.subscriptions=new Nt(e),this.channels=new jt(e)}searchDeliveries(e={}){return this.post(`/deliveries/search`,{payload:e})}queueSummary(e={}){return this.post(`/deliveries/queue-summary`,{payload:e})}cancelQueuedDeliveries(e={}){return this.post(`/deliveries/cancel`,{payload:e})}subscribeDeliveries(e){let{signal:t,max_reconnect_attempts:n,on_snapshot:r,on_delivery:i,on_envelope:a,on_error:o,on_status:s,...c}=e;return kt({url:()=>this.buildStreamUrl(c),event_types:[`snapshot`,`event`,`heartbeat`,`error`],signal:t,max_reconnect_attempts:n,last_event_id_query_param:`since_event_id`,get_access_token:async()=>{let e=this.client;return e._auth?await e._auth():void 0},get_cursor:e=>e.cursor,on_status:s,on_error:o,on_event:({data:e})=>{a?.(e),e.type===`snapshot`?r?.(e.deliveries,e):e.type===`event`?i?.(e.item,e):e.type===`error`&&o?.(Error(e.error))}})}buildStreamUrl(e){let t=new URL(`${this.baseUrl}/stream`);return this.setStreamParam(t,`limit`,e.limit),this.setStreamParam(t,`event_id`,e.event_id),this.setStreamParam(t,`resource_id`,e.resource_id),this.setStreamListParam(t,`resource_type`,e.resource_type),this.setStreamListParam(t,`event_category`,e.event_category),this.setStreamListParam(t,`action`,e.action),this.setStreamListParam(t,`outbox_status`,e.outbox_status),this.setStreamParam(t,`since_event_id`,e.since_event_id),this.setStreamParam(t,`since_created_at`,e.since_created_at),this.setStreamParam(t,`include_event`,e.include_event),this.setStreamParam(t,`poll_interval_ms`,e.poll_interval_ms),t}setStreamParam(e,t,n){n!=null&&n!==``&&e.searchParams.set(t,String(n))}setStreamListParam(e,t,n){n?.length&&e.searchParams.set(t,n.join(`,`))}},Ft=class extends b{constructor(e,t){super(`Resource not found: ${t.message}`,e,404,t.payload)}},G=class{stream;name;type;id;constructor(e,t,n,r){this.stream=e,this.name=t,this.type=n,this.id=r}};function It(e){return e?.split(`;`,1)[0]?.trim().toLowerCase()||void 0}function K(e){return It(e)===`application/octet-stream`?void 0:e||void 0}function q(e,t){return K(e)||t||e||void 0}const Lt=`memories`,J=`agents`,Rt={attempts:3,methods:[`POST`],statuses:[502,503,504]};function zt(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e.split(/[?#]/,1)[0]||`unknown file`}}function Bt(e){if(!(e instanceof Error))return;let t=e.message.replace(/https?:\/\/[^\s)\]}>"']+/g,e=>zt(e)),n=Error(t);return n.name=e.name,n}function Vt(e,t){return e===404?`not found`:e===403?`forbidden`:e?`failed with status ${e}${t?` ${t}`:``}`:`failed`}var Y=class extends Error{status;constructor(e,t,n,r){let i=zt(e),a=Vt(t,n);super(`File download ${a}: ${i}`,{cause:Bt(r)}),this.name=`FileDownloadError`,this.status=t}};function X(e){let t=e.endsWith(`.tar.gz`)?e:`${e}.tar.gz`;return`${Lt}/${t}`}function Z(e,t){return`${J}/${e}/${t}`}var Ht=class extends I{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,retryPolicy:Rt})}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:K(e.type),id:e instanceof G?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 G,u=q(e.type,c),d=await U(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 G,{url:n,id:r,path:i,mime_type:a}=await this.getUploadUrl({id:t?e.id:void 0,name:e.name,mime_type:K(e.type)}),o=q(e.type,a)||`application/gzip`,s=await U(n,{method:`PUT`,body:t?e.stream:e,headers:{"Content-Type":o}}).catch(e=>{throw console.error(`Failed to upload file`,{err:e,url:n,id:r,path:i}),e});if(!s.ok)throw console.log(s),Error(`Failed to upload file: ${s.statusText}`);return{id:r,path:i}}async downloadFile(e){let{url:t}=e.startsWith(`https:`)?{url:e}:await this.getDownloadUrl(e),n;try{n=await U(t,{method:`GET`})}catch(t){throw new Y(e,void 0,void 0,t)}if(!n.ok)throw new Y(e,n.status,n.statusText);if(!n.body)throw new Y(e);return n.body}async copyFile(e,t){return(await this.post(`/copy`,{payload:{source:e,dest:t}})).dest}async uploadMemoryPack(e){let t=X(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 G(r.stream(),n,r.type,t))}else return this.uploadFile(new G(e.stream,n,e.type,t))}async downloadMemoryPack(e,t=!1){let n=await this.downloadFile(X(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=Z(e,t);if(n instanceof File){let e=n;return this.uploadFile(new G(e.stream(),t,e.type,r))}else return this.uploadFile(new G(n.stream,t,n.type,r))}async downloadArtifact(e,t){let n=Z(e,t);return this.downloadFile(n)}getArtifactDownloadUrl(e,t,n){let r=Z(e,t);return this.getDownloadUrl(r,t,n)}async listArtifacts(e){let t=`${J}/${e}/`;return(await this.listByPrefix(t)).files}},Ut=class extends I{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}})}},Wt=class extends I{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}},Gt=class extends I{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 startGroundedExtraction(e){return this.post(`/grounded`,{payload:e??{}})}async getGroundedExtractionResult(){return this.get(`/grounded/result`)}async startGroundedAssistant(e){return this.post(`/grounded/assistant`,{payload:e??{}})}},Kt=class extends I{constructor(e){super(e,`/api/v1/objects`)}analyze(e){return new Gt(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 U(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 G,{url:n,id:r,mime_type:i}=await this.getUploadUrl({id:t?e.id:void 0,name:e.name,mime_type:K(e.type)}),a=q(e.type,i),o=await U(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,t){let{content:n,...r}=e,a={...r};n instanceof G||n instanceof File?a.content=await this.upload(n):a.content=n;let o={};return t?.processing_priority&&(o[i.PROCESSING_PRIORITY]=t.processing_priority),t?.collection_id&&(o[i.COLLECTION_ID]=t.collection_id),await this.post(`/`,{payload:a,headers:o})}async createFromExternalSource(e,t={},n){let r=await this.client.files.getMetadata(e),a={...t,content:{source:e,name:r.name,type:r.contentType,etag:r.etag}},o={};return n?.processing_priority&&(o[i.PROCESSING_PRIORITY]=n.processing_priority),n?.collection_id&&(o[i.COLLECTION_ID]=n.collection_id),await this.post(`/`,{payload:a,headers:o})}async update(e,t,n){let{content:r,...a}=t,o={...a};r instanceof G||r instanceof File?o.content=await this.upload(r):o.content=r;let s={};return n?.ifMatch&&(s[`if-match`]=n.ifMatch),n?.processing_priority&&(s[i.PROCESSING_PRIORITY]=n.processing_priority),n?.createRevision&&(s[i.CREATE_REVISION]=`true`,n.revisionLabel&&(s[i.REVISION_LABEL]=n.revisionLabel)),n?.suppressWorkflows&&(s[i.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,t){let n=Object.keys(e);return this.client.runOperation({name:`update`,ids:n,params:t?{updates:e,...t}: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 u(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})}},qt=class extends I{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}`)}},Jt=class extends I{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}`)}},Yt=class extends I{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})}},Xt=class extends I{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 a=Date.now();for(;;){let t=await this.getStatus(i.workflow_id,i.workflow_run_id);if(t.status===l.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(p(t.status)){let e=l[t.status]||String(t.status);throw Error(t.error||`Rendering failed with status: ${e}`)}if(Date.now()-a>=r)throw Error(`Rendering timed out after ${r}ms`);await Zt(n)}}};function Zt(e){return new Promise(t=>setTimeout(t,e))}var Qt=class extends I{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}})}},$t=class extends I{constructor(e){super(e,`/api/v1/tasks`)}list(e={}){return this.get(`/`,{query:e})}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}`)}},en=class extends I{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}`)}},tn=class extends I{catalog;constructor(e){super(e,`/api/v1/types`),this.catalog=new en(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}`)}},nn=class extends I{constructor(e){super(e,`/api/v1/view-executions`)}execute(e,t={}){return this.post(`/${encodeURIComponent(e)}/execute`,{payload:t})}preview(e){return this.post(`/preview`,{payload:e})}},rn=class extends I{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=>g(m(e),t))}async streamMessages(e,t,r,i,a){return new Promise((o,s)=>{let c=0,l=i||0,u=Date.now(),d=!1,f=null,p=null,h=null,_=null,v=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},y=()=>{h&&=(clearTimeout(h),null),p&&=(clearInterval(p),null),f&&=(f.close(),null),a&&_&&(a.removeEventListener(`abort`,_),_=null)},b=e=>{d||(d=!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(!d)try{let a=await L(),u=this.client,_=new URL(`${u.workflows.baseUrl}/runs/${e}/${t}/stream`);l>0&&_.searchParams.set(`since`,l.toString()),_.searchParams.set(`skipHistory`,`true`);let S=u._auth?await u._auth():void 0;if(d)return;if(!S){d=!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 ${t} (attempt ${c+1}/10)`);let w=new a(_.href);f=w,p=setInterval(()=>{},1e3),w.onopen=()=>{i&&console.log(`Successfully reconnected to SSE stream for run ${t}`),c=0},w.onmessage=e=>{if(!e.data||e.data.startsWith(`:`)){console.log(`Received comment or heartbeat; ignoring it.: `,e.data);return}try{let i=m(e.data);l=i.ts?Math.max(l,i.ts):Date.now(),r&&r(g(i,t),b),gt(i,t)?(console.log(`Closing stream due to COMPLETE message from main workstream`),d||(d=!0,y(),o(null))):i.t===n.COMPLETE&&console.log(`Received COMPLETE message that does not close the root stream for run ${t}`)}catch(t){console.error(`Failed to parse SSE message:`,t,e.data)}},w.onerror=e=>{if(!d)if(console.warn(`SSE stream error for run ${t}:`,e),y(),c<10){let e=v(c);console.log(`Attempting to reconnect in ${e}ms (attempt ${c+1}/10)`),c++,h=setTimeout(()=>{h=null,d||x(!0)},e)}else console.error(`Failed to reconnect to SSE stream for run ${t} after 10 attempts`),d=!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++,h=setTimeout(()=>{h=null,d||x(!0)},e)}else s(e)}};(async()=>{try{let n=await this.retrieveMessages(e,t,i),a=!1;for(let e=0;e<n.length;e++){let i=n[e];l=Math.max(l,i.timestamp||0),r&&r(i,b),a=e===n.length-1&&W(i,t)}if(a){b(null);return}}catch(e){console.warn(`Failed to fetch historical messages, continuing with SSE:`,e)}!d&&l<=0&&(l=Math.max(1,u-1)),x(!1)})().catch(s)})}async streamMessagesWS(e,t,r,i){return new Promise((a,o)=>{let s=0,c=null,l=i||0,u=!1,d=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},f=async()=>{if(!u)try{let i=this.client,p=new URL(`${i.workflows.baseUrl}/runs/${e}/${t}/ws`);p.protocol=p.protocol.replace(`http`,`ws`),l>0&&p.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];p.searchParams.set(`access_token`,g),s>0&&console.log(`Reconnecting to WebSocket for run ${t} (attempt ${s+1}/10)`),c=new WebSocket(p.href),c.onopen=()=>{s>0&&console.log(`Successfully reconnected to WebSocket for run ${t}`),s=0,u||a({cleanup:()=>{u=!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=e=>{try{let t=JSON.parse(e.data);if(`type`in t&&typeof t.type==`string`){if(t.type===`pong`){console.debug(`Received pong`);return}else if(t.type===`ack`){console.debug(`Signal acknowledged`,t);return}else if(t.type===`error`){console.error(`WebSocket error message`,t);return}}let i=m(t);l=i.ts?Math.max(l,i.ts):Date.now(),r&&r(i);let a=i.w||`main`;(i.t===n.TERMINATED||i.t===n.COMPLETE&&a===`main`)&&(console.log(`Closing WebSocket due to workflow completion`),u=!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(!u&&s<10){let e=d(s);console.log(`WebSocket closed, reconnecting in ${e}ms (attempt ${s+1}/10)`),s++,setTimeout(f,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=d(s);s++,setTimeout(f,e)}else o(e)}};f()})}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 an(this);definitions=new on(this)},an=class extends I{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})}},on=class extends I{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 sn(e){if(!e)throw Error(`zeno client serverUrl is required`);return e}var cn=class extends Se{constructor(e={}){super(sn(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 Ft(e.request,e):e}withApiVersion(e){return e?this.headers[c]=String(e):delete this.headers[c],this}withAppVersion(e){return e?this.headers[t]=String(e):delete this.headers[t],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,[c]:r}}agents=new _t(this);cost=new bt(this);objects=new Kt(this);types=new tn(this);workflows=new rn(this);schedules=new Qt(this);processes=new Jt(this);tasks=new $t(this);files=new Ht(this);collections=new yt(this);embeddings=new wt(this);email=new Ct(this);events=new Pt(this);eventSubscriptions=this.events.subscriptions;pendingAsks=new qt(this);data=new St(this);indexing=new Wt(this);query=new Yt(this);hiveMemory=new Ut(this);rendering=new Xt(this);views=new nn(this)},ln=class extends I{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}})}},un=class extends I{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}})}},dn=class extends I{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}`)}},fn=class extends I{executionApi;constructor(e,t){super(e,`/api/v1/views`),this.executionApi=t}list(e={}){return this.get(`/`,{query:{limit:e.limit,offset:e.offset}})}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${encodeURIComponent(e)}`)}update(e,t){return this.put(`/${encodeURIComponent(e)}`,{payload:t})}delete(e){return this.del(`/${encodeURIComponent(e)}`)}execute(e,t={}){return this.executionApi.execute(e,t)}preview(e){return this.executionApi.preview(e)}},Q=class e extends Se{_jwt=null;store;sessionTags;tokenServerUrl;oauthClients;oauthGrants;oauthServer;oauthProviders;remoteMcpConnections;secrets;internalSecrets;static async fromAuthToken(t,n,r){n||=$(t);let i=r||vn(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 cn({serverUrl:n,tokenServerUrl:this.tokenServerUrl,apikey:e.apikey,onRequest:e.onRequest,onResponse:e.onResponse,retryPolicy:e.retryPolicy,timeout:e.timeout,fetch:e.fetch}),this.views=new fn(this,this.store.views),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 qe(this),this.oauthGrants=new Ye(this),this.oauthServer=new Ze(this,this.tokenServerUrl),this.oauthProviders=new Xe(this),this.remoteMcpConnections=new rt(this),this.secrets=new at(this),this.internalSecrets=new Ke(this)}withApiVersion(e){return e?this.headers[c]=String(e):delete this.headers[c],this}withAppVersion(e){return this.store.withAppVersion(e),e?this.headers[t]=String(e):delete this.headers[t],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(!pn(e))return`Bearer ${e}`;if(mn(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,[c]:r}}projects=new Qe(this);environments=new Ae(this);interactions=new Ge(this);skills=new ot(this);prompts=new et(this);runs=new it(this);account=new Ce(this);accounts=new we(this);apikeys=new Ee(this);analytics=new Te(this);auditTrail=new Oe(this);training=new un(this);users=new dn(this);iam=new Me(this);refs=new nt(this);commands=new ke(this);apps=new De(this);tools=new ln(this);quota=new tt(this);views};function pn(e){return e.startsWith(`pk-`)||e.startsWith(`sk-`)}function mn(e){if(!e)return!0;let t=$(e).exp;return Date.now()>=t*1e3-6e4}function $(e){let t=e.split(`.`)[1],n=_n(t);return JSON.parse(n)}function hn(){return globalThis.Buffer}function gn(){return globalThis.process?.env?.STS_URL}function _n(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`),n=hn();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 vn(e){return e?typeof e==`string`?yn(e):e:yn(`api.vertesia.io`)}function yn(e){if(e===`local`)return{studio:`http://localhost:8091`,store:`http://localhost:8092`,token:gn()??`https://sts.dev1.vertesia.io`,git:`https://git.dev1.vertesia.io`};{let t=`https://${e}`;return{studio:t,store:t,token:t.replace(`api`,`sts`),git:t.replace(`api`,`git`)}}}var bn=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 Ie(this.client,this.id,e,t)}};export{e as APP_VERSION_HEADER,J as ARTIFACTS_PREFIX,_t as AgentsApi,St as DataApi,Ct as EmailApi,wt as EmbeddingsApi,jt as EventIngestChannelsApi,Nt as EventSubscriptionsApi,Pt as EventsApi,Y as FileDownloadError,Ht as FilesApi,Ut as HiveMemoryApi,R as IS_INTERACTION_OUTPUT,Wt as IndexingApi,bn as InteractionBase,V as InteractionOutput,Ke as InternalSecretsApi,Lt as MEMORIES_PREFIX,qe as OAuthClientsApi,Ye as OAuthGrantsApi,Xe as OAuthProvidersApi,Ze as OAuthServerApi,Kt as ObjectsApi,qt as PendingAsksApi,s as Permission,Jt as ProcessApi,Yt as QueryApi,rt as RemoteMcpConnectionsApi,Xt as RenderingApi,Qt as SchedulesApi,at as SecretsApi,nn as StoreViewsApi,G as StreamSource,$t as TaskApi,en as TypeCatalogApi,tn as TypesApi,Q as VertesiaClient,fn as ViewsApi,rn as WorkflowsApi,on as WorkflowsDefinitionApi,an as WorkflowsRulesApi,cn as ZenoClient,Ft as ZenoClientNotFoundError,u as canGenerateRendition,H as createInteractionOutput,vn as decodeEndpoints,$ as decodeJWT,B as enhanceExecutionRun,z as enhanceInteractionExecutionResult,U as fetchSignedUrl,Z as getAgentArtifactPath,X as getMemoryFilePath,d as getOAuthPermissionScopes,f as getSupportedRenditionFormats,mn as isTokenExpired,kt as openManagedEventSource,h as supportsVisualRendition};
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;S(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function S(e,t,n){if(t===n){k();return}let r=e.charCodeAt(t);if(E(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}\n${i}`,d++;return}if(D(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);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){T(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;T(s,a.slice(o+c),a)}function T(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}\n${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new C(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new C(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function k(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function A(e={}){if(e.consume&&o.length>0){let e=o.join(``);S(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1,m=!1,h=!1}return{feed:g,reset:A}}function E(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 D(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}function O(e,t){let n=1;for(;n<e.length&&n<t.length;){if(e.charCodeAt(n)!==t.charCodeAt(n))return!1;n++}return e.length<=t.length||e.charCodeAt(t.length)===58}var k=class extends TransformStream{constructor(){let e;super({start(t){e=T({onEvent(e){let n={type:`event`,...e};t.enqueue(n)}})},transform(t){e.feed(t)}})}};let A;if(globalThis.TextDecoderStream&&typeof globalThis.TextDecoderStream==`function`)A=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)}}A=e}async function j(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 A).pipeThrough(new k)}function M(e){let t=[];for(let n of Object.keys(e)){let r=e[n];if(r==null)continue;let i=encodeURIComponent(n);for(let e of Array.isArray(r)?r:[r])e!=null&&t.push(`${i}=${encodeURIComponent(String(e))}`)}return t.join(`&`)}function ee(e,t){return e.endsWith(`/`)?t.startsWith(`/`)?e+t.substring(1):e+t:t.startsWith(`/`)?e+t:`${e}/${t}`}function N(e){return e[e.length-1]===`/`?e.slice(0,-1):e}const te=`x-ratelimit-reason`,ne=`x-ratelimit-retry-ms`;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 P(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 P(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 F(e){let t=e.headers.get(`x-retry-after-ms`);if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return e}let n=e.headers.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r)&&r>=0)return r*1e3;let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}function de(e,t){if(e.status!==429||e.headers.get(te)!==`pacing`)return;let n=e.headers.get(ne),r=n?Number(n):NaN,i=Number.isFinite(r)&&r>=0?r:F(e);if(!(i===void 0||i>t.maxWaitMs))return i}function fe(e){if(e.status!==429)return;let t=e.headers.get(te);if(t!==`pacing`&&t!==`quota`)return;let n=e.headers.get(ne),r=n?Number(n):NaN,i=Number.isFinite(r)&&r>=0?r:F(e);if(i!==void 0)return{reason:t,retryAfterMs:i,resource:e.headers.get(`x-ratelimit-resource`)??void 0,window:e.headers.get(`x-ratelimit-window`)??void 0}}function pe(e){return new Promise(t=>setTimeout(t,e))}function me(e,t,n){let r=(n?F(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 ye(e){try{await e.body?.cancel()}catch{}}var I=class{_fetch;baseUrl;errorFactory=e=>e;verboseErrors=!0;retryPolicy;pacingRetry;defaultTimeoutMs;constructor(e,t){this.baseUrl=N(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://`)?N(e):N(ee(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`):P(n)&&n.message?r=String(n.message):P(n)&&n.error&&(typeof n.error==`string`?r=String(n.error):P(n.error)&&typeof n.error.message==`string`&&(r=n.error.message))),new x(r,e,t.status,n,this.verboseErrors,fe(t),F(t))}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}}}).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`?j(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+=`?${M(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 S(e,he(t)))),await this.waitBeforeRetry(d,h),h++;continue}if(this.handleFetchResponse(e,t),f&&g<f.attempts&&m){let e=de(t,f);if(e!==void 0){await ye(t),await pe(e),g++;continue}}if(d&&this.shouldRetryResponse(d,c,h,m,t)){await ye(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 S(_,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 be(e){return e?`authorization`in e:!1}function xe(){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 Se=class extends I{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 xe()&&(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&&!be(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)}},L=class extends I{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}},Ce=class extends L{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`)}},we=class extends L{constructor(e){super(e,`/api/v1/accounts`)}create(e){return this.post(`/`,{payload:{name:e}})}list(){return this.get(`/`)}},Te=class extends L{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}`:``}`)}},Ee=class extends L{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})}},De=class extends L{constructor(e){super(e,`/api/v1/apps`)}create(e){return this.post(`/`,{payload:e})}update(e,t){return this.put(`/${e}`,{payload:t})}previewDelete(e){return this.del(`/${e}`)}setMcpCollectionApiKey(e,t,n){return this.put(`/${encodeURIComponent(e)}/collections/${encodeURIComponent(t)}/api-key`,{payload:{api_key:n}})}getMcpCollectionApiKeyStatus(e,t){return this.get(`/${encodeURIComponent(e)}/collections/${encodeURIComponent(t)}/api-key`)}deleteMcpCollectionApiKey(e,t){return this.del(`/${encodeURIComponent(e)}/collections/${encodeURIComponent(t)}/api-key`)}deleteApp(e){return this.del(`/${e}`,{query:{confirm:`true`}})}listVersions(e){return this.get(`/versions`,{query:{...e?.app_id&&{app_id:e.app_id},...e?.kind&&{kind:e.kind},...e?.include_expired!==void 0&&{include_expired:e.include_expired},...e?.limit!==void 0&&{limit:e.limit}}})}upsertVersion(e){return this.post(`/versions`,{payload:e})}getVersion(e){return this.get(`/versions/${e}`)}promoteVersion(e){return this.post(`/versions/${e}/promote`)}rebuildVersion(e){return this.post(`/versions/${e}/rebuild`)}deleteVersion(e){return this.del(`/versions/${e}`)}startBuild(e,t){return this.post(`/${encodeURIComponent(e)}/builds`,{payload:t})}getBuildProgress(e,t,n){return this.get(`/${encodeURIComponent(e)}/builds/${encodeURIComponent(t)}/${encodeURIComponent(n)}/progress`)}startScaffold(e){return this.post(`/scaffolds`,{payload:e})}getScaffoldProgress(e,t){return this.get(`/scaffolds/${encodeURIComponent(e)}/${encodeURIComponent(t)}/progress`)}listAppInstallationTools(e){return this.get(`/installations/${e}/tools`)}inspect(e){return this.get(`/${e}/inspect`)}getRepoTree(e,t){return this.get(`/${encodeURIComponent(e)}/repo/tree`,{query:{prefix:t?.prefix,ref:t?.ref}})}async getRepoFile(e,t,n){let r=`/${encodeURIComponent(e)}/repo/file`,i=await this.get(r,{query:{path:t,ref:n?.ref},reader:e=>e});if(!i.ok){let e=await this.readJSONPayload(i),t=await this.createRequest(i.url||this.getUrl(r),{method:`GET`});throw this.createServerError(t,i,e)}return i}commitRepoDocuments(e,t,n){let r=new FormData,i={ref:n.ref,expected_head:n.expectedHead,message:n.message||`Upload documentation`,files:t.map((e,t)=>({field:`file_${t}`,path:e.path}))};return r.append(`metadata`,JSON.stringify(i)),t.forEach((e,t)=>{r.append(`file_${t}`,e.content,e.fileName||e.path.split(`/`).pop()||`document`)}),this.post(`/${encodeURIComponent(e)}/repo/documents`,{payload:r,jsonPayload:!1,timeoutMs:12e4})}getRepoCommits(e,t,n){return this.get(`/${encodeURIComponent(e)}/repo/commits`,{query:{path:t,ref:n?.ref,limit:n?.limit,cursor:n?.cursor}})}getRepoRefs(e){return this.get(`/${encodeURIComponent(e)}/repo/refs`)}listDevelopmentTasks(e){return this.get(`/${encodeURIComponent(e)}/development-tasks`)}getDevelopmentTask(e,t){return this.get(`/${encodeURIComponent(e)}/development-tasks/${encodeURIComponent(t)}`)}startDevelopmentTask(e,t,n){return this.post(`/${encodeURIComponent(e)}/development-tasks/${encodeURIComponent(t)}/runs`,{payload:n})}createRepoBranch(e,t){return this.post(`/${encodeURIComponent(e)}/repo/branches`,{payload:t})}getAppPackage(e,t=`all`){return this.get(`/${encodeURIComponent(e)}/package`,{query:{scope:Array.isArray(t)?t.join(`,`):t}})}getAppInstallationPackage(e,t=`all`){return this.get(`/installations/${e}/package`,{query:{scope:Array.isArray(t)?t.join(`,`):t}})}getSystemToolsPackage(e=`tools`){return this.get(`/studio-tools/package`,{query:{scope:e}})}list(e){return this.get(`/`,{query:{...e?.scope&&{scope:e.scope}}})}install(e,t,n,r,i){return this.post(`/install`,{payload:{app_id:e,settings:t,oauth_params:n,oauth_provider_params:r,api_key_params:i}})}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}})}},Oe=class extends L{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}`:``}`)}aggregate(e){return this.post(`/aggregate`,{payload:e})}},ke=class extends L{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`)}},Ae=class extends L{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})}},je=class extends L{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`)}},Me=class extends L{constructor(e){super(e,`/api/v1/iam`)}aces=new Pe(this);roles=new Ne(this);groups=new je(this);getPrincipalIdentity(){return this.get(`/users/identity`)}},Ne=class extends L{constructor(e){super(e,`/roles`)}list(){return this.get(`/`)}listSystem(){return this.get(`/system`)}},Pe=class extends L{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 Fe=(()=>{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:18e5})();async function R(){return typeof globalThis.EventSource==`function`?globalThis.EventSource:(await import(`eventsource`)).EventSource}async function Ie(e,t,n={},r){let i=!!r,a=await e.runs.create({...n,interaction:t,stream:i},{timeoutMs:i?void 0:Fe});if(i){if(a.status===o.failed)return a;await Re(e,a.id,r)}return a}async function Le(e,t,n={},r){let i=!!r,a=await e.post(`/api/v1/execute`,{payload:{...n,interaction:t,stream:i},timeoutMs:i?void 0:Fe});if(i){if(a.status===o.failed)return a;await Re(e,a.id,r)}return a}function Re(e,t,n){return new Promise((r,i)=>{(async()=>{try{let a=await R(),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 ze(e,t){return await e.post(`/api/v1/execute/async`,{payload:t})}async function Be(e,t){return await e.post(`/api/v1/execute/rate-limit/request`,{payload:t})}var Ve=class extends L{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 z=Symbol(`InteractionOutput`);function B(e){return e.result=V.from(e.result),e}function He(e){return e.result=V.from(e.result),e}var V=class{results;constructor(e){this.results=e}static from(e){return e?Ue(e)?e:H(Array.isArray(e)?e:typeof e==`object`?[{type:`json`,value:e}]:[{type:`text`,value:String(e)}]):H([])}static isInteractionOutputArray(e){return Ue(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`)}hasThoughts(){return this.results.some(e=>e.type===`thoughts`)}hasImage(){return this.results.some(e=>e.type===`image`)}hasVideo(){return this.results.some(e=>e.type===`video`)}text(e=`
10
+ `){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)}thoughts(e=`
11
+ `){return this.results.filter(e=>e.type===`thoughts`).map(e=>e.value).join(e)}thoughtParts(){return this.results.filter(e=>e.type===`thoughts`).map(e=>e.value)}object(){let e=this.results.find(e=>e.type===`json`);return e?e.value:We(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)}video(){let e=this.results.find(e=>e.type===`video`);if(!e)throw Error(`No video result found`);return e.value}videos(){return this.results.filter(e=>e.type===`video`).map(e=>e.value)}stringify(e=`
12
+ `,t=2){return this.results.filter(e=>e.type!==`thoughts`).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 Ue(e){return!!e&&typeof e==`object`&&e[z]===!0}function H(e){let t=new V(e);return new Proxy(e,{get(e,n,r){if(n===z)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 We(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 Ge(e){return!!e&&typeof e==`object`&&`id`in e&&typeof e.id==`string`}var Ke=class extends L{catalog;constructor(e){super(e,`/api/v1/interactions`),this.catalog=new Ve(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 B(await Ie(this.client,e,t,n).catch(e=>{throw e instanceof x&&Ge(e.payload)?e.updateDetails({run_id:e.payload.id}):e}))}async executeByName(e,t={},n){return B(await Le(this.client,e,t,n).catch(e=>{throw e instanceof x&&Ge(e.payload)?e.updateDetails({run_id:e.payload.id}):e}))}executeAsync(e){return ze(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 Be(this.client,e)}resolve(e,t){return this.get(`/resolve/${encodeURIComponent(e)}`,{query:t})}},qe=class extends L{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})}},Je=class extends L{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 Ye(e){if(e)return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>[e,String(t)]))}var Xe=class extends L{constructor(e){super(e,`/api/v1/oauth-grants`)}list(e){return this.get(`/`,{query:Ye(e)})}retrieve(e){return this.get(`/${e}`)}revoke(e,t){return this.del(`/${e}`,{query:t})}revokeBulk(e){return this.post(`/revoke`,{payload:e})}},Ze=class extends L{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`)}},Qe=class extends I{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,t){if(!t)return this.post(`/requests`,{payload:e});if(!/^\/env\/[a-z][a-z0-9-]{1,15}\/dev-[a-z0-9-]+$/.test(t))return Promise.reject(Error(`Invalid OAuth authorization server path`));let n=new URL(`${t}/requests`,this.baseUrl).toString();return this.post(n,{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:{}})}},$e=class extends L{integrations;constructor(e){super(e,`/api/v1/projects`),this.integrations=new et(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(`/${encodeURIComponent(e)}/app-types`,{query:{tag:t}})}getAppContentType(e,t){return this.get(`/${encodeURIComponent(e)}/app-types/${encodeURIComponent(t)}`)}listAppProcesses(e,t){return this.get(`/${encodeURIComponent(e)}/app-processes`,{query:{tag:t}})}getAppProcess(e,t){return this.get(`/${encodeURIComponent(e)}/app-processes/${encodeURIComponent(t)}`)}listAppViews(e,t){return this.get(`/${encodeURIComponent(e)}/app-views`,{query:{tag:t}})}getAppView(e,t){return this.get(`/${encodeURIComponent(e)}/app-views/${encodeURIComponent(t)}`)}listAppRenderingTemplates(e,t){return this.get(`/${encodeURIComponent(e)}/app-templates`,{query:{tag:t}})}getAppRenderingTemplate(e,t){return this.get(`/${encodeURIComponent(e)}/app-templates/${encodeURIComponent(t)}`)}getCompositeAppConfiguration(e){return this.get(`/${encodeURIComponent(e)}/composite-app`)}updateCompositeAppConfiguration(e,t){return this.put(`/${encodeURIComponent(e)}/composite-app`,{payload:t})}},et=class extends L{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`)}},tt=class extends L{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`)}},nt=class extends L{constructor(e){super(e,`/api/v1/quota`)}standing(){return this.get(`/standing`)}tier(){return this.get(`/tier`)}},rt=class extends L{constructor(e){super(e,`/api/v1/refs`)}resolve(e){return this.post(`/resolve`,{payload:{refs:e}})}},it=class extends L{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}})}},at=class extends L{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 He(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 B(await this.post(`/`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal}))}sendToolResults(e,t){return this.post(`/tool-results`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal})}sendUserMessage(e,t){return this.post(`/user-message`,{payload:e,timeoutMs:t?.timeoutMs,signal:t?.signal})}computeFacets(e){return this.post(`/facets`,{payload:e})}search(e){return this.post(`/search`,{payload:e})}clone(e){return this.post(`/clone`,{payload:e})}},ot=class extends L{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})}},st=class extends L{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 ct=new Set([429,500,502,503,504]);function lt(e){return new Promise(t=>setTimeout(t,e))}function ut(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 dt(e,t,n,r){let i=r?ut(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 ft=new TextEncoder;function pt(e){if(typeof e==`string`)return ft.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 mt(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(pt(r))}}catch(e){throw await t.cancel(e).catch(()=>void 0),e}finally{t.releaseLock()}return new Blob(n)}return e}}async function U(e,t={}){let{method:n=`GET`,headers:r,attempts:i=4,baseDelayMs:a=500,maxDelayMs:o=8e3,retryableStatuses:s=ct}=t,c=await mt(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 lt(dt(t,a,o,i))}catch(e){if(l=e,u)throw e;await lt(dt(t,a,o))}}throw l instanceof Error?l:Error(`Failed to fetch signed URL: ${e}`)}function ht(e){if(!e||typeof e!=`object`)return;let t=e.process_run_id;return typeof t==`string`?t:void 0}function gt(e,t){let n=ht(e);return!n||n===t}function W(e,t,r=!1){return e.type===n.TERMINATED||(e.type===n.COMPLETE||r&&e.type===n.IDLE)&&(e.workstream_id??`main`)===`main`?gt(e.details,t):!1}function _t(e,t,r=!1){return e.t===n.TERMINATED||(e.t===n.COMPLETE||r&&e.t===n.IDLE)&&(e.w??`main`)===`main`?gt(e.d,t):!1}var vt=class extends L{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(yt)}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),e?.until&&(t.until=e.until),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),e?.until&&(t.until=e.until),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=>g(m(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,u=Date.now(),d=!1,f=null,p=null,h=null,_=null,v=null,y=!1,b=0,x=null,S=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},C=()=>{y=!1,_&&=(clearTimeout(_),null),v&&=(clearTimeout(v),null)},w=()=>{h&&=(clearTimeout(h),null),C(),p&&=(clearInterval(p),null),f&&=(f.close(),null),r&&x&&(r.removeEventListener(`abort`,x),x=null)},T=e=>{d||(d=!0,w(),a(e))},E=e=>typeof e==`string`&&[`completed`,`failed`,`cancelled`].includes(e),D=(t,n)=>{b++,console.warn(`Agent stream ${e}: ${t} failed while polling (consecutive failures: ${b}); retrying in 5s:`,n instanceof Error?n.message:n)},O=async()=>{if(d||!y)return;let n=!1;try{let r=await this.retrieveMessages(e,l||void 0);n=!0;for(let n of r){if(d)return;let r=n.timestamp||0;if(!(r<=l)){if(l=r,t&&t(n,T),d)return;if(W(n,e,i?.closeOnIdle)){T(null);return}}}}catch(e){D(`GET /updates`,e)}if(!(d||!y)){try{let t=await this.get(`/${e}`);if(E(t?.status)){T(null);return}n&&(b=0)}catch(e){D(`run status check`,e)}d||!y||(_=setTimeout(()=>{_=null,O()},5e3))}},k=()=>{v=null,!(d||!y)&&(C(),c=0,console.log(`Agent stream ${e}: retrying the SSE connection after the polling fallback.`),M(`resume`))},A=t=>{d||y||(w(),y=!0,b=0,console.warn(`Agent stream ${e}: SSE unavailable after 10 attempts; falling back to GET /updates polling every 5s (SSE retried every 60s).`,t instanceof Error?t.message:t),v=setTimeout(k,6e4),O())},j=e=>{if(d)return;if(c>=10){A(e);return}let t=S(c);c++,h=setTimeout(()=>{h=null,d||M(`reconnect`)},t)};if(r){if(r.aborted)return d=!0,w(),a(null),s;x=()=>{T(null)},r.addEventListener(`abort`,x,{once:!0})}try{if(!d){let r=await this.retrieveMessages(e,n);i?.onHistoryLoaded?.(r);let a=!1;for(let n=0;n<r.length;n++){let o=r[n];if(d||(l=Math.max(l,o.timestamp||0),t&&t(o,T),d))break;a=n===r.length-1&&W(o,e,i?.closeOnIdle)}if(a)return T(null),s}}catch(e){d||(i?.onHistoryError?.(e),console.warn(`Failed to fetch historical messages, continuing with SSE:`,e))}!d&&l<=0&&(l=Math.max(1,u-1));let M=async(n=`initial`)=>{if(!d)try{let r=await R();if(d)return;let a=this.client,s=new URL(`${a.agents.baseUrl}/${e}/stream`);l>0&&s.searchParams.set(`since`,l.toString()),s.searchParams.set(`skipHistory`,`true`);let u=a._auth?await a._auth():void 0;if(d)return;if(!u){d=!0,w(),o(Error(`No auth token available`));return}let h=u.split(` `)[1];if(s.searchParams.set(`access_token`,h),n===`reconnect`&&console.log(`Reconnecting to agent stream ${e} (attempt ${c}/10)`),d)return;let _=new r(s.href);f=_,p=setInterval(()=>{},1e3);let v=0;_.onopen=()=>{n!==`initial`&&console.log(`Reconnected to agent stream ${e}`),v=Date.now()},_.onmessage=n=>{if(!d&&!(!n.data||n.data.startsWith(`:`)))try{let r=m(n.data);l=r.ts?Math.max(l,r.ts):Date.now(),t&&t(g(r,e),T),_t(r,e,i?.closeOnIdle)&&T(null)}catch(e){console.error(`Failed to parse SSE message:`,e,n.data)}},_.onerror=e=>{d||(w(),(v?Date.now()-v:0)>5e3&&(c=0),j(Error(`SSE connection failed after 10 reconnection attempts`)))}}catch(e){if(d)return;j(e)}};return M(`initial`),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 R(),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})}getArtifactContent(e,t){return this.get(`/${e}/artifact-content/${t}`)}updateArtifactContent(e,t,n){return this.put(`/${e}/artifact-content/${t}`,{payload: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 U(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 U(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 yt(e){return e.run_kind===`process`}var bt=class extends L{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`)}},xt=class extends L{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}`:``}`}},St=class extends L{storeId;constructor(e,t){super(e,`/api/v1/data/${t}/dashboards`),this.storeId=t}storeHeaders(){return{[a.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()})}},Ct=class extends L{constructor(e){super(e,`/api/v1/data`)}storeHeaders(e){return{[a.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 St(this.client,e)}},wt=class extends L{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})}},Tt=class extends L{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 Et(e){return JSON.parse(e)}function Dt(e,t,n){let r=Math.min(t*2**e,n);return r+Math.random()*.1*r}function Ot(e,t){if(!t)return;let n=t.startsWith(`Bearer `)?t.slice(7):t;e.searchParams.set(`access_token`,n)}async function kt(e){let t=typeof e==`function`?await e():e;return t instanceof URL?new URL(t.href):new URL(t)}function At(e){let t=e.event_types?.length?e.event_types:[`message`],n=e.max_reconnect_attempts??10,r=e.base_reconnect_delay_ms??1e3,i=e.max_reconnect_delay_ms??3e4,a=e.parse??Et,o=!1,s=0,c=null,l=null,u=null,d=0,f,p=t=>{e.on_status?.(t)},m=()=>{c&&=(c.close(),null),l&&=(clearTimeout(l),null)},h=()=>{o||(o=!0,m(),e.signal&&u&&(e.signal.removeEventListener(`abort`,u),u=null),p(`closed`))},g=t=>{if(o)return;if(m(),(d?Date.now()-d:0)>5e3&&(s=0),s>=n){h(),e.on_error?.(t);return}let a=Dt(s,r,i);s+=1,p(`reconnecting`),l=setTimeout(()=>{l=null,v(!0)},a)},_=(t,n)=>{if(!(o||!n.data||String(n.data).startsWith(`:`)))try{let r=a(String(n.data),t),i=e.get_cursor?.(r);f=n.lastEventId||i||f,e.on_event({data:r,event_type:t,event_id:n.lastEventId||i})}catch(t){e.on_error?.(t)}},v=async n=>{if(!o)try{p(n?`reconnecting`:`connecting`);let r=await R();if(o)return;let i=await kt(e.url);if(f&&e.last_event_id_query_param&&!i.searchParams.has(e.last_event_id_query_param)&&i.searchParams.set(e.last_event_id_query_param,f),Ot(i,await e.get_access_token?.()),o)return;let a=new r(i.href);c=a,d=0,a.onopen=()=>{d=Date.now(),p(`open`)};for(let e of t)a.addEventListener(e,t=>_(e,t));a.onerror=e=>{g(e)}}catch(e){g(e)}};if(e.signal){if(e.signal.aborted)return o=!0,p(`closed`),{get closed(){return o},close:h};u=h,e.signal.addEventListener(`abort`,u,{once:!0})}return v(!1),{get closed(){return o},close:h}}function jt(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 Mt=class extends L{constructor(e){super(e,`/api/v1/events/channels`)}list(e){return this.get(`/`,{query:jt(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 Nt(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 Pt=class extends L{constructor(e){super(e,`/api/v1/events/subscriptions`)}list(e){return this.get(`/`,{query:Nt(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}`)}},Ft=class extends L{subscriptions;channels;constructor(e){super(e,`/api/v1/events`),this.subscriptions=new Pt(e),this.channels=new Mt(e)}searchDeliveries(e={}){return this.post(`/deliveries/search`,{payload:e})}queueSummary(e={}){return this.post(`/deliveries/queue-summary`,{payload:e})}cancelQueuedDeliveries(e={}){return this.post(`/deliveries/cancel`,{payload:e})}subscribeDeliveries(e){let{signal:t,max_reconnect_attempts:n,on_snapshot:r,on_delivery:i,on_envelope:a,on_error:o,on_status:s,...c}=e;return At({url:()=>this.buildStreamUrl(c),event_types:[`snapshot`,`event`,`heartbeat`,`error`],signal:t,max_reconnect_attempts:n,last_event_id_query_param:`since_event_id`,get_access_token:async()=>{let e=this.client;return e._auth?await e._auth():void 0},get_cursor:e=>e.cursor,on_status:s,on_error:o,on_event:({data:e})=>{a?.(e),e.type===`snapshot`?r?.(e.deliveries,e):e.type===`event`?i?.(e.item,e):e.type===`error`&&o?.(Error(e.error))}})}buildStreamUrl(e){let t=new URL(`${this.baseUrl}/stream`);return this.setStreamParam(t,`limit`,e.limit),this.setStreamParam(t,`event_id`,e.event_id),this.setStreamParam(t,`resource_id`,e.resource_id),this.setStreamListParam(t,`resource_type`,e.resource_type),this.setStreamListParam(t,`event_category`,e.event_category),this.setStreamListParam(t,`action`,e.action),this.setStreamListParam(t,`outbox_status`,e.outbox_status),this.setStreamParam(t,`since_event_id`,e.since_event_id),this.setStreamParam(t,`since_created_at`,e.since_created_at),this.setStreamParam(t,`include_event`,e.include_event),this.setStreamParam(t,`poll_interval_ms`,e.poll_interval_ms),t}setStreamParam(e,t,n){n!=null&&n!==``&&e.searchParams.set(t,String(n))}setStreamListParam(e,t,n){n?.length&&e.searchParams.set(t,n.join(`,`))}},It=class extends b{constructor(e,t){super(`Resource not found: ${t.message}`,e,404,t.payload)}},G=class{stream;name;type;id;constructor(e,t,n,r){this.stream=e,this.name=t,this.type=n,this.id=r}};function Lt(e){return e?.split(`;`,1)[0]?.trim().toLowerCase()||void 0}function K(e){return Lt(e)===`application/octet-stream`?void 0:e||void 0}function q(e,t){return K(e)||t||e||void 0}const Rt=`memories`,J=`agents`,zt={attempts:3,methods:[`POST`],statuses:[502,503,504]};function Bt(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e.split(/[?#]/,1)[0]||`unknown file`}}function Vt(e){if(!(e instanceof Error))return;let t=e.message.replace(/https?:\/\/[^\s)\]}>"']+/g,e=>Bt(e)),n=Error(t);return n.name=e.name,n}function Ht(e,t){return e===404?`not found`:e===403?`forbidden`:e?`failed with status ${e}${t?` ${t}`:``}`:`failed`}var Y=class extends Error{status;constructor(e,t,n,r){let i=Bt(e),a=Ht(t,n);super(`File download ${a}: ${i}`,{cause:Vt(r)}),this.name=`FileDownloadError`,this.status=t}};function X(e){let t=e.endsWith(`.tar.gz`)?e:`${e}.tar.gz`;return`${Rt}/${t}`}function Z(e,t){return`${J}/${e}/${t}`}var Ut=class extends L{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}})}ensureBucketCreateAccess(e){let t={principal:e};return this.post(`/bucket/create-access`,{payload:t})}getBucketCreateAccessStatus(e){return this.get(`/bucket/create-access`,{query:{principal:e}})}list(e){return this.get(`/list`,{query:{prefix:e}})}getUploadUrl(e){return this.post(`/upload-url`,{payload:e,retryPolicy:zt})}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:K(e.type),id:e instanceof G?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 G,u=q(e.type,c),d=await U(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 G,{url:n,id:r,path:i,mime_type:a}=await this.getUploadUrl({id:t?e.id:void 0,name:e.name,mime_type:K(e.type)}),o=q(e.type,a)||`application/gzip`,s=await U(n,{method:`PUT`,body:t?e.stream:e,headers:{"Content-Type":o}}).catch(e=>{throw console.error(`Failed to upload file`,{err:e,url:n,id:r,path:i}),e});if(!s.ok)throw console.log(s),Error(`Failed to upload file: ${s.statusText}`);return{id:r,path:i}}async downloadFile(e){let{url:t}=e.startsWith(`https:`)?{url:e}:await this.getDownloadUrl(e),n;try{n=await U(t,{method:`GET`})}catch(t){throw new Y(e,void 0,void 0,t)}if(!n.ok)throw new Y(e,n.status,n.statusText);if(!n.body)throw new Y(e);return n.body}async copyFile(e,t){return(await this.post(`/copy`,{payload:{source:e,dest:t}})).dest}async uploadMemoryPack(e){let t=X(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 G(r.stream(),n,r.type,t))}return this.uploadFile(new G(e.stream,n,e.type,t))}async downloadMemoryPack(e,t=!1){let n=await this.downloadFile(X(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=Z(e,t);if(n instanceof File){let e=n;return this.uploadFile(new G(e.stream(),t,e.type,r))}return this.uploadFile(new G(n.stream,t,n.type,r))}async downloadArtifact(e,t){let n=Z(e,t);return this.downloadFile(n)}getArtifactDownloadUrl(e,t,n){let r=Z(e,t);return this.getDownloadUrl(r,t,n)}async listArtifacts(e){let t=`${J}/${e}/`;return(await this.listByPrefix(t)).files}},Wt=class extends L{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}},Gt=class extends L{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 startGroundedExtraction(e){return this.post(`/grounded`,{payload:e??{}})}async getGroundedExtractionResult(){return this.get(`/grounded/result`)}async startGroundedAssistant(e){return this.post(`/grounded/assistant`,{payload:e??{}})}},Kt=class extends L{constructor(e){super(e,`/api/v1/objects`)}analyze(e){return new Gt(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 U(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 G,{url:n,id:r,mime_type:i}=await this.getUploadUrl({id:t?e.id:void 0,name:e.name,mime_type:K(e.type)}),a=q(e.type,i),o=await U(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,t){let{content:n,...r}=e,a={...r};a.content=n instanceof G||n instanceof File?await this.upload(n):n;let o={};return t?.processing_priority&&(o[i.PROCESSING_PRIORITY]=t.processing_priority),t?.collection_id&&(o[i.COLLECTION_ID]=t.collection_id),await this.post(`/`,{payload:a,headers:o})}async createFromExternalSource(e,t={},n){let r=await this.client.files.getMetadata(e),a={...t,content:{source:e,name:r.name,type:r.contentType,etag:r.etag}},o={};return n?.processing_priority&&(o[i.PROCESSING_PRIORITY]=n.processing_priority),n?.collection_id&&(o[i.COLLECTION_ID]=n.collection_id),await this.post(`/`,{payload:a,headers:o})}async update(e,t,n){let{content:r,...a}=t,o={...a};o.content=r instanceof G||r instanceof File?await this.upload(r):r;let s={};return n?.ifMatch&&(s[`if-match`]=n.ifMatch),n?.processing_priority&&(s[i.PROCESSING_PRIORITY]=n.processing_priority),n?.createRevision&&(s[i.CREATE_REVISION]=`true`,n.revisionLabel&&(s[i.REVISION_LABEL]=n.revisionLabel)),n?.suppressWorkflows&&(s[i.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,t){let n=Object.keys(e);return this.client.runOperation({name:`update`,ids:n,params:t?{updates:e,...t}: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 u(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})}},qt=class extends L{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}`)}},Jt=class extends L{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?.all_versions||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}`)}listTestSuites(e){return this.get(`/${e}/test-suites`)}createTestSuite(e,t){return this.post(`/${e}/test-suites`,{payload:t})}updateTestSuite(e,t,n){return this.put(`/${e}/test-suites/${t}`,{payload:n})}deleteTestSuite(e,t){return this.del(`/${e}/test-suites/${t}`)}startTestRun(e,t){return this.post(`/${e}/test-runs`,{payload:t})}listTestRuns(e,t){return this.get(`/${e}/test-runs`,{query:t?.limit==null?void 0:{limit:String(t.limit)}})}retrieveTestRun(e,t){return this.get(`/${e}/test-runs/${t}`)}cancelTestRun(e,t){return this.post(`/${e}/test-runs/${t}/cancel`,{})}},Yt=class extends L{constructor(e){super(e,`/api/v1/process-test-runs`)}submit(e){return this.post(`/`,{payload:e,retryPolicy:!1})}retrieve(e){return this.get(`/${e}`)}cancel(e){return this.post(`/${e}/cancel`,{})}delete(e){return this.del(`/${e}`)}},Xt=class extends L{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})}},Zt=class extends L{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??6e5,i=await this.start(e);if(!i.workflow_id||!i.workflow_run_id)throw Error(`Failed to start rendering workflow`);let a=Date.now();for(;;){let t=await this.getStatus(i.workflow_id,i.workflow_run_id);if(t.status===l.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(p(t.status)){let e=l[t.status]||String(t.status);throw Error(t.error||`Rendering failed with status: ${e}`)}if(Date.now()-a>=r)throw Error(`Rendering timed out after ${r}ms`);await Qt(n)}}};function Qt(e){return new Promise(t=>setTimeout(t,e))}var $t=class extends L{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}})}},en=class extends L{constructor(e){super(e,`/api/v1/tasks`)}list(e={}){return this.get(`/`,{query:e})}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}`)}},tn=class extends L{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}`)}},nn=class extends L{catalog;constructor(e){super(e,`/api/v1/types`),this.catalog=new tn(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}`)}},rn=class extends L{constructor(e){super(e,`/api/v1/view-executions`)}execute(e,t={}){return this.post(`/${encodeURIComponent(e)}/execute`,{payload:t})}preview(e){return this.post(`/preview`,{payload:e})}},an=class extends L{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=>g(m(e),t))}async streamMessages(e,t,r,i,a){return new Promise((o,s)=>{let c=0,l=i||0,u=Date.now(),d=!1,f=null,p=null,h=null,_=null,v=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},y=()=>{h&&=(clearTimeout(h),null),p&&=(clearInterval(p),null),f&&=(f.close(),null),a&&_&&(a.removeEventListener(`abort`,_),_=null)},b=e=>{d||(d=!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(!d)try{let a=await R(),u=this.client,_=new URL(`${u.workflows.baseUrl}/runs/${e}/${t}/stream`);l>0&&_.searchParams.set(`since`,l.toString()),_.searchParams.set(`skipHistory`,`true`);let S=u._auth?await u._auth():void 0;if(d)return;if(!S){d=!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 ${t} (attempt ${c+1}/10)`);let w=new a(_.href);f=w,p=setInterval(()=>{},1e3),w.onopen=()=>{i&&console.log(`Successfully reconnected to SSE stream for run ${t}`),c=0},w.onmessage=e=>{if(!e.data||e.data.startsWith(`:`)){console.log(`Received comment or heartbeat; ignoring it.: `,e.data);return}try{let i=m(e.data);l=i.ts?Math.max(l,i.ts):Date.now(),r&&r(g(i,t),b),_t(i,t)?(console.log(`Closing stream due to COMPLETE message from main workstream`),d||(d=!0,y(),o(null))):i.t===n.COMPLETE&&console.log(`Received COMPLETE message that does not close the root stream for run ${t}`)}catch(t){console.error(`Failed to parse SSE message:`,t,e.data)}},w.onerror=e=>{if(!d){if(console.warn(`SSE stream error for run ${t}:`,e),y(),c<10){let e=v(c);console.log(`Attempting to reconnect in ${e}ms (attempt ${c+1}/10)`),c++,h=setTimeout(()=>{h=null,d||x(!0)},e)}else console.error(`Failed to reconnect to SSE stream for run ${t} after 10 attempts`),d=!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++,h=setTimeout(()=>{h=null,d||x(!0)},e)}else s(e)}};(async()=>{try{let n=await this.retrieveMessages(e,t,i),a=!1;for(let e=0;e<n.length;e++){let i=n[e];l=Math.max(l,i.timestamp||0),r&&r(i,b),a=e===n.length-1&&W(i,t)}if(a){b(null);return}}catch(e){console.warn(`Failed to fetch historical messages, continuing with SSE:`,e)}!d&&l<=0&&(l=Math.max(1,u-1)),x(!1)})().catch(s)})}async streamMessagesWS(e,t,r,i){return new Promise((a,o)=>{let s=0,c=null,l=i||0,u=!1,d=e=>{let t=Math.min(1e3*2**e,3e4);return t+Math.random()*.1*t},f=async()=>{if(!u)try{let i=this.client,p=new URL(`${i.workflows.baseUrl}/runs/${e}/${t}/ws`);p.protocol=p.protocol.replace(`http`,`ws`),l>0&&p.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];p.searchParams.set(`access_token`,g),s>0&&console.log(`Reconnecting to WebSocket for run ${t} (attempt ${s+1}/10)`),c=new WebSocket(p.href),c.onopen=()=>{s>0&&console.log(`Successfully reconnected to WebSocket for run ${t}`),s=0,u||a({cleanup:()=>{u=!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=e=>{try{let t=JSON.parse(e.data);if(`type`in t&&typeof t.type==`string`){if(t.type===`pong`){console.debug(`Received pong`);return}if(t.type===`ack`){console.debug(`Signal acknowledged`,t);return}if(t.type===`error`){console.error(`WebSocket error message`,t);return}}let i=m(t);l=i.ts?Math.max(l,i.ts):Date.now(),r&&r(i);let a=i.w||`main`;(i.t===n.TERMINATED||i.t===n.COMPLETE&&a===`main`)&&(console.log(`Closing WebSocket due to workflow completion`),u=!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(!u&&s<10){let e=d(s);console.log(`WebSocket closed, reconnecting in ${e}ms (attempt ${s+1}/10)`),s++,setTimeout(f,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=d(s);s++,setTimeout(f,e)}else o(e)}};f()})}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 on(this);definitions=new sn(this)},on=class extends L{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})}},sn=class extends L{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 cn(e){if(!e)throw Error(`zeno client serverUrl is required`);return e}var ln=class extends Se{constructor(e={}){super(cn(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 It(e.request,e):e}withApiVersion(e){return e?this.headers[c]=String(e):delete this.headers[c],this}withAppVersion(e){return e?this.headers[t]=String(e):delete this.headers[t],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,[c]:r}}agents=new vt(this);cost=new xt(this);objects=new Kt(this);types=new nn(this);workflows=new an(this);schedules=new $t(this);processes=new Jt(this);processTestRuns=new Yt(this);tasks=new en(this);files=new Ut(this);collections=new bt(this);embeddings=new Tt(this);email=new wt(this);events=new Ft(this);eventSubscriptions=this.events.subscriptions;pendingAsks=new qt(this);data=new Ct(this);indexing=new Wt(this);query=new Xt(this);rendering=new Zt(this);views=new rn(this)},un=class extends L{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(`,`)),e?.context&&(t.context=e.context),this.get(`/`,{query:Object.keys(t).length>0?t:void 0})}inspect(e,t){if(!e.trim())throw Error(`Tool name must not be empty`);return this.get(`/${encodeURIComponent(e)}`,{query:t?.context?{context:t.context}:void 0})}listBuiltins(){return this.list({sources:[`builtin`]})}validate(e){return this.post(`/validate`,{payload:{names:e}})}},dn=class extends L{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}})}},fn=class extends L{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}`)}},pn=class extends L{executionApi;constructor(e,t){super(e,`/api/v1/views`),this.executionApi=t}list(e={}){return this.get(`/`,{query:{limit:e.limit,offset:e.offset}})}create(e){return this.post(`/`,{payload:e})}retrieve(e){return this.get(`/${encodeURIComponent(e)}`)}update(e,t){return this.put(`/${encodeURIComponent(e)}`,{payload:t})}delete(e){return this.del(`/${encodeURIComponent(e)}`)}execute(e,t={}){return this.executionApi.execute(e,t)}preview(e){return this.executionApi.preview(e)}},Q=class e extends Se{_jwt=null;store;sessionTags;tokenServerUrl;oauthClients;oauthGrants;oauthServer;oauthProviders;remoteMcpConnections;secrets;internalSecrets;static async fromAuthToken(t,n,r){n||=$(t);let i=r||yn(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 ln({serverUrl:n,tokenServerUrl:this.tokenServerUrl,apikey:e.apikey,onRequest:e.onRequest,onResponse:e.onResponse,retryPolicy:e.retryPolicy,timeout:e.timeout,fetch:e.fetch}),this.views=new pn(this,this.store.views),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 Je(this),this.oauthGrants=new Xe(this),this.oauthServer=new Qe(this,this.tokenServerUrl),this.oauthProviders=new Ze(this),this.remoteMcpConnections=new it(this),this.secrets=new ot(this),this.internalSecrets=new qe(this)}withApiVersion(e){return e?this.headers[c]=String(e):delete this.headers[c],this}withAppVersion(e){return this.store.withAppVersion(e),e?this.headers[t]=String(e):delete this.headers[t],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(!mn(e))return`Bearer ${e}`;if(hn(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 processTestRuns(){return this.store.processTestRuns}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,[c]:r}}projects=new $e(this);environments=new Ae(this);interactions=new Ke(this);skills=new st(this);prompts=new tt(this);runs=new at(this);account=new Ce(this);accounts=new we(this);apikeys=new Ee(this);analytics=new Te(this);auditTrail=new Oe(this);training=new dn(this);users=new fn(this);iam=new Me(this);refs=new rt(this);commands=new ke(this);apps=new De(this);tools=new un(this);quota=new nt(this);views};function mn(e){return e.startsWith(`pk-`)||e.startsWith(`sk-`)}function hn(e){if(!e)return!0;let t=$(e).exp;return Date.now()>=t*1e3-6e4}function $(e){let t=e.split(`.`)[1],n=vn(t);return JSON.parse(n)}function gn(){return globalThis.Buffer}function _n(){return globalThis.process?.env?.STS_URL}function vn(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`),n=gn();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)}throw Error(`No base64 decoder available`)}function yn(e){return e?typeof e==`string`?bn(e):e:bn(`api.vertesia.io`)}function bn(e){if(e===`local`)return{studio:`http://localhost:8091`,store:`http://localhost:8092`,token:_n()??`https://sts.dev1.vertesia.io`,git:`https://git.dev1.vertesia.io`};{let t=`https://${e}`;return{studio:t,store:t,token:t.replace(`api`,`sts`),git:t.replace(`api`,`git`)}}}var xn=class{id;client;constructor(e,t){this.id=e,this.client=t instanceof Q?t: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 Ie(this.client,this.id,e,t)}};export{e as APP_VERSION_HEADER,J as ARTIFACTS_PREFIX,vt as AgentsApi,Ct as DataApi,wt as EmailApi,Tt as EmbeddingsApi,Mt as EventIngestChannelsApi,Pt as EventSubscriptionsApi,Ft as EventsApi,Y as FileDownloadError,Ut as FilesApi,z as IS_INTERACTION_OUTPUT,Wt as IndexingApi,xn as InteractionBase,V as InteractionOutput,qe as InternalSecretsApi,Rt as MEMORIES_PREFIX,Je as OAuthClientsApi,Xe as OAuthGrantsApi,Ze as OAuthProvidersApi,Qe as OAuthServerApi,Kt as ObjectsApi,qt as PendingAsksApi,s as Permission,Jt as ProcessApi,Yt as ProcessTestRunApi,Xt as QueryApi,it as RemoteMcpConnectionsApi,Zt as RenderingApi,$t as SchedulesApi,ot as SecretsApi,rn as StoreViewsApi,G as StreamSource,en as TaskApi,tn as TypeCatalogApi,nn as TypesApi,Q as VertesiaClient,pn as ViewsApi,an as WorkflowsApi,sn as WorkflowsDefinitionApi,on as WorkflowsRulesApi,ln as ZenoClient,It as ZenoClientNotFoundError,u as canGenerateRendition,H as createInteractionOutput,yn as decodeEndpoints,$ as decodeJWT,He as enhanceExecutionRun,B as enhanceInteractionExecutionResult,U as fetchSignedUrl,Z as getAgentArtifactPath,X as getMemoryFilePath,d as getOAuthPermissionScopes,f as getSupportedRenditionFormats,hn as isTokenExpired,At as openManagedEventSource,h as supportsVisualRendition};
14
13
  //# sourceMappingURL=vertesia-client.js.map