@asgard-js/core 0.3.28 → 0.3.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function(m,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(m=typeof globalThis<"u"?globalThis:m||self,w(m["@asgard-js/core"]={}))})(this,(function(m){"use strict";class w extends Error{status;statusText;body;constructor(t,e,r){super(`HTTP ${t}: ${e}`),this.name="HttpError",this.status=t,this.statusText=e,this.body=r}}function st(n){return n instanceof w}class V extends Error{runKind;constructor(t){super(`Cannot send a message while a "${t}" run is in flight on this channel.`),this.name="ChannelBusyError",this.runKind=t}}function it(n){return n instanceof V}var k=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(k||{}),l=(n=>(n.INIT="asgard.run.init",n.PROCESS="asgard.process",n.PROCESS_START="asgard.process.start",n.PROCESS_COMPLETE="asgard.process.complete",n.MESSAGE="asgard.message",n.MESSAGE_START="asgard.message.start",n.MESSAGE_DELTA="asgard.message.delta",n.MESSAGE_COMPLETE="asgard.message.complete",n.MESSAGE_USER="asgard.message.user",n.MESSAGE_THINKING_START="asgard.message.thinking.start",n.MESSAGE_THINKING_DELTA="asgard.message.thinking.delta",n.MESSAGE_THINKING_COMPLETE="asgard.message.thinking.complete",n.TOOL_CALL="asgard.tool_call",n.TOOL_CALL_START="asgard.tool_call.start",n.TOOL_CALL_COMPLETE="asgard.tool_call.complete",n.TOOL_CALL_CONSENT="asgard.tool_call.consent",n.SUBAGENT_START="asgard.subagent.start",n.SUBAGENT_COMPLETE="asgard.subagent.complete",n.CHANNEL_TITLE_UPDATE="asgard.channel.title.update",n.SANDBOX_LAUNCH="asgard.sandbox.launch",n.SANDBOX_READY="asgard.sandbox.ready",n.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(l||{}),le=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(le||{}),de=(n=>(n.TEXT="TEXT",n.HINT="HINT",n.BUTTON="BUTTON",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.LOCATION="LOCATION",n.CAROUSEL="CAROUSEL",n.CHART="CHART",n.TABLE="TABLE",n.ATTACHMENT="ATTACHMENT",n))(de||{});async function ot(n,t){const e=n.getReader();let r;for(;!(r=await e.read()).done;)t(r.value)}function at(n){let t,e,r,s=!1;return function(o){t===void 0?(t=o,e=0,r=-1):t=ut(t,o);const a=t.length;let c=0;for(;e<a;){s&&(t[e]===10&&(c=++e),s=!1);let u=-1;for(;e<a&&u===-1;++e)switch(t[e]){case 58:r===-1&&(r=e-c);break;case 13:s=!0;case 10:u=e;break}if(u===-1)break;n(t.subarray(c,u),r),c=e,r=-1}c===a?t=void 0:c!==0&&(t=t.subarray(c),e-=c)}}function ct(n,t,e){let r=he();const s=new TextDecoder;return function(o,a){if(o.length===0)e?.(r),r=he();else if(a>0){const c=s.decode(o.subarray(0,a)),u=a+(o[a+1]===32?2:1),h=s.decode(o.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
2
2
  `+h:h;break;case"event":r.event=h;break;case"id":n(r.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||t(r.retry=g);break}}}}function ut(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function he(){return{data:"",event:"",id:"",retry:void 0}}var lt=function(n,t){var e={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&t.indexOf(r)<0&&(e[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(n,r[s])&&(e[r[s]]=n[r[s]]);return e};const z="text/event-stream",dt=1e3,fe="last-event-id";function pe(n,t){var{signal:e,headers:r,onopen:s,onmessage:i,onclose:o,onerror:a,openWhenHidden:c,fetch:u}=t,h=lt(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,y)=>{const d=Object.assign({},r);d.accept||(d.accept=z);let p;function f(){p.abort(),document.hidden||ce()}c||document.addEventListener("visibilitychange",f);let U=dt,C=0;function M(){document.removeEventListener("visibilitychange",f),window.clearTimeout(C),p.abort()}e?.addEventListener("abort",()=>{M(),g()});const _n=u??window.fetch,Ln=s??ht;async function ce(){var ue;p=new AbortController;try{const X=await _n(n,Object.assign(Object.assign({},h),{headers:d,signal:p.signal}));await Ln(X),await ot(X.body,at(ct(_=>{_?d[fe]=_:delete d[fe]},_=>{U=_},i))),o?.(),M(),g()}catch(X){if(!p.signal.aborted)try{const _=(ue=a?.(X))!==null&&ue!==void 0?ue:U;window.clearTimeout(C),C=window.setTimeout(ce,_)}catch(_){M(),y(_)}}}ce()})}function ht(n){const t=n.headers.get("content-type");if(!t?.startsWith(z))throw new Error(`Expected content-type to be ${z}, Actual: ${t}`)}var J=function(n,t){return J=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,r){e.__proto__=r}||function(e,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])},J(n,t)};function I(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");J(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function ft(n,t,e,r){function s(i){return i instanceof e?i:new e(function(o){o(i)})}return new(e||(e=Promise))(function(i,o){function a(h){try{u(r.next(h))}catch(g){o(g)}}function c(h){try{u(r.throw(h))}catch(g){o(g)}}function u(h){h.done?i(h.value):s(h.value).then(a,c)}u((r=r.apply(n,t||[])).next())})}function me(n,t){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(h){return c([u,h])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(e=0)),e;)try{if(r=1,s&&(i=u[0]&2?s.return:u[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,u[1])).done)return i;switch(s=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,s=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){e.label=u[1];break}if(u[0]===6&&e.label<i[1]){e.label=i[1],i=u;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(u);break}i[2]&&e.ops.pop(),e.trys.pop();continue}u=t.call(n,e)}catch(h){u=[6,h],s=0}finally{r=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function R(n){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&n[t],r=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function H(n,t){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var r=e.call(n),s,i=[],o;try{for(;(t===void 0||t-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(e=r.return)&&e.call(r)}finally{if(o)throw o.error}}return i}function F(n,t,e){if(e||arguments.length===2)for(var r=0,s=t.length,i;r<s;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return n.concat(i||Array.prototype.slice.call(t))}function N(n){return this instanceof N?(this.v=n,this):new N(n)}function pt(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=e.apply(n,t||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(d){return function(p){return Promise.resolve(p).then(d,g)}}function a(d,p){r[d]&&(s[d]=function(f){return new Promise(function(U,C){i.push([d,f,U,C])>1||c(d,f)})},p&&(s[d]=p(s[d])))}function c(d,p){try{u(r[d](p))}catch(f){y(i[0][3],f)}}function u(d){d.value instanceof N?Promise.resolve(d.value.v).then(h,g):y(i[0][2],d)}function h(d){c("next",d)}function g(d){c("throw",d)}function y(d,p){d(p),i.shift(),i.length&&c(i[0][0],i[0][1])}}function mt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=n[Symbol.asyncIterator],e;return t?t.call(n):(n=typeof R=="function"?R(n):n[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(i){e[i]=n[i]&&function(o){return new Promise(function(a,c){o=n[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(u){i({value:u,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;function b(n){return typeof n=="function"}function ge(n){var t=function(r){Error.call(r),r.stack=new Error().stack},e=n(t);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var Q=ge(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
3
3
  `+e.map(function(r,s){return s+1+") "+r.toString()}).join(`
4
- `):"",this.name="UnsubscriptionError",this.errors=e}});function G(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var j=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,r,s,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=R(o),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(f){t={error:f}}finally{try{c&&!c.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else o.remove(this);var h=this.initialTeardown;if(b(h))try{h()}catch(f){i=f instanceof Q?f.errors:[f]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var y=R(g),d=y.next();!d.done;d=y.next()){var p=d.value;try{ye(p)}catch(f){i=i??[],f instanceof Q?i=F(F([],H(i)),H(f.errors)):i.push(f)}}}catch(f){r={error:f}}finally{try{d&&!d.done&&(s=y.return)&&s.call(y)}finally{if(r)throw r.error}}}if(i)throw new Q(i)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)ye(t);else{if(t instanceof n){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(t)}},n.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},n.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},n.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&G(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&G(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),be=j.EMPTY;function ve(n){return n instanceof j||n&&"closed"in n&&b(n.remove)&&b(n.add)&&b(n.unsubscribe)}function ye(n){b(n)?n():n.unsubscribe()}var gt={Promise:void 0},bt={setTimeout:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setTimeout.apply(void 0,F([n,t],H(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Se(n){bt.setTimeout(function(){throw n})}function Z(){}function q(n){n()}var ee=(function(n){I(t,n);function t(e){var r=n.call(this)||this;return r.isStopped=!1,e?(r.destination=e,ve(e)&&e.add(r)):r.destination=St,r}return t.create=function(e,r,s){return new te(e,r,s)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(j),vt=(function(){function n(t){this.partialObserver=t}return n.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(r){K(r)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(r){K(r)}else K(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){K(e)}},n})(),te=(function(n){I(t,n);function t(e,r,s){var i=n.call(this)||this,o;return b(e)||!e?o={next:e??void 0,error:r??void 0,complete:s??void 0}:o=e,i.destination=new vt(o),i}return t})(ee);function K(n){Se(n)}function yt(n){throw n}var St={closed:!0,next:Z,error:yt,complete:Z},ne=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Y(n){return n}function wt(n){return n.length===0?Y:n.length===1?n[0]:function(e){return n.reduce(function(r,s){return s(r)},e)}}var E=(function(){function n(t){t&&(this._subscribe=t)}return n.prototype.lift=function(t){var e=new n;return e.source=this,e.operator=t,e},n.prototype.subscribe=function(t,e,r){var s=this,i=It(t)?t:new te(t,e,r);return q(function(){var o=s,a=o.operator,c=o.source;i.add(a?a.call(i,c):c?s._subscribe(i):s._trySubscribe(i))}),i},n.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},n.prototype.forEach=function(t,e){var r=this;return e=we(e),new e(function(s,i){var o=new te({next:function(a){try{t(a)}catch(c){i(c),o.unsubscribe()}},error:i,complete:s});r.subscribe(o)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[ne]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return wt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=we(t),new t(function(r,s){var i;e.subscribe(function(o){return i=o},function(o){return s(o)},function(){return r(i)})})},n.create=function(t){return new n(t)},n})();function we(n){var t;return(t=n??gt.Promise)!==null&&t!==void 0?t:Promise}function Et(n){return n&&b(n.next)&&b(n.error)&&b(n.complete)}function It(n){return n&&n instanceof ee||Et(n)&&ve(n)}function Tt(n){return b(n?.lift)}function x(n){return function(t){if(Tt(t))return t.lift(function(e){try{return n(e,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function O(n,t,e,r,s){return new Ct(n,t,e,r,s)}var Ct=(function(n){I(t,n);function t(e,r,s,i,o,a){var c=n.call(this,e)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(u){try{r(u)}catch(h){e.error(h)}}:n.prototype._next,c._error=i?function(u){try{i(u)}catch(h){e.error(h)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=s?function(){try{s()}catch(u){e.error(u)}finally{this.unsubscribe()}}:n.prototype._complete,c}return t.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ee),xt=ge(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),re=(function(n){I(t,n);function t(){var e=n.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return t.prototype.lift=function(e){var r=new Ee(this,this);return r.operator=e,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new xt},t.prototype.next=function(e){var r=this;q(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=R(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(e)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(e){var r=this;q(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=e;for(var s=r.observers;s.length;)s.shift().error(e)}})},t.prototype.complete=function(){var e=this;q(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var r=e.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(e){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,e)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var r=this,s=this,i=s.hasError,o=s.isStopped,a=s.observers;return i||o?be:(this.currentObservers=null,a.push(e),new j(function(){r.currentObservers=null,G(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var r=this,s=r.hasError,i=r.thrownError,o=r.isStopped;s?e.error(i):o&&e.complete()},t.prototype.asObservable=function(){var e=new E;return e.source=this,e},t.create=function(e,r){return new Ee(e,r)},t})(E),Ee=(function(n){I(t,n);function t(e,r){var s=n.call(this)||this;return s.destination=e,s.source=r,s}return t.prototype.next=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,e)},t.prototype.error=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,e)},t.prototype.complete=function(){var e,r;(r=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||r===void 0||r.call(e)},t.prototype._subscribe=function(e){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(e))!==null&&s!==void 0?s:be},t})(re),A=(function(n){I(t,n);function t(e){var r=n.call(this)||this;return r._value=e,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var r=n.prototype._subscribe.call(this,e);return!r.closed&&e.next(this._value),r},t.prototype.getValue=function(){var e=this,r=e.hasError,s=e.thrownError,i=e._value;if(r)throw s;return this._throwIfClosed(),i},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(re),Ot={now:function(){return Date.now()}},At=(function(n){I(t,n);function t(e,r){return n.call(this)||this}return t.prototype.schedule=function(e,r){return this},t})(j),Ie={setInterval:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setInterval.apply(void 0,F([n,t],H(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Pt=(function(n){I(t,n);function t(e,r){var s=n.call(this,e,r)||this;return s.scheduler=e,s.work=r,s.pending=!1,s}return t.prototype.schedule=function(e,r){var s;if(r===void 0&&(r=0),this.closed)return this;this.state=e;var i=this.id,o=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(o,i,r)),this.pending=!0,this.delay=r,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(o,this.id,r),this},t.prototype.requestAsyncId=function(e,r,s){return s===void 0&&(s=0),Ie.setInterval(e.flush.bind(e,this),s)},t.prototype.recycleAsyncId=function(e,r,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return r;r!=null&&Ie.clearInterval(r)},t.prototype.execute=function(e,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(e,r);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,r){var s=!1,i;try{this.work(e)}catch(o){s=!0,i=o||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,r=e.id,s=e.scheduler,i=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,G(i,this),r!=null&&(this.id=this.recycleAsyncId(s,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(At),Te=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,r){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(r,e)},n.now=Ot.now,n})(),_t=(function(n){I(t,n);function t(e,r){r===void 0&&(r=Te.now);var s=n.call(this,e,r)||this;return s.actions=[],s._active=!1,s}return t.prototype.flush=function(e){var r=this.actions;if(this._active){r.push(e);return}var s;this._active=!0;do if(s=e.execute(e.state,e.delay))break;while(e=r.shift());if(this._active=!1,s){for(;e=r.shift();)e.unsubscribe();throw s}},t})(Te),Ce=new _t(Pt),Lt=Ce,Ut=new E(function(n){return n.complete()});function xe(n){return n&&b(n.schedule)}function Oe(n){return n[n.length-1]}function Mt(n){return b(Oe(n))?n.pop():void 0}function Ae(n){return xe(Oe(n))?n.pop():void 0}var Pe=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function _e(n){return b(n?.then)}function Le(n){return b(n[ne])}function Ue(n){return Symbol.asyncIterator&&b(n?.[Symbol.asyncIterator])}function Me(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function kt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ke=kt();function Re(n){return b(n?.[ke])}function Ne(n){return pt(this,arguments,function(){var e,r,s,i;return me(this,function(o){switch(o.label){case 0:e=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,N(e.read())];case 3:return r=o.sent(),s=r.value,i=r.done,i?[4,N(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,N(s)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function je(n){return b(n?.getReader)}function L(n){if(n instanceof E)return n;if(n!=null){if(Le(n))return Rt(n);if(Pe(n))return Nt(n);if(_e(n))return jt(n);if(Ue(n))return $e(n);if(Re(n))return $t(n);if(je(n))return Dt(n)}throw Me(n)}function Rt(n){return new E(function(t){var e=n[ne]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Nt(n){return new E(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function jt(n){return new E(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Se)})}function $t(n){return new E(function(t){var e,r;try{for(var s=R(n),i=s.next();!i.done;i=s.next()){var o=i.value;if(t.next(o),t.closed)return}}catch(a){e={error:a}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}t.complete()})}function $e(n){return new E(function(t){Ht(n,t).catch(function(e){return t.error(e)})})}function Dt(n){return $e(Ne(n))}function Ht(n,t){var e,r,s,i;return ft(this,void 0,void 0,function(){var o,a;return me(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=mt(n),c.label=1;case 1:return[4,e.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),s={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(i=e.return)?[4,i.call(e)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function P(n,t,e,r,s){r===void 0&&(r=0),s===void 0&&(s=!1);var i=t.schedule(function(){e(),s?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(i),!s)return i}function De(n,t){return t===void 0&&(t=0),x(function(e,r){e.subscribe(O(r,function(s){return P(r,n,function(){return r.next(s)},t)},function(){return P(r,n,function(){return r.complete()},t)},function(s){return P(r,n,function(){return r.error(s)},t)}))})}function He(n,t){return t===void 0&&(t=0),x(function(e,r){r.add(n.schedule(function(){return e.subscribe(r)},t))})}function Ft(n,t){return L(n).pipe(He(t),De(t))}function Bt(n,t){return L(n).pipe(He(t),De(t))}function Gt(n,t){return new E(function(e){var r=0;return t.schedule(function(){r===n.length?e.complete():(e.next(n[r++]),e.closed||this.schedule())})})}function qt(n,t){return new E(function(e){var r;return P(e,t,function(){r=n[ke](),P(e,t,function(){var s,i,o;try{s=r.next(),i=s.value,o=s.done}catch(a){e.error(a);return}o?e.complete():e.next(i)},0,!0)}),function(){return b(r?.return)&&r.return()}})}function Fe(n,t){if(!n)throw new Error("Iterable cannot be null");return new E(function(e){P(e,t,function(){var r=n[Symbol.asyncIterator]();P(e,t,function(){r.next().then(function(s){s.done?e.complete():e.next(s.value)})},0,!0)})})}function Kt(n,t){return Fe(Ne(n),t)}function Yt(n,t){if(n!=null){if(Le(n))return Ft(n,t);if(Pe(n))return Gt(n,t);if(_e(n))return Bt(n,t);if(Ue(n))return Fe(n,t);if(Re(n))return qt(n,t);if(je(n))return Kt(n,t)}throw Me(n)}function se(n,t){return t?Yt(n,t):L(n)}function Wt(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ae(n);return se(n,e)}function Xt(n){return n instanceof Date&&!isNaN(n)}function $(n,t){return x(function(e,r){var s=0;e.subscribe(O(r,function(i){r.next(n.call(t,i,s++))}))})}var Vt=Array.isArray;function zt(n,t){return Vt(t)?n.apply(void 0,F([],H(t))):n(t)}function Jt(n){return $(function(t){return zt(n,t)})}var Qt=Array.isArray,Zt=Object.getPrototypeOf,en=Object.prototype,tn=Object.keys;function nn(n){if(n.length===1){var t=n[0];if(Qt(t))return{args:t,keys:null};if(rn(t)){var e=tn(t);return{args:e.map(function(r){return t[r]}),keys:e}}}return{args:n,keys:null}}function rn(n){return n&&typeof n=="object"&&Zt(n)===en}function sn(n,t){return n.reduce(function(e,r,s){return e[r]=t[s],e},{})}function on(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ae(n),r=Mt(n),s=nn(n),i=s.args,o=s.keys;if(i.length===0)return se([],e);var a=new E(an(i,e,o?function(c){return sn(o,c)}:Y));return r?a.pipe(Jt(r)):a}function an(n,t,e){return e===void 0&&(e=Y),function(r){Be(t,function(){for(var s=n.length,i=new Array(s),o=s,a=s,c=function(h){Be(t,function(){var g=se(n[h],t),y=!1;g.subscribe(O(r,function(d){i[h]=d,y||(y=!0,a--),a||r.next(e(i.slice()))},function(){--o||r.complete()}))},r)},u=0;u<s;u++)c(u)},r)}}function Be(n,t,e){n?P(e,n,t):t()}function cn(n,t,e,r,s,i,o,a){var c=[],u=0,h=0,g=!1,y=function(){g&&!c.length&&!u&&t.complete()},d=function(f){return u<r?p(f):c.push(f)},p=function(f){u++;var U=!1;L(e(f,h++)).subscribe(O(t,function(C){t.next(C)},function(){U=!0},void 0,function(){if(U)try{u--;for(var C=function(){var M=c.shift();o||p(M)};c.length&&u<r;)C();y()}catch(M){t.error(M)}}))};return n.subscribe(O(t,d,function(){g=!0,y()})),function(){}}function W(n,t,e){return e===void 0&&(e=1/0),b(t)?W(function(r,s){return $(function(i,o){return t(r,i,s,o)})(L(n(r,s)))},e):(typeof t=="number"&&(e=t),x(function(r,s){return cn(r,s,n,e)}))}function un(n,t,e){n===void 0&&(n=0),e===void 0&&(e=Lt);var r=-1;return t!=null&&(xe(t)?e=t:r=t),new E(function(s){var i=Xt(n)?+n-e.now():n;i<0&&(i=0);var o=0;return e.schedule(function(){s.closed||(s.next(o++),0<=r?this.schedule(void 0,r):s.complete())},i)})}function ln(n,t){return b(t)?W(n,t,1):W(n,1)}function dn(n){return n<=0?function(){return Ut}:x(function(t,e){var r=0;t.subscribe(O(e,function(s){++r<=n&&(e.next(s),n<=r&&e.complete())}))})}function hn(n){return $(function(){return n})}function fn(n,t){return W(function(e,r){return L(n(e,r)).pipe(dn(1),hn(e))})}function pn(n,t){t===void 0&&(t=Ce);var e=un(n,t);return fn(function(){return e})}function D(n,t){return t===void 0&&(t=Y),n=n??mn,x(function(e,r){var s,i=!0;e.subscribe(O(r,function(o){var a=t(o);(i||!n(s,a))&&(i=!1,s=a,r.next(o))}))})}function mn(n,t){return n===t}function gn(n){return x(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function bn(n){return x(function(t,e){L(n).subscribe(O(e,function(){return e.complete()},Z)),!e.closed&&t.subscribe(e)})}function Ge(n){const{endpoint:t,apiKey:e,payload:r,debugMode:s,customHeaders:i}=n,o=n.method??"POST";return new E(a=>{const c=new AbortController;let u,h=!1,g=!1;const y={"Content-Type":"application/json",...i};e&&(y["X-API-KEY"]=e);const d=new URL(t);return s&&d.searchParams.set("is_debug","true"),pe(d.toString(),{method:o,headers:y,body:o==="POST"&&r?JSON.stringify(r):void 0,signal:c.signal,openWhenHidden:!0,onopen:async p=>{if(p.ok)u=p.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await p.json()}catch{try{f=await p.text()}catch{f=null}}a.error(new w(p.status,p.statusText,f)),c.abort()}},onmessage:p=>{p.id&&(h=!0);const f=JSON.parse(p.data);u?f.traceId=u:f.requestId&&(f.traceId=f.requestId,u||(u=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:p=>{if(g)throw p;if(!h)throw a.error(p),c.abort(),p}}),()=>{g=!0,c.abort()}})}class vn{listeners={};on(t,e){this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).concat(e)})}off(t,e){this.listeners[t]&&(this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).filter(r=>r!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(r=>r(...e))}}class yn{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new re;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new vn;transformSsePayload;customHeaders;constructor(t){if(!t.endpoint&&!t.botProviderEndpoint)throw new Error("Either endpoint or botProviderEndpoint must be provided");if(this.apiKey=t.apiKey,this.debugMode=t.debugMode,this.transformSsePayload=t.transformSsePayload,this.botProviderEndpoint=t.botProviderEndpoint,this.customHeaders={...t.customHeaders,...t.userIdentityHint?{"X-ASGARD-USER-IDENTITY-HINT":t.userIdentityHint}:{}},!t.endpoint&&t.botProviderEndpoint){const e=t.botProviderEndpoint.replace(/\/+$/,"");this.endpoint=`${e}/message/sse`}else t.endpoint&&(this.endpoint=t.endpoint,this.debugMode&&console.warn('[AsgardServiceClient] The "endpoint" option is deprecated and will be removed in the next major version. Please use "botProviderEndpoint" instead. The SSE endpoint will be automatically derived as "${botProviderEndpoint}/message/sse".'))}on(t,e){this.sseEmitter.remove(t),this.sseEmitter.on(t,e)}handleEvent(t){switch(t.eventType){case l.INIT:this.sseEmitter.emit(l.INIT,t);break;case l.PROCESS_START:case l.PROCESS_COMPLETE:this.sseEmitter.emit(l.PROCESS,t);break;case l.MESSAGE_START:case l.MESSAGE_DELTA:case l.MESSAGE_COMPLETE:this.sseEmitter.emit(l.MESSAGE,t);break;case l.TOOL_CALL_START:case l.TOOL_CALL_COMPLETE:this.sseEmitter.emit(l.TOOL_CALL,t);break;case l.TOOL_CALL_CONSENT:this.sseEmitter.emit(l.TOOL_CALL_CONSENT,t);break;case l.DONE:this.sseEmitter.emit(l.DONE,t);break;case l.ERROR:this.sseEmitter.emit(l.ERROR,t);break}}fetchSse(t,e){return e?.onSseStart?.(),this.inFlight+=1,this.runSse(Ge({apiKey:this.apiKey,endpoint:this.endpoint,debugMode:this.debugMode,payload:this.transformSsePayload?.(t)??t,customHeaders:this.customHeaders}),e)}rejoinSse(t,e){e?.onSseStart?.(),this.inFlight+=1;const r=new URL(this.endpoint);return r.searchParams.set("custom_channel_id",t),this.runSse(Ge({apiKey:this.apiKey,endpoint:r.toString(),debugMode:this.debugMode,method:"GET",customHeaders:this.customHeaders}),e)}deriveChannelMetadataEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel/metadata`:null}async channelMetadata(t){const e=this.deriveChannelMetadataEndpoint();if(!e)throw new Error("Unable to derive channel metadata endpoint. Please provide botProviderEndpoint in config.");const r=new URL(e);r.searchParams.set("custom_channel_id",t);const s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const i=await fetch(r.toString(),{method:"GET",headers:s});if(i.status===404)return null;if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.json(),a=o.data??o;return{title:a.title??null,runState:a.runState??"IDLE",lastActivityAt:a.lastActivityAt,launchedSandboxes:(a.launchedSandboxes??[]).map(c=>({sandboxName:c.sandboxName,sandboxBlueprintName:c.sandboxBlueprintName,workingDirectory:c.workingDirectory,editorServerEnabled:c.editorServerEnabled,browserEnabled:c.browserEnabled}))}}deriveSuspendEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/suspend`:null}async suspendChannel(t,e){const r=this.deriveSuspendEndpoint();if(!r)throw new Error("Unable to derive channel suspend endpoint. Please provide botProviderEndpoint in config.");const s=new URL(r);s.searchParams.set("custom_channel_id",t),e?.requestId&&s.searchParams.set("request_id",e.requestId),e?.force&&s.searchParams.set("force","true");const i=await fetch(s.toString(),{method:"POST",headers:this.apiHeaders()});if(!(i.ok||i.status===404))throw new w(i.status,i.statusText,await i.text().catch(()=>{}))}runSse(t,e){return t.pipe(ln(r=>Wt(r).pipe(pn(e?.delayTime??50))),bn(this.destroy$),gn(()=>this.onRunSettled())).subscribe({next:r=>{this.detached||(e?.onSseMessage?.(r),this.handleEvent(r))},error:r=>{this.detached||e?.onSseError?.(r)},complete:()=>{this.detached||e?.onSseCompleted?.()}})}detach(t){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),t.timeoutMs)}}onRunSettled(){this.inFlight=Math.max(0,this.inFlight-1),this.detached&&this.inFlight===0&&this.close()}close(){this.closed||(this.closed=!0,this.detachTimer&&(clearTimeout(this.detachTimer),this.detachTimer=void 0),this.destroy$.next(),this.destroy$.complete())}async uploadFile(t,e){const r=this.deriveBlobEndpoint();if(!r)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const s=new FormData;s.append("file",t),s.append("customChannelId",e);const i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const o=await fetch(r,{method:"POST",headers:i,body:s});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const a=await o.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(o){throw console.error("[AsgardServiceClient] File upload error:",o),o}}async downloadChannelHomeFile(t,e){const r=this.getBaseEndpoint();if(!r)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const s=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,i=`${r}/channel-home/download?${s}`,o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const a=await fetch(i,{method:"GET",headers:o});if(!a.ok)throw new Error(`Channel Home download failed: ${a.status} ${a.statusText}`);const c=await a.blob(),u=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] Channel Home download response:",{filename:u,size:c.size}),{blob:c,filename:u}}catch(a){throw console.error("[AsgardServiceClient] Channel Home download error:",a),a}}async generateSandboxBrowserOpenUrl(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox browser open-url endpoint. Please provide botProviderEndpoint in config.");const r=`${e}/sandbox/${encodeURIComponent(t)}/browser/open-url`,s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const i=await fetch(r,{method:"POST",headers:s});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.json(),a=o.data?.openURL??o.openURL;if(!a)throw new Error("Sandbox browser open-url response did not contain an openURL.");return a}deriveSandboxFsEndpoint(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox fs endpoint. Please provide botProviderEndpoint in config.");return`${e}/sandbox/${encodeURIComponent(t)}/fs`}apiHeaders(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async sandboxFsList(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/list`);r.searchParams.set("path",e);const s=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!s.ok)throw new w(s.status,s.statusText,await s.text().catch(()=>{}));const i=await s.json(),o=i.data??i;return{entries:o.entries??[],truncated:o.truncated??!1}}async sandboxFsRead(t,e,r){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);s.searchParams.set("path",e),r?.offsetBytes!=null&&s.searchParams.set("offset_bytes",String(r.offsetBytes)),r?.limitBytes!=null&&s.searchParams.set("limit_bytes",String(r.limitBytes));const i=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.blob(),a=i.headers.get("X-Total-Bytes");return{content:o,totalBytes:a!=null?Number(a):o.size,truncated:i.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,r,s){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);i.searchParams.set("path",e),s?.mode!=null&&i.searchParams.set("mode",String(s.mode)),s?.createOnly&&i.searchParams.set("create_only","true");const o=new FormData;o.append("file",r instanceof Blob?r:new Blob([r]));const a=await fetch(i.toString(),{method:"PUT",headers:this.apiHeaders(),body:o});if(!a.ok)throw new w(a.status,a.statusText,await a.text().catch(()=>{}));const c=await a.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,r,s){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(s).forEach(([a,c])=>i.searchParams.set(a,c));const o=await fetch(i.toString(),{method:r,headers:this.apiHeaders()});if(!o.ok)throw new w(o.status,o.statusText,await o.text().catch(()=>{}));return o.json().catch(()=>null)}async sandboxFsStat(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/stat`);r.searchParams.set("path",e);const s=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!s.ok)throw new w(s.status,s.statusText,await s.text().catch(()=>{}));const i=await s.json(),o=i.data??i;return{exists:o.exists??!1,isDir:o.isDir??!1,sizeBytes:o.sizeBytes??0,mtimeUnix:o.mtimeUnix??0,mode:o.mode??0,etag:o.etag}}async sandboxFsMkdir(t,e){await this.sandboxFsRequest(t,"mkdir","POST",{path:e})}async sandboxFsRemove(t,e){await this.sandboxFsRequest(t,"item","DELETE",{path:e})}async sandboxFsRemoveAll(t,e){await this.sandboxFsRequest(t,"all","DELETE",{path:e})}async sandboxFsCopy(t,e,r,s){const i={src:e,dst:r};s?.overwrite&&(i.overwrite="true");const o=await this.sandboxFsRequest(t,"copy","POST",i);return{bytesCopied:(o?.data??o)?.bytesCopied??0}}async sandboxFsMove(t,e,r,s){const i={src:e,dst:r};s?.overwrite&&(i.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",i)}sandboxFsWatch(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/watch`);return r.searchParams.set("path",e),new E(s=>{const i=new AbortController;return pe(r.toString(),{headers:this.apiHeaders(),signal:i.signal,openWhenHidden:!0,onopen:async o=>{if(!o.ok){const a=await o.text().catch(()=>{});s.error(new w(o.status,o.statusText,a)),i.abort()}},onmessage:o=>{o.event==="change"&&s.next(JSON.parse(o.data))},onclose:()=>s.complete(),onerror:o=>{throw s.error(o),i.abort(),o}}),()=>i.abort()})}deriveBlobEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/blob`:null}getBaseEndpoint(){let t=this.botProviderEndpoint;return!t&&this.endpoint&&(t=this.endpoint.replace("/message/sse","")),t?t.replace(/\/+$/,""):null}}const S=[];for(let n=0;n<256;++n)S.push((n+256).toString(16).slice(1));function Sn(n,t=0){return(S[n[t+0]]+S[n[t+1]]+S[n[t+2]]+S[n[t+3]]+"-"+S[n[t+4]]+S[n[t+5]]+"-"+S[n[t+6]]+S[n[t+7]]+"-"+S[n[t+8]]+S[n[t+9]]+"-"+S[n[t+10]]+S[n[t+11]]+S[n[t+12]]+S[n[t+13]]+S[n[t+14]]+S[n[t+15]]).toLowerCase()}let ie;const wn=new Uint8Array(16);function En(){if(!ie){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ie=crypto.getRandomValues.bind(crypto)}return ie(wn)}const qe={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function In(n,t,e){n=n||{};const r=n.random??n.rng?.()??En();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Sn(r)}function Ke(n,t,e){return qe.randomUUID&&!n?qe.randomUUID():In(n)}class v{messages=null;pendingConsent=null;constructor({messages:t,pendingConsent:e=null}){this.messages=t,this.pendingConsent=e??null}pushMessage(t){const e=new Map(this.messages);return e.set(t.messageId,t),new v({messages:e,pendingConsent:this.pendingConsent})}clearPendingConsent(){return this.pendingConsent?new v({messages:this.messages,pendingConsent:null}):this}settleInFlightMessages(){if(!this.messages)return this;let t=!1;const e=new Map(this.messages);for(const[r,s]of e)s.type==="tool-call"&&!s.isComplete&&(e.set(r,{...s,isComplete:!0,isCancelled:!0}),t=!0),s.type==="thinking"&&s.isThinking&&(e.set(r,{...s,isThinking:!1}),t=!0);return t?new v({messages:e,pendingConsent:this.pendingConsent}):this}cancelInFlightToolCalls(){return this.settleInFlightMessages()}onMessage(t){switch(t.eventType){case l.MESSAGE_START:return this.onMessageStart(t);case l.MESSAGE_DELTA:return this.onMessageDelta(t);case l.MESSAGE_COMPLETE:return this.onMessageComplete(t);case l.MESSAGE_USER:return this.onMessageUser(t);case l.MESSAGE_THINKING_START:return this.onThinkingStart(t);case l.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case l.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case l.TOOL_CALL_START:return this.onToolCallStart(t);case l.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case l.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case l.SUBAGENT_START:return this.onSubagentStart(t);case l.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case l.ERROR:return this.onMessageError(t);default:return this}}isTerminalBot(t){return t?.type==="bot"&&!t.isTyping}isTerminalThinking(t){return t?.type==="thinking"&&!t.isThinking}onMessageStart(t){const e=t.fact.messageStart.message;if(e.parentToolUseId)return this;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages);return r.set(e.messageId,{type:"bot",eventType:l.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new v({messages:r,pendingConsent:this.pendingConsent})}onMessageDelta(t){const e=t.fact.messageDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalBot(r))return this;const s=r?.type==="bot"?r:void 0,i=new Map(this.messages);return i.set(e.messageId,{type:"bot",eventType:l.MESSAGE_DELTA,isTyping:!0,typingText:`${s?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??s?.traceId,raw:s?.raw??""}),new v({messages:i,pendingConsent:this.pendingConsent})}onMessageComplete(t){const e=t.fact.messageComplete.message;if(e.parentToolUseId)return this;const r=new Map(this.messages),s=r.get(e.messageId);return r.set(e.messageId,{type:"bot",eventType:l.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??(s?.type==="bot"?s.traceId:void 0),raw:JSON.stringify(t)}),new v({messages:r,pendingConsent:this.pendingConsent})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(e.parentToolUseId)return this;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages),s={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return r.set(e.messageId,s),new v({messages:r,pendingConsent:this.pendingConsent})}onThinkingDelta(t){const e=t.fact.messageThinkingDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalThinking(r))return this;const s=r?.type==="thinking"?r:void 0,i=new Map(this.messages),o={type:"thinking",messageId:e.messageId,text:`${s?.text??""}${e.text}`,isThinking:!0,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return i.set(e.messageId,o),new v({messages:i,pendingConsent:this.pendingConsent})}onThinkingComplete(t){const e=t.fact.messageThinkingComplete.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId),s=r?.type==="thinking"?r:void 0,i=new Map(this.messages),o={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return i.set(e.messageId,o),new v({messages:i,pendingConsent:this.pendingConsent})}onMessageUser(t){const e=t.fact.messageUser;if((this.messages?.get(e.messageId)??(e.customMessageId?this.messages?.get(e.customMessageId):void 0))?.type==="user")return this;const s=new Map(this.messages),i={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return s.set(e.messageId,i),new v({messages:s,pendingConsent:this.pendingConsent})}onMessageError(t){const e=Ke(),r=t.fact.runError.error,s=new Map(this.messages);return s.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:r,time:new Date,traceId:t.traceId}),new v({messages:s,pendingConsent:this.pendingConsent})}onToolCallStart(t){const e=t.fact.toolCallStart,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,i={type:"tool-call",eventType:l.TOOL_CALL_START,messageId:s,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,isComplete:!1,time:new Date,traceId:t.traceId};return r.set(s,i),new v({messages:r,pendingConsent:this.pendingConsent})}onToolCallComplete(t){const e=t.fact.toolCallComplete,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,i=r.get(s);if(i?.type==="tool-call"){const o={...i,eventType:l.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??i.traceId};r.set(s,o)}return new v({messages:r,pendingConsent:this.pendingConsent})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new v({messages:this.messages,pendingConsent:e})}onSubagentStart(t){const e=t.fact.subagentStart,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:start`,i={type:"subagent",messageId:s,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return r.set(s,i),new v({messages:r,pendingConsent:this.pendingConsent})}onSubagentComplete(t){const e=t.fact.subagentComplete,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:complete`,i={type:"subagent",messageId:s,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return r.set(s,i),new v({messages:r,pendingConsent:this.pendingConsent})}}const Tn=new Set(["TaskCreate","TaskUpdate"]);function Ye(n){return n.toolsetName===""&&Tn.has(n.toolName)}function We(n){return typeof n=="object"&&n!==null?n:void 0}function T(n){return typeof n=="string"?n:void 0}function Xe(n){const t=[],e=new Map;for(const r of n){const s=r.parameter??{},i=r.sidecar??{};if(r.toolName==="TaskCreate"){const o=We(i.task),a=T(o?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:T(s.subject)||T(o?.subject)||"",activeForm:T(s.activeForm),description:T(s.description),status:e.get(a)?.status??"pending"})}else if(r.toolName==="TaskUpdate"){const o=We(i.statusChange),a=T(s.taskId)||T(i.taskId),c=T(o?.to)||T(s.status);if(!a||!c)continue;const u=e.get(a);u&&e.set(a,{...u,status:c})}}return t.map(r=>e.get(r))}function Ve(n){return n.toolsetName===""&&n.toolName==="Agent"}function ze(n){return!!n}function Je(n){const t=[],e=new Map,r=new Map,s=i=>(e.has(i)||(t.push(i),e.set(i,{status:"running"}),r.set(i,new Map)),e.get(i));for(const i of n)switch(i.kind){case"agentStart":{const o=s(i.toolUseId);i.description&&!o.description&&(o.description=i.description);break}case"subagentStart":{const o=s(i.parentToolUseId);o.agentId=i.agentId??o.agentId,o.subagentType=i.subagentType??o.subagentType,o.description=i.description??o.description;break}case"toolStart":{s(i.parentToolUseId),r.get(i.parentToolUseId).set(i.toolUseId,{toolsetName:i.toolsetName,toolName:i.toolName,parameter:i.parameter??{},reason:i.reason,status:"running"});break}case"toolComplete":{const o=r.get(i.parentToolUseId)?.get(i.toolUseId);o&&(o.status=i.isError?"error":"completed");break}case"subagentComplete":{const o=s(i.parentToolUseId);o.status=i.status,o.summary=i.summary;break}}return t.map(i=>({parentToolUseId:i,...e.get(i),tools:Array.from(r.get(i).values())}))}function Cn(n){return typeof n=="string"?n:void 0}function Qe(n){const t=[];for(const e of n){if(e.type==="tool-call"&&Ve(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:Cn(e.parameter.description)});continue}if(e.type==="tool-call"&&ze(e.parentToolUseId)){const r=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:r,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:r,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function Ze(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Ye(e));return Xe(t)}function et(n){return Je(Qe(Array.from(n.messages?.values()??[])))}function tt(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.id===s.id&&e.status===s.status&&e.subject===s.subject&&e.activeForm===s.activeForm&&e.description===s.description})}function xn(n,t){return n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.toolName===s.toolName&&e.toolsetName===s.toolsetName&&e.status===s.status&&e.reason===s.reason})}function nt(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.parentToolUseId===s.parentToolUseId&&e.status===s.status&&e.subagentType===s.subagentType&&e.description===s.description&&e.summary===s.summary&&xn(e.tools,s.tools)})}function rt(n){const t=new A([]),e=new A([]),r=new j;return r.add(n.pipe($(Ze),D(tt)).subscribe(t)),r.add(n.pipe($(et),D(nt)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>r.unsubscribe()}}function oe(n){const t=new Map;for(const e of n)t.set(e.sandboxName,e);return[...t.values()].sort((e,r)=>(e.sandboxBlueprintName||e.sandboxName).localeCompare(r.sandboxBlueprintName||r.sandboxName))}const ae={kind:null,stopPhase:"idle"},On=1e4;function An(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class B{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;sandboxPhaseSubject;launchedSandboxesSubject;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;sandboxPhase$;launchedSandboxes$;runStatus$;currentUserMessageId;lastSentMessageId;currentRun;forceStopTimer;constructor(t){if(!t.client)throw new Error("client must be required");if(!t.customChannelId)throw new Error("customChannelId must be required");this.client=t.client,this.customChannelId=t.customChannelId,this.customMessageId=t.customMessageId,this.joinRunState=t.runState??"IDLE",this.isConnecting$=new A(!1),this.runStatusSubject=new A(ae),this.conversation$=new A(t.conversation),this.channelTitleSubject=new A(t.channelTitle??null),this.sandboxPhaseSubject=new A("idle"),this.launchedSandboxesSubject=new A(oe(t.launchedSandboxes??[])),this.derivedStores=rt(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(D()),this.sandboxPhase$=this.sandboxPhaseSubject.pipe(D()),this.launchedSandboxes$=this.launchedSandboxesSubject.pipe(D()),this.runStatus$=this.runStatusSubject.pipe(D(An)),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}getSandboxPhase(){return this.sandboxPhaseSubject.value}getLaunchedSandboxes(){return this.launchedSandboxesSubject.value}getRunStatus(){return this.runStatusSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=oe(t);this.pendingLaunches=this.pendingLaunches.filter(r=>!e.some(s=>s.sandboxName===r)),this.launchedSandboxesSubject.next(e)}dropSandbox(t){const e=this.launchedSandboxesSubject.value,r=e.filter(s=>s.sandboxName!==t);r.length!==e.length&&this.launchedSandboxesSubject.next(r)}noteSandboxLaunch(t){this.pendingLaunches.includes(t)||(this.pendingLaunches=[...this.pendingLaunches,t]),this.refetchMetadata()}async refetchMetadata(){if(!this.client.channelMetadata)return;const t=await this.client.channelMetadata(this.customChannelId);t&&this.applyLaunchedSandboxes(t.launchedSandboxes)}setChannelTitle(t){this.channelTitleSubject.next(t)}static create(t){const e=new B(t);return e.subscribe(),e}static async reset(t,e,r,s){const i=new B(t);try{return i.subscribe(),s?.(i),await i.resetChannel(e,r),i}catch(o){throw i.close(),o}}static async restore(t,e,r){const s=new B(t);try{return s.subscribe(),r?.(s),await s.rejoinChannel(e),s}catch(i){throw s.close(),i}}subscribe(){this.statesSubscription=on([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe($(([t,e,r,s,i,o,a,c])=>({isConnecting:t,conversation:e,tasks:r,subagents:s,channelTitle:i,sandboxPhase:o,launchedSandboxes:a,runStatus:c}))).subscribe(this.statesObserver)}resolvePayload(t){if(typeof t=="function")try{return t()}catch(e){throw new Error(`Failed to resolve payload function: ${e instanceof Error?e.message:String(e)}`)}return t}updateSandboxPhase(t){switch(t){case l.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case l.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case l.INIT:case l.ERROR:this.sandboxPhaseSubject.next("idle");break}}buildRunHandlers(t,e,r){return{onSseStart:t?.onSseStart,onSseMessage:s=>{if(t?.onSseMessage?.(s),this.captureRequestId(s.requestId),s.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(s.fact.channelTitleUpdate.title),this.updateSandboxPhase(s.eventType),s.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(s.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&s.traceId){const i=new Map(this.conversation$.value.messages),o=i.get(this.currentUserMessageId);o&&o.type==="user"&&(i.set(this.currentUserMessageId,{...o,traceId:s.traceId}),this.conversation$.next(new v({messages:i}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(s))},onSseError:s=>{t?.onSseError?.(s),this.settleRun(),r(s)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.settleRun(),e()}}}settleRun(){const t=this.runStatusSubject.value.stopPhase!=="idle";this.clearForceStopTimer(),this.isConnecting$.next(!1),this.runStatusSubject.next(ae),this.currentUserMessageId=void 0,this.currentRun=void 0,t&&this.conversation$.next(this.conversation$.value.settleInFlightMessages())}captureRequestId(t){const e=this.runStatusSubject.value;!t||e.requestId||!e.kind||this.runStatusSubject.next({...e,requestId:t})}clearForceStopTimer(){this.forceStopTimer&&(clearTimeout(this.forceStopTimer),this.forceStopTimer=void 0)}fetchSse(t,e,r){return new Promise((s,i)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(r,s,i))})}rejoinChannel(t){return new Promise((e,r)=>{if(!this.client.rejoinSse){e();return}this.isConnecting$.next(!0),this.runStatusSubject.next({kind:this.joinRunState==="RUNNING"?"restore":"replay",stopPhase:"idle"}),this.currentRun=this.client.rejoinSse(this.customChannelId,this.buildRunHandlers(t,e,r))})}resetChannel(t,e){return this.fetchSse("reset",{action:k.RESET_CHANNEL,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const r=this.runStatusSubject.value.kind;if(r)return Promise.reject(new V(r));const s=t.text.trim(),i=t.customMessageId??Ke();return this.currentUserMessageId=i,this.lastSentMessageId=i,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:i,text:s,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:k.NONE,customChannelId:this.customChannelId,customMessageId:i,payload:this.resolvePayload(t?.payload),text:s,blobIds:t?.blobIds},e)}replyToolCallConsents(t,e,r){return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse("user",{action:k.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(r),text:"",toolCallConsents:t},e)}nudge(t){return this.fetchSse("nudge",{action:k.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,text:""},t)}async stopGeneration(t){const e=this.runStatusSubject.value;if(!(!this.currentRun||e.kind!=="user")&&!(e.stopPhase!=="idle"&&!t?.force)){if(!this.client.suspendChannel){this.abortConnection();return}this.clearForceStopTimer(),this.runStatusSubject.next({...e,stopPhase:"stopping"});try{await this.client.suspendChannel(this.customChannelId,{requestId:e.requestId,force:t?.force})}catch(r){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),r}this.armForceStopTimer()}}armForceStopTimer(){this.clearForceStopTimer(),this.forceStopTimer=setTimeout(()=>{this.forceStopTimer=void 0;const t=this.runStatusSubject.value;t.stopPhase==="stopping"&&this.runStatusSubject.next({...t,stopPhase:"force-stoppable"})},On)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(ae),this.currentUserMessageId=void 0,this.conversation$.next(this.conversation$.value.settleInFlightMessages()))}close(){this.currentRun?.unsubscribe(),this.currentRun=void 0,this.clearForceStopTimer(),this.isConnecting$.complete(),this.runStatusSubject.complete(),this.conversation$.complete(),this.channelTitleSubject.complete(),this.sandboxPhaseSubject.complete(),this.launchedSandboxesSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}function Pn(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),r=t[2],s=new URLSearchParams(t[3]??"");if(r==="open-browser")return{kind:"open-browser",sandboxName:e};if(r==="open-file"){const i=s.get("absolute_path");return i?{kind:"open-file",sandboxName:e,absolutePath:i}:null}return null}m.AsgardServiceClient=yn,m.Channel=B,m.ChannelBusyError=V,m.Conversation=v,m.EventType=l,m.FetchSseAction=k,m.HttpError=w,m.MessageTemplateType=de,m.ToolCallConsentResult=le,m.conversationToSubagentEvents=Qe,m.createDerivedStores=rt,m.deriveSubagents=et,m.deriveTasks=Ze,m.isAgentTool=Ve,m.isChannelBusyError=it,m.isHttpError=st,m.isSubagentChildTool=ze,m.isTaskTool=Ye,m.reconcileLaunched=oe,m.reduceSubagents=Je,m.reduceTaskEvents=Xe,m.resolveSandboxUri=Pn,m.subagentsEqual=nt,m.tasksEqual=tt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
4
+ `):"",this.name="UnsubscriptionError",this.errors=e}});function G(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var j=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,r,s,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=R(o),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(f){t={error:f}}finally{try{c&&!c.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else o.remove(this);var h=this.initialTeardown;if(b(h))try{h()}catch(f){i=f instanceof Q?f.errors:[f]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var y=R(g),d=y.next();!d.done;d=y.next()){var p=d.value;try{ye(p)}catch(f){i=i??[],f instanceof Q?i=F(F([],H(i)),H(f.errors)):i.push(f)}}}catch(f){r={error:f}}finally{try{d&&!d.done&&(s=y.return)&&s.call(y)}finally{if(r)throw r.error}}}if(i)throw new Q(i)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)ye(t);else{if(t instanceof n){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(t)}},n.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},n.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},n.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&G(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&G(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),be=j.EMPTY;function ve(n){return n instanceof j||n&&"closed"in n&&b(n.remove)&&b(n.add)&&b(n.unsubscribe)}function ye(n){b(n)?n():n.unsubscribe()}var gt={Promise:void 0},bt={setTimeout:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setTimeout.apply(void 0,F([n,t],H(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Se(n){bt.setTimeout(function(){throw n})}function Z(){}function q(n){n()}var ee=(function(n){I(t,n);function t(e){var r=n.call(this)||this;return r.isStopped=!1,e?(r.destination=e,ve(e)&&e.add(r)):r.destination=St,r}return t.create=function(e,r,s){return new te(e,r,s)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(j),vt=(function(){function n(t){this.partialObserver=t}return n.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(r){K(r)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(r){K(r)}else K(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){K(e)}},n})(),te=(function(n){I(t,n);function t(e,r,s){var i=n.call(this)||this,o;return b(e)||!e?o={next:e??void 0,error:r??void 0,complete:s??void 0}:o=e,i.destination=new vt(o),i}return t})(ee);function K(n){Se(n)}function yt(n){throw n}var St={closed:!0,next:Z,error:yt,complete:Z},ne=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Y(n){return n}function wt(n){return n.length===0?Y:n.length===1?n[0]:function(e){return n.reduce(function(r,s){return s(r)},e)}}var E=(function(){function n(t){t&&(this._subscribe=t)}return n.prototype.lift=function(t){var e=new n;return e.source=this,e.operator=t,e},n.prototype.subscribe=function(t,e,r){var s=this,i=It(t)?t:new te(t,e,r);return q(function(){var o=s,a=o.operator,c=o.source;i.add(a?a.call(i,c):c?s._subscribe(i):s._trySubscribe(i))}),i},n.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},n.prototype.forEach=function(t,e){var r=this;return e=we(e),new e(function(s,i){var o=new te({next:function(a){try{t(a)}catch(c){i(c),o.unsubscribe()}},error:i,complete:s});r.subscribe(o)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[ne]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return wt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=we(t),new t(function(r,s){var i;e.subscribe(function(o){return i=o},function(o){return s(o)},function(){return r(i)})})},n.create=function(t){return new n(t)},n})();function we(n){var t;return(t=n??gt.Promise)!==null&&t!==void 0?t:Promise}function Et(n){return n&&b(n.next)&&b(n.error)&&b(n.complete)}function It(n){return n&&n instanceof ee||Et(n)&&ve(n)}function Tt(n){return b(n?.lift)}function x(n){return function(t){if(Tt(t))return t.lift(function(e){try{return n(e,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function O(n,t,e,r,s){return new Ct(n,t,e,r,s)}var Ct=(function(n){I(t,n);function t(e,r,s,i,o,a){var c=n.call(this,e)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(u){try{r(u)}catch(h){e.error(h)}}:n.prototype._next,c._error=i?function(u){try{i(u)}catch(h){e.error(h)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=s?function(){try{s()}catch(u){e.error(u)}finally{this.unsubscribe()}}:n.prototype._complete,c}return t.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ee),xt=ge(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),re=(function(n){I(t,n);function t(){var e=n.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return t.prototype.lift=function(e){var r=new Ee(this,this);return r.operator=e,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new xt},t.prototype.next=function(e){var r=this;q(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=R(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(e)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(e){var r=this;q(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=e;for(var s=r.observers;s.length;)s.shift().error(e)}})},t.prototype.complete=function(){var e=this;q(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var r=e.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(e){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,e)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var r=this,s=this,i=s.hasError,o=s.isStopped,a=s.observers;return i||o?be:(this.currentObservers=null,a.push(e),new j(function(){r.currentObservers=null,G(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var r=this,s=r.hasError,i=r.thrownError,o=r.isStopped;s?e.error(i):o&&e.complete()},t.prototype.asObservable=function(){var e=new E;return e.source=this,e},t.create=function(e,r){return new Ee(e,r)},t})(E),Ee=(function(n){I(t,n);function t(e,r){var s=n.call(this)||this;return s.destination=e,s.source=r,s}return t.prototype.next=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,e)},t.prototype.error=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,e)},t.prototype.complete=function(){var e,r;(r=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||r===void 0||r.call(e)},t.prototype._subscribe=function(e){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(e))!==null&&s!==void 0?s:be},t})(re),A=(function(n){I(t,n);function t(e){var r=n.call(this)||this;return r._value=e,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var r=n.prototype._subscribe.call(this,e);return!r.closed&&e.next(this._value),r},t.prototype.getValue=function(){var e=this,r=e.hasError,s=e.thrownError,i=e._value;if(r)throw s;return this._throwIfClosed(),i},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(re),Ot={now:function(){return Date.now()}},At=(function(n){I(t,n);function t(e,r){return n.call(this)||this}return t.prototype.schedule=function(e,r){return this},t})(j),Ie={setInterval:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setInterval.apply(void 0,F([n,t],H(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Pt=(function(n){I(t,n);function t(e,r){var s=n.call(this,e,r)||this;return s.scheduler=e,s.work=r,s.pending=!1,s}return t.prototype.schedule=function(e,r){var s;if(r===void 0&&(r=0),this.closed)return this;this.state=e;var i=this.id,o=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(o,i,r)),this.pending=!0,this.delay=r,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(o,this.id,r),this},t.prototype.requestAsyncId=function(e,r,s){return s===void 0&&(s=0),Ie.setInterval(e.flush.bind(e,this),s)},t.prototype.recycleAsyncId=function(e,r,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return r;r!=null&&Ie.clearInterval(r)},t.prototype.execute=function(e,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(e,r);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,r){var s=!1,i;try{this.work(e)}catch(o){s=!0,i=o||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,r=e.id,s=e.scheduler,i=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,G(i,this),r!=null&&(this.id=this.recycleAsyncId(s,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(At),Te=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,r){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(r,e)},n.now=Ot.now,n})(),_t=(function(n){I(t,n);function t(e,r){r===void 0&&(r=Te.now);var s=n.call(this,e,r)||this;return s.actions=[],s._active=!1,s}return t.prototype.flush=function(e){var r=this.actions;if(this._active){r.push(e);return}var s;this._active=!0;do if(s=e.execute(e.state,e.delay))break;while(e=r.shift());if(this._active=!1,s){for(;e=r.shift();)e.unsubscribe();throw s}},t})(Te),Ce=new _t(Pt),Lt=Ce,Ut=new E(function(n){return n.complete()});function xe(n){return n&&b(n.schedule)}function Oe(n){return n[n.length-1]}function Mt(n){return b(Oe(n))?n.pop():void 0}function Ae(n){return xe(Oe(n))?n.pop():void 0}var Pe=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function _e(n){return b(n?.then)}function Le(n){return b(n[ne])}function Ue(n){return Symbol.asyncIterator&&b(n?.[Symbol.asyncIterator])}function Me(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function kt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ke=kt();function Re(n){return b(n?.[ke])}function Ne(n){return pt(this,arguments,function(){var e,r,s,i;return me(this,function(o){switch(o.label){case 0:e=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,N(e.read())];case 3:return r=o.sent(),s=r.value,i=r.done,i?[4,N(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,N(s)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function je(n){return b(n?.getReader)}function L(n){if(n instanceof E)return n;if(n!=null){if(Le(n))return Rt(n);if(Pe(n))return Nt(n);if(_e(n))return jt(n);if(Ue(n))return $e(n);if(Re(n))return $t(n);if(je(n))return Dt(n)}throw Me(n)}function Rt(n){return new E(function(t){var e=n[ne]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Nt(n){return new E(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function jt(n){return new E(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Se)})}function $t(n){return new E(function(t){var e,r;try{for(var s=R(n),i=s.next();!i.done;i=s.next()){var o=i.value;if(t.next(o),t.closed)return}}catch(a){e={error:a}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}t.complete()})}function $e(n){return new E(function(t){Ht(n,t).catch(function(e){return t.error(e)})})}function Dt(n){return $e(Ne(n))}function Ht(n,t){var e,r,s,i;return ft(this,void 0,void 0,function(){var o,a;return me(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=mt(n),c.label=1;case 1:return[4,e.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),s={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(i=e.return)?[4,i.call(e)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function P(n,t,e,r,s){r===void 0&&(r=0),s===void 0&&(s=!1);var i=t.schedule(function(){e(),s?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(i),!s)return i}function De(n,t){return t===void 0&&(t=0),x(function(e,r){e.subscribe(O(r,function(s){return P(r,n,function(){return r.next(s)},t)},function(){return P(r,n,function(){return r.complete()},t)},function(s){return P(r,n,function(){return r.error(s)},t)}))})}function He(n,t){return t===void 0&&(t=0),x(function(e,r){r.add(n.schedule(function(){return e.subscribe(r)},t))})}function Ft(n,t){return L(n).pipe(He(t),De(t))}function Bt(n,t){return L(n).pipe(He(t),De(t))}function Gt(n,t){return new E(function(e){var r=0;return t.schedule(function(){r===n.length?e.complete():(e.next(n[r++]),e.closed||this.schedule())})})}function qt(n,t){return new E(function(e){var r;return P(e,t,function(){r=n[ke](),P(e,t,function(){var s,i,o;try{s=r.next(),i=s.value,o=s.done}catch(a){e.error(a);return}o?e.complete():e.next(i)},0,!0)}),function(){return b(r?.return)&&r.return()}})}function Fe(n,t){if(!n)throw new Error("Iterable cannot be null");return new E(function(e){P(e,t,function(){var r=n[Symbol.asyncIterator]();P(e,t,function(){r.next().then(function(s){s.done?e.complete():e.next(s.value)})},0,!0)})})}function Kt(n,t){return Fe(Ne(n),t)}function Yt(n,t){if(n!=null){if(Le(n))return Ft(n,t);if(Pe(n))return Gt(n,t);if(_e(n))return Bt(n,t);if(Ue(n))return Fe(n,t);if(Re(n))return qt(n,t);if(je(n))return Kt(n,t)}throw Me(n)}function se(n,t){return t?Yt(n,t):L(n)}function Wt(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ae(n);return se(n,e)}function Xt(n){return n instanceof Date&&!isNaN(n)}function $(n,t){return x(function(e,r){var s=0;e.subscribe(O(r,function(i){r.next(n.call(t,i,s++))}))})}var Vt=Array.isArray;function zt(n,t){return Vt(t)?n.apply(void 0,F([],H(t))):n(t)}function Jt(n){return $(function(t){return zt(n,t)})}var Qt=Array.isArray,Zt=Object.getPrototypeOf,en=Object.prototype,tn=Object.keys;function nn(n){if(n.length===1){var t=n[0];if(Qt(t))return{args:t,keys:null};if(rn(t)){var e=tn(t);return{args:e.map(function(r){return t[r]}),keys:e}}}return{args:n,keys:null}}function rn(n){return n&&typeof n=="object"&&Zt(n)===en}function sn(n,t){return n.reduce(function(e,r,s){return e[r]=t[s],e},{})}function on(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ae(n),r=Mt(n),s=nn(n),i=s.args,o=s.keys;if(i.length===0)return se([],e);var a=new E(an(i,e,o?function(c){return sn(o,c)}:Y));return r?a.pipe(Jt(r)):a}function an(n,t,e){return e===void 0&&(e=Y),function(r){Be(t,function(){for(var s=n.length,i=new Array(s),o=s,a=s,c=function(h){Be(t,function(){var g=se(n[h],t),y=!1;g.subscribe(O(r,function(d){i[h]=d,y||(y=!0,a--),a||r.next(e(i.slice()))},function(){--o||r.complete()}))},r)},u=0;u<s;u++)c(u)},r)}}function Be(n,t,e){n?P(e,n,t):t()}function cn(n,t,e,r,s,i,o,a){var c=[],u=0,h=0,g=!1,y=function(){g&&!c.length&&!u&&t.complete()},d=function(f){return u<r?p(f):c.push(f)},p=function(f){u++;var U=!1;L(e(f,h++)).subscribe(O(t,function(C){t.next(C)},function(){U=!0},void 0,function(){if(U)try{u--;for(var C=function(){var M=c.shift();o||p(M)};c.length&&u<r;)C();y()}catch(M){t.error(M)}}))};return n.subscribe(O(t,d,function(){g=!0,y()})),function(){}}function W(n,t,e){return e===void 0&&(e=1/0),b(t)?W(function(r,s){return $(function(i,o){return t(r,i,s,o)})(L(n(r,s)))},e):(typeof t=="number"&&(e=t),x(function(r,s){return cn(r,s,n,e)}))}function un(n,t,e){n===void 0&&(n=0),e===void 0&&(e=Lt);var r=-1;return t!=null&&(xe(t)?e=t:r=t),new E(function(s){var i=Xt(n)?+n-e.now():n;i<0&&(i=0);var o=0;return e.schedule(function(){s.closed||(s.next(o++),0<=r?this.schedule(void 0,r):s.complete())},i)})}function ln(n,t){return b(t)?W(n,t,1):W(n,1)}function dn(n){return n<=0?function(){return Ut}:x(function(t,e){var r=0;t.subscribe(O(e,function(s){++r<=n&&(e.next(s),n<=r&&e.complete())}))})}function hn(n){return $(function(){return n})}function fn(n,t){return W(function(e,r){return L(n(e,r)).pipe(dn(1),hn(e))})}function pn(n,t){t===void 0&&(t=Ce);var e=un(n,t);return fn(function(){return e})}function D(n,t){return t===void 0&&(t=Y),n=n??mn,x(function(e,r){var s,i=!0;e.subscribe(O(r,function(o){var a=t(o);(i||!n(s,a))&&(i=!1,s=a,r.next(o))}))})}function mn(n,t){return n===t}function gn(n){return x(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function bn(n){return x(function(t,e){L(n).subscribe(O(e,function(){return e.complete()},Z)),!e.closed&&t.subscribe(e)})}function Ge(n){const{endpoint:t,apiKey:e,payload:r,debugMode:s,customHeaders:i}=n,o=n.method??"POST";return new E(a=>{const c=new AbortController;let u,h=!1,g=!1;const y={"Content-Type":"application/json",...i};e&&(y["X-API-KEY"]=e);const d=new URL(t);return s&&d.searchParams.set("is_debug","true"),pe(d.toString(),{method:o,headers:y,body:o==="POST"&&r?JSON.stringify(r):void 0,signal:c.signal,openWhenHidden:!0,onopen:async p=>{if(p.ok)u=p.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await p.json()}catch{try{f=await p.text()}catch{f=null}}a.error(new w(p.status,p.statusText,f)),c.abort()}},onmessage:p=>{p.id&&(h=!0);const f=JSON.parse(p.data);u?f.traceId=u:f.requestId&&(f.traceId=f.requestId,u||(u=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:p=>{if(g)throw p;if(!h)throw a.error(p),c.abort(),p}}),()=>{g=!0,c.abort()}})}class vn{listeners={};on(t,e){this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).concat(e)})}off(t,e){this.listeners[t]&&(this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).filter(r=>r!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(r=>r(...e))}}class yn{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new re;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new vn;transformSsePayload;customHeaders;constructor(t){if(!t.endpoint&&!t.botProviderEndpoint)throw new Error("Either endpoint or botProviderEndpoint must be provided");if(this.apiKey=t.apiKey,this.debugMode=t.debugMode,this.transformSsePayload=t.transformSsePayload,this.botProviderEndpoint=t.botProviderEndpoint,this.customHeaders={...t.customHeaders,...t.userIdentityHint?{"X-ASGARD-USER-IDENTITY-HINT":t.userIdentityHint}:{}},!t.endpoint&&t.botProviderEndpoint){const e=t.botProviderEndpoint.replace(/\/+$/,"");this.endpoint=`${e}/message/sse`}else t.endpoint&&(this.endpoint=t.endpoint,this.debugMode&&console.warn('[AsgardServiceClient] The "endpoint" option is deprecated and will be removed in the next major version. Please use "botProviderEndpoint" instead. The SSE endpoint will be automatically derived as "${botProviderEndpoint}/message/sse".'))}on(t,e){this.sseEmitter.remove(t),this.sseEmitter.on(t,e)}handleEvent(t){switch(t.eventType){case l.INIT:this.sseEmitter.emit(l.INIT,t);break;case l.PROCESS_START:case l.PROCESS_COMPLETE:this.sseEmitter.emit(l.PROCESS,t);break;case l.MESSAGE_START:case l.MESSAGE_DELTA:case l.MESSAGE_COMPLETE:this.sseEmitter.emit(l.MESSAGE,t);break;case l.TOOL_CALL_START:case l.TOOL_CALL_COMPLETE:this.sseEmitter.emit(l.TOOL_CALL,t);break;case l.TOOL_CALL_CONSENT:this.sseEmitter.emit(l.TOOL_CALL_CONSENT,t);break;case l.DONE:this.sseEmitter.emit(l.DONE,t);break;case l.ERROR:this.sseEmitter.emit(l.ERROR,t);break}}fetchSse(t,e){return e?.onSseStart?.(),this.inFlight+=1,this.runSse(Ge({apiKey:this.apiKey,endpoint:this.endpoint,debugMode:this.debugMode,payload:this.transformSsePayload?.(t)??t,customHeaders:this.customHeaders}),e)}rejoinSse(t,e){e?.onSseStart?.(),this.inFlight+=1;const r=new URL(this.endpoint);return r.searchParams.set("custom_channel_id",t),this.runSse(Ge({apiKey:this.apiKey,endpoint:r.toString(),debugMode:this.debugMode,method:"GET",customHeaders:this.customHeaders}),e)}deriveChannelMetadataEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel/metadata`:null}async channelMetadata(t){const e=this.deriveChannelMetadataEndpoint();if(!e)throw new Error("Unable to derive channel metadata endpoint. Please provide botProviderEndpoint in config.");const r=new URL(e);r.searchParams.set("custom_channel_id",t);const s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const i=await fetch(r.toString(),{method:"GET",headers:s});if(i.status===404)return null;if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.json(),a=o.data??o;return{title:a.title??null,runState:a.runState??"IDLE",lastActivityAt:a.lastActivityAt,launchedSandboxes:(a.launchedSandboxes??[]).map(c=>({sandboxName:c.sandboxName,sandboxBlueprintName:c.sandboxBlueprintName,workingDirectory:c.workingDirectory,editorServerEnabled:c.editorServerEnabled,browserEnabled:c.browserEnabled}))}}deriveSuspendEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/suspend`:null}async suspendChannel(t,e){const r=this.deriveSuspendEndpoint();if(!r)throw new Error("Unable to derive channel suspend endpoint. Please provide botProviderEndpoint in config.");const s=new URL(r);s.searchParams.set("custom_channel_id",t),e?.requestId&&s.searchParams.set("request_id",e.requestId),e?.force&&s.searchParams.set("force","true");const i=await fetch(s.toString(),{method:"POST",headers:this.apiHeaders()});if(!(i.ok||i.status===404))throw new w(i.status,i.statusText,await i.text().catch(()=>{}))}runSse(t,e){return t.pipe(ln(r=>Wt(r).pipe(pn(e?.delayTime??50))),bn(this.destroy$),gn(()=>this.onRunSettled())).subscribe({next:r=>{this.detached||(e?.onSseMessage?.(r),this.handleEvent(r))},error:r=>{this.detached||e?.onSseError?.(r)},complete:()=>{this.detached||e?.onSseCompleted?.()}})}detach(t){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),t.timeoutMs)}}onRunSettled(){this.inFlight=Math.max(0,this.inFlight-1),this.detached&&this.inFlight===0&&this.close()}close(){this.closed||(this.closed=!0,this.detachTimer&&(clearTimeout(this.detachTimer),this.detachTimer=void 0),this.destroy$.next(),this.destroy$.complete())}async uploadFile(t,e){const r=this.deriveBlobEndpoint();if(!r)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const s=new FormData;s.append("file",t),s.append("customChannelId",e);const i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const o=await fetch(r,{method:"POST",headers:i,body:s});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const a=await o.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(o){throw console.error("[AsgardServiceClient] File upload error:",o),o}}async downloadChannelHomeFile(t,e){const r=this.getBaseEndpoint();if(!r)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const s=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,i=`${r}/channel-home/download?${s}`,o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const a=await fetch(i,{method:"GET",headers:o});if(!a.ok)throw new Error(`Channel Home download failed: ${a.status} ${a.statusText}`);const c=await a.blob(),u=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] Channel Home download response:",{filename:u,size:c.size}),{blob:c,filename:u}}catch(a){throw console.error("[AsgardServiceClient] Channel Home download error:",a),a}}async generateSandboxBrowserOpenUrl(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox browser open-url endpoint. Please provide botProviderEndpoint in config.");const r=`${e}/sandbox/${encodeURIComponent(t)}/browser/open-url`,s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const i=await fetch(r,{method:"POST",headers:s});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.json(),a=o.data?.openURL??o.openURL;if(!a)throw new Error("Sandbox browser open-url response did not contain an openURL.");return a}deriveSandboxFsEndpoint(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox fs endpoint. Please provide botProviderEndpoint in config.");return`${e}/sandbox/${encodeURIComponent(t)}/fs`}apiHeaders(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async sandboxFsList(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/list`);r.searchParams.set("path",e);const s=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!s.ok)throw new w(s.status,s.statusText,await s.text().catch(()=>{}));const i=await s.json(),o=i.data??i;return{entries:o.entries??[],truncated:o.truncated??!1}}async sandboxFsRead(t,e,r){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);s.searchParams.set("path",e),r?.offsetBytes!=null&&s.searchParams.set("offset_bytes",String(r.offsetBytes)),r?.limitBytes!=null&&s.searchParams.set("limit_bytes",String(r.limitBytes));const i=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.blob(),a=i.headers.get("X-Total-Bytes");return{content:o,totalBytes:a!=null?Number(a):o.size,truncated:i.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,r,s){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);i.searchParams.set("path",e),s?.mode!=null&&i.searchParams.set("mode",String(s.mode)),s?.createOnly&&i.searchParams.set("create_only","true");const o=new FormData;o.append("file",r instanceof Blob?r:new Blob([r]));const a=await fetch(i.toString(),{method:"PUT",headers:this.apiHeaders(),body:o});if(!a.ok)throw new w(a.status,a.statusText,await a.text().catch(()=>{}));const c=await a.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,r,s){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(s).forEach(([a,c])=>i.searchParams.set(a,c));const o=await fetch(i.toString(),{method:r,headers:this.apiHeaders()});if(!o.ok)throw new w(o.status,o.statusText,await o.text().catch(()=>{}));return o.json().catch(()=>null)}async sandboxFsStat(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/stat`);r.searchParams.set("path",e);const s=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!s.ok)throw new w(s.status,s.statusText,await s.text().catch(()=>{}));const i=await s.json(),o=i.data??i;return{exists:o.exists??!1,isDir:o.isDir??!1,sizeBytes:o.sizeBytes??0,mtimeUnix:o.mtimeUnix??0,mode:o.mode??0,etag:o.etag}}async sandboxFsMkdir(t,e){await this.sandboxFsRequest(t,"mkdir","POST",{path:e})}async sandboxFsRemove(t,e){await this.sandboxFsRequest(t,"item","DELETE",{path:e})}async sandboxFsRemoveAll(t,e){await this.sandboxFsRequest(t,"all","DELETE",{path:e})}async sandboxFsCopy(t,e,r,s){const i={src:e,dst:r};s?.overwrite&&(i.overwrite="true");const o=await this.sandboxFsRequest(t,"copy","POST",i);return{bytesCopied:(o?.data??o)?.bytesCopied??0}}async sandboxFsMove(t,e,r,s){const i={src:e,dst:r};s?.overwrite&&(i.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",i)}sandboxFsWatch(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/watch`);return r.searchParams.set("path",e),new E(s=>{const i=new AbortController;return pe(r.toString(),{headers:this.apiHeaders(),signal:i.signal,openWhenHidden:!0,onopen:async o=>{if(!o.ok){const a=await o.text().catch(()=>{});s.error(new w(o.status,o.statusText,a)),i.abort()}},onmessage:o=>{o.event==="change"&&s.next(JSON.parse(o.data))},onclose:()=>s.complete(),onerror:o=>{throw s.error(o),i.abort(),o}}),()=>i.abort()})}deriveBlobEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/blob`:null}getBaseEndpoint(){let t=this.botProviderEndpoint;return!t&&this.endpoint&&(t=this.endpoint.replace("/message/sse","")),t?t.replace(/\/+$/,""):null}}const S=[];for(let n=0;n<256;++n)S.push((n+256).toString(16).slice(1));function Sn(n,t=0){return(S[n[t+0]]+S[n[t+1]]+S[n[t+2]]+S[n[t+3]]+"-"+S[n[t+4]]+S[n[t+5]]+"-"+S[n[t+6]]+S[n[t+7]]+"-"+S[n[t+8]]+S[n[t+9]]+"-"+S[n[t+10]]+S[n[t+11]]+S[n[t+12]]+S[n[t+13]]+S[n[t+14]]+S[n[t+15]]).toLowerCase()}let ie;const wn=new Uint8Array(16);function En(){if(!ie){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ie=crypto.getRandomValues.bind(crypto)}return ie(wn)}const qe={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function In(n,t,e){n=n||{};const r=n.random??n.rng?.()??En();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Sn(r)}function Ke(n,t,e){return qe.randomUUID&&!n?qe.randomUUID():In(n)}class v{messages=null;pendingConsent=null;constructor({messages:t,pendingConsent:e=null}){this.messages=t,this.pendingConsent=e??null}pushMessage(t){const e=new Map(this.messages);return e.set(t.messageId,t),new v({messages:e,pendingConsent:this.pendingConsent})}clearPendingConsent(){return this.pendingConsent?new v({messages:this.messages,pendingConsent:null}):this}settleInFlightMessages(){if(!this.messages)return this;let t=!1;const e=new Map(this.messages);for(const[r,s]of e)s.type==="tool-call"&&!s.isComplete&&(e.set(r,{...s,isComplete:!0,isCancelled:!0}),t=!0),s.type==="thinking"&&s.isThinking&&(e.set(r,{...s,isThinking:!1}),t=!0);return t?new v({messages:e,pendingConsent:this.pendingConsent}):this}cancelInFlightToolCalls(){return this.settleInFlightMessages()}onMessage(t){switch(t.eventType){case l.MESSAGE_START:return this.onMessageStart(t);case l.MESSAGE_DELTA:return this.onMessageDelta(t);case l.MESSAGE_COMPLETE:return this.onMessageComplete(t);case l.MESSAGE_USER:return this.onMessageUser(t);case l.MESSAGE_THINKING_START:return this.onThinkingStart(t);case l.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case l.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case l.TOOL_CALL_START:return this.onToolCallStart(t);case l.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case l.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case l.SUBAGENT_START:return this.onSubagentStart(t);case l.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case l.ERROR:return this.onMessageError(t);default:return this}}isTerminalBot(t){return t?.type==="bot"&&!t.isTyping}isTerminalThinking(t){return t?.type==="thinking"&&!t.isThinking}onMessageStart(t){const e=t.fact.messageStart.message;if(e.parentToolUseId)return this;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages);return r.set(e.messageId,{type:"bot",eventType:l.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new v({messages:r,pendingConsent:this.pendingConsent})}onMessageDelta(t){const e=t.fact.messageDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalBot(r))return this;const s=r?.type==="bot"?r:void 0,i=new Map(this.messages);return i.set(e.messageId,{type:"bot",eventType:l.MESSAGE_DELTA,isTyping:!0,typingText:`${s?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??s?.traceId,raw:s?.raw??""}),new v({messages:i,pendingConsent:this.pendingConsent})}onMessageComplete(t){const e=t.fact.messageComplete.message;if(e.parentToolUseId)return this;const r=new Map(this.messages),s=r.get(e.messageId);return r.set(e.messageId,{type:"bot",eventType:l.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??(s?.type==="bot"?s.traceId:void 0),raw:JSON.stringify(t)}),new v({messages:r,pendingConsent:this.pendingConsent})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(e.parentToolUseId)return this;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages),s={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return r.set(e.messageId,s),new v({messages:r,pendingConsent:this.pendingConsent})}onThinkingDelta(t){const e=t.fact.messageThinkingDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalThinking(r))return this;const s=r?.type==="thinking"?r:void 0,i=new Map(this.messages),o={type:"thinking",messageId:e.messageId,text:`${s?.text??""}${e.text}`,isThinking:!0,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return i.set(e.messageId,o),new v({messages:i,pendingConsent:this.pendingConsent})}onThinkingComplete(t){const e=t.fact.messageThinkingComplete.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId),s=r?.type==="thinking"?r:void 0,i=new Map(this.messages),o={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return i.set(e.messageId,o),new v({messages:i,pendingConsent:this.pendingConsent})}onMessageUser(t){const e=t.fact.messageUser;if((this.messages?.get(e.messageId)??(e.customMessageId?this.messages?.get(e.customMessageId):void 0))?.type==="user")return this;const s=new Map(this.messages),i={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return s.set(e.messageId,i),new v({messages:s,pendingConsent:this.pendingConsent})}onMessageError(t){const e=Ke(),r=t.fact.runError.error,s=new Map(this.messages);return s.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:r,time:new Date,traceId:t.traceId}),new v({messages:s,pendingConsent:this.pendingConsent})}onToolCallStart(t){const e=t.fact.toolCallStart,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,i={type:"tool-call",eventType:l.TOOL_CALL_START,messageId:s,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,isComplete:!1,time:new Date,traceId:t.traceId};return r.set(s,i),new v({messages:r,pendingConsent:this.pendingConsent})}onToolCallComplete(t){const e=t.fact.toolCallComplete,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,i=r.get(s);if(i?.type==="tool-call"){const o={...i,eventType:l.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??i.traceId};r.set(s,o)}return new v({messages:r,pendingConsent:this.pendingConsent})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new v({messages:this.messages,pendingConsent:e})}onSubagentStart(t){const e=t.fact.subagentStart,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:start`,i={type:"subagent",messageId:s,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return r.set(s,i),new v({messages:r,pendingConsent:this.pendingConsent})}onSubagentComplete(t){const e=t.fact.subagentComplete,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:complete`,i={type:"subagent",messageId:s,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return r.set(s,i),new v({messages:r,pendingConsent:this.pendingConsent})}}const Tn=new Set(["TaskCreate","TaskUpdate"]);function Ye(n){return n.toolsetName===""&&Tn.has(n.toolName)}function We(n){return typeof n=="object"&&n!==null?n:void 0}function T(n){return typeof n=="string"?n:void 0}function Xe(n){const t=[],e=new Map;for(const r of n){const s=r.parameter??{},i=r.sidecar??{};if(r.toolName==="TaskCreate"){const o=We(i.task),a=T(o?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:T(s.subject)||T(o?.subject)||"",activeForm:T(s.activeForm),description:T(s.description),status:e.get(a)?.status??"pending"})}else if(r.toolName==="TaskUpdate"){const o=We(i.statusChange),a=T(s.taskId)||T(i.taskId),c=T(o?.to)||T(s.status);if(!a||!c)continue;const u=e.get(a);u&&e.set(a,{...u,status:c})}}return t.map(r=>e.get(r))}function Ve(n){return n.toolsetName===""&&n.toolName==="Agent"}function ze(n){return!!n}function Je(n){const t=[],e=new Map,r=new Map,s=i=>(e.has(i)||(t.push(i),e.set(i,{status:"running"}),r.set(i,new Map)),e.get(i));for(const i of n)switch(i.kind){case"agentStart":{const o=s(i.toolUseId);i.description&&!o.description&&(o.description=i.description);break}case"subagentStart":{const o=s(i.parentToolUseId);o.agentId=i.agentId??o.agentId,o.subagentType=i.subagentType??o.subagentType,o.description=i.description??o.description;break}case"toolStart":{s(i.parentToolUseId),r.get(i.parentToolUseId).set(i.toolUseId,{toolsetName:i.toolsetName,toolName:i.toolName,parameter:i.parameter??{},reason:i.reason,status:"running"});break}case"toolComplete":{const o=r.get(i.parentToolUseId)?.get(i.toolUseId);o&&(o.status=i.isError?"error":"completed");break}case"subagentComplete":{const o=s(i.parentToolUseId);o.status=i.status,o.summary=i.summary;break}}return t.map(i=>({parentToolUseId:i,...e.get(i),tools:Array.from(r.get(i).values())}))}function Cn(n){return typeof n=="string"?n:void 0}function Qe(n){const t=[];for(const e of n){if(e.type==="tool-call"&&Ve(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:Cn(e.parameter.description)});continue}if(e.type==="tool-call"&&ze(e.parentToolUseId)){const r=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:r,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:r,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function Ze(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Ye(e));return Xe(t)}function et(n){return Je(Qe(Array.from(n.messages?.values()??[])))}function tt(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.id===s.id&&e.status===s.status&&e.subject===s.subject&&e.activeForm===s.activeForm&&e.description===s.description})}function xn(n,t){return n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.toolName===s.toolName&&e.toolsetName===s.toolsetName&&e.status===s.status&&e.reason===s.reason})}function nt(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.parentToolUseId===s.parentToolUseId&&e.status===s.status&&e.subagentType===s.subagentType&&e.description===s.description&&e.summary===s.summary&&xn(e.tools,s.tools)})}function rt(n){const t=new A([]),e=new A([]),r=new j;return r.add(n.pipe($(Ze),D(tt)).subscribe(t)),r.add(n.pipe($(et),D(nt)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>r.unsubscribe()}}function oe(n){const t=new Map;for(const e of n)t.set(e.sandboxName,e);return[...t.values()].sort((e,r)=>(e.sandboxBlueprintName||e.sandboxName).localeCompare(r.sandboxBlueprintName||r.sandboxName))}const ae={kind:null,stopPhase:"idle"},On=1e4;function An(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class B{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;sandboxPhaseSubject;launchedSandboxesSubject;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;sandboxPhase$;launchedSandboxes$;runStatus$;currentUserMessageId;lastSentMessageId;currentRun;forceStopTimer;constructor(t){if(!t.client)throw new Error("client must be required");if(!t.customChannelId)throw new Error("customChannelId must be required");this.client=t.client,this.customChannelId=t.customChannelId,this.customMessageId=t.customMessageId,this.joinRunState=t.runState??"IDLE",this.isConnecting$=new A(!1),this.runStatusSubject=new A(ae),this.conversation$=new A(t.conversation),this.channelTitleSubject=new A(t.channelTitle??null),this.sandboxPhaseSubject=new A("idle"),this.launchedSandboxesSubject=new A(oe(t.launchedSandboxes??[])),this.derivedStores=rt(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(D()),this.sandboxPhase$=this.sandboxPhaseSubject.pipe(D()),this.launchedSandboxes$=this.launchedSandboxesSubject.pipe(D()),this.runStatus$=this.runStatusSubject.pipe(D(An)),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}getSandboxPhase(){return this.sandboxPhaseSubject.value}getLaunchedSandboxes(){return this.launchedSandboxesSubject.value}getRunStatus(){return this.runStatusSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=oe(t);this.pendingLaunches=this.pendingLaunches.filter(r=>!e.some(s=>s.sandboxName===r)),this.launchedSandboxesSubject.next(e)}dropSandbox(t){const e=this.launchedSandboxesSubject.value,r=e.filter(s=>s.sandboxName!==t);r.length!==e.length&&this.launchedSandboxesSubject.next(r)}noteSandboxLaunch(t){this.pendingLaunches.includes(t)||(this.pendingLaunches=[...this.pendingLaunches,t]),this.refetchMetadata()}async refetchMetadata(){if(!this.client.channelMetadata)return;const t=await this.client.channelMetadata(this.customChannelId);t&&this.applyLaunchedSandboxes(t.launchedSandboxes)}setChannelTitle(t){this.channelTitleSubject.next(t)}static create(t){const e=new B(t);return e.subscribe(),e}static async reset(t,e,r,s){const i=new B(t);try{return i.subscribe(),s?.(i),await i.resetChannel(e,r),i}catch(o){throw i.close(),o}}static async restore(t,e,r){const s=new B(t);try{return s.subscribe(),r?.(s),await s.rejoinChannel(e),s}catch(i){throw s.close(),i}}subscribe(){this.statesSubscription=on([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe($(([t,e,r,s,i,o,a,c])=>({isConnecting:t,conversation:e,tasks:r,subagents:s,channelTitle:i,sandboxPhase:o,launchedSandboxes:a,runStatus:c}))).subscribe(this.statesObserver)}resolvePayload(t){if(typeof t=="function")try{return t()}catch(e){throw new Error(`Failed to resolve payload function: ${e instanceof Error?e.message:String(e)}`)}return t}updateSandboxPhase(t){switch(t){case l.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case l.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case l.INIT:case l.ERROR:this.sandboxPhaseSubject.next("idle");break}}buildRunHandlers(t,e,r){return{onSseStart:t?.onSseStart,onSseMessage:s=>{if(t?.onSseMessage?.(s),this.captureRequestId(s.requestId),s.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(s.fact.channelTitleUpdate.title),this.updateSandboxPhase(s.eventType),s.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(s.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&s.traceId){const i=new Map(this.conversation$.value.messages),o=i.get(this.currentUserMessageId);o&&o.type==="user"&&(i.set(this.currentUserMessageId,{...o,traceId:s.traceId}),this.conversation$.next(new v({messages:i}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(s))},onSseError:s=>{t?.onSseError?.(s),this.settleRun(),r(s)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.settleRun(),e()}}}settleRun(){const t=this.runStatusSubject.value.stopPhase!=="idle";this.clearForceStopTimer(),this.isConnecting$.next(!1),this.runStatusSubject.next(ae),this.currentUserMessageId=void 0,this.currentRun=void 0,t&&this.conversation$.next(this.conversation$.value.settleInFlightMessages())}captureRequestId(t){const e=this.runStatusSubject.value;!t||e.requestId||!e.kind||this.runStatusSubject.next({...e,requestId:t})}clearForceStopTimer(){this.forceStopTimer&&(clearTimeout(this.forceStopTimer),this.forceStopTimer=void 0)}fetchSse(t,e,r){return new Promise((s,i)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(r,s,i))})}rejoinChannel(t){return new Promise((e,r)=>{if(!this.client.rejoinSse){e();return}this.isConnecting$.next(!0),this.runStatusSubject.next({kind:this.joinRunState==="RUNNING"?"restore":"replay",stopPhase:"idle"}),this.currentRun=this.client.rejoinSse(this.customChannelId,this.buildRunHandlers(t,e,r))})}resetChannel(t,e){return this.fetchSse("reset",{action:k.RESET_CHANNEL,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const r=this.runStatusSubject.value.kind;if(r)return Promise.reject(new V(r));const s=t.text.trim(),i=t.customMessageId??Ke();return this.currentUserMessageId=i,this.lastSentMessageId=i,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:i,text:s,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:k.NONE,customChannelId:this.customChannelId,customMessageId:i,payload:this.resolvePayload(t?.payload),text:s,blobIds:t?.blobIds},e)}replyToolCallConsents(t,e,r){return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse("user",{action:k.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(r),text:"",toolCallConsents:t},e)}nudge(t,e){return this.fetchSse("nudge",{action:k.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t)}async stopGeneration(t){const e=this.runStatusSubject.value;if(!(!this.currentRun||e.kind!=="user")&&!(e.stopPhase!=="idle"&&!t?.force)){if(!this.client.suspendChannel){this.abortConnection();return}this.clearForceStopTimer(),this.runStatusSubject.next({...e,stopPhase:"stopping"});try{await this.client.suspendChannel(this.customChannelId,{requestId:e.requestId,force:t?.force})}catch(r){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),r}this.armForceStopTimer()}}armForceStopTimer(){this.clearForceStopTimer(),this.forceStopTimer=setTimeout(()=>{this.forceStopTimer=void 0;const t=this.runStatusSubject.value;t.stopPhase==="stopping"&&this.runStatusSubject.next({...t,stopPhase:"force-stoppable"})},On)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(ae),this.currentUserMessageId=void 0,this.conversation$.next(this.conversation$.value.settleInFlightMessages()))}close(){this.currentRun?.unsubscribe(),this.currentRun=void 0,this.clearForceStopTimer(),this.isConnecting$.complete(),this.runStatusSubject.complete(),this.conversation$.complete(),this.channelTitleSubject.complete(),this.sandboxPhaseSubject.complete(),this.launchedSandboxesSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}function Pn(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),r=t[2],s=new URLSearchParams(t[3]??"");if(r==="open-browser")return{kind:"open-browser",sandboxName:e};if(r==="open-file"){const i=s.get("absolute_path");return i?{kind:"open-file",sandboxName:e,absolutePath:i}:null}return null}m.AsgardServiceClient=yn,m.Channel=B,m.ChannelBusyError=V,m.Conversation=v,m.EventType=l,m.FetchSseAction=k,m.HttpError=w,m.MessageTemplateType=de,m.ToolCallConsentResult=le,m.conversationToSubagentEvents=Qe,m.createDerivedStores=rt,m.deriveSubagents=et,m.deriveTasks=Ze,m.isAgentTool=Ve,m.isChannelBusyError=it,m.isHttpError=st,m.isSubagentChildTool=ze,m.isTaskTool=Ye,m.reconcileLaunched=oe,m.reduceSubagents=Je,m.reduceTaskEvents=Xe,m.resolveSandboxUri=Pn,m.subagentsEqual=nt,m.tasksEqual=tt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
5
5
  //# sourceMappingURL=index.js.map