@asgard-js/core 0.3.94 → 0.3.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -146,6 +146,7 @@ The main client class for interacting with the Asgard AI platform.
146
146
  - **downloadChannelHomeFile(relativePath, customChannelId)**: `Promise<ChannelHomeDownloadResult>` - Download a file from the channel's Channel Home file-exchange plane (backs `channel-home://` URI actions); resolves to `{ blob, filename }`
147
147
  - **rejoinSse(customChannelId, options?)**: Cold-start transcript rejoin — a `GET /message/sse` with an empty `Last-Event-ID` that replays the channel's collapsed history through the same reducer, so a returning user sees their prior conversation without re-POSTing. Optional on `IAsgardServiceClient` for backward compatibility
148
148
  - **deleteChannel(customChannelId)**: `Promise<void>` - End the conversation and release everything the channel holds — the in-flight run, transcript, uploaded blobs, tool-call allow-list, Sandbox and Channel Home — via `DELETE /channel`. Resolves once the teardown is **done** (up to about a minute when a live Sandbox has to terminate first, so do not impose a shorter timeout), after which the same `customChannelId` is a blank slate. Deleting a channel that does not exist is a success. Optional on `IAsgardServiceClient` for backward compatibility
149
+ - **clearChannel(customChannelId)**: `Promise<void>` - Clear the conversation but **keep the channel's files** via `POST /channel/clear`: the in-flight run, transcript, agent session, title and pending tool consent go; the Channel Home files, uploaded blobs, tool-call allow-list and the channel itself stay, and the Sandbox restarts onto the same files. Resolves on any 2xx once the clear is **done** (up to about 45 seconds while a live Sandbox stops — do not impose a shorter timeout); clearing a channel that does not exist is a success. Everything else, `404` included (it means the relay route is missing), rejects with `HttpError`. Optional on `IAsgardServiceClient` for backward compatibility
149
150
  - **channelMetadata(customChannelId)**: `Promise<ChannelMetadata | null>` - Join-init existence + restore gate — `GET /channel/metadata`; resolves to the metadata on `200`, `null` on `404` (channel does not exist), and rejects on any other error. `ChannelMetadata` is `{ title: string | null; runState: 'RUNNING' | 'IDLE'; lastActivityAt?: string }`. Optional on `IAsgardServiceClient` for backward compatibility
