@asgard-js/core 0.3.74 → 0.3.75
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 +5 -3
- package/dist/constants/enum.d.ts +10 -0
- package/dist/constants/enum.d.ts.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +165 -96
- package/dist/index.mjs.map +1 -1
- package/dist/lib/channel.d.ts +36 -4
- package/dist/lib/channel.d.ts.map +1 -1
- package/dist/lib/client.d.ts +18 -0
- package/dist/lib/client.d.ts.map +1 -1
- package/dist/types/channel.d.ts +2 -1
- package/dist/types/channel.d.ts.map +1 -1
- package/dist/types/client.d.ts +15 -0
- package/dist/types/client.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -141,10 +141,11 @@ The main client class for interacting with the Asgard AI platform.
|
|
|
141
141
|
|
|
142
142
|
#### Methods
|
|
143
143
|
|
|
144
|
-
- **fetchSse(payload, options?)**: Send a message via Server-Sent Events. `payload.action` is a `FetchSseAction` value — `NONE` for a normal message
|
|
144
|
+
- **fetchSse(payload, options?)**: Send a message via Server-Sent Events. `payload.action` is a `FetchSseAction` value — `NONE` for a normal message (and for the opening turn of a new conversation), `RESPONSE_TOOL_CALL_CONSENT` to answer a consent prompt, `NUDGE` for an invisible sandbox wake. `RESET_CHANNEL` is **deprecated** and no longer sent by the SDK — see `deleteChannel` below
|
|
145
145
|
- **uploadFile(file, customChannelId)**: Upload file to Blob API and return BlobUploadResponse
|
|
146
146
|
- **downloadChannelHomeFile(relativePath, customChannelId)**: `Promise<ChannelHomeDownloadResult>` - Download a file from the channel's Channel Home file-exchange plane (backs `channel-home://` URI actions); resolves to `{ blob, filename }`
|
|
147
147
|
- **rejoinSse(customChannelId, options?)**: Cold-start transcript rejoin — a `GET /message/sse` with an empty `Last-Event-ID` that replays the channel's collapsed history through the same reducer, so a returning user sees their prior conversation without re-POSTing. Optional on `IAsgardServiceClient` for backward compatibility
|
|
148
|
+
- **deleteChannel(customChannelId)**: `Promise<void>` - End the conversation and release everything the channel holds — the in-flight run, transcript, uploaded blobs, tool-call allow-list, Sandbox and Channel Home — via `DELETE /channel`. Resolves once the teardown is **done** (up to about a minute when a live Sandbox has to terminate first, so do not impose a shorter timeout), after which the same `customChannelId` is a blank slate. Deleting a channel that does not exist is a success. Optional on `IAsgardServiceClient` for backward compatibility
|
|
148
149
|
- **channelMetadata(customChannelId)**: `Promise<ChannelMetadata | null>` - Join-init existence + restore gate — `GET /channel/metadata`; resolves to the metadata on `200`, `null` on `404` (channel does not exist), and rejects on any other error. `ChannelMetadata` is `{ title: string | null; runState: 'RUNNING' | 'IDLE'; lastActivityAt?: string }`. Optional on `IAsgardServiceClient` for backward compatibility
|
|
149
150
|
- **suspendChannel(customChannelId, options?)**: `Promise<void>` - Ask the backend to stop the channel's background run — `POST /message/suspend?custom_channel_id=…`, with optional `requestId` (stop only that run) and `force` (abandon it rather than let it wind down). Resolves on any 2xx **and** on `404` (channel never created = nothing to stop); rejects with `HttpError` otherwise. Resolving means _accepted_, not _stopped_ — see [Stopping generation](#stopping-generation). Optional on `IAsgardServiceClient` for backward compatibility
|
|
150
151
|
- **on(event, handler)**: Listen to a specific SSE event. `event` must be an `EventType` value (e.g. `EventType.MESSAGE`), not a plain string; registering a listener for an event replaces any previous one
|
|
@@ -172,7 +173,8 @@ Higher-level abstraction for managing a conversation channel with reactive state
|
|
|
172
173
|
|
|
173
174
|
#### Static Methods
|
|
174
175
|
|
|
175
|
-
- **Channel.reset(config, payload?, options?)**: `Promise<Channel>` -
|
|
176
|
+
- **Channel.reset(config, payload?, options?)**: `Promise<Channel>` - Clear an **existing** conversation and start over on the same id: `client.deleteChannel()` first, and only once that resolves, a fresh channel opened with an `action=NONE` turn (the server replies with a welcome message). Nothing local is built until the delete succeeds, so a failed teardown leaves your current channel and conversation untouched. Rejects if the client cannot delete
|
|
177
|
+
- **Channel.open(config, payload?, options?)**: `Promise<Channel>` - Open a channel that does not exist yet with the same `action=NONE` turn, **without** deleting anything — the mount-time path for a `404` from `channelMetadata`
|
|
176
178
|
- **Channel.restore(config, options?)**: `Promise<Channel>` - Join an **existing** channel without resetting it — seeds the title from `config.channelTitle` and replays the server transcript via `rejoinSse`, preserving history / session / title. This is the join-without-wiping path behind the metadata-gated mount (F-015)
|
|
177
179
|
- **Channel.create(config)**: `Channel` - Create a channel and subscribe to its state without any SSE request (no reset, no rejoin); the first connection happens when you call `sendMessage`
|
|
178
180
|
|
|
@@ -254,7 +256,7 @@ interface RunStatus {
|
|
|
254
256
|
```
|
|
255
257
|
|
|
256
258
|
**Only a `user` run is stoppable.** `isConnecting` is true for four unrelated things — the user's own
|
|
257
|
-
turn, the
|
|
259
|
+
turn, the opening welcome run, a transcript rejoin, and an invisible nudge — and `kind` is what
|
|
258
260
|
tells them apart. `stopGeneration()` is a no-op for every kind but `user`. A `replay` (rejoining a
|
|
259
261
|
channel whose run already finished) is loading history, not generating, so it should not show a
|
|
260
262
|
run-in-progress indicator either.
|
package/dist/constants/enum.d.ts
CHANGED
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
export declare enum FetchSseAction {
|
|
2
|
+
/**
|
|
3
|
+
* @deprecated The SDK no longer sends this (F-032). It bundles "delete the channel" and "post the
|
|
4
|
+
* first message" into one request, and blobs belong to the channel that was live when they were
|
|
5
|
+
* uploaded — so the delete strips them and the accompanying `blobIds` resolve to nothing, silently.
|
|
6
|
+
* The backend now answers `400` to `RESET_CHANNEL` carrying a non-empty `blobIds`.
|
|
7
|
+
*
|
|
8
|
+
* To clear a conversation and start over on the same id, call `client.deleteChannel(customChannelId)`
|
|
9
|
+
* and then open with `action: NONE` — `Channel.reset()` does exactly that. Retained (and still
|
|
10
|
+
* accepted by the backend) so existing type references keep compiling.
|
|
11
|
+
*/
|
|
2
12
|
RESET_CHANNEL = "RESET_CHANNEL",
|
|
3
13
|
NONE = "NONE",
|
|
4
14
|
RESPONSE_TOOL_CALL_CONSENT = "RESPONSE_TOOL_CALL_CONSENT",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.d.ts","sourceRoot":"","sources":["../../src/constants/enum.ts"],"names":[],"mappings":"AAAA,oBAAY,cAAc;IACxB,aAAa,kBAAkB;IAC/B,IAAI,SAAS;IACb,0BAA0B,+BAA+B;IACzD,KAAK,UAAU;CAChB;AAED,oBAAY,SAAS;IACnB,IAAI,oBAAoB;IACxB,OAAO,mBAAmB;IAC1B,aAAa,yBAAyB;IACtC,gBAAgB,4BAA4B;IAC5C,OAAO,mBAAmB;IAC1B,aAAa,yBAAyB;IACtC,aAAa,yBAAyB;IACtC,gBAAgB,4BAA4B;IAE5C,YAAY,wBAAwB;IAGpC,sBAAsB,kCAAkC;IACxD,sBAAsB,kCAAkC;IACxD,yBAAyB,qCAAqC;IAM9D,oBAAoB,gCAAgC;IACpD,oBAAoB,gCAAgC;IACpD,uBAAuB,mCAAmC;IAC1D,SAAS,qBAAqB;IAC9B,eAAe,2BAA2B;IAC1C,kBAAkB,8BAA8B;IAChD,iBAAiB,6BAA6B;IAI9C,cAAc,0BAA0B;IACxC,iBAAiB,6BAA6B;IAE9C,oBAAoB,gCAAgC;IAIpD,iBAAiB,6BAA6B;IAI9C,cAAc,0BAA0B;IACxC,aAAa,yBAAyB;IACtC,IAAI,oBAAoB;IACxB,KAAK,qBAAqB;CAC3B;AAED,oBAAY,qBAAqB;IAC/B,UAAU,eAAe;IACzB,YAAY,iBAAiB;IAC7B,SAAS,cAAc;CACxB;AAED,oBAAY,mBAAmB;IAC7B,IAAI,SAAS;IACb,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,KAAK,UAAU;IACf,KAAK,UAAU;IACf,QAAQ,aAAa;IACrB,QAAQ,aAAa;IACrB,KAAK,UAAU;IACf,KAAK,UAAU;IACf,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,MAAM,WAAW;CAClB"}
|
|
1
|
+
{"version":3,"file":"enum.d.ts","sourceRoot":"","sources":["../../src/constants/enum.ts"],"names":[],"mappings":"AAAA,oBAAY,cAAc;IACxB;;;;;;;;;OASG;IACH,aAAa,kBAAkB;IAC/B,IAAI,SAAS;IACb,0BAA0B,+BAA+B;IACzD,KAAK,UAAU;CAChB;AAED,oBAAY,SAAS;IACnB,IAAI,oBAAoB;IACxB,OAAO,mBAAmB;IAC1B,aAAa,yBAAyB;IACtC,gBAAgB,4BAA4B;IAC5C,OAAO,mBAAmB;IAC1B,aAAa,yBAAyB;IACtC,aAAa,yBAAyB;IACtC,gBAAgB,4BAA4B;IAE5C,YAAY,wBAAwB;IAGpC,sBAAsB,kCAAkC;IACxD,sBAAsB,kCAAkC;IACxD,yBAAyB,qCAAqC;IAM9D,oBAAoB,gCAAgC;IACpD,oBAAoB,gCAAgC;IACpD,uBAAuB,mCAAmC;IAC1D,SAAS,qBAAqB;IAC9B,eAAe,2BAA2B;IAC1C,kBAAkB,8BAA8B;IAChD,iBAAiB,6BAA6B;IAI9C,cAAc,0BAA0B;IACxC,iBAAiB,6BAA6B;IAE9C,oBAAoB,gCAAgC;IAIpD,iBAAiB,6BAA6B;IAI9C,cAAc,0BAA0B;IACxC,aAAa,yBAAyB;IACtC,IAAI,oBAAoB;IACxB,KAAK,qBAAqB;CAC3B;AAED,oBAAY,qBAAqB;IAC/B,UAAU,eAAe;IACzB,YAAY,iBAAiB;IAC7B,SAAS,cAAc;CACxB;AAED,oBAAY,mBAAmB;IAC7B,IAAI,SAAS;IACb,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,KAAK,UAAU;IACf,KAAK,UAAU;IACf,QAAQ,aAAa;IACrB,QAAQ,aAAa;IACrB,KAAK,UAAU;IACf,KAAK,UAAU;IACf,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,MAAM,WAAW;CAClB"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class
|
|
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 mt(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 gt=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 se="text/event-stream",bt=1e3,pe="last-event-id";function Ae(n,t){var{signal:e,headers:s,onopen:r,onmessage:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class y 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 ut(n){return n instanceof y}class Y 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 lt(n){return n instanceof Y}class z 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 dt(n){return n instanceof z}var H=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n.NUDGE="NUDGE",n))(H||{}),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||{}),ce=(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))(ce||{});async function ht(n,t){const e=n.getReader();let s;for(;!(s=await e.read()).done;)t(s.value)}function ft(n){let t,e,s,r=!1;return function(o){t===void 0?(t=o,e=0,s=-1):t=mt(t,o);const a=t.length;let u=0;for(;e<a;){r&&(t[e]===10&&(u=++e),r=!1);let c=-1;for(;e<a&&c===-1;++e)switch(t[e]){case 58:s===-1&&(s=e-u);break;case 13:r=!0;case 10:c=e;break}if(c===-1)break;n(t.subarray(u,c),s),u=e,s=-1}u===a?t=void 0:u!==0&&(t=t.subarray(u),e-=u)}}function pt(n,t,e){let s=fe();const r=new TextDecoder;return function(o,a){if(o.length===0)e?.(s),s=fe();else if(a>0){const u=r.decode(o.subarray(0,a)),c=a+(o[a+1]===32?2:1),d=r.decode(o.subarray(c));switch(u){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 mt(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 gt=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 se="text/event-stream",bt=1e3,pe="last-event-id";function Ae(n,t){var{signal:e,headers:s,onopen:r,onmessage:i,onclose:o,onerror:a,openWhenHidden:u,fetch:c}=t,d=gt(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,v)=>{const h=Object.assign({},s);h.accept||(h.accept=se);let p;function f(){p.abort(),document.hidden||j()}u||document.addEventListener("visibilitychange",f);let T=bt,E=0;function G(){document.removeEventListener("visibilitychange",f),window.clearTimeout(E),p.abort()}e?.addEventListener("abort",()=>{G(),g()});const k=c??window.fetch,L=r??vt;async function j(){var $;p=new AbortController;try{const D=await k(n,Object.assign(Object.assign({},d),{headers:h,signal:p.signal}));await L(D),await ht(D.body,ft(pt(P=>{P?h[pe]=P:delete h[pe]},P=>{T=P},i))),o?.(),G(),g()}catch(D){if(!p.signal.aborted)try{const P=($=a?.(D))!==null&&$!==void 0?$:T;window.clearTimeout(E),E=window.setTimeout(j,P)}catch(P){G(),v(P)}}}j()})}function vt(n){const t=n.headers.get("content-type");if(!t?.startsWith(se))throw new Error(`Expected content-type to be ${se}, Actual: ${t}`)}var re=function(n,t){return re=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])},re(n,t)};function O(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");re(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function St(n,t,e,s){function r(i){return i instanceof e?i:new e(function(o){o(i)})}return new(e||(e=Promise))(function(i,o){function a(d){try{c(s.next(d))}catch(g){o(g)}}function u(d){try{c(s.throw(d))}catch(g){o(g)}}function c(d){d.done?i(d.value):r(d.value).then(a,u)}c((s=s.apply(n,t||[])).next())})}function Oe(n,t){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,r,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(d){return u([c,d])}}function u(c){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(e=0)),e;)try{if(s=1,r&&(i=c[0]&2?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return e.label++,{value:c[1],done:!1};case 5:e.label++,r=c[1],c=[0];continue;case 7:c=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){e=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){e.label=c[1];break}if(c[0]===6&&e.label<i[1]){e.label=i[1],i=c;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(c);break}i[2]&&e.ops.pop(),e.trys.pop();continue}c=t.call(n,e)}catch(d){c=[6,d],r=0}finally{s=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function M(n){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&n[t],s=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&s>=n.length&&(n=void 0),{value:n&&n[s++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function q(n,t){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var s=e.call(n),r,i=[],o;try{for(;(t===void 0||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(e=s.return)&&e.call(s)}finally{if(o)throw o.error}}return i}function K(n,t,e){if(e||arguments.length===2)for(var s=0,r=t.length,i;s<r;s++)(i||!(s in t))&&(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return n.concat(i||Array.prototype.slice.call(t))}function B(n){return this instanceof B?(this.v=n,this):new B(n)}function yt(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=e.apply(n,t||[]),r,i=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(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(T,E){i.push([h,f,T,E])>1||u(h,f)})},p&&(r[h]=p(r[h])))}function u(h,p){try{c(s[h](p))}catch(f){v(i[0][3],f)}}function c(h){h.value instanceof B?Promise.resolve(h.value.v).then(d,g):v(i[0][2],h)}function d(h){u("next",h)}function g(h){u("throw",h)}function v(h,p){h(p),i.shift(),i.length&&u(i[0][0],i[0][1])}}function wt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=n[Symbol.asyncIterator],e;return t?t.call(n):(n=typeof M=="function"?M(n):n[Symbol.iterator](),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(i){e[i]=n[i]&&function(o){return new Promise(function(a,u){o=n[i](o),r(a,u,o.done,o.value)})}}function r(i,o,a,u){Promise.resolve(u).then(function(c){i({value:c,done:a})},o)}}function b(n){return typeof n=="function"}function Pe(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 ee=Pe(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
|
|
3
3
|
`+e.map(function(s,r){return r+1+") "+s.toString()}).join(`
|
|
4
|
-
`):"",this.name="UnsubscriptionError",this.errors=e}});function V(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var R=(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=U(i),u=a.next();!u.done;u=a.next()){var c=u.value;c.remove(this)}}catch(f){t={error:f}}finally{try{u&&!u.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 ee?f.errors:[f]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var v=U(g),h=v.next();!h.done;h=v.next()){var p=h.value;try{me(p)}catch(f){o=o??[],f instanceof ee?o=K(K([],q(o)),q(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 ee(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)&&V(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&V(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),_e=R.EMPTY;function Le(n){return n instanceof R||n&&"closed"in n&&b(n.remove)&&b(n.add)&&b(n.unsubscribe)}function me(n){b(n)?n():n.unsubscribe()}var Et={Promise:void 0},Tt={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,K([n,t],q(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Me(n){Tt.setTimeout(function(){throw n})}function oe(){}function W(n){n()}var ue=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,Le(e)&&e.add(s)):s.destination=xt,s}return t.create=function(e,s,r){return new ie(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})(R),It=(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){X(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){X(s)}else X(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){X(e)}},n})(),ie=(function(n){O(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 It(i),o}return t})(ue);function X(n){Me(n)}function Ct(n){throw n}var xt={closed:!0,next:oe,error:Ct,complete:oe},le=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Q(n){return n}function At(n){return n.length===0?Q: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=Pt(t)?t:new ie(t,e,s);return W(function(){var i=r,a=i.operator,u=i.source;o.add(a?a.call(o,u):u?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 ie({next:function(a){try{t(a)}catch(u){o(u),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[le]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return At(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??Et.Promise)!==null&&t!==void 0?t:Promise}function Ot(n){return n&&b(n.next)&&b(n.error)&&b(n.complete)}function Pt(n){return n&&n instanceof ue||Ot(n)&&Le(n)}function _t(n){return b(n?.lift)}function _(n){return function(t){if(_t(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(n,t,e,s,r){return new Lt(n,t,e,s,r)}var Lt=(function(n){O(t,n);function t(e,s,r,o,i,a){var u=n.call(this,e)||this;return u.onFinalize=i,u.shouldUnsubscribe=a,u._next=s?function(c){try{s(c)}catch(d){e.error(d)}}:n.prototype._next,u._error=o?function(c){try{o(c)}catch(d){e.error(d)}finally{this.unsubscribe()}}:n.prototype._error,u._complete=r?function(){try{r()}catch(c){e.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,u}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})(ue),Mt=Pe(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),de=(function(n){O(t,n);function t(){var e=n.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return t.prototype.lift=function(e){var s=new be(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Mt},t.prototype.next=function(e){var s=this;W(function(){var r,o;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var i=U(s.currentObservers),a=i.next();!a.done;a=i.next()){var u=a.value;u.next(e)}}catch(c){r={error:c}}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;W(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;W(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?_e:(this.currentObservers=null,a.push(e),new R(function(){s.currentObservers=null,V(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){O(t,n);function t(e,s){var r=n.call(this)||this;return r.destination=e,r.source=s,r}return t.prototype.next=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.next)===null||r===void 0||r.call(s,e)},t.prototype.error=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.error)===null||r===void 0||r.call(s,e)},t.prototype.complete=function(){var e,s;(s=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||s===void 0||s.call(e)},t.prototype._subscribe=function(e){var s,r;return(r=(s=this.source)===null||s===void 0?void 0:s.subscribe(e))!==null&&r!==void 0?r:_e},t})(de),A=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s._value=e,s}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var s=n.prototype._subscribe.call(this,e);return!s.closed&&e.next(this._value),s},t.prototype.getValue=function(){var e=this,s=e.hasError,r=e.thrownError,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})(de),Ut={now:function(){return Date.now()}},Rt=(function(n){O(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(R),ve={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,K([n,t],q(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Nt=(function(n){O(t,n);function t(e,s){var r=n.call(this,e,s)||this;return r.scheduler=e,r.work=s,r.pending=!1,r}return t.prototype.schedule=function(e,s){var r;if(s===void 0&&(s=0),this.closed)return this;this.state=e;var 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,V(o,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Rt),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=Ut.now,n})(),kt=(function(n){O(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),jt=new kt(Nt);function $t(n){return n&&b(n.schedule)}function Ue(n){return n[n.length-1]}function Dt(n){return b(Ue(n))?n.pop():void 0}function Re(n){return $t(Ue(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 je(n){return b(n[le])}function $e(n){return Symbol.asyncIterator&&b(n?.[Symbol.asyncIterator])}function De(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ht(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var He=Ht();function Fe(n){return b(n?.[He])}function Be(n){return yt(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,F(e.read())];case 3:return s=i.sent(),r=s.value,o=s.done,o?[4,F(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,F(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 Ge(n){return b(n?.getReader)}function Z(n){if(n instanceof y)return n;if(n!=null){if(je(n))return Ft(n);if(Ne(n))return Bt(n);if(ke(n))return Gt(n);if($e(n))return qe(n);if(Fe(n))return qt(n);if(Ge(n))return Kt(n)}throw De(n)}function Ft(n){return new y(function(t){var e=n[le]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Bt(n){return new y(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Gt(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,Me)})}function qt(n){return new y(function(t){var e,s;try{for(var r=U(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 qe(n){return new y(function(t){Vt(n,t).catch(function(e){return t.error(e)})})}function Kt(n){return qe(Be(n))}function Vt(n,t){var e,s,r,o;return St(this,void 0,void 0,function(){var i,a;return Oe(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),e=wt(n),u.label=1;case 1:return[4,e.next()];case 2:if(s=u.sent(),!!s.done)return[3,4];if(i=s.value,t.next(i),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),r={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),s&&!s.done&&(o=e.return)?[4,o.call(e)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function C(n,t,e,s,r){s===void 0&&(s=0),r===void 0&&(r=!1);var o=t.schedule(function(){e(),r?n.add(this.schedule(null,s)):this.unsubscribe()},s);if(n.add(o),!r)return o}function Ke(n,t){return t===void 0&&(t=0),_(function(e,s){e.subscribe(N(s,function(r){return C(s,n,function(){return s.next(r)},t)},function(){return C(s,n,function(){return s.complete()},t)},function(r){return C(s,n,function(){return s.error(r)},t)}))})}function Ve(n,t){return t===void 0&&(t=0),_(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function Xt(n,t){return Z(n).pipe(Ve(t),Ke(t))}function Wt(n,t){return Z(n).pipe(Ve(t),Ke(t))}function Yt(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 C(e,t,function(){s=n[He](),C(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 Xe(n,t){if(!n)throw new Error("Iterable cannot be null");return new y(function(e){C(e,t,function(){var s=n[Symbol.asyncIterator]();C(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function Jt(n,t){return Xe(Be(n),t)}function Qt(n,t){if(n!=null){if(je(n))return Xt(n,t);if(Ne(n))return Yt(n,t);if(ke(n))return Wt(n,t);if($e(n))return Xe(n,t);if(Fe(n))return zt(n,t);if(Ge(n))return Jt(n,t)}throw De(n)}function We(n,t){return t?Qt(n,t):Z(n)}function J(n,t){return _(function(e,s){var r=0;e.subscribe(N(s,function(o){s.next(n.call(t,o,r++))}))})}var Zt=Array.isArray;function en(n,t){return Zt(t)?n.apply(void 0,K([],q(t))):n(t)}function tn(n){return J(function(t){return en(n,t)})}var nn=Array.isArray,sn=Object.getPrototypeOf,rn=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(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function cn(n){return n&&typeof n=="object"&&sn(n)===rn}function un(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function ln(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Re(n),s=Dt(n),r=an(n),o=r.args,i=r.keys;if(o.length===0)return We([],e);var a=new y(dn(o,e,i?function(u){return un(i,u)}:Q));return s?a.pipe(tn(s)):a}function dn(n,t,e){return e===void 0&&(e=Q),function(s){ye(t,function(){for(var r=n.length,o=new Array(r),i=r,a=r,u=function(d){ye(t,function(){var g=We(n[d],t),v=!1;g.subscribe(N(s,function(h){o[d]=h,v||(v=!0,a--),a||s.next(e(o.slice()))},function(){--i||s.complete()}))},s)},c=0;c<r;c++)u(c)},s)}}function ye(n,t,e){n?C(e,n,t):t()}function hn(n,t){return _(function(e,s){var r=0;e.subscribe(N(s,function(o){return n.call(t,o,r++)&&s.next(o)}))})}function fn(n){for(var t,e,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var o=(t=Re(s))!==null&&t!==void 0?t:jt,i=(e=s[0])!==null&&e!==void 0?e:null,a=s[1]||1/0;return _(function(u,c){var d=[],g=!1,v=function(f){var T=f.buffer,w=f.subs;w.unsubscribe(),V(d,f),c.next(T),g&&h()},h=function(){if(d){var f=new R;c.add(f);var T=[],w={buffer:T,subs:f};d.push(w),C(f,o,function(){return v(w)},n)}};i!==null&&i>=0?C(c,o,h,i,!0):g=!0,h();var p=N(c,function(f){var T,w,B=d.slice();try{for(var k=U(B),L=k.next();!L.done;L=k.next()){var j=L.value,$=j.buffer;$.push(f),a<=$.length&&v(j)}}catch(D){T={error:D}}finally{try{L&&!L.done&&(w=k.return)&&w.call(k)}finally{if(T)throw T.error}}},function(){for(;d?.length;)c.next(d.shift().buffer);p?.unsubscribe(),c.complete(),c.unsubscribe()},void 0,function(){return d=null});u.subscribe(p)})}function M(n,t){return t===void 0&&(t=Q),n=n??pn,_(function(e,s){var r,o=!0;e.subscribe(N(s,function(i){var a=t(i);(o||!n(r,a))&&(o=!1,r=a,s.next(i))}))})}function pn(n,t){return n===t}function mn(n){return _(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function gn(n){return _(function(t,e){Z(n).subscribe(N(e,function(){return e.complete()},oe)),!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 u=new AbortController;let c,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:u.signal,openWhenHidden:!0,onopen:async p=>{if(p.ok)c=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 E(p.status,p.statusText,f)),u.abort()}},onmessage:p=>{p.id&&(d=!0);const f=JSON.parse(p.data);c?f.traceId=c:f.requestId&&(f.traceId=f.requestId,c||(c=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:p=>{if(g)throw p;if(!d)throw a.error(p),u.abort(),p}}),()=>{g=!0,u.abort()}})}class bn{listeners={};on(t,e){this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).concat(e)})}off(t,e){this.listeners[t]&&(this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).filter(s=>s!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(s=>s(...e))}}const vn=50;class Sn{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new de;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new bn;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 E(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(u=>({sandboxName:u.sandboxName,sandboxBlueprintName:u.sandboxBlueprintName,workingDirectory:u.workingDirectory,editorServerEnabled:u.editorServerEnabled,browserEnabled:u.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 E(o.status,o.statusText,await o.text().catch(()=>{}))}runSse(t,e){return t.pipe(fn(e?.delayTime??vn),hn(s=>s.length>0),gn(this.destroy$),mn(()=>this.onRunSettled())).subscribe({next:s=>{if(!this.detached)for(const r of s)e?.onSseMessage?.(r),this.handleEvent(r)},error:s=>{this.detached||e?.onSseError?.(s)},complete:()=>{this.detached||e?.onSseCompleted?.()}})}detach(t){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),t.timeoutMs)}}onRunSettled(){this.inFlight=Math.max(0,this.inFlight-1),this.detached&&this.inFlight===0&&this.close()}close(){this.closed||(this.closed=!0,this.detachTimer&&(clearTimeout(this.detachTimer),this.detachTimer=void 0),this.destroy$.next(),this.destroy$.complete())}async uploadFile(t,e){const s=this.deriveBlobEndpoint();if(!s)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const r=new FormData;r.append("file",t),r.append("customChannelId",e);const o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const i=await fetch(s,{method:"POST",headers:o,body:r});if(!i.ok)throw new Error(`Upload failed: ${i.status} ${i.statusText}`);const a=await i.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(i){throw console.error("[AsgardServiceClient] File upload error:",i),i}}async downloadChannelHomeFile(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const r=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,o=`${s}/channel-home/download?${r}`,i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const a=await fetch(o,{method:"GET",headers:i});if(!a.ok)throw new Error(`Channel Home download failed: ${a.status} ${a.statusText}`);const u=await a.blob(),c=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] Channel Home download response:",{filename:c,size:u.size}),{blob:u,filename:c}}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 E(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 E(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 E(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,signal:r?.signal});if(!a.ok)throw new E(a.status,a.statusText,await a.text().catch(()=>{}));const u=await a.json();return{bytesWritten:(u.data??u).bytesWritten??0}}async sandboxFsRequest(t,e,s,r){const o=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(r).forEach(([a,u])=>o.searchParams.set(a,u));const i=await fetch(o.toString(),{method:s,headers:this.apiHeaders()});if(!i.ok)throw new E(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 E(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 E(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 Ye="",yn=new Set(["",".",".."]);function I(n,t){if(n===Ye){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=>yn.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const he=1e3,ze=1e4;function Ee(n){return Math.min(Math.max(1,Math.floor(n)),he)}class wn{endpoint;apiKey;customHeaders;constructor(t){this.endpoint=t.sourceSetEndpoint.replace(/\/+$/,""),this.apiKey=t.apiKey,this.customHeaders=t.customHeaders}headers(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async request(t,e,s,r,o){const i=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([u,c])=>i.searchParams.set(u,c));const a=await fetch(i.toString(),{method:e,headers:this.headers(),body:r,signal:o});if(!a.ok)throw new E(a.status,a.statusText,await a.text().catch(()=>{}));return a}async list(t,e){const s={path:I(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??ze,o=[];let i=0,a=!0,u=0;for(;;){const c=await this.list(t,{page:u,pageSize:s}),d=c.paging;if(d&&d.index!==u){i=d.total,a=!1;break}if(o.push(...c.entries),!d){a=c.entries.length<s;break}if(i=d.total,o.length>=i)break;if(o.length>=r||c.entries.length===0){a=!1;break}u+=1}return{entries:o,total:i,complete:a}}async stat(t){const s=await(await this.request("stat","GET",{path:I(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:I(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:I(t)};s?.mode!=null&&(r.mode=String(s.mode)),s?.createOnly&&(r.create_only="true");const o=new FormData;o.append("file",e instanceof Blob?e:new Blob([e]));const a=await(await this.request("file","PUT",r,o,s?.signal)).json();return{bytesWritten:(a.data??a).bytesWritten??0}}async mkdir(t,e){await this.request("mkdir","POST",{path:I(t)},void 0,e?.signal)}async remove(t){await this.request("item","DELETE",{path:I(t)})}async removeAll(t){await this.request("all","DELETE",{path:I(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:I(t),dst:I(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 En(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 te;const Tn=new Uint8Array(16);function In(){if(!te){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");te=crypto.getRandomValues.bind(crypto)}return te(Tn)}const Cn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Te={randomUUID:Cn};function xn(n,t,e){n=n||{};const s=n.random??n.rng?.()??In();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,En(s)}function Je(n,t,e){return Te.randomUUID&&!n?Te.randomUUID():xn(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===ce.CANVAS?e.template:void 0,r=s?.canvas?.html;if(!r){if(!this.messages?.has(e.messageId))return this;const c=new Map(this.messages);return c.delete(e.messageId),new m({messages:c,pendingConsent:this.pendingConsent})}const o=this.messages?.get(e.messageId),i=o?.type==="canvas"?o:void 0,a=new Map(this.messages),u={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,u),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,blobs:e.blobs,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=Je(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new m({messages:r,pendingConsent:this.pendingConsent})}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 An=new Set(["TaskCreate","TaskUpdate"]);function Qe(n){return n.toolsetName===""&&An.has(n.toolName)}function Ie(n){return typeof n=="object"&&n!==null?n:void 0}function x(n){return typeof n=="string"?n:void 0}function Ze(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},o=s.sidecar??{};if(s.toolName==="TaskCreate"){const i=Ie(o.task),a=x(i?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:x(r.subject)||x(i?.subject)||"",activeForm:x(r.activeForm),description:x(r.description),status:e.get(a)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const i=Ie(o.statusChange),a=x(r.taskId)||x(o.taskId),u=x(i?.to)||x(r.status);if(!a||!u)continue;const c=e.get(a);c&&e.set(a,{...c,status:u})}}return t.map(s=>e.get(s))}function et(n){return n.toolsetName===""&&n.toolName==="Agent"}function tt(n){return!!n}function Ce(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function nt(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 On(n){return typeof n=="string"?n:void 0}function st(n){const t=[];for(const e of n){if(e.type==="tool-call"&&et(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:On(e.parameter.description)});continue}if(e.type==="tool-call"&&tt(e.parentToolUseId)){const s=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:s,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:s,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function rt(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Qe(e));return Ze(t)}function ot(n){return nt(st(Array.from(n.messages?.values()??[])))}function it(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.id===r.id&&e.status===r.status&&e.subject===r.subject&&e.activeForm===r.activeForm&&e.description===r.description})}function Pn(n,t){return n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.toolName===r.toolName&&e.toolsetName===r.toolsetName&&e.status===r.status&&e.reason===r.reason})}function at(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.parentToolUseId===r.parentToolUseId&&e.status===r.status&&e.subagentType===r.subagentType&&e.description===r.description&&e.summary===r.summary&&Pn(e.tools,r.tools)})}function ct(n){const t=new A([]),e=new A([]),s=new R;return s.add(n.pipe(J(rt),M(it)).subscribe(t)),s.add(n.pipe(J(ot),M(at)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function ae(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 ne={kind:null,stopPhase:"idle"},_n=1e4;function Ln(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class G{client;customChannelId;customMessageId;joinRunState;isConnecting$;runStatusSubject;conversation$;channelTitleSubject;promptSuggestionSubject;sandboxPhaseSubject;launchedSandboxesSubject;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 A(!1),this.runStatusSubject=new A(ne),this.conversation$=new A(t.conversation),this.channelTitleSubject=new A(t.channelTitle??null),this.promptSuggestionSubject=new A(null),this.sandboxPhaseSubject=new A("idle"),this.launchedSandboxesSubject=new A(ae(t.launchedSandboxes??[])),this.derivedStores=ct(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(Ln)),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=ae(t);this.pendingLaunches=this.pendingLaunches.filter(s=>!e.some(r=>r.sandboxName===s)),this.launchedSandboxesSubject.next(e)}dropSandbox(t){const e=this.launchedSandboxesSubject.value,s=e.filter(r=>r.sandboxName!==t);s.length!==e.length&&this.launchedSandboxesSubject.next(s)}noteSandboxLaunch(t){this.pendingLaunches.includes(t)||(this.pendingLaunches=[...this.pendingLaunches,t]),this.refetchMetadata()}async refetchMetadata(){if(!this.client.channelMetadata)return;const t=await this.client.channelMetadata(this.customChannelId);t&&this.applyLaunchedSandboxes(t.launchedSandboxes)}setChannelTitle(t){this.channelTitleSubject.next(t)}static create(t){const e=new G(t);return e.subscribe(),e}static async reset(t,e,s,r){const o=new G(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 G(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(o){throw r.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,s,r,o,i,a,u,c])=>({isConnecting:t,conversation:e,tasks:s,subagents:r,channelTitle:o,promptSuggestion:i,sandboxPhase:a,launchedSandboxes:u,runStatus:c}))).subscribe(this.statesObserver)}resolvePayload(t){if(typeof t=="function")try{return t()}catch(e){throw new Error(`Failed to resolve payload function: ${e instanceof Error?e.message:String(e)}`)}return t}updateSandboxPhase(t){switch(t){case l.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case l.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case l.INIT:case l.ERROR:this.sandboxPhaseSubject.next("idle");break}}buildRunHandlers(t,e,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(ne),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:H.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 Y(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new z(r.processId));this.clearPromptSuggestion();const o=t.text.trim(),i=t.customMessageId??Je();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:H.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:H.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 Y(s));const r=this.conversation$.value.pendingConsent;return r?Promise.reject(new z(r.processId)):this.fetchSse("nudge",{action:H.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t)}async stopGeneration(t){const e=this.runStatusSubject.value;if(!(!this.currentRun||e.kind!=="user")&&!(e.stopPhase!=="idle"&&!t?.force)){if(!this.client.suspendChannel){this.abortConnection();return}this.clearForceStopTimer(),this.runStatusSubject.next({...e,stopPhase:"stopping"});try{await this.client.suspendChannel(this.customChannelId,{requestId:e.requestId,force:t?.force})}catch(s){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),s}this.armForceStopTimer()}}armForceStopTimer(){this.clearForceStopTimer(),this.forceStopTimer=setTimeout(()=>{this.forceStopTimer=void 0;const t=this.runStatusSubject.value;t.stopPhase==="stopping"&&this.runStatusSubject.next({...t,stopPhase:"force-stoppable"})},_n)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(ne),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 Mn(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=Sn;exports.AsgardSourceSetClient=wn;exports.Channel=G;exports.ChannelAwaitingConsentError=z;exports.ChannelBusyError=Y;exports.Conversation=m;exports.EventType=l;exports.FetchSseAction=H;exports.HttpError=E;exports.MessageTemplateType=ce;exports.SOURCE_SET_DEFAULT_MAX_ENTRIES=ze;exports.SOURCE_SET_MAX_PAGE_SIZE=he;exports.SOURCE_SET_VOLUME_ROOT=Ye;exports.ToolCallConsentResult=xe;exports.assertVolumePath=I;exports.conversationToSubagentEvents=st;exports.createDerivedStores=ct;exports.deriveSubagents=ot;exports.deriveTasks=rt;exports.isAgentTool=et;exports.isChannelAwaitingConsentError=dt;exports.isChannelBusyError=lt;exports.isHttpError=ut;exports.isSubagentChildTool=tt;exports.isTaskTool=Qe;exports.reconcileLaunched=ae;exports.reduceSubagents=nt;exports.reduceTaskEvents=Ze;exports.resolveSandboxUri=Mn;exports.subagentsEqual=at;exports.tasksEqual=it;
|
|
4
|
+
`):"",this.name="UnsubscriptionError",this.errors=e}});function V(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var R=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,s,r,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=M(o),u=a.next();!u.done;u=a.next()){var c=u.value;c.remove(this)}}catch(f){t={error:f}}finally{try{u&&!u.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else o.remove(this);var d=this.initialTeardown;if(b(d))try{d()}catch(f){i=f instanceof ee?f.errors:[f]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var v=M(g),h=v.next();!h.done;h=v.next()){var p=h.value;try{me(p)}catch(f){i=i??[],f instanceof ee?i=K(K([],q(i)),q(f.errors)):i.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(i)throw new ee(i)}},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)&&V(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&V(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),_e=R.EMPTY;function Le(n){return n instanceof R||n&&"closed"in n&&b(n.remove)&&b(n.add)&&b(n.unsubscribe)}function me(n){b(n)?n():n.unsubscribe()}var Et={Promise:void 0},Tt={setTimeout:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setTimeout.apply(void 0,K([n,t],q(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Ue(n){Tt.setTimeout(function(){throw n})}function ie(){}function W(n){n()}var ue=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s.isStopped=!1,e?(s.destination=e,Le(e)&&e.add(s)):s.destination=xt,s}return t.create=function(e,s,r){return new oe(e,s,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(R),It=(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){X(s)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(s){X(s)}else X(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){X(e)}},n})(),oe=(function(n){O(t,n);function t(e,s,r){var i=n.call(this)||this,o;return b(e)||!e?o={next:e??void 0,error:s??void 0,complete:r??void 0}:o=e,i.destination=new It(o),i}return t})(ue);function X(n){Ue(n)}function Ct(n){throw n}var xt={closed:!0,next:ie,error:Ct,complete:ie},le=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Q(n){return n}function At(n){return n.length===0?Q:n.length===1?n[0]:function(e){return n.reduce(function(s,r){return r(s)},e)}}var w=(function(){function n(t){t&&(this._subscribe=t)}return n.prototype.lift=function(t){var e=new n;return e.source=this,e.operator=t,e},n.prototype.subscribe=function(t,e,s){var r=this,i=Pt(t)?t:new oe(t,e,s);return W(function(){var o=r,a=o.operator,u=o.source;i.add(a?a.call(i,u):u?r._subscribe(i):r._trySubscribe(i))}),i},n.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},n.prototype.forEach=function(t,e){var s=this;return e=ge(e),new e(function(r,i){var o=new oe({next:function(a){try{t(a)}catch(u){i(u),o.unsubscribe()}},error:i,complete:r});s.subscribe(o)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[le]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return At(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=ge(t),new t(function(s,r){var i;e.subscribe(function(o){return i=o},function(o){return r(o)},function(){return s(i)})})},n.create=function(t){return new n(t)},n})();function ge(n){var t;return(t=n??Et.Promise)!==null&&t!==void 0?t:Promise}function Ot(n){return n&&b(n.next)&&b(n.error)&&b(n.complete)}function Pt(n){return n&&n instanceof ue||Ot(n)&&Le(n)}function _t(n){return b(n?.lift)}function _(n){return function(t){if(_t(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(n,t,e,s,r){return new Lt(n,t,e,s,r)}var Lt=(function(n){O(t,n);function t(e,s,r,i,o,a){var u=n.call(this,e)||this;return u.onFinalize=o,u.shouldUnsubscribe=a,u._next=s?function(c){try{s(c)}catch(d){e.error(d)}}:n.prototype._next,u._error=i?function(c){try{i(c)}catch(d){e.error(d)}finally{this.unsubscribe()}}:n.prototype._error,u._complete=r?function(){try{r()}catch(c){e.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,u}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})(ue),Ut=Pe(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),de=(function(n){O(t,n);function t(){var e=n.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return t.prototype.lift=function(e){var s=new be(this,this);return s.operator=e,s},t.prototype._throwIfClosed=function(){if(this.closed)throw new Ut},t.prototype.next=function(e){var s=this;W(function(){var r,i;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var o=M(s.currentObservers),a=o.next();!a.done;a=o.next()){var u=a.value;u.next(e)}}catch(c){r={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var s=this;W(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;W(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var s=e.observers;s.length;)s.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(e){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,e)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var s=this,r=this,i=r.hasError,o=r.isStopped,a=r.observers;return i||o?_e:(this.currentObservers=null,a.push(e),new R(function(){s.currentObservers=null,V(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var s=this,r=s.hasError,i=s.thrownError,o=s.isStopped;r?e.error(i):o&&e.complete()},t.prototype.asObservable=function(){var e=new w;return e.source=this,e},t.create=function(e,s){return new be(e,s)},t})(w),be=(function(n){O(t,n);function t(e,s){var r=n.call(this)||this;return r.destination=e,r.source=s,r}return t.prototype.next=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.next)===null||r===void 0||r.call(s,e)},t.prototype.error=function(e){var s,r;(r=(s=this.destination)===null||s===void 0?void 0:s.error)===null||r===void 0||r.call(s,e)},t.prototype.complete=function(){var e,s;(s=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||s===void 0||s.call(e)},t.prototype._subscribe=function(e){var s,r;return(r=(s=this.source)===null||s===void 0?void 0:s.subscribe(e))!==null&&r!==void 0?r:_e},t})(de),A=(function(n){O(t,n);function t(e){var s=n.call(this)||this;return s._value=e,s}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var s=n.prototype._subscribe.call(this,e);return!s.closed&&e.next(this._value),s},t.prototype.getValue=function(){var e=this,s=e.hasError,r=e.thrownError,i=e._value;if(s)throw r;return this._throwIfClosed(),i},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(de),Mt={now:function(){return Date.now()}},Rt=(function(n){O(t,n);function t(e,s){return n.call(this)||this}return t.prototype.schedule=function(e,s){return this},t})(R),ve={setInterval:function(n,t){for(var e=[],s=2;s<arguments.length;s++)e[s-2]=arguments[s];return setInterval.apply(void 0,K([n,t],q(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},Nt=(function(n){O(t,n);function t(e,s){var r=n.call(this,e,s)||this;return r.scheduler=e,r.work=s,r.pending=!1,r}return t.prototype.schedule=function(e,s){var r;if(s===void 0&&(s=0),this.closed)return this;this.state=e;var i=this.id,o=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(o,i,s)),this.pending=!0,this.delay=s,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(o,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,i;try{this.work(e)}catch(o){r=!0,i=o||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,s=e.id,r=e.scheduler,i=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,V(i,this),s!=null&&(this.id=this.recycleAsyncId(r,s,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(Rt),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=Mt.now,n})(),kt=(function(n){O(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),jt=new kt(Nt);function $t(n){return n&&b(n.schedule)}function Me(n){return n[n.length-1]}function Dt(n){return b(Me(n))?n.pop():void 0}function Re(n){return $t(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 je(n){return b(n[le])}function $e(n){return Symbol.asyncIterator&&b(n?.[Symbol.asyncIterator])}function De(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ht(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var He=Ht();function Fe(n){return b(n?.[He])}function Be(n){return yt(this,arguments,function(){var e,s,r,i;return Oe(this,function(o){switch(o.label){case 0:e=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,B(e.read())];case 3:return s=o.sent(),r=s.value,i=s.done,i?[4,B(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,B(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function Ge(n){return b(n?.getReader)}function Z(n){if(n instanceof w)return n;if(n!=null){if(je(n))return Ft(n);if(Ne(n))return Bt(n);if(ke(n))return Gt(n);if($e(n))return qe(n);if(Fe(n))return qt(n);if(Ge(n))return Kt(n)}throw De(n)}function Ft(n){return new w(function(t){var e=n[le]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Bt(n){return new w(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Gt(n){return new w(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,Ue)})}function qt(n){return new w(function(t){var e,s;try{for(var r=M(n),i=r.next();!i.done;i=r.next()){var o=i.value;if(t.next(o),t.closed)return}}catch(a){e={error:a}}finally{try{i&&!i.done&&(s=r.return)&&s.call(r)}finally{if(e)throw e.error}}t.complete()})}function qe(n){return new w(function(t){Vt(n,t).catch(function(e){return t.error(e)})})}function Kt(n){return qe(Be(n))}function Vt(n,t){var e,s,r,i;return St(this,void 0,void 0,function(){var o,a;return Oe(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),e=wt(n),u.label=1;case 1:return[4,e.next()];case 2:if(s=u.sent(),!!s.done)return[3,4];if(o=s.value,t.next(o),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),r={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),s&&!s.done&&(i=e.return)?[4,i.call(e)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function C(n,t,e,s,r){s===void 0&&(s=0),r===void 0&&(r=!1);var i=t.schedule(function(){e(),r?n.add(this.schedule(null,s)):this.unsubscribe()},s);if(n.add(i),!r)return i}function Ke(n,t){return t===void 0&&(t=0),_(function(e,s){e.subscribe(N(s,function(r){return C(s,n,function(){return s.next(r)},t)},function(){return C(s,n,function(){return s.complete()},t)},function(r){return C(s,n,function(){return s.error(r)},t)}))})}function Ve(n,t){return t===void 0&&(t=0),_(function(e,s){s.add(n.schedule(function(){return e.subscribe(s)},t))})}function Xt(n,t){return Z(n).pipe(Ve(t),Ke(t))}function Wt(n,t){return Z(n).pipe(Ve(t),Ke(t))}function Yt(n,t){return new w(function(e){var s=0;return t.schedule(function(){s===n.length?e.complete():(e.next(n[s++]),e.closed||this.schedule())})})}function zt(n,t){return new w(function(e){var s;return C(e,t,function(){s=n[He](),C(e,t,function(){var r,i,o;try{r=s.next(),i=r.value,o=r.done}catch(a){e.error(a);return}o?e.complete():e.next(i)},0,!0)}),function(){return b(s?.return)&&s.return()}})}function Xe(n,t){if(!n)throw new Error("Iterable cannot be null");return new w(function(e){C(e,t,function(){var s=n[Symbol.asyncIterator]();C(e,t,function(){s.next().then(function(r){r.done?e.complete():e.next(r.value)})},0,!0)})})}function Jt(n,t){return Xe(Be(n),t)}function Qt(n,t){if(n!=null){if(je(n))return Xt(n,t);if(Ne(n))return Yt(n,t);if(ke(n))return Wt(n,t);if($e(n))return Xe(n,t);if(Fe(n))return zt(n,t);if(Ge(n))return Jt(n,t)}throw De(n)}function We(n,t){return t?Qt(n,t):Z(n)}function J(n,t){return _(function(e,s){var r=0;e.subscribe(N(s,function(i){s.next(n.call(t,i,r++))}))})}var Zt=Array.isArray;function en(n,t){return Zt(t)?n.apply(void 0,K([],q(t))):n(t)}function tn(n){return J(function(t){return en(n,t)})}var nn=Array.isArray,sn=Object.getPrototypeOf,rn=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(s){return t[s]}),keys:e}}}return{args:n,keys:null}}function cn(n){return n&&typeof n=="object"&&sn(n)===rn}function un(n,t){return n.reduce(function(e,s,r){return e[s]=t[r],e},{})}function ln(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Re(n),s=Dt(n),r=an(n),i=r.args,o=r.keys;if(i.length===0)return We([],e);var a=new w(dn(i,e,o?function(u){return un(o,u)}:Q));return s?a.pipe(tn(s)):a}function dn(n,t,e){return e===void 0&&(e=Q),function(s){ye(t,function(){for(var r=n.length,i=new Array(r),o=r,a=r,u=function(d){ye(t,function(){var g=We(n[d],t),v=!1;g.subscribe(N(s,function(h){i[d]=h,v||(v=!0,a--),a||s.next(e(i.slice()))},function(){--o||s.complete()}))},s)},c=0;c<r;c++)u(c)},s)}}function ye(n,t,e){n?C(e,n,t):t()}function hn(n,t){return _(function(e,s){var r=0;e.subscribe(N(s,function(i){return n.call(t,i,r++)&&s.next(i)}))})}function fn(n){for(var t,e,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var i=(t=Re(s))!==null&&t!==void 0?t:jt,o=(e=s[0])!==null&&e!==void 0?e:null,a=s[1]||1/0;return _(function(u,c){var d=[],g=!1,v=function(f){var T=f.buffer,E=f.subs;E.unsubscribe(),V(d,f),c.next(T),g&&h()},h=function(){if(d){var f=new R;c.add(f);var T=[],E={buffer:T,subs:f};d.push(E),C(f,i,function(){return v(E)},n)}};o!==null&&o>=0?C(c,i,h,o,!0):g=!0,h();var p=N(c,function(f){var T,E,G=d.slice();try{for(var k=M(G),L=k.next();!L.done;L=k.next()){var j=L.value,$=j.buffer;$.push(f),a<=$.length&&v(j)}}catch(D){T={error:D}}finally{try{L&&!L.done&&(E=k.return)&&E.call(k)}finally{if(T)throw T.error}}},function(){for(;d?.length;)c.next(d.shift().buffer);p?.unsubscribe(),c.complete(),c.unsubscribe()},void 0,function(){return d=null});u.subscribe(p)})}function U(n,t){return t===void 0&&(t=Q),n=n??pn,_(function(e,s){var r,i=!0;e.subscribe(N(s,function(o){var a=t(o);(i||!n(r,a))&&(i=!1,r=a,s.next(o))}))})}function pn(n,t){return n===t}function mn(n){return _(function(t,e){try{t.subscribe(e)}finally{e.add(n)}})}function gn(n){return _(function(t,e){Z(n).subscribe(N(e,function(){return e.complete()},ie)),!e.closed&&t.subscribe(e)})}function we(n){const{endpoint:t,apiKey:e,payload:s,debugMode:r,customHeaders:i}=n,o=n.method??"POST";return new w(a=>{const u=new AbortController;let c,d=!1,g=!1;const v={"Content-Type":"application/json",...i};e&&(v["X-API-KEY"]=e);const h=new URL(t);return r&&h.searchParams.set("is_debug","true"),Ae(h.toString(),{method:o,headers:v,body:o==="POST"&&s?JSON.stringify(s):void 0,signal:u.signal,openWhenHidden:!0,onopen:async p=>{if(p.ok)c=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 y(p.status,p.statusText,f)),u.abort()}},onmessage:p=>{p.id&&(d=!0);const f=JSON.parse(p.data);c?f.traceId=c:f.requestId&&(f.traceId=f.requestId,c||(c=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:p=>{if(g)throw p;if(!d)throw a.error(p),u.abort(),p}}),()=>{g=!0,u.abort()}})}class bn{listeners={};on(t,e){this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).concat(e)})}off(t,e){this.listeners[t]&&(this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).filter(s=>s!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(s=>s(...e))}}const vn=50;class Sn{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new de;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new bn;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 i=await fetch(s.toString(),{method:"GET",headers:r});if(i.status===404)return null;if(!i.ok)throw new y(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.json(),a=o.data??o;return{title:a.title??null,runState:a.runState??"IDLE",lastActivityAt:a.lastActivityAt,launchedSandboxes:(a.launchedSandboxes??[]).map(u=>({sandboxName:u.sandboxName,sandboxBlueprintName:u.sandboxBlueprintName,workingDirectory:u.workingDirectory,editorServerEnabled:u.editorServerEnabled,browserEnabled:u.browserEnabled}))}}deriveSuspendEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/message/suspend`:null}async suspendChannel(t,e){const s=this.deriveSuspendEndpoint();if(!s)throw new Error("Unable to derive channel suspend endpoint. Please provide botProviderEndpoint in config.");const r=new URL(s);r.searchParams.set("custom_channel_id",t),e?.requestId&&r.searchParams.set("request_id",e.requestId),e?.force&&r.searchParams.set("force","true");const i=await fetch(r.toString(),{method:"POST",headers:this.apiHeaders()});if(!(i.ok||i.status===404))throw new y(i.status,i.statusText,await i.text().catch(()=>{}))}deriveChannelEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel`:null}async deleteChannel(t){const e=this.deriveChannelEndpoint();if(!e)throw new Error("Unable to derive channel endpoint. Please provide botProviderEndpoint in config.");const s=new URL(e);s.searchParams.set("custom_channel_id",t);const r=await fetch(s.toString(),{method:"DELETE",headers:this.apiHeaders()});if(!r.ok)throw new y(r.status,r.statusText,await r.text().catch(()=>{}))}runSse(t,e){return t.pipe(fn(e?.delayTime??vn),hn(s=>s.length>0),gn(this.destroy$),mn(()=>this.onRunSettled())).subscribe({next:s=>{if(!this.detached)for(const r of s)e?.onSseMessage?.(r),this.handleEvent(r)},error:s=>{this.detached||e?.onSseError?.(s)},complete:()=>{this.detached||e?.onSseCompleted?.()}})}detach(t){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),t.timeoutMs)}}onRunSettled(){this.inFlight=Math.max(0,this.inFlight-1),this.detached&&this.inFlight===0&&this.close()}close(){this.closed||(this.closed=!0,this.detachTimer&&(clearTimeout(this.detachTimer),this.detachTimer=void 0),this.destroy$.next(),this.destroy$.complete())}async uploadFile(t,e){const s=this.deriveBlobEndpoint();if(!s)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const r=new FormData;r.append("file",t),r.append("customChannelId",e);const i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const o=await fetch(s,{method:"POST",headers:i,body:r});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const a=await o.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(o){throw console.error("[AsgardServiceClient] File upload error:",o),o}}async downloadChannelHomeFile(t,e){const s=this.getBaseEndpoint();if(!s)throw new Error("Unable to derive channel-home download endpoint. Please provide botProviderEndpoint in config.");const r=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,i=`${s}/channel-home/download?${r}`,o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const a=await fetch(i,{method:"GET",headers:o});if(!a.ok)throw new Error(`Channel Home download failed: ${a.status} ${a.statusText}`);const u=await a.blob(),c=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] Channel Home download response:",{filename:c,size:u.size}),{blob:u,filename:c}}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 i=await fetch(s,{method:"POST",headers:r});if(!i.ok)throw new y(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.json(),a=o.data?.openURL??o.openURL;if(!a)throw new Error("Sandbox browser open-url response did not contain an openURL.");return a}deriveSandboxFsEndpoint(t){const e=this.getBaseEndpoint();if(!e)throw new Error("Unable to derive sandbox fs endpoint. Please provide botProviderEndpoint in config.");return`${e}/sandbox/${encodeURIComponent(t)}/fs`}apiHeaders(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async sandboxFsList(t,e){const 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 y(r.status,r.statusText,await r.text().catch(()=>{}));const i=await r.json(),o=i.data??i;return{entries:o.entries??[],truncated:o.truncated??!1}}async sandboxFsRead(t,e,s){const r=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);r.searchParams.set("path",e),s?.offsetBytes!=null&&r.searchParams.set("offset_bytes",String(s.offsetBytes)),s?.limitBytes!=null&&r.searchParams.set("limit_bytes",String(s.limitBytes));const i=await fetch(r.toString(),{method:"GET",headers:this.apiHeaders()});if(!i.ok)throw new y(i.status,i.statusText,await i.text().catch(()=>{}));const o=await i.blob(),a=i.headers.get("X-Total-Bytes");return{content:o,totalBytes:a!=null?Number(a):o.size,truncated:i.headers.get("X-Truncated")==="true"}}async sandboxFsWrite(t,e,s,r){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/file`);i.searchParams.set("path",e),r?.mode!=null&&i.searchParams.set("mode",String(r.mode)),r?.createOnly&&i.searchParams.set("create_only","true");const o=new FormData;o.append("file",s instanceof Blob?s:new Blob([s]));const a=await fetch(i.toString(),{method:"PUT",headers:this.apiHeaders(),body:o,signal:r?.signal});if(!a.ok)throw new y(a.status,a.statusText,await a.text().catch(()=>{}));const u=await a.json();return{bytesWritten:(u.data??u).bytesWritten??0}}async sandboxFsRequest(t,e,s,r){const i=new URL(`${this.deriveSandboxFsEndpoint(t)}/${e}`);Object.entries(r).forEach(([a,u])=>i.searchParams.set(a,u));const o=await fetch(i.toString(),{method:s,headers:this.apiHeaders()});if(!o.ok)throw new y(o.status,o.statusText,await o.text().catch(()=>{}));return o.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 y(r.status,r.statusText,await r.text().catch(()=>{}));const i=await r.json(),o=i.data??i;return{exists:o.exists??!1,isDir:o.isDir??!1,sizeBytes:o.sizeBytes??0,mtimeUnix:o.mtimeUnix??0,mode:o.mode??0,etag:o.etag}}async sandboxFsMkdir(t,e){await this.sandboxFsRequest(t,"mkdir","POST",{path:e})}async sandboxFsRemove(t,e){await this.sandboxFsRequest(t,"item","DELETE",{path:e})}async sandboxFsRemoveAll(t,e){await this.sandboxFsRequest(t,"all","DELETE",{path:e})}async sandboxFsCopy(t,e,s,r){const i={src:e,dst:s};r?.overwrite&&(i.overwrite="true");const o=await this.sandboxFsRequest(t,"copy","POST",i);return{bytesCopied:(o?.data??o)?.bytesCopied??0}}async sandboxFsMove(t,e,s,r){const i={src:e,dst:s};r?.overwrite&&(i.overwrite="true"),await this.sandboxFsRequest(t,"move","POST",i)}sandboxFsWatch(t,e){const s=new URL(`${this.deriveSandboxFsEndpoint(t)}/watch`);return s.searchParams.set("path",e),new w(r=>{const i=new AbortController;return Ae(s.toString(),{headers:this.apiHeaders(),signal:i.signal,openWhenHidden:!0,onopen:async o=>{if(!o.ok){const a=await o.text().catch(()=>{});r.error(new y(o.status,o.statusText,a)),i.abort()}},onmessage:o=>{o.event==="change"&&r.next(JSON.parse(o.data))},onclose:()=>r.complete(),onerror:o=>{throw r.error(o),i.abort(),o}}),()=>i.abort()})}deriveBlobEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/blob`:null}getBaseEndpoint(){let t=this.botProviderEndpoint;return!t&&this.endpoint&&(t=this.endpoint.replace("/message/sse","")),t?t.replace(/\/+$/,""):null}}const Ye="",yn=new Set(["",".",".."]);function I(n,t){if(n===Ye){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=>yn.has(e)))throw new Error(`SourceSet volume path must not contain empty, "." or ".." segments: "${n}".`);return n}const he=1e3,ze=1e4;function Ee(n){return Math.min(Math.max(1,Math.floor(n)),he)}class wn{endpoint;apiKey;customHeaders;constructor(t){this.endpoint=t.sourceSetEndpoint.replace(/\/+$/,""),this.apiKey=t.apiKey,this.customHeaders=t.customHeaders}headers(){const t={...this.customHeaders};return this.apiKey&&(t["X-API-KEY"]=this.apiKey),t}async request(t,e,s,r,i){const o=new URL(`${this.endpoint}/${t}`);Object.entries(s).forEach(([u,c])=>o.searchParams.set(u,c));const a=await fetch(o.toString(),{method:e,headers:this.headers(),body:r,signal:i});if(!a.ok)throw new y(a.status,a.statusText,await a.text().catch(()=>{}));return a}async list(t,e){const s={path:I(t,{allowRoot:!0})};e?.page!=null&&(s.page=String(e.page)),e?.pageSize!=null&&(s.page_size=String(Ee(e.pageSize)));const i=await(await this.request("list","GET",s)).json(),o=i.data??i;return{entries:o.entries??[],paging:o.paging??i.paging??null}}async listAll(t,e){const s=Ee(e?.pageSize??he),r=e?.maxEntries??ze,i=[];let o=0,a=!0,u=0;for(;;){const c=await this.list(t,{page:u,pageSize:s}),d=c.paging;if(d&&d.index!==u){o=d.total,a=!1;break}if(i.push(...c.entries),!d){a=c.entries.length<s;break}if(o=d.total,i.length>=o)break;if(i.length>=r||c.entries.length===0){a=!1;break}u+=1}return{entries:i,total:o,complete:a}}async stat(t){const s=await(await this.request("stat","GET",{path:I(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:I(t)};e?.offsetBytes!=null&&(s.offset_bytes=String(e.offsetBytes)),e?.limitBytes!=null&&(s.limit_bytes=String(e.limitBytes));const r=await this.request("file","GET",s),i=await r.blob(),o=r.headers.get("X-Total-Bytes");return{content:i,totalBytes:o!=null?Number(o):i.size,truncated:r.headers.get("X-Truncated")==="true"}}async write(t,e,s){const r={path:I(t)};s?.mode!=null&&(r.mode=String(s.mode)),s?.createOnly&&(r.create_only="true");const i=new FormData;i.append("file",e instanceof Blob?e:new Blob([e]));const a=await(await this.request("file","PUT",r,i,s?.signal)).json();return{bytesWritten:(a.data??a).bytesWritten??0}}async mkdir(t,e){await this.request("mkdir","POST",{path:I(t)},void 0,e?.signal)}async remove(t){await this.request("item","DELETE",{path:I(t)})}async removeAll(t){await this.request("all","DELETE",{path:I(t)})}async copy(t,e,s){const r=this.copyMoveQuery(t,e,s),o=await(await this.request("copy","POST",r)).json();return{bytesCopied:(o.data??o).bytesCopied??0}}async move(t,e,s){await this.request("move","POST",this.copyMoveQuery(t,e,s))}copyMoveQuery(t,e,s){const r={src:I(t),dst:I(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 En(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 te;const Tn=new Uint8Array(16);function In(){if(!te){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");te=crypto.getRandomValues.bind(crypto)}return te(Tn)}const Cn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Te={randomUUID:Cn};function xn(n,t,e){n=n||{};const s=n.random??n.rng?.()??In();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,En(s)}function Je(n,t,e){return Te.randomUUID&&!n?Te.randomUUID():xn(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,i=new Map(this.messages);return i.set(e.messageId,{type:"bot",eventType:l.MESSAGE_DELTA,isTyping:!0,typingText:`${r?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??r?.traceId,raw:r?.raw??""}),new m({messages:i,pendingConsent:this.pendingConsent})}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,i=new Map(this.messages),o={type:"thinking",messageId:e.messageId,text:`${r?.text??""}${e.text}`,isThinking:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,o),new m({messages:i,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,i=new Map(this.messages),o={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,o),new m({messages:i,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,i=new Map(this.messages),o={type:"canvas",messageId:e.messageId,html:`${r?.html??""}${e.text}`,title:r?.title,isDrawing:!0,time:r?.time??new Date,traceId:t.traceId??r?.traceId};return i.set(e.messageId,o),new m({messages:i,pendingConsent:this.pendingConsent})}onCanvasComplete(t){const e=t.fact.messageCanvasComplete.message;if(e.parentToolUseId)return this;const s=e.template?.type===ce.CANVAS?e.template:void 0,r=s?.canvas?.html;if(!r){if(!this.messages?.has(e.messageId))return this;const c=new Map(this.messages);return c.delete(e.messageId),new m({messages:c,pendingConsent:this.pendingConsent})}const i=this.messages?.get(e.messageId),o=i?.type==="canvas"?i:void 0,a=new Map(this.messages),u={type:"canvas",messageId:e.messageId,html:r,title:s?.title,isDrawing:!1,time:o?.time??new Date,traceId:t.traceId??o?.traceId};return a.set(e.messageId,u),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),i={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,blobs:e.blobs,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return r.set(e.messageId,i),new m({messages:r,pendingConsent:this.pendingConsent})}onMessageError(t){const e=Je(),s=t.fact.runError.error,r=new Map(this.messages);return r.set(e,{type:"error",eventType:l.ERROR,messageId:e,error:s,time:new Date,traceId:t.traceId}),new m({messages:r,pendingConsent:this.pendingConsent})}onToolCallStart(t){const e=t.fact.toolCallStart,s=new Map(this.messages),r=`${e.processId}-${e.callSeq}`;if(this.isTerminalToolCall(this.messages?.get(r)))return this;const i={type:"tool-call",eventType:l.TOOL_CALL_START,messageId:r,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,isComplete:!1,time:new Date,traceId:t.traceId};return s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent})}onToolCallComplete(t){const e=t.fact.toolCallComplete,s=new Map(this.messages),r=`${e.processId}-${e.callSeq}`,i=s.get(r);if(i?.type==="tool-call"){const o={...i,eventType:l.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??i.traceId};s.set(r,o)}else{const o={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,o)}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`,i={type:"subagent",messageId:r,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return s.delete(r),s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent})}onSubagentComplete(t){const e=t.fact.subagentComplete,s=new Map(this.messages),r=`subagent:${e.parentToolUseId}:complete`,i={type:"subagent",messageId:r,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return s.delete(r),s.set(r,i),new m({messages:s,pendingConsent:this.pendingConsent})}}const An=new Set(["TaskCreate","TaskUpdate"]);function Qe(n){return n.toolsetName===""&&An.has(n.toolName)}function Ie(n){return typeof n=="object"&&n!==null?n:void 0}function x(n){return typeof n=="string"?n:void 0}function Ze(n){const t=[],e=new Map;for(const s of n){const r=s.parameter??{},i=s.sidecar??{};if(s.toolName==="TaskCreate"){const o=Ie(i.task),a=x(o?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:x(r.subject)||x(o?.subject)||"",activeForm:x(r.activeForm),description:x(r.description),status:e.get(a)?.status??"pending"})}else if(s.toolName==="TaskUpdate"){const o=Ie(i.statusChange),a=x(r.taskId)||x(i.taskId),u=x(o?.to)||x(r.status);if(!a||!u)continue;const c=e.get(a);c&&e.set(a,{...c,status:u})}}return t.map(s=>e.get(s))}function et(n){return n.toolsetName===""&&n.toolName==="Agent"}function tt(n){return!!n}function Ce(n){n.status!=="running"&&(n.status="running",n.summary=void 0)}function nt(n){const t=[],e=new Map,s=new Map,r=i=>(e.has(i)||(t.push(i),e.set(i,{status:"running"}),s.set(i,new Map)),e.get(i));for(const i of n)switch(i.kind){case"agentStart":{const o=r(i.toolUseId);i.description&&!o.description&&(o.description=i.description);break}case"subagentStart":{const o=r(i.parentToolUseId);o.agentId=i.agentId??o.agentId,o.subagentType=i.subagentType??o.subagentType,o.description=i.description??o.description,Ce(o);break}case"toolStart":{Ce(r(i.parentToolUseId)),s.get(i.parentToolUseId).set(i.toolUseId,{toolsetName:i.toolsetName,toolName:i.toolName,parameter:i.parameter??{},reason:i.reason,status:"running"});break}case"toolComplete":{const o=s.get(i.parentToolUseId)?.get(i.toolUseId);o&&(o.status=i.isError?"error":"completed");break}case"subagentComplete":{const o=r(i.parentToolUseId);o.status=i.status,o.summary=i.summary;break}}return t.map(i=>({parentToolUseId:i,...e.get(i),tools:Array.from(s.get(i).values())}))}function On(n){return typeof n=="string"?n:void 0}function st(n){const t=[];for(const e of n){if(e.type==="tool-call"&&et(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:On(e.parameter.description)});continue}if(e.type==="tool-call"&&tt(e.parentToolUseId)){const s=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:s,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:s,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function rt(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Qe(e));return Ze(t)}function it(n){return nt(st(Array.from(n.messages?.values()??[])))}function ot(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.id===r.id&&e.status===r.status&&e.subject===r.subject&&e.activeForm===r.activeForm&&e.description===r.description})}function Pn(n,t){return n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.toolName===r.toolName&&e.toolsetName===r.toolsetName&&e.status===r.status&&e.reason===r.reason})}function at(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,s)=>{const r=t[s];return e.parentToolUseId===r.parentToolUseId&&e.status===r.status&&e.subagentType===r.subagentType&&e.description===r.description&&e.summary===r.summary&&Pn(e.tools,r.tools)})}function ct(n){const t=new A([]),e=new A([]),s=new R;return s.add(n.pipe(J(rt),U(ot)).subscribe(t)),s.add(n.pipe(J(it),U(at)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>s.unsubscribe()}}function ae(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 ne={kind:null,stopPhase:"idle"},_n=1e4;function Ln(n,t){return n.kind===t.kind&&n.stopPhase===t.stopPhase&&n.requestId===t.requestId}class F{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 A(!1),this.runStatusSubject=new A(ne),this.conversation$=new A(t.conversation),this.channelTitleSubject=new A(t.channelTitle??null),this.promptSuggestionSubject=new A(null),this.sandboxPhaseSubject=new A("idle"),this.launchedSandboxesSubject=new A(ae(t.launchedSandboxes??[])),this.derivedStores=ct(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(Ln)),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=ae(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 F(t);return e.subscribe(),e}static async open(t,e,s,r){const i=new F(t);try{return i.subscribe(),r?.(i),await i.openChannel(e,s),i}catch(o){throw i.close(),o}}static async reset(t,e,s,r){if(!t.client.deleteChannel)throw new Error("This client cannot reset a channel: IAsgardServiceClient.deleteChannel is not implemented. Implement it (DELETE {base}/channel?custom_channel_id=…) or use AsgardServiceClient.");return await t.client.deleteChannel(t.customChannelId),F.open(t,e,s,r)}static async restore(t,e,s){const r=new F(t);try{return r.subscribe(),s?.(r),await r.rejoinChannel(e),r}catch(i){throw r.close(),i}}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,s,r,i,o,a,u,c])=>({isConnecting:t,conversation:e,tasks:s,subagents:r,channelTitle:i,promptSuggestion:o,sandboxPhase:a,launchedSandboxes:u,runStatus:c}))).subscribe(this.statesObserver)}resolvePayload(t){if(typeof t=="function")try{return t()}catch(e){throw new Error(`Failed to resolve payload function: ${e instanceof Error?e.message:String(e)}`)}return t}updateSandboxPhase(t){switch(t){case l.SANDBOX_LAUNCH:this.sandboxPhaseSubject.next("launching");break;case l.SANDBOX_READY:this.sandboxPhaseSubject.next("ready");break;case l.INIT:case l.ERROR:this.sandboxPhaseSubject.next("idle");break}}buildRunHandlers(t,e,s){return{onSseStart:t?.onSseStart,onSseMessage:r=>{if(t?.onSseMessage?.(r),this.captureRequestId(r.requestId),r.eventType===l.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(r.fact.channelTitleUpdate.title),r.eventType===l.PROMPT_SUGGESTION?this.promptSuggestionSubject.next(r.fact.promptSuggestion.suggestion):r.eventType===l.INIT&&this.clearPromptSuggestion(),this.updateSandboxPhase(r.eventType),r.eventType===l.SANDBOX_LAUNCH&&this.noteSandboxLaunch(r.fact.sandboxLaunch.sandboxName),this.currentUserMessageId&&r.traceId){const i=new Map(this.conversation$.value.messages),o=i.get(this.currentUserMessageId);o&&o.type==="user"&&(i.set(this.currentUserMessageId,{...o,traceId:r.traceId}),this.conversation$.next(new m({messages:i,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(ne),this.currentUserMessageId=void 0,this.currentRun=void 0,t&&this.conversation$.next(this.conversation$.value.settleInFlightMessages())}captureRequestId(t){const e=this.runStatusSubject.value;!t||e.requestId||!e.kind||this.runStatusSubject.next({...e,requestId:t})}clearForceStopTimer(){this.forceStopTimer&&(clearTimeout(this.forceStopTimer),this.forceStopTimer=void 0)}fetchSse(t,e,s){return new Promise((r,i)=>{this.isConnecting$.next(!0),this.runStatusSubject.next({kind:t,stopPhase:"idle"}),this.currentRun=this.client.fetchSse(e,this.buildRunHandlers(s,r,i))})}rejoinChannel(t){return new Promise((e,s)=>{if(!this.client.rejoinSse){e();return}this.isConnecting$.next(!0),this.runStatusSubject.next({kind:this.joinRunState==="RUNNING"?"restore":"replay",stopPhase:"idle"}),this.currentRun=this.client.rejoinSse(this.customChannelId,this.buildRunHandlers(t,e,s))})}openChannel(t,e){return this.fetchSse("reset",{action:H.NONE,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new Y(s));const r=this.conversation$.value.pendingConsent;if(r)return Promise.reject(new z(r.processId));this.clearPromptSuggestion();const i=t.text.trim(),o=t.customMessageId??Je();return this.currentUserMessageId=o,this.lastSentMessageId=o,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:o,text:i,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse("user",{action:H.NONE,customChannelId:this.customChannelId,customMessageId:o,payload:this.resolvePayload(t?.payload),text:i,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:H.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(s),text:"",toolCallConsents:t},e).catch(i=>{throw r&&this.conversation$.next(this.conversation$.value.restorePendingConsent(r)),i})}nudge(t,e){const s=this.runStatusSubject.value.kind;if(s)return Promise.reject(new Y(s));const r=this.conversation$.value.pendingConsent;return r?Promise.reject(new z(r.processId)):this.fetchSse("nudge",{action:H.NUDGE,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(e),text:""},t)}async stopGeneration(t){const e=this.runStatusSubject.value;if(!(!this.currentRun||e.kind!=="user")&&!(e.stopPhase!=="idle"&&!t?.force)){if(!this.client.suspendChannel){this.abortConnection();return}this.clearForceStopTimer(),this.runStatusSubject.next({...e,stopPhase:"stopping"});try{await this.client.suspendChannel(this.customChannelId,{requestId:e.requestId,force:t?.force})}catch(s){throw this.clearForceStopTimer(),this.runStatusSubject.next({...this.runStatusSubject.value,stopPhase:"idle"}),s}this.armForceStopTimer()}}armForceStopTimer(){this.clearForceStopTimer(),this.forceStopTimer=setTimeout(()=>{this.forceStopTimer=void 0;const t=this.runStatusSubject.value;t.stopPhase==="stopping"&&this.runStatusSubject.next({...t,stopPhase:"force-stoppable"})},_n)}abortConnection(){this.currentRun&&(this.currentRun.unsubscribe(),this.clearForceStopTimer(),this.currentRun=void 0,this.isConnecting$.next(!1),this.runStatusSubject.next(ne),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 Un(n){const t=/^sandbox:\/\/([^/]+)\/([^?#]+)(?:\?([^#]*))?/.exec(n.trim());if(!t)return null;const e=decodeURIComponent(t[1]),s=t[2],r=new URLSearchParams(t[3]??"");if(s==="open-browser")return{kind:"open-browser",sandboxName:e};if(s==="open-file"){const i=r.get("absolute_path");return i?{kind:"open-file",sandboxName:e,absolutePath:i}:null}return null}exports.AsgardServiceClient=Sn;exports.AsgardSourceSetClient=wn;exports.Channel=F;exports.ChannelAwaitingConsentError=z;exports.ChannelBusyError=Y;exports.Conversation=m;exports.EventType=l;exports.FetchSseAction=H;exports.HttpError=y;exports.MessageTemplateType=ce;exports.SOURCE_SET_DEFAULT_MAX_ENTRIES=ze;exports.SOURCE_SET_MAX_PAGE_SIZE=he;exports.SOURCE_SET_VOLUME_ROOT=Ye;exports.ToolCallConsentResult=xe;exports.assertVolumePath=I;exports.conversationToSubagentEvents=st;exports.createDerivedStores=ct;exports.deriveSubagents=it;exports.deriveTasks=rt;exports.isAgentTool=et;exports.isChannelAwaitingConsentError=dt;exports.isChannelBusyError=lt;exports.isHttpError=ut;exports.isSubagentChildTool=tt;exports.isTaskTool=Qe;exports.reconcileLaunched=ae;exports.reduceSubagents=nt;exports.reduceTaskEvents=Ze;exports.resolveSandboxUri=Un;exports.subagentsEqual=at;exports.tasksEqual=ot;
|
|
5
5
|
//# sourceMappingURL=index.cjs.map
|