@anam-ai/js-sdk 5.0.0-alpha.sam.5 → 5.0.0-alpha.sam.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main/modules/ToolCallManager.d.ts +4 -3
- package/dist/main/modules/ToolCallManager.d.ts.map +1 -1
- package/dist/main/modules/ToolCallManager.js +81 -86
- package/dist/main/modules/ToolCallManager.js.map +1 -1
- package/dist/module/modules/ToolCallManager.d.ts +4 -3
- package/dist/module/modules/ToolCallManager.d.ts.map +1 -1
- package/dist/module/modules/ToolCallManager.js +81 -86
- package/dist/module/modules/ToolCallManager.js.map +1 -1
- package/dist/umd/anam.js +1 -1
- package/package.json +1 -1
|
@@ -11,9 +11,10 @@ export declare class ToolCallManager {
|
|
|
11
11
|
private genericHandlers;
|
|
12
12
|
private pendingCalls;
|
|
13
13
|
registerHandler(eventName: string, handler: ToolCallHandler): () => void;
|
|
14
|
-
processToolCallStartedEvent(toolCallEvent: WebRtcToolCallStartedEvent): void
|
|
15
|
-
processToolCallCompletedEvent(toolCallEvent: WebRtcToolCallCompletedEvent): void
|
|
16
|
-
processToolCallFailedEvent(toolCallEvent: WebRtcToolCallFailedEvent): void
|
|
14
|
+
processToolCallStartedEvent(toolCallEvent: WebRtcToolCallStartedEvent): Promise<void>;
|
|
15
|
+
processToolCallCompletedEvent(toolCallEvent: WebRtcToolCallCompletedEvent): Promise<void>;
|
|
16
|
+
processToolCallFailedEvent(toolCallEvent: WebRtcToolCallFailedEvent): Promise<void>;
|
|
17
|
+
private collectErrors;
|
|
17
18
|
/**
|
|
18
19
|
* Converts a WebRtcClientToolEvent to a ClientToolEvent
|
|
19
20
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolCallManager.d.ts","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC3B,MAAM,wCAAwC,CAAC;AAEhD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,OAAO,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAClE;AAOD,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAuD;IACvE,OAAO,CAAC,eAAe,CAAuC;IAC9D,OAAO,CAAC,YAAY,CAAuC;IAE3D,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,MAAM,IAAI;
|
|
1
|
+
{"version":3,"file":"ToolCallManager.d.ts","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC3B,MAAM,wCAAwC,CAAC;AAEhD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,OAAO,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAClE;AAOD,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAuD;IACvE,OAAO,CAAC,eAAe,CAAuC;IAC9D,OAAO,CAAC,YAAY,CAAuC;IAE3D,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,MAAM,IAAI;IAoBlE,2BAA2B,CAAC,aAAa,EAAE,0BAA0B;IAuDrE,6BAA6B,CACjC,aAAa,EAAE,4BAA4B;IAgDvC,0BAA0B,CAAC,aAAa,EAAE,yBAAyB;IAmCzE,OAAO,CAAC,aAAa;IAerB;;OAEG;IACH,MAAM,CAAC,sCAAsC,CAC3C,WAAW,EAAE,qBAAqB,GACjC,eAAe;IAYlB,MAAM,CAAC,6CAA6C,CAClD,WAAW,EAAE,4BAA4B,GACxC,eAAe;CAWnB"}
|
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
2
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
12
|
exports.ToolCallManager = void 0;
|
|
4
13
|
class ToolCallManager {
|
|
@@ -21,43 +30,42 @@ class ToolCallManager {
|
|
|
21
30
|
};
|
|
22
31
|
}
|
|
23
32
|
processToolCallStartedEvent(toolCallEvent) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
33
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
34
|
+
const { tool_name, timestamp } = toolCallEvent;
|
|
35
|
+
const handlersForTool = this.handlers[tool_name] || {};
|
|
36
|
+
const handlers = Object.values(handlersForTool);
|
|
37
|
+
const genericHandlers = Object.values(this.genericHandlers);
|
|
38
|
+
const payload = {
|
|
39
|
+
eventUid: toolCallEvent.event_uid,
|
|
40
|
+
toolCallId: toolCallEvent.tool_call_id,
|
|
41
|
+
toolName: toolCallEvent.tool_name,
|
|
42
|
+
toolType: toolCallEvent.tool_type,
|
|
43
|
+
toolSubtype: toolCallEvent.tool_subtype,
|
|
44
|
+
arguments: toolCallEvent.arguments,
|
|
45
|
+
timestamp: toolCallEvent.timestamp,
|
|
46
|
+
};
|
|
47
|
+
const parsedTimestamp = new Date(timestamp);
|
|
48
|
+
// Store in pending calls before invoking handlers
|
|
49
|
+
this.pendingCalls[toolCallEvent.tool_call_id] = {
|
|
50
|
+
payload: payload,
|
|
51
|
+
timestamp: parsedTimestamp.getTime(),
|
|
52
|
+
};
|
|
53
|
+
const errors = [];
|
|
54
|
+
const genericResults = yield Promise.allSettled(genericHandlers.map((handler) => handler.onStart(payload)));
|
|
55
|
+
this.collectErrors(genericResults, errors);
|
|
56
|
+
const handlerResults = yield Promise.allSettled(handlers.map((handler) => handler.onStart(payload)));
|
|
57
|
+
this.collectErrors(handlerResults, errors);
|
|
58
|
+
if (toolCallEvent.tool_type === 'client') {
|
|
59
|
+
yield this.processToolCallCompletedEvent(Object.assign(Object.assign({}, toolCallEvent), { result: null, timestamp: new Date().toISOString() }));
|
|
46
60
|
}
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error in onStart handler: ${
|
|
61
|
+
if (errors.length > 0) {
|
|
62
|
+
const combinedMessage = errors.map((e) => e.message).join('; ');
|
|
63
|
+
yield this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error in onStart handler: ${combinedMessage}`, timestamp: new Date().toISOString() }));
|
|
50
64
|
}
|
|
51
65
|
});
|
|
52
|
-
const parsedTimestamp = new Date(timestamp);
|
|
53
|
-
// Store in pending calls
|
|
54
|
-
this.pendingCalls[toolCallEvent.tool_call_id] = {
|
|
55
|
-
payload: payload,
|
|
56
|
-
timestamp: parsedTimestamp.getTime(),
|
|
57
|
-
};
|
|
58
66
|
}
|
|
59
67
|
processToolCallCompletedEvent(toolCallEvent) {
|
|
60
|
-
|
|
68
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
61
69
|
const { tool_name, tool_call_id, timestamp } = toolCallEvent;
|
|
62
70
|
const handlersForTool = this.handlers[tool_name] || {};
|
|
63
71
|
const handlers = Object.values(handlersForTool);
|
|
@@ -65,65 +73,41 @@ class ToolCallManager {
|
|
|
65
73
|
const parsedTimestamp = new Date(timestamp);
|
|
66
74
|
const pendingCall = this.pendingCalls[tool_call_id];
|
|
67
75
|
const executionTime = parsedTimestamp.getTime() - pendingCall.timestamp;
|
|
68
|
-
|
|
69
|
-
// this allows users to have a single handler for all tools that can, for example, log all tool calls and their execution times
|
|
70
|
-
genericHandlers.forEach((handler) => {
|
|
71
|
-
handler.onComplete({
|
|
72
|
-
eventUid: toolCallEvent.event_uid,
|
|
73
|
-
toolCallId: toolCallEvent.tool_call_id,
|
|
74
|
-
toolName: toolCallEvent.tool_name,
|
|
75
|
-
toolType: toolCallEvent.tool_type,
|
|
76
|
-
toolSubtype: toolCallEvent.tool_subtype,
|
|
77
|
-
result: toolCallEvent.result,
|
|
78
|
-
executionTime: executionTime,
|
|
79
|
-
timestamp: toolCallEvent.timestamp,
|
|
80
|
-
});
|
|
81
|
-
});
|
|
82
|
-
handlers.forEach((handler) => {
|
|
83
|
-
handler.onComplete({
|
|
84
|
-
eventUid: toolCallEvent.event_uid,
|
|
85
|
-
toolCallId: toolCallEvent.tool_call_id,
|
|
86
|
-
toolName: toolCallEvent.tool_name,
|
|
87
|
-
toolType: toolCallEvent.tool_type,
|
|
88
|
-
toolSubtype: toolCallEvent.tool_subtype,
|
|
89
|
-
result: toolCallEvent.result,
|
|
90
|
-
executionTime: executionTime,
|
|
91
|
-
timestamp: toolCallEvent.timestamp,
|
|
92
|
-
});
|
|
93
|
-
});
|
|
94
|
-
// Clean up pending call
|
|
95
|
-
delete this.pendingCalls[tool_call_id];
|
|
96
|
-
}
|
|
97
|
-
catch (error) {
|
|
98
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
99
|
-
this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error processing tool call completed event: ${errorMessage}`, timestamp: new Date().toISOString() }));
|
|
100
|
-
throw error;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
processToolCallFailedEvent(toolCallEvent) {
|
|
104
|
-
const { tool_name, tool_call_id, timestamp } = toolCallEvent;
|
|
105
|
-
const handlersForTool = this.handlers[tool_name] || {};
|
|
106
|
-
const handlers = Object.values(handlersForTool);
|
|
107
|
-
const genericHandlers = Object.values(this.genericHandlers);
|
|
108
|
-
const parsedTimestamp = new Date(timestamp);
|
|
109
|
-
const pendingCall = this.pendingCalls[tool_call_id];
|
|
110
|
-
const executionTime = parsedTimestamp.getTime() - pendingCall.timestamp;
|
|
111
|
-
// always call generic handlers first
|
|
112
|
-
// this allows users to have a single handler for all tools that can, for example, log all tool calls and their execution times
|
|
113
|
-
genericHandlers.forEach((handler) => {
|
|
114
|
-
handler.onFail({
|
|
76
|
+
const payload = {
|
|
115
77
|
eventUid: toolCallEvent.event_uid,
|
|
116
78
|
toolCallId: toolCallEvent.tool_call_id,
|
|
117
79
|
toolName: toolCallEvent.tool_name,
|
|
118
80
|
toolType: toolCallEvent.tool_type,
|
|
119
81
|
toolSubtype: toolCallEvent.tool_subtype,
|
|
120
|
-
|
|
82
|
+
result: toolCallEvent.result,
|
|
121
83
|
executionTime: executionTime,
|
|
122
84
|
timestamp: toolCallEvent.timestamp,
|
|
123
|
-
}
|
|
85
|
+
};
|
|
86
|
+
const errors = [];
|
|
87
|
+
const genericResults = yield Promise.allSettled(genericHandlers.map((handler) => handler.onComplete(payload)));
|
|
88
|
+
this.collectErrors(genericResults, errors);
|
|
89
|
+
const handlerResults = yield Promise.allSettled(handlers.map((handler) => handler.onComplete(payload)));
|
|
90
|
+
this.collectErrors(handlerResults, errors);
|
|
91
|
+
// Clean up pending call
|
|
92
|
+
delete this.pendingCalls[tool_call_id];
|
|
93
|
+
if (errors.length > 0) {
|
|
94
|
+
const combinedMessage = errors.map((e) => e.message).join('; ');
|
|
95
|
+
yield this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error in onComplete handler: ${combinedMessage}`, timestamp: new Date().toISOString() }));
|
|
96
|
+
}
|
|
124
97
|
});
|
|
125
|
-
|
|
126
|
-
|
|
98
|
+
}
|
|
99
|
+
processToolCallFailedEvent(toolCallEvent) {
|
|
100
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
101
|
+
const { tool_name, tool_call_id, timestamp } = toolCallEvent;
|
|
102
|
+
const handlersForTool = this.handlers[tool_name] || {};
|
|
103
|
+
const handlers = Object.values(handlersForTool);
|
|
104
|
+
const genericHandlers = Object.values(this.genericHandlers);
|
|
105
|
+
const parsedTimestamp = new Date(timestamp);
|
|
106
|
+
const pendingCall = this.pendingCalls[tool_call_id];
|
|
107
|
+
const executionTime = pendingCall
|
|
108
|
+
? parsedTimestamp.getTime() - pendingCall.timestamp
|
|
109
|
+
: 0;
|
|
110
|
+
const payload = {
|
|
127
111
|
eventUid: toolCallEvent.event_uid,
|
|
128
112
|
toolCallId: toolCallEvent.tool_call_id,
|
|
129
113
|
toolName: toolCallEvent.tool_name,
|
|
@@ -132,10 +116,21 @@ class ToolCallManager {
|
|
|
132
116
|
error: new Error(toolCallEvent.error_message),
|
|
133
117
|
executionTime: executionTime,
|
|
134
118
|
timestamp: toolCallEvent.timestamp,
|
|
135
|
-
}
|
|
119
|
+
};
|
|
120
|
+
yield Promise.allSettled(genericHandlers.map((handler) => handler.onFail(payload)));
|
|
121
|
+
yield Promise.allSettled(handlers.map((handler) => handler.onFail(payload)));
|
|
122
|
+
// Clean up pending call
|
|
123
|
+
delete this.pendingCalls[tool_call_id];
|
|
136
124
|
});
|
|
137
|
-
|
|
138
|
-
|
|
125
|
+
}
|
|
126
|
+
collectErrors(results, errors) {
|
|
127
|
+
for (const result of results) {
|
|
128
|
+
if (result.status === 'rejected') {
|
|
129
|
+
errors.push(result.reason instanceof Error
|
|
130
|
+
? result.reason
|
|
131
|
+
: new Error(String(result.reason)));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
139
134
|
}
|
|
140
135
|
/**
|
|
141
136
|
* Converts a WebRtcClientToolEvent to a ClientToolEvent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolCallManager.js","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ToolCallManager.js","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"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"}
|
|
@@ -11,9 +11,10 @@ export declare class ToolCallManager {
|
|
|
11
11
|
private genericHandlers;
|
|
12
12
|
private pendingCalls;
|
|
13
13
|
registerHandler(eventName: string, handler: ToolCallHandler): () => void;
|
|
14
|
-
processToolCallStartedEvent(toolCallEvent: WebRtcToolCallStartedEvent): void
|
|
15
|
-
processToolCallCompletedEvent(toolCallEvent: WebRtcToolCallCompletedEvent): void
|
|
16
|
-
processToolCallFailedEvent(toolCallEvent: WebRtcToolCallFailedEvent): void
|
|
14
|
+
processToolCallStartedEvent(toolCallEvent: WebRtcToolCallStartedEvent): Promise<void>;
|
|
15
|
+
processToolCallCompletedEvent(toolCallEvent: WebRtcToolCallCompletedEvent): Promise<void>;
|
|
16
|
+
processToolCallFailedEvent(toolCallEvent: WebRtcToolCallFailedEvent): Promise<void>;
|
|
17
|
+
private collectErrors;
|
|
17
18
|
/**
|
|
18
19
|
* Converts a WebRtcClientToolEvent to a ClientToolEvent
|
|
19
20
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolCallManager.d.ts","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC3B,MAAM,wCAAwC,CAAC;AAEhD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,OAAO,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAClE;AAOD,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAuD;IACvE,OAAO,CAAC,eAAe,CAAuC;IAC9D,OAAO,CAAC,YAAY,CAAuC;IAE3D,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,MAAM,IAAI;
|
|
1
|
+
{"version":3,"file":"ToolCallManager.d.ts","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC3B,MAAM,wCAAwC,CAAC;AAEhD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,OAAO,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAClE;AAOD,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAuD;IACvE,OAAO,CAAC,eAAe,CAAuC;IAC9D,OAAO,CAAC,YAAY,CAAuC;IAE3D,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,MAAM,IAAI;IAoBlE,2BAA2B,CAAC,aAAa,EAAE,0BAA0B;IAuDrE,6BAA6B,CACjC,aAAa,EAAE,4BAA4B;IAgDvC,0BAA0B,CAAC,aAAa,EAAE,yBAAyB;IAmCzE,OAAO,CAAC,aAAa;IAerB;;OAEG;IACH,MAAM,CAAC,sCAAsC,CAC3C,WAAW,EAAE,qBAAqB,GACjC,eAAe;IAYlB,MAAM,CAAC,6CAA6C,CAClD,WAAW,EAAE,4BAA4B,GACxC,eAAe;CAWnB"}
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
1
10
|
export class ToolCallManager {
|
|
2
11
|
constructor() {
|
|
3
12
|
this.handlers = {};
|
|
@@ -18,43 +27,42 @@ export class ToolCallManager {
|
|
|
18
27
|
};
|
|
19
28
|
}
|
|
20
29
|
processToolCallStartedEvent(toolCallEvent) {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
30
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
31
|
+
const { tool_name, timestamp } = toolCallEvent;
|
|
32
|
+
const handlersForTool = this.handlers[tool_name] || {};
|
|
33
|
+
const handlers = Object.values(handlersForTool);
|
|
34
|
+
const genericHandlers = Object.values(this.genericHandlers);
|
|
35
|
+
const payload = {
|
|
36
|
+
eventUid: toolCallEvent.event_uid,
|
|
37
|
+
toolCallId: toolCallEvent.tool_call_id,
|
|
38
|
+
toolName: toolCallEvent.tool_name,
|
|
39
|
+
toolType: toolCallEvent.tool_type,
|
|
40
|
+
toolSubtype: toolCallEvent.tool_subtype,
|
|
41
|
+
arguments: toolCallEvent.arguments,
|
|
42
|
+
timestamp: toolCallEvent.timestamp,
|
|
43
|
+
};
|
|
44
|
+
const parsedTimestamp = new Date(timestamp);
|
|
45
|
+
// Store in pending calls before invoking handlers
|
|
46
|
+
this.pendingCalls[toolCallEvent.tool_call_id] = {
|
|
47
|
+
payload: payload,
|
|
48
|
+
timestamp: parsedTimestamp.getTime(),
|
|
49
|
+
};
|
|
50
|
+
const errors = [];
|
|
51
|
+
const genericResults = yield Promise.allSettled(genericHandlers.map((handler) => handler.onStart(payload)));
|
|
52
|
+
this.collectErrors(genericResults, errors);
|
|
53
|
+
const handlerResults = yield Promise.allSettled(handlers.map((handler) => handler.onStart(payload)));
|
|
54
|
+
this.collectErrors(handlerResults, errors);
|
|
55
|
+
if (toolCallEvent.tool_type === 'client') {
|
|
56
|
+
yield this.processToolCallCompletedEvent(Object.assign(Object.assign({}, toolCallEvent), { result: null, timestamp: new Date().toISOString() }));
|
|
43
57
|
}
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error in onStart handler: ${
|
|
58
|
+
if (errors.length > 0) {
|
|
59
|
+
const combinedMessage = errors.map((e) => e.message).join('; ');
|
|
60
|
+
yield this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error in onStart handler: ${combinedMessage}`, timestamp: new Date().toISOString() }));
|
|
47
61
|
}
|
|
48
62
|
});
|
|
49
|
-
const parsedTimestamp = new Date(timestamp);
|
|
50
|
-
// Store in pending calls
|
|
51
|
-
this.pendingCalls[toolCallEvent.tool_call_id] = {
|
|
52
|
-
payload: payload,
|
|
53
|
-
timestamp: parsedTimestamp.getTime(),
|
|
54
|
-
};
|
|
55
63
|
}
|
|
56
64
|
processToolCallCompletedEvent(toolCallEvent) {
|
|
57
|
-
|
|
65
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
58
66
|
const { tool_name, tool_call_id, timestamp } = toolCallEvent;
|
|
59
67
|
const handlersForTool = this.handlers[tool_name] || {};
|
|
60
68
|
const handlers = Object.values(handlersForTool);
|
|
@@ -62,65 +70,41 @@ export class ToolCallManager {
|
|
|
62
70
|
const parsedTimestamp = new Date(timestamp);
|
|
63
71
|
const pendingCall = this.pendingCalls[tool_call_id];
|
|
64
72
|
const executionTime = parsedTimestamp.getTime() - pendingCall.timestamp;
|
|
65
|
-
|
|
66
|
-
// this allows users to have a single handler for all tools that can, for example, log all tool calls and their execution times
|
|
67
|
-
genericHandlers.forEach((handler) => {
|
|
68
|
-
handler.onComplete({
|
|
69
|
-
eventUid: toolCallEvent.event_uid,
|
|
70
|
-
toolCallId: toolCallEvent.tool_call_id,
|
|
71
|
-
toolName: toolCallEvent.tool_name,
|
|
72
|
-
toolType: toolCallEvent.tool_type,
|
|
73
|
-
toolSubtype: toolCallEvent.tool_subtype,
|
|
74
|
-
result: toolCallEvent.result,
|
|
75
|
-
executionTime: executionTime,
|
|
76
|
-
timestamp: toolCallEvent.timestamp,
|
|
77
|
-
});
|
|
78
|
-
});
|
|
79
|
-
handlers.forEach((handler) => {
|
|
80
|
-
handler.onComplete({
|
|
81
|
-
eventUid: toolCallEvent.event_uid,
|
|
82
|
-
toolCallId: toolCallEvent.tool_call_id,
|
|
83
|
-
toolName: toolCallEvent.tool_name,
|
|
84
|
-
toolType: toolCallEvent.tool_type,
|
|
85
|
-
toolSubtype: toolCallEvent.tool_subtype,
|
|
86
|
-
result: toolCallEvent.result,
|
|
87
|
-
executionTime: executionTime,
|
|
88
|
-
timestamp: toolCallEvent.timestamp,
|
|
89
|
-
});
|
|
90
|
-
});
|
|
91
|
-
// Clean up pending call
|
|
92
|
-
delete this.pendingCalls[tool_call_id];
|
|
93
|
-
}
|
|
94
|
-
catch (error) {
|
|
95
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
96
|
-
this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error processing tool call completed event: ${errorMessage}`, timestamp: new Date().toISOString() }));
|
|
97
|
-
throw error;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
processToolCallFailedEvent(toolCallEvent) {
|
|
101
|
-
const { tool_name, tool_call_id, timestamp } = toolCallEvent;
|
|
102
|
-
const handlersForTool = this.handlers[tool_name] || {};
|
|
103
|
-
const handlers = Object.values(handlersForTool);
|
|
104
|
-
const genericHandlers = Object.values(this.genericHandlers);
|
|
105
|
-
const parsedTimestamp = new Date(timestamp);
|
|
106
|
-
const pendingCall = this.pendingCalls[tool_call_id];
|
|
107
|
-
const executionTime = parsedTimestamp.getTime() - pendingCall.timestamp;
|
|
108
|
-
// always call generic handlers first
|
|
109
|
-
// this allows users to have a single handler for all tools that can, for example, log all tool calls and their execution times
|
|
110
|
-
genericHandlers.forEach((handler) => {
|
|
111
|
-
handler.onFail({
|
|
73
|
+
const payload = {
|
|
112
74
|
eventUid: toolCallEvent.event_uid,
|
|
113
75
|
toolCallId: toolCallEvent.tool_call_id,
|
|
114
76
|
toolName: toolCallEvent.tool_name,
|
|
115
77
|
toolType: toolCallEvent.tool_type,
|
|
116
78
|
toolSubtype: toolCallEvent.tool_subtype,
|
|
117
|
-
|
|
79
|
+
result: toolCallEvent.result,
|
|
118
80
|
executionTime: executionTime,
|
|
119
81
|
timestamp: toolCallEvent.timestamp,
|
|
120
|
-
}
|
|
82
|
+
};
|
|
83
|
+
const errors = [];
|
|
84
|
+
const genericResults = yield Promise.allSettled(genericHandlers.map((handler) => handler.onComplete(payload)));
|
|
85
|
+
this.collectErrors(genericResults, errors);
|
|
86
|
+
const handlerResults = yield Promise.allSettled(handlers.map((handler) => handler.onComplete(payload)));
|
|
87
|
+
this.collectErrors(handlerResults, errors);
|
|
88
|
+
// Clean up pending call
|
|
89
|
+
delete this.pendingCalls[tool_call_id];
|
|
90
|
+
if (errors.length > 0) {
|
|
91
|
+
const combinedMessage = errors.map((e) => e.message).join('; ');
|
|
92
|
+
yield this.processToolCallFailedEvent(Object.assign(Object.assign({}, toolCallEvent), { error_message: `Error in onComplete handler: ${combinedMessage}`, timestamp: new Date().toISOString() }));
|
|
93
|
+
}
|
|
121
94
|
});
|
|
122
|
-
|
|
123
|
-
|
|
95
|
+
}
|
|
96
|
+
processToolCallFailedEvent(toolCallEvent) {
|
|
97
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
98
|
+
const { tool_name, tool_call_id, timestamp } = toolCallEvent;
|
|
99
|
+
const handlersForTool = this.handlers[tool_name] || {};
|
|
100
|
+
const handlers = Object.values(handlersForTool);
|
|
101
|
+
const genericHandlers = Object.values(this.genericHandlers);
|
|
102
|
+
const parsedTimestamp = new Date(timestamp);
|
|
103
|
+
const pendingCall = this.pendingCalls[tool_call_id];
|
|
104
|
+
const executionTime = pendingCall
|
|
105
|
+
? parsedTimestamp.getTime() - pendingCall.timestamp
|
|
106
|
+
: 0;
|
|
107
|
+
const payload = {
|
|
124
108
|
eventUid: toolCallEvent.event_uid,
|
|
125
109
|
toolCallId: toolCallEvent.tool_call_id,
|
|
126
110
|
toolName: toolCallEvent.tool_name,
|
|
@@ -129,10 +113,21 @@ export class ToolCallManager {
|
|
|
129
113
|
error: new Error(toolCallEvent.error_message),
|
|
130
114
|
executionTime: executionTime,
|
|
131
115
|
timestamp: toolCallEvent.timestamp,
|
|
132
|
-
}
|
|
116
|
+
};
|
|
117
|
+
yield Promise.allSettled(genericHandlers.map((handler) => handler.onFail(payload)));
|
|
118
|
+
yield Promise.allSettled(handlers.map((handler) => handler.onFail(payload)));
|
|
119
|
+
// Clean up pending call
|
|
120
|
+
delete this.pendingCalls[tool_call_id];
|
|
133
121
|
});
|
|
134
|
-
|
|
135
|
-
|
|
122
|
+
}
|
|
123
|
+
collectErrors(results, errors) {
|
|
124
|
+
for (const result of results) {
|
|
125
|
+
if (result.status === 'rejected') {
|
|
126
|
+
errors.push(result.reason instanceof Error
|
|
127
|
+
? result.reason
|
|
128
|
+
: new Error(String(result.reason)));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
136
131
|
}
|
|
137
132
|
/**
|
|
138
133
|
* Converts a WebRtcClientToolEvent to a ClientToolEvent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolCallManager.js","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"AAuBA,MAAM,OAAO,eAAe;IAA5B;QACU,aAAQ,GAAoD,EAAE,CAAC;QAC/D,oBAAe,GAAoC,EAAE,CAAC;QACtD,iBAAY,GAAoC,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"ToolCallManager.js","sourceRoot":"","sources":["../../../src/modules/ToolCallManager.ts"],"names":[],"mappings":"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"}
|
package/dist/umd/anam.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see anam.js.LICENSE.txt */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.anam=t():e.anam=t()}(self,()=>{return e={18:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreApiRestClient=void 0;const r=n(71),o=n(985),s=n(672);t.CoreApiRestClient=class{constructor(e,t,n){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(null==n?void 0:n.baseUrl)||o.DEFAULT_API_BASE_URL,this.apiVersion=(null==n?void 0:n.apiVersion)||o.DEFAULT_API_VERSION,this.apiGatewayConfig=(null==n?void 0:n.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var n,i;if((null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.enabled)&&(null===(i=this.apiGatewayConfig)||void 0===i?void 0:i.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,i=new URL(`${this.baseUrl}${e}`);return{url:n,headers:Object.assign(Object.assign({},t),{"X-Anam-Target-Url":i.href})}}return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return i(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new r.ClientError("Persona configuration must be provided when using apiKey",r.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const n=`${this.apiVersion}/engine/session`,{url:i,headers:s}=this.buildGatewayUrlAndHeaders(n,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),a=yield fetch(i,{method:"POST",headers:s,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:o.CLIENT_METADATA})}),l=yield a.json(),c=l.error;switch(a.status){case 200:case 201:return l;case 400:throw new r.ClientError("Invalid request to start session",r.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new r.ClientError("Authentication failed when starting session",r.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new r.ClientError("Please sign up for a plan to start a session",r.ErrorCode.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new r.ClientError("Authentication failed when starting session",r.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:throw"Concurrent session limit reached"===c?new r.ClientError("Concurrency limit reached, please upgrade your plan",r.ErrorCode.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message}):"Spend cap reached"===c?new r.ClientError("Spend cap reached, please upgrade your plan",r.ErrorCode.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message}):new r.ClientError("Usage limit reached, please upgrade your plan",r.ErrorCode.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new r.ClientError("There are no available personas, please try again later",r.ErrorCode.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new r.ClientError("Unknown error when starting session",r.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:l.message})}}catch(e){if(e instanceof r.ClientError)throw e;throw new r.ClientError("Failed to start session",r.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e)})}})}unsafe_getSessionToken(e){return i(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};(0,s.isCustomPersonaConfig)(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const e=`${this.apiVersion}/auth/session-token`,{url:n,headers:i}=this.buildGatewayUrlAndHeaders(e,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}),r=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(t)});return(yield r.json()).sessionToken}catch(e){throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}},21:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AnamEvent=void 0,function(e){e.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",e.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",e.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",e.CONNECTION_CLOSED="CONNECTION_CLOSED",e.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",e.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",e.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",e.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",e.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",e.SESSION_READY="SESSION_READY",e.SERVER_WARNING="SERVER_WARNING",e.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",e.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",e.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",e.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",e.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",e.TOOL_CALL_EVENT_RECEIVED="TOOL_CALL_EVENT_RECEIVED",e.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",e.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED"}(n||(t.AnamEvent=n={}))},35:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolCallManager=void 0,t.ToolCallManager=class{constructor(){this.handlers={},this.genericHandlers={},this.pendingCalls={}}registerHandler(e,t){const n=Math.random().toString(36).substring(2,15);return"*"===e?(this.genericHandlers[n]=t,()=>{delete this.genericHandlers[n]}):(this.handlers[e]=Object.assign(Object.assign({},this.handlers[e]),{[n]:t}),()=>{delete this.handlers[e][n]})}processToolCallStartedEvent(e){const{tool_call_id:t,tool_name:n,timestamp:i}=e,r=this.handlers[n]||{},o=Object.values(r),s=Object.values(this.genericHandlers),a={eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp};s.forEach(e=>{e.onStart(a)}),o.forEach(t=>{try{t.onStart(a),"client"===a.toolType&&this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{timestamp:(new Date).toISOString(),result:{}}))}catch(t){const n=t instanceof Error?t.message:String(t);this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${n}`,timestamp:(new Date).toISOString()}))}});const l=new Date(i);this.pendingCalls[e.tool_call_id]={payload:a,timestamp:l.getTime()}}processToolCallCompletedEvent(e){try{const{tool_name:t,tool_call_id:n,timestamp:i}=e,r=this.handlers[t]||{},o=Object.values(r),s=Object.values(this.genericHandlers),a=new Date(i),l=this.pendingCalls[n],c=a.getTime()-l.timestamp;s.forEach(t=>{t.onComplete({eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:c,timestamp:e.timestamp})}),o.forEach(t=>{t.onComplete({eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:c,timestamp:e.timestamp})}),delete this.pendingCalls[n]}catch(t){const n=t instanceof Error?t.message:String(t);throw this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error processing tool call completed event: ${n}`,timestamp:(new Date).toISOString()})),t}}processToolCallFailedEvent(e){const{tool_name:t,tool_call_id:n,timestamp:i}=e,r=this.handlers[t]||{},o=Object.values(r),s=Object.values(this.genericHandlers),a=new Date(i),l=this.pendingCalls[n],c=a.getTime()-l.timestamp;s.forEach(t=>{t.onFail({eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,error:new Error(e.error_message),executionTime:c,timestamp:e.timestamp})}),o.forEach(t=>{t.onFail({eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,error:new Error(e.error_message),executionTime:c,timestamp:e.timestamp})}),delete this.pendingCalls[e.tool_call_id]}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallCompletedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}},60:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=void 0,function(e){e.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",e.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",e.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",e.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",e.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"}(n||(t.ConnectionClosedCode=n={}))},71:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientError=t.ErrorCode=void 0;const i=n(948);var r;!function(e){e.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",e.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",e.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",e.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",e.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",e.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",e.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",e.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",e.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"}(r||(t.ErrorCode=r={}));class o extends Error{constructor(e,t,n=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=n,this.details=r,Object.setPrototypeOf(this,o.prototype),(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:n})}}t.ClientError=o},170:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=t.MessageRole=t.AudioPermissionState=t.DataChannelMessage=t.SignalMessageAction=void 0;var i=n(295);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}});var r=n(513);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return r.DataChannelMessage}});var o=n(793);Object.defineProperty(t,"AudioPermissionState",{enumerable:!0,get:function(){return o.AudioPermissionState}});var s=n(822);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return s.MessageRole}});var a=n(878);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return a.AnamEvent}});var l=n(878);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return l.InternalEvent}});var c=n(878);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return c.ConnectionClosedCode}});var u=n(421);Object.defineProperty(t,"AgentAudioInputStream",{enumerable:!0,get:function(){return u.AgentAudioInputStream}})},251:(e,t)=>{t.read=function(e,t,n,i,r){var o,s,a=8*r-i-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?r-1:0,h=n?-1:1,E=e[t+d];for(d+=h,o=E&(1<<-u)-1,E>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=i;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-c;else{if(o===l)return s?NaN:1/0*(E?-1:1);s+=Math.pow(2,i),o-=c}return(E?-1:1)*s*Math.pow(2,o-i)},t.write=function(e,t,n,i,r,o){var s,a,l,c=8*o-r-1,u=(1<<c)-1,d=u>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,E=i?0:o-1,p=i?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*l-1)*Math.pow(2,r),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,r),s=0));r>=8;e[n+E]=255&a,E+=p,a/=256,r-=8);for(s=s<<r|a,c+=r;c>0;e[n+E]=255&s,E+=p,s/=256,c-=8);e[n+E-p]|=128*f}},259:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEventEmitter=void 0,t.InternalEventEmitter=class{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}},272:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateApiGatewayConfig=void 0,t.validateApiGatewayConfig=function(e){if(e&&e.enabled){if(!e.baseUrl)return"API Gateway baseUrl is required when enabled";try{const t=new URL(e.baseUrl);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return`Invalid API Gateway baseUrl protocol: ${t.protocol}. Must be http:, https:, ws:, or wss:`}catch(t){return`Invalid API Gateway baseUrl: ${e.baseUrl}`}return e.wsPath&&!e.wsPath.startsWith("/")?"API Gateway wsPath must start with /":void 0}}},273:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0,function(e){e.USER="user",e.PERSONA="persona"}(n||(t.MessageRole=n={}))},279:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SignallingClient=void 0;const r=n(170);t.SignallingClient=class{constructor(e,t,n,i,r){var o,s,a,l,c;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=n,this.internalEventEmitter=i,this.apiGatewayConfig=r,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:d,url:h}=t;if(this.heartbeatIntervalSeconds=u||5,this.maxWsReconnectionAttempts=d||5,!h.baseUrl)throw new Error("Signalling Client: baseUrl is required");if((null===(o=this.apiGatewayConfig)||void 0===o?void 0:o.enabled)&&(null===(s=this.apiGatewayConfig)||void 0===s?void 0:s.baseUrl)){const t=new URL(this.apiGatewayConfig.baseUrl),n=null!==(a=this.apiGatewayConfig.wsPath)&&void 0!==a?a:"/ws";t.protocol=t.protocol.replace("http","ws"),t.pathname=n,this.url=t;const i=h.protocol||"https",r="http"===i?"ws":"wss",o=`${i}://${h.baseUrl}`,s=null!==(l=h.signallingPath)&&void 0!==l?l:"/ws",c=new URL(o);c.protocol="ws"===r?"ws:":"wss:",h.port&&(c.port=h.port),c.pathname=s,c.searchParams.append("session_id",e),this.url.searchParams.append("target_url",c.href)}else{const t=`${h.protocol||"https"}://${h.baseUrl}`;this.url=new URL(t),this.url.protocol="http"===h.protocol?"ws:":"wss:",h.port&&(this.url.port=h.port),this.url.pathname=null!==(c=h.signallingPath)&&void 0!==c?c:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return i(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},n={actionType:r.SignalMessageAction.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(n)})}sendIceCandidate(e){return i(this,void 0,void 0,function*(){const t={actionType:r.SignalMessageAction.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if((null===(t=this.socket)||void 0===t?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(e){console.error("SignallingClient - sendSignalMessage: error sending message",e)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return i(this,void 0,void 0,function*(){const t={actionType:r.SignalMessageAction.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:r.SignalMessageAction.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:r.SignalMessageAction.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return i(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(r.InternalEvent.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return i(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,this.stopSignal||(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var n;(null===(n=this.socket)||void 0===n?void 0:n.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return i(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=1e3*this.heartbeatIntervalSeconds,t={actionType:r.SignalMessageAction.HEARTBEAT,sessionId:this.sessionId,payload:""},n=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var e;this.stopSignal||(null===(e=this.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN&&this.socket.send(n)},e)}}},287:(e,t,n)=>{"use strict";const i=n(526),r=n(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=function(e){return+e!=e&&(e=0),l.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let i=a(n);const r=i.write(e,t);return r!==n&&(i=i.slice(0,r)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(q(e,Uint8Array)){const t=new Uint8Array(e);return E(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(q(e,ArrayBuffer)||e&&q(e.buffer,ArrayBuffer))return E(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(q(e,SharedArrayBuffer)||e&&q(e.buffer,SharedArrayBuffer)))return E(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,n);const r=function(e){if(l.isBuffer(e)){const t=0|p(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),n=a(t);for(let i=0;i<t;i+=1)n[i]=255&e[i];return n}function E(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(i,l.prototype),i}function p(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(r)return i?-1:z(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return R(this,t,n);case"ascii":return b(this,t,n);case"latin1":case"binary":return w(this,t,n);case"base64":return y(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function C(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function m(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),J(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:v(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):v(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function v(e,t,n,i,r){let o,s=1,a=e.length,l=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,l/=2,n/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){let i=-1;for(o=n;o<a;o++)if(c(e,o)===c(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===l)return i*s}else-1!==i&&(o-=o-i),i=-1}else for(n+l>a&&(n=a-l),o=n;o>=0;o--){let n=!0;for(let i=0;i<l;i++)if(c(e,o+i)!==c(t,i)){n=!1;break}if(n)return o}return-1}function _(e,t,n,i){n=Number(n)||0;const r=e.length-n;i?(i=Number(i))>r&&(i=r):i=r;const o=t.length;let s;for(i>o/2&&(i=o/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(J(i))return s;e[n+s]=i}return s}function S(e,t,n,i){return Y(z(t,e.length-n),e,n,i)}function A(e,t,n,i){return Y(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function I(e,t,n,i){return Y(K(t),e,n,i)}function T(e,t,n,i){return Y(function(e,t){let n,i,r;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),i=n>>8,r=n%256,o.push(r),o.push(i);return o}(t,e.length-n),e,n,i)}function y(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function R(e,t,n){n=Math.min(e.length,n);const i=[];let r=t;for(;r<n;){const t=e[r];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(r+s<=n){let n,i,a,l;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[r+1],128==(192&n)&&(l=(31&t)<<6|63&n,l>127&&(o=l));break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(l=(15&t)<<12|(63&n)<<6|63&i,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:n=e[r+1],i=e[r+2],a=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&a)&&(l=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&a,l>65535&&l<1114112&&(o=l))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),r+=s}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=O));return n}(i)}t.kMaxLength=s,l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,n){return function(e,t,n){return u(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},l.allocUnsafe=function(e){return d(e)},l.allocUnsafeSlow=function(e){return d(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(q(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),q(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let r=0,o=Math.min(n,i);r<o;++r)if(e[r]!==t[r]){n=e[r],i=t[r];break}return n<i?-1:i<n?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const i=l.allocUnsafe(t);let r=0;for(n=0;n<e.length;++n){let t=e[n];if(q(t,Uint8Array))r+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,r)):Uint8Array.prototype.set.call(i,t,r);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,r)}r+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)C(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)C(this,t,t+3),C(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)C(this,t,t+7),C(this,t+1,t+6),C(this,t+2,t+5),C(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):g.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(e,t,n,i,r){if(q(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;let o=(r>>>=0)-(i>>>=0),s=(n>>>=0)-(t>>>=0);const a=Math.min(o,s),c=this.slice(i,r),u=e.slice(t,n);for(let e=0;e<a;++e)if(c[e]!==u[e]){o=c[e],s=u[e];break}return o<s?-1:s<o?1:0},l.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},l.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},l.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},l.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function b(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(127&e[r]);return i}function w(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(e[r]);return i}function N(e,t,n){const i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);let r="";for(let i=t;i<n;++i)r+=X[e[i]];return r}function M(e,t,n){const i=e.slice(t,n);let r="";for(let e=0;e<i.length-1;e+=2)r+=String.fromCharCode(i[e]+256*i[e+1]);return r}function D(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function L(e,t,n,i,r,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<o)throw new RangeError('"value" argument is out of bounds');if(n+i>e.length)throw new RangeError("Index out of range")}function P(e,t,n,i,r){$(t,i,r,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,i,r){$(t,i,r,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function k(e,t,n,i,r,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function B(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function j(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,8),r.write(e,t,n,i,52,8),n+8}l.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],r=1,o=0;for(;++o<t&&(r*=256);)i+=this[e+o]*r;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e+--t],r=1;for(;t>0&&(r*=256);)i+=this[e+--t]*r;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(r)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<<BigInt(32))+BigInt(r)}),l.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],r=1,o=0;for(;++o<t&&(r*=256);)i+=this[e+o]*r;return r*=128,i>=r&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=t,r=1,o=this[e+--i];for(;i>0&&(r*=256);)o+=this[e+--i]*r;return r*=128,o>=r&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),r.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let r=1,o=0;for(this[t]=255&e;++o<n&&(r*=256);)this[t+o]=e/r&255;return t+n},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let r=n-1,o=1;for(this[t+r]=255&e;--r>=0&&(o*=256);)this[t+r]=e/o&255;return t+n},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let r=0,o=1,s=0;for(this[t]=255&e;++r<n&&(o*=256);)e<0&&0===s&&0!==this[t+r-1]&&(s=1),this[t+r]=(e/o|0)-s&255;return t+n},l.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let r=n-1,o=1,s=0;for(this[t+r]=255&e;--r>=0&&(o*=256);)e<0&&0===s&&0!==this[t+r+1]&&(s=1),this[t+r]=(e/o|0)-s&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,n){return B(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return B(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);const r=i-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),t),r},l.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let r;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(r=t;r<n;++r)this[r]=e;else{const o=l.isBuffer(e)?e:l.from(e,i),s=o.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(r=0;r<n-t;++r)this[r+t]=o[r%s]}return this};const V={};function G(e,t,n){V[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const i="-"===e[0]?1:0;for(;n>=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,i,r,o){if(e>n||e<t){const i="bigint"==typeof t?"n":"";let r;throw r=o>3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(o+1)}${i}`:`>= -(2${i} ** ${8*(o+1)-1}${i}) and < 2 ** ${8*(o+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new V.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){x(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||H(t,e.length-(n+1))}(i,r,o)}function x(e,t){if("number"!=typeof e)throw new V.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,n){if(Math.floor(e)!==e)throw x(e,n),new V.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new V.ERR_BUFFER_OUT_OF_BOUNDS;throw new V.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}G("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),G("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),G("ERR_OUT_OF_RANGE",function(e,t,n){let i=`The value of "${e}" is out of range.`,r=n;return Number.isInteger(n)&&Math.abs(n)>2**32?r=F(String(n)):"bigint"==typeof n&&(r=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(r=F(r)),r+="n"),i+=` It must be ${t}. Received ${r}`,i},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const i=e.length;let r=null;const o=[];for(let s=0;s<i;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function K(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,n,i){let r;for(r=0;r<i&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let r=0;r<16;++r)t[i+r]=e[n]+e[r]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},295:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0;var i=n(656);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}})},322:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStreamState=void 0,function(e){e[e.UNSTARTED=0]="UNSTARTED",e[e.STREAMING=1]="STREAMING",e[e.INTERRUPTED=2]="INTERRUPTED",e[e.ENDED=3]="ENDED"}(n||(t.TalkMessageStreamState=n={}))},353:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateCorrelationId=void 0,t.generateCorrelationId=function(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}},421:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=void 0,t.AgentAudioInputStream=class{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const t={audioData:"string"==typeof e?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(t)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array.from(t,e=>String.fromCharCode(e)).join("");return btoa(n)}}},440:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorCode=t.ClientError=t.unsafe_createClientWithApiKey=t.createClient=void 0;const s=o(n(816)),a=n(71);Object.defineProperty(t,"ClientError",{enumerable:!0,get:function(){return a.ClientError}}),Object.defineProperty(t,"ErrorCode",{enumerable:!0,get:function(){return a.ErrorCode}}),t.createClient=(e,t)=>new s.default(e,void 0,t),t.unsafe_createClientWithApiKey=(e,t,n)=>new s.default(void 0,t,Object.assign(Object.assign({},n),{apiKey:e})),r(n(170),t)},462:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHistoryClient=void 0;const i=n(170);t.MessageHistoryClient=class{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},n=this.messages.findIndex(e=>e.id===t.id);if(-1!==n){const e=this.messages[n];this.messages[n]=Object.assign(Object.assign({},e),{content:e.content+t.content,interrupted:e.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case i.MessageRole.USER:this.processUserMessage(t);break;case i.MessageRole.PERSONA:this.processPersonaMessage(t)}t.endOfSpeech&&this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_HISTORY_UPDATED,this.messages)}}},471:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=void 0;const i=n(170);t.ReasoningHistoryClient=class{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(i.AnamEvent.REASONING_STREAM_EVENT_RECEIVED,t);const n={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(e=>e.id===n.id);if(-1!==r){const e=this.reasoning_messages[r];e.content+=n.content,this.reasoning_messages[r]=e}else this.reasoning_messages.push(n);t.endOfThought&&this.publicEventEmitter.emit(i.AnamEvent.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}},513:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebRtcReasoningTextMessageEvent=t.DataChannelMessage=void 0;var i=n(676);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return i.DataChannelMessage}});var r=n(540);Object.defineProperty(t,"WebRtcReasoningTextMessageEvent",{enumerable:!0,get:function(){return r.WebRtcReasoningTextMessageEvent}})},526:(e,t)=>{"use strict";t.byteLength=function(e){var t=a(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,o=a(e),s=o[0],l=o[1],c=new r(function(e,t,n){return 3*(t+n)/4-n}(0,s,l)),u=0,d=l>0?s-4:s;for(n=0;n<d;n+=4)t=i[e.charCodeAt(n)]<<18|i[e.charCodeAt(n+1)]<<12|i[e.charCodeAt(n+2)]<<6|i[e.charCodeAt(n+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=255&t;return 2===l&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[u++]=255&t),1===l&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t),c},t.fromByteArray=function(e){for(var t,i=e.length,r=i%3,o=[],s=16383,a=0,l=i-r;a<l;a+=s)o.push(c(e,a,a+s>l?l:a+s));return 1===r?(t=e[i-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=o[s],i[o.charCodeAt(s)]=s;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function c(e,t,n){for(var i,r=[],o=t;o<n;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),r.push(l(i));return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},529:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.EngineApiRestClient=void 0,t.EngineApiRestClient=class{constructor(e,t,n){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=n}sendTalkCommand(e){return n(this,void 0,void 0,function*(){var t,n;try{let i,r={"Content-Type":"application/json"};const o="/talk",s=`?session_id=${this.sessionId}`;if((null===(t=this.apiGatewayConfig)||void 0===t?void 0:t.enabled)&&(null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.baseUrl)){i=`${this.apiGatewayConfig.baseUrl}${o}${s}`;const e=new URL(`${this.baseUrl}${o}${s}`);r["X-Anam-Target-Url"]=e.href}else i=`${this.baseUrl}${o}${s}`;const a=yield fetch(i,{method:"POST",headers:r,body:JSON.stringify({content:e})});if(!a.ok)throw new Error(`Failed to send talk command: ${a.status} ${a.statusText}`)}catch(e){throw console.error(e),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}},540:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},577:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.StreamingClient=void 0;const r=n(948),o=n(958),s=n(170),a=n(421),l=n(711);t.StreamingClient=class{constructor(e,t,n,i,r){var a,l,c,u;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:s.AudioPermissionState.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=n,this.internalEventEmitter=i,this.toolCallManager=r,this.apiGatewayConfig=t.apiGateway;const{inputAudio:d}=t;this.inputAudioState=d.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=!0===t.inputAudio.disableInputAudio,this.internalEventEmitter.addListener(s.InternalEvent.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(s.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(s.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(s.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new o.SignallingClient(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new o.EngineApiRestClient(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=null!==(l=null===(a=t.metrics)||void 0===a?void 0:a.showPeerConnectionStatsReport)&&void 0!==l&&l,this.peerConnectionStatsReportOutputFormat=null!==(u=null===(c=t.metrics)||void 0===c?void 0:c.peerConnectionStatsReportOutputFormat)&&void 0!==u?u:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>i(this,void 0,void 0,function*(){if(this.peerConnection&&this.dataChannel&&"open"===this.dataChannel.readyState)try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),5e3))}sendClientSideMetrics(e){e.forEach(e=>{if("inbound-rtp"===e.type){const t={message_type:"remote_rtp_stats",data:e};this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(JSON.stringify(t))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},15e3);this.successMetricPoller=setInterval(()=>i(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired)return this.successMetricPoller&&clearInterval(this.successMetricPoller),void clearTimeout(e);try{const t=yield this.peerConnection.getStats();let n=!1,i=null;t.forEach(e=>{"inbound-rtp"===e.type&&"video"===e.kind&&(void 0!==e.framesDecoded&&e.framesDecoded>0?(n=!0,i="framesDecoded"):void 0!==e.framesReceived&&e.framesReceived>0?(n=!0,i="framesReceived"):e.bytesReceived>0&&e.packetsReceived>0&&e.bytesReceived>1e5&&(n=!0,i="bytesReceived"))}),n&&!this.successMetricFired&&(this.successMetricFired=!0,(0,r.sendClientMetric)(r.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",i?{detectionMethod:i}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch(e){}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(null==e)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(e=>{e.stop()});const n={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:n}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(s.AnamEvent.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(e){throw console.error("Failed to change audio input device:",e),new Error(`StreamingClient - changeAudioInputDevice: ${e instanceof Error?e.message:String(e)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection)return void console.error("StreamingClient - startConnection: peer connection already exists");this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return i(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new l.TalkMessageStream(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new a.AgentAudioInputStream(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return i(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:2}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return i(this,void 0,void 0,function*(){if(this.peerConnection)switch(e.actionType){case s.SignalMessageAction.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case s.SignalMessageAction.ICE_CANDIDATE:const n=e.payload,i=new RTCIceCandidate(n);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(i):this.remoteIceCandidateBuffer.push(i);break;case s.SignalMessageAction.END_SESSION:const r=e.payload;this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.SERVER_CLOSED_CONNECTION,r),this.shutdown();break;case s.SignalMessageAction.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(s.AnamEvent.SERVER_WARNING,o);break;case s.SignalMessageAction.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(s.AnamEvent.TALK_STREAM_INTERRUPTED,a.correlationId);break;case s.SignalMessageAction.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(s.AnamEvent.SESSION_READY,l);break;case s.SignalMessageAction.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}else console.error("StreamingClient - onSignalMessage: peerConnection is not initialized")})}onSignallingClientConnected(){return i(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;"connected"!==(null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState)&&"completed"!==(null===(t=this.peerConnection)||void 0===t?void 0:t.iceConnectionState)||(this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;"closed"===(null===(e=this.peerConnection)||void 0===e?void 0:e.connectionState)&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),"NotAllowedError"===e.name&&"Permission denied"===e.message?this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(e){if("video"===e.track.kind){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(s.AnamEvent.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const e=this.videoElement.requestVideoFrameCallback(()=>{var t;null===(t=this.videoElement)||void 0===t||t.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(s.AnamEvent.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,(0,r.sendClientMetric)(r.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else"audio"===e.track.kind&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(s.AnamEvent.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return i(this,void 0,void 0,function*(){if(!this.peerConnection)return void console.error("StreamingClient - setupDataChannels: peer connection is not initialized");if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=null!=e?e:null},e.onclose=()=>{},e.onmessage=e=>{try{const t=JSON.parse(e.data);switch(t.messageType){case s.DataChannelMessage.SPEECH_TEXT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,t.data);break;case s.DataChannelMessage.TOOL_CALL_STARTED_EVENT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,t.data);break;case s.DataChannelMessage.TOOL_CALL_COMPLETED_EVENT:const e=t.data;"client"===e.tool_type&&(this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,{event_uid:e.event_uid,session_id:e.session_id,event_name:e.tool_name,event_data:e.arguments,timestamp:e.timestamp,timestamp_user_action:e.timestamp_user_action,user_action_correlation_id:e.user_action_correlation_id,used_outside_engine:e.used_outside_engine}),this.publicEventEmitter.emit(s.AnamEvent.CLIENT_TOOL_EVENT_RECEIVED,o.ToolCallManager.WebRTCToolCallCompletedEventToClientToolEvent(e))),this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,t.data);break;case s.DataChannelMessage.TOOL_CALL_FAILED_EVENT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,t.data);break;case s.DataChannelMessage.REASONING_TEXT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,t.data)}}catch(e){console.error("Failed to parse data channel message:",e)}}})}requestMicrophonePermissionAsync(){return i(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==s.AudioPermissionState.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:s.AudioPermissionState.PENDING}),this.publicEventEmitter.emit(s.AnamEvent.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:s.AudioPermissionState.GRANTED}),this.publicEventEmitter.emit(s.AnamEvent.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:s.AudioPermissionState.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(s.AnamEvent.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return i(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length)return void console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],t=this.peerConnection.getSenders().find(e=>{var t;return"audio"===(null===(t=e.track)||void 0===t?void 0:t.kind)||null===e.track&&null!==e.dtmf});if(t)try{yield t.replaceTrack(e)}catch(t){console.error("Failed to replace audio track:",t),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(s.AnamEvent.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return i(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),this.peerConnection){try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)}else console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized")})}shutdown(){return i(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield null===(e=this.peerConnection)||void 0===e?void 0:e.getStats();if(t){const e=(0,r.createRTCStatsReport)(t,this.peerConnectionStatsReportOutputFormat);e&&console.log(e,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(e=>{e.stop()}),this.inputAudioStream=null}catch(e){console.error("StreamingClient - shutdown: error stopping input audio stream",e)}try{this.signallingClient.stop()}catch(e){console.error("StreamingClient - shutdown: error stopping signallilng",e)}try{this.peerConnection&&"closed"!==this.peerConnection.connectionState&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(e){console.error("StreamingClient - shutdown: error closing peer connection",e)}})}}},645:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEvent=void 0,function(e){e.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",e.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",e.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",e.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",e.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"}(n||(t.InternalEvent=n={}))},656:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0,function(e){e.OFFER="offer",e.ANSWER="answer",e.ICE_CANDIDATE="icecandidate",e.END_SESSION="endsession",e.HEARTBEAT="heartbeat",e.WARNING="warning",e.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",e.TALK_STREAM_INPUT="talkstream",e.SESSION_READY="sessionready",e.AGENT_AUDIO_INPUT="agentaudioinput",e.AGENT_AUDIO_INPUT_END="agentaudioinputend"}(n||(t.SignalMessageAction=n={}))},672:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isCustomPersonaConfig=void 0,t.isCustomPersonaConfig=function(e){return"brainType"in e||"llmId"in e}},676:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DataChannelMessage=void 0,function(e){e.SPEECH_TEXT="speechText",e.CLIENT_TOOL_EVENT="clientToolEvent",e.TOOL_CALL_STARTED_EVENT="toolCallStarted",e.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",e.TOOL_CALL_FAILED_EVENT="toolCallFailed",e.REASONING_TEXT="reasoningText"}(n||(t.DataChannelMessage=n={}))},711:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStream=void 0;const r=n(170),o=n(322);t.TalkMessageStream=class{constructor(e,t,n){this.state=o.TalkMessageStreamState.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=n,this.internalEventEmitter.addListener(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return i(this,void 0,void 0,function*(){e.actionType===r.SignalMessageAction.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=o.TalkMessageStreamState.INTERRUPTED,this.onDeactivate())})}endMessage(){return i(this,void 0,void 0,function*(){if(this.state===o.TalkMessageStreamState.ENDED)return void console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");if(this.state!==o.TalkMessageStreamState.STREAMING)return void console.warn("Talk stream is not active state: "+this.state);const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=o.TalkMessageStreamState.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return i(this,void 0,void 0,function*(){if(this.state!==o.TalkMessageStreamState.STREAMING&&this.state!==o.TalkMessageStreamState.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===o.TalkMessageStreamState.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?o.TalkMessageStreamState.ENDED:o.TalkMessageStreamState.STREAMING,this.state===o.TalkMessageStreamState.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===o.TalkMessageStreamState.STREAMING||this.state===o.TalkMessageStreamState.UNSTARTED}getState(){return this.state}}},793:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AudioPermissionState=void 0,function(e){e.PENDING="pending",e.GRANTED="granted",e.DENIED="denied",e.NOT_REQUESTED="not_requested"}(n||(t.AudioPermissionState=n={}))},816:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0});const r=n(287),o=n(71),s=n(948),a=n(353),l=n(272),c=n(958),u=n(170);t.default=class{constructor(e,t,n){var i,r,a,l,d;this.inputAudioState={isMuted:!1,permissionState:u.AudioPermissionState.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const h=this.validateClientConfig(e,t,n);if(h)throw new o.ClientError(h,o.ErrorCode.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=n,((null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.baseUrl)||(null===(r=null==n?void 0:n.api)||void 0===r?void 0:r.apiVersion))&&(0,s.setClientMetricsBaseUrl)(n.api.baseUrl||s.DEFAULT_ANAM_METRICS_BASE_URL,n.api.apiVersion||s.DEFAULT_ANAM_API_VERSION),(null===(l=null===(a=null==n?void 0:n.api)||void 0===a?void 0:a.apiGateway)||void 0===l?void 0:l.enabled)&&(0,s.setClientMetricsApiGateway)(n.api.apiGateway),(null===(d=null==n?void 0:n.metrics)||void 0===d?void 0:d.disableClientMetrics)&&(0,s.setClientMetricsDisabled)(!0),this.publicEventEmitter=new c.PublicEventEmitter,this.internalEventEmitter=new c.InternalEventEmitter,this.toolCallManager=new c.ToolCallManager,this.apiClient=new c.CoreApiRestClient(e,null==n?void 0:n.apiKey,null==n?void 0:n.api),this.messageHistoryClient=new c.MessageHistoryClient(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new c.ReasoningHistoryClient(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],n=r.Buffer.from(t,"base64").toString("utf8");return JSON.parse(n)}catch(e){throw new Error("Invalid session token format")}}validateClientConfig(e,t,n){var i,r;if(!e&&!(null==n?void 0:n.apiKey))return"Either sessionToken or apiKey must be provided";if((null==n?void 0:n.apiKey)&&e)return"Only one of sessionToken or apiKey should be used";const o=(0,l.validateApiGatewayConfig)(null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.apiGateway);if(o)return o;if(e){const n=this.decodeJwt(e);this.organizationId=n.accountId,(0,s.setMetricsContext)({organizationId:this.organizationId});const i=null===(r=n.type)||void 0===r?void 0:r.toLowerCase();if("legacy"===i)return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if(("ephemeral"===i||"stateful"===i)&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(null==n?void 0:n.voiceDetection){if(n.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(void 0!==n.voiceDetection.endOfSpeechSensitivity){if("number"!=typeof n.voiceDetection.endOfSpeechSensitivity)return"End of speech sensitivity must be a number";if(n.voiceDetection.endOfSpeechSensitivity<0||n.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if((null===(e=this.clientOptions)||void 0===e?void 0:e.voiceDetection)&&(t.voiceDetection=this.clientOptions.voiceDetection),0!==Object.keys(t).length)return t}startSession(e){return i(this,void 0,void 0,function*(){var t,n,i,r,a,l,u,d,h,E,p,f;const g=this.personaConfig,C=this.buildStartSessionOptionsForClient(),m=yield this.apiClient.startSession(g,C),{sessionId:v,clientConfig:_,engineHost:S,engineProtocol:A,signallingEndpoint:I}=m,{heartbeatIntervalSeconds:T,maxWsReconnectionAttempts:y,iceServers:R}=_;this.sessionId=v,(0,s.setMetricsContext)({sessionId:this.sessionId});const O=(null===(t=this.clientOptions)||void 0===t?void 0:t.iceServers)?this.clientOptions.iceServers:R;try{this.streamingClient=new c.StreamingClient(v,{engine:{baseUrl:`${A}://${S}`},signalling:{heartbeatIntervalSeconds:T,maxWsReconnectionAttempts:y,url:{baseUrl:S,protocol:A,signallingPath:I}},iceServers:O,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:(null===(n=this.clientOptions)||void 0===n?void 0:n.disableInputAudio)?void 0:e,audioDeviceId:null===(i=this.clientOptions)||void 0===i?void 0:i.audioDeviceId,disableInputAudio:null===(r=this.clientOptions)||void 0===r?void 0:r.disableInputAudio},apiGateway:null===(l=null===(a=this.clientOptions)||void 0===a?void 0:a.api)||void 0===l?void 0:l.apiGateway,metrics:{showPeerConnectionStatsReport:null!==(h=null===(d=null===(u=this.clientOptions)||void 0===u?void 0:u.metrics)||void 0===d?void 0:d.showPeerConnectionStatsReport)&&void 0!==h&&h,peerConnectionStatsReportOutputFormat:null!==(f=null===(p=null===(E=this.clientOptions)||void 0===E?void 0:E.metrics)||void 0===p?void 0:p.peerConnectionStatsReportOutputFormat)&&void 0!==f?f:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(e){throw(0,s.setMetricsContext)({sessionId:null}),new o.ClientError("Failed to initialize streaming client",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:v})}return v})}startSessionIfNeeded(e){return i(this,void 0,void 0,function*(){if(!(this.sessionId&&this.streamingClient||(yield this.startSession(e),this.sessionId&&this.streamingClient)))throw new o.ClientError("Session ID or streaming client is not available after starting session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return i(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const n=(0,a.generateCorrelationId)();return(0,s.setMetricsContext)({attemptCorrelationId:n,sessionId:null}),(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(e=>{var t;const n=[];let i=!1,r=!1;this.publicEventEmitter.addListener(u.AnamEvent.VIDEO_STREAM_STARTED,t=>{n.push(t),i=!0,r&&e(n)}),this.publicEventEmitter.addListener(u.AnamEvent.AUDIO_STREAM_STARTED,t=>{n.push(t),r=!0,i&&e(n)}),null===(t=this.streamingClient)||void 0===t||t.startConnection()})})}streamToVideoAndAudioElements(e,t,n){return i(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,n)})}streamToVideoElement(e,t){return i(this,void 0,void 0,function*(){var n;const i=(0,a.generateCorrelationId)();(0,s.setMetricsContext)({attemptCorrelationId:i,sessionId:null}),(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),(null===(n=this.clientOptions)||void 0===n?void 0:n.disableInputAudio)&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(e){if(e instanceof o.ClientError)throw e;throw new o.ClientError("Failed to start session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return i(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(!this.streamingClient)throw new Error("Failed to send message: session is not started.");this.streamingClient.sendDataMessage(e)}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const n=(new Date).toISOString().replace("Z",""),i=JSON.stringify({content:e,timestamp:n,session_id:t,message_type:"speech"});this.sendDataMessage(i)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:(new Date).toISOString()});this.sendDataMessage(t)}stopStreaming(){return i(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(u.AnamEvent.CONNECTION_CLOSED,u.ConnectionClosedCode.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,(0,s.setMetricsContext)({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return i(this,void 0,void 0,function*(){var t;if(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&""===e.trim())throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){this.toolCallManager.registerHandler(e,t)}}},822:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0;var i=n(273);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return i.MessageRole}})},878:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=void 0;var i=n(21);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return i.AnamEvent}});var r=n(645);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return r.InternalEvent}});var o=n(60);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return o.ConnectionClosedCode}})},948:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.createRTCStatsReport=t.sendClientMetric=t.setMetricsContext=t.setClientMetricsDisabled=t.setClientMetricsApiGateway=t.setClientMetricsBaseUrl=t.ClientMetricMeasurement=t.DEFAULT_ANAM_API_VERSION=t.DEFAULT_ANAM_METRICS_BASE_URL=void 0;const r=n(985);var o;t.DEFAULT_ANAM_METRICS_BASE_URL="https://api.anam.ai",t.DEFAULT_ANAM_API_VERSION="/v1",function(e){e.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",e.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",e.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"}(o||(t.ClientMetricMeasurement=o={}));let s,a=t.DEFAULT_ANAM_METRICS_BASE_URL,l=t.DEFAULT_ANAM_API_VERSION,c=!1;t.setClientMetricsBaseUrl=(e,n=t.DEFAULT_ANAM_API_VERSION)=>{a=e,l=n},t.setClientMetricsApiGateway=e=>{s=e},t.setClientMetricsDisabled=e=>{c=e};let u={sessionId:null,organizationId:null,attemptCorrelationId:null};t.setMetricsContext=e=>{u=Object.assign(Object.assign({},u),e)},t.sendClientMetric=(e,t,n)=>i(void 0,void 0,void 0,function*(){if(!c)try{const i=Object.assign(Object.assign({},r.CLIENT_METADATA),n);u.sessionId&&(i.sessionId=u.sessionId),u.organizationId&&(i.organizationId=u.organizationId),u.attemptCorrelationId&&(i.attemptCorrelationId=u.attemptCorrelationId);const o=`${l}/metrics/client`;let c,d={"Content-Type":"application/json"};(null==s?void 0:s.enabled)&&(null==s?void 0:s.baseUrl)?(c=`${s.baseUrl}${o}`,d["X-Anam-Target-Url"]=`${a}${o}`):c=`${a}${o}`,yield fetch(c,{method:"POST",headers:d,body:JSON.stringify({name:e,value:t,tags:i})})}catch(e){console.error("Failed to send error metric:",e)}}),t.createRTCStatsReport=(e,t="console")=>{var n,i,r;const o={};e.forEach(e=>{o[e.type]||(o[e.type]=[]),o[e.type].push(e)});const s={issues:[]},a=(null===(n=o["inbound-rtp"])||void 0===n?void 0:n.filter(e=>"video"===e.kind))||[];a.length>0&&(s.personaVideoStream=[],a.forEach(e=>{var t,n,i,r,o;const a={framesReceived:null!==(t=e.framesReceived)&&void 0!==t?t:"unknown",framesDropped:null!==(n=e.framesDropped)&&void 0!==n?n:"unknown",framesPerSecond:null!==(i=e.framesPerSecond)&&void 0!==i?i:"unknown",packetsReceived:null!==(r=e.packetsReceived)&&void 0!==r?r:"unknown",packetsLost:null!==(o=e.packetsLost)&&void 0!==o?o:"unknown",resolution:e.frameWidth&&e.frameHeight?`${e.frameWidth}x${e.frameHeight}`:void 0,jitter:void 0!==e.jitter?e.jitter:void 0};s.personaVideoStream.push(a)}));const l=(null===(i=o["inbound-rtp"])||void 0===i?void 0:i.filter(e=>"audio"===e.kind))||[];l.length>0&&(s.personaAudioStream=[],l.forEach(e=>{var t,n,i;const r={packetsReceived:null!==(t=e.packetsReceived)&&void 0!==t?t:"unknown",packetsLost:null!==(n=e.packetsLost)&&void 0!==n?n:"unknown",audioLevel:null!==(i=e.audioLevel)&&void 0!==i?i:"unknown",jitter:void 0!==e.jitter?e.jitter:void 0,totalAudioEnergy:void 0!==e.totalAudioEnergy?e.totalAudioEnergy:void 0};s.personaAudioStream.push(r)}));const c=(null===(r=o["outbound-rtp"])||void 0===r?void 0:r.filter(e=>"audio"===e.kind))||[];c.length>0&&(s.userAudioInput=[],c.forEach(e=>{var t,n;const i={packetsSent:null!==(t=e.packetsSent)&&void 0!==t?t:"unknown",retransmittedPackets:null!==(n=e.retransmittedPacketsSent)&&void 0!==n?n:void 0,avgPacketSendDelay:void 0!==e.totalPacketSendDelay?e.totalPacketSendDelay/(e.packetsSent||1)*1e3:void 0};s.userAudioInput.push(i)})),o.codec&&(s.codecs=[],o.codec.forEach(e=>{const t={status:e.payloadType?"Active":"Available",mimeType:e.mimeType||"Unknown",payloadType:e.payloadType||"N/A",clockRate:e.clockRate||void 0,channels:e.channels||void 0};s.codecs.push(t)})),o.transport&&(s.transportLayer=[],o.transport.forEach(e=>{const t={dtlsState:e.dtlsState||"unknown",iceState:e.iceState||"unknown",bytesSent:e.bytesSent||void 0,bytesReceived:e.bytesReceived||void 0};s.transportLayer.push(t)}));const u=[];if(a.forEach(e=>{"number"==typeof e.framesDropped&&e.framesDropped>0&&u.push(`Video: ${e.framesDropped} frames dropped`),"number"==typeof e.packetsLost&&e.packetsLost>0&&u.push(`Video: ${e.packetsLost} packets lost`),"number"==typeof e.framesPerSecond&&e.framesPerSecond<23&&u.push(`Video: Low frame rate (${e.framesPerSecond} fps)`)}),l.forEach(e=>{"number"==typeof e.packetsLost&&e.packetsLost>0&&u.push(`Audio: ${e.packetsLost} packets lost`),"number"==typeof e.jitter&&e.jitter>.1&&u.push(`Audio: High jitter (${(1e3*e.jitter).toFixed(1)}ms)`)}),s.issues=u,"json"===t)return s;console.group("📊 WebRTC Session Statistics Report"),s.personaVideoStream&&s.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),s.personaVideoStream.forEach(e=>{console.log(`Frames Received: ${e.framesReceived}`),console.log(`Frames Dropped: ${e.framesDropped}`),console.log(`Frames Per Second: ${e.framesPerSecond}`),console.log(`Packets Received: ${"number"==typeof e.packetsReceived?e.packetsReceived.toLocaleString():e.packetsReceived}`),console.log(`Packets Lost: ${e.packetsLost}`),e.resolution&&console.log(`Resolution: ${e.resolution}`),void 0!==e.jitter&&console.log(`Jitter: ${e.jitter.toFixed(5)}ms`)}),console.groupEnd()),s.personaAudioStream&&s.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),s.personaAudioStream.forEach(e=>{console.log(`Packets Received: ${"number"==typeof e.packetsReceived?e.packetsReceived.toLocaleString():e.packetsReceived}`),console.log(`Packets Lost: ${e.packetsLost}`),console.log(`Audio Level: ${e.audioLevel}`),void 0!==e.jitter&&console.log(`Jitter: ${e.jitter.toFixed(5)}ms`),void 0!==e.totalAudioEnergy&&console.log(`Total Audio Energy: ${e.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),s.userAudioInput&&s.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),s.userAudioInput.forEach(e=>{console.log(`Packets Sent: ${"number"==typeof e.packetsSent?e.packetsSent.toLocaleString():e.packetsSent}`),e.retransmittedPackets&&console.log(`Retransmitted Packets: ${e.retransmittedPackets}`),void 0!==e.avgPacketSendDelay&&console.log(`Avg Packet Send Delay: ${e.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),s.codecs&&s.codecs.length>0&&(console.group("🔧 Codecs Used"),s.codecs.forEach(e=>{console.log(`${e.status} ${e.mimeType} - Payload Type: ${e.payloadType}`),e.clockRate&&console.log(` Clock Rate: ${e.clockRate}Hz`),e.channels&&console.log(` Channels: ${e.channels}`)}),console.groupEnd()),s.transportLayer&&s.transportLayer.length>0&&(console.group("🚚 Transport Layer"),s.transportLayer.forEach(e=>{console.log(`DTLS State: ${e.dtlsState}`),console.log(`ICE State: ${e.iceState}`),(e.bytesReceived||e.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(e.bytesSent||0).toLocaleString()}, Received: ${(e.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),s.issues.length>0?(console.group("⚠️ Potential Issues Detected"),s.issues.forEach(e=>console.warn(e)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()}},958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=t.ToolCallManager=t.StreamingClient=t.PublicEventEmitter=t.MessageHistoryClient=t.InternalEventEmitter=t.EngineApiRestClient=t.CoreApiRestClient=t.SignallingClient=void 0;var i=n(279);Object.defineProperty(t,"SignallingClient",{enumerable:!0,get:function(){return i.SignallingClient}});var r=n(18);Object.defineProperty(t,"CoreApiRestClient",{enumerable:!0,get:function(){return r.CoreApiRestClient}});var o=n(529);Object.defineProperty(t,"EngineApiRestClient",{enumerable:!0,get:function(){return o.EngineApiRestClient}});var s=n(259);Object.defineProperty(t,"InternalEventEmitter",{enumerable:!0,get:function(){return s.InternalEventEmitter}});var a=n(462);Object.defineProperty(t,"MessageHistoryClient",{enumerable:!0,get:function(){return a.MessageHistoryClient}});var l=n(995);Object.defineProperty(t,"PublicEventEmitter",{enumerable:!0,get:function(){return l.PublicEventEmitter}});var c=n(577);Object.defineProperty(t,"StreamingClient",{enumerable:!0,get:function(){return c.StreamingClient}});var u=n(35);Object.defineProperty(t,"ToolCallManager",{enumerable:!0,get:function(){return u.ToolCallManager}});var d=n(471);Object.defineProperty(t,"ReasoningHistoryClient",{enumerable:!0,get:function(){return d.ReasoningHistoryClient}})},985:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLIENT_METADATA=t.DEFAULT_API_VERSION=t.DEFAULT_API_BASE_URL=t.DEFAULT_HEADERS=void 0,t.DEFAULT_HEADERS={"Content-Type":"application/json"},t.DEFAULT_API_BASE_URL="https://api.anam.ai",t.DEFAULT_API_VERSION="/v1",t.CLIENT_METADATA={client:"js-sdk",version:"0.0.0-automated"}},995:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PublicEventEmitter=void 0;const i=n(948),r=n(170);t.PublicEventEmitter=class{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===r.AnamEvent.CONNECTION_ESTABLISHED&&(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===r.AnamEvent.CONNECTION_CLOSED){const[e,n]=t;(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,e,n?{details:n}:void 0)}this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}}},t={},function n(i){var r=t[i];if(void 0!==r)return r.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(440);var e,t});
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.anam=t():e.anam=t()}(self,()=>{return e={18:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreApiRestClient=void 0;const r=n(71),o=n(985),s=n(672);t.CoreApiRestClient=class{constructor(e,t,n){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(null==n?void 0:n.baseUrl)||o.DEFAULT_API_BASE_URL,this.apiVersion=(null==n?void 0:n.apiVersion)||o.DEFAULT_API_VERSION,this.apiGatewayConfig=(null==n?void 0:n.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var n,i;if((null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.enabled)&&(null===(i=this.apiGatewayConfig)||void 0===i?void 0:i.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,i=new URL(`${this.baseUrl}${e}`);return{url:n,headers:Object.assign(Object.assign({},t),{"X-Anam-Target-Url":i.href})}}return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return i(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new r.ClientError("Persona configuration must be provided when using apiKey",r.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const n=`${this.apiVersion}/engine/session`,{url:i,headers:s}=this.buildGatewayUrlAndHeaders(n,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),a=yield fetch(i,{method:"POST",headers:s,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:o.CLIENT_METADATA})}),l=yield a.json(),c=l.error;switch(a.status){case 200:case 201:return l;case 400:throw new r.ClientError("Invalid request to start session",r.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new r.ClientError("Authentication failed when starting session",r.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new r.ClientError("Please sign up for a plan to start a session",r.ErrorCode.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new r.ClientError("Authentication failed when starting session",r.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:throw"Concurrent session limit reached"===c?new r.ClientError("Concurrency limit reached, please upgrade your plan",r.ErrorCode.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message}):"Spend cap reached"===c?new r.ClientError("Spend cap reached, please upgrade your plan",r.ErrorCode.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message}):new r.ClientError("Usage limit reached, please upgrade your plan",r.ErrorCode.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new r.ClientError("There are no available personas, please try again later",r.ErrorCode.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new r.ClientError("Unknown error when starting session",r.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:l.message})}}catch(e){if(e instanceof r.ClientError)throw e;throw new r.ClientError("Failed to start session",r.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e)})}})}unsafe_getSessionToken(e){return i(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};(0,s.isCustomPersonaConfig)(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const e=`${this.apiVersion}/auth/session-token`,{url:n,headers:i}=this.buildGatewayUrlAndHeaders(e,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}),r=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(t)});return(yield r.json()).sessionToken}catch(e){throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}},21:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AnamEvent=void 0,function(e){e.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",e.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",e.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",e.CONNECTION_CLOSED="CONNECTION_CLOSED",e.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",e.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",e.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",e.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",e.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",e.SESSION_READY="SESSION_READY",e.SERVER_WARNING="SERVER_WARNING",e.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",e.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",e.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",e.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",e.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",e.TOOL_CALL_EVENT_RECEIVED="TOOL_CALL_EVENT_RECEIVED",e.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",e.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED"}(n||(t.AnamEvent=n={}))},35:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.ToolCallManager=void 0,t.ToolCallManager=class{constructor(){this.handlers={},this.genericHandlers={},this.pendingCalls={}}registerHandler(e,t){const n=Math.random().toString(36).substring(2,15);return"*"===e?(this.genericHandlers[n]=t,()=>{delete this.genericHandlers[n]}):(this.handlers[e]=Object.assign(Object.assign({},this.handlers[e]),{[n]:t}),()=>{delete this.handlers[e][n]})}processToolCallStartedEvent(e){return n(this,void 0,void 0,function*(){const{tool_name:t,timestamp:n}=e,i=this.handlers[t]||{},r=Object.values(i),o=Object.values(this.genericHandlers),s={eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp},a=new Date(n);this.pendingCalls[e.tool_call_id]={payload:s,timestamp:a.getTime()};const l=[],c=yield Promise.allSettled(o.map(e=>e.onStart(s)));this.collectErrors(c,l);const u=yield Promise.allSettled(r.map(e=>e.onStart(s)));if(this.collectErrors(u,l),"client"===e.tool_type&&(yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:null,timestamp:(new Date).toISOString()}))),l.length>0){const t=l.map(e=>e.message).join("; ");yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${t}`,timestamp:(new Date).toISOString()}))}})}processToolCallCompletedEvent(e){return n(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:n,timestamp:i}=e,r=this.handlers[t]||{},o=Object.values(r),s=Object.values(this.genericHandlers),a=new Date(i),l=this.pendingCalls[n],c=a.getTime()-l.timestamp,u={eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:c,timestamp:e.timestamp},d=[],h=yield Promise.allSettled(s.map(e=>e.onComplete(u)));this.collectErrors(h,d);const E=yield Promise.allSettled(o.map(e=>e.onComplete(u)));if(this.collectErrors(E,d),delete this.pendingCalls[n],d.length>0){const t=d.map(e=>e.message).join("; ");yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onComplete handler: ${t}`,timestamp:(new Date).toISOString()}))}})}processToolCallFailedEvent(e){return n(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:n,timestamp:i}=e,r=this.handlers[t]||{},o=Object.values(r),s=Object.values(this.genericHandlers),a=new Date(i),l=this.pendingCalls[n],c=l?a.getTime()-l.timestamp:0,u={eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,error:new Error(e.error_message),executionTime:c,timestamp:e.timestamp};yield Promise.allSettled(s.map(e=>e.onFail(u))),yield Promise.allSettled(o.map(e=>e.onFail(u))),delete this.pendingCalls[n]})}collectErrors(e,t){for(const n of e)"rejected"===n.status&&t.push(n.reason instanceof Error?n.reason:new Error(String(n.reason)))}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallCompletedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}},60:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=void 0,function(e){e.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",e.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",e.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",e.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",e.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"}(n||(t.ConnectionClosedCode=n={}))},71:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientError=t.ErrorCode=void 0;const i=n(948);var r;!function(e){e.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",e.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",e.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",e.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",e.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",e.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",e.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",e.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",e.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"}(r||(t.ErrorCode=r={}));class o extends Error{constructor(e,t,n=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=n,this.details=r,Object.setPrototypeOf(this,o.prototype),(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:n})}}t.ClientError=o},170:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=t.MessageRole=t.AudioPermissionState=t.DataChannelMessage=t.SignalMessageAction=void 0;var i=n(295);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}});var r=n(513);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return r.DataChannelMessage}});var o=n(793);Object.defineProperty(t,"AudioPermissionState",{enumerable:!0,get:function(){return o.AudioPermissionState}});var s=n(822);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return s.MessageRole}});var a=n(878);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return a.AnamEvent}});var l=n(878);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return l.InternalEvent}});var c=n(878);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return c.ConnectionClosedCode}});var u=n(421);Object.defineProperty(t,"AgentAudioInputStream",{enumerable:!0,get:function(){return u.AgentAudioInputStream}})},251:(e,t)=>{t.read=function(e,t,n,i,r){var o,s,a=8*r-i-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?r-1:0,h=n?-1:1,E=e[t+d];for(d+=h,o=E&(1<<-u)-1,E>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=i;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-c;else{if(o===l)return s?NaN:1/0*(E?-1:1);s+=Math.pow(2,i),o-=c}return(E?-1:1)*s*Math.pow(2,o-i)},t.write=function(e,t,n,i,r,o){var s,a,l,c=8*o-r-1,u=(1<<c)-1,d=u>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,E=i?0:o-1,p=i?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*l-1)*Math.pow(2,r),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,r),s=0));r>=8;e[n+E]=255&a,E+=p,a/=256,r-=8);for(s=s<<r|a,c+=r;c>0;e[n+E]=255&s,E+=p,s/=256,c-=8);e[n+E-p]|=128*f}},259:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEventEmitter=void 0,t.InternalEventEmitter=class{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}},272:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateApiGatewayConfig=void 0,t.validateApiGatewayConfig=function(e){if(e&&e.enabled){if(!e.baseUrl)return"API Gateway baseUrl is required when enabled";try{const t=new URL(e.baseUrl);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return`Invalid API Gateway baseUrl protocol: ${t.protocol}. Must be http:, https:, ws:, or wss:`}catch(t){return`Invalid API Gateway baseUrl: ${e.baseUrl}`}return e.wsPath&&!e.wsPath.startsWith("/")?"API Gateway wsPath must start with /":void 0}}},273:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0,function(e){e.USER="user",e.PERSONA="persona"}(n||(t.MessageRole=n={}))},279:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SignallingClient=void 0;const r=n(170);t.SignallingClient=class{constructor(e,t,n,i,r){var o,s,a,l,c;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=n,this.internalEventEmitter=i,this.apiGatewayConfig=r,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:d,url:h}=t;if(this.heartbeatIntervalSeconds=u||5,this.maxWsReconnectionAttempts=d||5,!h.baseUrl)throw new Error("Signalling Client: baseUrl is required");if((null===(o=this.apiGatewayConfig)||void 0===o?void 0:o.enabled)&&(null===(s=this.apiGatewayConfig)||void 0===s?void 0:s.baseUrl)){const t=new URL(this.apiGatewayConfig.baseUrl),n=null!==(a=this.apiGatewayConfig.wsPath)&&void 0!==a?a:"/ws";t.protocol=t.protocol.replace("http","ws"),t.pathname=n,this.url=t;const i=h.protocol||"https",r="http"===i?"ws":"wss",o=`${i}://${h.baseUrl}`,s=null!==(l=h.signallingPath)&&void 0!==l?l:"/ws",c=new URL(o);c.protocol="ws"===r?"ws:":"wss:",h.port&&(c.port=h.port),c.pathname=s,c.searchParams.append("session_id",e),this.url.searchParams.append("target_url",c.href)}else{const t=`${h.protocol||"https"}://${h.baseUrl}`;this.url=new URL(t),this.url.protocol="http"===h.protocol?"ws:":"wss:",h.port&&(this.url.port=h.port),this.url.pathname=null!==(c=h.signallingPath)&&void 0!==c?c:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return i(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},n={actionType:r.SignalMessageAction.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(n)})}sendIceCandidate(e){return i(this,void 0,void 0,function*(){const t={actionType:r.SignalMessageAction.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if((null===(t=this.socket)||void 0===t?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(e){console.error("SignallingClient - sendSignalMessage: error sending message",e)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return i(this,void 0,void 0,function*(){const t={actionType:r.SignalMessageAction.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:r.SignalMessageAction.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:r.SignalMessageAction.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return i(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(r.InternalEvent.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return i(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,this.stopSignal||(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var n;(null===(n=this.socket)||void 0===n?void 0:n.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return i(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=1e3*this.heartbeatIntervalSeconds,t={actionType:r.SignalMessageAction.HEARTBEAT,sessionId:this.sessionId,payload:""},n=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var e;this.stopSignal||(null===(e=this.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN&&this.socket.send(n)},e)}}},287:(e,t,n)=>{"use strict";const i=n(526),r=n(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=function(e){return+e!=e&&(e=0),l.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let i=a(n);const r=i.write(e,t);return r!==n&&(i=i.slice(0,r)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(q(e,Uint8Array)){const t=new Uint8Array(e);return E(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(q(e,ArrayBuffer)||e&&q(e.buffer,ArrayBuffer))return E(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(q(e,SharedArrayBuffer)||e&&q(e.buffer,SharedArrayBuffer)))return E(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,n);const r=function(e){if(l.isBuffer(e)){const t=0|p(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),n=a(t);for(let i=0;i<t;i+=1)n[i]=255&e[i];return n}function E(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(i,l.prototype),i}function p(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(r)return i?-1:z(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return R(this,t,n);case"ascii":return b(this,t,n);case"latin1":case"binary":return w(this,t,n);case"base64":return y(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function C(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function m(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),J(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:v(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):v(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function v(e,t,n,i,r){let o,s=1,a=e.length,l=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,l/=2,n/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){let i=-1;for(o=n;o<a;o++)if(c(e,o)===c(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===l)return i*s}else-1!==i&&(o-=o-i),i=-1}else for(n+l>a&&(n=a-l),o=n;o>=0;o--){let n=!0;for(let i=0;i<l;i++)if(c(e,o+i)!==c(t,i)){n=!1;break}if(n)return o}return-1}function _(e,t,n,i){n=Number(n)||0;const r=e.length-n;i?(i=Number(i))>r&&(i=r):i=r;const o=t.length;let s;for(i>o/2&&(i=o/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(J(i))return s;e[n+s]=i}return s}function S(e,t,n,i){return Y(z(t,e.length-n),e,n,i)}function A(e,t,n,i){return Y(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function I(e,t,n,i){return Y(K(t),e,n,i)}function T(e,t,n,i){return Y(function(e,t){let n,i,r;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),i=n>>8,r=n%256,o.push(r),o.push(i);return o}(t,e.length-n),e,n,i)}function y(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function R(e,t,n){n=Math.min(e.length,n);const i=[];let r=t;for(;r<n;){const t=e[r];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(r+s<=n){let n,i,a,l;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[r+1],128==(192&n)&&(l=(31&t)<<6|63&n,l>127&&(o=l));break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(l=(15&t)<<12|(63&n)<<6|63&i,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:n=e[r+1],i=e[r+2],a=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&a)&&(l=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&a,l>65535&&l<1114112&&(o=l))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),r+=s}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=O));return n}(i)}t.kMaxLength=s,l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,n){return function(e,t,n){return u(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},l.allocUnsafe=function(e){return d(e)},l.allocUnsafeSlow=function(e){return d(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(q(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),q(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let r=0,o=Math.min(n,i);r<o;++r)if(e[r]!==t[r]){n=e[r],i=t[r];break}return n<i?-1:i<n?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const i=l.allocUnsafe(t);let r=0;for(n=0;n<e.length;++n){let t=e[n];if(q(t,Uint8Array))r+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,r)):Uint8Array.prototype.set.call(i,t,r);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,r)}r+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)C(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)C(this,t,t+3),C(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)C(this,t,t+7),C(this,t+1,t+6),C(this,t+2,t+5),C(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):g.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(e,t,n,i,r){if(q(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;let o=(r>>>=0)-(i>>>=0),s=(n>>>=0)-(t>>>=0);const a=Math.min(o,s),c=this.slice(i,r),u=e.slice(t,n);for(let e=0;e<a;++e)if(c[e]!==u[e]){o=c[e],s=u[e];break}return o<s?-1:s<o?1:0},l.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},l.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},l.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},l.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function b(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(127&e[r]);return i}function w(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(e[r]);return i}function N(e,t,n){const i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);let r="";for(let i=t;i<n;++i)r+=X[e[i]];return r}function M(e,t,n){const i=e.slice(t,n);let r="";for(let e=0;e<i.length-1;e+=2)r+=String.fromCharCode(i[e]+256*i[e+1]);return r}function D(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function L(e,t,n,i,r,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<o)throw new RangeError('"value" argument is out of bounds');if(n+i>e.length)throw new RangeError("Index out of range")}function P(e,t,n,i,r){$(t,i,r,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,i,r){$(t,i,r,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function k(e,t,n,i,r,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function B(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function j(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,8),r.write(e,t,n,i,52,8),n+8}l.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],r=1,o=0;for(;++o<t&&(r*=256);)i+=this[e+o]*r;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e+--t],r=1;for(;t>0&&(r*=256);)i+=this[e+--t]*r;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(r)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<<BigInt(32))+BigInt(r)}),l.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],r=1,o=0;for(;++o<t&&(r*=256);)i+=this[e+o]*r;return r*=128,i>=r&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=t,r=1,o=this[e+--i];for(;i>0&&(r*=256);)o+=this[e+--i]*r;return r*=128,o>=r&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||H(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),r.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let r=1,o=0;for(this[t]=255&e;++o<n&&(r*=256);)this[t+o]=e/r&255;return t+n},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let r=n-1,o=1;for(this[t+r]=255&e;--r>=0&&(o*=256);)this[t+r]=e/o&255;return t+n},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let r=0,o=1,s=0;for(this[t]=255&e;++r<n&&(o*=256);)e<0&&0===s&&0!==this[t+r-1]&&(s=1),this[t+r]=(e/o|0)-s&255;return t+n},l.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let r=n-1,o=1,s=0;for(this[t+r]=255&e;--r>=0&&(o*=256);)e<0&&0===s&&0!==this[t+r+1]&&(s=1),this[t+r]=(e/o|0)-s&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,n){return B(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return B(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);const r=i-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),t),r},l.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let r;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(r=t;r<n;++r)this[r]=e;else{const o=l.isBuffer(e)?e:l.from(e,i),s=o.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(r=0;r<n-t;++r)this[r+t]=o[r%s]}return this};const V={};function G(e,t,n){V[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const i="-"===e[0]?1:0;for(;n>=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,i,r,o){if(e>n||e<t){const i="bigint"==typeof t?"n":"";let r;throw r=o>3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(o+1)}${i}`:`>= -(2${i} ** ${8*(o+1)-1}${i}) and < 2 ** ${8*(o+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new V.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){x(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||H(t,e.length-(n+1))}(i,r,o)}function x(e,t){if("number"!=typeof e)throw new V.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,n){if(Math.floor(e)!==e)throw x(e,n),new V.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new V.ERR_BUFFER_OUT_OF_BOUNDS;throw new V.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}G("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),G("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),G("ERR_OUT_OF_RANGE",function(e,t,n){let i=`The value of "${e}" is out of range.`,r=n;return Number.isInteger(n)&&Math.abs(n)>2**32?r=F(String(n)):"bigint"==typeof n&&(r=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(r=F(r)),r+="n"),i+=` It must be ${t}. Received ${r}`,i},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const i=e.length;let r=null;const o=[];for(let s=0;s<i;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function K(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,n,i){let r;for(r=0;r<i&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let r=0;r<16;++r)t[i+r]=e[n]+e[r]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},295:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0;var i=n(656);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}})},322:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStreamState=void 0,function(e){e[e.UNSTARTED=0]="UNSTARTED",e[e.STREAMING=1]="STREAMING",e[e.INTERRUPTED=2]="INTERRUPTED",e[e.ENDED=3]="ENDED"}(n||(t.TalkMessageStreamState=n={}))},353:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateCorrelationId=void 0,t.generateCorrelationId=function(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}},421:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=void 0,t.AgentAudioInputStream=class{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const t={audioData:"string"==typeof e?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(t)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array.from(t,e=>String.fromCharCode(e)).join("");return btoa(n)}}},440:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorCode=t.ClientError=t.unsafe_createClientWithApiKey=t.createClient=void 0;const s=o(n(816)),a=n(71);Object.defineProperty(t,"ClientError",{enumerable:!0,get:function(){return a.ClientError}}),Object.defineProperty(t,"ErrorCode",{enumerable:!0,get:function(){return a.ErrorCode}}),t.createClient=(e,t)=>new s.default(e,void 0,t),t.unsafe_createClientWithApiKey=(e,t,n)=>new s.default(void 0,t,Object.assign(Object.assign({},n),{apiKey:e})),r(n(170),t)},462:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHistoryClient=void 0;const i=n(170);t.MessageHistoryClient=class{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},n=this.messages.findIndex(e=>e.id===t.id);if(-1!==n){const e=this.messages[n];this.messages[n]=Object.assign(Object.assign({},e),{content:e.content+t.content,interrupted:e.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case i.MessageRole.USER:this.processUserMessage(t);break;case i.MessageRole.PERSONA:this.processPersonaMessage(t)}t.endOfSpeech&&this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_HISTORY_UPDATED,this.messages)}}},471:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=void 0;const i=n(170);t.ReasoningHistoryClient=class{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(i.AnamEvent.REASONING_STREAM_EVENT_RECEIVED,t);const n={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(e=>e.id===n.id);if(-1!==r){const e=this.reasoning_messages[r];e.content+=n.content,this.reasoning_messages[r]=e}else this.reasoning_messages.push(n);t.endOfThought&&this.publicEventEmitter.emit(i.AnamEvent.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}},513:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebRtcReasoningTextMessageEvent=t.DataChannelMessage=void 0;var i=n(676);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return i.DataChannelMessage}});var r=n(540);Object.defineProperty(t,"WebRtcReasoningTextMessageEvent",{enumerable:!0,get:function(){return r.WebRtcReasoningTextMessageEvent}})},526:(e,t)=>{"use strict";t.byteLength=function(e){var t=a(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,o=a(e),s=o[0],l=o[1],c=new r(function(e,t,n){return 3*(t+n)/4-n}(0,s,l)),u=0,d=l>0?s-4:s;for(n=0;n<d;n+=4)t=i[e.charCodeAt(n)]<<18|i[e.charCodeAt(n+1)]<<12|i[e.charCodeAt(n+2)]<<6|i[e.charCodeAt(n+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=255&t;return 2===l&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[u++]=255&t),1===l&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t),c},t.fromByteArray=function(e){for(var t,i=e.length,r=i%3,o=[],s=16383,a=0,l=i-r;a<l;a+=s)o.push(c(e,a,a+s>l?l:a+s));return 1===r?(t=e[i-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=o[s],i[o.charCodeAt(s)]=s;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function c(e,t,n){for(var i,r=[],o=t;o<n;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),r.push(l(i));return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},529:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.EngineApiRestClient=void 0,t.EngineApiRestClient=class{constructor(e,t,n){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=n}sendTalkCommand(e){return n(this,void 0,void 0,function*(){var t,n;try{let i,r={"Content-Type":"application/json"};const o="/talk",s=`?session_id=${this.sessionId}`;if((null===(t=this.apiGatewayConfig)||void 0===t?void 0:t.enabled)&&(null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.baseUrl)){i=`${this.apiGatewayConfig.baseUrl}${o}${s}`;const e=new URL(`${this.baseUrl}${o}${s}`);r["X-Anam-Target-Url"]=e.href}else i=`${this.baseUrl}${o}${s}`;const a=yield fetch(i,{method:"POST",headers:r,body:JSON.stringify({content:e})});if(!a.ok)throw new Error(`Failed to send talk command: ${a.status} ${a.statusText}`)}catch(e){throw console.error(e),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}},540:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},577:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.StreamingClient=void 0;const r=n(948),o=n(958),s=n(170),a=n(421),l=n(711);t.StreamingClient=class{constructor(e,t,n,i,r){var a,l,c,u;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:s.AudioPermissionState.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=n,this.internalEventEmitter=i,this.toolCallManager=r,this.apiGatewayConfig=t.apiGateway;const{inputAudio:d}=t;this.inputAudioState=d.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=!0===t.inputAudio.disableInputAudio,this.internalEventEmitter.addListener(s.InternalEvent.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(s.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(s.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(s.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new o.SignallingClient(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new o.EngineApiRestClient(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=null!==(l=null===(a=t.metrics)||void 0===a?void 0:a.showPeerConnectionStatsReport)&&void 0!==l&&l,this.peerConnectionStatsReportOutputFormat=null!==(u=null===(c=t.metrics)||void 0===c?void 0:c.peerConnectionStatsReportOutputFormat)&&void 0!==u?u:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>i(this,void 0,void 0,function*(){if(this.peerConnection&&this.dataChannel&&"open"===this.dataChannel.readyState)try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),5e3))}sendClientSideMetrics(e){e.forEach(e=>{if("inbound-rtp"===e.type){const t={message_type:"remote_rtp_stats",data:e};this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(JSON.stringify(t))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},15e3);this.successMetricPoller=setInterval(()=>i(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired)return this.successMetricPoller&&clearInterval(this.successMetricPoller),void clearTimeout(e);try{const t=yield this.peerConnection.getStats();let n=!1,i=null;t.forEach(e=>{"inbound-rtp"===e.type&&"video"===e.kind&&(void 0!==e.framesDecoded&&e.framesDecoded>0?(n=!0,i="framesDecoded"):void 0!==e.framesReceived&&e.framesReceived>0?(n=!0,i="framesReceived"):e.bytesReceived>0&&e.packetsReceived>0&&e.bytesReceived>1e5&&(n=!0,i="bytesReceived"))}),n&&!this.successMetricFired&&(this.successMetricFired=!0,(0,r.sendClientMetric)(r.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",i?{detectionMethod:i}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch(e){}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(null==e)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(e=>{e.stop()});const n={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:n}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(s.AnamEvent.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(e){throw console.error("Failed to change audio input device:",e),new Error(`StreamingClient - changeAudioInputDevice: ${e instanceof Error?e.message:String(e)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection)return void console.error("StreamingClient - startConnection: peer connection already exists");this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return i(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new l.TalkMessageStream(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new a.AgentAudioInputStream(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return i(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:2}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return i(this,void 0,void 0,function*(){if(this.peerConnection)switch(e.actionType){case s.SignalMessageAction.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case s.SignalMessageAction.ICE_CANDIDATE:const n=e.payload,i=new RTCIceCandidate(n);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(i):this.remoteIceCandidateBuffer.push(i);break;case s.SignalMessageAction.END_SESSION:const r=e.payload;this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.SERVER_CLOSED_CONNECTION,r),this.shutdown();break;case s.SignalMessageAction.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(s.AnamEvent.SERVER_WARNING,o);break;case s.SignalMessageAction.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(s.AnamEvent.TALK_STREAM_INTERRUPTED,a.correlationId);break;case s.SignalMessageAction.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(s.AnamEvent.SESSION_READY,l);break;case s.SignalMessageAction.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}else console.error("StreamingClient - onSignalMessage: peerConnection is not initialized")})}onSignallingClientConnected(){return i(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;"connected"!==(null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState)&&"completed"!==(null===(t=this.peerConnection)||void 0===t?void 0:t.iceConnectionState)||(this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;"closed"===(null===(e=this.peerConnection)||void 0===e?void 0:e.connectionState)&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),"NotAllowedError"===e.name&&"Permission denied"===e.message?this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(e){if("video"===e.track.kind){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(s.AnamEvent.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const e=this.videoElement.requestVideoFrameCallback(()=>{var t;null===(t=this.videoElement)||void 0===t||t.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(s.AnamEvent.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,(0,r.sendClientMetric)(r.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else"audio"===e.track.kind&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(s.AnamEvent.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return i(this,void 0,void 0,function*(){if(!this.peerConnection)return void console.error("StreamingClient - setupDataChannels: peer connection is not initialized");if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=null!=e?e:null},e.onclose=()=>{},e.onmessage=e=>{try{const t=JSON.parse(e.data);switch(t.messageType){case s.DataChannelMessage.SPEECH_TEXT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,t.data);break;case s.DataChannelMessage.TOOL_CALL_STARTED_EVENT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,t.data);break;case s.DataChannelMessage.TOOL_CALL_COMPLETED_EVENT:const e=t.data;"client"===e.tool_type&&(this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,{event_uid:e.event_uid,session_id:e.session_id,event_name:e.tool_name,event_data:e.arguments,timestamp:e.timestamp,timestamp_user_action:e.timestamp_user_action,user_action_correlation_id:e.user_action_correlation_id,used_outside_engine:e.used_outside_engine}),this.publicEventEmitter.emit(s.AnamEvent.CLIENT_TOOL_EVENT_RECEIVED,o.ToolCallManager.WebRTCToolCallCompletedEventToClientToolEvent(e))),this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,t.data);break;case s.DataChannelMessage.TOOL_CALL_FAILED_EVENT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,t.data);break;case s.DataChannelMessage.REASONING_TEXT:this.internalEventEmitter.emit(s.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,t.data)}}catch(e){console.error("Failed to parse data channel message:",e)}}})}requestMicrophonePermissionAsync(){return i(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==s.AudioPermissionState.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:s.AudioPermissionState.PENDING}),this.publicEventEmitter.emit(s.AnamEvent.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:s.AudioPermissionState.GRANTED}),this.publicEventEmitter.emit(s.AnamEvent.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:s.AudioPermissionState.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(s.AnamEvent.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return i(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length)return void console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],t=this.peerConnection.getSenders().find(e=>{var t;return"audio"===(null===(t=e.track)||void 0===t?void 0:t.kind)||null===e.track&&null!==e.dtmf});if(t)try{yield t.replaceTrack(e)}catch(t){console.error("Failed to replace audio track:",t),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(s.AnamEvent.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return i(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),this.peerConnection){try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)}else console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized")})}shutdown(){return i(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield null===(e=this.peerConnection)||void 0===e?void 0:e.getStats();if(t){const e=(0,r.createRTCStatsReport)(t,this.peerConnectionStatsReportOutputFormat);e&&console.log(e,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(e=>{e.stop()}),this.inputAudioStream=null}catch(e){console.error("StreamingClient - shutdown: error stopping input audio stream",e)}try{this.signallingClient.stop()}catch(e){console.error("StreamingClient - shutdown: error stopping signallilng",e)}try{this.peerConnection&&"closed"!==this.peerConnection.connectionState&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(e){console.error("StreamingClient - shutdown: error closing peer connection",e)}})}}},645:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEvent=void 0,function(e){e.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",e.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",e.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",e.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",e.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"}(n||(t.InternalEvent=n={}))},656:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0,function(e){e.OFFER="offer",e.ANSWER="answer",e.ICE_CANDIDATE="icecandidate",e.END_SESSION="endsession",e.HEARTBEAT="heartbeat",e.WARNING="warning",e.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",e.TALK_STREAM_INPUT="talkstream",e.SESSION_READY="sessionready",e.AGENT_AUDIO_INPUT="agentaudioinput",e.AGENT_AUDIO_INPUT_END="agentaudioinputend"}(n||(t.SignalMessageAction=n={}))},672:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isCustomPersonaConfig=void 0,t.isCustomPersonaConfig=function(e){return"brainType"in e||"llmId"in e}},676:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DataChannelMessage=void 0,function(e){e.SPEECH_TEXT="speechText",e.CLIENT_TOOL_EVENT="clientToolEvent",e.TOOL_CALL_STARTED_EVENT="toolCallStarted",e.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",e.TOOL_CALL_FAILED_EVENT="toolCallFailed",e.REASONING_TEXT="reasoningText"}(n||(t.DataChannelMessage=n={}))},711:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStream=void 0;const r=n(170),o=n(322);t.TalkMessageStream=class{constructor(e,t,n){this.state=o.TalkMessageStreamState.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=n,this.internalEventEmitter.addListener(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return i(this,void 0,void 0,function*(){e.actionType===r.SignalMessageAction.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=o.TalkMessageStreamState.INTERRUPTED,this.onDeactivate())})}endMessage(){return i(this,void 0,void 0,function*(){if(this.state===o.TalkMessageStreamState.ENDED)return void console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");if(this.state!==o.TalkMessageStreamState.STREAMING)return void console.warn("Talk stream is not active state: "+this.state);const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=o.TalkMessageStreamState.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return i(this,void 0,void 0,function*(){if(this.state!==o.TalkMessageStreamState.STREAMING&&this.state!==o.TalkMessageStreamState.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===o.TalkMessageStreamState.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?o.TalkMessageStreamState.ENDED:o.TalkMessageStreamState.STREAMING,this.state===o.TalkMessageStreamState.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===o.TalkMessageStreamState.STREAMING||this.state===o.TalkMessageStreamState.UNSTARTED}getState(){return this.state}}},793:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AudioPermissionState=void 0,function(e){e.PENDING="pending",e.GRANTED="granted",e.DENIED="denied",e.NOT_REQUESTED="not_requested"}(n||(t.AudioPermissionState=n={}))},816:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0});const r=n(287),o=n(71),s=n(948),a=n(353),l=n(272),c=n(958),u=n(170);t.default=class{constructor(e,t,n){var i,r,a,l,d;this.inputAudioState={isMuted:!1,permissionState:u.AudioPermissionState.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const h=this.validateClientConfig(e,t,n);if(h)throw new o.ClientError(h,o.ErrorCode.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=n,((null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.baseUrl)||(null===(r=null==n?void 0:n.api)||void 0===r?void 0:r.apiVersion))&&(0,s.setClientMetricsBaseUrl)(n.api.baseUrl||s.DEFAULT_ANAM_METRICS_BASE_URL,n.api.apiVersion||s.DEFAULT_ANAM_API_VERSION),(null===(l=null===(a=null==n?void 0:n.api)||void 0===a?void 0:a.apiGateway)||void 0===l?void 0:l.enabled)&&(0,s.setClientMetricsApiGateway)(n.api.apiGateway),(null===(d=null==n?void 0:n.metrics)||void 0===d?void 0:d.disableClientMetrics)&&(0,s.setClientMetricsDisabled)(!0),this.publicEventEmitter=new c.PublicEventEmitter,this.internalEventEmitter=new c.InternalEventEmitter,this.toolCallManager=new c.ToolCallManager,this.apiClient=new c.CoreApiRestClient(e,null==n?void 0:n.apiKey,null==n?void 0:n.api),this.messageHistoryClient=new c.MessageHistoryClient(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new c.ReasoningHistoryClient(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],n=r.Buffer.from(t,"base64").toString("utf8");return JSON.parse(n)}catch(e){throw new Error("Invalid session token format")}}validateClientConfig(e,t,n){var i,r;if(!e&&!(null==n?void 0:n.apiKey))return"Either sessionToken or apiKey must be provided";if((null==n?void 0:n.apiKey)&&e)return"Only one of sessionToken or apiKey should be used";const o=(0,l.validateApiGatewayConfig)(null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.apiGateway);if(o)return o;if(e){const n=this.decodeJwt(e);this.organizationId=n.accountId,(0,s.setMetricsContext)({organizationId:this.organizationId});const i=null===(r=n.type)||void 0===r?void 0:r.toLowerCase();if("legacy"===i)return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if(("ephemeral"===i||"stateful"===i)&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(null==n?void 0:n.voiceDetection){if(n.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(void 0!==n.voiceDetection.endOfSpeechSensitivity){if("number"!=typeof n.voiceDetection.endOfSpeechSensitivity)return"End of speech sensitivity must be a number";if(n.voiceDetection.endOfSpeechSensitivity<0||n.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if((null===(e=this.clientOptions)||void 0===e?void 0:e.voiceDetection)&&(t.voiceDetection=this.clientOptions.voiceDetection),0!==Object.keys(t).length)return t}startSession(e){return i(this,void 0,void 0,function*(){var t,n,i,r,a,l,u,d,h,E,p,f;const g=this.personaConfig,C=this.buildStartSessionOptionsForClient(),m=yield this.apiClient.startSession(g,C),{sessionId:v,clientConfig:_,engineHost:S,engineProtocol:A,signallingEndpoint:I}=m,{heartbeatIntervalSeconds:T,maxWsReconnectionAttempts:y,iceServers:R}=_;this.sessionId=v,(0,s.setMetricsContext)({sessionId:this.sessionId});const O=(null===(t=this.clientOptions)||void 0===t?void 0:t.iceServers)?this.clientOptions.iceServers:R;try{this.streamingClient=new c.StreamingClient(v,{engine:{baseUrl:`${A}://${S}`},signalling:{heartbeatIntervalSeconds:T,maxWsReconnectionAttempts:y,url:{baseUrl:S,protocol:A,signallingPath:I}},iceServers:O,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:(null===(n=this.clientOptions)||void 0===n?void 0:n.disableInputAudio)?void 0:e,audioDeviceId:null===(i=this.clientOptions)||void 0===i?void 0:i.audioDeviceId,disableInputAudio:null===(r=this.clientOptions)||void 0===r?void 0:r.disableInputAudio},apiGateway:null===(l=null===(a=this.clientOptions)||void 0===a?void 0:a.api)||void 0===l?void 0:l.apiGateway,metrics:{showPeerConnectionStatsReport:null!==(h=null===(d=null===(u=this.clientOptions)||void 0===u?void 0:u.metrics)||void 0===d?void 0:d.showPeerConnectionStatsReport)&&void 0!==h&&h,peerConnectionStatsReportOutputFormat:null!==(f=null===(p=null===(E=this.clientOptions)||void 0===E?void 0:E.metrics)||void 0===p?void 0:p.peerConnectionStatsReportOutputFormat)&&void 0!==f?f:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(e){throw(0,s.setMetricsContext)({sessionId:null}),new o.ClientError("Failed to initialize streaming client",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:v})}return v})}startSessionIfNeeded(e){return i(this,void 0,void 0,function*(){if(!(this.sessionId&&this.streamingClient||(yield this.startSession(e),this.sessionId&&this.streamingClient)))throw new o.ClientError("Session ID or streaming client is not available after starting session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return i(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const n=(0,a.generateCorrelationId)();return(0,s.setMetricsContext)({attemptCorrelationId:n,sessionId:null}),(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(e=>{var t;const n=[];let i=!1,r=!1;this.publicEventEmitter.addListener(u.AnamEvent.VIDEO_STREAM_STARTED,t=>{n.push(t),i=!0,r&&e(n)}),this.publicEventEmitter.addListener(u.AnamEvent.AUDIO_STREAM_STARTED,t=>{n.push(t),r=!0,i&&e(n)}),null===(t=this.streamingClient)||void 0===t||t.startConnection()})})}streamToVideoAndAudioElements(e,t,n){return i(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,n)})}streamToVideoElement(e,t){return i(this,void 0,void 0,function*(){var n;const i=(0,a.generateCorrelationId)();(0,s.setMetricsContext)({attemptCorrelationId:i,sessionId:null}),(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),(null===(n=this.clientOptions)||void 0===n?void 0:n.disableInputAudio)&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(e){if(e instanceof o.ClientError)throw e;throw new o.ClientError("Failed to start session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return i(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(!this.streamingClient)throw new Error("Failed to send message: session is not started.");this.streamingClient.sendDataMessage(e)}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const n=(new Date).toISOString().replace("Z",""),i=JSON.stringify({content:e,timestamp:n,session_id:t,message_type:"speech"});this.sendDataMessage(i)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:(new Date).toISOString()});this.sendDataMessage(t)}stopStreaming(){return i(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(u.AnamEvent.CONNECTION_CLOSED,u.ConnectionClosedCode.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,(0,s.setMetricsContext)({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return i(this,void 0,void 0,function*(){var t;if(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&""===e.trim())throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){this.toolCallManager.registerHandler(e,t)}}},822:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0;var i=n(273);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return i.MessageRole}})},878:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=void 0;var i=n(21);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return i.AnamEvent}});var r=n(645);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return r.InternalEvent}});var o=n(60);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return o.ConnectionClosedCode}})},948:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.createRTCStatsReport=t.sendClientMetric=t.setMetricsContext=t.setClientMetricsDisabled=t.setClientMetricsApiGateway=t.setClientMetricsBaseUrl=t.ClientMetricMeasurement=t.DEFAULT_ANAM_API_VERSION=t.DEFAULT_ANAM_METRICS_BASE_URL=void 0;const r=n(985);var o;t.DEFAULT_ANAM_METRICS_BASE_URL="https://api.anam.ai",t.DEFAULT_ANAM_API_VERSION="/v1",function(e){e.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",e.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",e.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"}(o||(t.ClientMetricMeasurement=o={}));let s,a=t.DEFAULT_ANAM_METRICS_BASE_URL,l=t.DEFAULT_ANAM_API_VERSION,c=!1;t.setClientMetricsBaseUrl=(e,n=t.DEFAULT_ANAM_API_VERSION)=>{a=e,l=n},t.setClientMetricsApiGateway=e=>{s=e},t.setClientMetricsDisabled=e=>{c=e};let u={sessionId:null,organizationId:null,attemptCorrelationId:null};t.setMetricsContext=e=>{u=Object.assign(Object.assign({},u),e)},t.sendClientMetric=(e,t,n)=>i(void 0,void 0,void 0,function*(){if(!c)try{const i=Object.assign(Object.assign({},r.CLIENT_METADATA),n);u.sessionId&&(i.sessionId=u.sessionId),u.organizationId&&(i.organizationId=u.organizationId),u.attemptCorrelationId&&(i.attemptCorrelationId=u.attemptCorrelationId);const o=`${l}/metrics/client`;let c,d={"Content-Type":"application/json"};(null==s?void 0:s.enabled)&&(null==s?void 0:s.baseUrl)?(c=`${s.baseUrl}${o}`,d["X-Anam-Target-Url"]=`${a}${o}`):c=`${a}${o}`,yield fetch(c,{method:"POST",headers:d,body:JSON.stringify({name:e,value:t,tags:i})})}catch(e){console.error("Failed to send error metric:",e)}}),t.createRTCStatsReport=(e,t="console")=>{var n,i,r;const o={};e.forEach(e=>{o[e.type]||(o[e.type]=[]),o[e.type].push(e)});const s={issues:[]},a=(null===(n=o["inbound-rtp"])||void 0===n?void 0:n.filter(e=>"video"===e.kind))||[];a.length>0&&(s.personaVideoStream=[],a.forEach(e=>{var t,n,i,r,o;const a={framesReceived:null!==(t=e.framesReceived)&&void 0!==t?t:"unknown",framesDropped:null!==(n=e.framesDropped)&&void 0!==n?n:"unknown",framesPerSecond:null!==(i=e.framesPerSecond)&&void 0!==i?i:"unknown",packetsReceived:null!==(r=e.packetsReceived)&&void 0!==r?r:"unknown",packetsLost:null!==(o=e.packetsLost)&&void 0!==o?o:"unknown",resolution:e.frameWidth&&e.frameHeight?`${e.frameWidth}x${e.frameHeight}`:void 0,jitter:void 0!==e.jitter?e.jitter:void 0};s.personaVideoStream.push(a)}));const l=(null===(i=o["inbound-rtp"])||void 0===i?void 0:i.filter(e=>"audio"===e.kind))||[];l.length>0&&(s.personaAudioStream=[],l.forEach(e=>{var t,n,i;const r={packetsReceived:null!==(t=e.packetsReceived)&&void 0!==t?t:"unknown",packetsLost:null!==(n=e.packetsLost)&&void 0!==n?n:"unknown",audioLevel:null!==(i=e.audioLevel)&&void 0!==i?i:"unknown",jitter:void 0!==e.jitter?e.jitter:void 0,totalAudioEnergy:void 0!==e.totalAudioEnergy?e.totalAudioEnergy:void 0};s.personaAudioStream.push(r)}));const c=(null===(r=o["outbound-rtp"])||void 0===r?void 0:r.filter(e=>"audio"===e.kind))||[];c.length>0&&(s.userAudioInput=[],c.forEach(e=>{var t,n;const i={packetsSent:null!==(t=e.packetsSent)&&void 0!==t?t:"unknown",retransmittedPackets:null!==(n=e.retransmittedPacketsSent)&&void 0!==n?n:void 0,avgPacketSendDelay:void 0!==e.totalPacketSendDelay?e.totalPacketSendDelay/(e.packetsSent||1)*1e3:void 0};s.userAudioInput.push(i)})),o.codec&&(s.codecs=[],o.codec.forEach(e=>{const t={status:e.payloadType?"Active":"Available",mimeType:e.mimeType||"Unknown",payloadType:e.payloadType||"N/A",clockRate:e.clockRate||void 0,channels:e.channels||void 0};s.codecs.push(t)})),o.transport&&(s.transportLayer=[],o.transport.forEach(e=>{const t={dtlsState:e.dtlsState||"unknown",iceState:e.iceState||"unknown",bytesSent:e.bytesSent||void 0,bytesReceived:e.bytesReceived||void 0};s.transportLayer.push(t)}));const u=[];if(a.forEach(e=>{"number"==typeof e.framesDropped&&e.framesDropped>0&&u.push(`Video: ${e.framesDropped} frames dropped`),"number"==typeof e.packetsLost&&e.packetsLost>0&&u.push(`Video: ${e.packetsLost} packets lost`),"number"==typeof e.framesPerSecond&&e.framesPerSecond<23&&u.push(`Video: Low frame rate (${e.framesPerSecond} fps)`)}),l.forEach(e=>{"number"==typeof e.packetsLost&&e.packetsLost>0&&u.push(`Audio: ${e.packetsLost} packets lost`),"number"==typeof e.jitter&&e.jitter>.1&&u.push(`Audio: High jitter (${(1e3*e.jitter).toFixed(1)}ms)`)}),s.issues=u,"json"===t)return s;console.group("📊 WebRTC Session Statistics Report"),s.personaVideoStream&&s.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),s.personaVideoStream.forEach(e=>{console.log(`Frames Received: ${e.framesReceived}`),console.log(`Frames Dropped: ${e.framesDropped}`),console.log(`Frames Per Second: ${e.framesPerSecond}`),console.log(`Packets Received: ${"number"==typeof e.packetsReceived?e.packetsReceived.toLocaleString():e.packetsReceived}`),console.log(`Packets Lost: ${e.packetsLost}`),e.resolution&&console.log(`Resolution: ${e.resolution}`),void 0!==e.jitter&&console.log(`Jitter: ${e.jitter.toFixed(5)}ms`)}),console.groupEnd()),s.personaAudioStream&&s.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),s.personaAudioStream.forEach(e=>{console.log(`Packets Received: ${"number"==typeof e.packetsReceived?e.packetsReceived.toLocaleString():e.packetsReceived}`),console.log(`Packets Lost: ${e.packetsLost}`),console.log(`Audio Level: ${e.audioLevel}`),void 0!==e.jitter&&console.log(`Jitter: ${e.jitter.toFixed(5)}ms`),void 0!==e.totalAudioEnergy&&console.log(`Total Audio Energy: ${e.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),s.userAudioInput&&s.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),s.userAudioInput.forEach(e=>{console.log(`Packets Sent: ${"number"==typeof e.packetsSent?e.packetsSent.toLocaleString():e.packetsSent}`),e.retransmittedPackets&&console.log(`Retransmitted Packets: ${e.retransmittedPackets}`),void 0!==e.avgPacketSendDelay&&console.log(`Avg Packet Send Delay: ${e.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),s.codecs&&s.codecs.length>0&&(console.group("🔧 Codecs Used"),s.codecs.forEach(e=>{console.log(`${e.status} ${e.mimeType} - Payload Type: ${e.payloadType}`),e.clockRate&&console.log(` Clock Rate: ${e.clockRate}Hz`),e.channels&&console.log(` Channels: ${e.channels}`)}),console.groupEnd()),s.transportLayer&&s.transportLayer.length>0&&(console.group("🚚 Transport Layer"),s.transportLayer.forEach(e=>{console.log(`DTLS State: ${e.dtlsState}`),console.log(`ICE State: ${e.iceState}`),(e.bytesReceived||e.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(e.bytesSent||0).toLocaleString()}, Received: ${(e.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),s.issues.length>0?(console.group("⚠️ Potential Issues Detected"),s.issues.forEach(e=>console.warn(e)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()}},958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=t.ToolCallManager=t.StreamingClient=t.PublicEventEmitter=t.MessageHistoryClient=t.InternalEventEmitter=t.EngineApiRestClient=t.CoreApiRestClient=t.SignallingClient=void 0;var i=n(279);Object.defineProperty(t,"SignallingClient",{enumerable:!0,get:function(){return i.SignallingClient}});var r=n(18);Object.defineProperty(t,"CoreApiRestClient",{enumerable:!0,get:function(){return r.CoreApiRestClient}});var o=n(529);Object.defineProperty(t,"EngineApiRestClient",{enumerable:!0,get:function(){return o.EngineApiRestClient}});var s=n(259);Object.defineProperty(t,"InternalEventEmitter",{enumerable:!0,get:function(){return s.InternalEventEmitter}});var a=n(462);Object.defineProperty(t,"MessageHistoryClient",{enumerable:!0,get:function(){return a.MessageHistoryClient}});var l=n(995);Object.defineProperty(t,"PublicEventEmitter",{enumerable:!0,get:function(){return l.PublicEventEmitter}});var c=n(577);Object.defineProperty(t,"StreamingClient",{enumerable:!0,get:function(){return c.StreamingClient}});var u=n(35);Object.defineProperty(t,"ToolCallManager",{enumerable:!0,get:function(){return u.ToolCallManager}});var d=n(471);Object.defineProperty(t,"ReasoningHistoryClient",{enumerable:!0,get:function(){return d.ReasoningHistoryClient}})},985:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLIENT_METADATA=t.DEFAULT_API_VERSION=t.DEFAULT_API_BASE_URL=t.DEFAULT_HEADERS=void 0,t.DEFAULT_HEADERS={"Content-Type":"application/json"},t.DEFAULT_API_BASE_URL="https://api.anam.ai",t.DEFAULT_API_VERSION="/v1",t.CLIENT_METADATA={client:"js-sdk",version:"0.0.0-automated"}},995:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PublicEventEmitter=void 0;const i=n(948),r=n(170);t.PublicEventEmitter=class{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===r.AnamEvent.CONNECTION_ESTABLISHED&&(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===r.AnamEvent.CONNECTION_CLOSED){const[e,n]=t;(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,e,n?{details:n}:void 0)}this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}}},t={},function n(i){var r=t[i];if(void 0!==r)return r.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(440);var e,t});
|