150
151
  - **sendMessageFeedback(request)**: `Promise<MessageFeedbackReply>` - Rate one assistant reply Good or Bad (F-033) — `POST /message/feedback` with `{ customChannelId, messageId, verdict: 'GOOD' | 'BAD', comment? }`; resolves to `{ messageId, seq }` (the persisted entry's own id and transcript cursor). Rejects with `HttpError` on `404` (not a ratable reply: a thinking block, the user's own message, an unknown id), `400` (bad verdict / comment over 8 KiB of UTF-8) or any other failure. See [Message feedback](#message-feedback). Optional on `IAsgardServiceClient` for backward compatibility
151
152
  - **suspendChannel(customChannelId, options?)**: `Promise<void>` - Ask the backend to stop the channel's background run — `POST /message/suspend?custom_channel_id=…`, with optional `requestId` (stop only that run) and `force` (abandon it rather than let it wind down). Resolves on any 2xx **and** on `404` (channel never created = nothing to stop); rejects with `HttpError` otherwise. Resolving means _accepted_, not _stopped_ — see [Stopping generation](#stopping-generation). Optional on `IAsgardServiceClient` for backward compatibility
@@ -174,7 +175,7 @@ Higher-level abstraction for managing a conversation channel with reactive state
174
175
 
175
176
  #### Static Methods
176
177
 
177
- - **Channel.reset(config, payload?, options?)**: `Promise<Channel>` - Clear an **existing** conversation and start over on the same id: `client.deleteChannel()` first, and only once that resolves, a fresh channel opened with an `action=NONE` turn (the server replies with a welcome message). Nothing local is built until the delete succeeds, so a failed teardown leaves your current channel and conversation untouched. Rejects if the client cannot delete
178
+ - **Channel.reset(config, payload?, options?, onChannelCreated?, mode?)**: `Promise<Channel>` - Clear an **existing** conversation and start over on the same id: release it first — `client.deleteChannel()` for `mode: 'delete'` (the default), `client.clearChannel()` for `mode: 'clear'`, which keeps the Channel Home files — and only once that resolves, a fresh channel opened with an `action=NONE` turn (the server replies with a welcome message). Nothing local is built until that first step succeeds, so a failed delete / clear leaves your current channel and conversation untouched. Rejects if the client lacks the method for the chosen mode (it never falls back to the other one)
178
179
  - **Channel.open(config, payload?, options?)**: `Promise<Channel>` - Open a channel that does not exist yet with the same `action=NONE` turn, **without** deleting anything — the mount-time path for a `404` from `channelMetadata`
179
180
  - **Channel.restore(config, options?)**: `Promise<Channel>` - Join an **existing** channel without resetting it — seeds the title from `config.channelTitle` and replays the server transcript via `rejoinSse`, preserving history / session / title. This is the join-without-wiping path behind the metadata-gated mount (F-015)
180
181
  - **Channel.create(config)**: `Channel` - Create a channel and subscribe to its state without any SSE request (no reset, no rejoin); the first connection happens when you call `sendMessage`
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class C 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 bt(n){return n instanceof C}class z 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 St(n){return n instanceof z}class J 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 vt(n){return n instanceof J}var B=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(B||{}),h=(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))(h||{}),Pe=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(Pe||{}),he=(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))(he||{});async function yt(n,t){const e=n.getReader();let s;for(;!(s=await e.read()).done;)t(s.value)}function wt(n){let t,e,s,r=!1;return function(i){t===void 0?(t=i,e=0,s=-1):t=It(t,i);const a=t.length;let c=0;for(;e<a;){r&&(t[e]===10&&(c=++e),r=!1);let u=-1;for(;e<a&&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===a?t=void 0:c!==0&&(t=t.subarray(c),e-=c)}}function Et(n,t,e){let s=Se();const r=new TextDecoder;return function(i,a){if(i.length===0)e?.(s),s=Se();else if(a>0){const c=r.decode(i.subarray(0,a)),u=a+(i[a+1]===32?2:1),l=r.decode(i.subarray(u));switch(c){case"data":s.data=s.data?s.data+`
2
2
  `+l:l;break;case"event":s.event=l;break;case"id":n(s.id=l);break;case"retry":const v=parseInt(l,10);isNaN(v)||t(s.retry=v);break}}}}function It(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function Se(){return{data:"",event:"",id:"",retry:void 0}}var Tt=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 oe="text/event-stream",Ct=1e3,ve="last-event-id";function Me(n,t){var{signal:e,headers:s,onopen:r,onmessage:o,onclose:i,onerror:a,openWhenHidden:c,fetch:u}=t,l=Tt(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((v,w)=>{const p=Object.assign({},s);p.accept||(p.accept=oe);let g;function d(){g.abort(),document.hidden||b()}c||document.addEventListener("visibilitychange",d);let x=Ct,k=0;function f(){document.removeEventListener("visibilitychange",d),window.clearTimeout(k),g.abort()}e?.addEventListener("abort",()=>{f(),v()});const m=u??window.fetch,S=r??xt;async function b(){var I;g=new AbortController;try{const U=await m(n,Object.assign(Object.assign({},l),{headers:p,signal:g.signal}));await S(U),await yt(U.body,wt(Et(_=>{_?p[ve]=_:delete p[ve]},_=>{x=_},o))),i?.(),f(),v()}catch(U){if(!g.signal.aborted)try{const _=(I=a?.(U))!==null&&I!==void 0?I:x;window.clearTimeout(k),k=window.setTimeout(b,_)}catch(_){f(),w(_)}}}b()})}function xt(n){const t=n.headers.get("content-type");if(!t?.startsWith(oe))throw new Error(`Expected content-type to be ${oe}, Actual: ${t}`)}var ie=function(n,t){return ie=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])},ie(n,t)};function F(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");ie(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function kt(n,t,e,s){function r(o){return o instanceof e?o:new e(function(i){i(o)})}return new(e||(e=Promise))(function(o,i){function a(l){try{u(s.next(l))}catch(v){i(v)}}function c(l){try{u(s.throw(l))}catch(v){i(v)}}function u(l){l.done?o(l.value):r(l.value).then(a,c)}u((s=s.apply(n,t||[])).next())})}function Le(n,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},s,r,o,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(l){return c([u,l])}}function c(u){if(s)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(e=0)),e;)try{if(s=1,r&&(o=u[0]&2?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=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(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){e.label=u[1];break}if(u[0]===6&&e.label<o[1]){e.label=o[1],o=u;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(u);break}o[2]&&e.ops.pop(),e.trys.pop();continue}u=t.call(n,e)}catch(l){u=[6,l],r=0}finally{s=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function $(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,o=[],i;try{for(;(t===void 0||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(e=s.return)&&e.call(s)}finally{if(i)throw i.error}}return o}function W(n,t,e){if(e||arguments.length===2)for(var s=0,r=t.length,o;s<r;s++)(o||!(s in t))&&(o||(o=Array.prototype.slice.call(t,0,s)),o[s]=t[s]);return n.concat(o||Array.prototype.slice.call(t))}function K(n){return this instanceof K?(this.v=n,this):new K(n)}function At(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=e.apply(n,t||[]),r,o=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),r[Symbol.asyncIterator]=function(){return this},r;function i(p){return function(g){return Promise.resolve(g).then(p,v)}}function a(p,g){s[p]&&(r[p]=function(d){return new Promise(function(x,k){o.push([p,d,x,k])>1||c(p,d)})},g&&(r[p]=g(r[p])))}function c(p,g){try{u(s[p](g))}catch(d){w(o[0][3],d)}}function u(p){p.value instanceof K?Promise.resolve(p.value.v).then(l,v):w(o[0][2],p)}function l(p){c("next",p)}function v(p){c("throw",p)}function w(p,g){p(g),o.shift(),o.length&&c(o[0][0],o[0][1])}}function Ot(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 $=="function"?$(n):n[Symbol.iterator](),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(o){e[o]=n[o]&&function(i){return new Promise(function(a,c){i=n[o](i),r(a,c,i.done,i.value)})}}function r(o,i,a,c){Promise.resolve(c).then(function(u){o({value:u,done:a})},i)}}function E(n){return typeof n=="function"}function Ue(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 te=Ue(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 X(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var D=(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,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=$(i),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(d){t={error:d}}finally{try{c&&!c.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else i.remove(this);var l=this.initialTeardown;if(E(l))try{l()}catch(d){o=d instanceof te?d.errors:[d]}var v=this._finalizers;if(v){this._finalizers=null;try{for(var w=$(v),p=w.next();!p.done;p=w.next()){var g=p.value;try{ye(g)}catch(d){o=o??[],d instanceof te?o=W(W([],q(o)),q(d.errors)):o.push(d)}}}catch(d){s={error:d}}finally{try{p&&!p.done&&(r=w.return)&&r.call(w)}finally{if(s)throw s.error}}}if(o)throw new te(o)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)ye(t);else{if(t instanceof n){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(t)}},n.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},n.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},n.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&X(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&X(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),Re=D.EMPTY;function Fe(n){return n instanceof D||n&&"closed"in n&&E(n.remove)&&E(n.add)&&E(n.unsubscribe)}function ye(n){E(n)?n():n.unsubscribe()}var _t={Promise:void 0},Pt={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,W([n,t],q(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Ne(n){Pt.setTimeout(function(){throw n})}function ae(){}function Y(n){n()}var fe=(function(n){F(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,Fe(e)&&e.add(s)):s.destination=Ut,s}return t.create=function(e,s,r){return new ce(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})(D),Mt=(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){V(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){V(s)}else V(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){V(e)}},n})(),ce=(function(n){F(t,n);function t(e,s,r){var o=n.call(this)||this,i;return E(e)||!e?i={next:e??void 0,error:s??void 0,complete:r??void 0}:i=e,o.destination=new Mt(i),o}return t})(fe);function V(n){Ne(n)}function Lt(n){throw n}var Ut={closed:!0,next:ae,error:Lt,complete:ae},pe=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Z(n){return n}function Rt(n){return n.length===0?Z:n.length===1?n[0]:function(e){return n.reduce(function(s,r){return r(s)},e)}}var A=(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,o=Nt(t)?t:new ce(t,e,s);return Y(function(){var i=r,a=i.operator,c=i.source;o.add(a?a.call(o,c):c?r._subscribe(o):r._trySubscribe(o))}),o},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=we(e),new e(function(r,o){var i=new ce({next:function(a){try{t(a)}catch(c){o(c),i.unsubscribe()}},error:o,complete:r});s.subscribe(i)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[pe]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Rt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=we(t),new t(function(s,r){var o;e.subscribe(function(i){return o=i},function(i){return r(i)},function(){return s(o)})})},n.create=function(t){return new n(t)},n})();function we(n){var t;return(t=n??_t.Promise)!==null&&t!==void 0?t:Promise}function Ft(n){return n&&E(n.next)&&E(n.error)&&E(n.complete)}function Nt(n){return n&&n instanceof fe||Ft(n)&&Fe(n)}function jt(n){return E(n?.lift)}function j(n){return function(t){if(jt(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 H(n,t,e,s,r){return new $t(n,t,e,s,r)}var $t=(function(n){F(t,n);function t(e,s,r,o,i,a){var c=n.call(this,e)||this;return c.onFinalize=i,c.shouldUnsubscribe=a,c._next=s?function(u){try{s(u)}catch(l){e.error(l)}}:n.prototype._next,c._error=o?function(u){try{o(u)}catch(l){e.error(l)}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})(fe),Dt=Ue(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ge=(function(n){F(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 Ee(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Dt},t.prototype.next=function(e){var s=this;Y(function(){var r,o;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var i=$(s.currentObservers),a=i.next();!a.done;a=i.next()){var c=a.value;c.next(e)}}catch(u){r={error:u}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var s=this;Y(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;Y(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,o=r.hasError,i=r.isStopped,a=r.observers;return o||i?Re:(this.currentObservers=null,a.push(e),new D(function(){s.currentObservers=null,X(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var s=this,r=s.hasError,o=s.thrownError,i=s.isStopped;r?e.error(o):i&&e.complete()},t.prototype.asObservable=function(){var e=new A;return e.source=this,e},t.create=function(e,s){return new Ee(e,s)},t})(A),Ee=(function(n){F(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:Re},t})(ge),M=(function(n){F(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,o=e._value;if(s)throw r;return this._throwIfClosed(),o},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(ge),Ht={now:function(){return Date.now()}},Bt=(function(n){F(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(D),Ie={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,W([n,t],q(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Gt=(function(n){F(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 o=this.id,i=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(i,o,s)),this.pending=!0,this.delay=s,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(i,this.id,s),this},t.prototype.requestAsyncId=function(e,s,r){return r===void 0&&(r=0),Ie.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&&Ie.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,o;try{this.work(e)}catch(i){r=!0,o=i||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),o},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,s=e.id,r=e.scheduler,o=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,X(o,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Bt),Te=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,s){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(s,e)},n.now=Ht.now,n})(),Kt=(function(n){F(t,n);function t(e,s){s===void 0&&(s=Te.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})(Te),qt=new Kt(Gt);function Wt(n){return n&&E(n.schedule)}function je(n){return n[n.length-1]}function Xt(n){return E(je(n))?n.pop():void 0}function $e(n){return Wt(je(n))?n.pop():void 0}var De=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function He(n){return E(n?.then)}function Be(n){return E(n[pe])}function Ge(n){return Symbol.asyncIterator&&E(n?.[Symbol.asyncIterator])}function Ke(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 Vt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var qe=Vt();function We(n){return E(n?.[qe])}function Xe(n){return At(this,arguments,function(){var e,s,r,o;return Le(this,function(i){switch(i.label){case 0:e=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,K(e.read())];case 3:return s=i.sent(),r=s.value,o=s.done,o?[4,K(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,K(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function Ve(n){return E(n?.getReader)}function ee(n){if(n instanceof A)return n;if(n!=null){if(Be(n))return Yt(n);if(De(n))return zt(n);if(He(n))return Jt(n);if(Ge(n))return Ye(n);if(We(n))return Qt(n);if(Ve(n))return Zt(n)}throw Ke(n)}function Yt(n){return new A(function(t){var e=n[pe]();if(E(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function zt(n){return new A(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Jt(n){return new A(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Ne)})}function Qt(n){return new A(function(t){var e,s;try{for(var r=$(n),o=r.next();!o.done;o=r.next()){var i=o.value;if(t.next(i),t.closed)return}}catch(a){e={error:a}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(e)throw e.error}}t.complete()})}function Ye(n){return new A(function(t){en(n,t).catch(function(e){return t.error(e)})})}function Zt(n){return Ye(Xe(n))}function en(n,t){var e,s,r,o;return kt(this,void 0,void 0,function(){var i,a;return Le(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=Ot(n),c.label=1;case 1:return[4,e.next()];case 2:if(s=c.sent(),!!s.done)return[3,4];if(i=s.value,t.next(i),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),s&&!s.done&&(o=e.return)?[4,o.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 L(n,t,e,s,r){s===void 0&&(s=0),r===void 0&&(r=!1);var o=t.schedule(function(){e(),r?n.add(this.schedule(null,s)):this.unsubscribe()},s);if(n.add(o),!r)return o}function ze(n,t){return t===void 0&&(t=0),j(function(e,s){e.subscribe(H(s,function(r){return L(s,n,function(){return s.next(r)},t)},function(){return L(s,n,function(){return s.complete()},t)},function(r){return L(s,n,function(){return s.error(r)},t)}))})}function Je(n,t){return t===void 0&&(t=0),j(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function tn(n,t){return ee(n).pipe(Je(t),ze(t))}function nn(n,t){return ee(n).pipe(Je(t),ze(t))}function sn(n,t){return new A(function(e){var s=0;return t.schedule(function(){s===n.length?e.complete():(e.next(n[s++]),e.closed||this.schedule())})})}function rn(n,t){return new A(function(e){var s;return L(e,t,function(){s=n[qe](),L(e,t,function(){var r,o,i;try{r=s.next(),o=r.value,i=r.done}catch(a){e.error(a);return}i?e.complete():e.next(o)},0,!0)}),function(){return E(s?.return)&&s.return()}})}function Qe(n,t){if(!n)throw new Error("Iterable cannot be null");return new A(function(e){L(e,t,function(){var s=n[Symbol.asyncIterator]();L(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function on(n,t){return Qe(Xe(n),t)}function an(n,t){if(n!=null){if(Be(n))return tn(n,t);if(De(n))return sn(n,t);if(He(n))return nn(n,t);if(Ge(n))return Qe(n,t);if(We(n))return rn(n,t);if(Ve(n))return on(n,t)}throw Ke(n)}function Ze(n,t){return t?an(n,t):ee(n)}function Q(n,t){return j(function(e,s){var r=0;e.subscribe(H(s,function(o){s.next(n.call(t,o,r++))}))})}var cn=Array.isArray;function un(n,t){return cn(t)?n.apply(void 0,W([],q(t))):n(t)}function ln(n){return Q(function(t){return un(n,t)})}var dn=Array.isArray,hn=Object.getPrototypeOf,fn=Object.prototype,pn=Object.keys;function gn(n){if(n.length===1){var t=n[0];if(dn(t))return{args:t,keys:null};if(mn(t)){var e=pn(t);return{args:e.map(function(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function mn(n){return n&&typeof n=="object"&&hn(n)===fn}function bn(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function Sn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=$e(n),s=Xt(n),r=gn(n),o=r.args,i=r.keys;if(o.length===0)return Ze([],e);var a=new A(vn(o,e,i?function(c){return bn(i,c)}:Z));return s?a.pipe(ln(s)):a}function vn(n,t,e){return e===void 0&&(e=Z),function(s){Ce(t,function(){for(var r=n.length,o=new Array(r),i=r,a=r,c=function(l){Ce(t,function(){var v=Ze(n[l],t),w=!1;v.subscribe(H(s,function(p){o[l]=p,w||(w=!0,a--),a||s.next(e(o.slice()))},function(){--i||s.complete()}))},s)},u=0;u<r;u++)c(u)},s)}}function Ce(n,t,e){n?L(e,n,t):t()}function yn(n,t){return j(function(e,s){var r=0;e.subscribe(H(s,function(o){return n.call(t,o,r++)&&s.next(o)}))})}function wn(n){for(var t,e,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var o=(t=$e(s))!==null&&t!==void 0?t:qt,i=(e=s[0])!==null&&e!==void 0?e:null,a=s[1]||1/0;return j(function(c,u){var l=[],v=!1,w=function(d){var x=d.buffer,k=d.subs;k.unsubscribe(),X(l,d),u.next(x),v&&p()},p=function(){if(l){var d=new D;u.add(d);var x=[],k={buffer:x,subs:d};l.push(k),L(d,o,function(){return w(k)},n)}};i!==null&&i>=0?L(u,o,p,i,!0):v=!0,p();var g=H(u,function(d){var x,k,f=l.slice();try{for(var m=$(f),S=m.next();!S.done;S=m.next()){var b=S.value,I=b.buffer;I.push(d),a<=I.length&&w(b)}}catch(U){x={error:U}}finally{try{S&&!S.done&&(k=m.return)&&k.call(m)}finally{if(x)throw x.error}}},function(){for(;l?.length;)u.next(l.shift().buffer);g?.unsubscribe(),u.complete(),u.unsubscribe()},void 0,function(){return l=null});c.subscribe(g)})}function N(n,t){return t===void 0&&(t=Z),n=n??En,j(function(e,s){var r,o=!0;e.subscribe(H(s,function(i){var a=t(i);(o||!n(r,a))&&(o=!1,r=a,s.next(i))}))})}function En(n,t){return n===t}function In(n){return j(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function Tn(n){return j(function(t,e){ee(n).subscribe(H(e,function(){return e.complete()},ae)),!e.closed&&t.subscribe(e)})}function xe(n){const{endpoint:t,apiKey:e,payload:s,debugMode:r,customHeaders:o}=n,i=n.method??"POST";return new A(a=>{const c=new AbortController;let u,l=!1,v=!1;const w={"Content-Type":"application/json",...o};e&&(w["X-API-KEY"]=e);const p=new URL(t);return r&&p.searchParams.set("is_debug","true"),Me(p.toString(),{method:i,headers:w,body:i==="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 d;try{d=await g.json()}catch{try{d=await g.text()}catch{d=null}}a.error(new C(g.status,g.statusText,d)),c.abort()}},onmessage:g=>{g.id&&(l=!0);const d=JSON.parse(g.data);u?d.traceId=u:d.requestId&&(d.traceId=d.requestId,u||(u=d.requestId)),a.next(d)},onclose:()=>{a.complete()},onerror:g=>{if(v)throw g;if(!l)throw a.error(g),c.abort(),g}}),()=>{v=!0,c.abort()}})}class Cn{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 xn=50;function ne(n,t){return t?.customChannelId&&n.searchParams.set("custom_channel_id",t.customChannelId),n}async function kn(n,t,e){if(!n.body)return n.blob();const s=n.body.getReader(),r=[];let o=0;for(e(0,t);;){const{done:i,value:a}=await s.read();if(i)break;r.push(a.slice()),o+=a.byteLength,e(o,t)}return new Blob(r,{type:n.headers.get("Content-Type")??""})}class An{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new ge;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new Cn;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 h.INIT:this.sseEmitter.emit(h.INIT,t);break;case h.PROCESS_START:case h.PROCESS_COMPLETE:this.sseEmitter.emit(h.PROCESS,t);break;case h.MESSAGE_START:case h.MESSAGE_DELTA:case h.MESSAGE_COMPLETE:this.sseEmitter.emit(h.MESSAGE,t);break;case h.TOOL_CALL_START:case h.TOOL_CALL_COMPLETE:this.sseEmitter.emit(h.TOOL_CALL,t);break;case h.TOOL_CALL_CONSENT:this.sseEmitter.emit(h.TOOL_CALL_CONSENT,t);break;case h.DONE:this.sseEmitter.emit(h.DONE,t);break;case h.ERROR:this.sseEmitter.emit(h.ERROR,t);break}}fetchSse(t,e){return e?.onSseStart?.(),this.inFlight+=1,this.runSse(xe({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(xe({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 o=await fetch(s.toString(),{method:"GET",headers:r});if(o.status===404)return null;if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data??i;return{title:a.title??null,runState:a.runState??"IDLE",lastActivityAt:a.lastActivityAt,launchedSandboxes:(a.launchedSandboxes??[]).map(c=>({sandboxName:c.sandboxName,sandboxBlueprintName:c.sandboxBlueprintName,workingDirectory:c.workingDirectory,editorServerEnabled:c.editorServerEnabled,browserEnabled:c.browserEnabled}))}}deriveSuspendEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/suspend`:null}async suspendChannel(t,e){const 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 o=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!(o.ok||o.status===404))throw new C(o.status,o.statusText,await o.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 C(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}:{}},o=await fetch(e,{method:"POST",headers:{...this.apiHeaders(),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data??i;return{messageId:a.messageId,seq:a.seq}}runSse(t,e){return t.pipe(wn(e?.delayTime??xn),yn(s=>s.length>0),Tn(this.destroy$),In(()=>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 o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const i=await fetch(s,{method:"POST",headers:o,body:r});if(!i.ok)throw new Error(`Upload failed: ${i.status} ${i.statusText}`);const a=await i.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(i){throw console.error("[AsgardServiceClient] File upload error:",i),i}}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)}`,o=`${s}/channel-home/download?${r}`,i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const a=await fetch(o,{method:"GET",headers:i});if(!a.ok)throw new Error(`Channel Home download failed: ${a.status} ${a.statusText}`);const c=await a.blob(),u=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] Channel Home download response:",{filename:u,size:c.size}),{blob:c,filename:u}}catch(a){throw console.error("[AsgardServiceClient] Channel Home download error:",a),a}}async generateSandboxBrowserOpenUrl(t,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=ne(new URL(`${s}/sandbox/${encodeURIComponent(t)}/browser/open-url`),e),o=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data?.openURL??i.openURL;if(!a)throw new Error("Sandbox browser open-url response did not contain an openURL.");return a}async createSandboxBrowserSession(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive sandbox browser session endpoint. Please provide botProviderEndpoint in config.");const r=ne(new URL(`${s}/sandbox/${encodeURIComponent(t)}/browser/session`),e),o=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data?.wsUrl??i.wsUrl,c=i.data?.token??i.token;if(!a||!c)throw new Error("Sandbox browser session response did not contain both wsUrl and token.");return{wsUrl:a,token:c}}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 ne(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 o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data??i;return{entries:a.entries??[],truncated:a.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 o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=o.headers.get("X-Total-Bytes"),a=s?.onProgress?await kn(o,i!=null?Number(i):null,s.onProgress):await o.blob();return{content:a,totalBytes:i!=null?Number(i):a.size,truncated:o.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,s,r){const o=this.sandboxFsUrl(t,"file",r);o.searchParams.set("path",e),r?.mode!=null&&o.searchParams.set("mode",String(r.mode)),r?.createOnly&&o.searchParams.set("create_only","true");const i=new FormData;i.append("file",s instanceof Blob?s:new Blob([s]));const a=await fetch(o.toString(),{method:"PUT",headers:this.apiHeaders(),body:i,signal:r?.signal});if(!a.ok)throw new C(a.status,a.statusText,await a.text().catch(()=>{}));const c=await a.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,s,r,o){const i=this.sandboxFsUrl(t,e,o);Object.entries(r).forEach(([c,u])=>i.searchParams.set(c,u));const a=await fetch(i.toString(),{method:s,headers:this.apiHeaders()});if(!a.ok)throw new C(a.status,a.statusText,await a.text().catch(()=>{}));return a.json().catch(()=>null)}async sandboxFsStat(t,e,s){const r=this.sandboxFsUrl(t,"stat",s);r.searchParams.set("path",e);const o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.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,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 o={src:e,dst:s};r?.overwrite&&(o.overwrite="true");const i=await this.sandboxFsRequest(t,"copy","POST",o,r);return{bytesCopied:(i?.data??i)?.bytesCopied??0}}async sandboxFsMove(t,e,s,r){const o={src:e,dst:s};r?.overwrite&&(o.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",o,r)}sandboxFsWatch(t,e,s){const r=this.sandboxFsUrl(t,"watch",s);return r.searchParams.set("path",e),new A(o=>{const i=new AbortController;return Me(r.toString(),{headers:this.apiHeaders(),signal:i.signal,openWhenHidden:!0,onopen:async a=>{if(!a.ok){const c=await a.text().catch(()=>{});o.error(new C(a.status,a.statusText,c)),i.abort()}},onmessage:a=>{a.event==="change"&&o.next(JSON.parse(a.data))},onclose:()=>o.complete(),onerror:a=>{throw o.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 et="",On=new Set(["",".",".."]);function P(n,t){if(n===et){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=>On.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const me=1e3,tt=1e4;function ke(n){return Math.min(Math.max(1,Math.floor(n)),me)}class _n{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,o){const i=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([c,u])=>i.searchParams.set(c,u));const a=await fetch(i.toString(),{method:e,headers:this.headers(),body:r,signal:o});if(!a.ok)throw new C(a.status,a.statusText,await a.text().catch(()=>{}));return a}async list(t,e){const s={path:P(t,{allowRoot:!0})};e?.page!=null&&(s.page=String(e.page)),e?.pageSize!=null&&(s.page_size=String(ke(e.pageSize)));const o=await(await this.request("list","GET",s)).json(),i=o.data??o;return{entries:i.entries??[],paging:i.paging??o.paging??null}}async listAll(t,e){const s=ke(e?.pageSize??me),r=e?.maxEntries??tt,o=[];let i=0,a=!0,c=0;for(;;){const u=await this.list(t,{page:c,pageSize:s}),l=u.paging;if(l&&l.index!==c){i=l.total,a=!1;break}if(o.push(...u.entries),!l){a=u.entries.length<s;break}if(i=l.total,o.length>=i)break;if(o.length>=r||u.entries.length===0){a=!1;break}c+=1}return{entries:o,total:i,complete:a}}async stat(t){const s=await(await this.request("stat","GET",{path:P(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:P(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),o=await r.blob(),i=r.headers.get("X-Total-Bytes");return{content:o,totalBytes:i!=null?Number(i):o.size,truncated:r.headers.get("X-Truncated")==="true"}}async write(t,e,s){const r={path:P(t)};s?.mode!=null&&(r.mode=String(s.mode)),s?.createOnly&&(r.create_only="true");const o=new FormData;o.append("file",e instanceof Blob?e:new Blob([e]));const a=await(await this.request("file","PUT",r,o,s?.signal)).json();return{bytesWritten:(a.data??a).bytesWritten??0}}async mkdir(t,e){await this.request("mkdir","POST",{path:P(t)},void 0,e?.signal)}async remove(t){await this.request("item","DELETE",{path:P(t)})}async removeAll(t){await this.request("all","DELETE",{path:P(t)})}async copy(t,e,s){const r=this.copyMoveQuery(t,e,s),i=await(await this.request("copy","POST",r)).json();return{bytesCopied:(i.data??i).bytesCopied??0}}async move(t,e,s){await this.request("move","POST",this.copyMoveQuery(t,e,s))}copyMoveQuery(t,e,s){const r={src:P(t),dst:P(e)};return s?.overwrite&&(r.overwrite="true"),r}}const T=[];for(let n=0;n<256;++n)T.push((n+256).toString(16).slice(1));function Pn(n,t=0){return(T[n[t+0]]+T[n[t+1]]+T[n[t+2]]+T[n[t+3]]+"-"+T[n[t+4]]+T[n[t+5]]+"-"+T[n[t+6]]+T[n[t+7]]+"-"+T[n[t+8]]+T[n[t+9]]+"-"+T[n[t+10]]+T[n[t+11]]+T[n[t+12]]+T[n[t+13]]+T[n[t+14]]+T[n[t+15]]).toLowerCase()}let se;const Mn=new Uint8Array(16);function Ln(){if(!se){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");se=crypto.getRandomValues.bind(crypto)}return se(Mn)}const Un=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ae={randomUUID:Un};function Rn(n,t,e){n=n||{};const s=n.random??n.rng?.()??Ln();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,Pn(s)}function nt(n,t,e){return Ae.randomUUID&&!n?Ae.randomUUID():Rn(n)}class y{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 y({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}clearPendingConsent(){return this.pendingConsent?new y({messages:this.messages,pendingConsent:null,pendingFeedback:this.pendingFeedback}):this}restorePendingConsent(t){return this.pendingConsent?this:new y({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 y({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback}):this}cancelInFlightToolCalls(){return this.settleInFlightMessages()}onMessage(t){switch(t.eventType){case h.MESSAGE_START:return this.onMessageStart(t);case h.MESSAGE_DELTA:return this.onMessageDelta(t);case h.MESSAGE_COMPLETE:return this.onMessageComplete(t);case h.MESSAGE_USER:return this.onMessageUser(t);case h.MESSAGE_FEEDBACK:return this.onMessageFeedback(t);case h.MESSAGE_THINKING_START:return this.onThinkingStart(t);case h.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case h.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case h.MESSAGE_CANVAS_START:return this.onCanvasStart(t);case h.MESSAGE_CANVAS_DELTA:return this.onCanvasDelta(t);case h.MESSAGE_CANVAS_COMPLETE:return this.onCanvasComplete(t);case h.TOOL_CALL_START:return this.onToolCallStart(t);case h.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case h.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case h.SUBAGENT_START:return this.onSubagentStart(t);case h.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case h.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:h.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new y({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,o=new Map(this.messages);return o.set(e.messageId,{type:"bot",eventType:h.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 y({messages:o,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),o=r?.type==="bot"?r:void 0,i=this.pendingFeedback?.get(e.messageId),a=i??o?.feedback;s.set(e.messageId,{type:"bot",eventType:h.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,...a?{feedback:a}:{},time:new Date,traceId:t.traceId??o?.traceId,raw:JSON.stringify(t)});let c=this.pendingFeedback;return i&&(c=new Map(this.pendingFeedback),c.delete(e.messageId)),new y({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 o=new Map(this.messages),i={...s,feedback:e};return o.set(t,i),new y({messages:o,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const r=new Map(this.pendingFeedback);return r.set(t,e),new y({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 y({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,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:`${r?.text??""}${e.text}`,isThinking:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return o.set(e.messageId,i),new y({messages:o,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,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return o.set(e.messageId,i),new y({messages:o,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 y({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,o=new Map(this.messages),i={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 o.set(e.messageId,i),new y({messages:o,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const s=e.template?.type===he.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 y({messages:u,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const o=this.messages?.get(e.messageId),i=o?.type==="canvas"?o:void 0,a=new Map(this.messages),c={type:"canvas",messageId:e.messageId,html:r,title:s?.title,isDrawing:!1,time:i?.time??new Date,traceId:t.traceId??i?.traceId};return a.set(e.messageId,c),new y({messages:a,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),o={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,o),new y({messages:r,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageError(t){const e=nt(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:h.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new y({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 o={type:"tool-call",eventType:h.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,o),new y({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}`,o=s.get(r);if(o?.type==="tool-call"){const i={...o,eventType:h.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??o.traceId};s.set(r,i)}else{const i={type:"tool-call",eventType:h.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,i)}return new y({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new y({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`,o={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,o),new y({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`,o={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,o),new y({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}}const Fn=new Set(["TaskCreate","TaskUpdate"]);function st(n){return n.toolsetName===""&&Fn.has(n.toolName)}function Oe(n){return typeof n=="object"&&n!==null?n:void 0}function R(n){return typeof n=="string"?n:void 0}function rt(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},o=s.sidecar??{};if(s.toolName==="TaskCreate"){const i=Oe(o.task),a=R(i?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:R(r.subject)||R(i?.subject)||"",activeForm:R(r.activeForm),description:R(r.description),status:e.get(a)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const i=Oe(o.statusChange),a=R(r.taskId)||R(o.taskId),c=R(i?.to)||R(r.status);if(!a||!c)continue;const u=e.get(a);u&&e.set(a,{...u,status:c})}}return t.map(s=>e.get(s))}function ot(n){return n.toolsetName===""&&n.toolName==="Agent"}function it(n){return!!n}function _e(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function at(n){const t=[],e=new Map,s=new Map,r=o=>(e.has(o)||(t.push(o),e.set(o,{status:"running"}),s.set(o,new Map)),e.get(o));for(const o of n)switch(o.kind){case"agentStart":{const i=r(o.toolUseId);o.description&&!i.description&&(i.description=o.description);break}case"subagentStart":{const i=r(o.parentToolUseId);i.agentId=o.agentId??i.agentId,i.subagentType=o.subagentType??i.subagentType,i.description=o.description??i.description,_e(i);break}case"toolStart":{_e(r(o.parentToolUseId)),s.get(o.parentToolUseId).set(o.toolUseId,{toolsetName:o.toolsetName,toolName:o.toolName,parameter:o.parameter??{},reason:o.reason,status:"running"});break}case"toolComplete":{const i=s.get(o.parentToolUseId)?.get(o.toolUseId);if(!i)break;i.status=o.isError?"error":"completed",o.result!==void 0&&(i.result=o.result),o.sidecar!==void 0&&(i.sidecar=o.sidecar);break}case"subagentComplete":{const i=r(o.parentToolUseId);i.status=o.status,i.summary=o.summary;break}}return t.map(o=>({parentToolUseId:o,...e.get(o),tools:Array.from(s.get(o).values())}))}function Nn(n){return typeof n=="string"?n:void 0}function ct(n){const t=[];for(const e of n){if(e.type==="tool-call"&&ot(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:Nn(e.parameter.description)});continue}if(e.type==="tool-call"&&it(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,result:e.result,sidecar:e.sidecar});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 ut(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&st(e));return rt(t)}function lt(n){return at(ct(Array.from(n.messages?.values()??[])))}function dt(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 jn(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&&e.result===r.result&&e.sidecar===r.sidecar})}function ht(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&&jn(e.tools,r.tools)})}function ft(n){const t=new M([]),e=new M([]),s=new D;return s.add(n.pipe(Q(ut),N(dt)).subscribe(t)),s.add(n.pipe(Q(lt),N(ht)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function ue(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 re={kind:null,stopPhase:"idle"},$n=1e4;function Dn(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class G{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;sandboxWakeSubject;wakeInFlight;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;promptSuggestion$;sandboxPhase$;launchedSandboxes$;runStatus$;sandboxWake$;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 M(!1),this.runStatusSubject=new M(re),this.conversation$=new M(t.conversation),this.channelTitleSubject=new M(t.channelTitle??null),this.promptSuggestionSubject=new M(null),this.sandboxPhaseSubject=new M("idle"),this.launchedSandboxesSubject=new M(ue(t.launchedSandboxes??[])),this.sandboxWakeSubject=new M({phase:"idle"}),this.derivedStores=ft(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(Dn)),this.sandboxWake$=this.sandboxWakeSubject.pipe(N((e,s)=>e.phase===s.phase)),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}getSandboxWake(){return this.sandboxWakeSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=ue(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 G(t);return e.subscribe(),e}static async open(t,e,s,r){const o=new G(t);try{return o.subscribe(),r?.(o),await o.openChannel(e,s),o}catch(i){throw o.close(),i}}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),G.open(t,e,s,r)}static async restore(t,e,s){const r=new G(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(o){throw r.close(),o}}subscribe(){this.statesSubscription=Sn([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.promptSuggestion$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe(Q(([t,e,s,r,o,i,a,c,u])=>({isConnecting:t,conversation:e,tasks:s,subagents:r,channelTitle:o,promptSuggestion:i,sandboxPhase:a,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 h.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case h.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case h.INIT:case h.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===h.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(r.fact.channelTitleUpdate.title),r.eventType===h.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(r.fact.promptSuggestion.suggestion):r.eventType===h.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(r.eventType),r.eventType===h.SANDBOX_LAUNCH&&this.noteSandboxLaunch(r.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&r.traceId){const o=new Map(this.conversation$.value.messages),i=o.get(this.currentUserMessageId);i&&i.type==="user"&&(o.set(this.currentUserMessageId,{...i,traceId:r.traceId}),this.conversation$.next(new y({messages:o,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(re),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,o)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(s,r,o))})}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:B.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 z(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new J(r.processId));this.clearPromptSuggestion();const o=t.text.trim(),i=t.customMessageId??nt();return this.currentUserMessageId=i,this.lastSentMessageId=i,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:i,text:o,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:B.NONE,customChannelId:this.customChannelId,customMessageId:i,payload:this.resolvePayload(t?.payload),text:o,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:B.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(s),text:"",toolCallConsents:t},e).catch(o=>{throw r&&this.conversation$.next(this.conversation$.value.restorePendingConsent(r)),o})}nudge(t,e){return this.wakeInFlight&&!this.runStatusSubject.value.kind?this.wakeInFlight.then(()=>{}):this.sendNudge(t,e)}async wakeSandbox(t,e,s){return this.wakeInFlight?this.judgeWake(await this.wakeInFlight,t):this.isSandboxLive(t)?"live":this.runStatusSubject.value.kind||this.conversation$.value.pendingConsent?"blocked":(this.sendNudge(s,e,t).catch(()=>{}),this.judgeWake(await(this.wakeInFlight??Promise.resolve(!1)),t))}isSandboxLive(t){const e=this.launchedSandboxesSubject.value;return t?e.some(s=>s.sandboxName===t):e.length>0}judgeWake(t,e){return t&&this.isSandboxLive(e)?"live":"failed"}trackWake(t,e){this.sandboxWakeSubject.next({phase:"waking"});const s=(async()=>{try{return await t,await this.refetchMetadata(),!0}catch{return!1}})();this.wakeInFlight=s,s.then(r=>{this.wakeInFlight=void 0,!this.sandboxWakeSubject.closed&&this.sandboxWakeSubject.next({phase:this.judgeWake(r,e)==="live"?"idle":"failed"})})}sendNudge(t,e,s){const r=this.runStatusSubject.value.kind;if(r)return Promise.reject(new z(r));const o=this.conversation$.value.pendingConsent;if(o)return Promise.reject(new J(o.processId));const i=this.fetchSse("nudge",{action:B.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t);return this.trackWake(i,s),i}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(re),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.sandboxWakeSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}const pt={GOOD:"[Response Feedback: Good]",BAD:"[Response Feedback: Bad]"},Hn=8*1024;function Bn(n){return new TextEncoder().encode(n).length}function Gn(n,t){const e=pt[n],s=t?.trim()??"";return s?`${e}
4
+ `):"",this.name="UnsubscriptionError",this.errors=e}});function X(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var D=(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,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=$(i),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(d){t={error:d}}finally{try{c&&!c.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else i.remove(this);var l=this.initialTeardown;if(E(l))try{l()}catch(d){o=d instanceof te?d.errors:[d]}var v=this._finalizers;if(v){this._finalizers=null;try{for(var w=$(v),p=w.next();!p.done;p=w.next()){var g=p.value;try{ye(g)}catch(d){o=o??[],d instanceof te?o=W(W([],q(o)),q(d.errors)):o.push(d)}}}catch(d){s={error:d}}finally{try{p&&!p.done&&(r=w.return)&&r.call(w)}finally{if(s)throw s.error}}}if(o)throw new te(o)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)ye(t);else{if(t instanceof n){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(t)}},n.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},n.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},n.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&X(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&X(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),Re=D.EMPTY;function Fe(n){return n instanceof D||n&&"closed"in n&&E(n.remove)&&E(n.add)&&E(n.unsubscribe)}function ye(n){E(n)?n():n.unsubscribe()}var _t={Promise:void 0},Pt={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,W([n,t],q(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Ne(n){Pt.setTimeout(function(){throw n})}function ae(){}function Y(n){n()}var fe=(function(n){F(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,Fe(e)&&e.add(s)):s.destination=Ut,s}return t.create=function(e,s,r){return new ce(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})(D),Mt=(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){V(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){V(s)}else V(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){V(e)}},n})(),ce=(function(n){F(t,n);function t(e,s,r){var o=n.call(this)||this,i;return E(e)||!e?i={next:e??void 0,error:s??void 0,complete:r??void 0}:i=e,o.destination=new Mt(i),o}return t})(fe);function V(n){Ne(n)}function Lt(n){throw n}var Ut={closed:!0,next:ae,error:Lt,complete:ae},pe=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Z(n){return n}function Rt(n){return n.length===0?Z:n.length===1?n[0]:function(e){return n.reduce(function(s,r){return r(s)},e)}}var A=(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,o=Nt(t)?t:new ce(t,e,s);return Y(function(){var i=r,a=i.operator,c=i.source;o.add(a?a.call(o,c):c?r._subscribe(o):r._trySubscribe(o))}),o},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=we(e),new e(function(r,o){var i=new ce({next:function(a){try{t(a)}catch(c){o(c),i.unsubscribe()}},error:o,complete:r});s.subscribe(i)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[pe]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Rt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=we(t),new t(function(s,r){var o;e.subscribe(function(i){return o=i},function(i){return r(i)},function(){return s(o)})})},n.create=function(t){return new n(t)},n})();function we(n){var t;return(t=n??_t.Promise)!==null&&t!==void 0?t:Promise}function Ft(n){return n&&E(n.next)&&E(n.error)&&E(n.complete)}function Nt(n){return n&&n instanceof fe||Ft(n)&&Fe(n)}function jt(n){return E(n?.lift)}function j(n){return function(t){if(jt(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 H(n,t,e,s,r){return new $t(n,t,e,s,r)}var $t=(function(n){F(t,n);function t(e,s,r,o,i,a){var c=n.call(this,e)||this;return c.onFinalize=i,c.shouldUnsubscribe=a,c._next=s?function(u){try{s(u)}catch(l){e.error(l)}}:n.prototype._next,c._error=o?function(u){try{o(u)}catch(l){e.error(l)}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})(fe),Dt=Ue(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ge=(function(n){F(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 Ee(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Dt},t.prototype.next=function(e){var s=this;Y(function(){var r,o;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var i=$(s.currentObservers),a=i.next();!a.done;a=i.next()){var c=a.value;c.next(e)}}catch(u){r={error:u}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var s=this;Y(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;Y(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,o=r.hasError,i=r.isStopped,a=r.observers;return o||i?Re:(this.currentObservers=null,a.push(e),new D(function(){s.currentObservers=null,X(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var s=this,r=s.hasError,o=s.thrownError,i=s.isStopped;r?e.error(o):i&&e.complete()},t.prototype.asObservable=function(){var e=new A;return e.source=this,e},t.create=function(e,s){return new Ee(e,s)},t})(A),Ee=(function(n){F(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:Re},t})(ge),M=(function(n){F(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,o=e._value;if(s)throw r;return this._throwIfClosed(),o},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(ge),Ht={now:function(){return Date.now()}},Bt=(function(n){F(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(D),Ie={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,W([n,t],q(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Gt=(function(n){F(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 o=this.id,i=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(i,o,s)),this.pending=!0,this.delay=s,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(i,this.id,s),this},t.prototype.requestAsyncId=function(e,s,r){return r===void 0&&(r=0),Ie.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&&Ie.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,o;try{this.work(e)}catch(i){r=!0,o=i||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),o},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,s=e.id,r=e.scheduler,o=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,X(o,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Bt),Te=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,s){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(s,e)},n.now=Ht.now,n})(),Kt=(function(n){F(t,n);function t(e,s){s===void 0&&(s=Te.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})(Te),qt=new Kt(Gt);function Wt(n){return n&&E(n.schedule)}function je(n){return n[n.length-1]}function Xt(n){return E(je(n))?n.pop():void 0}function $e(n){return Wt(je(n))?n.pop():void 0}var De=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function He(n){return E(n?.then)}function Be(n){return E(n[pe])}function Ge(n){return Symbol.asyncIterator&&E(n?.[Symbol.asyncIterator])}function Ke(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 Vt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var qe=Vt();function We(n){return E(n?.[qe])}function Xe(n){return At(this,arguments,function(){var e,s,r,o;return Le(this,function(i){switch(i.label){case 0:e=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,K(e.read())];case 3:return s=i.sent(),r=s.value,o=s.done,o?[4,K(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,K(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function Ve(n){return E(n?.getReader)}function ee(n){if(n instanceof A)return n;if(n!=null){if(Be(n))return Yt(n);if(De(n))return zt(n);if(He(n))return Jt(n);if(Ge(n))return Ye(n);if(We(n))return Qt(n);if(Ve(n))return Zt(n)}throw Ke(n)}function Yt(n){return new A(function(t){var e=n[pe]();if(E(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function zt(n){return new A(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Jt(n){return new A(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Ne)})}function Qt(n){return new A(function(t){var e,s;try{for(var r=$(n),o=r.next();!o.done;o=r.next()){var i=o.value;if(t.next(i),t.closed)return}}catch(a){e={error:a}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(e)throw e.error}}t.complete()})}function Ye(n){return new A(function(t){en(n,t).catch(function(e){return t.error(e)})})}function Zt(n){return Ye(Xe(n))}function en(n,t){var e,s,r,o;return kt(this,void 0,void 0,function(){var i,a;return Le(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=Ot(n),c.label=1;case 1:return[4,e.next()];case 2:if(s=c.sent(),!!s.done)return[3,4];if(i=s.value,t.next(i),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),s&&!s.done&&(o=e.return)?[4,o.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 L(n,t,e,s,r){s===void 0&&(s=0),r===void 0&&(r=!1);var o=t.schedule(function(){e(),r?n.add(this.schedule(null,s)):this.unsubscribe()},s);if(n.add(o),!r)return o}function ze(n,t){return t===void 0&&(t=0),j(function(e,s){e.subscribe(H(s,function(r){return L(s,n,function(){return s.next(r)},t)},function(){return L(s,n,function(){return s.complete()},t)},function(r){return L(s,n,function(){return s.error(r)},t)}))})}function Je(n,t){return t===void 0&&(t=0),j(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function tn(n,t){return ee(n).pipe(Je(t),ze(t))}function nn(n,t){return ee(n).pipe(Je(t),ze(t))}function sn(n,t){return new A(function(e){var s=0;return t.schedule(function(){s===n.length?e.complete():(e.next(n[s++]),e.closed||this.schedule())})})}function rn(n,t){return new A(function(e){var s;return L(e,t,function(){s=n[qe](),L(e,t,function(){var r,o,i;try{r=s.next(),o=r.value,i=r.done}catch(a){e.error(a);return}i?e.complete():e.next(o)},0,!0)}),function(){return E(s?.return)&&s.return()}})}function Qe(n,t){if(!n)throw new Error("Iterable cannot be null");return new A(function(e){L(e,t,function(){var s=n[Symbol.asyncIterator]();L(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function on(n,t){return Qe(Xe(n),t)}function an(n,t){if(n!=null){if(Be(n))return tn(n,t);if(De(n))return sn(n,t);if(He(n))return nn(n,t);if(Ge(n))return Qe(n,t);if(We(n))return rn(n,t);if(Ve(n))return on(n,t)}throw Ke(n)}function Ze(n,t){return t?an(n,t):ee(n)}function Q(n,t){return j(function(e,s){var r=0;e.subscribe(H(s,function(o){s.next(n.call(t,o,r++))}))})}var cn=Array.isArray;function un(n,t){return cn(t)?n.apply(void 0,W([],q(t))):n(t)}function ln(n){return Q(function(t){return un(n,t)})}var dn=Array.isArray,hn=Object.getPrototypeOf,fn=Object.prototype,pn=Object.keys;function gn(n){if(n.length===1){var t=n[0];if(dn(t))return{args:t,keys:null};if(mn(t)){var e=pn(t);return{args:e.map(function(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function mn(n){return n&&typeof n=="object"&&hn(n)===fn}function bn(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function Sn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=$e(n),s=Xt(n),r=gn(n),o=r.args,i=r.keys;if(o.length===0)return Ze([],e);var a=new A(vn(o,e,i?function(c){return bn(i,c)}:Z));return s?a.pipe(ln(s)):a}function vn(n,t,e){return e===void 0&&(e=Z),function(s){Ce(t,function(){for(var r=n.length,o=new Array(r),i=r,a=r,c=function(l){Ce(t,function(){var v=Ze(n[l],t),w=!1;v.subscribe(H(s,function(p){o[l]=p,w||(w=!0,a--),a||s.next(e(o.slice()))},function(){--i||s.complete()}))},s)},u=0;u<r;u++)c(u)},s)}}function Ce(n,t,e){n?L(e,n,t):t()}function yn(n,t){return j(function(e,s){var r=0;e.subscribe(H(s,function(o){return n.call(t,o,r++)&&s.next(o)}))})}function wn(n){for(var t,e,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var o=(t=$e(s))!==null&&t!==void 0?t:qt,i=(e=s[0])!==null&&e!==void 0?e:null,a=s[1]||1/0;return j(function(c,u){var l=[],v=!1,w=function(d){var x=d.buffer,k=d.subs;k.unsubscribe(),X(l,d),u.next(x),v&&p()},p=function(){if(l){var d=new D;u.add(d);var x=[],k={buffer:x,subs:d};l.push(k),L(d,o,function(){return w(k)},n)}};i!==null&&i>=0?L(u,o,p,i,!0):v=!0,p();var g=H(u,function(d){var x,k,f=l.slice();try{for(var m=$(f),S=m.next();!S.done;S=m.next()){var b=S.value,I=b.buffer;I.push(d),a<=I.length&&w(b)}}catch(U){x={error:U}}finally{try{S&&!S.done&&(k=m.return)&&k.call(m)}finally{if(x)throw x.error}}},function(){for(;l?.length;)u.next(l.shift().buffer);g?.unsubscribe(),u.complete(),u.unsubscribe()},void 0,function(){return l=null});c.subscribe(g)})}function N(n,t){return t===void 0&&(t=Z),n=n??En,j(function(e,s){var r,o=!0;e.subscribe(H(s,function(i){var a=t(i);(o||!n(r,a))&&(o=!1,r=a,s.next(i))}))})}function En(n,t){return n===t}function In(n){return j(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function Tn(n){return j(function(t,e){ee(n).subscribe(H(e,function(){return e.complete()},ae)),!e.closed&&t.subscribe(e)})}function xe(n){const{endpoint:t,apiKey:e,payload:s,debugMode:r,customHeaders:o}=n,i=n.method??"POST";return new A(a=>{const c=new AbortController;let u,l=!1,v=!1;const w={"Content-Type":"application/json",...o};e&&(w["X-API-KEY"]=e);const p=new URL(t);return r&&p.searchParams.set("is_debug","true"),Me(p.toString(),{method:i,headers:w,body:i==="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 d;try{d=await g.json()}catch{try{d=await g.text()}catch{d=null}}a.error(new C(g.status,g.statusText,d)),c.abort()}},onmessage:g=>{g.id&&(l=!0);const d=JSON.parse(g.data);u?d.traceId=u:d.requestId&&(d.traceId=d.requestId,u||(u=d.requestId)),a.next(d)},onclose:()=>{a.complete()},onerror:g=>{if(v)throw g;if(!l)throw a.error(g),c.abort(),g}}),()=>{v=!0,c.abort()}})}class Cn{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 xn=50;function ne(n,t){return t?.customChannelId&&n.searchParams.set("custom_channel_id",t.customChannelId),n}async function kn(n,t,e){if(!n.body)return n.blob();const s=n.body.getReader(),r=[];let o=0;for(e(0,t);;){const{done:i,value:a}=await s.read();if(i)break;r.push(a.slice()),o+=a.byteLength,e(o,t)}return new Blob(r,{type:n.headers.get("Content-Type")??""})}class An{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new ge;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new Cn;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 h.INIT:this.sseEmitter.emit(h.INIT,t);break;case h.PROCESS_START:case h.PROCESS_COMPLETE:this.sseEmitter.emit(h.PROCESS,t);break;case h.MESSAGE_START:case h.MESSAGE_DELTA:case h.MESSAGE_COMPLETE:this.sseEmitter.emit(h.MESSAGE,t);break;case h.TOOL_CALL_START:case h.TOOL_CALL_COMPLETE:this.sseEmitter.emit(h.TOOL_CALL,t);break;case h.TOOL_CALL_CONSENT:this.sseEmitter.emit(h.TOOL_CALL_CONSENT,t);break;case h.DONE:this.sseEmitter.emit(h.DONE,t);break;case h.ERROR:this.sseEmitter.emit(h.ERROR,t);break}}fetchSse(t,e){return e?.onSseStart?.(),this.inFlight+=1,this.runSse(xe({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(xe({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 o=await fetch(s.toString(),{method:"GET",headers:r});if(o.status===404)return null;if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data??i;return{title:a.title??null,runState:a.runState??"IDLE",lastActivityAt:a.lastActivityAt,launchedSandboxes:(a.launchedSandboxes??[]).map(c=>({sandboxName:c.sandboxName,sandboxBlueprintName:c.sandboxBlueprintName,workingDirectory:c.workingDirectory,editorServerEnabled:c.editorServerEnabled,browserEnabled:c.browserEnabled}))}}deriveSuspendEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/suspend`:null}async suspendChannel(t,e){const 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 o=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!(o.ok||o.status===404))throw new C(o.status,o.statusText,await o.text().catch(()=>{}))}deriveChannelEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel`:null}async deleteChannel(t){await this.releaseChannel("DELETE","",t)}async clearChannel(t){await this.releaseChannel("POST","/clear",t)}async releaseChannel(t,e,s){const r=this.deriveChannelEndpoint();if(!r)throw new Error("Unable to derive channel endpoint. Please provide botProviderEndpoint in config.");const o=new URL(`${r}${e}`);o.searchParams.set("custom_channel_id",s);const i=await fetch(o.toString(),{method:t,headers:this.apiHeaders()});if(!i.ok)throw new C(i.status,i.statusText,await i.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}:{}},o=await fetch(e,{method:"POST",headers:{...this.apiHeaders(),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data??i;return{messageId:a.messageId,seq:a.seq}}runSse(t,e){return t.pipe(wn(e?.delayTime??xn),yn(s=>s.length>0),Tn(this.destroy$),In(()=>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 o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const i=await fetch(s,{method:"POST",headers:o,body:r});if(!i.ok)throw new Error(`Upload failed: ${i.status} ${i.statusText}`);const a=await i.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(i){throw console.error("[AsgardServiceClient] File upload error:",i),i}}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)}`,o=`${s}/channel-home/download?${r}`,i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const a=await fetch(o,{method:"GET",headers:i});if(!a.ok)throw new Error(`Channel Home download failed: ${a.status} ${a.statusText}`);const c=await a.blob(),u=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] Channel Home download response:",{filename:u,size:c.size}),{blob:c,filename:u}}catch(a){throw console.error("[AsgardServiceClient] Channel Home download error:",a),a}}async generateSandboxBrowserOpenUrl(t,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=ne(new URL(`${s}/sandbox/${encodeURIComponent(t)}/browser/open-url`),e),o=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data?.openURL??i.openURL;if(!a)throw new Error("Sandbox browser open-url response did not contain an openURL.");return a}async createSandboxBrowserSession(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive sandbox browser session endpoint. Please provide botProviderEndpoint in config.");const r=ne(new URL(`${s}/sandbox/${encodeURIComponent(t)}/browser/session`),e),o=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data?.wsUrl??i.wsUrl,c=i.data?.token??i.token;if(!a||!c)throw new Error("Sandbox browser session response did not contain both wsUrl and token.");return{wsUrl:a,token:c}}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 ne(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 o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.json(),a=i.data??i;return{entries:a.entries??[],truncated:a.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 o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=o.headers.get("X-Total-Bytes"),a=s?.onProgress?await kn(o,i!=null?Number(i):null,s.onProgress):await o.blob();return{content:a,totalBytes:i!=null?Number(i):a.size,truncated:o.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,s,r){const o=this.sandboxFsUrl(t,"file",r);o.searchParams.set("path",e),r?.mode!=null&&o.searchParams.set("mode",String(r.mode)),r?.createOnly&&o.searchParams.set("create_only","true");const i=new FormData;i.append("file",s instanceof Blob?s:new Blob([s]));const a=await fetch(o.toString(),{method:"PUT",headers:this.apiHeaders(),body:i,signal:r?.signal});if(!a.ok)throw new C(a.status,a.statusText,await a.text().catch(()=>{}));const c=await a.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,s,r,o){const i=this.sandboxFsUrl(t,e,o);Object.entries(r).forEach(([c,u])=>i.searchParams.set(c,u));const a=await fetch(i.toString(),{method:s,headers:this.apiHeaders()});if(!a.ok)throw new C(a.status,a.statusText,await a.text().catch(()=>{}));return a.json().catch(()=>null)}async sandboxFsStat(t,e,s){const r=this.sandboxFsUrl(t,"stat",s);r.searchParams.set("path",e);const o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new C(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.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,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 o={src:e,dst:s};r?.overwrite&&(o.overwrite="true");const i=await this.sandboxFsRequest(t,"copy","POST",o,r);return{bytesCopied:(i?.data??i)?.bytesCopied??0}}async sandboxFsMove(t,e,s,r){const o={src:e,dst:s};r?.overwrite&&(o.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",o,r)}sandboxFsWatch(t,e,s){const r=this.sandboxFsUrl(t,"watch",s);return r.searchParams.set("path",e),new A(o=>{const i=new AbortController;return Me(r.toString(),{headers:this.apiHeaders(),signal:i.signal,openWhenHidden:!0,onopen:async a=>{if(!a.ok){const c=await a.text().catch(()=>{});o.error(new C(a.status,a.statusText,c)),i.abort()}},onmessage:a=>{a.event==="change"&&o.next(JSON.parse(a.data))},onclose:()=>o.complete(),onerror:a=>{throw o.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 et="",On=new Set(["",".",".."]);function P(n,t){if(n===et){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=>On.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const me=1e3,tt=1e4;function ke(n){return Math.min(Math.max(1,Math.floor(n)),me)}class _n{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,o){const i=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([c,u])=>i.searchParams.set(c,u));const a=await fetch(i.toString(),{method:e,headers:this.headers(),body:r,signal:o});if(!a.ok)throw new C(a.status,a.statusText,await a.text().catch(()=>{}));return a}async list(t,e){const s={path:P(t,{allowRoot:!0})};e?.page!=null&&(s.page=String(e.page)),e?.pageSize!=null&&(s.page_size=String(ke(e.pageSize)));const o=await(await this.request("list","GET",s)).json(),i=o.data??o;return{entries:i.entries??[],paging:i.paging??o.paging??null}}async listAll(t,e){const s=ke(e?.pageSize??me),r=e?.maxEntries??tt,o=[];let i=0,a=!0,c=0;for(;;){const u=await this.list(t,{page:c,pageSize:s}),l=u.paging;if(l&&l.index!==c){i=l.total,a=!1;break}if(o.push(...u.entries),!l){a=u.entries.length<s;break}if(i=l.total,o.length>=i)break;if(o.length>=r||u.entries.length===0){a=!1;break}c+=1}return{entries:o,total:i,complete:a}}async stat(t){const s=await(await this.request("stat","GET",{path:P(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:P(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),o=await r.blob(),i=r.headers.get("X-Total-Bytes");return{content:o,totalBytes:i!=null?Number(i):o.size,truncated:r.headers.get("X-Truncated")==="true"}}async write(t,e,s){const r={path:P(t)};s?.mode!=null&&(r.mode=String(s.mode)),s?.createOnly&&(r.create_only="true");const o=new FormData;o.append("file",e instanceof Blob?e:new Blob([e]));const a=await(await this.request("file","PUT",r,o,s?.signal)).json();return{bytesWritten:(a.data??a).bytesWritten??0}}async mkdir(t,e){await this.request("mkdir","POST",{path:P(t)},void 0,e?.signal)}async remove(t){await this.request("item","DELETE",{path:P(t)})}async removeAll(t){await this.request("all","DELETE",{path:P(t)})}async copy(t,e,s){const r=this.copyMoveQuery(t,e,s),i=await(await this.request("copy","POST",r)).json();return{bytesCopied:(i.data??i).bytesCopied??0}}async move(t,e,s){await this.request("move","POST",this.copyMoveQuery(t,e,s))}copyMoveQuery(t,e,s){const r={src:P(t),dst:P(e)};return s?.overwrite&&(r.overwrite="true"),r}}const T=[];for(let n=0;n<256;++n)T.push((n+256).toString(16).slice(1));function Pn(n,t=0){return(T[n[t+0]]+T[n[t+1]]+T[n[t+2]]+T[n[t+3]]+"-"+T[n[t+4]]+T[n[t+5]]+"-"+T[n[t+6]]+T[n[t+7]]+"-"+T[n[t+8]]+T[n[t+9]]+"-"+T[n[t+10]]+T[n[t+11]]+T[n[t+12]]+T[n[t+13]]+T[n[t+14]]+T[n[t+15]]).toLowerCase()}let se;const Mn=new Uint8Array(16);function Ln(){if(!se){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");se=crypto.getRandomValues.bind(crypto)}return se(Mn)}const Un=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ae={randomUUID:Un};function Rn(n,t,e){n=n||{};const s=n.random??n.rng?.()??Ln();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,Pn(s)}function nt(n,t,e){return Ae.randomUUID&&!n?Ae.randomUUID():Rn(n)}class y{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 y({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}clearPendingConsent(){return this.pendingConsent?new y({messages:this.messages,pendingConsent:null,pendingFeedback:this.pendingFeedback}):this}restorePendingConsent(t){return this.pendingConsent?this:new y({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 y({messages:e,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback}):this}cancelInFlightToolCalls(){return this.settleInFlightMessages()}onMessage(t){switch(t.eventType){case h.MESSAGE_START:return this.onMessageStart(t);case h.MESSAGE_DELTA:return this.onMessageDelta(t);case h.MESSAGE_COMPLETE:return this.onMessageComplete(t);case h.MESSAGE_USER:return this.onMessageUser(t);case h.MESSAGE_FEEDBACK:return this.onMessageFeedback(t);case h.MESSAGE_THINKING_START:return this.onThinkingStart(t);case h.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case h.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case h.MESSAGE_CANVAS_START:return this.onCanvasStart(t);case h.MESSAGE_CANVAS_DELTA:return this.onCanvasDelta(t);case h.MESSAGE_CANVAS_COMPLETE:return this.onCanvasComplete(t);case h.TOOL_CALL_START:return this.onToolCallStart(t);case h.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case h.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case h.SUBAGENT_START:return this.onSubagentStart(t);case h.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case h.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:h.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new y({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,o=new Map(this.messages);return o.set(e.messageId,{type:"bot",eventType:h.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 y({messages:o,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),o=r?.type==="bot"?r:void 0,i=this.pendingFeedback?.get(e.messageId),a=i??o?.feedback;s.set(e.messageId,{type:"bot",eventType:h.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,...a?{feedback:a}:{},time:new Date,traceId:t.traceId??o?.traceId,raw:JSON.stringify(t)});let c=this.pendingFeedback;return i&&(c=new Map(this.pendingFeedback),c.delete(e.messageId)),new y({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 o=new Map(this.messages),i={...s,feedback:e};return o.set(t,i),new y({messages:o,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const r=new Map(this.pendingFeedback);return r.set(t,e),new y({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 y({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,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:`${r?.text??""}${e.text}`,isThinking:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return o.set(e.messageId,i),new y({messages:o,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,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return o.set(e.messageId,i),new y({messages:o,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 y({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,o=new Map(this.messages),i={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 o.set(e.messageId,i),new y({messages:o,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const s=e.template?.type===he.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 y({messages:u,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}const o=this.messages?.get(e.messageId),i=o?.type==="canvas"?o:void 0,a=new Map(this.messages),c={type:"canvas",messageId:e.messageId,html:r,title:s?.title,isDrawing:!1,time:i?.time??new Date,traceId:t.traceId??i?.traceId};return a.set(e.messageId,c),new y({messages:a,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),o={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,o),new y({messages:r,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onMessageError(t){const e=nt(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:h.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new y({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 o={type:"tool-call",eventType:h.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,o),new y({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}`,o=s.get(r);if(o?.type==="tool-call"){const i={...o,eventType:h.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??o.traceId};s.set(r,i)}else{const i={type:"tool-call",eventType:h.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,i)}return new y({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new y({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`,o={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,o),new y({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`,o={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,o),new y({messages:s,pendingConsent:this.pendingConsent,pendingFeedback:this.pendingFeedback})}}const Fn=new Set(["TaskCreate","TaskUpdate"]);function st(n){return n.toolsetName===""&&Fn.has(n.toolName)}function Oe(n){return typeof n=="object"&&n!==null?n:void 0}function R(n){return typeof n=="string"?n:void 0}function rt(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},o=s.sidecar??{};if(s.toolName==="TaskCreate"){const i=Oe(o.task),a=R(i?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:R(r.subject)||R(i?.subject)||"",activeForm:R(r.activeForm),description:R(r.description),status:e.get(a)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const i=Oe(o.statusChange),a=R(r.taskId)||R(o.taskId),c=R(i?.to)||R(r.status);if(!a||!c)continue;const u=e.get(a);u&&e.set(a,{...u,status:c})}}return t.map(s=>e.get(s))}function ot(n){return n.toolsetName===""&&n.toolName==="Agent"}function it(n){return!!n}function _e(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function at(n){const t=[],e=new Map,s=new Map,r=o=>(e.has(o)||(t.push(o),e.set(o,{status:"running"}),s.set(o,new Map)),e.get(o));for(const o of n)switch(o.kind){case"agentStart":{const i=r(o.toolUseId);o.description&&!i.description&&(i.description=o.description);break}case"subagentStart":{const i=r(o.parentToolUseId);i.agentId=o.agentId??i.agentId,i.subagentType=o.subagentType??i.subagentType,i.description=o.description??i.description,_e(i);break}case"toolStart":{_e(r(o.parentToolUseId)),s.get(o.parentToolUseId).set(o.toolUseId,{toolsetName:o.toolsetName,toolName:o.toolName,parameter:o.parameter??{},reason:o.reason,status:"running"});break}case"toolComplete":{const i=s.get(o.parentToolUseId)?.get(o.toolUseId);if(!i)break;i.status=o.isError?"error":"completed",o.result!==void 0&&(i.result=o.result),o.sidecar!==void 0&&(i.sidecar=o.sidecar);break}case"subagentComplete":{const i=r(o.parentToolUseId);i.status=o.status,i.summary=o.summary;break}}return t.map(o=>({parentToolUseId:o,...e.get(o),tools:Array.from(s.get(o).values())}))}function Nn(n){return typeof n=="string"?n:void 0}function ct(n){const t=[];for(const e of n){if(e.type==="tool-call"&&ot(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:Nn(e.parameter.description)});continue}if(e.type==="tool-call"&&it(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,result:e.result,sidecar:e.sidecar});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 ut(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&st(e));return rt(t)}function lt(n){return at(ct(Array.from(n.messages?.values()??[])))}function dt(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 jn(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&&e.result===r.result&&e.sidecar===r.sidecar})}function ht(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&&jn(e.tools,r.tools)})}function ft(n){const t=new M([]),e=new M([]),s=new D;return s.add(n.pipe(Q(ut),N(dt)).subscribe(t)),s.add(n.pipe(Q(lt),N(ht)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function ue(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 re={kind:null,stopPhase:"idle"},$n=1e4;function Dn(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class G{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;sandboxWakeSubject;wakeInFlight;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;promptSuggestion$;sandboxPhase$;launchedSandboxes$;runStatus$;sandboxWake$;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 M(!1),this.runStatusSubject=new M(re),this.conversation$=new M(t.conversation),this.channelTitleSubject=new M(t.channelTitle??null),this.promptSuggestionSubject=new M(null),this.sandboxPhaseSubject=new M("idle"),this.launchedSandboxesSubject=new M(ue(t.launchedSandboxes??[])),this.sandboxWakeSubject=new M({phase:"idle"}),this.derivedStores=ft(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(Dn)),this.sandboxWake$=this.sandboxWakeSubject.pipe(N((e,s)=>e.phase===s.phase)),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}getSandboxWake(){return this.sandboxWakeSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=ue(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 G(t);return e.subscribe(),e}static async open(t,e,s,r){const o=new G(t);try{return o.subscribe(),r?.(o),await o.openChannel(e,s),o}catch(i){throw o.close(),i}}static async reset(t,e,s,r,o="delete"){const{client:i,customChannelId:a}=t;if(o==="clear"){if(!i.clearChannel)throw new Error("This client cannot clear a channel: IAsgardServiceClient.clearChannel is not implemented. Implement it (POST {base}/channel/clear?custom_channel_id=…) or use AsgardServiceClient.");await i.clearChannel(a)}else{if(!i.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.");await i.deleteChannel(a)}return G.open(t,e,s,r)}static async restore(t,e,s){const r=new G(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(o){throw r.close(),o}}subscribe(){this.statesSubscription=Sn([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.promptSuggestion$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe(Q(([t,e,s,r,o,i,a,c,u])=>({isConnecting:t,conversation:e,tasks:s,subagents:r,channelTitle:o,promptSuggestion:i,sandboxPhase:a,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 h.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case h.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case h.INIT:case h.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===h.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(r.fact.channelTitleUpdate.title),r.eventType===h.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(r.fact.promptSuggestion.suggestion):r.eventType===h.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(r.eventType),r.eventType===h.SANDBOX_LAUNCH&&this.noteSandboxLaunch(r.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&r.traceId){const o=new Map(this.conversation$.value.messages),i=o.get(this.currentUserMessageId);i&&i.type==="user"&&(o.set(this.currentUserMessageId,{...i,traceId:r.traceId}),this.conversation$.next(new y({messages:o,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(re),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,o)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(s,r,o))})}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:B.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 z(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new J(r.processId));this.clearPromptSuggestion();const o=t.text.trim(),i=t.customMessageId??nt();return this.currentUserMessageId=i,this.lastSentMessageId=i,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:i,text:o,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:B.NONE,customChannelId:this.customChannelId,customMessageId:i,payload:this.resolvePayload(t?.payload),text:o,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:B.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(s),text:"",toolCallConsents:t},e).catch(o=>{throw r&&this.conversation$.next(this.conversation$.value.restorePendingConsent(r)),o})}nudge(t,e){return this.wakeInFlight&&!this.runStatusSubject.value.kind?this.wakeInFlight.then(()=>{}):this.sendNudge(t,e)}async wakeSandbox(t,e,s){return this.wakeInFlight?this.judgeWake(await this.wakeInFlight,t):this.isSandboxLive(t)?"live":this.runStatusSubject.value.kind||this.conversation$.value.pendingConsent?"blocked":(this.sendNudge(s,e,t).catch(()=>{}),this.judgeWake(await(this.wakeInFlight??Promise.resolve(!1)),t))}isSandboxLive(t){const e=this.launchedSandboxesSubject.value;return t?e.some(s=>s.sandboxName===t):e.length>0}judgeWake(t,e){return t&&this.isSandboxLive(e)?"live":"failed"}trackWake(t,e){this.sandboxWakeSubject.next({phase:"waking"});const s=(async()=>{try{return await t,await this.refetchMetadata(),!0}catch{return!1}})();this.wakeInFlight=s,s.then(r=>{this.wakeInFlight=void 0,!this.sandboxWakeSubject.closed&&this.sandboxWakeSubject.next({phase:this.judgeWake(r,e)==="live"?"idle":"failed"})})}sendNudge(t,e,s){const r=this.runStatusSubject.value.kind;if(r)return Promise.reject(new z(r));const o=this.conversation$.value.pendingConsent;if(o)return Promise.reject(new J(o.processId));const i=this.fetchSse("nudge",{action:B.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t);return this.trackWake(i,s),i}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(re),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.sandboxWakeSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}const pt={GOOD:"[Response Feedback: Good]",BAD:"[Response Feedback: Bad]"},Hn=8*1024;function Bn(n){return new TextEncoder().encode(n).length}function Gn(n,t){const e=pt[n],s=t?.trim()??"";return s?`${e}
5
5
 
6
6
  ${s}`:e}const Kn=["open-file","open-folder","download-file"];function qn(n){return Kn.includes(n)}function Wn(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(qn(s)){const o=r.get("absolute_path");return o?{kind:s,sandboxName:e,absolutePath:o}:null}return null}const le={Backspace:65288,Tab:65289,Enter:65293,Escape:65307,Delete:65535,Home:65360,ArrowLeft:65361,ArrowUp:65362,ArrowRight:65363,ArrowDown:65364,PageUp:65365,PageDown:65366,End:65367,Insert:65379,F1:65470,F2:65471,F3:65472,F4:65473,F5:65474,F6:65475,F7:65476,F8:65477,F9:65478,F10:65479,F11:65480,F12:65481,Shift:65505,Control:65507,CapsLock:65509,Alt:65513,Meta:65515,ContextMenu:65383," ":32},O={ISO_Level3_Shift:65027,Shift_L:65505,Mode_switch:65406,Control_L:65507,Meta_L:65511,Alt_L:65513,Alt_R:65514,Super_L:65515,Super_R:65516},gt=16777216;function be(n){const t=n.codePointAt(0)??0;return t>255?t|gt:t}function Xn(n){return n in le?le[n]:n.length===1?be(n):null}function Vn(n){return n>=32&&n<=126||n>=gt}function Yn(){if(typeof navigator>"u")return!1;const n=navigator.platform||"";return/(Mac|iPhone|iPod|iPad)/i.test(n)}function zn(n,t=Yn()){if(!t)return n;switch(n){case O.Meta_L:return O.Control_L;case O.Super_L:return O.Alt_L;case O.Super_R:return O.Super_L;case O.Alt_L:return O.Mode_switch;case O.Alt_R:return O.ISO_Level3_Shift;default:return n}}const Jn=19,de=10,Qn=100;function Zn(n){const t=n.deltaMode===0?1:Jn,e=s=>Math.max(-de,Math.min(de,-s*t))||0;return{x:e(n.deltaX),y:e(n.deltaY)}}function es(n){return n>=65&&n<=90}const ts=1e4,ns=8e3,ss=1,rs=7,os=new Set(["control/move"]);function mt(n){if(n.byteLength<rs)return null;const t=new DataView(n);return t.getUint8(0)!==ss?null:{x:t.getUint16(3),y:t.getUint16(5)}}function is(n){return{async connect(t,e){e.onStatus("connecting");const{wsUrl:s,token:r}=await n.createSession(t),o=s.includes("?")?"&":"?",i=new WebSocket(`${s}${o}token=${encodeURIComponent(r)}`);let a=null,c=null,u="none",l,v=!1,w=null;const p=[],g=(f,m)=>{i.readyState===WebSocket.OPEN&&(i.send(JSON.stringify({event:f,payload:m})),os.has(f)||e.onWire?.("send",f,m))},d=(f,m)=>{u==="me"&&g(f,m)},x=f=>{u!==f&&(u=f,e.onHostChange(f))};try{await new Promise((f,m)=>{const S=setTimeout(()=>m(new Error("Sandbox browser WebSocket connection timed out.")),ns);i.onopen=()=>{clearTimeout(S),f()},i.onerror=()=>{clearTimeout(S),m(new Error("Sandbox browser WebSocket failed to connect."))}})}catch(f){throw v=!0,i.close(),f}i.onclose=f=>{v||(e.onStatus("error",`Sandbox browser connection closed (code ${f.code}).`),e.onWire?.("recv","ws/close",{code:f.code}))};const k=async f=>{const m=new RTCPeerConnection({iceServers:f.iceservers??[]});a=m,m.onicecandidate=b=>{b.candidate&&g("signal/candidate",b.candidate.toJSON())},m.oniceconnectionstatechange=()=>{e.onWire?.("recv","ice/state",m.iceConnectionState),m.iceConnectionState==="failed"&&e.onStatus("error","ICE connection failed.")},m.ontrack=b=>{const[I]=b.streams;I&&w!==I.id&&(w=I.id,e.onStream(I),e.onStatus("live"))},m.ondatachannel=b=>{const I=b.channel;I.binaryType="arraybuffer",I.onmessage=U=>{if(!(U.data instanceof ArrayBuffer))return;const _=mt(U.data);_&&e.onRemoteCursor?.(_)}},await m.setRemoteDescription({type:"offer",sdp:f.sdp});for(const b of p.splice(0))await m.addIceCandidate(b).catch(()=>{});const S=await m.createAnswer();await m.setLocalDescription(S),g("signal/answer",{sdp:S.sdp,displayname:n.displayName??"asgard-js-sdk"})};return i.onmessage=f=>{let m;try{m=JSON.parse(String(f.data))}catch{return}const S=m.payload??{};switch(m.event!=="signal/candidate"&&e.onWire?.("recv",m.event,S),m.event){case"system/init":{c=S.session_id??null;const I=(S.control_host??void 0)?.id??void 0;I!==void 0&&x(I?I===c?"me":"agent":"none");return}case"control/host":{const b=S.host_id??null;x(b?b===c?"me":"agent":"none");return}case"clipboard/updated":{e.onClipboardChange?.(S.text??"");return}case"signal/provide":case"signal/offer":{k(S).catch(b=>{e.onStatus("error",b instanceof Error?b.message:String(b))});return}case"signal/candidate":{const b=S;a?.remoteDescription?a.addIceCandidate(b).catch(()=>{}):p.push(b);return}default:return}},g("signal/request",{video:{},audio:{}}),l=setInterval(()=>g("client/heartbeat",{}),ts),{requestControl(){g("control/request",{})},releaseControl(){d("control/release",{})},sendPointer(f){const m=Math.round(f.x),S=Math.round(f.y);if(f.type==="move"){d("control/move",{x:m,y:S});return}if(f.type==="scroll"){d("control/scroll",{delta_x:Math.round(f.deltaX??0),delta_y:Math.round(f.deltaY??0),control_key:!1});return}d(f.type==="down"?"control/buttondown":"control/buttonup",{x:m,y:S,code:f.button??1})},sendKey(f){if(f.type==="text"){for(const m of f.text??""){const S=be(m),b=es(S);b&&d("control/keydown",{keysym:O.Shift_L}),d("control/keydown",{keysym:S}),d("control/keyup",{keysym:S}),b&&d("control/keyup",{keysym:O.Shift_L})}return}typeof f.keysym=="number"&&d(f.type==="down"?"control/keydown":"control/keyup",{keysym:f.keysym})},setClipboard(f){d("clipboard/set",{text:f})},paste(f){d("control/paste",{text:f})},close(){v=!0,l&&clearInterval(l),l=void 0,a?.close(),a=null,i.close()}}}}}exports.AsgardServiceClient=An;exports.AsgardSourceSetClient=_n;exports.Channel=G;exports.ChannelAwaitingConsentError=J;exports.ChannelBusyError=z;exports.Conversation=y;exports.EventType=h;exports.FEEDBACK_COMMENT_MAX_BYTES=Hn;exports.FetchSseAction=B;exports.HttpError=C;exports.KEYSYM=le;exports.MessageTemplateType=he;exports.RESPONSE_FEEDBACK_PREFIX=pt;exports.SOURCE_SET_DEFAULT_MAX_ENTRIES=tt;exports.SOURCE_SET_MAX_PAGE_SIZE=me;exports.SOURCE_SET_VOLUME_ROOT=et;exports.ToolCallConsentResult=Pe;exports.WHEEL_MAX=de;exports.WHEEL_THROTTLE_MS=Qn;exports.XK=O;exports.assertVolumePath=P;exports.charToKeysym=be;exports.composeFeedbackMessage=Gn;exports.conversationToSubagentEvents=ct;exports.createDerivedStores=ft;exports.createSandboxBrowserTransport=is;exports.decodeCursorFrame=mt;exports.deriveSubagents=lt;exports.deriveTasks=ut;exports.feedbackCommentByteLength=Bn;exports.isAgentTool=ot;exports.isChannelAwaitingConsentError=vt;exports.isChannelBusyError=St;exports.isHttpError=bt;exports.isPrintableKeysym=Vn;exports.isSubagentChildTool=it;exports.isTaskTool=st;exports.keyToKeysym=Xn;exports.mapModifierKeysym=zn;exports.normalizeWheel=Zn;exports.reconcileLaunched=ue;exports.reduceSubagents=at;exports.reduceTaskEvents=rt;exports.resolveSandboxUri=Wn;exports.subagentsEqual=ht;exports.tasksEqual=dt;
7
7
  //# sourceMappingURL=index.cjs.map