@asgard-js/core 0.2.62 → 0.2.63

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.
Files changed (50) hide show
  1. package/README.md +95 -20
  2. package/dist/constants/enum.d.ts +7 -0
  3. package/dist/constants/enum.d.ts.map +1 -1
  4. package/dist/index.cjs +4 -4
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +6 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +4 -4
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +1555 -1145
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/lib/channel.d.ts +39 -1
  13. package/dist/lib/channel.d.ts.map +1 -1
  14. package/dist/lib/channel.spec.d.ts +2 -0
  15. package/dist/lib/channel.spec.d.ts.map +1 -0
  16. package/dist/lib/client.d.ts +16 -1
  17. package/dist/lib/client.d.ts.map +1 -1
  18. package/dist/lib/client.spec.d.ts +2 -0
  19. package/dist/lib/client.spec.d.ts.map +1 -0
  20. package/dist/lib/conversation.d.ts +18 -0
  21. package/dist/lib/conversation.d.ts.map +1 -1
  22. package/dist/lib/conversation.spec.d.ts +2 -0
  23. package/dist/lib/conversation.spec.d.ts.map +1 -0
  24. package/dist/lib/create-sse-observable.d.ts +4 -1
  25. package/dist/lib/create-sse-observable.d.ts.map +1 -1
  26. package/dist/lib/derived-stores.d.ts +39 -0
  27. package/dist/lib/derived-stores.d.ts.map +1 -0
  28. package/dist/lib/derived-stores.spec.d.ts +2 -0
  29. package/dist/lib/derived-stores.spec.d.ts.map +1 -0
  30. package/dist/lib/subagent-reducer.d.ts +46 -0
  31. package/dist/lib/subagent-reducer.d.ts.map +1 -0
  32. package/dist/lib/subagent-reducer.spec.d.ts +2 -0
  33. package/dist/lib/subagent-reducer.spec.d.ts.map +1 -0
  34. package/dist/lib/task-reducer.d.ts +23 -0
  35. package/dist/lib/task-reducer.d.ts.map +1 -0
  36. package/dist/lib/task-reducer.spec.d.ts +2 -0
  37. package/dist/lib/task-reducer.spec.d.ts.map +1 -0
  38. package/dist/types/channel.d.ts +73 -1
  39. package/dist/types/channel.d.ts.map +1 -1
  40. package/dist/types/client.d.ts +9 -0
  41. package/dist/types/client.d.ts.map +1 -1
  42. package/dist/types/index.d.ts +2 -0
  43. package/dist/types/index.d.ts.map +1 -1
  44. package/dist/types/sse-response.d.ts +66 -0
  45. package/dist/types/sse-response.d.ts.map +1 -1
  46. package/dist/types/subagent.d.ts +37 -0
  47. package/dist/types/subagent.d.ts.map +1 -0
  48. package/dist/types/task.d.ts +21 -0
  49. package/dist/types/task.d.ts.map +1 -0
  50. package/package.json +1 -1
package/README.md CHANGED
@@ -21,7 +21,7 @@ npm install @asgard-js/core
21
21
  Here's a basic example of how to use the core package:
22
22
 
23
23
  ```javascript
24
- import { AsgardServiceClient } from '@asgard-js/core';
24
+ import { AsgardServiceClient, FetchSseAction, EventType } from '@asgard-js/core';
25
25
 
26
26
  const client = new AsgardServiceClient({
27
27
  apiKey: 'your-api-key',
@@ -33,7 +33,7 @@ const client = new AsgardServiceClient({
33
33
  client.fetchSse({
34
34
  customChannelId: 'your-channel-id',
35
35
  text: 'Hello, Asgard!',
36
- action: 'message',
36
+ action: FetchSseAction.NONE,
37
37
  });
38
38
 
39
39
  // Upload files (optional, requires uploadFile method)
@@ -51,7 +51,7 @@ if (client.uploadFile) {
51
51
  client.fetchSse({
52
52
  customChannelId: 'your-channel-id',
53
53
  text: 'Here is my image:',
54
- action: 'message',
54
+ action: FetchSseAction.NONE,
55
55
  blobIds: [blobId],
56
56
  });
57
57
  }
@@ -61,15 +61,15 @@ if (client.uploadFile) {
61
61
  }
62
62
 
63
63
  // Listen to events
64
- client.on('MESSAGE', response => {
64
+ client.on(EventType.MESSAGE, response => {
65
65
  console.log('Received message:', response);
66
66
  });
67
67
 
68
- client.on('DONE', response => {
68
+ client.on(EventType.DONE, response => {
69
69
  console.log('Conversation completed:', response);
70
70
  });
71
71
 
72
- client.on('ERROR', error => {
72
+ client.on(EventType.ERROR, error => {
73
73
  console.error('Error occurred:', error);
74
74
  });
75
75
  ```
