@asgard-js/core 0.3.81 → 0.3.83

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,7 +1,7 @@
1
- (function(p,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(p=typeof globalThis<"u"?globalThis:p||self,v(p["@asgard-js/core"]={}))})(this,(function(p){"use strict";class v extends Error{status;statusText;body;constructor(t,e,s){super(`HTTP ${t}: ${e}`),this.name="HttpError",this.status=t,this.statusText=e,this.body=s}}function dt(n){return n instanceof v}class W 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 ht(n){return n instanceof W}class Y extends Error{processId;constructor(t){super("Cannot send this turn while the channel is awaiting a tool-call consent response."),this.name="ChannelAwaitingConsentError",this.processId=t}}function ft(n){return n instanceof Y}var F=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(F||{}),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.MESSAGE_CANVAS_START="asgard.message.canvas.start",n.MESSAGE_CANVAS_DELTA="asgard.message.canvas.delta",n.MESSAGE_CANVAS_COMPLETE="asgard.message.canvas.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.PROMPT_SUGGESTION="asgard.prompt_suggestion",n.SANDBOX_LAUNCH="asgard.sandbox.launch",n.SANDBOX_READY="asgard.sandbox.ready",n.MESSAGE_FEEDBACK="asgard.message.feedback",n.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(l||{}),pe=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(pe||{}),te=(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.QUESTION="QUESTION",n.CANVAS="CANVAS",n))(te||{});async function pt(n,t){const e=n.getReader();let s;for(;!(s=await e.read()).done;)t(s.value)}function gt(n){let t,e,s,r=!1;return function(a){t===void 0?(t=a,e=0,s=-1):t=bt(t,a);const o=t.length;let c=0;for(;e<o;){r&&(t[e]===10&&(c=++e),r=!1);let u=-1;for(;e<o&&u===-1;++e)switch(t[e]){case 58:s===-1&&(s=e-c);break;case 13:r=!0;case 10:u=e;break}if(u===-1)break;n(t.subarray(c,u),s),c=e,s=-1}c===o?t=void 0:c!==0&&(t=t.subarray(c),e-=c)}}function mt(n,t,e){let s=ge();const r=new TextDecoder;return function(a,o){if(a.length===0)e?.(s),s=ge();else if(o>0){const c=r.decode(a.subarray(0,o)),u=o+(a[o+1]===32?2:1),d=r.decode(a.subarray(u));switch(c){case"data":s.data=s.data?s.data+`
2
- `+d:d;break;case"event":s.event=d;break;case"id":n(s.id=d);break;case"retry":const b=parseInt(d,10);isNaN(b)||t(s.retry=b);break}}}}function bt(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function ge(){return{data:"",event:"",id:"",retry:void 0}}var vt=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(e[s[r]]=n[s[r]]);return e};const ne="text/event-stream",St=1e3,me="last-event-id";function be(n,t){var{signal:e,headers:s,onopen:r,onmessage:i,onclose:a,onerror:o,openWhenHidden:c,fetch:u}=t,d=vt(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((b,y)=>{const h=Object.assign({},s);h.accept||(h.accept=ne);let g;function f(){g.abort(),document.hidden||B()}c||document.addEventListener("visibilitychange",f);let T=St,I=0;function X(){document.removeEventListener("visibilitychange",f),window.clearTimeout(I),g.abort()}e?.addEventListener("abort",()=>{X(),b()});const D=u??window.fetch,N=r??yt;async function B(){var H;g=new AbortController;try{const G=await D(n,Object.assign(Object.assign({},d),{headers:h,signal:g.signal}));await N(G),await pt(G.body,gt(mt(_=>{_?h[me]=_:delete h[me]},_=>{T=_},i))),a?.(),X(),b()}catch(G){if(!g.signal.aborted)try{const _=(H=o?.(G))!==null&&H!==void 0?H:T;window.clearTimeout(I),I=window.setTimeout(B,_)}catch(_){X(),y(_)}}}B()})}function yt(n){const t=n.headers.get("content-type");if(!t?.startsWith(ne))throw new Error(`Expected content-type to be ${ne}, Actual: ${t}`)}var se=function(n,t){return se=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,s){e.__proto__=s}||function(e,s){for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(e[r]=s[r])},se(n,t)};function O(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");se(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function Et(n,t,e,s){function r(i){return i instanceof e?i:new e(function(a){a(i)})}return new(e||(e=Promise))(function(i,a){function o(d){try{u(s.next(d))}catch(b){a(b)}}function c(d){try{u(s.throw(d))}catch(b){a(b)}}function u(d){d.done?i(d.value):r(d.value).then(o,c)}u((s=s.apply(n,t||[])).next())})}function ve(n,t){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,r,i,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(u){return function(d){return c([u,d])}}function c(u){if(s)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(e=0)),e;)try{if(s=1,r&&(i=u[0]&2?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=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++,r=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(d){u=[6,d],r=0}finally{s=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function M(n){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&n[t],s=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&s>=n.length&&(n=void 0),{value:n&&n[s++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function q(n,t){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var s=e.call(n),r,i=[],a;try{for(;(t===void 0||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(e=s.return)&&e.call(s)}finally{if(a)throw a.error}}return i}function K(n,t,e){if(e||arguments.length===2)for(var s=0,r=t.length,i;s<r;s++)(i||!(s in t))&&(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return n.concat(i||Array.prototype.slice.call(t))}function j(n){return this instanceof j?(this.v=n,this):new j(n)}function wt(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=e.apply(n,t||[]),r,i=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(h){return function(g){return Promise.resolve(g).then(h,b)}}function o(h,g){s[h]&&(r[h]=function(f){return new Promise(function(T,I){i.push([h,f,T,I])>1||c(h,f)})},g&&(r[h]=g(r[h])))}function c(h,g){try{u(s[h](g))}catch(f){y(i[0][3],f)}}function u(h){h.value instanceof j?Promise.resolve(h.value.v).then(d,b):y(i[0][2],h)}function d(h){c("next",h)}function b(h){c("throw",h)}function y(h,g){h(g),i.shift(),i.length&&c(i[0][0],i[0][1])}}function It(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 M=="function"?M(n):n[Symbol.iterator](),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(i){e[i]=n[i]&&function(a){return new Promise(function(o,c){a=n[i](a),r(o,c,a.done,a.value)})}}function r(i,a,o,c){Promise.resolve(c).then(function(u){i({value:u,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;function S(n){return typeof n=="function"}function Se(n){var t=function(s){Error.call(s),s.stack=new Error().stack},e=n(t);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var re=Se(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
1
+ (function(p,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(p=typeof globalThis<"u"?globalThis:p||self,v(p["@asgard-js/core"]={}))})(this,(function(p){"use strict";class v extends Error{status;statusText;body;constructor(t,e,s){super(`HTTP ${t}: ${e}`),this.name="HttpError",this.status=t,this.statusText=e,this.body=s}}function ht(n){return n instanceof v}class W 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 ft(n){return n instanceof W}class Y extends Error{processId;constructor(t){super("Cannot send this turn while the channel is awaiting a tool-call consent response."),this.name="ChannelAwaitingConsentError",this.processId=t}}function pt(n){return n instanceof Y}var F=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(F||{}),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.MESSAGE_CANVAS_START="asgard.message.canvas.start",n.MESSAGE_CANVAS_DELTA="asgard.message.canvas.delta",n.MESSAGE_CANVAS_COMPLETE="asgard.message.canvas.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.PROMPT_SUGGESTION="asgard.prompt_suggestion",n.SANDBOX_LAUNCH="asgard.sandbox.launch",n.SANDBOX_READY="asgard.sandbox.ready",n.MESSAGE_FEEDBACK="asgard.message.feedback",n.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(l||{}),pe=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(pe||{}),te=(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.QUESTION="QUESTION",n.CANVAS="CANVAS",n))(te||{});async function gt(n,t){const e=n.getReader();let s;for(;!(s=await e.read()).done;)t(s.value)}function mt(n){let t,e,s,r=!1;return function(a){t===void 0?(t=a,e=0,s=-1):t=vt(t,a);const o=t.length;let c=0;for(;e<o;){r&&(t[e]===10&&(c=++e),r=!1);let u=-1;for(;e<o&&u===-1;++e)switch(t[e]){case 58:s===-1&&(s=e-c);break;case 13:r=!0;case 10:u=e;break}if(u===-1)break;n(t.subarray(c,u),s),c=e,s=-1}c===o?t=void 0:c!==0&&(t=t.subarray(c),e-=c)}}function bt(n,t,e){let s=ge();const r=new TextDecoder;return function(a,o){if(a.length===0)e?.(s),s=ge();else if(o>0){const c=r.decode(a.subarray(0,o)),u=o+(a[o+1]===32?2:1),d=r.decode(a.subarray(u));switch(c){case"data":s.data=s.data?s.data+`
2
+ `+d:d;break;case"event":s.event=d;break;case"id":n(s.id=d);break;case"retry":const b=parseInt(d,10);isNaN(b)||t(s.retry=b);break}}}}function vt(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function ge(){return{data:"",event:"",id:"",retry:void 0}}var St=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(e[s[r]]=n[s[r]]);return e};const ne="text/event-stream",yt=1e3,me="last-event-id";function be(n,t){var{signal:e,headers:s,onopen:r,onmessage:i,onclose:a,onerror:o,openWhenHidden:c,fetch:u}=t,d=St(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((b,y)=>{const h=Object.assign({},s);h.accept||(h.accept=ne);let g;function f(){g.abort(),document.hidden||B()}c||document.addEventListener("visibilitychange",f);let T=yt,I=0;function X(){document.removeEventListener("visibilitychange",f),window.clearTimeout(I),g.abort()}e?.addEventListener("abort",()=>{X(),b()});const D=u??window.fetch,R=r??wt;async function B(){var H;g=new AbortController;try{const G=await D(n,Object.assign(Object.assign({},d),{headers:h,signal:g.signal}));await R(G),await gt(G.body,mt(bt(P=>{P?h[me]=P:delete h[me]},P=>{T=P},i))),a?.(),X(),b()}catch(G){if(!g.signal.aborted)try{const P=(H=o?.(G))!==null&&H!==void 0?H:T;window.clearTimeout(I),I=window.setTimeout(B,P)}catch(P){X(),y(P)}}}B()})}function wt(n){const t=n.headers.get("content-type");if(!t?.startsWith(ne))throw new Error(`Expected content-type to be ${ne}, Actual: ${t}`)}var se=function(n,t){return se=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,s){e.__proto__=s}||function(e,s){for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(e[r]=s[r])},se(n,t)};function O(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");se(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function Et(n,t,e,s){function r(i){return i instanceof e?i:new e(function(a){a(i)})}return new(e||(e=Promise))(function(i,a){function o(d){try{u(s.next(d))}catch(b){a(b)}}function c(d){try{u(s.throw(d))}catch(b){a(b)}}function u(d){d.done?i(d.value):r(d.value).then(o,c)}u((s=s.apply(n,t||[])).next())})}function ve(n,t){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,r,i,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(u){return function(d){return c([u,d])}}function c(u){if(s)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(e=0)),e;)try{if(s=1,r&&(i=u[0]&2?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=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++,r=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(d){u=[6,d],r=0}finally{s=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function M(n){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&n[t],s=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&s>=n.length&&(n=void 0),{value:n&&n[s++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function q(n,t){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var s=e.call(n),r,i=[],a;try{for(;(t===void 0||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(e=s.return)&&e.call(s)}finally{if(a)throw a.error}}return i}function K(n,t,e){if(e||arguments.length===2)for(var s=0,r=t.length,i;s<r;s++)(i||!(s in t))&&(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return n.concat(i||Array.prototype.slice.call(t))}function j(n){return this instanceof j?(this.v=n,this):new j(n)}function It(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=e.apply(n,t||[]),r,i=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(h){return function(g){return Promise.resolve(g).then(h,b)}}function o(h,g){s[h]&&(r[h]=function(f){return new Promise(function(T,I){i.push([h,f,T,I])>1||c(h,f)})},g&&(r[h]=g(r[h])))}function c(h,g){try{u(s[h](g))}catch(f){y(i[0][3],f)}}function u(h){h.value instanceof j?Promise.resolve(h.value.v).then(d,b):y(i[0][2],h)}function d(h){c("next",h)}function b(h){c("throw",h)}function y(h,g){h(g),i.shift(),i.length&&c(i[0][0],i[0][1])}}function Tt(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 M=="function"?M(n):n[Symbol.iterator](),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(i){e[i]=n[i]&&function(a){return new Promise(function(o,c){a=n[i](a),r(o,c,a.done,a.value)})}}function r(i,a,o,c){Promise.resolve(c).then(function(u){i({value:u,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;function S(n){return typeof n=="function"}function Se(n){var t=function(s){Error.call(s),s.stack=new Error().stack},e=n(t);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var re=Se(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
3
3
  `+e.map(function(s,r){return r+1+") "+s.toString()}).join(`
4
- `):"",this.name="UnsubscriptionError",this.errors=e}});function V(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var U=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,s,r,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var o=M(a),c=o.next();!c.done;c=o.next()){var u=c.value;u.remove(this)}}catch(f){t={error:f}}finally{try{c&&!c.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}else a.remove(this);var d=this.initialTeardown;if(S(d))try{d()}catch(f){i=f instanceof re?f.errors:[f]}var b=this._finalizers;if(b){this._finalizers=null;try{for(var y=M(b),h=y.next();!h.done;h=y.next()){var g=h.value;try{we(g)}catch(f){i=i??[],f instanceof re?i=K(K([],q(i)),q(f.errors)):i.push(f)}}}catch(f){s={error:f}}finally{try{h&&!h.done&&(r=y.return)&&r.call(y)}finally{if(s)throw s.error}}}if(i)throw new re(i)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)we(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)&&V(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&V(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),ye=U.EMPTY;function Ee(n){return n instanceof U||n&&"closed"in n&&S(n.remove)&&S(n.add)&&S(n.unsubscribe)}function we(n){S(n)?n():n.unsubscribe()}var Tt={Promise:void 0},Ct={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,K([n,t],q(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Ie(n){Ct.setTimeout(function(){throw n})}function ie(){}function z(n){n()}var ae=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,Ee(e)&&e.add(s)):s.destination=xt,s}return t.create=function(e,s,r){return new oe(e,s,r)},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})(U),At=(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(s){J(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){J(s)}else J(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){J(e)}},n})(),oe=(function(n){O(t,n);function t(e,s,r){var i=n.call(this)||this,a;return S(e)||!e?a={next:e??void 0,error:s??void 0,complete:r??void 0}:a=e,i.destination=new At(a),i}return t})(ae);function J(n){Ie(n)}function Ot(n){throw n}var xt={closed:!0,next:ie,error:Ot,complete:ie},ce=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Q(n){return n}function kt(n){return n.length===0?Q:n.length===1?n[0]:function(e){return n.reduce(function(s,r){return r(s)},e)}}var w=(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,s){var r=this,i=_t(t)?t:new oe(t,e,s);return z(function(){var a=r,o=a.operator,c=a.source;i.add(o?o.call(i,c):c?r._subscribe(i):r._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 s=this;return e=Te(e),new e(function(r,i){var a=new oe({next:function(o){try{t(o)}catch(c){i(c),a.unsubscribe()}},error:i,complete:r});s.subscribe(a)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[ce]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return kt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=Te(t),new t(function(s,r){var i;e.subscribe(function(a){return i=a},function(a){return r(a)},function(){return s(i)})})},n.create=function(t){return new n(t)},n})();function Te(n){var t;return(t=n??Tt.Promise)!==null&&t!==void 0?t:Promise}function Pt(n){return n&&S(n.next)&&S(n.error)&&S(n.complete)}function _t(n){return n&&n instanceof ae||Pt(n)&&Ee(n)}function Mt(n){return S(n?.lift)}function P(n){return function(t){if(Mt(t))return t.lift(function(e){try{return n(e,this)}catch(s){this.error(s)}});throw new TypeError("Unable to lift unknown Observable type")}}function L(n,t,e,s,r){return new Ut(n,t,e,s,r)}var Ut=(function(n){O(t,n);function t(e,s,r,i,a,o){var c=n.call(this,e)||this;return c.onFinalize=a,c.shouldUnsubscribe=o,c._next=s?function(u){try{s(u)}catch(d){e.error(d)}}:n.prototype._next,c._error=i?function(u){try{i(u)}catch(d){e.error(d)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=r?function(){try{r()}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 s=this.closed;n.prototype.unsubscribe.call(this),!s&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ae),Lt=Se(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ue=(function(n){O(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 s=new Ce(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Lt},t.prototype.next=function(e){var s=this;z(function(){var r,i;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var a=M(s.currentObservers),o=a.next();!o.done;o=a.next()){var c=o.value;c.next(e)}}catch(u){r={error:u}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var s=this;z(function(){if(s._throwIfClosed(),!s.isStopped){s.hasError=s.isStopped=!0,s.thrownError=e;for(var r=s.observers;r.length;)r.shift().error(e)}})},t.prototype.complete=function(){var e=this;z(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var s=e.observers;s.length;)s.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 s=this,r=this,i=r.hasError,a=r.isStopped,o=r.observers;return i||a?ye:(this.currentObservers=null,o.push(e),new U(function(){s.currentObservers=null,V(o,e)}))},t.prototype._checkFinalizedStatuses=function(e){var s=this,r=s.hasError,i=s.thrownError,a=s.isStopped;r?e.error(i):a&&e.complete()},t.prototype.asObservable=function(){var e=new w;return e.source=this,e},t.create=function(e,s){return new Ce(e,s)},t})(w),Ce=(function(n){O(t,n);function t(e,s){var r=n.call(this)||this;return r.destination=e,r.source=s,r}return t.prototype.next=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.next)===null||r===void 0||r.call(s,e)},t.prototype.error=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.error)===null||r===void 0||r.call(s,e)},t.prototype.complete=function(){var e,s;(s=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||s===void 0||s.call(e)},t.prototype._subscribe=function(e){var s,r;return(r=(s=this.source)===null||s===void 0?void 0:s.subscribe(e))!==null&&r!==void 0?r:ye},t})(ue),x=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s._value=e,s}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var s=n.prototype._subscribe.call(this,e);return!s.closed&&e.next(this._value),s},t.prototype.getValue=function(){var e=this,s=e.hasError,r=e.thrownError,i=e._value;if(s)throw r;return this._throwIfClosed(),i},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(ue),Rt={now:function(){return Date.now()}},Nt=(function(n){O(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(U),Ae={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,K([n,t],q(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Ft=(function(n){O(t,n);function t(e,s){var r=n.call(this,e,s)||this;return r.scheduler=e,r.work=s,r.pending=!1,r}return t.prototype.schedule=function(e,s){var r;if(s===void 0&&(s=0),this.closed)return this;this.state=e;var i=this.id,a=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(a,i,s)),this.pending=!0,this.delay=s,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(a,this.id,s),this},t.prototype.requestAsyncId=function(e,s,r){return r===void 0&&(r=0),Ae.setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,s,r){if(r===void 0&&(r=0),r!=null&&this.delay===r&&this.pending===!1)return s;s!=null&&Ae.clearInterval(s)},t.prototype.execute=function(e,s){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,s);if(r)return r;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,s){var r=!1,i;try{this.work(e)}catch(a){r=!0,i=a||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,s=e.id,r=e.scheduler,i=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,V(i,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Nt),Oe=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,s){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(s,e)},n.now=Rt.now,n})(),jt=(function(n){O(t,n);function t(e,s){s===void 0&&(s=Oe.now);var r=n.call(this,e,s)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(e){var s=this.actions;if(this._active){s.push(e);return}var r;this._active=!0;do if(r=e.execute(e.state,e.delay))break;while(e=s.shift());if(this._active=!1,r){for(;e=s.shift();)e.unsubscribe();throw r}},t})(Oe),$t=new jt(Ft);function Dt(n){return n&&S(n.schedule)}function xe(n){return n[n.length-1]}function Bt(n){return S(xe(n))?n.pop():void 0}function ke(n){return Dt(xe(n))?n.pop():void 0}var Pe=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function _e(n){return S(n?.then)}function Me(n){return S(n[ce])}function Ue(n){return Symbol.asyncIterator&&S(n?.[Symbol.asyncIterator])}function Le(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 Ht(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Re=Ht();function Ne(n){return S(n?.[Re])}function Fe(n){return wt(this,arguments,function(){var e,s,r,i;return ve(this,function(a){switch(a.label){case 0:e=n.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,j(e.read())];case 3:return s=a.sent(),r=s.value,i=s.done,i?[4,j(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,j(r)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function je(n){return S(n?.getReader)}function Z(n){if(n instanceof w)return n;if(n!=null){if(Me(n))return Gt(n);if(Pe(n))return qt(n);if(_e(n))return Kt(n);if(Ue(n))return $e(n);if(Ne(n))return Vt(n);if(je(n))return Xt(n)}throw Le(n)}function Gt(n){return new w(function(t){var e=n[ce]();if(S(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function qt(n){return new w(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Kt(n){return new w(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Ie)})}function Vt(n){return new w(function(t){var e,s;try{for(var r=M(n),i=r.next();!i.done;i=r.next()){var a=i.value;if(t.next(a),t.closed)return}}catch(o){e={error:o}}finally{try{i&&!i.done&&(s=r.return)&&s.call(r)}finally{if(e)throw e.error}}t.complete()})}function $e(n){return new w(function(t){Wt(n,t).catch(function(e){return t.error(e)})})}function Xt(n){return $e(Fe(n))}function Wt(n,t){var e,s,r,i;return Et(this,void 0,void 0,function(){var a,o;return ve(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=It(n),c.label=1;case 1:return[4,e.next()];case 2:if(s=c.sent(),!!s.done)return[3,4];if(a=s.value,t.next(a),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return o=c.sent(),r={error:o},[3,11];case 6:return c.trys.push([6,,9,10]),s&&!s.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(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function C(n,t,e,s,r){s===void 0&&(s=0),r===void 0&&(r=!1);var i=t.schedule(function(){e(),r?n.add(this.schedule(null,s)):this.unsubscribe()},s);if(n.add(i),!r)return i}function De(n,t){return t===void 0&&(t=0),P(function(e,s){e.subscribe(L(s,function(r){return C(s,n,function(){return s.next(r)},t)},function(){return C(s,n,function(){return s.complete()},t)},function(r){return C(s,n,function(){return s.error(r)},t)}))})}function Be(n,t){return t===void 0&&(t=0),P(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function Yt(n,t){return Z(n).pipe(Be(t),De(t))}function zt(n,t){return Z(n).pipe(Be(t),De(t))}function Jt(n,t){return new w(function(e){var s=0;return t.schedule(function(){s===n.length?e.complete():(e.next(n[s++]),e.closed||this.schedule())})})}function Qt(n,t){return new w(function(e){var s;return C(e,t,function(){s=n[Re](),C(e,t,function(){var r,i,a;try{r=s.next(),i=r.value,a=r.done}catch(o){e.error(o);return}a?e.complete():e.next(i)},0,!0)}),function(){return S(s?.return)&&s.return()}})}function He(n,t){if(!n)throw new Error("Iterable cannot be null");return new w(function(e){C(e,t,function(){var s=n[Symbol.asyncIterator]();C(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function Zt(n,t){return He(Fe(n),t)}function en(n,t){if(n!=null){if(Me(n))return Yt(n,t);if(Pe(n))return Jt(n,t);if(_e(n))return zt(n,t);if(Ue(n))return He(n,t);if(Ne(n))return Qt(n,t);if(je(n))return Zt(n,t)}throw Le(n)}function Ge(n,t){return t?en(n,t):Z(n)}function ee(n,t){return P(function(e,s){var r=0;e.subscribe(L(s,function(i){s.next(n.call(t,i,r++))}))})}var tn=Array.isArray;function nn(n,t){return tn(t)?n.apply(void 0,K([],q(t))):n(t)}function sn(n){return ee(function(t){return nn(n,t)})}var rn=Array.isArray,an=Object.getPrototypeOf,on=Object.prototype,cn=Object.keys;function un(n){if(n.length===1){var t=n[0];if(rn(t))return{args:t,keys:null};if(ln(t)){var e=cn(t);return{args:e.map(function(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function ln(n){return n&&typeof n=="object"&&an(n)===on}function dn(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function hn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=ke(n),s=Bt(n),r=un(n),i=r.args,a=r.keys;if(i.length===0)return Ge([],e);var o=new w(fn(i,e,a?function(c){return dn(a,c)}:Q));return s?o.pipe(sn(s)):o}function fn(n,t,e){return e===void 0&&(e=Q),function(s){qe(t,function(){for(var r=n.length,i=new Array(r),a=r,o=r,c=function(d){qe(t,function(){var b=Ge(n[d],t),y=!1;b.subscribe(L(s,function(h){i[d]=h,y||(y=!0,o--),o||s.next(e(i.slice()))},function(){--a||s.complete()}))},s)},u=0;u<r;u++)c(u)},s)}}function qe(n,t,e){n?C(e,n,t):t()}function pn(n,t){return P(function(e,s){var r=0;e.subscribe(L(s,function(i){return n.call(t,i,r++)&&s.next(i)}))})}function gn(n){for(var t,e,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var i=(t=ke(s))!==null&&t!==void 0?t:$t,a=(e=s[0])!==null&&e!==void 0?e:null,o=s[1]||1/0;return P(function(c,u){var d=[],b=!1,y=function(f){var T=f.buffer,I=f.subs;I.unsubscribe(),V(d,f),u.next(T),b&&h()},h=function(){if(d){var f=new U;u.add(f);var T=[],I={buffer:T,subs:f};d.push(I),C(f,i,function(){return y(I)},n)}};a!==null&&a>=0?C(u,i,h,a,!0):b=!0,h();var g=L(u,function(f){var T,I,X=d.slice();try{for(var D=M(X),N=D.next();!N.done;N=D.next()){var B=N.value,H=B.buffer;H.push(f),o<=H.length&&y(B)}}catch(G){T={error:G}}finally{try{N&&!N.done&&(I=D.return)&&I.call(D)}finally{if(T)throw T.error}}},function(){for(;d?.length;)u.next(d.shift().buffer);g?.unsubscribe(),u.complete(),u.unsubscribe()},void 0,function(){return d=null});c.subscribe(g)})}function R(n,t){return t===void 0&&(t=Q),n=n??mn,P(function(e,s){var r,i=!0;e.subscribe(L(s,function(a){var o=t(a);(i||!n(r,o))&&(i=!1,r=o,s.next(a))}))})}function mn(n,t){return n===t}function bn(n){return P(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function vn(n){return P(function(t,e){Z(n).subscribe(L(e,function(){return e.complete()},ie)),!e.closed&&t.subscribe(e)})}function Ke(n){const{endpoint:t,apiKey:e,payload:s,debugMode:r,customHeaders:i}=n,a=n.method??"POST";return new w(o=>{const c=new AbortController;let u,d=!1,b=!1;const y={"Content-Type":"application/json",...i};e&&(y["X-API-KEY"]=e);const h=new URL(t);return r&&h.searchParams.set("is_debug","true"),be(h.toString(),{method:a,headers:y,body:a==="POST"&&s?JSON.stringify(s):void 0,signal:c.signal,openWhenHidden:!0,onopen:async g=>{if(g.ok)u=g.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await g.json()}catch{try{f=await g.text()}catch{f=null}}o.error(new v(g.status,g.statusText,f)),c.abort()}},onmessage:g=>{g.id&&(d=!0);const f=JSON.parse(g.data);u?f.traceId=u:f.requestId&&(f.traceId=f.requestId,u||(u=f.requestId)),o.next(f)},onclose:()=>{o.complete()},onerror:g=>{if(b)throw g;if(!d)throw o.error(g),c.abort(),g}}),()=>{b=!0,c.abort()}})}class Sn{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(s=>s!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(s=>s(...e))}}const yn=50;class En{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new ue;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new Sn;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(Ke({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 s=new URL(this.endpoint);return s.searchParams.set("custom_channel_id",t),this.runSse(Ke({apiKey:this.apiKey,endpoint:s.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 s=new URL(e);s.searchParams.set("custom_channel_id",t);const r={...this.customHeaders};this.apiKey&&(r["X-API-KEY"]=this.apiKey);const i=await fetch(s.toString(),{method:"GET",headers:r});if(i.status===404)return null;if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data??a;return{title:o.title??null,runState:o.runState??"IDLE",lastActivityAt:o.lastActivityAt,launchedSandboxes:(o.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 s=this.deriveSuspendEndpoint();if(!s)throw new Error("Unable to derive channel suspend endpoint. Please provide botProviderEndpoint in config.");const r=new URL(s);r.searchParams.set("custom_channel_id",t),e?.requestId&&r.searchParams.set("request_id",e.requestId),e?.force&&r.searchParams.set("force","true");const i=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!(i.ok||i.status===404))throw new v(i.status,i.statusText,await i.text().catch(()=>{}))}deriveChannelEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel`:null}async deleteChannel(t){const e=this.deriveChannelEndpoint();if(!e)throw new Error("Unable to derive channel endpoint. Please provide botProviderEndpoint in config.");const s=new URL(e);s.searchParams.set("custom_channel_id",t);const r=await fetch(s.toString(),{method:"DELETE",headers:this.apiHeaders()});if(!r.ok)throw new v(r.status,r.statusText,await r.text().catch(()=>{}))}deriveFeedbackEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/feedback`:null}async sendMessageFeedback(t){const e=this.deriveFeedbackEndpoint();if(!e)throw new Error("Unable to derive message feedback endpoint. Please provide botProviderEndpoint in config.");const s=t.comment?.trim(),r={customChannelId:t.customChannelId,messageId:t.messageId,verdict:t.verdict,...s?{comment:s}:{}},i=await fetch(e,{method:"POST",headers:{...this.apiHeaders(),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data??a;return{messageId:o.messageId,seq:o.seq}}runSse(t,e){return t.pipe(gn(e?.delayTime??yn),pn(s=>s.length>0),vn(this.destroy$),bn(()=>this.onRunSettled())).subscribe({next:s=>{if(!this.detached)for(const r of s)e?.onSseMessage?.(r),this.handleEvent(r)},error:s=>{this.detached||e?.onSseError?.(s)},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 s=this.deriveBlobEndpoint();if(!s)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const r=new FormData;r.append("file",t),r.append("customChannelId",e);const i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const a=await fetch(s,{method:"POST",headers:i,body:r});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const o=await a.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",o),o}catch(a){throw console.error("[AsgardServiceClient] File upload error:",a),a}}async downloadChannelHomeFile(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const r=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,i=`${s}/channel-home/download?${r}`,a={...this.customHeaders};this.apiKey&&(a["X-API-KEY"]=this.apiKey);try{const o=await fetch(i,{method:"GET",headers:a});if(!o.ok)throw new Error(`Channel Home download failed: ${o.status} ${o.statusText}`);const c=await o.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(o){throw console.error("[AsgardServiceClient] Channel Home download error:",o),o}}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 s=`${e}/sandbox/${encodeURIComponent(t)}/browser/open-url`,r={...this.customHeaders};this.apiKey&&(r["X-API-KEY"]=this.apiKey);const i=await fetch(s,{method:"POST",headers:r});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data?.openURL??a.openURL;if(!o)throw new Error("Sandbox browser open-url response did not contain an openURL.");return o}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 s=new URL(`${this.deriveSandboxFsEndpoint(t)}/list`);s.searchParams.set("path",e);const r=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!r.ok)throw new v(r.status,r.statusText,await r.text().catch(()=>{}));const i=await r.json(),a=i.data??i;return{entries:a.entries??[],truncated:a.truncated??!1}}async sandboxFsRead(t,e,s){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);r.searchParams.set("path",e),s?.offsetBytes!=null&&r.searchParams.set("offset_bytes",String(s.offsetBytes)),s?.limitBytes!=null&&r.searchParams.set("limit_bytes",String(s.limitBytes));const i=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.blob(),o=i.headers.get("X-Total-Bytes");return{content:a,totalBytes:o!=null?Number(o):a.size,truncated:i.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,s,r){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);i.searchParams.set("path",e),r?.mode!=null&&i.searchParams.set("mode",String(r.mode)),r?.createOnly&&i.searchParams.set("create_only","true");const a=new FormData;a.append("file",s instanceof Blob?s:new Blob([s]));const o=await fetch(i.toString(),{method:"PUT",headers:this.apiHeaders(),body:a,signal:r?.signal});if(!o.ok)throw new v(o.status,o.statusText,await o.text().catch(()=>{}));const c=await o.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,s,r){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(r).forEach(([o,c])=>i.searchParams.set(o,c));const a=await fetch(i.toString(),{method:s,headers:this.apiHeaders()});if(!a.ok)throw new v(a.status,a.statusText,await a.text().catch(()=>{}));return a.json().catch(()=>null)}async sandboxFsStat(t,e){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/stat`);s.searchParams.set("path",e);const r=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!r.ok)throw new v(r.status,r.statusText,await r.text().catch(()=>{}));const i=await r.json(),a=i.data??i;return{exists:a.exists??!1,isDir:a.isDir??!1,sizeBytes:a.sizeBytes??0,mtimeUnix:a.mtimeUnix??0,mode:a.mode??0,etag:a.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,s,r){const i={src:e,dst:s};r?.overwrite&&(i.overwrite="true");const a=await this.sandboxFsRequest(t,"copy","POST",i);return{bytesCopied:(a?.data??a)?.bytesCopied??0}}async sandboxFsMove(t,e,s,r){const i={src:e,dst:s};r?.overwrite&&(i.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",i)}sandboxFsWatch(t,e){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/watch`);return s.searchParams.set("path",e),new w(r=>{const i=new AbortController;return be(s.toString(),{headers:this.apiHeaders(),signal:i.signal,openWhenHidden:!0,onopen:async a=>{if(!a.ok){const o=await a.text().catch(()=>{});r.error(new v(a.status,a.statusText,o)),i.abort()}},onmessage:a=>{a.event==="change"&&r.next(JSON.parse(a.data))},onclose:()=>r.complete(),onerror:a=>{throw r.error(a),i.abort(),a}}),()=>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 Ve="",wn=new Set(["",".",".."]);function A(n,t){if(n===Ve){if(t?.allowRoot)return n;throw new Error("SourceSet volume path must not be empty: the volume root is not a valid target for this operation.")}if(n.startsWith("/"))throw new Error(`SourceSet volume path must be relative, with no leading slash (the root is ""): "${n}".`);if(n.endsWith("/"))throw new Error(`SourceSet volume path must not end with a slash: "${n}".`);if(n.split("/").some(e=>wn.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const le=1e3,Xe=1e4;function We(n){return Math.min(Math.max(1,Math.floor(n)),le)}class In{endpoint;apiKey;customHeaders;constructor(t){this.endpoint=t.sourceSetEndpoint.replace(/\/+$/,""),this.apiKey=t.apiKey,this.customHeaders=t.customHeaders}headers(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async request(t,e,s,r,i){const a=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([c,u])=>a.searchParams.set(c,u));const o=await fetch(a.toString(),{method:e,headers:this.headers(),body:r,signal:i});if(!o.ok)throw new v(o.status,o.statusText,await o.text().catch(()=>{}));return o}async list(t,e){const s={path:A(t,{allowRoot:!0})};e?.page!=null&&(s.page=String(e.page)),e?.pageSize!=null&&(s.page_size=String(We(e.pageSize)));const i=await(await this.request("list","GET",s)).json(),a=i.data??i;return{entries:a.entries??[],paging:a.paging??i.paging??null}}async listAll(t,e){const s=We(e?.pageSize??le),r=e?.maxEntries??Xe,i=[];let a=0,o=!0,c=0;for(;;){const u=await this.list(t,{page:c,pageSize:s}),d=u.paging;if(d&&d.index!==c){a=d.total,o=!1;break}if(i.push(...u.entries),!d){o=u.entries.length<s;break}if(a=d.total,i.length>=a)break;if(i.length>=r||u.entries.length===0){o=!1;break}c+=1}return{entries:i,total:a,complete:o}}async stat(t){const s=await(await this.request("stat","GET",{path:A(t)})).json(),r=s.data??s;return{exists:r.exists??!1,isDir:r.isDir??!1,sizeBytes:r.sizeBytes??0,mtimeUnix:r.mtimeUnix??0,mode:r.mode??0,etag:r.etag}}async read(t,e){const s={path:A(t)};e?.offsetBytes!=null&&(s.offset_bytes=String(e.offsetBytes)),e?.limitBytes!=null&&(s.limit_bytes=String(e.limitBytes));const r=await this.request("file","GET",s),i=await r.blob(),a=r.headers.get("X-Total-Bytes");return{content:i,totalBytes:a!=null?Number(a):i.size,truncated:r.headers.get("X-Truncated")==="true"}}async write(t,e,s){const r={path:A(t)};s?.mode!=null&&(r.mode=String(s.mode)),s?.createOnly&&(r.create_only="true");const i=new FormData;i.append("file",e instanceof Blob?e:new Blob([e]));const o=await(await this.request("file","PUT",r,i,s?.signal)).json();return{bytesWritten:(o.data??o).bytesWritten??0}}async mkdir(t,e){await this.request("mkdir","POST",{path:A(t)},void 0,e?.signal)}async remove(t){await this.request("item","DELETE",{path:A(t)})}async removeAll(t){await this.request("all","DELETE",{path:A(t)})}async copy(t,e,s){const r=this.copyMoveQuery(t,e,s),a=await(await this.request("copy","POST",r)).json();return{bytesCopied:(a.data??a).bytesCopied??0}}async move(t,e,s){await this.request("move","POST",this.copyMoveQuery(t,e,s))}copyMoveQuery(t,e,s){const r={src:A(t),dst:A(e)};return s?.overwrite&&(r.overwrite="true"),r}}const E=[];for(let n=0;n<256;++n)E.push((n+256).toString(16).slice(1));function Tn(n,t=0){return(E[n[t+0]]+E[n[t+1]]+E[n[t+2]]+E[n[t+3]]+"-"+E[n[t+4]]+E[n[t+5]]+"-"+E[n[t+6]]+E[n[t+7]]+"-"+E[n[t+8]]+E[n[t+9]]+"-"+E[n[t+10]]+E[n[t+11]]+E[n[t+12]]+E[n[t+13]]+E[n[t+14]]+E[n[t+15]]).toLowerCase()}let de;const Cn=new Uint8Array(16);function An(){if(!de){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");de=crypto.getRandomValues.bind(crypto)}return de(Cn)}const Ye={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function On(n,t,e){n=n||{};const s=n.random??n.rng?.()??An();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Tn(s)}function ze(n,t,e){return Ye.randomUUID&&!n?Ye.randomUUID():On(n)}class m{messages=null;pendingConsent=null;pendingFeedback=null;constructor({messages:t,pendingConsent:e=null,pendingFeedback:s=null}){this.messages=t,this.pendingConsent=e??null,this.pendingFeedback=s??null}pushMessage(t){const e=new Map(this.messages);return e.set(t.messageId,t),new m({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}clearPendingConsent(){return this.pendingConsent?new m({messages:this.messages,pendingConsent:null,pendingFeedback:this.pendingFeedback}):this}restorePendingConsent(t){return this.pendingConsent?this:new m({messages:this.messages,pendingConsent:t,pendingFeedback:this.pendingFeedback})}settleInFlightMessages(){if(!this.messages)return this;let t=!1;const e=new Map(this.messages);for(const[s,r]of e)r.type==="tool-call"&&!r.isComplete&&(e.set(s,{...r,isComplete:!0,isCancelled:!0}),t=!0),r.type==="thinking"&&r.isThinking&&(e.set(s,{...r,isThinking:!1}),t=!0);return t?new m({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback}):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_FEEDBACK:return this.onMessageFeedback(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.MESSAGE_CANVAS_START:return this.onCanvasStart(t);case l.MESSAGE_CANVAS_DELTA:return this.onCanvasDelta(t);case l.MESSAGE_CANVAS_COMPLETE:return this.onCanvasComplete(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}isTerminalToolCall(t){return t?.type==="tool-call"&&t.isComplete===!0}isTerminalCanvas(t){return t?.type==="canvas"&&!t.isDrawing}onMessageStart(t){const e=t.fact.messageStart.message;if(e.parentToolUseId)return this;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages);return s.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 m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageDelta(t){const e=t.fact.messageDelta.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId);if(this.isTerminalBot(s))return this;const r=s?.type==="bot"?s:void 0,i=new Map(this.messages);return i.set(e.messageId,{type:"bot",eventType:l.MESSAGE_DELTA,isTyping:!0,typingText:`${r?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??r?.traceId,raw:r?.raw??""}),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageComplete(t){const e=t.fact.messageComplete.message;if(e.parentToolUseId)return this;const s=new Map(this.messages),r=s.get(e.messageId),i=r?.type==="bot"?r:void 0,a=this.pendingFeedback?.get(e.messageId),o=a??i?.feedback;s.set(e.messageId,{type:"bot",eventType:l.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,...o?{feedback:o}:{},time:new Date,traceId:t.traceId??i?.traceId,raw:JSON.stringify(t)});let c=this.pendingFeedback;return a&&(c=new Map(this.pendingFeedback),c.delete(e.messageId)),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:c})}onMessageFeedback(t){const e=t.fact.messageFeedback,s={verdict:e.verdict,...e.text?{comment:e.text}:{}};return this.applyFeedback(e.targetMessageId,s)}applyFeedback(t,e){const s=this.messages?.get(t);if(s?.type==="bot"){const i=new Map(this.messages),a={...s,feedback:e};return i.set(t,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const r=new Map(this.pendingFeedback);return r.set(t,e),new m({messages:this.messages,pendingConsent:this.pendingConsent,pendingFeedback:r})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(e.parentToolUseId)return this;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages),r={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return s.set(e.messageId,r),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onThinkingDelta(t){const e=t.fact.messageThinkingDelta.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId);if(this.isTerminalThinking(s))return this;const r=s?.type==="thinking"?s:void 0,i=new Map(this.messages),a={type:"thinking",messageId:e.messageId,text:`${r?.text??""}${e.text}`,isThinking:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onThinkingComplete(t){const e=t.fact.messageThinkingComplete.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId),r=s?.type==="thinking"?s:void 0,i=new Map(this.messages),a={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasStart(t){const e=t.fact.messageCanvasStart.message;if(e.parentToolUseId)return this;if(this.isTerminalCanvas(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages),r={type:"canvas",messageId:e.messageId,html:"",isDrawing:!0,time:new Date,traceId:t.traceId};return s.set(e.messageId,r),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasDelta(t){const e=t.fact.messageCanvasDelta.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId);if(this.isTerminalCanvas(s))return this;const r=s?.type==="canvas"?s:void 0,i=new Map(this.messages),a={type:"canvas",messageId:e.messageId,html:`${r?.html??""}${e.text}`,title:r?.title,isDrawing:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const s=e.template?.type===te.CANVAS?e.template:void 0,r=s?.canvas?.html;if(!r){if(!this.messages?.has(e.messageId))return this;const u=new Map(this.messages);return u.delete(e.messageId),new m({messages:u,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const i=this.messages?.get(e.messageId),a=i?.type==="canvas"?i:void 0,o=new Map(this.messages),c={type:"canvas",messageId:e.messageId,html:r,title:s?.title,isDrawing:!1,time:a?.time??new Date,traceId:t.traceId??a?.traceId};return o.set(e.messageId,c),new m({messages:o,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}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 r=new Map(this.messages),i={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,blobs:e.blobs,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return r.set(e.messageId,i),new m({messages:r,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageError(t){const e=ze(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new m({messages:r,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallStart(t){const e=t.fact.toolCallStart,s=new Map(this.messages),r=`${e.processId}-${e.callSeq}`;if(this.isTerminalToolCall(this.messages?.get(r)))return this;const i={type:"tool-call",eventType:l.TOOL_CALL_START,messageId:r,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 s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallComplete(t){const e=t.fact.toolCallComplete,s=new Map(this.messages),r=`${e.processId}-${e.callSeq}`,i=s.get(r);if(i?.type==="tool-call"){const a={...i,eventType:l.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??i.traceId};s.set(r,a)}else{const a={type:"tool-call",eventType:l.TOOL_CALL_COMPLETE,messageId:r,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,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,time:new Date,traceId:t.traceId};s.set(r,a)}return new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new m({messages:this.messages,pendingConsent:e,pendingFeedback:this.pendingFeedback})}onSubagentStart(t){const e=t.fact.subagentStart,s=new Map(this.messages),r=`subagent:${e.parentToolUseId}:start`,i={type:"subagent",messageId:r,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return s.delete(r),s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onSubagentComplete(t){const e=t.fact.subagentComplete,s=new Map(this.messages),r=`subagent:${e.parentToolUseId}:complete`,i={type:"subagent",messageId:r,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return s.delete(r),s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}}const xn=new Set(["TaskCreate","TaskUpdate"]);function Je(n){return n.toolsetName===""&&xn.has(n.toolName)}function Qe(n){return typeof n=="object"&&n!==null?n:void 0}function k(n){return typeof n=="string"?n:void 0}function Ze(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},i=s.sidecar??{};if(s.toolName==="TaskCreate"){const a=Qe(i.task),o=k(a?.id);if(!o)continue;e.has(o)||t.push(o),e.set(o,{id:o,subject:k(r.subject)||k(a?.subject)||"",activeForm:k(r.activeForm),description:k(r.description),status:e.get(o)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const a=Qe(i.statusChange),o=k(r.taskId)||k(i.taskId),c=k(a?.to)||k(r.status);if(!o||!c)continue;const u=e.get(o);u&&e.set(o,{...u,status:c})}}return t.map(s=>e.get(s))}function et(n){return n.toolsetName===""&&n.toolName==="Agent"}function tt(n){return!!n}function nt(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function st(n){const t=[],e=new Map,s=new Map,r=i=>(e.has(i)||(t.push(i),e.set(i,{status:"running"}),s.set(i,new Map)),e.get(i));for(const i of n)switch(i.kind){case"agentStart":{const a=r(i.toolUseId);i.description&&!a.description&&(a.description=i.description);break}case"subagentStart":{const a=r(i.parentToolUseId);a.agentId=i.agentId??a.agentId,a.subagentType=i.subagentType??a.subagentType,a.description=i.description??a.description,nt(a);break}case"toolStart":{nt(r(i.parentToolUseId)),s.get(i.parentToolUseId).set(i.toolUseId,{toolsetName:i.toolsetName,toolName:i.toolName,parameter:i.parameter??{},reason:i.reason,status:"running"});break}case"toolComplete":{const a=s.get(i.parentToolUseId)?.get(i.toolUseId);a&&(a.status=i.isError?"error":"completed");break}case"subagentComplete":{const a=r(i.parentToolUseId);a.status=i.status,a.summary=i.summary;break}}return t.map(i=>({parentToolUseId:i,...e.get(i),tools:Array.from(s.get(i).values())}))}function kn(n){return typeof n=="string"?n:void 0}function rt(n){const t=[];for(const e of n){if(e.type==="tool-call"&&et(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:kn(e.parameter.description)});continue}if(e.type==="tool-call"&&tt(e.parentToolUseId)){const s=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:s,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:s,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 it(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Je(e));return Ze(t)}function at(n){return st(rt(Array.from(n.messages?.values()??[])))}function ot(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.id===r.id&&e.status===r.status&&e.subject===r.subject&&e.activeForm===r.activeForm&&e.description===r.description})}function Pn(n,t){return n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.toolName===r.toolName&&e.toolsetName===r.toolsetName&&e.status===r.status&&e.reason===r.reason})}function ct(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.parentToolUseId===r.parentToolUseId&&e.status===r.status&&e.subagentType===r.subagentType&&e.description===r.description&&e.summary===r.summary&&Pn(e.tools,r.tools)})}function ut(n){const t=new x([]),e=new x([]),s=new U;return s.add(n.pipe(ee(it),R(ot)).subscribe(t)),s.add(n.pipe(ee(at),R(ct)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function he(n){const t=new Map;for(const e of n)t.set(e.sandboxName,e);return[...t.values()].sort((e,s)=>(e.sandboxBlueprintName||e.sandboxName).localeCompare(s.sandboxBlueprintName||s.sandboxName))}const fe={kind:null,stopPhase:"idle"},_n=1e4;function Mn(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class ${client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;promptSuggestion$;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 x(!1),this.runStatusSubject=new x(fe),this.conversation$=new x(t.conversation),this.channelTitleSubject=new x(t.channelTitle??null),this.promptSuggestionSubject=new x(null),this.sandboxPhaseSubject=new x("idle"),this.launchedSandboxesSubject=new x(he(t.launchedSandboxes??[])),this.derivedStores=ut(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(R()),this.promptSuggestion$=this.promptSuggestionSubject.pipe(R()),this.sandboxPhase$=this.sandboxPhaseSubject.pipe(R()),this.launchedSandboxes$=this.launchedSandboxesSubject.pipe(R()),this.runStatus$=this.runStatusSubject.pipe(R(Mn)),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}getPromptSuggestion(){return this.promptSuggestionSubject.value}clearPromptSuggestion(){this.promptSuggestionSubject.next(null)}getSandboxPhase(){return this.sandboxPhaseSubject.value}getLaunchedSandboxes(){return this.launchedSandboxesSubject.value}getRunStatus(){return this.runStatusSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=he(t);this.pendingLaunches=this.pendingLaunches.filter(s=>!e.some(r=>r.sandboxName===s)),this.launchedSandboxesSubject.next(e)}dropSandbox(t){const e=this.launchedSandboxesSubject.value,s=e.filter(r=>r.sandboxName!==t);s.length!==e.length&&this.launchedSandboxesSubject.next(s)}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 $(t);return e.subscribe(),e}static async open(t,e,s,r){const i=new $(t);try{return i.subscribe(),r?.(i),await i.openChannel(e,s),i}catch(a){throw i.close(),a}}static async reset(t,e,s,r){if(!t.client.deleteChannel)throw new Error("This client cannot reset a channel: IAsgardServiceClient.deleteChannel is not implemented. Implement it (DELETE {base}/channel?custom_channel_id=…) or use AsgardServiceClient.");return await t.client.deleteChannel(t.customChannelId),$.open(t,e,s,r)}static async restore(t,e,s){const r=new $(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(i){throw r.close(),i}}subscribe(){this.statesSubscription=hn([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.promptSuggestion$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe(ee(([t,e,s,r,i,a,o,c,u])=>({isConnecting:t,conversation:e,tasks:s,subagents:r,channelTitle:i,promptSuggestion:a,sandboxPhase:o,launchedSandboxes:c,runStatus:u}))).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,s){return{onSseStart:t?.onSseStart,onSseMessage:r=>{if(t?.onSseMessage?.(r),this.captureRequestId(r.requestId),r.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(r.fact.channelTitleUpdate.title),r.eventType===l.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(r.fact.promptSuggestion.suggestion):r.eventType===l.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(r.eventType),r.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(r.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&r.traceId){const i=new Map(this.conversation$.value.messages),a=i.get(this.currentUserMessageId);a&&a.type==="user"&&(i.set(this.currentUserMessageId,{...a,traceId:r.traceId}),this.conversation$.next(new m({messages:i,pendingConsent:this.conversation$.value.pendingConsent,pendingFeedback:this.conversation$.value.pendingFeedback}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(r))},onSseError:r=>{t?.onSseError?.(r),this.settleRun(),s(r)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.settleRun(),e()}}}settleRun(){const t=this.runStatusSubject.value.stopPhase!=="idle";this.clearForceStopTimer(),this.isConnecting$.next(!1),this.runStatusSubject.next(fe),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,s){return new Promise((r,i)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(s,r,i))})}rejoinChannel(t){return new Promise((e,s)=>{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,s))})}openChannel(t,e){return this.fetchSse("reset",{action:F.NONE,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new W(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new Y(r.processId));this.clearPromptSuggestion();const i=t.text.trim(),a=t.customMessageId??ze();return this.currentUserMessageId=a,this.lastSentMessageId=a,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:a,text:i,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:F.NONE,customChannelId:this.customChannelId,customMessageId:a,payload:this.resolvePayload(t?.payload),text:i,blobIds:t?.blobIds},e)}async sendMessageFeedback(t,e){if(!this.client.sendMessageFeedback)throw new Error("This client cannot rate a reply: IAsgardServiceClient.sendMessageFeedback is not implemented. Implement it (POST {base}/message/feedback) or use AsgardServiceClient.");const s=await this.client.sendMessageFeedback({customChannelId:this.customChannelId,messageId:t,verdict:e.verdict,comment:e.comment}),r=e.comment?.trim();return this.conversation$.next(this.conversation$.value.applyFeedback(t,{verdict:e.verdict,...r?{comment:r}:{}})),s}replyToolCallConsents(t,e,s){const r=this.conversation$.value.pendingConsent;return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse("user",{action:F.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(s),text:"",toolCallConsents:t},e).catch(i=>{throw r&&this.conversation$.next(this.conversation$.value.restorePendingConsent(r)),i})}nudge(t,e){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new W(s));const r=this.conversation$.value.pendingConsent;return r?Promise.reject(new Y(r.processId)):this.fetchSse("nudge",{action:F.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(s){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),s}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"})},_n)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(fe),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()}}const lt={GOOD:"[Response Feedback: Good]",BAD:"[Response Feedback: Bad]"},Un=8*1024;function Ln(n){return new TextEncoder().encode(n).length}function Rn(n,t){const e=lt[n],s=t?.trim()??"";return s?`${e}
4
+ `):"",this.name="UnsubscriptionError",this.errors=e}});function V(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var U=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,s,r,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var o=M(a),c=o.next();!c.done;c=o.next()){var u=c.value;u.remove(this)}}catch(f){t={error:f}}finally{try{c&&!c.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}else a.remove(this);var d=this.initialTeardown;if(S(d))try{d()}catch(f){i=f instanceof re?f.errors:[f]}var b=this._finalizers;if(b){this._finalizers=null;try{for(var y=M(b),h=y.next();!h.done;h=y.next()){var g=h.value;try{Ee(g)}catch(f){i=i??[],f instanceof re?i=K(K([],q(i)),q(f.errors)):i.push(f)}}}catch(f){s={error:f}}finally{try{h&&!h.done&&(r=y.return)&&r.call(y)}finally{if(s)throw s.error}}}if(i)throw new re(i)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)Ee(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)&&V(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&V(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),ye=U.EMPTY;function we(n){return n instanceof U||n&&"closed"in n&&S(n.remove)&&S(n.add)&&S(n.unsubscribe)}function Ee(n){S(n)?n():n.unsubscribe()}var Ct={Promise:void 0},At={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,K([n,t],q(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Ie(n){At.setTimeout(function(){throw n})}function ie(){}function z(n){n()}var ae=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,we(e)&&e.add(s)):s.destination=kt,s}return t.create=function(e,s,r){return new oe(e,s,r)},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})(U),Ot=(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(s){J(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){J(s)}else J(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){J(e)}},n})(),oe=(function(n){O(t,n);function t(e,s,r){var i=n.call(this)||this,a;return S(e)||!e?a={next:e??void 0,error:s??void 0,complete:r??void 0}:a=e,i.destination=new Ot(a),i}return t})(ae);function J(n){Ie(n)}function xt(n){throw n}var kt={closed:!0,next:ie,error:xt,complete:ie},ce=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Q(n){return n}function _t(n){return n.length===0?Q:n.length===1?n[0]:function(e){return n.reduce(function(s,r){return r(s)},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,s){var r=this,i=Mt(t)?t:new oe(t,e,s);return z(function(){var a=r,o=a.operator,c=a.source;i.add(o?o.call(i,c):c?r._subscribe(i):r._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 s=this;return e=Te(e),new e(function(r,i){var a=new oe({next:function(o){try{t(o)}catch(c){i(c),a.unsubscribe()}},error:i,complete:r});s.subscribe(a)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[ce]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return _t(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=Te(t),new t(function(s,r){var i;e.subscribe(function(a){return i=a},function(a){return r(a)},function(){return s(i)})})},n.create=function(t){return new n(t)},n})();function Te(n){var t;return(t=n??Ct.Promise)!==null&&t!==void 0?t:Promise}function Pt(n){return n&&S(n.next)&&S(n.error)&&S(n.complete)}function Mt(n){return n&&n instanceof ae||Pt(n)&&we(n)}function Ut(n){return S(n?.lift)}function _(n){return function(t){if(Ut(t))return t.lift(function(e){try{return n(e,this)}catch(s){this.error(s)}});throw new TypeError("Unable to lift unknown Observable type")}}function L(n,t,e,s,r){return new Lt(n,t,e,s,r)}var Lt=(function(n){O(t,n);function t(e,s,r,i,a,o){var c=n.call(this,e)||this;return c.onFinalize=a,c.shouldUnsubscribe=o,c._next=s?function(u){try{s(u)}catch(d){e.error(d)}}:n.prototype._next,c._error=i?function(u){try{i(u)}catch(d){e.error(d)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=r?function(){try{r()}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 s=this.closed;n.prototype.unsubscribe.call(this),!s&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ae),Nt=Se(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ue=(function(n){O(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 s=new Ce(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Nt},t.prototype.next=function(e){var s=this;z(function(){var r,i;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var a=M(s.currentObservers),o=a.next();!o.done;o=a.next()){var c=o.value;c.next(e)}}catch(u){r={error:u}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var s=this;z(function(){if(s._throwIfClosed(),!s.isStopped){s.hasError=s.isStopped=!0,s.thrownError=e;for(var r=s.observers;r.length;)r.shift().error(e)}})},t.prototype.complete=function(){var e=this;z(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var s=e.observers;s.length;)s.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 s=this,r=this,i=r.hasError,a=r.isStopped,o=r.observers;return i||a?ye:(this.currentObservers=null,o.push(e),new U(function(){s.currentObservers=null,V(o,e)}))},t.prototype._checkFinalizedStatuses=function(e){var s=this,r=s.hasError,i=s.thrownError,a=s.isStopped;r?e.error(i):a&&e.complete()},t.prototype.asObservable=function(){var e=new E;return e.source=this,e},t.create=function(e,s){return new Ce(e,s)},t})(E),Ce=(function(n){O(t,n);function t(e,s){var r=n.call(this)||this;return r.destination=e,r.source=s,r}return t.prototype.next=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.next)===null||r===void 0||r.call(s,e)},t.prototype.error=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.error)===null||r===void 0||r.call(s,e)},t.prototype.complete=function(){var e,s;(s=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||s===void 0||s.call(e)},t.prototype._subscribe=function(e){var s,r;return(r=(s=this.source)===null||s===void 0?void 0:s.subscribe(e))!==null&&r!==void 0?r:ye},t})(ue),x=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s._value=e,s}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var s=n.prototype._subscribe.call(this,e);return!s.closed&&e.next(this._value),s},t.prototype.getValue=function(){var e=this,s=e.hasError,r=e.thrownError,i=e._value;if(s)throw r;return this._throwIfClosed(),i},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(ue),Rt={now:function(){return Date.now()}},Ft=(function(n){O(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(U),Ae={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,K([n,t],q(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},jt=(function(n){O(t,n);function t(e,s){var r=n.call(this,e,s)||this;return r.scheduler=e,r.work=s,r.pending=!1,r}return t.prototype.schedule=function(e,s){var r;if(s===void 0&&(s=0),this.closed)return this;this.state=e;var i=this.id,a=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(a,i,s)),this.pending=!0,this.delay=s,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(a,this.id,s),this},t.prototype.requestAsyncId=function(e,s,r){return r===void 0&&(r=0),Ae.setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,s,r){if(r===void 0&&(r=0),r!=null&&this.delay===r&&this.pending===!1)return s;s!=null&&Ae.clearInterval(s)},t.prototype.execute=function(e,s){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,s);if(r)return r;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,s){var r=!1,i;try{this.work(e)}catch(a){r=!0,i=a||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,s=e.id,r=e.scheduler,i=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,V(i,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Ft),Oe=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,s){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(s,e)},n.now=Rt.now,n})(),$t=(function(n){O(t,n);function t(e,s){s===void 0&&(s=Oe.now);var r=n.call(this,e,s)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(e){var s=this.actions;if(this._active){s.push(e);return}var r;this._active=!0;do if(r=e.execute(e.state,e.delay))break;while(e=s.shift());if(this._active=!1,r){for(;e=s.shift();)e.unsubscribe();throw r}},t})(Oe),Dt=new $t(jt);function Bt(n){return n&&S(n.schedule)}function xe(n){return n[n.length-1]}function Ht(n){return S(xe(n))?n.pop():void 0}function ke(n){return Bt(xe(n))?n.pop():void 0}var _e=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function Pe(n){return S(n?.then)}function Me(n){return S(n[ce])}function Ue(n){return Symbol.asyncIterator&&S(n?.[Symbol.asyncIterator])}function Le(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 Gt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ne=Gt();function Re(n){return S(n?.[Ne])}function Fe(n){return It(this,arguments,function(){var e,s,r,i;return ve(this,function(a){switch(a.label){case 0:e=n.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,j(e.read())];case 3:return s=a.sent(),r=s.value,i=s.done,i?[4,j(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,j(r)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function je(n){return S(n?.getReader)}function Z(n){if(n instanceof E)return n;if(n!=null){if(Me(n))return qt(n);if(_e(n))return Kt(n);if(Pe(n))return Vt(n);if(Ue(n))return $e(n);if(Re(n))return Xt(n);if(je(n))return Wt(n)}throw Le(n)}function qt(n){return new E(function(t){var e=n[ce]();if(S(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Kt(n){return new E(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Vt(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,Ie)})}function Xt(n){return new E(function(t){var e,s;try{for(var r=M(n),i=r.next();!i.done;i=r.next()){var a=i.value;if(t.next(a),t.closed)return}}catch(o){e={error:o}}finally{try{i&&!i.done&&(s=r.return)&&s.call(r)}finally{if(e)throw e.error}}t.complete()})}function $e(n){return new E(function(t){Yt(n,t).catch(function(e){return t.error(e)})})}function Wt(n){return $e(Fe(n))}function Yt(n,t){var e,s,r,i;return Et(this,void 0,void 0,function(){var a,o;return ve(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=Tt(n),c.label=1;case 1:return[4,e.next()];case 2:if(s=c.sent(),!!s.done)return[3,4];if(a=s.value,t.next(a),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return o=c.sent(),r={error:o},[3,11];case 6:return c.trys.push([6,,9,10]),s&&!s.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(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function C(n,t,e,s,r){s===void 0&&(s=0),r===void 0&&(r=!1);var i=t.schedule(function(){e(),r?n.add(this.schedule(null,s)):this.unsubscribe()},s);if(n.add(i),!r)return i}function De(n,t){return t===void 0&&(t=0),_(function(e,s){e.subscribe(L(s,function(r){return C(s,n,function(){return s.next(r)},t)},function(){return C(s,n,function(){return s.complete()},t)},function(r){return C(s,n,function(){return s.error(r)},t)}))})}function Be(n,t){return t===void 0&&(t=0),_(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function zt(n,t){return Z(n).pipe(Be(t),De(t))}function Jt(n,t){return Z(n).pipe(Be(t),De(t))}function Qt(n,t){return new E(function(e){var s=0;return t.schedule(function(){s===n.length?e.complete():(e.next(n[s++]),e.closed||this.schedule())})})}function Zt(n,t){return new E(function(e){var s;return C(e,t,function(){s=n[Ne](),C(e,t,function(){var r,i,a;try{r=s.next(),i=r.value,a=r.done}catch(o){e.error(o);return}a?e.complete():e.next(i)},0,!0)}),function(){return S(s?.return)&&s.return()}})}function He(n,t){if(!n)throw new Error("Iterable cannot be null");return new E(function(e){C(e,t,function(){var s=n[Symbol.asyncIterator]();C(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function en(n,t){return He(Fe(n),t)}function tn(n,t){if(n!=null){if(Me(n))return zt(n,t);if(_e(n))return Qt(n,t);if(Pe(n))return Jt(n,t);if(Ue(n))return He(n,t);if(Re(n))return Zt(n,t);if(je(n))return en(n,t)}throw Le(n)}function Ge(n,t){return t?tn(n,t):Z(n)}function ee(n,t){return _(function(e,s){var r=0;e.subscribe(L(s,function(i){s.next(n.call(t,i,r++))}))})}var nn=Array.isArray;function sn(n,t){return nn(t)?n.apply(void 0,K([],q(t))):n(t)}function rn(n){return ee(function(t){return sn(n,t)})}var an=Array.isArray,on=Object.getPrototypeOf,cn=Object.prototype,un=Object.keys;function ln(n){if(n.length===1){var t=n[0];if(an(t))return{args:t,keys:null};if(dn(t)){var e=un(t);return{args:e.map(function(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function dn(n){return n&&typeof n=="object"&&on(n)===cn}function hn(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function fn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=ke(n),s=Ht(n),r=ln(n),i=r.args,a=r.keys;if(i.length===0)return Ge([],e);var o=new E(pn(i,e,a?function(c){return hn(a,c)}:Q));return s?o.pipe(rn(s)):o}function pn(n,t,e){return e===void 0&&(e=Q),function(s){qe(t,function(){for(var r=n.length,i=new Array(r),a=r,o=r,c=function(d){qe(t,function(){var b=Ge(n[d],t),y=!1;b.subscribe(L(s,function(h){i[d]=h,y||(y=!0,o--),o||s.next(e(i.slice()))},function(){--a||s.complete()}))},s)},u=0;u<r;u++)c(u)},s)}}function qe(n,t,e){n?C(e,n,t):t()}function gn(n,t){return _(function(e,s){var r=0;e.subscribe(L(s,function(i){return n.call(t,i,r++)&&s.next(i)}))})}function mn(n){for(var t,e,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var i=(t=ke(s))!==null&&t!==void 0?t:Dt,a=(e=s[0])!==null&&e!==void 0?e:null,o=s[1]||1/0;return _(function(c,u){var d=[],b=!1,y=function(f){var T=f.buffer,I=f.subs;I.unsubscribe(),V(d,f),u.next(T),b&&h()},h=function(){if(d){var f=new U;u.add(f);var T=[],I={buffer:T,subs:f};d.push(I),C(f,i,function(){return y(I)},n)}};a!==null&&a>=0?C(u,i,h,a,!0):b=!0,h();var g=L(u,function(f){var T,I,X=d.slice();try{for(var D=M(X),R=D.next();!R.done;R=D.next()){var B=R.value,H=B.buffer;H.push(f),o<=H.length&&y(B)}}catch(G){T={error:G}}finally{try{R&&!R.done&&(I=D.return)&&I.call(D)}finally{if(T)throw T.error}}},function(){for(;d?.length;)u.next(d.shift().buffer);g?.unsubscribe(),u.complete(),u.unsubscribe()},void 0,function(){return d=null});c.subscribe(g)})}function N(n,t){return t===void 0&&(t=Q),n=n??bn,_(function(e,s){var r,i=!0;e.subscribe(L(s,function(a){var o=t(a);(i||!n(r,o))&&(i=!1,r=o,s.next(a))}))})}function bn(n,t){return n===t}function vn(n){return _(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function Sn(n){return _(function(t,e){Z(n).subscribe(L(e,function(){return e.complete()},ie)),!e.closed&&t.subscribe(e)})}function Ke(n){const{endpoint:t,apiKey:e,payload:s,debugMode:r,customHeaders:i}=n,a=n.method??"POST";return new E(o=>{const c=new AbortController;let u,d=!1,b=!1;const y={"Content-Type":"application/json",...i};e&&(y["X-API-KEY"]=e);const h=new URL(t);return r&&h.searchParams.set("is_debug","true"),be(h.toString(),{method:a,headers:y,body:a==="POST"&&s?JSON.stringify(s):void 0,signal:c.signal,openWhenHidden:!0,onopen:async g=>{if(g.ok)u=g.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await g.json()}catch{try{f=await g.text()}catch{f=null}}o.error(new v(g.status,g.statusText,f)),c.abort()}},onmessage:g=>{g.id&&(d=!0);const f=JSON.parse(g.data);u?f.traceId=u:f.requestId&&(f.traceId=f.requestId,u||(u=f.requestId)),o.next(f)},onclose:()=>{o.complete()},onerror:g=>{if(b)throw g;if(!d)throw o.error(g),c.abort(),g}}),()=>{b=!0,c.abort()}})}class yn{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(s=>s!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(s=>s(...e))}}const wn=50;function Ve(n,t){return t?.customChannelId&&n.searchParams.set("custom_channel_id",t.customChannelId),n}class En{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new ue;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new yn;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(Ke({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 s=new URL(this.endpoint);return s.searchParams.set("custom_channel_id",t),this.runSse(Ke({apiKey:this.apiKey,endpoint:s.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 s=new URL(e);s.searchParams.set("custom_channel_id",t);const r={...this.customHeaders};this.apiKey&&(r["X-API-KEY"]=this.apiKey);const i=await fetch(s.toString(),{method:"GET",headers:r});if(i.status===404)return null;if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data??a;return{title:o.title??null,runState:o.runState??"IDLE",lastActivityAt:o.lastActivityAt,launchedSandboxes:(o.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 s=this.deriveSuspendEndpoint();if(!s)throw new Error("Unable to derive channel suspend endpoint. Please provide botProviderEndpoint in config.");const r=new URL(s);r.searchParams.set("custom_channel_id",t),e?.requestId&&r.searchParams.set("request_id",e.requestId),e?.force&&r.searchParams.set("force","true");const i=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!(i.ok||i.status===404))throw new v(i.status,i.statusText,await i.text().catch(()=>{}))}deriveChannelEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel`:null}async deleteChannel(t){const e=this.deriveChannelEndpoint();if(!e)throw new Error("Unable to derive channel endpoint. Please provide botProviderEndpoint in config.");const s=new URL(e);s.searchParams.set("custom_channel_id",t);const r=await fetch(s.toString(),{method:"DELETE",headers:this.apiHeaders()});if(!r.ok)throw new v(r.status,r.statusText,await r.text().catch(()=>{}))}deriveFeedbackEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/feedback`:null}async sendMessageFeedback(t){const e=this.deriveFeedbackEndpoint();if(!e)throw new Error("Unable to derive message feedback endpoint. Please provide botProviderEndpoint in config.");const s=t.comment?.trim(),r={customChannelId:t.customChannelId,messageId:t.messageId,verdict:t.verdict,...s?{comment:s}:{}},i=await fetch(e,{method:"POST",headers:{...this.apiHeaders(),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data??a;return{messageId:o.messageId,seq:o.seq}}runSse(t,e){return t.pipe(mn(e?.delayTime??wn),gn(s=>s.length>0),Sn(this.destroy$),vn(()=>this.onRunSettled())).subscribe({next:s=>{if(!this.detached)for(const r of s)e?.onSseMessage?.(r),this.handleEvent(r)},error:s=>{this.detached||e?.onSseError?.(s)},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 s=this.deriveBlobEndpoint();if(!s)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const r=new FormData;r.append("file",t),r.append("customChannelId",e);const i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const a=await fetch(s,{method:"POST",headers:i,body:r});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const o=await a.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",o),o}catch(a){throw console.error("[AsgardServiceClient] File upload error:",a),a}}async downloadChannelHomeFile(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const r=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,i=`${s}/channel-home/download?${r}`,a={...this.customHeaders};this.apiKey&&(a["X-API-KEY"]=this.apiKey);try{const o=await fetch(i,{method:"GET",headers:a});if(!o.ok)throw new Error(`Channel Home download failed: ${o.status} ${o.statusText}`);const c=await o.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(o){throw console.error("[AsgardServiceClient] Channel Home download error:",o),o}}async generateSandboxBrowserOpenUrl(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive sandbox browser open-url endpoint. Please provide botProviderEndpoint in config.");const r=Ve(new URL(`${s}/sandbox/${encodeURIComponent(t)}/browser/open-url`),e),i=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data?.openURL??a.openURL;if(!o)throw new Error("Sandbox browser open-url response did not contain an openURL.");return o}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`}sandboxFsUrl(t,e,s){return Ve(new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`),s)}apiHeaders(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async sandboxFsList(t,e,s){const r=this.sandboxFsUrl(t,"list",s);r.searchParams.set("path",e);const i=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data??a;return{entries:o.entries??[],truncated:o.truncated??!1}}async sandboxFsRead(t,e,s){const r=this.sandboxFsUrl(t,"file",s);r.searchParams.set("path",e),s?.offsetBytes!=null&&r.searchParams.set("offset_bytes",String(s.offsetBytes)),s?.limitBytes!=null&&r.searchParams.set("limit_bytes",String(s.limitBytes));const i=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.blob(),o=i.headers.get("X-Total-Bytes");return{content:a,totalBytes:o!=null?Number(o):a.size,truncated:i.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,s,r){const i=this.sandboxFsUrl(t,"file",r);i.searchParams.set("path",e),r?.mode!=null&&i.searchParams.set("mode",String(r.mode)),r?.createOnly&&i.searchParams.set("create_only","true");const a=new FormData;a.append("file",s instanceof Blob?s:new Blob([s]));const o=await fetch(i.toString(),{method:"PUT",headers:this.apiHeaders(),body:a,signal:r?.signal});if(!o.ok)throw new v(o.status,o.statusText,await o.text().catch(()=>{}));const c=await o.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,s,r,i){const a=this.sandboxFsUrl(t,e,i);Object.entries(r).forEach(([c,u])=>a.searchParams.set(c,u));const o=await fetch(a.toString(),{method:s,headers:this.apiHeaders()});if(!o.ok)throw new v(o.status,o.statusText,await o.text().catch(()=>{}));return o.json().catch(()=>null)}async sandboxFsStat(t,e,s){const r=this.sandboxFsUrl(t,"stat",s);r.searchParams.set("path",e);const i=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new v(i.status,i.statusText,await i.text().catch(()=>{}));const a=await i.json(),o=a.data??a;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,s){await this.sandboxFsRequest(t,"mkdir","POST",{path:e},s)}async sandboxFsRemove(t,e,s){await this.sandboxFsRequest(t,"item","DELETE",{path:e},s)}async sandboxFsRemoveAll(t,e,s){await this.sandboxFsRequest(t,"all","DELETE",{path:e},s)}async sandboxFsCopy(t,e,s,r){const i={src:e,dst:s};r?.overwrite&&(i.overwrite="true");const a=await this.sandboxFsRequest(t,"copy","POST",i,r);return{bytesCopied:(a?.data??a)?.bytesCopied??0}}async sandboxFsMove(t,e,s,r){const i={src:e,dst:s};r?.overwrite&&(i.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",i,r)}sandboxFsWatch(t,e,s){const r=this.sandboxFsUrl(t,"watch",s);return r.searchParams.set("path",e),new E(i=>{const a=new AbortController;return be(r.toString(),{headers:this.apiHeaders(),signal:a.signal,openWhenHidden:!0,onopen:async o=>{if(!o.ok){const c=await o.text().catch(()=>{});i.error(new v(o.status,o.statusText,c)),a.abort()}},onmessage:o=>{o.event==="change"&&i.next(JSON.parse(o.data))},onclose:()=>i.complete(),onerror:o=>{throw i.error(o),a.abort(),o}}),()=>a.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 Xe="",In=new Set(["",".",".."]);function A(n,t){if(n===Xe){if(t?.allowRoot)return n;throw new Error("SourceSet volume path must not be empty: the volume root is not a valid target for this operation.")}if(n.startsWith("/"))throw new Error(`SourceSet volume path must be relative, with no leading slash (the root is ""): "${n}".`);if(n.endsWith("/"))throw new Error(`SourceSet volume path must not end with a slash: "${n}".`);if(n.split("/").some(e=>In.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const le=1e3,We=1e4;function Ye(n){return Math.min(Math.max(1,Math.floor(n)),le)}class Tn{endpoint;apiKey;customHeaders;constructor(t){this.endpoint=t.sourceSetEndpoint.replace(/\/+$/,""),this.apiKey=t.apiKey,this.customHeaders=t.customHeaders}headers(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async request(t,e,s,r,i){const a=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([c,u])=>a.searchParams.set(c,u));const o=await fetch(a.toString(),{method:e,headers:this.headers(),body:r,signal:i});if(!o.ok)throw new v(o.status,o.statusText,await o.text().catch(()=>{}));return o}async list(t,e){const s={path:A(t,{allowRoot:!0})};e?.page!=null&&(s.page=String(e.page)),e?.pageSize!=null&&(s.page_size=String(Ye(e.pageSize)));const i=await(await this.request("list","GET",s)).json(),a=i.data??i;return{entries:a.entries??[],paging:a.paging??i.paging??null}}async listAll(t,e){const s=Ye(e?.pageSize??le),r=e?.maxEntries??We,i=[];let a=0,o=!0,c=0;for(;;){const u=await this.list(t,{page:c,pageSize:s}),d=u.paging;if(d&&d.index!==c){a=d.total,o=!1;break}if(i.push(...u.entries),!d){o=u.entries.length<s;break}if(a=d.total,i.length>=a)break;if(i.length>=r||u.entries.length===0){o=!1;break}c+=1}return{entries:i,total:a,complete:o}}async stat(t){const s=await(await this.request("stat","GET",{path:A(t)})).json(),r=s.data??s;return{exists:r.exists??!1,isDir:r.isDir??!1,sizeBytes:r.sizeBytes??0,mtimeUnix:r.mtimeUnix??0,mode:r.mode??0,etag:r.etag}}async read(t,e){const s={path:A(t)};e?.offsetBytes!=null&&(s.offset_bytes=String(e.offsetBytes)),e?.limitBytes!=null&&(s.limit_bytes=String(e.limitBytes));const r=await this.request("file","GET",s),i=await r.blob(),a=r.headers.get("X-Total-Bytes");return{content:i,totalBytes:a!=null?Number(a):i.size,truncated:r.headers.get("X-Truncated")==="true"}}async write(t,e,s){const r={path:A(t)};s?.mode!=null&&(r.mode=String(s.mode)),s?.createOnly&&(r.create_only="true");const i=new FormData;i.append("file",e instanceof Blob?e:new Blob([e]));const o=await(await this.request("file","PUT",r,i,s?.signal)).json();return{bytesWritten:(o.data??o).bytesWritten??0}}async mkdir(t,e){await this.request("mkdir","POST",{path:A(t)},void 0,e?.signal)}async remove(t){await this.request("item","DELETE",{path:A(t)})}async removeAll(t){await this.request("all","DELETE",{path:A(t)})}async copy(t,e,s){const r=this.copyMoveQuery(t,e,s),a=await(await this.request("copy","POST",r)).json();return{bytesCopied:(a.data??a).bytesCopied??0}}async move(t,e,s){await this.request("move","POST",this.copyMoveQuery(t,e,s))}copyMoveQuery(t,e,s){const r={src:A(t),dst:A(e)};return s?.overwrite&&(r.overwrite="true"),r}}const w=[];for(let n=0;n<256;++n)w.push((n+256).toString(16).slice(1));function Cn(n,t=0){return(w[n[t+0]]+w[n[t+1]]+w[n[t+2]]+w[n[t+3]]+"-"+w[n[t+4]]+w[n[t+5]]+"-"+w[n[t+6]]+w[n[t+7]]+"-"+w[n[t+8]]+w[n[t+9]]+"-"+w[n[t+10]]+w[n[t+11]]+w[n[t+12]]+w[n[t+13]]+w[n[t+14]]+w[n[t+15]]).toLowerCase()}let de;const An=new Uint8Array(16);function On(){if(!de){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");de=crypto.getRandomValues.bind(crypto)}return de(An)}const ze={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function xn(n,t,e){n=n||{};const s=n.random??n.rng?.()??On();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Cn(s)}function Je(n,t,e){return ze.randomUUID&&!n?ze.randomUUID():xn(n)}class m{messages=null;pendingConsent=null;pendingFeedback=null;constructor({messages:t,pendingConsent:e=null,pendingFeedback:s=null}){this.messages=t,this.pendingConsent=e??null,this.pendingFeedback=s??null}pushMessage(t){const e=new Map(this.messages);return e.set(t.messageId,t),new m({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}clearPendingConsent(){return this.pendingConsent?new m({messages:this.messages,pendingConsent:null,pendingFeedback:this.pendingFeedback}):this}restorePendingConsent(t){return this.pendingConsent?this:new m({messages:this.messages,pendingConsent:t,pendingFeedback:this.pendingFeedback})}settleInFlightMessages(){if(!this.messages)return this;let t=!1;const e=new Map(this.messages);for(const[s,r]of e)r.type==="tool-call"&&!r.isComplete&&(e.set(s,{...r,isComplete:!0,isCancelled:!0}),t=!0),r.type==="thinking"&&r.isThinking&&(e.set(s,{...r,isThinking:!1}),t=!0);return t?new m({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback}):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_FEEDBACK:return this.onMessageFeedback(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.MESSAGE_CANVAS_START:return this.onCanvasStart(t);case l.MESSAGE_CANVAS_DELTA:return this.onCanvasDelta(t);case l.MESSAGE_CANVAS_COMPLETE:return this.onCanvasComplete(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}isTerminalToolCall(t){return t?.type==="tool-call"&&t.isComplete===!0}isTerminalCanvas(t){return t?.type==="canvas"&&!t.isDrawing}onMessageStart(t){const e=t.fact.messageStart.message;if(e.parentToolUseId)return this;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages);return s.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 m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageDelta(t){const e=t.fact.messageDelta.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId);if(this.isTerminalBot(s))return this;const r=s?.type==="bot"?s:void 0,i=new Map(this.messages);return i.set(e.messageId,{type:"bot",eventType:l.MESSAGE_DELTA,isTyping:!0,typingText:`${r?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??r?.traceId,raw:r?.raw??""}),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageComplete(t){const e=t.fact.messageComplete.message;if(e.parentToolUseId)return this;const s=new Map(this.messages),r=s.get(e.messageId),i=r?.type==="bot"?r:void 0,a=this.pendingFeedback?.get(e.messageId),o=a??i?.feedback;s.set(e.messageId,{type:"bot",eventType:l.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,...o?{feedback:o}:{},time:new Date,traceId:t.traceId??i?.traceId,raw:JSON.stringify(t)});let c=this.pendingFeedback;return a&&(c=new Map(this.pendingFeedback),c.delete(e.messageId)),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:c})}onMessageFeedback(t){const e=t.fact.messageFeedback,s={verdict:e.verdict,...e.text?{comment:e.text}:{}};return this.applyFeedback(e.targetMessageId,s)}applyFeedback(t,e){const s=this.messages?.get(t);if(s?.type==="bot"){const i=new Map(this.messages),a={...s,feedback:e};return i.set(t,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const r=new Map(this.pendingFeedback);return r.set(t,e),new m({messages:this.messages,pendingConsent:this.pendingConsent,pendingFeedback:r})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(e.parentToolUseId)return this;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages),r={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return s.set(e.messageId,r),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onThinkingDelta(t){const e=t.fact.messageThinkingDelta.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId);if(this.isTerminalThinking(s))return this;const r=s?.type==="thinking"?s:void 0,i=new Map(this.messages),a={type:"thinking",messageId:e.messageId,text:`${r?.text??""}${e.text}`,isThinking:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onThinkingComplete(t){const e=t.fact.messageThinkingComplete.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId),r=s?.type==="thinking"?s:void 0,i=new Map(this.messages),a={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasStart(t){const e=t.fact.messageCanvasStart.message;if(e.parentToolUseId)return this;if(this.isTerminalCanvas(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages),r={type:"canvas",messageId:e.messageId,html:"",isDrawing:!0,time:new Date,traceId:t.traceId};return s.set(e.messageId,r),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasDelta(t){const e=t.fact.messageCanvasDelta.message;if(e.parentToolUseId)return this;const s=this.messages?.get(e.messageId);if(this.isTerminalCanvas(s))return this;const r=s?.type==="canvas"?s:void 0,i=new Map(this.messages),a={type:"canvas",messageId:e.messageId,html:`${r?.html??""}${e.text}`,title:r?.title,isDrawing:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,a),new m({messages:i,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const s=e.template?.type===te.CANVAS?e.template:void 0,r=s?.canvas?.html;if(!r){if(!this.messages?.has(e.messageId))return this;const u=new Map(this.messages);return u.delete(e.messageId),new m({messages:u,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const i=this.messages?.get(e.messageId),a=i?.type==="canvas"?i:void 0,o=new Map(this.messages),c={type:"canvas",messageId:e.messageId,html:r,title:s?.title,isDrawing:!1,time:a?.time??new Date,traceId:t.traceId??a?.traceId};return o.set(e.messageId,c),new m({messages:o,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}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 r=new Map(this.messages),i={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,blobs:e.blobs,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return r.set(e.messageId,i),new m({messages:r,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageError(t){const e=Je(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new m({messages:r,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallStart(t){const e=t.fact.toolCallStart,s=new Map(this.messages),r=`${e.processId}-${e.callSeq}`;if(this.isTerminalToolCall(this.messages?.get(r)))return this;const i={type:"tool-call",eventType:l.TOOL_CALL_START,messageId:r,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 s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallComplete(t){const e=t.fact.toolCallComplete,s=new Map(this.messages),r=`${e.processId}-${e.callSeq}`,i=s.get(r);if(i?.type==="tool-call"){const a={...i,eventType:l.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??i.traceId};s.set(r,a)}else{const a={type:"tool-call",eventType:l.TOOL_CALL_COMPLETE,messageId:r,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,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,time:new Date,traceId:t.traceId};s.set(r,a)}return new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new m({messages:this.messages,pendingConsent:e,pendingFeedback:this.pendingFeedback})}onSubagentStart(t){const e=t.fact.subagentStart,s=new Map(this.messages),r=`subagent:${e.parentToolUseId}:start`,i={type:"subagent",messageId:r,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return s.delete(r),s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onSubagentComplete(t){const e=t.fact.subagentComplete,s=new Map(this.messages),r=`subagent:${e.parentToolUseId}:complete`,i={type:"subagent",messageId:r,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return s.delete(r),s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}}const kn=new Set(["TaskCreate","TaskUpdate"]);function Qe(n){return n.toolsetName===""&&kn.has(n.toolName)}function Ze(n){return typeof n=="object"&&n!==null?n:void 0}function k(n){return typeof n=="string"?n:void 0}function et(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},i=s.sidecar??{};if(s.toolName==="TaskCreate"){const a=Ze(i.task),o=k(a?.id);if(!o)continue;e.has(o)||t.push(o),e.set(o,{id:o,subject:k(r.subject)||k(a?.subject)||"",activeForm:k(r.activeForm),description:k(r.description),status:e.get(o)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const a=Ze(i.statusChange),o=k(r.taskId)||k(i.taskId),c=k(a?.to)||k(r.status);if(!o||!c)continue;const u=e.get(o);u&&e.set(o,{...u,status:c})}}return t.map(s=>e.get(s))}function tt(n){return n.toolsetName===""&&n.toolName==="Agent"}function nt(n){return!!n}function st(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function rt(n){const t=[],e=new Map,s=new Map,r=i=>(e.has(i)||(t.push(i),e.set(i,{status:"running"}),s.set(i,new Map)),e.get(i));for(const i of n)switch(i.kind){case"agentStart":{const a=r(i.toolUseId);i.description&&!a.description&&(a.description=i.description);break}case"subagentStart":{const a=r(i.parentToolUseId);a.agentId=i.agentId??a.agentId,a.subagentType=i.subagentType??a.subagentType,a.description=i.description??a.description,st(a);break}case"toolStart":{st(r(i.parentToolUseId)),s.get(i.parentToolUseId).set(i.toolUseId,{toolsetName:i.toolsetName,toolName:i.toolName,parameter:i.parameter??{},reason:i.reason,status:"running"});break}case"toolComplete":{const a=s.get(i.parentToolUseId)?.get(i.toolUseId);a&&(a.status=i.isError?"error":"completed");break}case"subagentComplete":{const a=r(i.parentToolUseId);a.status=i.status,a.summary=i.summary;break}}return t.map(i=>({parentToolUseId:i,...e.get(i),tools:Array.from(s.get(i).values())}))}function _n(n){return typeof n=="string"?n:void 0}function it(n){const t=[];for(const e of n){if(e.type==="tool-call"&&tt(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:_n(e.parameter.description)});continue}if(e.type==="tool-call"&&nt(e.parentToolUseId)){const s=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:s,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:s,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 at(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Qe(e));return et(t)}function ot(n){return rt(it(Array.from(n.messages?.values()??[])))}function ct(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.id===r.id&&e.status===r.status&&e.subject===r.subject&&e.activeForm===r.activeForm&&e.description===r.description})}function Pn(n,t){return n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.toolName===r.toolName&&e.toolsetName===r.toolsetName&&e.status===r.status&&e.reason===r.reason})}function ut(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.parentToolUseId===r.parentToolUseId&&e.status===r.status&&e.subagentType===r.subagentType&&e.description===r.description&&e.summary===r.summary&&Pn(e.tools,r.tools)})}function lt(n){const t=new x([]),e=new x([]),s=new U;return s.add(n.pipe(ee(at),N(ct)).subscribe(t)),s.add(n.pipe(ee(ot),N(ut)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function he(n){const t=new Map;for(const e of n)t.set(e.sandboxName,e);return[...t.values()].sort((e,s)=>(e.sandboxBlueprintName||e.sandboxName).localeCompare(s.sandboxBlueprintName||s.sandboxName))}const fe={kind:null,stopPhase:"idle"},Mn=1e4;function Un(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class ${client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;promptSuggestion$;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 x(!1),this.runStatusSubject=new x(fe),this.conversation$=new x(t.conversation),this.channelTitleSubject=new x(t.channelTitle??null),this.promptSuggestionSubject=new x(null),this.sandboxPhaseSubject=new x("idle"),this.launchedSandboxesSubject=new x(he(t.launchedSandboxes??[])),this.derivedStores=lt(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(N()),this.promptSuggestion$=this.promptSuggestionSubject.pipe(N()),this.sandboxPhase$=this.sandboxPhaseSubject.pipe(N()),this.launchedSandboxes$=this.launchedSandboxesSubject.pipe(N()),this.runStatus$=this.runStatusSubject.pipe(N(Un)),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}getPromptSuggestion(){return this.promptSuggestionSubject.value}clearPromptSuggestion(){this.promptSuggestionSubject.next(null)}getSandboxPhase(){return this.sandboxPhaseSubject.value}getLaunchedSandboxes(){return this.launchedSandboxesSubject.value}getRunStatus(){return this.runStatusSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=he(t);this.pendingLaunches=this.pendingLaunches.filter(s=>!e.some(r=>r.sandboxName===s)),this.launchedSandboxesSubject.next(e)}dropSandbox(t){const e=this.launchedSandboxesSubject.value,s=e.filter(r=>r.sandboxName!==t);s.length!==e.length&&this.launchedSandboxesSubject.next(s)}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 $(t);return e.subscribe(),e}static async open(t,e,s,r){const i=new $(t);try{return i.subscribe(),r?.(i),await i.openChannel(e,s),i}catch(a){throw i.close(),a}}static async reset(t,e,s,r){if(!t.client.deleteChannel)throw new Error("This client cannot reset a channel: IAsgardServiceClient.deleteChannel is not implemented. Implement it (DELETE {base}/channel?custom_channel_id=…) or use AsgardServiceClient.");return await t.client.deleteChannel(t.customChannelId),$.open(t,e,s,r)}static async restore(t,e,s){const r=new $(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(i){throw r.close(),i}}subscribe(){this.statesSubscription=fn([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.promptSuggestion$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe(ee(([t,e,s,r,i,a,o,c,u])=>({isConnecting:t,conversation:e,tasks:s,subagents:r,channelTitle:i,promptSuggestion:a,sandboxPhase:o,launchedSandboxes:c,runStatus:u}))).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,s){return{onSseStart:t?.onSseStart,onSseMessage:r=>{if(t?.onSseMessage?.(r),this.captureRequestId(r.requestId),r.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(r.fact.channelTitleUpdate.title),r.eventType===l.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(r.fact.promptSuggestion.suggestion):r.eventType===l.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(r.eventType),r.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(r.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&r.traceId){const i=new Map(this.conversation$.value.messages),a=i.get(this.currentUserMessageId);a&&a.type==="user"&&(i.set(this.currentUserMessageId,{...a,traceId:r.traceId}),this.conversation$.next(new m({messages:i,pendingConsent:this.conversation$.value.pendingConsent,pendingFeedback:this.conversation$.value.pendingFeedback}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(r))},onSseError:r=>{t?.onSseError?.(r),this.settleRun(),s(r)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.settleRun(),e()}}}settleRun(){const t=this.runStatusSubject.value.stopPhase!=="idle";this.clearForceStopTimer(),this.isConnecting$.next(!1),this.runStatusSubject.next(fe),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,s){return new Promise((r,i)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(s,r,i))})}rejoinChannel(t){return new Promise((e,s)=>{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,s))})}openChannel(t,e){return this.fetchSse("reset",{action:F.NONE,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new W(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new Y(r.processId));this.clearPromptSuggestion();const i=t.text.trim(),a=t.customMessageId??Je();return this.currentUserMessageId=a,this.lastSentMessageId=a,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:a,text:i,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:F.NONE,customChannelId:this.customChannelId,customMessageId:a,payload:this.resolvePayload(t?.payload),text:i,blobIds:t?.blobIds},e)}async sendMessageFeedback(t,e){if(!this.client.sendMessageFeedback)throw new Error("This client cannot rate a reply: IAsgardServiceClient.sendMessageFeedback is not implemented. Implement it (POST {base}/message/feedback) or use AsgardServiceClient.");const s=await this.client.sendMessageFeedback({customChannelId:this.customChannelId,messageId:t,verdict:e.verdict,comment:e.comment}),r=e.comment?.trim();return this.conversation$.next(this.conversation$.value.applyFeedback(t,{verdict:e.verdict,...r?{comment:r}:{}})),s}replyToolCallConsents(t,e,s){const r=this.conversation$.value.pendingConsent;return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse("user",{action:F.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(s),text:"",toolCallConsents:t},e).catch(i=>{throw r&&this.conversation$.next(this.conversation$.value.restorePendingConsent(r)),i})}nudge(t,e){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new W(s));const r=this.conversation$.value.pendingConsent;return r?Promise.reject(new Y(r.processId)):this.fetchSse("nudge",{action:F.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(s){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),s}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"})},Mn)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(fe),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()}}const dt={GOOD:"[Response Feedback: Good]",BAD:"[Response Feedback: Bad]"},Ln=8*1024;function Nn(n){return new TextEncoder().encode(n).length}function Rn(n,t){const e=dt[n],s=t?.trim()??"";return s?`${e}
5
5
 
6
- ${s}`:e}function Nn(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),s=t[2],r=new URLSearchParams(t[3]??"");if(s==="open-browser")return{kind:"open-browser",sandboxName:e};if(s==="open-file"){const i=r.get("absolute_path");return i?{kind:"open-file",sandboxName:e,absolutePath:i}:null}return null}p.AsgardServiceClient=En,p.AsgardSourceSetClient=In,p.Channel=$,p.ChannelAwaitingConsentError=Y,p.ChannelBusyError=W,p.Conversation=m,p.EventType=l,p.FEEDBACK_COMMENT_MAX_BYTES=Un,p.FetchSseAction=F,p.HttpError=v,p.MessageTemplateType=te,p.RESPONSE_FEEDBACK_PREFIX=lt,p.SOURCE_SET_DEFAULT_MAX_ENTRIES=Xe,p.SOURCE_SET_MAX_PAGE_SIZE=le,p.SOURCE_SET_VOLUME_ROOT=Ve,p.ToolCallConsentResult=pe,p.assertVolumePath=A,p.composeFeedbackMessage=Rn,p.conversationToSubagentEvents=rt,p.createDerivedStores=ut,p.deriveSubagents=at,p.deriveTasks=it,p.feedbackCommentByteLength=Ln,p.isAgentTool=et,p.isChannelAwaitingConsentError=ft,p.isChannelBusyError=ht,p.isHttpError=dt,p.isSubagentChildTool=tt,p.isTaskTool=Je,p.reconcileLaunched=he,p.reduceSubagents=st,p.reduceTaskEvents=Ze,p.resolveSandboxUri=Nn,p.subagentsEqual=ct,p.tasksEqual=ot,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
6
+ ${s}`:e}function Fn(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),s=t[2],r=new URLSearchParams(t[3]??"");if(s==="open-browser")return{kind:"open-browser",sandboxName:e};if(s==="open-file"){const i=r.get("absolute_path");return i?{kind:"open-file",sandboxName:e,absolutePath:i}:null}return null}p.AsgardServiceClient=En,p.AsgardSourceSetClient=Tn,p.Channel=$,p.ChannelAwaitingConsentError=Y,p.ChannelBusyError=W,p.Conversation=m,p.EventType=l,p.FEEDBACK_COMMENT_MAX_BYTES=Ln,p.FetchSseAction=F,p.HttpError=v,p.MessageTemplateType=te,p.RESPONSE_FEEDBACK_PREFIX=dt,p.SOURCE_SET_DEFAULT_MAX_ENTRIES=We,p.SOURCE_SET_MAX_PAGE_SIZE=le,p.SOURCE_SET_VOLUME_ROOT=Xe,p.ToolCallConsentResult=pe,p.assertVolumePath=A,p.composeFeedbackMessage=Rn,p.conversationToSubagentEvents=it,p.createDerivedStores=lt,p.deriveSubagents=ot,p.deriveTasks=at,p.feedbackCommentByteLength=Nn,p.isAgentTool=tt,p.isChannelAwaitingConsentError=pt,p.isChannelBusyError=ft,p.isHttpError=ht,p.isSubagentChildTool=nt,p.isTaskTool=Qe,p.reconcileLaunched=he,p.reduceSubagents=rt,p.reduceTaskEvents=et,p.resolveSandboxUri=Fn,p.subagentsEqual=ut,p.tasksEqual=ct,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
7
7
  //# sourceMappingURL=index.js.map