@asgard-js/core 0.3.64 → 0.3.66

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
@@ -476,6 +476,68 @@ interface ChannelHomeDownloadResult {
476
476
  <a id="derived-state"></a>
477
477
  <br/>
478
478
 
479
+ ### AsgardSourceSetClient (SourceSet volume)
480
+
481
+ A **separate** client for the SourceSet volume HTTP API. It has nothing to do with
482
+ `AsgardServiceClient` — no inheritance, no shared instance, no channel. A volume is a plain remote
483
+ filesystem that is always there, so there is no lifecycle to coordinate with.
484
+
485
+ One instance serves every base, because the backend guarantees identical path segments after it:
486
+
487
+ | Endpoint | Auth |
488
+ | ---------------------------------------------- | ---------------------------------------------- |
489
+ | `{EDGE}/ns/{ns}/source-set/{name}/volume` | `apiKey` → sent as `X-API-KEY` |
490
+ | `{PLATFORM_API}/v1/source-set/{id}/volume` | `customHeaders: { Authorization: 'Bearer …' }` |
491
+ | `{PLATFORM_API}/v1/skill-set/{id}/volume` | same |
492
+ | `{HUB_API}/v1/directory/{directory_id}/volume` | same |
493
+
494
+ **Do not pass `apiKey` to a relay.** The volume key belongs to the relay, which holds it server-side;
495
+ putting it in a browser bundle hands it to everyone who loads the page.
496
+
497
+ ```ts
498
+ import { AsgardSourceSetClient } from '@asgard-js/core';
499
+
500
+ const fs = new AsgardSourceSetClient({
501
+ sourceSetEndpoint: 'https://api.example.com/v1/source-set/ss-1/volume',
502
+ customHeaders: { Authorization: `Bearer ${token}` },
503
+ });
504
+
505
+ const { entries, total, complete } = await fs.listAll(''); // '' is the volume root
506
+ await fs.write('notes/todo.md', '# Todo', { createOnly: true }); // 409 if it already exists
507
+ ```
508
+
509
+ #### Four contract differences from the sandbox fs API
510
+
511
+ Code copied from `sandboxFs*` compiles and then misbehaves. These are the reasons:
512
+
513
+ 1. **Paths are relative and the root is `''`**, not `/`. A leading or trailing slash, a doubled slash,
514
+ or a `.` / `..` segment is rejected before the request rather than becoming a 400.
515
+ 2. **Listing is paginated**, not truncation-flagged. `list()` returns one page; `listAll()` walks them.
516
+ 3. **`stat()` on a missing path resolves** with `exists: false` — the backend answers 200, so branching
517
+ on a thrown 404 never fires.
518
+ 4. **409 means conflict** — `createOnly` on a taken path, or `copy` / `move` onto an occupied
519
+ destination without `overwrite`. Detect it with `isHttpError(e) && e.status === 409`.
520
+
521
+ #### `listAll` tells you when it cannot vouch for a listing
522
+
523
+ ```ts
524
+ const { entries, total, complete } = await fs.listAll('docs');
525
+ ```
526
+
527
+ `complete` is `false` in three cases, and the caller is not meant to tell them apart — to a user they
528
+ all mean the same thing:
529
+
530
+ - the walk hit `maxEntries` (default `SOURCE_SET_DEFAULT_MAX_ENTRIES`, 10 000);
531
+ - the response carried no `paging` **and** a full page, so "is there more?" is unanswerable;
532
+ - a page came back indexed differently from the one requested, which makes every later page suspect.
533
+
534
+ `total` is the backend's own count, or `0` when it never gave one. So `!complete && total === 0` means
535
+ "short by an unknown amount" — surface that differently from a known shortfall rather than staying
536
+ quiet, which is the whole point.
537
+
538
+ **There is no watch.** A volume is served by several replicas, so a filesystem watch registered on one
539
+ cannot see another's writes, and the backend deliberately offers none. Re-list to pick up changes.
540
+
479
541
  ### Derived State (Task Check List / Subagent List)
480
542
 
481
543
  The Task Check List (F-010) and Subagent List (F-012) are pure folds over the conversation, exposed as **framework-agnostic** reactive slices so you can render them outside React — in Vue, Svelte, or vanilla JS. Each slice replays its current immutable snapshot and only emits when that slice actually changes (unrelated high-frequency message deltas are suppressed).
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class w extends Error{status;statusText;body;constructor(t,e,r){super(`HTTP ${t}: ${e}`),this.name="HttpError",this.status=t,this.statusText=e,this.body=r}}function at(n){return n instanceof w}class K 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 ct(n){return n instanceof K}class V 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 ut(n){return n instanceof V}var N=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(N||{}),l=(n=>(n.INIT="asgard.run.init",n.PROCESS="asgard.process",n.PROCESS_START="asgard.process.start",n.PROCESS_COMPLETE="asgard.process.complete",n.MESSAGE="asgard.message",n.MESSAGE_START="asgard.message.start",n.MESSAGE_DELTA="asgard.message.delta",n.MESSAGE_COMPLETE="asgard.message.complete",n.MESSAGE_USER="asgard.message.user",n.MESSAGE_THINKING_START="asgard.message.thinking.start",n.MESSAGE_THINKING_DELTA="asgard.message.thinking.delta",n.MESSAGE_THINKING_COMPLETE="asgard.message.thinking.complete",n.MESSAGE_CANVAS_START="asgard.message.canvas.start",n.MESSAGE_CANVAS_DELTA="asgard.message.canvas.delta",n.MESSAGE_CANVAS_COMPLETE="asgard.message.canvas.complete",n.TOOL_CALL="asgard.tool_call",n.TOOL_CALL_START="asgard.tool_call.start",n.TOOL_CALL_COMPLETE="asgard.tool_call.complete",n.TOOL_CALL_CONSENT="asgard.tool_call.consent",n.SUBAGENT_START="asgard.subagent.start",n.SUBAGENT_COMPLETE="asgard.subagent.complete",n.CHANNEL_TITLE_UPDATE="asgard.channel.title.update",n.PROMPT_SUGGESTION="asgard.prompt_suggestion",n.SANDBOX_LAUNCH="asgard.sandbox.launch",n.SANDBOX_READY="asgard.sandbox.ready",n.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(l||{}),Ie=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(Ie||{}),ie=(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))(ie||{});async function lt(n,t){const e=n.getReader();let r;for(;!(r=await e.read()).done;)t(r.value)}function dt(n){let t,e,r,s=!1;return function(i){t===void 0?(t=i,e=0,r=-1):t=ft(t,i);const a=t.length;let c=0;for(;e<a;){s&&(t[e]===10&&(c=++e),s=!1);let u=-1;for(;e<a&&u===-1;++e)switch(t[e]){case 58:r===-1&&(r=e-c);break;case 13:s=!0;case 10:u=e;break}if(u===-1)break;n(t.subarray(c,u),r),c=e,r=-1}c===a?t=void 0:c!==0&&(t=t.subarray(c),e-=c)}}function ht(n,t,e){let r=de();const s=new TextDecoder;return function(i,a){if(i.length===0)e?.(r),r=de();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===32?2:1),h=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
2
- `+h:h;break;case"event":r.event=h;break;case"id":n(r.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||t(r.retry=g);break}}}}function ft(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function de(){return{data:"",event:"",id:"",retry:void 0}}var pt=function(n,t){var e={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&t.indexOf(r)<0&&(e[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(n,r[s])&&(e[r[s]]=n[r[s]]);return e};const te="text/event-stream",mt=1e3,he="last-event-id";function Te(n,t){var{signal:e,headers:r,onopen:s,onmessage:o,onclose:i,onerror:a,openWhenHidden:c,fetch:u}=t,h=pt(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,v)=>{const d=Object.assign({},r);d.accept||(d.accept=te);let p;function f(){p.abort(),document.hidden||z()}c||document.addEventListener("visibilitychange",f);let _=mt,E=0;function L(){document.removeEventListener("visibilitychange",f),window.clearTimeout(E),p.abort()}e?.addEventListener("abort",()=>{L(),g()});const ot=u??window.fetch,it=s??gt;async function z(){var J;p=new AbortController;try{const G=await ot(n,Object.assign(Object.assign({},h),{headers:d,signal:p.signal}));await it(G),await lt(G.body,dt(ht(x=>{x?d[he]=x:delete d[he]},x=>{_=x},o))),i?.(),L(),g()}catch(G){if(!p.signal.aborted)try{const x=(J=a?.(G))!==null&&J!==void 0?J:_;window.clearTimeout(E),E=window.setTimeout(z,x)}catch(x){L(),v(x)}}}z()})}function gt(n){const t=n.headers.get("content-type");if(!t?.startsWith(te))throw new Error(`Expected content-type to be ${te}, Actual: ${t}`)}var ne=function(n,t){return ne=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,r){e.__proto__=r}||function(e,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])},ne(n,t)};function C(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");ne(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function bt(n,t,e,r){function s(o){return o instanceof e?o:new e(function(i){i(o)})}return new(e||(e=Promise))(function(o,i){function a(h){try{u(r.next(h))}catch(g){i(g)}}function c(h){try{u(r.throw(h))}catch(g){i(g)}}function u(h){h.done?o(h.value):s(h.value).then(a,c)}u((r=r.apply(n,t||[])).next())})}function Ce(n,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,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(h){return c([u,h])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(e=0)),e;)try{if(r=1,s&&(o=u[0]&2?s.return:u[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,u[1])).done)return o;switch(s=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++,s=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(h){u=[6,h],s=0}finally{r=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function R(n){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&n[t],r=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function H(n,t){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var r=e.call(n),s,o=[],i;try{for(;(t===void 0||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(e=r.return)&&e.call(r)}finally{if(i)throw i.error}}return o}function F(n,t,e){if(e||arguments.length===2)for(var r=0,s=t.length,o;r<s;r++)(o||!(r in t))&&(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return n.concat(o||Array.prototype.slice.call(t))}function k(n){return this instanceof k?(this.v=n,this):new k(n)}function vt(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=e.apply(n,t||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),s[Symbol.asyncIterator]=function(){return this},s;function i(d){return function(p){return Promise.resolve(p).then(d,g)}}function a(d,p){r[d]&&(s[d]=function(f){return new Promise(function(_,E){o.push([d,f,_,E])>1||c(d,f)})},p&&(s[d]=p(s[d])))}function c(d,p){try{u(r[d](p))}catch(f){v(o[0][3],f)}}function u(d){d.value instanceof k?Promise.resolve(d.value.v).then(h,g):v(o[0][2],d)}function h(d){c("next",d)}function g(d){c("throw",d)}function v(d,p){d(p),o.shift(),o.length&&c(o[0][0],o[0][1])}}function St(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=n[Symbol.asyncIterator],e;return t?t.call(n):(n=typeof R=="function"?R(n):n[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(o){e[o]=n[o]&&function(i){return new Promise(function(a,c){i=n[o](i),s(a,c,i.done,i.value)})}}function s(o,i,a,c){Promise.resolve(c).then(function(u){o({value:u,done:a})},i)}}function b(n){return typeof n=="function"}function xe(n){var t=function(r){Error.call(r),r.stack=new Error().stack},e=n(t);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var Q=xe(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
3
- `+e.map(function(r,s){return s+1+") "+r.toString()}).join(`
4
- `):"",this.name="UnsubscriptionError",this.errors=e}});function Y(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var $=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,r,s,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=R(i),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(f){t={error:f}}finally{try{c&&!c.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else i.remove(this);var h=this.initialTeardown;if(b(h))try{h()}catch(f){o=f instanceof Q?f.errors:[f]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var v=R(g),d=v.next();!d.done;d=v.next()){var p=d.value;try{fe(p)}catch(f){o=o??[],f instanceof Q?o=F(F([],H(o)),H(f.errors)):o.push(f)}}}catch(f){r={error:f}}finally{try{d&&!d.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}}if(o)throw new Q(o)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)fe(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)&&Y(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&Y(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),Ae=$.EMPTY;function Oe(n){return n instanceof $||n&&"closed"in n&&b(n.remove)&&b(n.add)&&b(n.unsubscribe)}function fe(n){b(n)?n():n.unsubscribe()}var yt={Promise:void 0},wt={setTimeout:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setTimeout.apply(void 0,F([n,t],H(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Pe(n){wt.setTimeout(function(){throw n})}function re(){}function q(n){n()}var ae=(function(n){C(t,n);function t(e){var r=n.call(this)||this;return r.isStopped=!1,e?(r.destination=e,Oe(e)&&e.add(r)):r.destination=Tt,r}return t.create=function(e,r,s){return new se(e,r,s)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})($),Et=(function(){function n(t){this.partialObserver=t}return n.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(r){B(r)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(r){B(r)}else B(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){B(e)}},n})(),se=(function(n){C(t,n);function t(e,r,s){var o=n.call(this)||this,i;return b(e)||!e?i={next:e??void 0,error:r??void 0,complete:s??void 0}:i=e,o.destination=new Et(i),o}return t})(ae);function B(n){Pe(n)}function It(n){throw n}var Tt={closed:!0,next:re,error:It,complete:re},ce=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function X(n){return n}function Ct(n){return n.length===0?X:n.length===1?n[0]:function(e){return n.reduce(function(r,s){return s(r)},e)}}var y=(function(){function n(t){t&&(this._subscribe=t)}return n.prototype.lift=function(t){var e=new n;return e.source=this,e.operator=t,e},n.prototype.subscribe=function(t,e,r){var s=this,o=At(t)?t:new se(t,e,r);return q(function(){var i=s,a=i.operator,c=i.source;o.add(a?a.call(o,c):c?s._subscribe(o):s._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 r=this;return e=pe(e),new e(function(s,o){var i=new se({next:function(a){try{t(a)}catch(c){o(c),i.unsubscribe()}},error:o,complete:s});r.subscribe(i)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[ce]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Ct(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=pe(t),new t(function(r,s){var o;e.subscribe(function(i){return o=i},function(i){return s(i)},function(){return r(o)})})},n.create=function(t){return new n(t)},n})();function pe(n){var t;return(t=n??yt.Promise)!==null&&t!==void 0?t:Promise}function xt(n){return n&&b(n.next)&&b(n.error)&&b(n.complete)}function At(n){return n&&n instanceof ae||xt(n)&&Oe(n)}function Ot(n){return b(n?.lift)}function P(n){return function(t){if(Ot(t))return t.lift(function(e){try{return n(e,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function O(n,t,e,r,s){return new Pt(n,t,e,r,s)}var Pt=(function(n){C(t,n);function t(e,r,s,o,i,a){var c=n.call(this,e)||this;return c.onFinalize=i,c.shouldUnsubscribe=a,c._next=r?function(u){try{r(u)}catch(h){e.error(h)}}:n.prototype._next,c._error=o?function(u){try{o(u)}catch(h){e.error(h)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=s?function(){try{s()}catch(u){e.error(u)}finally{this.unsubscribe()}}:n.prototype._complete,c}return t.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ae),_t=xe(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ue=(function(n){C(t,n);function t(){var e=n.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return t.prototype.lift=function(e){var r=new me(this,this);return r.operator=e,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new _t},t.prototype.next=function(e){var r=this;q(function(){var s,o;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=R(r.currentObservers),a=i.next();!a.done;a=i.next()){var c=a.value;c.next(e)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(s)throw s.error}}}})},t.prototype.error=function(e){var r=this;q(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=e;for(var s=r.observers;s.length;)s.shift().error(e)}})},t.prototype.complete=function(){var e=this;q(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var r=e.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(e){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,e)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var r=this,s=this,o=s.hasError,i=s.isStopped,a=s.observers;return o||i?Ae:(this.currentObservers=null,a.push(e),new $(function(){r.currentObservers=null,Y(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var r=this,s=r.hasError,o=r.thrownError,i=r.isStopped;s?e.error(o):i&&e.complete()},t.prototype.asObservable=function(){var e=new y;return e.source=this,e},t.create=function(e,r){return new me(e,r)},t})(y),me=(function(n){C(t,n);function t(e,r){var s=n.call(this)||this;return s.destination=e,s.source=r,s}return t.prototype.next=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,e)},t.prototype.error=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,e)},t.prototype.complete=function(){var e,r;(r=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||r===void 0||r.call(e)},t.prototype._subscribe=function(e){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(e))!==null&&s!==void 0?s:Ae},t})(ue),T=(function(n){C(t,n);function t(e){var r=n.call(this)||this;return r._value=e,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var r=n.prototype._subscribe.call(this,e);return!r.closed&&e.next(this._value),r},t.prototype.getValue=function(){var e=this,r=e.hasError,s=e.thrownError,o=e._value;if(r)throw s;return this._throwIfClosed(),o},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(ue),Lt={now:function(){return Date.now()}},Mt=(function(n){C(t,n);function t(e,r){return n.call(this)||this}return t.prototype.schedule=function(e,r){return this},t})($),ge={setInterval:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setInterval.apply(void 0,F([n,t],H(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Ut=(function(n){C(t,n);function t(e,r){var s=n.call(this,e,r)||this;return s.scheduler=e,s.work=r,s.pending=!1,s}return t.prototype.schedule=function(e,r){var s;if(r===void 0&&(r=0),this.closed)return this;this.state=e;var o=this.id,i=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(i,o,r)),this.pending=!0,this.delay=r,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(i,this.id,r),this},t.prototype.requestAsyncId=function(e,r,s){return s===void 0&&(s=0),ge.setInterval(e.flush.bind(e,this),s)},t.prototype.recycleAsyncId=function(e,r,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return r;r!=null&&ge.clearInterval(r)},t.prototype.execute=function(e,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(e,r);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,r){var s=!1,o;try{this.work(e)}catch(i){s=!0,o=i||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,r=e.id,s=e.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Y(o,this),r!=null&&(this.id=this.recycleAsyncId(s,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Mt),be=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,r){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(r,e)},n.now=Lt.now,n})(),Nt=(function(n){C(t,n);function t(e,r){r===void 0&&(r=be.now);var s=n.call(this,e,r)||this;return s.actions=[],s._active=!1,s}return t.prototype.flush=function(e){var r=this.actions;if(this._active){r.push(e);return}var s;this._active=!0;do if(s=e.execute(e.state,e.delay))break;while(e=r.shift());if(this._active=!1,s){for(;e=r.shift();)e.unsubscribe();throw s}},t})(be),_e=new Nt(Ut),kt=_e,Rt=new y(function(n){return n.complete()});function Le(n){return n&&b(n.schedule)}function Me(n){return n[n.length-1]}function jt(n){return b(Me(n))?n.pop():void 0}function Ue(n){return Le(Me(n))?n.pop():void 0}var Ne=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function ke(n){return b(n?.then)}function Re(n){return b(n[ce])}function je(n){return Symbol.asyncIterator&&b(n?.[Symbol.asyncIterator])}function $e(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 $t(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var De=$t();function He(n){return b(n?.[De])}function Fe(n){return vt(this,arguments,function(){var e,r,s,o;return Ce(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 r=i.sent(),s=r.value,o=r.done,o?[4,k(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,k(s)];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 Ge(n){return b(n?.getReader)}function U(n){if(n instanceof y)return n;if(n!=null){if(Re(n))return Dt(n);if(Ne(n))return Ht(n);if(ke(n))return Ft(n);if(je(n))return Be(n);if(He(n))return Gt(n);if(Ge(n))return Bt(n)}throw $e(n)}function Dt(n){return new y(function(t){var e=n[ce]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ht(n){return new y(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Ft(n){return new y(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Pe)})}function Gt(n){return new y(function(t){var e,r;try{for(var s=R(n),o=s.next();!o.done;o=s.next()){var i=o.value;if(t.next(i),t.closed)return}}catch(a){e={error:a}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}t.complete()})}function Be(n){return new y(function(t){qt(n,t).catch(function(e){return t.error(e)})})}function Bt(n){return Be(Fe(n))}function qt(n,t){var e,r,s,o;return bt(this,void 0,void 0,function(){var i,a;return Ce(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=St(n),c.label=1;case 1:return[4,e.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(i=r.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(),s={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.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(s)throw s.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function A(n,t,e,r,s){r===void 0&&(r=0),s===void 0&&(s=!1);var o=t.schedule(function(){e(),s?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(o),!s)return o}function qe(n,t){return t===void 0&&(t=0),P(function(e,r){e.subscribe(O(r,function(s){return A(r,n,function(){return r.next(s)},t)},function(){return A(r,n,function(){return r.complete()},t)},function(s){return A(r,n,function(){return r.error(s)},t)}))})}function Ke(n,t){return t===void 0&&(t=0),P(function(e,r){r.add(n.schedule(function(){return e.subscribe(r)},t))})}function Kt(n,t){return U(n).pipe(Ke(t),qe(t))}function Vt(n,t){return U(n).pipe(Ke(t),qe(t))}function Yt(n,t){return new y(function(e){var r=0;return t.schedule(function(){r===n.length?e.complete():(e.next(n[r++]),e.closed||this.schedule())})})}function Wt(n,t){return new y(function(e){var r;return A(e,t,function(){r=n[De](),A(e,t,function(){var s,o,i;try{s=r.next(),o=s.value,i=s.done}catch(a){e.error(a);return}i?e.complete():e.next(o)},0,!0)}),function(){return b(r?.return)&&r.return()}})}function Ve(n,t){if(!n)throw new Error("Iterable cannot be null");return new y(function(e){A(e,t,function(){var r=n[Symbol.asyncIterator]();A(e,t,function(){r.next().then(function(s){s.done?e.complete():e.next(s.value)})},0,!0)})})}function Xt(n,t){return Ve(Fe(n),t)}function zt(n,t){if(n!=null){if(Re(n))return Kt(n,t);if(Ne(n))return Yt(n,t);if(ke(n))return Vt(n,t);if(je(n))return Ve(n,t);if(He(n))return Wt(n,t);if(Ge(n))return Xt(n,t)}throw $e(n)}function le(n,t){return t?zt(n,t):U(n)}function Jt(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ue(n);return le(n,e)}function Qt(n){return n instanceof Date&&!isNaN(n)}function j(n,t){return P(function(e,r){var s=0;e.subscribe(O(r,function(o){r.next(n.call(t,o,s++))}))})}var Zt=Array.isArray;function en(n,t){return Zt(t)?n.apply(void 0,F([],H(t))):n(t)}function tn(n){return j(function(t){return en(n,t)})}var nn=Array.isArray,rn=Object.getPrototypeOf,sn=Object.prototype,on=Object.keys;function an(n){if(n.length===1){var t=n[0];if(nn(t))return{args:t,keys:null};if(cn(t)){var e=on(t);return{args:e.map(function(r){return t[r]}),keys:e}}}return{args:n,keys:null}}function cn(n){return n&&typeof n=="object"&&rn(n)===sn}function un(n,t){return n.reduce(function(e,r,s){return e[r]=t[s],e},{})}function ln(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ue(n),r=jt(n),s=an(n),o=s.args,i=s.keys;if(o.length===0)return le([],e);var a=new y(dn(o,e,i?function(c){return un(i,c)}:X));return r?a.pipe(tn(r)):a}function dn(n,t,e){return e===void 0&&(e=X),function(r){ve(t,function(){for(var s=n.length,o=new Array(s),i=s,a=s,c=function(h){ve(t,function(){var g=le(n[h],t),v=!1;g.subscribe(O(r,function(d){o[h]=d,v||(v=!0,a--),a||r.next(e(o.slice()))},function(){--i||r.complete()}))},r)},u=0;u<s;u++)c(u)},r)}}function ve(n,t,e){n?A(e,n,t):t()}function hn(n,t,e,r,s,o,i,a){var c=[],u=0,h=0,g=!1,v=function(){g&&!c.length&&!u&&t.complete()},d=function(f){return u<r?p(f):c.push(f)},p=function(f){u++;var _=!1;U(e(f,h++)).subscribe(O(t,function(E){t.next(E)},function(){_=!0},void 0,function(){if(_)try{u--;for(var E=function(){var L=c.shift();i||p(L)};c.length&&u<r;)E();v()}catch(L){t.error(L)}}))};return n.subscribe(O(t,d,function(){g=!0,v()})),function(){}}function W(n,t,e){return e===void 0&&(e=1/0),b(t)?W(function(r,s){return j(function(o,i){return t(r,o,s,i)})(U(n(r,s)))},e):(typeof t=="number"&&(e=t),P(function(r,s){return hn(r,s,n,e)}))}function fn(n,t,e){n===void 0&&(n=0),e===void 0&&(e=kt);var r=-1;return t!=null&&(Le(t)?e=t:r=t),new y(function(s){var o=Qt(n)?+n-e.now():n;o<0&&(o=0);var i=0;return e.schedule(function(){s.closed||(s.next(i++),0<=r?this.schedule(void 0,r):s.complete())},o)})}function pn(n,t){return b(t)?W(n,t,1):W(n,1)}function mn(n){return n<=0?function(){return Rt}:P(function(t,e){var r=0;t.subscribe(O(e,function(s){++r<=n&&(e.next(s),n<=r&&e.complete())}))})}function gn(n){return j(function(){return n})}function bn(n,t){return W(function(e,r){return U(n(e,r)).pipe(mn(1),gn(e))})}function vn(n,t){t===void 0&&(t=_e);var e=fn(n,t);return bn(function(){return e})}function M(n,t){return t===void 0&&(t=X),n=n??Sn,P(function(e,r){var s,o=!0;e.subscribe(O(r,function(i){var a=t(i);(o||!n(s,a))&&(o=!1,s=a,r.next(i))}))})}function Sn(n,t){return n===t}function yn(n){return P(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function wn(n){return P(function(t,e){U(n).subscribe(O(e,function(){return e.complete()},re)),!e.closed&&t.subscribe(e)})}function Se(n){const{endpoint:t,apiKey:e,payload:r,debugMode:s,customHeaders:o}=n,i=n.method??"POST";return new y(a=>{const c=new AbortController;let u,h=!1,g=!1;const v={"Content-Type":"application/json",...o};e&&(v["X-API-KEY"]=e);const d=new URL(t);return s&&d.searchParams.set("is_debug","true"),Te(d.toString(),{method:i,headers:v,body:i==="POST"&&r?JSON.stringify(r):void 0,signal:c.signal,openWhenHidden:!0,onopen:async p=>{if(p.ok)u=p.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await p.json()}catch{try{f=await p.text()}catch{f=null}}a.error(new w(p.status,p.statusText,f)),c.abort()}},onmessage:p=>{p.id&&(h=!0);const f=JSON.parse(p.data);u?f.traceId=u:f.requestId&&(f.traceId=f.requestId,u||(u=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:p=>{if(g)throw p;if(!h)throw a.error(p),c.abort(),p}}),()=>{g=!0,c.abort()}})}class En{listeners={};on(t,e){this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).concat(e)})}off(t,e){this.listeners[t]&&(this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).filter(r=>r!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(r=>r(...e))}}class In{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new ue;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new En;transformSsePayload;customHeaders;constructor(t){if(!t.endpoint&&!t.botProviderEndpoint)throw new Error("Either endpoint or botProviderEndpoint must be provided");if(this.apiKey=t.apiKey,this.debugMode=t.debugMode,this.transformSsePayload=t.transformSsePayload,this.botProviderEndpoint=t.botProviderEndpoint,this.customHeaders={...t.customHeaders,...t.userIdentityHint?{"X-ASGARD-USER-IDENTITY-HINT":t.userIdentityHint}:{}},!t.endpoint&&t.botProviderEndpoint){const e=t.botProviderEndpoint.replace(/\/+$/,"");this.endpoint=`${e}/message/sse`}else t.endpoint&&(this.endpoint=t.endpoint,this.debugMode&&console.warn('[AsgardServiceClient] The "endpoint" option is deprecated and will be removed in the next major version. Please use "botProviderEndpoint" instead. The SSE endpoint will be automatically derived as "${botProviderEndpoint}/message/sse".'))}on(t,e){this.sseEmitter.remove(t),this.sseEmitter.on(t,e)}handleEvent(t){switch(t.eventType){case l.INIT:this.sseEmitter.emit(l.INIT,t);break;case l.PROCESS_START:case l.PROCESS_COMPLETE:this.sseEmitter.emit(l.PROCESS,t);break;case l.MESSAGE_START:case l.MESSAGE_DELTA:case l.MESSAGE_COMPLETE:this.sseEmitter.emit(l.MESSAGE,t);break;case l.TOOL_CALL_START:case l.TOOL_CALL_COMPLETE:this.sseEmitter.emit(l.TOOL_CALL,t);break;case l.TOOL_CALL_CONSENT:this.sseEmitter.emit(l.TOOL_CALL_CONSENT,t);break;case l.DONE:this.sseEmitter.emit(l.DONE,t);break;case l.ERROR:this.sseEmitter.emit(l.ERROR,t);break}}fetchSse(t,e){return e?.onSseStart?.(),this.inFlight+=1,this.runSse(Se({apiKey:this.apiKey,endpoint:this.endpoint,debugMode:this.debugMode,payload:this.transformSsePayload?.(t)??t,customHeaders:this.customHeaders}),e)}rejoinSse(t,e){e?.onSseStart?.(),this.inFlight+=1;const r=new URL(this.endpoint);return r.searchParams.set("custom_channel_id",t),this.runSse(Se({apiKey:this.apiKey,endpoint:r.toString(),debugMode:this.debugMode,method:"GET",customHeaders:this.customHeaders}),e)}deriveChannelMetadataEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel/metadata`:null}async channelMetadata(t){const e=this.deriveChannelMetadataEndpoint();if(!e)throw new Error("Unable to derive channel metadata endpoint. Please provide botProviderEndpoint in config.");const r=new URL(e);r.searchParams.set("custom_channel_id",t);const s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const o=await fetch(r.toString(),{method:"GET",headers:s});if(o.status===404)return null;if(!o.ok)throw new w(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 r=this.deriveSuspendEndpoint();if(!r)throw new Error("Unable to derive channel suspend endpoint. Please provide botProviderEndpoint in config.");const s=new URL(r);s.searchParams.set("custom_channel_id",t),e?.requestId&&s.searchParams.set("request_id",e.requestId),e?.force&&s.searchParams.set("force","true");const o=await fetch(s.toString(),{method:"POST",headers:this.apiHeaders()});if(!(o.ok||o.status===404))throw new w(o.status,o.statusText,await o.text().catch(()=>{}))}runSse(t,e){return t.pipe(pn(r=>Jt(r).pipe(vn(e?.delayTime??50))),wn(this.destroy$),yn(()=>this.onRunSettled())).subscribe({next:r=>{this.detached||(e?.onSseMessage?.(r),this.handleEvent(r))},error:r=>{this.detached||e?.onSseError?.(r)},complete:()=>{this.detached||e?.onSseCompleted?.()}})}detach(t){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),t.timeoutMs)}}onRunSettled(){this.inFlight=Math.max(0,this.inFlight-1),this.detached&&this.inFlight===0&&this.close()}close(){this.closed||(this.closed=!0,this.detachTimer&&(clearTimeout(this.detachTimer),this.detachTimer=void 0),this.destroy$.next(),this.destroy$.complete())}async uploadFile(t,e){const r=this.deriveBlobEndpoint();if(!r)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const s=new FormData;s.append("file",t),s.append("customChannelId",e);const o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const i=await fetch(r,{method:"POST",headers:o,body:s});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 r=this.getBaseEndpoint();if(!r)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const s=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,o=`${r}/channel-home/download?${s}`,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){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox browser open-url endpoint. Please provide botProviderEndpoint in config.");const r=`${e}/sandbox/${encodeURIComponent(t)}/browser/open-url`,s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const o=await fetch(r,{method:"POST",headers:s});if(!o.ok)throw new w(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}deriveSandboxFsEndpoint(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox fs endpoint. Please provide botProviderEndpoint in config.");return`${e}/sandbox/${encodeURIComponent(t)}/fs`}apiHeaders(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async sandboxFsList(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/list`);r.searchParams.set("path",e);const s=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!s.ok)throw new w(s.status,s.statusText,await s.text().catch(()=>{}));const o=await s.json(),i=o.data??o;return{entries:i.entries??[],truncated:i.truncated??!1}}async sandboxFsRead(t,e,r){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);s.searchParams.set("path",e),r?.offsetBytes!=null&&s.searchParams.set("offset_bytes",String(r.offsetBytes)),r?.limitBytes!=null&&s.searchParams.set("limit_bytes",String(r.limitBytes));const o=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new w(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.blob(),a=o.headers.get("X-Total-Bytes");return{content:i,totalBytes:a!=null?Number(a):i.size,truncated:o.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,r,s){const o=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);o.searchParams.set("path",e),s?.mode!=null&&o.searchParams.set("mode",String(s.mode)),s?.createOnly&&o.searchParams.set("create_only","true");const i=new FormData;i.append("file",r instanceof Blob?r:new Blob([r]));const a=await fetch(o.toString(),{method:"PUT",headers:this.apiHeaders(),body:i});if(!a.ok)throw new w(a.status,a.statusText,await a.text().catch(()=>{}));const c=await a.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,r,s){const o=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(s).forEach(([a,c])=>o.searchParams.set(a,c));const i=await fetch(o.toString(),{method:r,headers:this.apiHeaders()});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));return i.json().catch(()=>null)}async sandboxFsStat(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/stat`);r.searchParams.set("path",e);const s=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!s.ok)throw new w(s.status,s.statusText,await s.text().catch(()=>{}));const o=await s.json(),i=o.data??o;return{exists:i.exists??!1,isDir:i.isDir??!1,sizeBytes:i.sizeBytes??0,mtimeUnix:i.mtimeUnix??0,mode:i.mode??0,etag:i.etag}}async sandboxFsMkdir(t,e){await this.sandboxFsRequest(t,"mkdir","POST",{path:e})}async sandboxFsRemove(t,e){await this.sandboxFsRequest(t,"item","DELETE",{path:e})}async sandboxFsRemoveAll(t,e){await this.sandboxFsRequest(t,"all","DELETE",{path:e})}async sandboxFsCopy(t,e,r,s){const o={src:e,dst:r};s?.overwrite&&(o.overwrite="true");const i=await this.sandboxFsRequest(t,"copy","POST",o);return{bytesCopied:(i?.data??i)?.bytesCopied??0}}async sandboxFsMove(t,e,r,s){const o={src:e,dst:r};s?.overwrite&&(o.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",o)}sandboxFsWatch(t,e){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/watch`);return r.searchParams.set("path",e),new y(s=>{const o=new AbortController;return Te(r.toString(),{headers:this.apiHeaders(),signal:o.signal,openWhenHidden:!0,onopen:async i=>{if(!i.ok){const a=await i.text().catch(()=>{});s.error(new w(i.status,i.statusText,a)),o.abort()}},onmessage:i=>{i.event==="change"&&s.next(JSON.parse(i.data))},onclose:()=>s.complete(),onerror:i=>{throw s.error(i),o.abort(),i}}),()=>o.abort()})}deriveBlobEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/blob`:null}getBaseEndpoint(){let t=this.botProviderEndpoint;return!t&&this.endpoint&&(t=this.endpoint.replace("/message/sse","")),t?t.replace(/\/+$/,""):null}}const S=[];for(let n=0;n<256;++n)S.push((n+256).toString(16).slice(1));function Tn(n,t=0){return(S[n[t+0]]+S[n[t+1]]+S[n[t+2]]+S[n[t+3]]+"-"+S[n[t+4]]+S[n[t+5]]+"-"+S[n[t+6]]+S[n[t+7]]+"-"+S[n[t+8]]+S[n[t+9]]+"-"+S[n[t+10]]+S[n[t+11]]+S[n[t+12]]+S[n[t+13]]+S[n[t+14]]+S[n[t+15]]).toLowerCase()}let Z;const Cn=new Uint8Array(16);function xn(){if(!Z){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Z=crypto.getRandomValues.bind(crypto)}return Z(Cn)}const An=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ye={randomUUID:An};function On(n,t,e){n=n||{};const r=n.random??n.rng?.()??xn();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Tn(r)}function Ye(n,t,e){return ye.randomUUID&&!n?ye.randomUUID():On(n)}class m{messages=null;pendingConsent=null;constructor({messages:t,pendingConsent:e=null}){this.messages=t,this.pendingConsent=e??null}pushMessage(t){const e=new Map(this.messages);return e.set(t.messageId,t),new m({messages:e,pendingConsent:this.pendingConsent})}clearPendingConsent(){return this.pendingConsent?new m({messages:this.messages,pendingConsent:null}):this}restorePendingConsent(t){return this.pendingConsent?this:new m({messages:this.messages,pendingConsent:t})}settleInFlightMessages(){if(!this.messages)return this;let t=!1;const e=new Map(this.messages);for(const[r,s]of e)s.type==="tool-call"&&!s.isComplete&&(e.set(r,{...s,isComplete:!0,isCancelled:!0}),t=!0),s.type==="thinking"&&s.isThinking&&(e.set(r,{...s,isThinking:!1}),t=!0);return t?new m({messages:e,pendingConsent:this.pendingConsent}):this}cancelInFlightToolCalls(){return this.settleInFlightMessages()}onMessage(t){switch(t.eventType){case l.MESSAGE_START:return this.onMessageStart(t);case l.MESSAGE_DELTA:return this.onMessageDelta(t);case l.MESSAGE_COMPLETE:return this.onMessageComplete(t);case l.MESSAGE_USER:return this.onMessageUser(t);case l.MESSAGE_THINKING_START:return this.onThinkingStart(t);case l.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case l.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case l.MESSAGE_CANVAS_START:return this.onCanvasStart(t);case l.MESSAGE_CANVAS_DELTA:return this.onCanvasDelta(t);case l.MESSAGE_CANVAS_COMPLETE:return this.onCanvasComplete(t);case l.TOOL_CALL_START:return this.onToolCallStart(t);case l.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case l.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case l.SUBAGENT_START:return this.onSubagentStart(t);case l.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case l.ERROR:return this.onMessageError(t);default:return this}}isTerminalBot(t){return t?.type==="bot"&&!t.isTyping}isTerminalThinking(t){return t?.type==="thinking"&&!t.isThinking}isTerminalToolCall(t){return t?.type==="tool-call"&&t.isComplete===!0}isTerminalCanvas(t){return t?.type==="canvas"&&!t.isDrawing}onMessageStart(t){const e=t.fact.messageStart.message;if(e.parentToolUseId)return this;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages);return r.set(e.messageId,{type:"bot",eventType:l.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new m({messages:r,pendingConsent:this.pendingConsent})}onMessageDelta(t){const e=t.fact.messageDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalBot(r))return this;const s=r?.type==="bot"?r:void 0,o=new Map(this.messages);return o.set(e.messageId,{type:"bot",eventType:l.MESSAGE_DELTA,isTyping:!0,typingText:`${s?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??s?.traceId,raw:s?.raw??""}),new m({messages:o,pendingConsent:this.pendingConsent})}onMessageComplete(t){const e=t.fact.messageComplete.message;if(e.parentToolUseId)return this;const r=new Map(this.messages),s=r.get(e.messageId);return r.set(e.messageId,{type:"bot",eventType:l.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??(s?.type==="bot"?s.traceId:void 0),raw:JSON.stringify(t)}),new m({messages:r,pendingConsent:this.pendingConsent})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(e.parentToolUseId)return this;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages),s={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return r.set(e.messageId,s),new m({messages:r,pendingConsent:this.pendingConsent})}onThinkingDelta(t){const e=t.fact.messageThinkingDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalThinking(r))return this;const s=r?.type==="thinking"?r:void 0,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:`${s?.text??""}${e.text}`,isThinking:!0,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return o.set(e.messageId,i),new m({messages:o,pendingConsent:this.pendingConsent})}onThinkingComplete(t){const e=t.fact.messageThinkingComplete.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId),s=r?.type==="thinking"?r:void 0,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return o.set(e.messageId,i),new m({messages:o,pendingConsent:this.pendingConsent})}onCanvasStart(t){const e=t.fact.messageCanvasStart.message;if(e.parentToolUseId)return this;if(this.isTerminalCanvas(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages),s={type:"canvas",messageId:e.messageId,html:"",isDrawing:!0,time:new Date,traceId:t.traceId};return r.set(e.messageId,s),new m({messages:r,pendingConsent:this.pendingConsent})}onCanvasDelta(t){const e=t.fact.messageCanvasDelta.message;if(e.parentToolUseId)return this;const r=this.messages?.get(e.messageId);if(this.isTerminalCanvas(r))return this;const s=r?.type==="canvas"?r:void 0,o=new Map(this.messages),i={type:"canvas",messageId:e.messageId,html:`${s?.html??""}${e.text}`,title:s?.title,isDrawing:!0,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return o.set(e.messageId,i),new m({messages:o,pendingConsent:this.pendingConsent})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const r=e.template?.type===ie.CANVAS?e.template:void 0,s=r?.canvas?.html;if(!s){if(!this.messages?.has(e.messageId))return this;const u=new Map(this.messages);return u.delete(e.messageId),new m({messages:u,pendingConsent:this.pendingConsent})}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:s,title:r?.title,isDrawing:!1,time:i?.time??new Date,traceId:t.traceId??i?.traceId};return a.set(e.messageId,c),new m({messages:a,pendingConsent:this.pendingConsent})}onMessageUser(t){const e=t.fact.messageUser;if((this.messages?.get(e.messageId)??(e.customMessageId?this.messages?.get(e.customMessageId):void 0))?.type==="user")return this;const s=new Map(this.messages),o={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return s.set(e.messageId,o),new m({messages:s,pendingConsent:this.pendingConsent})}onMessageError(t){const e=Ye(),r=t.fact.runError.error,s=new Map(this.messages);return s.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:r,time:new Date,traceId:t.traceId}),new m({messages:s,pendingConsent:this.pendingConsent})}onToolCallStart(t){const e=t.fact.toolCallStart,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`;if(this.isTerminalToolCall(this.messages?.get(s)))return this;const o={type:"tool-call",eventType:l.TOOL_CALL_START,messageId:s,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,isComplete:!1,time:new Date,traceId:t.traceId};return r.set(s,o),new m({messages:r,pendingConsent:this.pendingConsent})}onToolCallComplete(t){const e=t.fact.toolCallComplete,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,o=r.get(s);if(o?.type==="tool-call"){const i={...o,eventType:l.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??o.traceId};r.set(s,i)}else{const i={type:"tool-call",eventType:l.TOOL_CALL_COMPLETE,messageId:s,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,time:new Date,traceId:t.traceId};r.set(s,i)}return new m({messages:r,pendingConsent:this.pendingConsent})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new m({messages:this.messages,pendingConsent:e})}onSubagentStart(t){const e=t.fact.subagentStart,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:start`,o={type:"subagent",messageId:s,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return r.delete(s),r.set(s,o),new m({messages:r,pendingConsent:this.pendingConsent})}onSubagentComplete(t){const e=t.fact.subagentComplete,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:complete`,o={type:"subagent",messageId:s,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return r.delete(s),r.set(s,o),new m({messages:r,pendingConsent:this.pendingConsent})}}const Pn=new Set(["TaskCreate","TaskUpdate"]);function We(n){return n.toolsetName===""&&Pn.has(n.toolName)}function we(n){return typeof n=="object"&&n!==null?n:void 0}function I(n){return typeof n=="string"?n:void 0}function Xe(n){const t=[],e=new Map;for(const r of n){const s=r.parameter??{},o=r.sidecar??{};if(r.toolName==="TaskCreate"){const i=we(o.task),a=I(i?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:I(s.subject)||I(i?.subject)||"",activeForm:I(s.activeForm),description:I(s.description),status:e.get(a)?.status??"pending"})}else if(r.toolName==="TaskUpdate"){const i=we(o.statusChange),a=I(s.taskId)||I(o.taskId),c=I(i?.to)||I(s.status);if(!a||!c)continue;const u=e.get(a);u&&e.set(a,{...u,status:c})}}return t.map(r=>e.get(r))}function ze(n){return n.toolsetName===""&&n.toolName==="Agent"}function Je(n){return!!n}function Ee(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function Qe(n){const t=[],e=new Map,r=new Map,s=o=>(e.has(o)||(t.push(o),e.set(o,{status:"running"}),r.set(o,new Map)),e.get(o));for(const o of n)switch(o.kind){case"agentStart":{const i=s(o.toolUseId);o.description&&!i.description&&(i.description=o.description);break}case"subagentStart":{const i=s(o.parentToolUseId);i.agentId=o.agentId??i.agentId,i.subagentType=o.subagentType??i.subagentType,i.description=o.description??i.description,Ee(i);break}case"toolStart":{Ee(s(o.parentToolUseId)),r.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=r.get(o.parentToolUseId)?.get(o.toolUseId);i&&(i.status=o.isError?"error":"completed");break}case"subagentComplete":{const i=s(o.parentToolUseId);i.status=o.status,i.summary=o.summary;break}}return t.map(o=>({parentToolUseId:o,...e.get(o),tools:Array.from(r.get(o).values())}))}function _n(n){return typeof n=="string"?n:void 0}function Ze(n){const t=[];for(const e of n){if(e.type==="tool-call"&&ze(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:_n(e.parameter.description)});continue}if(e.type==="tool-call"&&Je(e.parentToolUseId)){const r=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:r,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:r,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function et(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&We(e));return Xe(t)}function tt(n){return Qe(Ze(Array.from(n.messages?.values()??[])))}function nt(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.id===s.id&&e.status===s.status&&e.subject===s.subject&&e.activeForm===s.activeForm&&e.description===s.description})}function Ln(n,t){return n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.toolName===s.toolName&&e.toolsetName===s.toolsetName&&e.status===s.status&&e.reason===s.reason})}function rt(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.parentToolUseId===s.parentToolUseId&&e.status===s.status&&e.subagentType===s.subagentType&&e.description===s.description&&e.summary===s.summary&&Ln(e.tools,s.tools)})}function st(n){const t=new T([]),e=new T([]),r=new $;return r.add(n.pipe(j(et),M(nt)).subscribe(t)),r.add(n.pipe(j(tt),M(rt)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>r.unsubscribe()}}function oe(n){const t=new Map;for(const e of n)t.set(e.sandboxName,e);return[...t.values()].sort((e,r)=>(e.sandboxBlueprintName||e.sandboxName).localeCompare(r.sandboxBlueprintName||r.sandboxName))}const ee={kind:null,stopPhase:"idle"},Mn=1e4;function Un(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class D{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;promptSuggestion$;sandboxPhase$;launchedSandboxes$;runStatus$;currentUserMessageId;lastSentMessageId;currentRun;forceStopTimer;constructor(t){if(!t.client)throw new Error("client must be required");if(!t.customChannelId)throw new Error("customChannelId must be required");this.client=t.client,this.customChannelId=t.customChannelId,this.customMessageId=t.customMessageId,this.joinRunState=t.runState??"IDLE",this.isConnecting$=new T(!1),this.runStatusSubject=new T(ee),this.conversation$=new T(t.conversation),this.channelTitleSubject=new T(t.channelTitle??null),this.promptSuggestionSubject=new T(null),this.sandboxPhaseSubject=new T("idle"),this.launchedSandboxesSubject=new T(oe(t.launchedSandboxes??[])),this.derivedStores=st(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(M()),this.promptSuggestion$=this.promptSuggestionSubject.pipe(M()),this.sandboxPhase$=this.sandboxPhaseSubject.pipe(M()),this.launchedSandboxes$=this.launchedSandboxesSubject.pipe(M()),this.runStatus$=this.runStatusSubject.pipe(M(Un)),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}getPromptSuggestion(){return this.promptSuggestionSubject.value}clearPromptSuggestion(){this.promptSuggestionSubject.next(null)}getSandboxPhase(){return this.sandboxPhaseSubject.value}getLaunchedSandboxes(){return this.launchedSandboxesSubject.value}getRunStatus(){return this.runStatusSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=oe(t);this.pendingLaunches=this.pendingLaunches.filter(r=>!e.some(s=>s.sandboxName===r)),this.launchedSandboxesSubject.next(e)}dropSandbox(t){const e=this.launchedSandboxesSubject.value,r=e.filter(s=>s.sandboxName!==t);r.length!==e.length&&this.launchedSandboxesSubject.next(r)}noteSandboxLaunch(t){this.pendingLaunches.includes(t)||(this.pendingLaunches=[...this.pendingLaunches,t]),this.refetchMetadata()}async refetchMetadata(){if(!this.client.channelMetadata)return;const t=await this.client.channelMetadata(this.customChannelId);t&&this.applyLaunchedSandboxes(t.launchedSandboxes)}setChannelTitle(t){this.channelTitleSubject.next(t)}static create(t){const e=new D(t);return e.subscribe(),e}static async reset(t,e,r,s){const o=new D(t);try{return o.subscribe(),s?.(o),await o.resetChannel(e,r),o}catch(i){throw o.close(),i}}static async restore(t,e,r){const s=new D(t);try{return s.subscribe(),r?.(s),await s.rejoinChannel(e),s}catch(o){throw s.close(),o}}subscribe(){this.statesSubscription=ln([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.promptSuggestion$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe(j(([t,e,r,s,o,i,a,c,u])=>({isConnecting:t,conversation:e,tasks:r,subagents:s,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 l.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case l.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case l.INIT:case l.ERROR:this.sandboxPhaseSubject.next("idle");break}}buildRunHandlers(t,e,r){return{onSseStart:t?.onSseStart,onSseMessage:s=>{if(t?.onSseMessage?.(s),this.captureRequestId(s.requestId),s.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(s.fact.channelTitleUpdate.title),s.eventType===l.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(s.fact.promptSuggestion.suggestion):s.eventType===l.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(s.eventType),s.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(s.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&s.traceId){const o=new Map(this.conversation$.value.messages),i=o.get(this.currentUserMessageId);i&&i.type==="user"&&(o.set(this.currentUserMessageId,{...i,traceId:s.traceId}),this.conversation$.next(new m({messages:o,pendingConsent:this.conversation$.value.pendingConsent}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(s))},onSseError:s=>{t?.onSseError?.(s),this.settleRun(),r(s)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.settleRun(),e()}}}settleRun(){const t=this.runStatusSubject.value.stopPhase!=="idle";this.clearForceStopTimer(),this.isConnecting$.next(!1),this.runStatusSubject.next(ee),this.currentUserMessageId=void 0,this.currentRun=void 0,t&&this.conversation$.next(this.conversation$.value.settleInFlightMessages())}captureRequestId(t){const e=this.runStatusSubject.value;!t||e.requestId||!e.kind||this.runStatusSubject.next({...e,requestId:t})}clearForceStopTimer(){this.forceStopTimer&&(clearTimeout(this.forceStopTimer),this.forceStopTimer=void 0)}fetchSse(t,e,r){return new Promise((s,o)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(r,s,o))})}rejoinChannel(t){return new Promise((e,r)=>{if(!this.client.rejoinSse){e();return}this.isConnecting$.next(!0),this.runStatusSubject.next({kind:this.joinRunState==="RUNNING"?"restore":"replay",stopPhase:"idle"}),this.currentRun=this.client.rejoinSse(this.customChannelId,this.buildRunHandlers(t,e,r))})}resetChannel(t,e){return this.fetchSse("reset",{action:N.RESET_CHANNEL,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const r=this.runStatusSubject.value.kind;if(r)return Promise.reject(new K(r));const s=this.conversation$.value.pendingConsent;if(s)return Promise.reject(new V(s.processId));this.clearPromptSuggestion();const o=t.text.trim(),i=t.customMessageId??Ye();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:N.NONE,customChannelId:this.customChannelId,customMessageId:i,payload:this.resolvePayload(t?.payload),text:o,blobIds:t?.blobIds},e)}replyToolCallConsents(t,e,r){const s=this.conversation$.value.pendingConsent;return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse("user",{action:N.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(r),text:"",toolCallConsents:t},e).catch(o=>{throw s&&this.conversation$.next(this.conversation$.value.restorePendingConsent(s)),o})}nudge(t,e){const r=this.runStatusSubject.value.kind;if(r)return Promise.reject(new K(r));const s=this.conversation$.value.pendingConsent;return s?Promise.reject(new V(s.processId)):this.fetchSse("nudge",{action:N.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t)}async stopGeneration(t){const e=this.runStatusSubject.value;if(!(!this.currentRun||e.kind!=="user")&&!(e.stopPhase!=="idle"&&!t?.force)){if(!this.client.suspendChannel){this.abortConnection();return}this.clearForceStopTimer(),this.runStatusSubject.next({...e,stopPhase:"stopping"});try{await this.client.suspendChannel(this.customChannelId,{requestId:e.requestId,force:t?.force})}catch(r){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),r}this.armForceStopTimer()}}armForceStopTimer(){this.clearForceStopTimer(),this.forceStopTimer=setTimeout(()=>{this.forceStopTimer=void 0;const t=this.runStatusSubject.value;t.stopPhase==="stopping"&&this.runStatusSubject.next({...t,stopPhase:"force-stoppable"})},Mn)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(ee),this.currentUserMessageId=void 0,this.conversation$.next(this.conversation$.value.settleInFlightMessages()))}close(){this.currentRun?.unsubscribe(),this.currentRun=void 0,this.clearForceStopTimer(),this.isConnecting$.complete(),this.runStatusSubject.complete(),this.conversation$.complete(),this.channelTitleSubject.complete(),this.sandboxPhaseSubject.complete(),this.launchedSandboxesSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}function Nn(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),r=t[2],s=new URLSearchParams(t[3]??"");if(r==="open-browser")return{kind:"open-browser",sandboxName:e};if(r==="open-file"){const o=s.get("absolute_path");return o?{kind:"open-file",sandboxName:e,absolutePath:o}:null}return null}exports.AsgardServiceClient=In;exports.Channel=D;exports.ChannelAwaitingConsentError=V;exports.ChannelBusyError=K;exports.Conversation=m;exports.EventType=l;exports.FetchSseAction=N;exports.HttpError=w;exports.MessageTemplateType=ie;exports.ToolCallConsentResult=Ie;exports.conversationToSubagentEvents=Ze;exports.createDerivedStores=st;exports.deriveSubagents=tt;exports.deriveTasks=et;exports.isAgentTool=ze;exports.isChannelAwaitingConsentError=ut;exports.isChannelBusyError=ct;exports.isHttpError=at;exports.isSubagentChildTool=Je;exports.isTaskTool=We;exports.reconcileLaunched=oe;exports.reduceSubagents=Qe;exports.reduceTaskEvents=Xe;exports.resolveSandboxUri=Nn;exports.subagentsEqual=rt;exports.tasksEqual=nt;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class w extends Error{status;statusText;body;constructor(t,e,s){super(`HTTP ${t}: ${e}`),this.name="HttpError",this.status=t,this.statusText=e,this.body=s}}function ht(n){return n instanceof w}class V extends Error{runKind;constructor(t){super(`Cannot send a message while a "${t}" run is in flight on this channel.`),this.name="ChannelBusyError",this.runKind=t}}function ft(n){return n instanceof V}class X extends Error{processId;constructor(t){super("Cannot send this turn while the channel is awaiting a tool-call consent response."),this.name="ChannelAwaitingConsentError",this.processId=t}}function pt(n){return n instanceof X}var R=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(R||{}),l=(n=>(n.INIT="asgard.run.init",n.PROCESS="asgard.process",n.PROCESS_START="asgard.process.start",n.PROCESS_COMPLETE="asgard.process.complete",n.MESSAGE="asgard.message",n.MESSAGE_START="asgard.message.start",n.MESSAGE_DELTA="asgard.message.delta",n.MESSAGE_COMPLETE="asgard.message.complete",n.MESSAGE_USER="asgard.message.user",n.MESSAGE_THINKING_START="asgard.message.thinking.start",n.MESSAGE_THINKING_DELTA="asgard.message.thinking.delta",n.MESSAGE_THINKING_COMPLETE="asgard.message.thinking.complete",n.MESSAGE_CANVAS_START="asgard.message.canvas.start",n.MESSAGE_CANVAS_DELTA="asgard.message.canvas.delta",n.MESSAGE_CANVAS_COMPLETE="asgard.message.canvas.complete",n.TOOL_CALL="asgard.tool_call",n.TOOL_CALL_START="asgard.tool_call.start",n.TOOL_CALL_COMPLETE="asgard.tool_call.complete",n.TOOL_CALL_CONSENT="asgard.tool_call.consent",n.SUBAGENT_START="asgard.subagent.start",n.SUBAGENT_COMPLETE="asgard.subagent.complete",n.CHANNEL_TITLE_UPDATE="asgard.channel.title.update",n.PROMPT_SUGGESTION="asgard.prompt_suggestion",n.SANDBOX_LAUNCH="asgard.sandbox.launch",n.SANDBOX_READY="asgard.sandbox.ready",n.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(l||{}),xe=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(xe||{}),ae=(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))(ae||{});async function mt(n,t){const e=n.getReader();let s;for(;!(s=await e.read()).done;)t(s.value)}function gt(n){let t,e,s,r=!1;return function(i){t===void 0?(t=i,e=0,s=-1):t=vt(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 bt(n,t,e){let s=fe();const r=new TextDecoder;return function(i,a){if(i.length===0)e?.(s),s=fe();else if(a>0){const c=r.decode(i.subarray(0,a)),u=a+(i[a+1]===32?2:1),d=r.decode(i.subarray(u));switch(c){case"data":s.data=s.data?s.data+`
2
+ `+d:d;break;case"event":s.event=d;break;case"id":n(s.id=d);break;case"retry":const g=parseInt(d,10);isNaN(g)||t(s.retry=g);break}}}}function vt(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function fe(){return{data:"",event:"",id:"",retry:void 0}}var St=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(e[s[r]]=n[s[r]]);return e};const ne="text/event-stream",yt=1e3,pe="last-event-id";function Ae(n,t){var{signal:e,headers:s,onopen:r,onmessage:o,onclose:i,onerror:a,openWhenHidden:c,fetch:u}=t,d=St(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,v)=>{const h=Object.assign({},s);h.accept||(h.accept=ne);let p;function f(){p.abort(),document.hidden||J()}c||document.addEventListener("visibilitychange",f);let M=yt,I=0;function L(){document.removeEventListener("visibilitychange",f),window.clearTimeout(I),p.abort()}e?.addEventListener("abort",()=>{L(),g()});const lt=u??window.fetch,dt=r??wt;async function J(){var Q;p=new AbortController;try{const B=await lt(n,Object.assign(Object.assign({},d),{headers:h,signal:p.signal}));await dt(B),await mt(B.body,gt(bt(A=>{A?h[pe]=A:delete h[pe]},A=>{M=A},o))),i?.(),L(),g()}catch(B){if(!p.signal.aborted)try{const A=(Q=a?.(B))!==null&&Q!==void 0?Q:M;window.clearTimeout(I),I=window.setTimeout(J,A)}catch(A){L(),v(A)}}}J()})}function wt(n){const t=n.headers.get("content-type");if(!t?.startsWith(ne))throw new Error(`Expected content-type to be ${ne}, Actual: ${t}`)}var se=function(n,t){return se=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,s){e.__proto__=s}||function(e,s){for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(e[r]=s[r])},se(n,t)};function x(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");se(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function Et(n,t,e,s){function r(o){return o instanceof e?o:new e(function(i){i(o)})}return new(e||(e=Promise))(function(o,i){function a(d){try{u(s.next(d))}catch(g){i(g)}}function c(d){try{u(s.throw(d))}catch(g){i(g)}}function u(d){d.done?o(d.value):r(d.value).then(a,c)}u((s=s.apply(n,t||[])).next())})}function Oe(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(d){return c([u,d])}}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(d){u=[6,d],r=0}finally{s=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function j(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 F(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 G(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 It(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(h){return function(p){return Promise.resolve(p).then(h,g)}}function a(h,p){s[h]&&(r[h]=function(f){return new Promise(function(M,I){o.push([h,f,M,I])>1||c(h,f)})},p&&(r[h]=p(r[h])))}function c(h,p){try{u(s[h](p))}catch(f){v(o[0][3],f)}}function u(h){h.value instanceof k?Promise.resolve(h.value.v).then(d,g):v(o[0][2],h)}function d(h){c("next",h)}function g(h){c("throw",h)}function v(h,p){h(p),o.shift(),o.length&&c(o[0][0],o[0][1])}}function Tt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=n[Symbol.asyncIterator],e;return t?t.call(n):(n=typeof j=="function"?j(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 b(n){return typeof n=="function"}function _e(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 Z=_e(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
3
+ `+e.map(function(s,r){return r+1+") "+s.toString()}).join(`
4
+ `):"",this.name="UnsubscriptionError",this.errors=e}});function W(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=j(i),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(f){t={error:f}}finally{try{c&&!c.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else i.remove(this);var d=this.initialTeardown;if(b(d))try{d()}catch(f){o=f instanceof Z?f.errors:[f]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var v=j(g),h=v.next();!h.done;h=v.next()){var p=h.value;try{me(p)}catch(f){o=o??[],f instanceof Z?o=G(G([],F(o)),F(f.errors)):o.push(f)}}}catch(f){s={error:f}}finally{try{h&&!h.done&&(r=v.return)&&r.call(v)}finally{if(s)throw s.error}}}if(o)throw new Z(o)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)me(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)&&W(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&W(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),Pe=D.EMPTY;function Me(n){return n instanceof D||n&&"closed"in n&&b(n.remove)&&b(n.add)&&b(n.unsubscribe)}function me(n){b(n)?n():n.unsubscribe()}var Ct={Promise:void 0},xt={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,G([n,t],F(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Le(n){xt.setTimeout(function(){throw n})}function re(){}function K(n){n()}var ce=(function(n){x(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,Me(e)&&e.add(s)):s.destination=_t,s}return t.create=function(e,s,r){return new oe(e,s,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(D),At=(function(){function n(t){this.partialObserver=t}return n.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(s){q(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){q(s)}else q(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){q(e)}},n})(),oe=(function(n){x(t,n);function t(e,s,r){var o=n.call(this)||this,i;return b(e)||!e?i={next:e??void 0,error:s??void 0,complete:r??void 0}:i=e,o.destination=new At(i),o}return t})(ce);function q(n){Le(n)}function Ot(n){throw n}var _t={closed:!0,next:re,error:Ot,complete:re},ue=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function z(n){return n}function Pt(n){return n.length===0?z:n.length===1?n[0]:function(e){return n.reduce(function(s,r){return r(s)},e)}}var y=(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=Lt(t)?t:new oe(t,e,s);return K(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=ge(e),new e(function(r,o){var i=new oe({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[ue]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Pt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=ge(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 ge(n){var t;return(t=n??Ct.Promise)!==null&&t!==void 0?t:Promise}function Mt(n){return n&&b(n.next)&&b(n.error)&&b(n.complete)}function Lt(n){return n&&n instanceof ce||Mt(n)&&Me(n)}function Ut(n){return b(n?.lift)}function P(n){return function(t){if(Ut(t))return t.lift(function(e){try{return n(e,this)}catch(s){this.error(s)}});throw new TypeError("Unable to lift unknown Observable type")}}function _(n,t,e,s,r){return new Nt(n,t,e,s,r)}var Nt=(function(n){x(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(d){e.error(d)}}:n.prototype._next,c._error=o?function(u){try{o(u)}catch(d){e.error(d)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=r?function(){try{r()}catch(u){e.error(u)}finally{this.unsubscribe()}}:n.prototype._complete,c}return t.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var s=this.closed;n.prototype.unsubscribe.call(this),!s&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ce),Rt=_e(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),le=(function(n){x(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 be(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Rt},t.prototype.next=function(e){var s=this;K(function(){var r,o;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var i=j(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;K(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;K(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?Pe:(this.currentObservers=null,a.push(e),new D(function(){s.currentObservers=null,W(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 y;return e.source=this,e},t.create=function(e,s){return new be(e,s)},t})(y),be=(function(n){x(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:Pe},t})(le),C=(function(n){x(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})(le),kt={now:function(){return Date.now()}},jt=(function(n){x(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(D),ve={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,G([n,t],F(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},$t=(function(n){x(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),ve.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&&ve.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,W(o,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(jt),Se=(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=kt.now,n})(),Dt=(function(n){x(t,n);function t(e,s){s===void 0&&(s=Se.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})(Se),Ue=new Dt($t),Ht=Ue,Ft=new y(function(n){return n.complete()});function Ne(n){return n&&b(n.schedule)}function Re(n){return n[n.length-1]}function Gt(n){return b(Re(n))?n.pop():void 0}function ke(n){return Ne(Re(n))?n.pop():void 0}var je=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function $e(n){return b(n?.then)}function De(n){return b(n[ue])}function He(n){return Symbol.asyncIterator&&b(n?.[Symbol.asyncIterator])}function Fe(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 Bt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ge=Bt();function Be(n){return b(n?.[Ge])}function qe(n){return It(this,arguments,function(){var e,s,r,o;return Oe(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 Ke(n){return b(n?.getReader)}function N(n){if(n instanceof y)return n;if(n!=null){if(De(n))return qt(n);if(je(n))return Kt(n);if($e(n))return Vt(n);if(He(n))return Ve(n);if(Be(n))return Xt(n);if(Ke(n))return Wt(n)}throw Fe(n)}function qt(n){return new y(function(t){var e=n[ue]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Kt(n){return new y(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Vt(n){return new y(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Le)})}function Xt(n){return new y(function(t){var e,s;try{for(var r=j(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 Ve(n){return new y(function(t){Yt(n,t).catch(function(e){return t.error(e)})})}function Wt(n){return Ve(qe(n))}function Yt(n,t){var e,s,r,o;return Et(this,void 0,void 0,function(){var i,a;return Oe(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),e=Tt(n),c.label=1;case 1:return[4,e.next()];case 2:if(s=c.sent(),!!s.done)return[3,4];if(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 O(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 Xe(n,t){return t===void 0&&(t=0),P(function(e,s){e.subscribe(_(s,function(r){return O(s,n,function(){return s.next(r)},t)},function(){return O(s,n,function(){return s.complete()},t)},function(r){return O(s,n,function(){return s.error(r)},t)}))})}function We(n,t){return t===void 0&&(t=0),P(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function zt(n,t){return N(n).pipe(We(t),Xe(t))}function Jt(n,t){return N(n).pipe(We(t),Xe(t))}function Qt(n,t){return new y(function(e){var s=0;return t.schedule(function(){s===n.length?e.complete():(e.next(n[s++]),e.closed||this.schedule())})})}function Zt(n,t){return new y(function(e){var s;return O(e,t,function(){s=n[Ge](),O(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 b(s?.return)&&s.return()}})}function Ye(n,t){if(!n)throw new Error("Iterable cannot be null");return new y(function(e){O(e,t,function(){var s=n[Symbol.asyncIterator]();O(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function en(n,t){return Ye(qe(n),t)}function tn(n,t){if(n!=null){if(De(n))return zt(n,t);if(je(n))return Qt(n,t);if($e(n))return Jt(n,t);if(He(n))return Ye(n,t);if(Be(n))return Zt(n,t);if(Ke(n))return en(n,t)}throw Fe(n)}function de(n,t){return t?tn(n,t):N(n)}function nn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=ke(n);return de(n,e)}function sn(n){return n instanceof Date&&!isNaN(n)}function $(n,t){return P(function(e,s){var r=0;e.subscribe(_(s,function(o){s.next(n.call(t,o,r++))}))})}var rn=Array.isArray;function on(n,t){return rn(t)?n.apply(void 0,G([],F(t))):n(t)}function an(n){return $(function(t){return on(n,t)})}var cn=Array.isArray,un=Object.getPrototypeOf,ln=Object.prototype,dn=Object.keys;function hn(n){if(n.length===1){var t=n[0];if(cn(t))return{args:t,keys:null};if(fn(t)){var e=dn(t);return{args:e.map(function(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function fn(n){return n&&typeof n=="object"&&un(n)===ln}function pn(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function mn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=ke(n),s=Gt(n),r=hn(n),o=r.args,i=r.keys;if(o.length===0)return de([],e);var a=new y(gn(o,e,i?function(c){return pn(i,c)}:z));return s?a.pipe(an(s)):a}function gn(n,t,e){return e===void 0&&(e=z),function(s){ye(t,function(){for(var r=n.length,o=new Array(r),i=r,a=r,c=function(d){ye(t,function(){var g=de(n[d],t),v=!1;g.subscribe(_(s,function(h){o[d]=h,v||(v=!0,a--),a||s.next(e(o.slice()))},function(){--i||s.complete()}))},s)},u=0;u<r;u++)c(u)},s)}}function ye(n,t,e){n?O(e,n,t):t()}function bn(n,t,e,s,r,o,i,a){var c=[],u=0,d=0,g=!1,v=function(){g&&!c.length&&!u&&t.complete()},h=function(f){return u<s?p(f):c.push(f)},p=function(f){u++;var M=!1;N(e(f,d++)).subscribe(_(t,function(I){t.next(I)},function(){M=!0},void 0,function(){if(M)try{u--;for(var I=function(){var L=c.shift();i||p(L)};c.length&&u<s;)I();v()}catch(L){t.error(L)}}))};return n.subscribe(_(t,h,function(){g=!0,v()})),function(){}}function Y(n,t,e){return e===void 0&&(e=1/0),b(t)?Y(function(s,r){return $(function(o,i){return t(s,o,r,i)})(N(n(s,r)))},e):(typeof t=="number"&&(e=t),P(function(s,r){return bn(s,r,n,e)}))}function vn(n,t,e){n===void 0&&(n=0),e===void 0&&(e=Ht);var s=-1;return t!=null&&(Ne(t)?e=t:s=t),new y(function(r){var o=sn(n)?+n-e.now():n;o<0&&(o=0);var i=0;return e.schedule(function(){r.closed||(r.next(i++),0<=s?this.schedule(void 0,s):r.complete())},o)})}function Sn(n,t){return b(t)?Y(n,t,1):Y(n,1)}function yn(n){return n<=0?function(){return Ft}:P(function(t,e){var s=0;t.subscribe(_(e,function(r){++s<=n&&(e.next(r),n<=s&&e.complete())}))})}function wn(n){return $(function(){return n})}function En(n,t){return Y(function(e,s){return N(n(e,s)).pipe(yn(1),wn(e))})}function In(n,t){t===void 0&&(t=Ue);var e=vn(n,t);return En(function(){return e})}function U(n,t){return t===void 0&&(t=z),n=n??Tn,P(function(e,s){var r,o=!0;e.subscribe(_(s,function(i){var a=t(i);(o||!n(r,a))&&(o=!1,r=a,s.next(i))}))})}function Tn(n,t){return n===t}function Cn(n){return P(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function xn(n){return P(function(t,e){N(n).subscribe(_(e,function(){return e.complete()},re)),!e.closed&&t.subscribe(e)})}function we(n){const{endpoint:t,apiKey:e,payload:s,debugMode:r,customHeaders:o}=n,i=n.method??"POST";return new y(a=>{const c=new AbortController;let u,d=!1,g=!1;const v={"Content-Type":"application/json",...o};e&&(v["X-API-KEY"]=e);const h=new URL(t);return r&&h.searchParams.set("is_debug","true"),Ae(h.toString(),{method:i,headers:v,body:i==="POST"&&s?JSON.stringify(s):void 0,signal:c.signal,openWhenHidden:!0,onopen:async p=>{if(p.ok)u=p.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await p.json()}catch{try{f=await p.text()}catch{f=null}}a.error(new w(p.status,p.statusText,f)),c.abort()}},onmessage:p=>{p.id&&(d=!0);const f=JSON.parse(p.data);u?f.traceId=u:f.requestId&&(f.traceId=f.requestId,u||(u=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:p=>{if(g)throw p;if(!d)throw a.error(p),c.abort(),p}}),()=>{g=!0,c.abort()}})}class An{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))}}class On{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new le;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new An;transformSsePayload;customHeaders;constructor(t){if(!t.endpoint&&!t.botProviderEndpoint)throw new Error("Either endpoint or botProviderEndpoint must be provided");if(this.apiKey=t.apiKey,this.debugMode=t.debugMode,this.transformSsePayload=t.transformSsePayload,this.botProviderEndpoint=t.botProviderEndpoint,this.customHeaders={...t.customHeaders,...t.userIdentityHint?{"X-ASGARD-USER-IDENTITY-HINT":t.userIdentityHint}:{}},!t.endpoint&&t.botProviderEndpoint){const e=t.botProviderEndpoint.replace(/\/+$/,"");this.endpoint=`${e}/message/sse`}else t.endpoint&&(this.endpoint=t.endpoint,this.debugMode&&console.warn('[AsgardServiceClient] The "endpoint" option is deprecated and will be removed in the next major version. Please use "botProviderEndpoint" instead. The SSE endpoint will be automatically derived as "${botProviderEndpoint}/message/sse".'))}on(t,e){this.sseEmitter.remove(t),this.sseEmitter.on(t,e)}handleEvent(t){switch(t.eventType){case l.INIT:this.sseEmitter.emit(l.INIT,t);break;case l.PROCESS_START:case l.PROCESS_COMPLETE:this.sseEmitter.emit(l.PROCESS,t);break;case l.MESSAGE_START:case l.MESSAGE_DELTA:case l.MESSAGE_COMPLETE:this.sseEmitter.emit(l.MESSAGE,t);break;case l.TOOL_CALL_START:case l.TOOL_CALL_COMPLETE:this.sseEmitter.emit(l.TOOL_CALL,t);break;case l.TOOL_CALL_CONSENT:this.sseEmitter.emit(l.TOOL_CALL_CONSENT,t);break;case l.DONE:this.sseEmitter.emit(l.DONE,t);break;case l.ERROR:this.sseEmitter.emit(l.ERROR,t);break}}fetchSse(t,e){return e?.onSseStart?.(),this.inFlight+=1,this.runSse(we({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(we({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 w(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 w(o.status,o.statusText,await o.text().catch(()=>{}))}runSse(t,e){return t.pipe(Sn(s=>nn(s).pipe(In(e?.delayTime??50))),xn(this.destroy$),Cn(()=>this.onRunSettled())).subscribe({next:s=>{this.detached||(e?.onSseMessage?.(s),this.handleEvent(s))},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){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox browser open-url endpoint. Please provide botProviderEndpoint in config.");const s=`${e}/sandbox/${encodeURIComponent(t)}/browser/open-url`,r={...this.customHeaders};this.apiKey&&(r["X-API-KEY"]=this.apiKey);const o=await fetch(s,{method:"POST",headers:r});if(!o.ok)throw new w(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}deriveSandboxFsEndpoint(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox fs endpoint. Please provide botProviderEndpoint in config.");return`${e}/sandbox/${encodeURIComponent(t)}/fs`}apiHeaders(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async sandboxFsList(t,e){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/list`);s.searchParams.set("path",e);const r=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!r.ok)throw new w(r.status,r.statusText,await r.text().catch(()=>{}));const o=await r.json(),i=o.data??o;return{entries:i.entries??[],truncated:i.truncated??!1}}async sandboxFsRead(t,e,s){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);r.searchParams.set("path",e),s?.offsetBytes!=null&&r.searchParams.set("offset_bytes",String(s.offsetBytes)),s?.limitBytes!=null&&r.searchParams.set("limit_bytes",String(s.limitBytes));const o=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!o.ok)throw new w(o.status,o.statusText,await o.text().catch(()=>{}));const i=await o.blob(),a=o.headers.get("X-Total-Bytes");return{content:i,totalBytes:a!=null?Number(a):i.size,truncated:o.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,s,r){const o=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);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});if(!a.ok)throw new w(a.status,a.statusText,await a.text().catch(()=>{}));const c=await a.json();return{bytesWritten:(c.data??c).bytesWritten??0}}async sandboxFsRequest(t,e,s,r){const o=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(r).forEach(([a,c])=>o.searchParams.set(a,c));const i=await fetch(o.toString(),{method:s,headers:this.apiHeaders()});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));return i.json().catch(()=>null)}async sandboxFsStat(t,e){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/stat`);s.searchParams.set("path",e);const r=await fetch(s.toString(),{method:"GET",headers:this.apiHeaders()});if(!r.ok)throw new w(r.status,r.statusText,await r.text().catch(()=>{}));const o=await r.json(),i=o.data??o;return{exists:i.exists??!1,isDir:i.isDir??!1,sizeBytes:i.sizeBytes??0,mtimeUnix:i.mtimeUnix??0,mode:i.mode??0,etag:i.etag}}async sandboxFsMkdir(t,e){await this.sandboxFsRequest(t,"mkdir","POST",{path:e})}async sandboxFsRemove(t,e){await this.sandboxFsRequest(t,"item","DELETE",{path:e})}async sandboxFsRemoveAll(t,e){await this.sandboxFsRequest(t,"all","DELETE",{path:e})}async sandboxFsCopy(t,e,s,r){const o={src:e,dst:s};r?.overwrite&&(o.overwrite="true");const i=await this.sandboxFsRequest(t,"copy","POST",o);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)}sandboxFsWatch(t,e){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/watch`);return s.searchParams.set("path",e),new y(r=>{const o=new AbortController;return Ae(s.toString(),{headers:this.apiHeaders(),signal:o.signal,openWhenHidden:!0,onopen:async i=>{if(!i.ok){const a=await i.text().catch(()=>{});r.error(new w(i.status,i.statusText,a)),o.abort()}},onmessage:i=>{i.event==="change"&&r.next(JSON.parse(i.data))},onclose:()=>r.complete(),onerror:i=>{throw r.error(i),o.abort(),i}}),()=>o.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 ze="",_n=new Set(["",".",".."]);function E(n,t){if(n===ze){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=>_n.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const he=1e3,Je=1e4;function Ee(n){return Math.min(Math.max(1,Math.floor(n)),he)}class Pn{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){const o=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([a,c])=>o.searchParams.set(a,c));const i=await fetch(o.toString(),{method:e,headers:this.headers(),body:r});if(!i.ok)throw new w(i.status,i.statusText,await i.text().catch(()=>{}));return i}async list(t,e){const s={path:E(t,{allowRoot:!0})};e?.page!=null&&(s.page=String(e.page)),e?.pageSize!=null&&(s.page_size=String(Ee(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=Ee(e?.pageSize??he),r=e?.maxEntries??Je,o=[];let i=0,a=!0,c=0;for(;;){const u=await this.list(t,{page:c,pageSize:s}),d=u.paging;if(d&&d.index!==c){i=d.total,a=!1;break}if(o.push(...u.entries),!d){a=u.entries.length<s;break}if(i=d.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:E(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:E(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:E(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)).json();return{bytesWritten:(a.data??a).bytesWritten??0}}async mkdir(t){await this.request("mkdir","POST",{path:E(t)})}async remove(t){await this.request("item","DELETE",{path:E(t)})}async removeAll(t){await this.request("all","DELETE",{path:E(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:E(t),dst:E(e)};return s?.overwrite&&(r.overwrite="true"),r}}const S=[];for(let n=0;n<256;++n)S.push((n+256).toString(16).slice(1));function Mn(n,t=0){return(S[n[t+0]]+S[n[t+1]]+S[n[t+2]]+S[n[t+3]]+"-"+S[n[t+4]]+S[n[t+5]]+"-"+S[n[t+6]]+S[n[t+7]]+"-"+S[n[t+8]]+S[n[t+9]]+"-"+S[n[t+10]]+S[n[t+11]]+S[n[t+12]]+S[n[t+13]]+S[n[t+14]]+S[n[t+15]]).toLowerCase()}let ee;const Ln=new Uint8Array(16);function Un(){if(!ee){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ee=crypto.getRandomValues.bind(crypto)}return ee(Ln)}const Nn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ie={randomUUID:Nn};function Rn(n,t,e){n=n||{};const s=n.random??n.rng?.()??Un();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,Mn(s)}function Qe(n,t,e){return Ie.randomUUID&&!n?Ie.randomUUID():Rn(n)}class m{messages=null;pendingConsent=null;constructor({messages:t,pendingConsent:e=null}){this.messages=t,this.pendingConsent=e??null}pushMessage(t){const e=new Map(this.messages);return e.set(t.messageId,t),new m({messages:e,pendingConsent:this.pendingConsent})}clearPendingConsent(){return this.pendingConsent?new m({messages:this.messages,pendingConsent:null}):this}restorePendingConsent(t){return this.pendingConsent?this:new m({messages:this.messages,pendingConsent:t})}settleInFlightMessages(){if(!this.messages)return this;let t=!1;const e=new Map(this.messages);for(const[s,r]of e)r.type==="tool-call"&&!r.isComplete&&(e.set(s,{...r,isComplete:!0,isCancelled:!0}),t=!0),r.type==="thinking"&&r.isThinking&&(e.set(s,{...r,isThinking:!1}),t=!0);return t?new m({messages:e,pendingConsent:this.pendingConsent}):this}cancelInFlightToolCalls(){return this.settleInFlightMessages()}onMessage(t){switch(t.eventType){case l.MESSAGE_START:return this.onMessageStart(t);case l.MESSAGE_DELTA:return this.onMessageDelta(t);case l.MESSAGE_COMPLETE:return this.onMessageComplete(t);case l.MESSAGE_USER:return this.onMessageUser(t);case l.MESSAGE_THINKING_START:return this.onThinkingStart(t);case l.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case l.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case l.MESSAGE_CANVAS_START:return this.onCanvasStart(t);case l.MESSAGE_CANVAS_DELTA:return this.onCanvasDelta(t);case l.MESSAGE_CANVAS_COMPLETE:return this.onCanvasComplete(t);case l.TOOL_CALL_START:return this.onToolCallStart(t);case l.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case l.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case l.SUBAGENT_START:return this.onSubagentStart(t);case l.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case l.ERROR:return this.onMessageError(t);default:return this}}isTerminalBot(t){return t?.type==="bot"&&!t.isTyping}isTerminalThinking(t){return t?.type==="thinking"&&!t.isThinking}isTerminalToolCall(t){return t?.type==="tool-call"&&t.isComplete===!0}isTerminalCanvas(t){return t?.type==="canvas"&&!t.isDrawing}onMessageStart(t){const e=t.fact.messageStart.message;if(e.parentToolUseId)return this;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages);return s.set(e.messageId,{type:"bot",eventType:l.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new m({messages:s,pendingConsent:this.pendingConsent})}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:l.MESSAGE_DELTA,isTyping:!0,typingText:`${r?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??r?.traceId,raw:r?.raw??""}),new m({messages:o,pendingConsent:this.pendingConsent})}onMessageComplete(t){const e=t.fact.messageComplete.message;if(e.parentToolUseId)return this;const s=new Map(this.messages),r=s.get(e.messageId);return s.set(e.messageId,{type:"bot",eventType:l.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??(r?.type==="bot"?r.traceId:void 0),raw:JSON.stringify(t)}),new m({messages:s,pendingConsent:this.pendingConsent})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(e.parentToolUseId)return this;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages),r={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return s.set(e.messageId,r),new m({messages:s,pendingConsent:this.pendingConsent})}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 m({messages:o,pendingConsent:this.pendingConsent})}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 m({messages:o,pendingConsent:this.pendingConsent})}onCanvasStart(t){const e=t.fact.messageCanvasStart.message;if(e.parentToolUseId)return this;if(this.isTerminalCanvas(this.messages?.get(e.messageId)))return this;const s=new Map(this.messages),r={type:"canvas",messageId:e.messageId,html:"",isDrawing:!0,time:new Date,traceId:t.traceId};return s.set(e.messageId,r),new m({messages:s,pendingConsent:this.pendingConsent})}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 m({messages:o,pendingConsent:this.pendingConsent})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const s=e.template?.type===ae.CANVAS?e.template:void 0,r=s?.canvas?.html;if(!r){if(!this.messages?.has(e.messageId))return this;const u=new Map(this.messages);return u.delete(e.messageId),new m({messages:u,pendingConsent:this.pendingConsent})}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 m({messages:a,pendingConsent:this.pendingConsent})}onMessageUser(t){const e=t.fact.messageUser;if((this.messages?.get(e.messageId)??(e.customMessageId?this.messages?.get(e.customMessageId):void 0))?.type==="user")return this;const r=new Map(this.messages),o={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return r.set(e.messageId,o),new m({messages:r,pendingConsent:this.pendingConsent})}onMessageError(t){const e=Qe(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new m({messages:r,pendingConsent:this.pendingConsent})}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:l.TOOL_CALL_START,messageId:r,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,isComplete:!1,time:new Date,traceId:t.traceId};return s.set(r,o),new m({messages:s,pendingConsent:this.pendingConsent})}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:l.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:l.TOOL_CALL_COMPLETE,messageId:r,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,time:new Date,traceId:t.traceId};s.set(r,i)}return new m({messages:s,pendingConsent:this.pendingConsent})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new m({messages:this.messages,pendingConsent:e})}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 m({messages:s,pendingConsent:this.pendingConsent})}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 m({messages:s,pendingConsent:this.pendingConsent})}}const kn=new Set(["TaskCreate","TaskUpdate"]);function Ze(n){return n.toolsetName===""&&kn.has(n.toolName)}function Te(n){return typeof n=="object"&&n!==null?n:void 0}function T(n){return typeof n=="string"?n:void 0}function et(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},o=s.sidecar??{};if(s.toolName==="TaskCreate"){const i=Te(o.task),a=T(i?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:T(r.subject)||T(i?.subject)||"",activeForm:T(r.activeForm),description:T(r.description),status:e.get(a)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const i=Te(o.statusChange),a=T(r.taskId)||T(o.taskId),c=T(i?.to)||T(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 tt(n){return n.toolsetName===""&&n.toolName==="Agent"}function nt(n){return!!n}function Ce(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function st(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,Ce(i);break}case"toolStart":{Ce(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);i&&(i.status=o.isError?"error":"completed");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 jn(n){return typeof n=="string"?n:void 0}function rt(n){const t=[];for(const e of n){if(e.type==="tool-call"&&tt(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:jn(e.parameter.description)});continue}if(e.type==="tool-call"&&nt(e.parentToolUseId)){const s=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:s,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:s,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function ot(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Ze(e));return et(t)}function it(n){return st(rt(Array.from(n.messages?.values()??[])))}function at(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 $n(n,t){return n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.toolName===r.toolName&&e.toolsetName===r.toolsetName&&e.status===r.status&&e.reason===r.reason})}function ct(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.parentToolUseId===r.parentToolUseId&&e.status===r.status&&e.subagentType===r.subagentType&&e.description===r.description&&e.summary===r.summary&&$n(e.tools,r.tools)})}function ut(n){const t=new C([]),e=new C([]),s=new D;return s.add(n.pipe($(ot),U(at)).subscribe(t)),s.add(n.pipe($(it),U(ct)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function ie(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 te={kind:null,stopPhase:"idle"},Dn=1e4;function Hn(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class H{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;pendingLaunches=[];derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;promptSuggestion$;sandboxPhase$;launchedSandboxes$;runStatus$;currentUserMessageId;lastSentMessageId;currentRun;forceStopTimer;constructor(t){if(!t.client)throw new Error("client must be required");if(!t.customChannelId)throw new Error("customChannelId must be required");this.client=t.client,this.customChannelId=t.customChannelId,this.customMessageId=t.customMessageId,this.joinRunState=t.runState??"IDLE",this.isConnecting$=new C(!1),this.runStatusSubject=new C(te),this.conversation$=new C(t.conversation),this.channelTitleSubject=new C(t.channelTitle??null),this.promptSuggestionSubject=new C(null),this.sandboxPhaseSubject=new C("idle"),this.launchedSandboxesSubject=new C(ie(t.launchedSandboxes??[])),this.derivedStores=ut(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(U()),this.promptSuggestion$=this.promptSuggestionSubject.pipe(U()),this.sandboxPhase$=this.sandboxPhaseSubject.pipe(U()),this.launchedSandboxes$=this.launchedSandboxesSubject.pipe(U()),this.runStatus$=this.runStatusSubject.pipe(U(Hn)),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}getPromptSuggestion(){return this.promptSuggestionSubject.value}clearPromptSuggestion(){this.promptSuggestionSubject.next(null)}getSandboxPhase(){return this.sandboxPhaseSubject.value}getLaunchedSandboxes(){return this.launchedSandboxesSubject.value}getRunStatus(){return this.runStatusSubject.value}getPendingLaunches(){return this.pendingLaunches}applyLaunchedSandboxes(t){const e=ie(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 H(t);return e.subscribe(),e}static async reset(t,e,s,r){const o=new H(t);try{return o.subscribe(),r?.(o),await o.resetChannel(e,s),o}catch(i){throw o.close(),i}}static async restore(t,e,s){const r=new H(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(o){throw r.close(),o}}subscribe(){this.statesSubscription=mn([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$,this.promptSuggestion$,this.sandboxPhase$,this.launchedSandboxes$,this.runStatus$]).pipe($(([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 l.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case l.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case l.INIT:case l.ERROR:this.sandboxPhaseSubject.next("idle");break}}buildRunHandlers(t,e,s){return{onSseStart:t?.onSseStart,onSseMessage:r=>{if(t?.onSseMessage?.(r),this.captureRequestId(r.requestId),r.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(r.fact.channelTitleUpdate.title),r.eventType===l.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(r.fact.promptSuggestion.suggestion):r.eventType===l.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(r.eventType),r.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(r.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&r.traceId){const 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 m({messages:o,pendingConsent:this.conversation$.value.pendingConsent}))),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(te),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))})}resetChannel(t,e){return this.fetchSse("reset",{action:R.RESET_CHANNEL,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 V(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new X(r.processId));this.clearPromptSuggestion();const o=t.text.trim(),i=t.customMessageId??Qe();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:R.NONE,customChannelId:this.customChannelId,customMessageId:i,payload:this.resolvePayload(t?.payload),text:o,blobIds:t?.blobIds},e)}replyToolCallConsents(t,e,s){const r=this.conversation$.value.pendingConsent;return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse("user",{action:R.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){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new V(s));const r=this.conversation$.value.pendingConsent;return r?Promise.reject(new X(r.processId)):this.fetchSse("nudge",{action:R.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t)}async stopGeneration(t){const e=this.runStatusSubject.value;if(!(!this.currentRun||e.kind!=="user")&&!(e.stopPhase!=="idle"&&!t?.force)){if(!this.client.suspendChannel){this.abortConnection();return}this.clearForceStopTimer(),this.runStatusSubject.next({...e,stopPhase:"stopping"});try{await this.client.suspendChannel(this.customChannelId,{requestId:e.requestId,force:t?.force})}catch(s){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),s}this.armForceStopTimer()}}armForceStopTimer(){this.clearForceStopTimer(),this.forceStopTimer=setTimeout(()=>{this.forceStopTimer=void 0;const t=this.runStatusSubject.value;t.stopPhase==="stopping"&&this.runStatusSubject.next({...t,stopPhase:"force-stoppable"})},Dn)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(te),this.currentUserMessageId=void 0,this.conversation$.next(this.conversation$.value.settleInFlightMessages()))}close(){this.currentRun?.unsubscribe(),this.currentRun=void 0,this.clearForceStopTimer(),this.isConnecting$.complete(),this.runStatusSubject.complete(),this.conversation$.complete(),this.channelTitleSubject.complete(),this.sandboxPhaseSubject.complete(),this.launchedSandboxesSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}function Fn(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),s=t[2],r=new URLSearchParams(t[3]??"");if(s==="open-browser")return{kind:"open-browser",sandboxName:e};if(s==="open-file"){const o=r.get("absolute_path");return o?{kind:"open-file",sandboxName:e,absolutePath:o}:null}return null}exports.AsgardServiceClient=On;exports.AsgardSourceSetClient=Pn;exports.Channel=H;exports.ChannelAwaitingConsentError=X;exports.ChannelBusyError=V;exports.Conversation=m;exports.EventType=l;exports.FetchSseAction=R;exports.HttpError=w;exports.MessageTemplateType=ae;exports.SOURCE_SET_DEFAULT_MAX_ENTRIES=Je;exports.SOURCE_SET_MAX_PAGE_SIZE=he;exports.SOURCE_SET_VOLUME_ROOT=ze;exports.ToolCallConsentResult=xe;exports.assertVolumePath=E;exports.conversationToSubagentEvents=rt;exports.createDerivedStores=ut;exports.deriveSubagents=it;exports.deriveTasks=ot;exports.isAgentTool=tt;exports.isChannelAwaitingConsentError=pt;exports.isChannelBusyError=ft;exports.isHttpError=ht;exports.isSubagentChildTool=nt;exports.isTaskTool=Ze;exports.reconcileLaunched=ie;exports.reduceSubagents=st;exports.reduceTaskEvents=et;exports.resolveSandboxUri=Fn;exports.subagentsEqual=ct;exports.tasksEqual=at;
5
5
  //# sourceMappingURL=index.cjs.map