@@ -114,7 +114,7 @@ const client = new AsgardServiceClient({
114
114
 
115
115
  ## API Reference
116
116
 
117
- The core package exports three main classes for different levels of abstraction and includes authentication types for dynamic API key management:
117
+ The core package exports three main classes for different levels of abstraction (`AsgardServiceClient`, `Channel`, `Conversation`), an `HttpError` class with an `isHttpError` type guard for HTTP failure handling, and authentication types for dynamic API key management:
118
118
 
119
119
  <a id="asgardserviceclient"></a>
120
120
  <br/>
@@ -141,19 +141,24 @@ 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
144
+ - **fetchSse(payload, options?)**: Send a message via Server-Sent Events. `payload.action` is a `FetchSseAction` value — `NONE` for a normal message, `RESET_CHANNEL` to (re)initialize the channel, `RESPONSE_TOOL_CALL_CONSENT` to answer a consent prompt
145
145
  - **uploadFile(file, customChannelId)**: Upload file to Blob API and return BlobUploadResponse
146
- - **on(event, handler)**: Listen to specific SSE events
147
- - **close()**: Close the SSE connection and cleanup resources
146
+ - **downloadCwdFile(relativePath, customChannelId)**: `Promise<CwdDownloadResult>` - Download a file from the channel sandbox working directory (backs `cwd://` URI actions); resolves to `{ blob, filename }`
147
+ - **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
148
+ - **detach({ timeoutMs })**: Detach from the owning component without aborting in-flight runs — the connection stays open so the backend can finish the current run, then auto-closes once all runs settle (or after `timeoutMs` as a safety net). Backs the React `keepConnectionOnUnmount` prop
149
+ - **close()**: Close the SSE connection and clean up resources (idempotent)
148
150
 
149
151
  #### Event Types
150
152
 
151
- - **INIT**: Run initialization events
152
- - **MESSAGE**: Message events (start, delta, complete)
153
- - **TOOL_CALL**: Tool call events (start, complete)
154
- - **PROCESS**: Process events (start, complete)
155
- - **DONE**: Run completion events
156
- - **ERROR**: Error events
153
+ Pass these `EventType` members (imported from `@asgard-js/core`) as the first argument to `on()`:
154
+
155
+ - **`EventType.INIT`** (`asgard.run.init`): Run initialization events
156
+ - **`EventType.MESSAGE`** (`asgard.message`): Message events (start, delta, complete)
157
+ - **`EventType.TOOL_CALL`** (`asgard.tool_call`): Tool call events (start, complete)
158
+ - **`EventType.TOOL_CALL_CONSENT`** (`asgard.tool_call.consent`): Tool call consent prompts awaiting a user decision
159
+ - **`EventType.PROCESS`** (`asgard.process`): Process events (start, complete)
160
+ - **`EventType.DONE`** (`asgard.run.done`): Run completion events
161
+ - **`EventType.ERROR`** (`asgard.run.error`): Error events
157
162
 
158
163
  <a id="channel"></a>
159
164
  <br/>
@@ -169,6 +174,7 @@ Higher-level abstraction for managing a conversation channel with reactive state
169
174
  #### Instance Methods
170
175
 
171
176
  - **sendMessage(payload, options?)**: `Promise<void>` - Send a message through the channel
177
+ - **replyToolCallConsents(answers, options?, payload?)**: `Promise<void>` - Reply to a pending tool-call consent prompt. `answers` is an array of `ToolCallConsentAnswer` (each `{ toolCallId, result, denyReason }`, where `result` is a `ToolCallConsentResult` value)
172
178
  - **close()**: `void` - Close the channel and cleanup subscriptions
173
179
 
174
180
  #### Configuration (ChannelConfig)
@@ -219,21 +225,24 @@ Immutable conversation state manager that handles message updates and SSE event
219
225
 
220
226
  #### Constructor
221
227
 
222
- - **constructor(options)**: Initialize conversation with `{messages: Map<string, ConversationMessage> | null}`
228
+ - **constructor(options)**: Initialize conversation with `{ messages: Map<string, ConversationMessage> | null, pendingConsent?: ToolCallConsentEventData | null }`
223
229
 
224
230
  #### Methods
225
231
 
226
232
  - **pushMessage(message)**: `Conversation` - Add a new message (returns new instance)
227
- - **onMessage(response)**: `Conversation` - Process SSE response and update conversation
233
+ - **onMessage(response)**: `Conversation` - Process an SSE response and update the conversation (returns new instance)
234
+ - **clearPendingConsent()**: `Conversation` - Clear the pending tool-call consent (returns new instance)
228
235
 
229
236
  #### Properties
230
237
 
231
238
  - **messages**: `Map<string, ConversationMessage> | null` - Map of all messages in the conversation
239
+ - **pendingConsent**: `ToolCallConsentEventData | null` - The tool-call consent prompt currently awaiting a user decision, or `null`
232
240
 
233
241
  #### Message Types
234
242
 
235
243
  - **ConversationUserMessage**: User-sent messages with `text` and `time`
236
244
  - **ConversationBotMessage**: Bot responses with `message`, `isTyping`, `typingText`, `eventType`
245
+ - **ConversationToolCallMessage**: Tool-call entries with `toolName`, `reason`, `parameter`, `result`, `isComplete`
237
246
  - **ConversationErrorMessage**: Error messages with `error` details
238
247
 
239
248
  #### Example Usage
@@ -273,7 +282,7 @@ if (uploadResponse.isSuccess && uploadResponse.data[0]) {
273
282
  client.fetchSse({
274
283
  customChannelId: 'your-channel-id',
275
284
  text: 'Here is my image',
276
- action: 'message',
285
+ action: FetchSseAction.NONE,
277
286
  blobIds: [blobId],
278
287
  });
279
288
  }
@@ -293,7 +302,14 @@ The core package includes authentication-related types for dynamic API key manag
293
302
  Authentication state management for applications requiring dynamic API key input:
294
303
 
295
304
  ```typescript
296
- type AuthState = 'loading' | 'needApiKey' | 'authenticated' | 'error' | 'invalidApiKey';
305
+ type AuthState =
306
+ | 'loading'
307
+ | 'needApiKey'
308
+ | 'authenticated'
309
+ | 'error'
310
+ | 'invalidApiKey'
311
+ | 'subscriptionExpired'
312
+ | 'botNotFound';
297
313
  ```
298
314
 
299
315
  **States:**
@@ -303,6 +319,8 @@ type AuthState = 'loading' | 'needApiKey' | 'authenticated' | 'error' | 'invalid
303
319
  - **`authenticated`**: Successfully authenticated
304
320
  - **`error`**: General authentication error
305
321
  - **`invalidApiKey`**: API key is invalid
322
+ - **`subscriptionExpired`**: The workspace subscription has expired
323
+ - **`botNotFound`**: The configured bot provider could not be found
306
324
 
307
325
  **Usage:**
308
326
 
@@ -322,6 +340,63 @@ function handleAuthState(state: AuthState) {
322
340
  }
323
341
  ```
324
342
 
343
+ <a id="error-handling"></a>
344
+ <br/>
345
+
346
+ ### Error Handling (HttpError)
347
+
348
+ HTTP failures (for example a non-2xx response while authenticating) are surfaced as an `HttpError` instance. Both `HttpError` and the `isHttpError` type guard are re-exported from the package root:
349
+
350
+ ```typescript
351
+ import { isHttpError } from '@asgard-js/core';
352
+
353
+ try {
354
+ // ... a call that may reject with an HttpError
355
+ } catch (error) {
356
+ if (isHttpError(error)) {
357
+ console.error(error.status, error.statusText, error.body);
358
+ }
359
+ }
360
+ ```
361
+
362
+ `HttpError` extends `Error` with readonly `status: number`, `statusText: string`, and `body: unknown` (its `name` is `'HttpError'`).
363
+
364
+ <a id="tool-call-consent"></a>
365
+ <br/>
366
+
367
+ ### Tool Call Consent
368
+
369
+ When a bot is configured to ask before running a tool, the backend emits an `EventType.TOOL_CALL_CONSENT` event. The pending request is exposed on `Conversation.pendingConsent`; reply to it with `Channel.replyToolCallConsents()`:
370
+
371
+ ```typescript
372
+ import { ToolCallConsentResult } from '@asgard-js/core';
373
+
374
+ await channel.replyToolCallConsents([
375
+ { toolCallId: 'call-1', result: ToolCallConsentResult.ALLOW_ONCE, denyReason: '' },
376
+ ]);
377
+ ```
378
+
379
+ **Related types:**
380
+
381
+ - **`ToolCallConsentResult`** (enum): `ALLOW_ONCE` | `ALLOW_ALWAYS` | `DENY_ONCE`
382
+ - **`ToolCallConsentPendingCall`**: `{ toolCallId, toolsetName, toolName, parameter, alreadyAllowed, reason? }`
383
+ - **`ToolCallConsentEventData`**: `{ processId, pendingCalls: ToolCallConsentPendingCall[] }`
384
+ - **`ToolCallConsentAnswer`**: `{ toolCallId, result, denyReason }`
385
+
386
+ <a id="cwd-download-result"></a>
387
+ <br/>
388
+
389
+ ### CwdDownloadResult
390
+
391
+ Returned by `client.downloadCwdFile()`:
392
+
393
+ ```typescript
394
+ interface CwdDownloadResult {
395
+ blob: Blob;
396
+ filename: string;
397
+ }
398
+ ```
399
+
325
400
  <a id="development"></a>
326
401
  <br/>
327
402
 
@@ -12,10 +12,17 @@ export declare enum EventType {
12
12
  MESSAGE_START = "asgard.message.start",
13
13
  MESSAGE_DELTA = "asgard.message.delta",
14
14
  MESSAGE_COMPLETE = "asgard.message.complete",
15
+ MESSAGE_USER = "asgard.message.user",
16
+ MESSAGE_THINKING_START = "asgard.message.thinking.start",
17
+ MESSAGE_THINKING_DELTA = "asgard.message.thinking.delta",
18
+ MESSAGE_THINKING_COMPLETE = "asgard.message.thinking.complete",
15
19
  TOOL_CALL = "asgard.tool_call",
16
20
  TOOL_CALL_START = "asgard.tool_call.start",
17
21
  TOOL_CALL_COMPLETE = "asgard.tool_call.complete",
18
22
  TOOL_CALL_CONSENT = "asgard.tool_call.consent",
23
+ SUBAGENT_START = "asgard.subagent.start",
24
+ SUBAGENT_COMPLETE = "asgard.subagent.complete",
25
+ CHANNEL_TITLE_UPDATE = "asgard.channel.title.update",
19
26
  DONE = "asgard.run.done",
20
27
  ERROR = "asgard.run.error"
21
28
  }
@@ -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;CAC1D;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;IAC5C,SAAS,qBAAqB;IAC9B,eAAe,2BAA2B;IAC1C,kBAAkB,8BAA8B;IAChD,iBAAiB,6BAA6B;IAC9C,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;CAC1B"}
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;CAC1D;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;IAC9D,SAAS,qBAAqB;IAC9B,eAAe,2BAA2B;IAC1C,kBAAkB,8BAA8B;IAChD,iBAAiB,6BAA6B;IAI9C,cAAc,0BAA0B;IACxC,iBAAiB,6BAA6B;IAE9C,oBAAoB,gCAAgC;IACpD,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;CAC1B"}
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class Q extends Error{status;statusText;body;constructor(e,t,r){super(`HTTP ${e}: ${t}`),this.name="HttpError",this.status=e,this.statusText=t,this.body=r}}function Fe(n){return n instanceof Q}var M=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n))(M||{}),d=(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.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.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(d||{}),he=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(he||{}),pe=(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))(pe||{}),W=function(n,e){return W=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},W(n,e)};function I(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");W(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ge(n,e,t,r){function o(i){return i instanceof t?i:new t(function(s){s(i)})}return new(t||(t=Promise))(function(i,s){function a(f){try{u(r.next(f))}catch(p){s(p)}}function c(f){try{u(r.throw(f))}catch(p){s(p)}}function u(f){f.done?i(f.value):o(f.value).then(a,c)}u((r=r.apply(n,e||[])).next())})}function ve(n,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,o,i,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(u){return function(f){return c([u,f])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(t=0)),t;)try{if(r=1,o&&(i=u[0]&2?o.return:u[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,u[1])).done)return i;switch(o=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,o=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){t.label=u[1];break}if(u[0]===6&&t.label<i[1]){t.label=i[1],i=u;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(u);break}i[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(n,t)}catch(f){u=[6,f],o=0}finally{r=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function P(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(s)throw s.error}}return i}function N(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return n.concat(i||Array.prototype.slice.call(e))}function x(n){return this instanceof x?(this.v=n,this):new x(n)}function Ke(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),o,i=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),o[Symbol.asyncIterator]=function(){return this},o;function s(l){return function(y){return Promise.resolve(y).then(l,p)}}function a(l,y){r[l]&&(o[l]=function(v){return new Promise(function(w,E){i.push([l,v,w,E])>1||c(l,v)})},y&&(o[l]=y(o[l])))}function c(l,y){try{u(r[l](y))}catch(v){h(i[0][3],v)}}function u(l){l.value instanceof x?Promise.resolve(l.value.v).then(f,p):h(i[0][2],l)}function f(l){c("next",l)}function p(l){c("throw",l)}function h(l,y){l(y),i.shift(),i.length&&c(i[0][0],i[0][1])}}function Ve(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof P=="function"?P(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(i){t[i]=n[i]&&function(s){return new Promise(function(a,c){s=n[i](s),o(a,c,s.done,s.value)})}}function o(i,s,a,c){Promise.resolve(c).then(function(u){i({value:u,done:a})},s)}}function m(n){return typeof n=="function"}function ye(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Y=ye(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
2
- `+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function j(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var U=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=P(s),c=a.next();!c.done;c=a.next()){var u=c.value;u.remove(this)}}catch(v){e={error:v}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else s.remove(this);var f=this.initialTeardown;if(m(f))try{f()}catch(v){i=v instanceof Y?v.errors:[v]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var h=P(p),l=h.next();!l.done;l=h.next()){var y=l.value;try{re(y)}catch(v){i=i??[],v instanceof Y?i=N(N([],R(i)),R(v.errors)):i.push(v)}}}catch(v){r={error:v}}finally{try{l&&!l.done&&(o=h.return)&&o.call(h)}finally{if(r)throw r.error}}}if(i)throw new Y(i)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)re(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&j(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&j(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})(),me=U.EMPTY;function be(n){return n instanceof U||n&&"closed"in n&&m(n.remove)&&m(n.add)&&m(n.unsubscribe)}function re(n){m(n)?n():n.unsubscribe()}var Be={Promise:void 0},Ye={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,N([n,e],R(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function ge(n){Ye.setTimeout(function(){throw n})}function X(){}function D(n){n()}var Z=(function(n){I(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,be(t)&&t.add(r)):r.destination=Xe,r}return e.create=function(t,r,o){return new z(t,r,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(U),qe=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){k(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){k(r)}else k(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){k(t)}},n})(),z=(function(n){I(e,n);function e(t,r,o){var i=n.call(this)||this,s;return m(t)||!t?s={next:t??void 0,error:r??void 0,complete:o??void 0}:s=t,i.destination=new qe(s),i}return e})(Z);function k(n){ge(n)}function We(n){throw n}var Xe={closed:!0,next:X,error:We,complete:X},ee=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function G(n){return n}function ze(n){return n.length===0?G:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var g=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,i=Qe(e)?e:new z(e,t,r);return D(function(){var s=o,a=s.operator,c=s.source;i.add(a?a.call(i,c):c?o._subscribe(i):o._trySubscribe(i))}),i},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=oe(t),new t(function(o,i){var s=new z({next:function(a){try{e(a)}catch(c){i(c),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[ee]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ze(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=oe(e),new e(function(r,o){var i;t.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},n.create=function(e){return new n(e)},n})();function oe(n){var e;return(e=n??Be.Promise)!==null&&e!==void 0?e:Promise}function Je(n){return n&&m(n.next)&&m(n.error)&&m(n.complete)}function Qe(n){return n&&n instanceof Z||Je(n)&&be(n)}function Ze(n){return m(n?.lift)}function L(n){return function(e){if(Ze(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function O(n,e,t,r,o){return new et(n,e,t,r,o)}var et=(function(n){I(e,n);function e(t,r,o,i,s,a){var c=n.call(this,t)||this;return c.onFinalize=s,c.shouldUnsubscribe=a,c._next=r?function(u){try{r(u)}catch(f){t.error(f)}}:n.prototype._next,c._error=i?function(u){try{i(u)}catch(f){t.error(f)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=o?function(){try{o()}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(Z),tt=ye(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),te=(function(n){I(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new ie(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new tt},e.prototype.next=function(t){var r=this;D(function(){var o,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=P(r.currentObservers),a=s.next();!a.done;a=s.next()){var c=a.value;c.next(t)}}catch(u){o={error:u}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var r=this;D(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var o=r.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;D(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?me:(this.currentObservers=null,a.push(t),new U(function(){r.currentObservers=null,j(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,o=r.hasError,i=r.thrownError,s=r.isStopped;o?t.error(i):s&&t.complete()},e.prototype.asObservable=function(){var t=new g;return t.source=this,t},e.create=function(t,r){return new ie(t,r)},e})(g),ie=(function(n){I(e,n);function e(t,r){var o=n.call(this)||this;return o.destination=t,o.source=r,o}return e.prototype.next=function(t){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,t)},e.prototype.error=function(t){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&o!==void 0?o:me},e})(te),se=(function(n){I(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,o=t.thrownError,i=t._value;if(r)throw o;return this._throwIfClosed(),i},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e})(te),nt={now:function(){return Date.now()}},rt=(function(n){I(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e})(U),ae={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,N([n,e],R(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},ot=(function(n){I(e,n);function e(t,r){var o=n.call(this,t,r)||this;return o.scheduler=t,o.work=r,o.pending=!1,o}return e.prototype.schedule=function(t,r){var o;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var i=this.id,s=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(s,i,r)),this.pending=!0,this.delay=r,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(s,this.id,r),this},e.prototype.requestAsyncId=function(t,r,o){return o===void 0&&(o=0),ae.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,r,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return r;r!=null&&ae.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,r);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var o=!1,i;try{this.work(t)}catch(s){o=!0,i=s||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),i},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,o=t.scheduler,i=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,j(i,this),r!=null&&(this.id=this.recycleAsyncId(o,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e})(rt),ce=(function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=nt.now,n})(),it=(function(n){I(e,n);function e(t,r){r===void 0&&(r=ce.now);var o=n.call(this,t,r)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,o){for(;t=r.shift();)t.unsubscribe();throw o}},e})(ce),Se=new it(ot),st=Se,at=new g(function(n){return n.complete()});function we(n){return n&&m(n.schedule)}function Ee(n){return n[n.length-1]}function ct(n){return m(Ee(n))?n.pop():void 0}function Oe(n){return we(Ee(n))?n.pop():void 0}var Ie=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function Ce(n){return m(n?.then)}function Ae(n){return m(n[ee])}function Te(n){return Symbol.asyncIterator&&m(n?.[Symbol.asyncIterator])}function _e(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ut(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Le=ut();function xe(n){return m(n?.[Le])}function Pe(n){return Ke(this,arguments,function(){var t,r,o,i;return ve(this,function(s){switch(s.label){case 0:t=n.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,x(t.read())];case 3:return r=s.sent(),o=r.value,i=r.done,i?[4,x(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,x(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Me(n){return m(n?.getReader)}function T(n){if(n instanceof g)return n;if(n!=null){if(Ae(n))return lt(n);if(Ie(n))return ft(n);if(Ce(n))return dt(n);if(Te(n))return Re(n);if(xe(n))return ht(n);if(Me(n))return pt(n)}throw _e(n)}function lt(n){return new g(function(e){var t=n[ee]();if(m(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ft(n){return new g(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function dt(n){return new g(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,ge)})}function ht(n){return new g(function(e){var t,r;try{for(var o=P(n),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(a){t={error:a}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function Re(n){return new g(function(e){vt(n,e).catch(function(t){return e.error(t)})})}function pt(n){return Re(Pe(n))}function vt(n,e){var t,r,o,i;return Ge(this,void 0,void 0,function(){var s,a;return ve(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=Ve(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(s=r.value,e.next(s),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(i=t.return)?[4,i.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function A(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var i=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(i),!o)return i}function Ne(n,e){return e===void 0&&(e=0),L(function(t,r){t.subscribe(O(r,function(o){return A(r,n,function(){return r.next(o)},e)},function(){return A(r,n,function(){return r.complete()},e)},function(o){return A(r,n,function(){return r.error(o)},e)}))})}function Ue(n,e){return e===void 0&&(e=0),L(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function yt(n,e){return T(n).pipe(Ue(e),Ne(e))}function mt(n,e){return T(n).pipe(Ue(e),Ne(e))}function bt(n,e){return new g(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function gt(n,e){return new g(function(t){var r;return A(t,e,function(){r=n[Le](),A(t,e,function(){var o,i,s;try{o=r.next(),i=o.value,s=o.done}catch(a){t.error(a);return}s?t.complete():t.next(i)},0,!0)}),function(){return m(r?.return)&&r.return()}})}function $e(n,e){if(!n)throw new Error("Iterable cannot be null");return new g(function(t){A(t,e,function(){var r=n[Symbol.asyncIterator]();A(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function St(n,e){return $e(Pe(n),e)}function wt(n,e){if(n!=null){if(Ae(n))return yt(n,e);if(Ie(n))return bt(n,e);if(Ce(n))return mt(n,e);if(Te(n))return $e(n,e);if(xe(n))return gt(n,e);if(Me(n))return St(n,e)}throw _e(n)}function ne(n,e){return e?wt(n,e):T(n)}function Et(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Oe(n);return ne(n,t)}function Ot(n){return n instanceof Date&&!isNaN(n)}function K(n,e){return L(function(t,r){var o=0;t.subscribe(O(r,function(i){r.next(n.call(e,i,o++))}))})}var It=Array.isArray;function Ct(n,e){return It(e)?n.apply(void 0,N([],R(e))):n(e)}function At(n){return K(function(e){return Ct(n,e)})}var Tt=Array.isArray,_t=Object.getPrototypeOf,Lt=Object.prototype,xt=Object.keys;function Pt(n){if(n.length===1){var e=n[0];if(Tt(e))return{args:e,keys:null};if(Mt(e)){var t=xt(e);return{args:t.map(function(r){return e[r]}),keys:t}}}return{args:n,keys:null}}function Mt(n){return n&&typeof n=="object"&&_t(n)===Lt}function Rt(n,e){return n.reduce(function(t,r,o){return t[r]=e[o],t},{})}function Nt(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Oe(n),r=ct(n),o=Pt(n),i=o.args,s=o.keys;if(i.length===0)return ne([],t);var a=new g(Ut(i,t,s?function(c){return Rt(s,c)}:G));return r?a.pipe(At(r)):a}function Ut(n,e,t){return t===void 0&&(t=G),function(r){ue(e,function(){for(var o=n.length,i=new Array(o),s=o,a=o,c=function(f){ue(e,function(){var p=ne(n[f],e),h=!1;p.subscribe(O(r,function(l){i[f]=l,h||(h=!0,a--),a||r.next(t(i.slice()))},function(){--s||r.complete()}))},r)},u=0;u<o;u++)c(u)},r)}}function ue(n,e,t){n?A(t,n,e):e()}function $t(n,e,t,r,o,i,s,a){var c=[],u=0,f=0,p=!1,h=function(){p&&!c.length&&!u&&e.complete()},l=function(v){return u<r?y(v):c.push(v)},y=function(v){u++;var w=!1;T(t(v,f++)).subscribe(O(e,function(E){e.next(E)},function(){w=!0},void 0,function(){if(w)try{u--;for(var E=function(){var _=c.shift();s||y(_)};c.length&&u<r;)E();h()}catch(_){e.error(_)}}))};return n.subscribe(O(e,l,function(){p=!0,h()})),function(){}}function H(n,e,t){return t===void 0&&(t=1/0),m(e)?H(function(r,o){return K(function(i,s){return e(r,i,o,s)})(T(n(r,o)))},t):(typeof e=="number"&&(t=e),L(function(r,o){return $t(r,o,n,t)}))}function ke(n,e,t){n===void 0&&(n=0),t===void 0&&(t=st);var r=-1;return e!=null&&(we(e)?t=e:r=e),new g(function(o){var i=Ot(n)?+n-t.now():n;i<0&&(i=0);var s=0;return t.schedule(function(){o.closed||(o.next(s++),0<=r?this.schedule(void 0,r):o.complete())},i)})}function kt(n,e){return m(e)?H(n,e,1):H(n,1)}function Dt(n){return n<=0?function(){return at}:L(function(e,t){var r=0;e.subscribe(O(t,function(o){++r<=n&&(t.next(o),n<=r&&t.complete())}))})}function jt(n){return K(function(){return n})}function Ht(n,e){return H(function(t,r){return T(n(t,r)).pipe(Dt(1),jt(t))})}function Ft(n,e){e===void 0&&(e=Se);var t=ke(n,e);return Ht(function(){return t})}function Gt(n){var e;e={count:n};var t=e.count,r=t===void 0?1/0:t,o=e.delay,i=e.resetOnSuccess,s=i===void 0?!1:i;return r<=0?G:L(function(a,c){var u=0,f,p=function(){var h=!1;f=a.subscribe(O(c,function(l){s&&(u=0),c.next(l)},void 0,function(l){if(u++<r){var y=function(){f?(f.unsubscribe(),f=null,p()):h=!0};if(o!=null){var v=typeof o=="number"?ke(o):T(o(l,u)),w=O(c,function(){w.unsubscribe(),y()},function(){c.complete()});v.subscribe(w)}else y()}else c.error(l)})),h&&(f.unsubscribe(),f=null,p())};p()})}function Kt(n){return L(function(e,t){T(n).subscribe(O(t,function(){return t.complete()},X)),!t.closed&&e.subscribe(t)})}async function Vt(n,e){const t=n.getReader();let r;for(;!(r=await t.read()).done;)e(r.value)}function Bt(n){let e,t,r,o=!1;return function(s){e===void 0?(e=s,t=0,r=-1):e=qt(e,s);const a=e.length;let c=0;for(;t<a;){o&&(e[t]===10&&(c=++t),o=!1);let u=-1;for(;t<a&&u===-1;++t)switch(e[t]){case 58:r===-1&&(r=t-c);break;case 13:o=!0;case 10:u=t;break}if(u===-1)break;n(e.subarray(c,u),r),c=t,r=-1}c===a?e=void 0:c!==0&&(e=e.subarray(c),t-=c)}}function Yt(n,e,t){let r=le();const o=new TextDecoder;return function(s,a){if(s.length===0)t?.(r),r=le();else if(a>0){const c=o.decode(s.subarray(0,a)),u=a+(s[a+1]===32?2:1),f=o.decode(s.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
4
- `+f:f;break;case"event":r.event=f;break;case"id":n(r.id=f);break;case"retry":const p=parseInt(f,10);isNaN(p)||e(r.retry=p);break}}}}function qt(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function le(){return{data:"",event:"",id:"",retry:void 0}}var Wt=function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(n);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(n,r[o])&&(t[r[o]]=n[r[o]]);return t};const J="text/event-stream",Xt=1e3,fe="last-event-id";function zt(n,e){var{signal:t,headers:r,onopen:o,onmessage:i,onclose:s,onerror:a,openWhenHidden:c,fetch:u}=e,f=Wt(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((p,h)=>{const l=Object.assign({},r);l.accept||(l.accept=J);let y;function v(){y.abort(),document.hidden||V()}c||document.addEventListener("visibilitychange",v);let w=Xt,E=0;function _(){document.removeEventListener("visibilitychange",v),window.clearTimeout(E),y.abort()}t?.addEventListener("abort",()=>{_(),p()});const je=u??window.fetch,He=o??Jt;async function V(){var B;y=new AbortController;try{const $=await je(n,Object.assign(Object.assign({},f),{headers:l,signal:y.signal}));await He($),await Vt($.body,Bt(Yt(C=>{C?l[fe]=C:delete l[fe]},C=>{w=C},i))),s?.(),_(),p()}catch($){if(!y.signal.aborted)try{const C=(B=a?.($))!==null&&B!==void 0?B:w;window.clearTimeout(E),E=window.setTimeout(V,C)}catch(C){_(),h(C)}}}V()})}function Jt(n){const e=n.headers.get("content-type");if(!e?.startsWith(J))throw new Error(`Expected content-type to be ${J}, Actual: ${e}`)}function Qt(n){const{endpoint:e,apiKey:t,payload:r,debugMode:o,customHeaders:i}=n;return new g(s=>{const a=new AbortController;let c;const u={"Content-Type":"application/json",...i};t&&(u["X-API-KEY"]=t);const f=new URLSearchParams;o&&f.set("is_debug","true");const p=new URL(e);return f.toString()&&(p.search=f.toString()),zt(p.toString(),{method:"POST",headers:u,body:r?JSON.stringify(r):void 0,signal:a.signal,openWhenHidden:!0,onopen:async h=>{if(h.ok)c=h.headers.get("X-Trace-Id")??void 0;else{let l;try{l=await h.json()}catch{try{l=await h.text()}catch{l=null}}s.error(new Q(h.status,h.statusText,l)),a.abort()}},onmessage:h=>{const l=JSON.parse(h.data);c?l.traceId=c:l.requestId&&(l.traceId=l.requestId,c||(c=l.requestId)),s.next(l)},onclose:()=>{s.complete()},onerror:h=>{throw s.error(h),a.abort(),h}}),()=>{a.abort()}})}class Zt{listeners={};on(e,t){this.listeners=Object.assign({},this.listeners,{[e]:(this.listeners[e]??[]).concat(t)})}off(e,t){this.listeners[e]&&(this.listeners=Object.assign({},this.listeners,{[e]:(this.listeners[e]??[]).filter(r=>r!==t)}))}remove(e){delete this.listeners[e]}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(r=>r(...t))}}class en{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new te;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new Zt;transformSsePayload;customHeaders;constructor(e){if(!e.endpoint&&!e.botProviderEndpoint)throw new Error("Either endpoint or botProviderEndpoint must be provided");if(this.apiKey=e.apiKey,this.debugMode=e.debugMode,this.transformSsePayload=e.transformSsePayload,this.botProviderEndpoint=e.botProviderEndpoint,this.customHeaders={...e.customHeaders,...e.userIdentityHint?{"X-ASGARD-USER-IDENTITY-HINT":e.userIdentityHint}:{}},!e.endpoint&&e.botProviderEndpoint){const t=e.botProviderEndpoint.replace(/\/+$/,"");this.endpoint=`${t}/message/sse`}else e.endpoint&&(this.endpoint=e.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(e,t){this.sseEmitter.remove(e),this.sseEmitter.on(e,t)}handleEvent(e){switch(e.eventType){case d.INIT:this.sseEmitter.emit(d.INIT,e);break;case d.PROCESS_START:case d.PROCESS_COMPLETE:this.sseEmitter.emit(d.PROCESS,e);break;case d.MESSAGE_START:case d.MESSAGE_DELTA:case d.MESSAGE_COMPLETE:this.sseEmitter.emit(d.MESSAGE,e);break;case d.TOOL_CALL_START:case d.TOOL_CALL_COMPLETE:this.sseEmitter.emit(d.TOOL_CALL,e);break;case d.TOOL_CALL_CONSENT:this.sseEmitter.emit(d.TOOL_CALL_CONSENT,e);break;case d.DONE:this.sseEmitter.emit(d.DONE,e);break;case d.ERROR:this.sseEmitter.emit(d.ERROR,e);break}}fetchSse(e,t){t?.onSseStart?.(),this.inFlight+=1,Qt({apiKey:this.apiKey,endpoint:this.endpoint,debugMode:this.debugMode,payload:this.transformSsePayload?.(e)??e,customHeaders:this.customHeaders}).pipe(kt(r=>Et(r).pipe(Ft(t?.delayTime??50))),Kt(this.destroy$),Gt(3)).subscribe({next:r=>{this.detached||(t?.onSseMessage?.(r),this.handleEvent(r))},error:r=>{this.detached||t?.onSseError?.(r),this.onRunSettled()},complete:()=>{this.detached||t?.onSseCompleted?.(),this.onRunSettled()}})}detach(e){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),e.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(e,t){const r=this.deriveBlobEndpoint();if(!r)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const o=new FormData;o.append("file",e),o.append("customChannelId",t);const i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const s=await fetch(r,{method:"POST",headers:i,body:o});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const a=await s.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(s){throw console.error("[AsgardServiceClient] File upload error:",s),s}}async downloadCwdFile(e,t){const r=this.getBaseEndpoint();if(!r)throw new Error("Unable to derive cwd download endpoint. Please provide botProviderEndpoint in config.");const o=`custom_channel_id=${encodeURIComponent(t)}&relative_path=${encodeURIComponent(e)}`,i=`${r}/cwd/download?${o}`,s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);try{const a=await fetch(i,{method:"GET",headers:s});if(!a.ok)throw new Error(`CWD download failed: ${a.status} ${a.statusText}`);const c=await a.blob(),u=e.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] CWD download response:",{filename:u,size:c.size}),{blob:c,filename:u}}catch(a){throw console.error("[AsgardServiceClient] CWD download error:",a),a}}deriveBlobEndpoint(){const e=this.getBaseEndpoint();return e?`${e}/blob`:null}getBaseEndpoint(){let e=this.botProviderEndpoint;return!e&&this.endpoint&&(e=this.endpoint.replace("/message/sse","")),e?e.replace(/\/+$/,""):null}}const b=[];for(let n=0;n<256;++n)b.push((n+256).toString(16).slice(1));function tn(n,e=0){return(b[n[e+0]]+b[n[e+1]]+b[n[e+2]]+b[n[e+3]]+"-"+b[n[e+4]]+b[n[e+5]]+"-"+b[n[e+6]]+b[n[e+7]]+"-"+b[n[e+8]]+b[n[e+9]]+"-"+b[n[e+10]]+b[n[e+11]]+b[n[e+12]]+b[n[e+13]]+b[n[e+14]]+b[n[e+15]]).toLowerCase()}let q;const nn=new Uint8Array(16);function rn(){if(!q){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");q=crypto.getRandomValues.bind(crypto)}return q(nn)}const on=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),de={randomUUID:on};function sn(n,e,t){n=n||{};const r=n.random??n.rng?.()??rn();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,tn(r)}function De(n,e,t){return de.randomUUID&&!n?de.randomUUID():sn(n)}class S{messages=null;pendingConsent=null;constructor({messages:e,pendingConsent:t=null}){this.messages=e,this.pendingConsent=t??null}pushMessage(e){const t=new Map(this.messages);return t.set(e.messageId,e),new S({messages:t,pendingConsent:this.pendingConsent})}clearPendingConsent(){return this.pendingConsent?new S({messages:this.messages,pendingConsent:null}):this}onMessage(e){switch(e.eventType){case d.MESSAGE_START:return this.onMessageStart(e);case d.MESSAGE_DELTA:return this.onMessageDelta(e);case d.MESSAGE_COMPLETE:return this.onMessageComplete(e);case d.TOOL_CALL_START:return this.onToolCallStart(e);case d.TOOL_CALL_COMPLETE:return this.onToolCallComplete(e);case d.TOOL_CALL_CONSENT:return this.onToolCallConsent(e);case d.ERROR:return this.onMessageError(e);default:return this}}onMessageStart(e){const t=e.fact.messageStart.message,r=new Map(this.messages);return r.set(t.messageId,{type:"bot",eventType:d.MESSAGE_START,isTyping:!0,typingText:"",messageId:t.messageId,message:t,time:new Date,traceId:e.traceId,raw:""}),new S({messages:r,pendingConsent:this.pendingConsent})}onMessageDelta(e){const t=e.fact.messageDelta.message,r=new Map(this.messages),o=r.get(t.messageId);if(o?.type!=="bot")return this;const i=`${o?.typingText??""}${t.text}`;return r.set(t.messageId,{type:"bot",eventType:d.MESSAGE_DELTA,isTyping:!0,typingText:i,messageId:t.messageId,message:t,time:new Date,traceId:e.traceId??o.traceId,raw:o.raw}),new S({messages:r,pendingConsent:this.pendingConsent})}onMessageComplete(e){const t=e.fact.messageComplete.message,r=new Map(this.messages),o=r.get(t.messageId);return r.set(t.messageId,{type:"bot",eventType:d.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:t.messageId,message:t,time:new Date,traceId:e.traceId??(o?.type==="bot"?o.traceId:void 0),raw:JSON.stringify(e)}),new S({messages:r,pendingConsent:this.pendingConsent})}onMessageError(e){const t=De(),r=e.fact.runError.error,o=new Map(this.messages);return o.set(t,{type:"error",eventType:d.ERROR,messageId:t,error:r,time:new Date,traceId:e.traceId}),new S({messages:o,pendingConsent:this.pendingConsent})}onToolCallStart(e){const t=e.fact.toolCallStart,r=new Map(this.messages),o=`${t.processId}-${t.callSeq}`,i={type:"tool-call",eventType:d.TOOL_CALL_START,messageId:o,processId:t.processId,callSeq:t.callSeq,toolName:t.toolCall.toolName,reason:t.toolCall.reason,toolsetName:t.toolCall.toolsetName,parameter:t.toolCall.parameter,isComplete:!1,time:new Date,traceId:e.traceId};return r.set(o,i),new S({messages:r,pendingConsent:this.pendingConsent})}onToolCallComplete(e){const t=e.fact.toolCallComplete,r=new Map(this.messages),o=`${t.processId}-${t.callSeq}`,i=r.get(o);if(i?.type==="tool-call"){const s={...i,eventType:d.TOOL_CALL_COMPLETE,result:t.toolCallResult,isComplete:!0,traceId:e.traceId??i.traceId};r.set(o,s)}return new S({messages:r,pendingConsent:this.pendingConsent})}onToolCallConsent(e){const t=e.fact.toolCallConsent;return new S({messages:this.messages,pendingConsent:t})}}class F{client;customChannelId;customMessageId;isConnecting$;conversation$;statesObserver;statesSubscription;currentUserMessageId;lastSentMessageId;constructor(e){if(!e.client)throw new Error("client must be required");if(!e.customChannelId)throw new Error("customChannelId must be required");this.client=e.client,this.customChannelId=e.customChannelId,this.customMessageId=e.customMessageId,this.isConnecting$=new se(!1),this.conversation$=new se(e.conversation),this.statesObserver=e.statesObserver}static create(e){const t=new F(e);return t.subscribe(),t}static async reset(e,t,r,o){const i=new F(e);try{return i.subscribe(),o?.(i),await i.resetChannel(t,r),i}catch(s){throw i.close(),s}}subscribe(){this.statesSubscription=Nt([this.isConnecting$,this.conversation$]).pipe(K(([e,t])=>({isConnecting:e,conversation:t}))).subscribe(this.statesObserver)}resolvePayload(e){if(typeof e=="function")try{return e()}catch(t){throw new Error(`Failed to resolve payload function: ${t instanceof Error?t.message:String(t)}`)}return e}fetchSse(e,t){return new Promise((r,o)=>{this.isConnecting$.next(!0),this.client.fetchSse(e,{onSseStart:t?.onSseStart,onSseMessage:i=>{if(t?.onSseMessage?.(i),this.currentUserMessageId&&i.traceId){const s=new Map(this.conversation$.value.messages),a=s.get(this.currentUserMessageId);a&&a.type==="user"&&(s.set(this.currentUserMessageId,{...a,traceId:i.traceId}),this.conversation$.next(new S({messages:s}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(i))},onSseError:i=>{t?.onSseError?.(i),this.isConnecting$.next(!1),this.currentUserMessageId=void 0,o(i)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.isConnecting$.next(!1),this.currentUserMessageId=void 0,r()}})})}resetChannel(e,t){return this.fetchSse({action:M.RESET_CHANNEL,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:e?.text||"",payload:this.resolvePayload(e?.payload)},t)}sendMessage(e,t){const r=e.text.trim(),o=e.customMessageId??De();return this.currentUserMessageId=o,this.lastSentMessageId=o,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:o,text:r,blobIds:e.blobIds,filePreviewUrls:e.filePreviewUrls,documentNames:e.documentNames,time:new Date})),this.fetchSse({action:M.NONE,customChannelId:this.customChannelId,customMessageId:o,payload:this.resolvePayload(e?.payload),text:r,blobIds:e?.blobIds},t)}replyToolCallConsents(e,t,r){return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse({action:M.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(r),text:"",toolCallConsents:e},t)}close(){this.isConnecting$.complete(),this.conversation$.complete(),this.statesSubscription?.unsubscribe()}}exports.AsgardServiceClient=en;exports.Channel=F;exports.Conversation=S;exports.EventType=d;exports.FetchSseAction=M;exports.HttpError=Q;exports.MessageTemplateType=pe;exports.ToolCallConsentResult=he;exports.isHttpError=Fe;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class q extends Error{status;statusText;body;constructor(t,e,r){super(`HTTP ${t}: ${e}`),this.name="HttpError",this.status=t,this.statusText=e,this.body=r}}function tt(n){return n instanceof q}var N=(n=>(n.RESET_CHANNEL="RESET_CHANNEL",n.NONE="NONE",n.RESPONSE_TOOL_CALL_CONSENT="RESPONSE_TOOL_CALL_CONSENT",n))(N||{}),d=(n=>(n.INIT="asgard.run.init",n.PROCESS="asgard.process",n.PROCESS_START="asgard.process.start",n.PROCESS_COMPLETE="asgard.process.complete",n.MESSAGE="asgard.message",n.MESSAGE_START="asgard.message.start",n.MESSAGE_DELTA="asgard.message.delta",n.MESSAGE_COMPLETE="asgard.message.complete",n.MESSAGE_USER="asgard.message.user",n.MESSAGE_THINKING_START="asgard.message.thinking.start",n.MESSAGE_THINKING_DELTA="asgard.message.thinking.delta",n.MESSAGE_THINKING_COMPLETE="asgard.message.thinking.complete",n.TOOL_CALL="asgard.tool_call",n.TOOL_CALL_START="asgard.tool_call.start",n.TOOL_CALL_COMPLETE="asgard.tool_call.complete",n.TOOL_CALL_CONSENT="asgard.tool_call.consent",n.SUBAGENT_START="asgard.subagent.start",n.SUBAGENT_COMPLETE="asgard.subagent.complete",n.CHANNEL_TITLE_UPDATE="asgard.channel.title.update",n.DONE="asgard.run.done",n.ERROR="asgard.run.error",n))(d||{}),ve=(n=>(n.ALLOW_ONCE="ALLOW_ONCE",n.ALLOW_ALWAYS="ALLOW_ALWAYS",n.DENY_ONCE="DENY_ONCE",n))(ve||{}),ye=(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))(ye||{}),J=function(n,t){return J=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,r){e.__proto__=r}||function(e,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])},J(n,t)};function w(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");J(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function nt(n,t,e,r){function s(o){return o instanceof e?o:new e(function(i){i(o)})}return new(e||(e=Promise))(function(o,i){function a(h){try{c(r.next(h))}catch(g){i(g)}}function u(h){try{c(r.throw(h))}catch(g){i(g)}}function c(h){h.done?o(h.value):s(h.value).then(a,u)}c((r=r.apply(n,t||[])).next())})}function be(n,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(h){return u([c,h])}}function u(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(e=0)),e;)try{if(r=1,s&&(o=c[0]&2?s.return:c[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,c[1])).done)return o;switch(s=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return e.label++,{value:c[1],done:!1};case 5:e.label++,s=c[1],c=[0];continue;case 7:c=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){e=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){e.label=c[1];break}if(c[0]===6&&e.label<o[1]){e.label=o[1],o=c;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(c);break}o[2]&&e.ops.pop(),e.trys.pop();continue}c=t.call(n,e)}catch(h){c=[6,h],s=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function k(n){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&n[t],r=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function j(n,t){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var r=e.call(n),s,o=[],i;try{for(;(t===void 0||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(e=r.return)&&e.call(r)}finally{if(i)throw i.error}}return o}function D(n,t,e){if(e||arguments.length===2)for(var r=0,s=t.length,o;r<s;r++)(o||!(r in t))&&(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return n.concat(o||Array.prototype.slice.call(t))}function L(n){return this instanceof L?(this.v=n,this):new L(n)}function rt(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=e.apply(n,t||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),s[Symbol.asyncIterator]=function(){return this},s;function i(l){return function(f){return Promise.resolve(f).then(l,g)}}function a(l,f){r[l]&&(s[l]=function(p){return new Promise(function(A,E){o.push([l,p,A,E])>1||u(l,p)})},f&&(s[l]=f(s[l])))}function u(l,f){try{c(r[l](f))}catch(p){v(o[0][3],p)}}function c(l){l.value instanceof L?Promise.resolve(l.value.v).then(h,g):v(o[0][2],l)}function h(l){u("next",l)}function g(l){u("throw",l)}function v(l,f){l(f),o.shift(),o.length&&u(o[0][0],o[0][1])}}function st(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=n[Symbol.asyncIterator],e;return t?t.call(n):(n=typeof k=="function"?k(n):n[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(o){e[o]=n[o]&&function(i){return new Promise(function(a,u){i=n[o](i),s(a,u,i.done,i.value)})}}function s(o,i,a,u){Promise.resolve(u).then(function(c){o({value:c,done:a})},i)}}function m(n){return typeof n=="function"}function Se(n){var t=function(r){Error.call(r),r.stack=new Error().stack},e=n(t);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var X=Se(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
2
+ `+e.map(function(r,s){return s+1+") "+r.toString()}).join(`
3
+ `):"",this.name="UnsubscriptionError",this.errors=e}});function F(n,t){if(n){var e=n.indexOf(t);0<=e&&n.splice(e,1)}}var U=(function(){function n(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var t,e,r,s,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=k(i),u=a.next();!u.done;u=a.next()){var c=u.value;c.remove(this)}}catch(p){t={error:p}}finally{try{u&&!u.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}else i.remove(this);var h=this.initialTeardown;if(m(h))try{h()}catch(p){o=p instanceof X?p.errors:[p]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var v=k(g),l=v.next();!l.done;l=v.next()){var f=l.value;try{ie(f)}catch(p){o=o??[],p instanceof X?o=D(D([],j(o)),j(p.errors)):o.push(p)}}}catch(p){r={error:p}}finally{try{l&&!l.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}}if(o)throw new X(o)}},n.prototype.add=function(t){var e;if(t&&t!==this)if(this.closed)ie(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)&&F(e,t)},n.prototype.remove=function(t){var e=this._finalizers;e&&F(e,t),t instanceof n&&t._removeParent(this)},n.EMPTY=(function(){var t=new n;return t.closed=!0,t})(),n})(),Ee=U.EMPTY;function Ie(n){return n instanceof U||n&&"closed"in n&&m(n.remove)&&m(n.add)&&m(n.unsubscribe)}function ie(n){m(n)?n():n.unsubscribe()}var ot={Promise:void 0},it={setTimeout:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setTimeout.apply(void 0,D([n,t],j(e)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function we(n){it.setTimeout(function(){throw n})}function Q(){}function K(n){n()}var ne=(function(n){w(t,n);function t(e){var r=n.call(this)||this;return r.isStopped=!1,e?(r.destination=e,Ie(e)&&e.add(r)):r.destination=ut,r}return t.create=function(e,r,s){return new Z(e,r,s)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(U),at=(function(){function n(t){this.partialObserver=t}return n.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(r){G(r)}},n.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(r){G(r)}else G(t)},n.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(e){G(e)}},n})(),Z=(function(n){w(t,n);function t(e,r,s){var o=n.call(this)||this,i;return m(e)||!e?i={next:e??void 0,error:r??void 0,complete:s??void 0}:i=e,o.destination=new at(i),o}return t})(ne);function G(n){we(n)}function ct(n){throw n}var ut={closed:!0,next:Q,error:ct,complete:Q},re=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function V(n){return n}function lt(n){return n.length===0?V:n.length===1?n[0]:function(e){return n.reduce(function(r,s){return s(r)},e)}}var S=(function(){function n(t){t&&(this._subscribe=t)}return n.prototype.lift=function(t){var e=new n;return e.source=this,e.operator=t,e},n.prototype.subscribe=function(t,e,r){var s=this,o=ht(t)?t:new Z(t,e,r);return K(function(){var i=s,a=i.operator,u=i.source;o.add(a?a.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},n.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},n.prototype.forEach=function(t,e){var r=this;return e=ae(e),new e(function(s,o){var i=new Z({next:function(a){try{t(a)}catch(u){o(u),i.unsubscribe()}},error:o,complete:s});r.subscribe(i)})},n.prototype._subscribe=function(t){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(t)},n.prototype[re]=function(){return this},n.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return lt(t)(this)},n.prototype.toPromise=function(t){var e=this;return t=ae(t),new t(function(r,s){var o;e.subscribe(function(i){return o=i},function(i){return s(i)},function(){return r(o)})})},n.create=function(t){return new n(t)},n})();function ae(n){var t;return(t=n??ot.Promise)!==null&&t!==void 0?t:Promise}function dt(n){return n&&m(n.next)&&m(n.error)&&m(n.complete)}function ht(n){return n&&n instanceof ne||dt(n)&&Ie(n)}function ft(n){return m(n?.lift)}function M(n){return function(t){if(ft(t))return t.lift(function(e){try{return n(e,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function O(n,t,e,r,s){return new pt(n,t,e,r,s)}var pt=(function(n){w(t,n);function t(e,r,s,o,i,a){var u=n.call(this,e)||this;return u.onFinalize=i,u.shouldUnsubscribe=a,u._next=r?function(c){try{r(c)}catch(h){e.error(h)}}:n.prototype._next,u._error=o?function(c){try{o(c)}catch(h){e.error(h)}finally{this.unsubscribe()}}:n.prototype._error,u._complete=s?function(){try{s()}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 r=this.closed;n.prototype.unsubscribe.call(this),!r&&((e=this.onFinalize)===null||e===void 0||e.call(this))}},t})(ne),gt=Se(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),se=(function(n){w(t,n);function t(){var e=n.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return t.prototype.lift=function(e){var r=new ce(this,this);return r.operator=e,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new gt},t.prototype.next=function(e){var r=this;K(function(){var s,o;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=k(r.currentObservers),a=i.next();!a.done;a=i.next()){var u=a.value;u.next(e)}}catch(c){s={error:c}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(s)throw s.error}}}})},t.prototype.error=function(e){var r=this;K(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=e;for(var s=r.observers;s.length;)s.shift().error(e)}})},t.prototype.complete=function(){var e=this;K(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var r=e.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(e){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,e)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var r=this,s=this,o=s.hasError,i=s.isStopped,a=s.observers;return o||i?Ee:(this.currentObservers=null,a.push(e),new U(function(){r.currentObservers=null,F(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var r=this,s=r.hasError,o=r.thrownError,i=r.isStopped;s?e.error(o):i&&e.complete()},t.prototype.asObservable=function(){var e=new S;return e.source=this,e},t.create=function(e,r){return new ce(e,r)},t})(S),ce=(function(n){w(t,n);function t(e,r){var s=n.call(this)||this;return s.destination=e,s.source=r,s}return t.prototype.next=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,e)},t.prototype.error=function(e){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,e)},t.prototype.complete=function(){var e,r;(r=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||r===void 0||r.call(e)},t.prototype._subscribe=function(e){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(e))!==null&&s!==void 0?s:Ee},t})(se),R=(function(n){w(t,n);function t(e){var r=n.call(this)||this;return r._value=e,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(e){var r=n.prototype._subscribe.call(this,e);return!r.closed&&e.next(this._value),r},t.prototype.getValue=function(){var e=this,r=e.hasError,s=e.thrownError,o=e._value;if(r)throw s;return this._throwIfClosed(),o},t.prototype.next=function(e){n.prototype.next.call(this,this._value=e)},t})(se),mt={now:function(){return Date.now()}},vt=(function(n){w(t,n);function t(e,r){return n.call(this)||this}return t.prototype.schedule=function(e,r){return this},t})(U),ue={setInterval:function(n,t){for(var e=[],r=2;r<arguments.length;r++)e[r-2]=arguments[r];return setInterval.apply(void 0,D([n,t],j(e)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},yt=(function(n){w(t,n);function t(e,r){var s=n.call(this,e,r)||this;return s.scheduler=e,s.work=r,s.pending=!1,s}return t.prototype.schedule=function(e,r){var s;if(r===void 0&&(r=0),this.closed)return this;this.state=e;var o=this.id,i=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(i,o,r)),this.pending=!0,this.delay=r,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(i,this.id,r),this},t.prototype.requestAsyncId=function(e,r,s){return s===void 0&&(s=0),ue.setInterval(e.flush.bind(e,this),s)},t.prototype.recycleAsyncId=function(e,r,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return r;r!=null&&ue.clearInterval(r)},t.prototype.execute=function(e,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(e,r);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,r){var s=!1,o;try{this.work(e)}catch(i){s=!0,o=i||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},t.prototype.unsubscribe=function(){if(!this.closed){var e=this,r=e.id,s=e.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,F(o,this),r!=null&&(this.id=this.recycleAsyncId(s,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},t})(vt),le=(function(){function n(t,e){e===void 0&&(e=n.now),this.schedulerActionCtor=t,this.now=e}return n.prototype.schedule=function(t,e,r){return e===void 0&&(e=0),new this.schedulerActionCtor(this,t).schedule(r,e)},n.now=mt.now,n})(),bt=(function(n){w(t,n);function t(e,r){r===void 0&&(r=le.now);var s=n.call(this,e,r)||this;return s.actions=[],s._active=!1,s}return t.prototype.flush=function(e){var r=this.actions;if(this._active){r.push(e);return}var s;this._active=!0;do if(s=e.execute(e.state,e.delay))break;while(e=r.shift());if(this._active=!1,s){for(;e=r.shift();)e.unsubscribe();throw s}},t})(le),Te=new bt(yt),St=Te,Et=new S(function(n){return n.complete()});function Ce(n){return n&&m(n.schedule)}function Oe(n){return n[n.length-1]}function It(n){return m(Oe(n))?n.pop():void 0}function Ae(n){return Ce(Oe(n))?n.pop():void 0}var _e=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function Me(n){return m(n?.then)}function xe(n){return m(n[re])}function Le(n){return Symbol.asyncIterator&&m(n?.[Symbol.asyncIterator])}function ke(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function wt(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Pe=wt();function Ue(n){return m(n?.[Pe])}function Ne(n){return rt(this,arguments,function(){var e,r,s,o;return be(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,L(e.read())];case 3:return r=i.sent(),s=r.value,o=r.done,o?[4,L(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,L(s)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function Re(n){return m(n?.getReader)}function x(n){if(n instanceof S)return n;if(n!=null){if(xe(n))return Tt(n);if(_e(n))return Ct(n);if(Me(n))return Ot(n);if(Le(n))return $e(n);if(Ue(n))return At(n);if(Re(n))return _t(n)}throw ke(n)}function Tt(n){return new S(function(t){var e=n[re]();if(m(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ct(n){return new S(function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}function Ot(n){return new S(function(t){n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,we)})}function At(n){return new S(function(t){var e,r;try{for(var s=k(n),o=s.next();!o.done;o=s.next()){var i=o.value;if(t.next(i),t.closed)return}}catch(a){e={error:a}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}t.complete()})}function $e(n){return new S(function(t){Mt(n,t).catch(function(e){return t.error(e)})})}function _t(n){return $e(Ne(n))}function Mt(n,t){var e,r,s,o;return nt(this,void 0,void 0,function(){var i,a;return be(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),e=st(n),u.label=1;case 1:return[4,e.next()];case 2:if(r=u.sent(),!!r.done)return[3,4];if(i=r.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(),s={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),r&&!r.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(s)throw s.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function C(n,t,e,r,s){r===void 0&&(r=0),s===void 0&&(s=!1);var o=t.schedule(function(){e(),s?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(o),!s)return o}function je(n,t){return t===void 0&&(t=0),M(function(e,r){e.subscribe(O(r,function(s){return C(r,n,function(){return r.next(s)},t)},function(){return C(r,n,function(){return r.complete()},t)},function(s){return C(r,n,function(){return r.error(s)},t)}))})}function De(n,t){return t===void 0&&(t=0),M(function(e,r){r.add(n.schedule(function(){return e.subscribe(r)},t))})}function xt(n,t){return x(n).pipe(De(t),je(t))}function Lt(n,t){return x(n).pipe(De(t),je(t))}function kt(n,t){return new S(function(e){var r=0;return t.schedule(function(){r===n.length?e.complete():(e.next(n[r++]),e.closed||this.schedule())})})}function Pt(n,t){return new S(function(e){var r;return C(e,t,function(){r=n[Pe](),C(e,t,function(){var s,o,i;try{s=r.next(),o=s.value,i=s.done}catch(a){e.error(a);return}i?e.complete():e.next(o)},0,!0)}),function(){return m(r?.return)&&r.return()}})}function He(n,t){if(!n)throw new Error("Iterable cannot be null");return new S(function(e){C(e,t,function(){var r=n[Symbol.asyncIterator]();C(e,t,function(){r.next().then(function(s){s.done?e.complete():e.next(s.value)})},0,!0)})})}function Ut(n,t){return He(Ne(n),t)}function Nt(n,t){if(n!=null){if(xe(n))return xt(n,t);if(_e(n))return kt(n,t);if(Me(n))return Lt(n,t);if(Le(n))return He(n,t);if(Ue(n))return Pt(n,t);if(Re(n))return Ut(n,t)}throw ke(n)}function oe(n,t){return t?Nt(n,t):x(n)}function Rt(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ae(n);return oe(n,e)}function $t(n){return n instanceof Date&&!isNaN(n)}function P(n,t){return M(function(e,r){var s=0;e.subscribe(O(r,function(o){r.next(n.call(t,o,s++))}))})}var jt=Array.isArray;function Dt(n,t){return jt(t)?n.apply(void 0,D([],j(t))):n(t)}function Ht(n){return P(function(t){return Dt(n,t)})}var Gt=Array.isArray,Kt=Object.getPrototypeOf,Ft=Object.prototype,Bt=Object.keys;function qt(n){if(n.length===1){var t=n[0];if(Gt(t))return{args:t,keys:null};if(Vt(t)){var e=Bt(t);return{args:e.map(function(r){return t[r]}),keys:e}}}return{args:n,keys:null}}function Vt(n){return n&&typeof n=="object"&&Kt(n)===Ft}function Yt(n,t){return n.reduce(function(e,r,s){return e[r]=t[s],e},{})}function Wt(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Ae(n),r=It(n),s=qt(n),o=s.args,i=s.keys;if(o.length===0)return oe([],e);var a=new S(Xt(o,e,i?function(u){return Yt(i,u)}:V));return r?a.pipe(Ht(r)):a}function Xt(n,t,e){return e===void 0&&(e=V),function(r){de(t,function(){for(var s=n.length,o=new Array(s),i=s,a=s,u=function(h){de(t,function(){var g=oe(n[h],t),v=!1;g.subscribe(O(r,function(l){o[h]=l,v||(v=!0,a--),a||r.next(e(o.slice()))},function(){--i||r.complete()}))},r)},c=0;c<s;c++)u(c)},r)}}function de(n,t,e){n?C(e,n,t):t()}function zt(n,t,e,r,s,o,i,a){var u=[],c=0,h=0,g=!1,v=function(){g&&!u.length&&!c&&t.complete()},l=function(p){return c<r?f(p):u.push(p)},f=function(p){c++;var A=!1;x(e(p,h++)).subscribe(O(t,function(E){t.next(E)},function(){A=!0},void 0,function(){if(A)try{c--;for(var E=function(){var _=u.shift();i||f(_)};u.length&&c<r;)E();v()}catch(_){t.error(_)}}))};return n.subscribe(O(t,l,function(){g=!0,v()})),function(){}}function B(n,t,e){return e===void 0&&(e=1/0),m(t)?B(function(r,s){return P(function(o,i){return t(r,o,s,i)})(x(n(r,s)))},e):(typeof t=="number"&&(e=t),M(function(r,s){return zt(r,s,n,e)}))}function Jt(n,t,e){n===void 0&&(n=0),e===void 0&&(e=St);var r=-1;return t!=null&&(Ce(t)?e=t:r=t),new S(function(s){var o=$t(n)?+n-e.now():n;o<0&&(o=0);var i=0;return e.schedule(function(){s.closed||(s.next(i++),0<=r?this.schedule(void 0,r):s.complete())},o)})}function Qt(n,t){return m(t)?B(n,t,1):B(n,1)}function Zt(n){return n<=0?function(){return Et}:M(function(t,e){var r=0;t.subscribe(O(e,function(s){++r<=n&&(e.next(s),n<=r&&e.complete())}))})}function en(n){return P(function(){return n})}function tn(n,t){return B(function(e,r){return x(n(e,r)).pipe(Zt(1),en(e))})}function nn(n,t){t===void 0&&(t=Te);var e=Jt(n,t);return tn(function(){return e})}function ee(n,t){return t===void 0&&(t=V),n=n??rn,M(function(e,r){var s,o=!0;e.subscribe(O(r,function(i){var a=t(i);(o||!n(s,a))&&(o=!1,s=a,r.next(i))}))})}function rn(n,t){return n===t}function sn(n){return M(function(t,e){x(n).subscribe(O(e,function(){return e.complete()},Q)),!e.closed&&t.subscribe(e)})}async function on(n,t){const e=n.getReader();let r;for(;!(r=await e.read()).done;)t(r.value)}function an(n){let t,e,r,s=!1;return function(i){t===void 0?(t=i,e=0,r=-1):t=un(t,i);const a=t.length;let u=0;for(;e<a;){s&&(t[e]===10&&(u=++e),s=!1);let c=-1;for(;e<a&&c===-1;++e)switch(t[e]){case 58:r===-1&&(r=e-u);break;case 13:s=!0;case 10:c=e;break}if(c===-1)break;n(t.subarray(u,c),r),u=e,r=-1}u===a?t=void 0:u!==0&&(t=t.subarray(u),e-=u)}}function cn(n,t,e){let r=he();const s=new TextDecoder;return function(i,a){if(i.length===0)e?.(r),r=he();else if(a>0){const u=s.decode(i.subarray(0,a)),c=a+(i[a+1]===32?2:1),h=s.decode(i.subarray(c));switch(u){case"data":r.data=r.data?r.data+`
4
+ `+h:h;break;case"event":r.event=h;break;case"id":n(r.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||t(r.retry=g);break}}}}function un(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function he(){return{data:"",event:"",id:"",retry:void 0}}var ln=function(n,t){var e={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&t.indexOf(r)<0&&(e[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(n,r[s])&&(e[r[s]]=n[r[s]]);return e};const te="text/event-stream",dn=1e3,fe="last-event-id";function hn(n,t){var{signal:e,headers:r,onopen:s,onmessage:o,onclose:i,onerror:a,openWhenHidden:u,fetch:c}=t,h=ln(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,v)=>{const l=Object.assign({},r);l.accept||(l.accept=te);let f;function p(){f.abort(),document.hidden||Y()}u||document.addEventListener("visibilitychange",p);let A=dn,E=0;function _(){document.removeEventListener("visibilitychange",p),window.clearTimeout(E),f.abort()}e?.addEventListener("abort",()=>{_(),g()});const Ze=c??window.fetch,et=s??fn;async function Y(){var W;f=new AbortController;try{const H=await Ze(n,Object.assign(Object.assign({},h),{headers:l,signal:f.signal}));await et(H),await on(H.body,an(cn(T=>{T?l[fe]=T:delete l[fe]},T=>{A=T},o))),i?.(),_(),g()}catch(H){if(!f.signal.aborted)try{const T=(W=a?.(H))!==null&&W!==void 0?W:A;window.clearTimeout(E),E=window.setTimeout(Y,T)}catch(T){_(),v(T)}}}Y()})}function fn(n){const t=n.headers.get("content-type");if(!t?.startsWith(te))throw new Error(`Expected content-type to be ${te}, Actual: ${t}`)}function pe(n){const{endpoint:t,apiKey:e,payload:r,debugMode:s,customHeaders:o}=n,i=n.method??"POST";return new S(a=>{const u=new AbortController;let c,h=!1;const g={"Content-Type":"application/json",...o};e&&(g["X-API-KEY"]=e);const v=new URL(t);return s&&v.searchParams.set("is_debug","true"),hn(v.toString(),{method:i,headers:g,body:i==="POST"&&r?JSON.stringify(r):void 0,signal:u.signal,openWhenHidden:!0,onopen:async l=>{if(l.ok)c=l.headers.get("X-Trace-Id")??void 0;else{let f;try{f=await l.json()}catch{try{f=await l.text()}catch{f=null}}a.error(new q(l.status,l.statusText,f)),u.abort()}},onmessage:l=>{l.id&&(h=!0);const f=JSON.parse(l.data);c?f.traceId=c:f.requestId&&(f.traceId=f.requestId,c||(c=f.requestId)),a.next(f)},onclose:()=>{a.complete()},onerror:l=>{if(!h)throw a.error(l),u.abort(),l}}),()=>{u.abort()}})}class pn{listeners={};on(t,e){this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).concat(e)})}off(t,e){this.listeners[t]&&(this.listeners=Object.assign({},this.listeners,{[t]:(this.listeners[t]??[]).filter(r=>r!==e)}))}remove(t){delete this.listeners[t]}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(r=>r(...e))}}class gn{apiKey;endpoint;botProviderEndpoint;debugMode;destroy$=new se;closed=!1;detached=!1;detachTimer;inFlight=0;sseEmitter=new pn;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 d.INIT:this.sseEmitter.emit(d.INIT,t);break;case d.PROCESS_START:case d.PROCESS_COMPLETE:this.sseEmitter.emit(d.PROCESS,t);break;case d.MESSAGE_START:case d.MESSAGE_DELTA:case d.MESSAGE_COMPLETE:this.sseEmitter.emit(d.MESSAGE,t);break;case d.TOOL_CALL_START:case d.TOOL_CALL_COMPLETE:this.sseEmitter.emit(d.TOOL_CALL,t);break;case d.TOOL_CALL_CONSENT:this.sseEmitter.emit(d.TOOL_CALL_CONSENT,t);break;case d.DONE:this.sseEmitter.emit(d.DONE,t);break;case d.ERROR:this.sseEmitter.emit(d.ERROR,t);break}}fetchSse(t,e){e?.onSseStart?.(),this.inFlight+=1,this.runSse(pe({apiKey:this.apiKey,endpoint:this.endpoint,debugMode:this.debugMode,payload:this.transformSsePayload?.(t)??t,customHeaders:this.customHeaders}),e)}rejoinSse(t,e){e?.onSseStart?.(),this.inFlight+=1;const r=new URL(this.endpoint);r.searchParams.set("custom_channel_id",t),this.runSse(pe({apiKey:this.apiKey,endpoint:r.toString(),debugMode:this.debugMode,method:"GET",customHeaders:this.customHeaders}),e)}deriveChannelMetadataEndpoint(){const t=this.getBaseEndpoint();return t?`${t}/channel/metadata`:null}async channelMetadata(t){const e=this.deriveChannelMetadataEndpoint();if(!e)throw new Error("Unable to derive channel metadata endpoint. Please provide botProviderEndpoint in config.");const r=new URL(e);r.searchParams.set("custom_channel_id",t);const s={...this.customHeaders};this.apiKey&&(s["X-API-KEY"]=this.apiKey);const o=await fetch(r.toString(),{method:"GET",headers:s});if(o.status===404)return null;if(!o.ok)throw new q(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}}runSse(t,e){t.pipe(Qt(r=>Rt(r).pipe(nn(e?.delayTime??50))),sn(this.destroy$)).subscribe({next:r=>{this.detached||(e?.onSseMessage?.(r),this.handleEvent(r))},error:r=>{this.detached||e?.onSseError?.(r),this.onRunSettled()},complete:()=>{this.detached||e?.onSseCompleted?.(),this.onRunSettled()}})}detach(t){if(!(this.detached||this.closed)){if(this.detached=!0,this.inFlight===0){this.close();return}this.detachTimer=setTimeout(()=>this.close(),t.timeoutMs)}}onRunSettled(){this.inFlight=Math.max(0,this.inFlight-1),this.detached&&this.inFlight===0&&this.close()}close(){this.closed||(this.closed=!0,this.detachTimer&&(clearTimeout(this.detachTimer),this.detachTimer=void 0),this.destroy$.next(),this.destroy$.complete())}async uploadFile(t,e){const r=this.deriveBlobEndpoint();if(!r)throw new Error("Unable to derive blob endpoint. Please provide botProviderEndpoint in config.");const s=new FormData;s.append("file",t),s.append("customChannelId",e);const o={...this.customHeaders};this.apiKey&&(o["X-API-KEY"]=this.apiKey);try{const i=await fetch(r,{method:"POST",headers:o,body:s});if(!i.ok)throw new Error(`Upload failed: ${i.status} ${i.statusText}`);const a=await i.json();return this.debugMode&&console.log("[AsgardServiceClient] File upload response:",a),a}catch(i){throw console.error("[AsgardServiceClient] File upload error:",i),i}}async downloadCwdFile(t,e){const r=this.getBaseEndpoint();if(!r)throw new Error("Unable to derive cwd download endpoint. Please provide botProviderEndpoint in config.");const s=`custom_channel_id=${encodeURIComponent(e)}&relative_path=${encodeURIComponent(t)}`,o=`${r}/cwd/download?${s}`,i={...this.customHeaders};this.apiKey&&(i["X-API-KEY"]=this.apiKey);try{const a=await fetch(o,{method:"GET",headers:i});if(!a.ok)throw new Error(`CWD download failed: ${a.status} ${a.statusText}`);const u=await a.blob(),c=t.split("/").pop()||"download";return this.debugMode&&console.log("[AsgardServiceClient] CWD download response:",{filename:c,size:u.size}),{blob:u,filename:c}}catch(a){throw console.error("[AsgardServiceClient] CWD download error:",a),a}}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 b=[];for(let n=0;n<256;++n)b.push((n+256).toString(16).slice(1));function mn(n,t=0){return(b[n[t+0]]+b[n[t+1]]+b[n[t+2]]+b[n[t+3]]+"-"+b[n[t+4]]+b[n[t+5]]+"-"+b[n[t+6]]+b[n[t+7]]+"-"+b[n[t+8]]+b[n[t+9]]+"-"+b[n[t+10]]+b[n[t+11]]+b[n[t+12]]+b[n[t+13]]+b[n[t+14]]+b[n[t+15]]).toLowerCase()}let z;const vn=new Uint8Array(16);function yn(){if(!z){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");z=crypto.getRandomValues.bind(crypto)}return z(vn)}const bn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ge={randomUUID:bn};function Sn(n,t,e){n=n||{};const r=n.random??n.rng?.()??yn();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,mn(r)}function Ge(n,t,e){return ge.randomUUID&&!n?ge.randomUUID():Sn(n)}class y{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 y({messages:e,pendingConsent:this.pendingConsent})}clearPendingConsent(){return this.pendingConsent?new y({messages:this.messages,pendingConsent:null}):this}onMessage(t){switch(t.eventType){case d.MESSAGE_START:return this.onMessageStart(t);case d.MESSAGE_DELTA:return this.onMessageDelta(t);case d.MESSAGE_COMPLETE:return this.onMessageComplete(t);case d.MESSAGE_USER:return this.onMessageUser(t);case d.MESSAGE_THINKING_START:return this.onThinkingStart(t);case d.MESSAGE_THINKING_DELTA:return this.onThinkingDelta(t);case d.MESSAGE_THINKING_COMPLETE:return this.onThinkingComplete(t);case d.TOOL_CALL_START:return this.onToolCallStart(t);case d.TOOL_CALL_COMPLETE:return this.onToolCallComplete(t);case d.TOOL_CALL_CONSENT:return this.onToolCallConsent(t);case d.SUBAGENT_START:return this.onSubagentStart(t);case d.SUBAGENT_COMPLETE:return this.onSubagentComplete(t);case d.ERROR:return this.onMessageError(t);default:return this}}isTerminalBot(t){return t?.type==="bot"&&!t.isTyping}isTerminalThinking(t){return t?.type==="thinking"&&!t.isThinking}onMessageStart(t){const e=t.fact.messageStart.message;if(this.isTerminalBot(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages);return r.set(e.messageId,{type:"bot",eventType:d.MESSAGE_START,isTyping:!0,typingText:"",messageId:e.messageId,message:e,time:new Date,traceId:t.traceId,raw:""}),new y({messages:r,pendingConsent:this.pendingConsent})}onMessageDelta(t){const e=t.fact.messageDelta.message,r=this.messages?.get(e.messageId);if(this.isTerminalBot(r))return this;const s=r?.type==="bot"?r:void 0,o=new Map(this.messages);return o.set(e.messageId,{type:"bot",eventType:d.MESSAGE_DELTA,isTyping:!0,typingText:`${s?.typingText??""}${e.text}`,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??s?.traceId,raw:s?.raw??""}),new y({messages:o,pendingConsent:this.pendingConsent})}onMessageComplete(t){const e=t.fact.messageComplete.message,r=new Map(this.messages),s=r.get(e.messageId);return r.set(e.messageId,{type:"bot",eventType:d.MESSAGE_COMPLETE,isTyping:!1,typingText:null,messageId:e.messageId,message:e,time:new Date,traceId:t.traceId??(s?.type==="bot"?s.traceId:void 0),raw:JSON.stringify(t)}),new y({messages:r,pendingConsent:this.pendingConsent})}onThinkingStart(t){const e=t.fact.messageThinkingStart.message;if(this.isTerminalThinking(this.messages?.get(e.messageId)))return this;const r=new Map(this.messages),s={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!0,time:new Date,traceId:t.traceId};return r.set(e.messageId,s),new y({messages:r,pendingConsent:this.pendingConsent})}onThinkingDelta(t){const e=t.fact.messageThinkingDelta.message,r=this.messages?.get(e.messageId);if(this.isTerminalThinking(r))return this;const s=r?.type==="thinking"?r:void 0,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:`${s?.text??""}${e.text}`,isThinking:!0,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return o.set(e.messageId,i),new y({messages:o,pendingConsent:this.pendingConsent})}onThinkingComplete(t){const e=t.fact.messageThinkingComplete.message,r=this.messages?.get(e.messageId),s=r?.type==="thinking"?r:void 0,o=new Map(this.messages),i={type:"thinking",messageId:e.messageId,text:e.text,isThinking:!1,time:s?.time??new Date,traceId:t.traceId??s?.traceId};return o.set(e.messageId,i),new y({messages:o,pendingConsent:this.pendingConsent})}onMessageUser(t){const e=t.fact.messageUser;if((this.messages?.get(e.messageId)??(e.customMessageId?this.messages?.get(e.customMessageId):void 0))?.type==="user")return this;const s=new Map(this.messages),o={type:"user",messageId:e.messageId,text:e.text,blobIds:e.blobIds,customMessageId:e.customMessageId,identityHint:e.identityHint,time:new Date,traceId:t.traceId};return s.set(e.messageId,o),new y({messages:s,pendingConsent:this.pendingConsent})}onMessageError(t){const e=Ge(),r=t.fact.runError.error,s=new Map(this.messages);return s.set(e,{type:"error",eventType:d.ERROR,messageId:e,error:r,time:new Date,traceId:t.traceId}),new y({messages:s,pendingConsent:this.pendingConsent})}onToolCallStart(t){const e=t.fact.toolCallStart,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,o={type:"tool-call",eventType:d.TOOL_CALL_START,messageId:s,processId:e.processId,callSeq:e.callSeq,toolName:e.toolCall.toolName,reason:e.toolCall.reason,toolsetName:e.toolCall.toolsetName,parameter:e.toolCall.parameter,toolUseId:e.toolUseId,parentToolUseId:e.parentToolUseId,isComplete:!1,time:new Date,traceId:t.traceId};return r.set(s,o),new y({messages:r,pendingConsent:this.pendingConsent})}onToolCallComplete(t){const e=t.fact.toolCallComplete,r=new Map(this.messages),s=`${e.processId}-${e.callSeq}`,o=r.get(s);if(o?.type==="tool-call"){const i={...o,eventType:d.TOOL_CALL_COMPLETE,result:e.toolCallResult,isError:e.isError,sidecar:e.toolUseResultSidecar,isComplete:!0,traceId:t.traceId??o.traceId};r.set(s,i)}return new y({messages:r,pendingConsent:this.pendingConsent})}onToolCallConsent(t){const e=t.fact.toolCallConsent;return new y({messages:this.messages,pendingConsent:e})}onSubagentStart(t){const e=t.fact.subagentStart,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:start`,o={type:"subagent",messageId:s,kind:"start",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description,time:new Date,traceId:t.traceId};return r.set(s,o),new y({messages:r,pendingConsent:this.pendingConsent})}onSubagentComplete(t){const e=t.fact.subagentComplete,r=new Map(this.messages),s=`subagent:${e.parentToolUseId}:complete`,o={type:"subagent",messageId:s,kind:"complete",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,status:e.status,summary:e.summary,time:new Date,traceId:t.traceId};return r.set(s,o),new y({messages:r,pendingConsent:this.pendingConsent})}}const En=new Set(["TaskCreate","TaskUpdate"]);function Ke(n){return n.toolsetName===""&&En.has(n.toolName)}function me(n){return typeof n=="object"&&n!==null?n:void 0}function I(n){return typeof n=="string"?n:void 0}function Fe(n){const t=[],e=new Map;for(const r of n){const s=r.parameter??{},o=r.sidecar??{};if(r.toolName==="TaskCreate"){const i=me(o.task),a=I(i?.id);if(!a)continue;e.has(a)||t.push(a),e.set(a,{id:a,subject:I(s.subject)||I(i?.subject)||"",activeForm:I(s.activeForm),description:I(s.description),status:e.get(a)?.status??"pending"})}else if(r.toolName==="TaskUpdate"){const i=me(o.statusChange),a=I(s.taskId)||I(o.taskId),u=I(i?.to)||I(s.status);if(!a||!u)continue;const c=e.get(a);c&&e.set(a,{...c,status:u})}}return t.map(r=>e.get(r))}function Be(n){return n.toolsetName===""&&n.toolName==="Agent"}function qe(n){return!!n}function Ve(n){const t=[],e=new Map,r=new Map,s=o=>(e.has(o)||(t.push(o),e.set(o,{status:"running"}),r.set(o,new Map)),e.get(o));for(const o of n)switch(o.kind){case"agentStart":{const i=s(o.toolUseId);o.description&&!i.description&&(i.description=o.description);break}case"subagentStart":{const i=s(o.parentToolUseId);i.agentId=o.agentId??i.agentId,i.subagentType=o.subagentType??i.subagentType,i.description=o.description??i.description;break}case"toolStart":{s(o.parentToolUseId),r.get(o.parentToolUseId).set(o.toolUseId,{toolsetName:o.toolsetName,toolName:o.toolName,parameter:o.parameter??{},reason:o.reason,status:"running"});break}case"toolComplete":{const i=r.get(o.parentToolUseId)?.get(o.toolUseId);i&&(i.status=o.isError?"error":"completed");break}case"subagentComplete":{const i=s(o.parentToolUseId);i.status=o.status,i.summary=o.summary;break}}return t.map(o=>({parentToolUseId:o,...e.get(o),tools:Array.from(r.get(o).values())}))}function In(n){return typeof n=="string"?n:void 0}function Ye(n){const t=[];for(const e of n){if(e.type==="tool-call"&&Be(e)){t.push({kind:"agentStart",toolUseId:e.toolUseId??e.messageId,description:In(e.parameter.description)});continue}if(e.type==="tool-call"&&qe(e.parentToolUseId)){const r=e.toolUseId??e.messageId;t.push({kind:"toolStart",parentToolUseId:e.parentToolUseId,toolUseId:r,toolsetName:e.toolsetName,toolName:e.toolName,parameter:e.parameter,reason:e.reason}),e.isComplete&&t.push({kind:"toolComplete",parentToolUseId:e.parentToolUseId,toolUseId:r,isError:e.isError});continue}if(e.type==="subagent"&&e.kind==="start"){t.push({kind:"subagentStart",parentToolUseId:e.parentToolUseId,agentId:e.agentId,subagentType:e.subagentType,description:e.description});continue}e.type==="subagent"&&e.kind==="complete"&&e.status&&t.push({kind:"subagentComplete",parentToolUseId:e.parentToolUseId,status:e.status,summary:e.summary})}return t}function We(n){const t=Array.from(n.messages?.values()??[]).filter(e=>e.type==="tool-call"&&e.isComplete&&Ke(e));return Fe(t)}function Xe(n){return Ve(Ye(Array.from(n.messages?.values()??[])))}function ze(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.id===s.id&&e.status===s.status&&e.subject===s.subject&&e.activeForm===s.activeForm&&e.description===s.description})}function wn(n,t){return n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.toolName===s.toolName&&e.toolsetName===s.toolsetName&&e.status===s.status&&e.reason===s.reason})}function Je(n,t){return n===t?!0:n.length!==t.length?!1:n.every((e,r)=>{const s=t[r];return e.parentToolUseId===s.parentToolUseId&&e.status===s.status&&e.subagentType===s.subagentType&&e.description===s.description&&e.summary===s.summary&&wn(e.tools,s.tools)})}function Qe(n){const t=new R([]),e=new R([]),r=new U;return r.add(n.pipe(P(We),ee(ze)).subscribe(t)),r.add(n.pipe(P(Xe),ee(Je)).subscribe(e)),{tasks$:t.asObservable(),subagents$:e.asObservable(),getTasks:()=>t.value,getSubagents:()=>e.value,teardown:()=>r.unsubscribe()}}class ${client;customChannelId;customMessageId;isConnecting$;conversation$;channelTitleSubject;derivedStores;statesObserver;statesSubscription;tasks$;subagents$;channelTitle$;currentUserMessageId;lastSentMessageId;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.isConnecting$=new R(!1),this.conversation$=new R(t.conversation),this.channelTitleSubject=new R(t.channelTitle??null),this.derivedStores=Qe(this.conversation$),this.tasks$=this.derivedStores.tasks$,this.subagents$=this.derivedStores.subagents$,this.channelTitle$=this.channelTitleSubject.pipe(ee()),this.statesObserver=t.statesObserver}getTasks(){return this.derivedStores.getTasks()}getSubagents(){return this.derivedStores.getSubagents()}getChannelTitle(){return this.channelTitleSubject.value}setChannelTitle(t){this.channelTitleSubject.next(t)}static create(t){const e=new $(t);return e.subscribe(),e}static async reset(t,e,r,s){const o=new $(t);try{return o.subscribe(),s?.(o),await o.resetChannel(e,r),o}catch(i){throw o.close(),i}}static async restore(t,e,r){const s=new $(t);try{return s.subscribe(),r?.(s),await s.rejoinChannel(e),s}catch(o){throw s.close(),o}}subscribe(){this.statesSubscription=Wt([this.isConnecting$,this.conversation$,this.derivedStores.tasks$,this.derivedStores.subagents$,this.channelTitle$]).pipe(P(([t,e,r,s,o])=>({isConnecting:t,conversation:e,tasks:r,subagents:s,channelTitle:o}))).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}buildRunHandlers(t,e,r){return{onSseStart:t?.onSseStart,onSseMessage:s=>{if(t?.onSseMessage?.(s),s.eventType===d.CHANNEL_TITLE_UPDATE&&this.channelTitleSubject.next(s.fact.channelTitleUpdate.title),this.currentUserMessageId&&s.traceId){const o=new Map(this.conversation$.value.messages),i=o.get(this.currentUserMessageId);i&&i.type==="user"&&(o.set(this.currentUserMessageId,{...i,traceId:s.traceId}),this.conversation$.next(new y({messages:o}))),this.currentUserMessageId=void 0}this.conversation$.next(this.conversation$.value.onMessage(s))},onSseError:s=>{t?.onSseError?.(s),this.isConnecting$.next(!1),this.currentUserMessageId=void 0,r(s)},onSseCompleted:()=>{t?.onSseCompleted?.(),this.isConnecting$.next(!1),this.currentUserMessageId=void 0,e()}}}fetchSse(t,e){return new Promise((r,s)=>{this.isConnecting$.next(!0),this.client.fetchSse(t,this.buildRunHandlers(e,r,s))})}rejoinChannel(t){return new Promise((e,r)=>{if(!this.client.rejoinSse){e();return}this.isConnecting$.next(!0),this.client.rejoinSse(this.customChannelId,this.buildRunHandlers(t,e,r))})}resetChannel(t,e){return this.fetchSse({action:N.RESET_CHANNEL,customChannelId:this.customChannelId,customMessageId:this.customMessageId,text:t?.text||"",payload:this.resolvePayload(t?.payload)},e)}sendMessage(t,e){const r=t.text.trim(),s=t.customMessageId??Ge();return this.currentUserMessageId=s,this.lastSentMessageId=s,this.conversation$.next(this.conversation$.value.pushMessage({type:"user",messageId:s,text:r,blobIds:t.blobIds,filePreviewUrls:t.filePreviewUrls,documentNames:t.documentNames,time:new Date})),this.fetchSse({action:N.NONE,customChannelId:this.customChannelId,customMessageId:s,payload:this.resolvePayload(t?.payload),text:r,blobIds:t?.blobIds},e)}replyToolCallConsents(t,e,r){return this.conversation$.next(this.conversation$.value.clearPendingConsent()),this.fetchSse({action:N.RESPONSE_TOOL_CALL_CONSENT,customChannelId:this.customChannelId,customMessageId:this.lastSentMessageId??this.customMessageId,payload:this.resolvePayload(r),text:"",toolCallConsents:t},e)}close(){this.isConnecting$.complete(),this.conversation$.complete(),this.channelTitleSubject.complete(),this.derivedStores.teardown(),this.statesSubscription?.unsubscribe()}}exports.AsgardServiceClient=gn;exports.Channel=$;exports.Conversation=y;exports.EventType=d;exports.FetchSseAction=N;exports.HttpError=q;exports.MessageTemplateType=ye;exports.ToolCallConsentResult=ve;exports.conversationToSubagentEvents=Ye;exports.createDerivedStores=Qe;exports.deriveSubagents=Xe;exports.deriveTasks=We;exports.isAgentTool=Be;exports.isHttpError=tt;exports.isSubagentChildTool=qe;exports.isTaskTool=Ke;exports.reduceSubagents=Ve;exports.reduceTaskEvents=Fe;exports.subagentsEqual=Je;exports.tasksEqual=ze;
5
5
  //# sourceMappingURL=index.cjs.map