@coze/realtime-api 1.0.4-beta.2 → 1.0.5-alpha.126a93

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.
@@ -1,10 +1,17 @@
1
1
  /*! For license information please see index.cjs.LICENSE.txt */
2
2
  "use strict";
3
3
  var __webpack_modules__ = {
4
+ "../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js": function(module) {
5
+ module.exports = function() {
6
+ throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object");
7
+ };
8
+ },
4
9
  "?666e": function() {
5
10
  /* (ignored) */ },
6
11
  "?79fd": function() {
7
12
  /* (ignored) */ },
13
+ "?8dee": function() {
14
+ /* (ignored) */ },
8
15
  "?9050": function() {
9
16
  /* (ignored) */ }
10
17
  };
@@ -241,8 +248,6 @@ class error_APIError extends CozeError {
241
248
  if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
242
249
  const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
243
250
  if (logId) list.push(`logid: ${logId}`);
244
- const help_doc = null == error ? void 0 : error.help_doc;
245
- if (help_doc) list.push(`help doc: ${help_doc}`);
246
251
  return list.join(', ');
247
252
  }
248
253
  if (status) return `http status code: ${status} (no body)`;
@@ -265,21 +270,20 @@ class error_APIError extends CozeError {
265
270
  return new error_APIError(status, error, message, headers);
266
271
  }
267
272
  constructor(status, error, message, headers){
268
- var _error_error, _error_error1;
273
+ var _error_detail, _error_error;
269
274
  super(`${error_APIError.makeMessage(status, error, message, headers)}`);
270
275
  this.status = status;
271
276
  this.headers = headers;
272
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
277
+ this.logid = (null == error ? void 0 : null === (_error_detail = error.detail) || void 0 === _error_detail ? void 0 : _error_detail.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
273
278
  // this.error = error;
274
279
  this.code = null == error ? void 0 : error.code;
275
280
  this.msg = null == error ? void 0 : error.msg;
276
281
  this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
277
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
278
282
  this.rawError = error;
279
283
  }
280
284
  }
281
285
  class APIConnectionError extends error_APIError {
282
- constructor({ message, cause }){
286
+ constructor({ message }){
283
287
  super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
284
288
  // if (cause) {
285
289
  // this.cause = cause;
@@ -3514,6 +3518,17 @@ class Runs extends APIResource {
3514
3518
  const response = await this._client.post(apiUrl, params, false, options);
3515
3519
  return response;
3516
3520
  }
3521
+ /**
3522
+ * Get the workflow run history | 工作流异步运行后,查看执行结果
3523
+ * @docs zh: https://www.coze.cn/open/docs/developer_guides/workflow_history
3524
+ * @param workflowId - Required The ID of the workflow. | 必选 工作流 ID。
3525
+ * @param executeId - Required The ID of the workflow execution. | 必选 工作流执行 ID。
3526
+ * @returns WorkflowExecuteHistory[] | 工作流执行历史
3527
+ */ async history(workflowId, executeId, options) {
3528
+ const apiUrl = `/v1/workflows/${workflowId}/run_histories/${executeId}`;
3529
+ const response = await this._client.get(apiUrl, void 0, false, options);
3530
+ return response.data;
3531
+ }
3517
3532
  }
3518
3533
  class WorkflowEvent {
3519
3534
  constructor(id, event, data){
@@ -3675,7 +3690,7 @@ class documents_Documents extends APIResource {
3675
3690
  * @returns ListDocumentData | 知识库文件列表
3676
3691
  */ async list(params, options) {
3677
3692
  const apiUrl = '/open_api/knowledge/document/list';
3678
- const response = await this._client.get(apiUrl, params, false, mergeConfig(options, {
3693
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3679
3694
  headers: documents_documents_headers
3680
3695
  }));
3681
3696
  return response;
@@ -3926,10 +3941,705 @@ class Templates extends APIResource {
3926
3941
  return response.data;
3927
3942
  }
3928
3943
  }
3944
+ class chat_Chat extends APIResource {
3945
+ async create(botId, options) {
3946
+ const apiUrl = `/v1/chat?bot_id=${botId}`;
3947
+ return await this._client.makeWebsocket(apiUrl, options);
3948
+ }
3949
+ }
3950
+ class transcriptions_Transcriptions extends APIResource {
3951
+ async create(options) {
3952
+ const apiUrl = '/v1/audio/transcriptions';
3953
+ return await this._client.makeWebsocket(apiUrl, options);
3954
+ }
3955
+ }
3956
+ class speech_Speech extends APIResource {
3957
+ async create(options) {
3958
+ const apiUrl = '/v1/audio/speech';
3959
+ return await this._client.makeWebsocket(apiUrl, options);
3960
+ }
3961
+ }
3962
+ class websockets_audio_Audio extends APIResource {
3963
+ constructor(...args){
3964
+ super(...args), this.speech = new speech_Speech(this._client), this.transcriptions = new transcriptions_Transcriptions(this._client);
3965
+ }
3966
+ }
3967
+ class Websockets extends APIResource {
3968
+ constructor(...args){
3969
+ super(...args), this.audio = new websockets_audio_Audio(this._client), this.chat = new chat_Chat(this._client);
3970
+ }
3971
+ }
3972
+ // EXTERNAL MODULE: ../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js
3973
+ var ws_browser = __webpack_require__("../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js");
3974
+ var browser_default = /*#__PURE__*/ __webpack_require__.n(ws_browser);
3975
+ /*! *****************************************************************************
3976
+ Copyright (c) Microsoft Corporation. All rights reserved.
3977
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
3978
+ this file except in compliance with the License. You may obtain a copy of the
3979
+ License at http://www.apache.org/licenses/LICENSE-2.0
3980
+
3981
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
3982
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
3983
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
3984
+ MERCHANTABLITY OR NON-INFRINGEMENT.
3985
+
3986
+ See the Apache Version 2.0 License for specific language governing permissions
3987
+ and limitations under the License.
3988
+ ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) {
3989
+ extendStatics = Object.setPrototypeOf || ({
3990
+ __proto__: []
3991
+ }) instanceof Array && function(d, b) {
3992
+ d.__proto__ = b;
3993
+ } || function(d, b) {
3994
+ for(var p in b)if (b.hasOwnProperty(p)) d[p] = b[p];
3995
+ };
3996
+ return extendStatics(d, b);
3997
+ };
3998
+ function __extends(d, b) {
3999
+ extendStatics(d, b);
4000
+ function __() {
4001
+ this.constructor = d;
4002
+ }
4003
+ d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
4004
+ }
4005
+ function __values(o) {
4006
+ var m = "function" == typeof Symbol && o[Symbol.iterator], i = 0;
4007
+ if (m) return m.call(o);
4008
+ return {
4009
+ next: function() {
4010
+ if (o && i >= o.length) o = void 0;
4011
+ return {
4012
+ value: o && o[i++],
4013
+ done: !o
4014
+ };
4015
+ }
4016
+ };
4017
+ }
4018
+ function __read(o, n) {
4019
+ var m = "function" == typeof Symbol && o[Symbol.iterator];
4020
+ if (!m) return o;
4021
+ var i = m.call(o), r, ar = [], e;
4022
+ try {
4023
+ while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value);
4024
+ } catch (error) {
4025
+ e = {
4026
+ error: error
4027
+ };
4028
+ } finally{
4029
+ try {
4030
+ if (r && !r.done && (m = i["return"])) m.call(i);
4031
+ } finally{
4032
+ if (e) throw e.error;
4033
+ }
4034
+ }
4035
+ return ar;
4036
+ }
4037
+ function __spread() {
4038
+ for(var ar = [], i = 0; i < arguments.length; i++)ar = ar.concat(__read(arguments[i]));
4039
+ return ar;
4040
+ }
4041
+ var reconnecting_websocket_mjs_Event = /** @class */ function() {
4042
+ function Event1(type, target) {
4043
+ this.target = target;
4044
+ this.type = type;
4045
+ }
4046
+ return Event1;
4047
+ }();
4048
+ var reconnecting_websocket_mjs_ErrorEvent = /** @class */ function(_super) {
4049
+ __extends(ErrorEvent, _super);
4050
+ function ErrorEvent(error, target) {
4051
+ var _this = _super.call(this, 'error', target) || this;
4052
+ _this.message = error.message;
4053
+ _this.error = error;
4054
+ return _this;
4055
+ }
4056
+ return ErrorEvent;
4057
+ }(reconnecting_websocket_mjs_Event);
4058
+ var reconnecting_websocket_mjs_CloseEvent = /** @class */ function(_super) {
4059
+ __extends(CloseEvent, _super);
4060
+ function CloseEvent(code, reason, target) {
4061
+ if (void 0 === code) code = 1000;
4062
+ if (void 0 === reason) reason = '';
4063
+ var _this = _super.call(this, 'close', target) || this;
4064
+ _this.wasClean = true;
4065
+ _this.code = code;
4066
+ _this.reason = reason;
4067
+ return _this;
4068
+ }
4069
+ return CloseEvent;
4070
+ }(reconnecting_websocket_mjs_Event);
4071
+ /*!
4072
+ * Reconnecting WebSocket
4073
+ * by Pedro Ladaria <pedro.ladaria@gmail.com>
4074
+ * https://github.com/pladaria/reconnecting-websocket
4075
+ * License MIT
4076
+ */ var getGlobalWebSocket = function() {
4077
+ if ('undefined' != typeof WebSocket) // @ts-ignore
4078
+ return WebSocket;
4079
+ };
4080
+ /**
4081
+ * Returns true if given argument looks like a WebSocket class
4082
+ */ var isWebSocket = function(w) {
4083
+ return void 0 !== w && !!w && 2 === w.CLOSING;
4084
+ };
4085
+ var DEFAULT = {
4086
+ maxReconnectionDelay: 10000,
4087
+ minReconnectionDelay: 1000 + 4000 * Math.random(),
4088
+ minUptime: 5000,
4089
+ reconnectionDelayGrowFactor: 1.3,
4090
+ connectionTimeout: 4000,
4091
+ maxRetries: 1 / 0,
4092
+ maxEnqueuedMessages: 1 / 0,
4093
+ startClosed: false,
4094
+ debug: false
4095
+ };
4096
+ var reconnecting_websocket_mjs_ReconnectingWebSocket = /** @class */ function() {
4097
+ function ReconnectingWebSocket(url, protocols, options) {
4098
+ var _this = this;
4099
+ if (void 0 === options) options = {};
4100
+ this._listeners = {
4101
+ error: [],
4102
+ message: [],
4103
+ open: [],
4104
+ close: []
4105
+ };
4106
+ this._retryCount = -1;
4107
+ this._shouldReconnect = true;
4108
+ this._connectLock = false;
4109
+ this._binaryType = 'blob';
4110
+ this._closeCalled = false;
4111
+ this._messageQueue = [];
4112
+ /**
4113
+ * An event listener to be called when the WebSocket connection's readyState changes to CLOSED
4114
+ */ this.onclose = null;
4115
+ /**
4116
+ * An event listener to be called when an error occurs
4117
+ */ this.onerror = null;
4118
+ /**
4119
+ * An event listener to be called when a message is received from the server
4120
+ */ this.onmessage = null;
4121
+ /**
4122
+ * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
4123
+ * this indicates that the connection is ready to send and receive data
4124
+ */ this.onopen = null;
4125
+ this._handleOpen = function(event) {
4126
+ _this._debug('open event');
4127
+ var _a = _this._options.minUptime, minUptime = void 0 === _a ? DEFAULT.minUptime : _a;
4128
+ clearTimeout(_this._connectTimeout);
4129
+ _this._uptimeTimeout = setTimeout(function() {
4130
+ return _this._acceptOpen();
4131
+ }, minUptime);
4132
+ _this._ws.binaryType = _this._binaryType;
4133
+ // send enqueued messages (messages sent before websocket open event)
4134
+ _this._messageQueue.forEach(function(message) {
4135
+ return _this._ws.send(message);
4136
+ });
4137
+ _this._messageQueue = [];
4138
+ if (_this.onopen) _this.onopen(event);
4139
+ _this._listeners.open.forEach(function(listener) {
4140
+ return _this._callEventListener(event, listener);
4141
+ });
4142
+ };
4143
+ this._handleMessage = function(event) {
4144
+ _this._debug('message event');
4145
+ if (_this.onmessage) _this.onmessage(event);
4146
+ _this._listeners.message.forEach(function(listener) {
4147
+ return _this._callEventListener(event, listener);
4148
+ });
4149
+ };
4150
+ this._handleError = function(event) {
4151
+ _this._debug('error event', event.message);
4152
+ _this._disconnect(void 0, 'TIMEOUT' === event.message ? 'timeout' : void 0);
4153
+ if (_this.onerror) _this.onerror(event);
4154
+ _this._debug('exec error listeners');
4155
+ _this._listeners.error.forEach(function(listener) {
4156
+ return _this._callEventListener(event, listener);
4157
+ });
4158
+ _this._connect();
4159
+ };
4160
+ this._handleClose = function(event) {
4161
+ _this._debug('close event');
4162
+ _this._clearTimeouts();
4163
+ if (_this._shouldReconnect) _this._connect();
4164
+ if (_this.onclose) _this.onclose(event);
4165
+ _this._listeners.close.forEach(function(listener) {
4166
+ return _this._callEventListener(event, listener);
4167
+ });
4168
+ };
4169
+ this._url = url;
4170
+ this._protocols = protocols;
4171
+ this._options = options;
4172
+ if (this._options.startClosed) this._shouldReconnect = false;
4173
+ this._connect();
4174
+ }
4175
+ Object.defineProperty(ReconnectingWebSocket, "CONNECTING", {
4176
+ get: function() {
4177
+ return 0;
4178
+ },
4179
+ enumerable: true,
4180
+ configurable: true
4181
+ });
4182
+ Object.defineProperty(ReconnectingWebSocket, "OPEN", {
4183
+ get: function() {
4184
+ return 1;
4185
+ },
4186
+ enumerable: true,
4187
+ configurable: true
4188
+ });
4189
+ Object.defineProperty(ReconnectingWebSocket, "CLOSING", {
4190
+ get: function() {
4191
+ return 2;
4192
+ },
4193
+ enumerable: true,
4194
+ configurable: true
4195
+ });
4196
+ Object.defineProperty(ReconnectingWebSocket, "CLOSED", {
4197
+ get: function() {
4198
+ return 3;
4199
+ },
4200
+ enumerable: true,
4201
+ configurable: true
4202
+ });
4203
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CONNECTING", {
4204
+ get: function() {
4205
+ return ReconnectingWebSocket.CONNECTING;
4206
+ },
4207
+ enumerable: true,
4208
+ configurable: true
4209
+ });
4210
+ Object.defineProperty(ReconnectingWebSocket.prototype, "OPEN", {
4211
+ get: function() {
4212
+ return ReconnectingWebSocket.OPEN;
4213
+ },
4214
+ enumerable: true,
4215
+ configurable: true
4216
+ });
4217
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSING", {
4218
+ get: function() {
4219
+ return ReconnectingWebSocket.CLOSING;
4220
+ },
4221
+ enumerable: true,
4222
+ configurable: true
4223
+ });
4224
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSED", {
4225
+ get: function() {
4226
+ return ReconnectingWebSocket.CLOSED;
4227
+ },
4228
+ enumerable: true,
4229
+ configurable: true
4230
+ });
4231
+ Object.defineProperty(ReconnectingWebSocket.prototype, "binaryType", {
4232
+ get: function() {
4233
+ return this._ws ? this._ws.binaryType : this._binaryType;
4234
+ },
4235
+ set: function(value) {
4236
+ this._binaryType = value;
4237
+ if (this._ws) this._ws.binaryType = value;
4238
+ },
4239
+ enumerable: true,
4240
+ configurable: true
4241
+ });
4242
+ Object.defineProperty(ReconnectingWebSocket.prototype, "retryCount", {
4243
+ /**
4244
+ * Returns the number or connection retries
4245
+ */ get: function() {
4246
+ return Math.max(this._retryCount, 0);
4247
+ },
4248
+ enumerable: true,
4249
+ configurable: true
4250
+ });
4251
+ Object.defineProperty(ReconnectingWebSocket.prototype, "bufferedAmount", {
4252
+ /**
4253
+ * The number of bytes of data that have been queued using calls to send() but not yet
4254
+ * transmitted to the network. This value resets to zero once all queued data has been sent.
4255
+ * This value does not reset to zero when the connection is closed; if you keep calling send(),
4256
+ * this will continue to climb. Read only
4257
+ */ get: function() {
4258
+ var bytes = this._messageQueue.reduce(function(acc, message) {
4259
+ if ('string' == typeof message) acc += message.length; // not byte size
4260
+ else if (message instanceof Blob) acc += message.size;
4261
+ else acc += message.byteLength;
4262
+ return acc;
4263
+ }, 0);
4264
+ return bytes + (this._ws ? this._ws.bufferedAmount : 0);
4265
+ },
4266
+ enumerable: true,
4267
+ configurable: true
4268
+ });
4269
+ Object.defineProperty(ReconnectingWebSocket.prototype, "extensions", {
4270
+ /**
4271
+ * The extensions selected by the server. This is currently only the empty string or a list of
4272
+ * extensions as negotiated by the connection
4273
+ */ get: function() {
4274
+ return this._ws ? this._ws.extensions : '';
4275
+ },
4276
+ enumerable: true,
4277
+ configurable: true
4278
+ });
4279
+ Object.defineProperty(ReconnectingWebSocket.prototype, "protocol", {
4280
+ /**
4281
+ * A string indicating the name of the sub-protocol the server selected;
4282
+ * this will be one of the strings specified in the protocols parameter when creating the
4283
+ * WebSocket object
4284
+ */ get: function() {
4285
+ return this._ws ? this._ws.protocol : '';
4286
+ },
4287
+ enumerable: true,
4288
+ configurable: true
4289
+ });
4290
+ Object.defineProperty(ReconnectingWebSocket.prototype, "readyState", {
4291
+ /**
4292
+ * The current state of the connection; this is one of the Ready state constants
4293
+ */ get: function() {
4294
+ if (this._ws) return this._ws.readyState;
4295
+ return this._options.startClosed ? ReconnectingWebSocket.CLOSED : ReconnectingWebSocket.CONNECTING;
4296
+ },
4297
+ enumerable: true,
4298
+ configurable: true
4299
+ });
4300
+ Object.defineProperty(ReconnectingWebSocket.prototype, "url", {
4301
+ /**
4302
+ * The URL as resolved by the constructor
4303
+ */ get: function() {
4304
+ return this._ws ? this._ws.url : '';
4305
+ },
4306
+ enumerable: true,
4307
+ configurable: true
4308
+ });
4309
+ /**
4310
+ * Closes the WebSocket connection or connection attempt, if any. If the connection is already
4311
+ * CLOSED, this method does nothing
4312
+ */ ReconnectingWebSocket.prototype.close = function(code, reason) {
4313
+ if (void 0 === code) code = 1000;
4314
+ this._closeCalled = true;
4315
+ this._shouldReconnect = false;
4316
+ this._clearTimeouts();
4317
+ if (!this._ws) {
4318
+ this._debug('close enqueued: no ws instance');
4319
+ return;
4320
+ }
4321
+ if (this._ws.readyState === this.CLOSED) {
4322
+ this._debug('close: already closed');
4323
+ return;
4324
+ }
4325
+ this._ws.close(code, reason);
4326
+ };
4327
+ /**
4328
+ * Closes the WebSocket connection or connection attempt and connects again.
4329
+ * Resets retry counter;
4330
+ */ ReconnectingWebSocket.prototype.reconnect = function(code, reason) {
4331
+ this._shouldReconnect = true;
4332
+ this._closeCalled = false;
4333
+ this._retryCount = -1;
4334
+ if (this._ws && this._ws.readyState !== this.CLOSED) {
4335
+ this._disconnect(code, reason);
4336
+ this._connect();
4337
+ } else this._connect();
4338
+ };
4339
+ /**
4340
+ * Enqueue specified data to be transmitted to the server over the WebSocket connection
4341
+ */ ReconnectingWebSocket.prototype.send = function(data) {
4342
+ if (this._ws && this._ws.readyState === this.OPEN) {
4343
+ this._debug('send', data);
4344
+ this._ws.send(data);
4345
+ } else {
4346
+ var _a = this._options.maxEnqueuedMessages, maxEnqueuedMessages = void 0 === _a ? DEFAULT.maxEnqueuedMessages : _a;
4347
+ if (this._messageQueue.length < maxEnqueuedMessages) {
4348
+ this._debug('enqueue', data);
4349
+ this._messageQueue.push(data);
4350
+ }
4351
+ }
4352
+ };
4353
+ /**
4354
+ * Register an event handler of a specific event type
4355
+ */ ReconnectingWebSocket.prototype.addEventListener = function(type, listener) {
4356
+ if (this._listeners[type]) // @ts-ignore
4357
+ this._listeners[type].push(listener);
4358
+ };
4359
+ ReconnectingWebSocket.prototype.dispatchEvent = function(event) {
4360
+ var e_1, _a;
4361
+ var listeners = this._listeners[event.type];
4362
+ if (listeners) try {
4363
+ for(var listeners_1 = __values(listeners), listeners_1_1 = listeners_1.next(); !listeners_1_1.done; listeners_1_1 = listeners_1.next()){
4364
+ var listener = listeners_1_1.value;
4365
+ this._callEventListener(event, listener);
4366
+ }
4367
+ } catch (e_1_1) {
4368
+ e_1 = {
4369
+ error: e_1_1
4370
+ };
4371
+ } finally{
4372
+ try {
4373
+ if (listeners_1_1 && !listeners_1_1.done && (_a = listeners_1.return)) _a.call(listeners_1);
4374
+ } finally{
4375
+ if (e_1) throw e_1.error;
4376
+ }
4377
+ }
4378
+ return true;
4379
+ };
4380
+ /**
4381
+ * Removes an event listener
4382
+ */ ReconnectingWebSocket.prototype.removeEventListener = function(type, listener) {
4383
+ if (this._listeners[type]) // @ts-ignore
4384
+ this._listeners[type] = this._listeners[type].filter(function(l) {
4385
+ return l !== listener;
4386
+ });
4387
+ };
4388
+ ReconnectingWebSocket.prototype._debug = function() {
4389
+ var args = [];
4390
+ for(var _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i];
4391
+ if (this._options.debug) // not using spread because compiled version uses Symbols
4392
+ // tslint:disable-next-line
4393
+ console.log.apply(console, __spread([
4394
+ 'RWS>'
4395
+ ], args));
4396
+ };
4397
+ ReconnectingWebSocket.prototype._getNextDelay = function() {
4398
+ var _a = this._options, _b = _a.reconnectionDelayGrowFactor, reconnectionDelayGrowFactor = void 0 === _b ? DEFAULT.reconnectionDelayGrowFactor : _b, _c = _a.minReconnectionDelay, minReconnectionDelay = void 0 === _c ? DEFAULT.minReconnectionDelay : _c, _d = _a.maxReconnectionDelay, maxReconnectionDelay = void 0 === _d ? DEFAULT.maxReconnectionDelay : _d;
4399
+ var delay = 0;
4400
+ if (this._retryCount > 0) {
4401
+ delay = minReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, this._retryCount - 1);
4402
+ if (delay > maxReconnectionDelay) delay = maxReconnectionDelay;
4403
+ }
4404
+ this._debug('next delay', delay);
4405
+ return delay;
4406
+ };
4407
+ ReconnectingWebSocket.prototype._wait = function() {
4408
+ var _this = this;
4409
+ return new Promise(function(resolve) {
4410
+ setTimeout(resolve, _this._getNextDelay());
4411
+ });
4412
+ };
4413
+ ReconnectingWebSocket.prototype._getNextUrl = function(urlProvider) {
4414
+ if ('string' == typeof urlProvider) return Promise.resolve(urlProvider);
4415
+ if ('function' == typeof urlProvider) {
4416
+ var url = urlProvider();
4417
+ if ('string' == typeof url) return Promise.resolve(url);
4418
+ if (!!url.then) return url;
4419
+ }
4420
+ throw Error('Invalid URL');
4421
+ };
4422
+ ReconnectingWebSocket.prototype._connect = function() {
4423
+ var _this = this;
4424
+ if (this._connectLock || !this._shouldReconnect) return;
4425
+ this._connectLock = true;
4426
+ var _a = this._options, _b = _a.maxRetries, maxRetries = void 0 === _b ? DEFAULT.maxRetries : _b, _c = _a.connectionTimeout, connectionTimeout = void 0 === _c ? DEFAULT.connectionTimeout : _c, _d = _a.WebSocket, WebSocket1 = void 0 === _d ? getGlobalWebSocket() : _d;
4427
+ if (this._retryCount >= maxRetries) {
4428
+ this._debug('max retries reached', this._retryCount, '>=', maxRetries);
4429
+ return;
4430
+ }
4431
+ this._retryCount++;
4432
+ this._debug('connect', this._retryCount);
4433
+ this._removeListeners();
4434
+ if (!isWebSocket(WebSocket1)) throw Error('No valid WebSocket class provided');
4435
+ this._wait().then(function() {
4436
+ return _this._getNextUrl(_this._url);
4437
+ }).then(function(url) {
4438
+ // close could be called before creating the ws
4439
+ if (_this._closeCalled) return;
4440
+ _this._debug('connect', {
4441
+ url: url,
4442
+ protocols: _this._protocols
4443
+ });
4444
+ _this._ws = _this._protocols ? new WebSocket1(url, _this._protocols) : new WebSocket1(url);
4445
+ _this._ws.binaryType = _this._binaryType;
4446
+ _this._connectLock = false;
4447
+ _this._addListeners();
4448
+ _this._connectTimeout = setTimeout(function() {
4449
+ return _this._handleTimeout();
4450
+ }, connectionTimeout);
4451
+ });
4452
+ };
4453
+ ReconnectingWebSocket.prototype._handleTimeout = function() {
4454
+ this._debug('timeout event');
4455
+ this._handleError(new reconnecting_websocket_mjs_ErrorEvent(Error('TIMEOUT'), this));
4456
+ };
4457
+ ReconnectingWebSocket.prototype._disconnect = function(code, reason) {
4458
+ if (void 0 === code) code = 1000;
4459
+ this._clearTimeouts();
4460
+ if (!this._ws) return;
4461
+ this._removeListeners();
4462
+ try {
4463
+ this._ws.close(code, reason);
4464
+ this._handleClose(new reconnecting_websocket_mjs_CloseEvent(code, reason, this));
4465
+ } catch (error) {
4466
+ // ignore
4467
+ }
4468
+ };
4469
+ ReconnectingWebSocket.prototype._acceptOpen = function() {
4470
+ this._debug('accept open');
4471
+ this._retryCount = 0;
4472
+ };
4473
+ ReconnectingWebSocket.prototype._callEventListener = function(event, listener) {
4474
+ if ('handleEvent' in listener) // @ts-ignore
4475
+ listener.handleEvent(event);
4476
+ else // @ts-ignore
4477
+ listener(event);
4478
+ };
4479
+ ReconnectingWebSocket.prototype._removeListeners = function() {
4480
+ if (!this._ws) return;
4481
+ this._debug('removeListeners');
4482
+ this._ws.removeEventListener('open', this._handleOpen);
4483
+ this._ws.removeEventListener('close', this._handleClose);
4484
+ this._ws.removeEventListener('message', this._handleMessage);
4485
+ // @ts-ignore
4486
+ this._ws.removeEventListener('error', this._handleError);
4487
+ };
4488
+ ReconnectingWebSocket.prototype._addListeners = function() {
4489
+ if (!this._ws) return;
4490
+ this._debug('addListeners');
4491
+ this._ws.addEventListener('open', this._handleOpen);
4492
+ this._ws.addEventListener('close', this._handleClose);
4493
+ this._ws.addEventListener('message', this._handleMessage);
4494
+ // @ts-ignore
4495
+ this._ws.addEventListener('error', this._handleError);
4496
+ };
4497
+ ReconnectingWebSocket.prototype._clearTimeouts = function() {
4498
+ clearTimeout(this._connectTimeout);
4499
+ clearTimeout(this._uptimeTimeout);
4500
+ };
4501
+ return ReconnectingWebSocket;
4502
+ }();
4503
+ /* ESM default export */ const reconnecting_websocket_mjs = reconnecting_websocket_mjs_ReconnectingWebSocket;
4504
+ // Common types (not exported)
4505
+ // Keep all existing exports but use the base types where applicable
4506
+ var types_WebsocketsEventType = /*#__PURE__*/ function(WebsocketsEventType) {
4507
+ // Common
4508
+ /** SDK error */ WebsocketsEventType["CLIENT_ERROR"] = "client_error";
4509
+ /** Connection closed */ WebsocketsEventType["CLOSED"] = "closed";
4510
+ // Error
4511
+ /** Received error event */ WebsocketsEventType["ERROR"] = "error";
4512
+ // v1/audio/speech
4513
+ /** Send text to server */ WebsocketsEventType["INPUT_TEXT_BUFFER_APPEND"] = "input_text_buffer.append";
4514
+ /** No text to send, after audio all received, can close connection */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETE"] = "input_text_buffer.complete";
4515
+ /** Send speech config to server */ WebsocketsEventType["SPEECH_UPDATE"] = "speech.update";
4516
+ /** Received `speech.updated` event */ WebsocketsEventType["SPEECH_UPDATED"] = "speech.updated";
4517
+ /** After speech created */ WebsocketsEventType["SPEECH_CREATED"] = "speech.created";
4518
+ /** Received `input_text_buffer.complete` event */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETED"] = "input_text_buffer.completed";
4519
+ /** Received `speech.update` event */ WebsocketsEventType["SPEECH_AUDIO_UPDATE"] = "speech.audio.update";
4520
+ /** All audio received, can close connection */ WebsocketsEventType["SPEECH_AUDIO_COMPLETED"] = "speech.audio.completed";
4521
+ // v1/audio/transcriptions
4522
+ /** Send audio to server */ WebsocketsEventType["INPUT_AUDIO_BUFFER_APPEND"] = "input_audio_buffer.append";
4523
+ /** No audio to send, after text all received, can close connection */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETE"] = "input_audio_buffer.complete";
4524
+ /** Send transcriptions config to server */ WebsocketsEventType["TRANSCRIPTIONS_UPDATE"] = "transcriptions.update";
4525
+ /** Send `input_audio_buffer.clear` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEAR"] = "input_audio_buffer.clear";
4526
+ /** After transcriptions created */ WebsocketsEventType["TRANSCRIPTIONS_CREATED"] = "transcriptions.created";
4527
+ /** Received `input_audio_buffer.complete` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETED"] = "input_audio_buffer.completed";
4528
+ /** Received `transcriptions.update` event */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_UPDATE"] = "transcriptions.message.update";
4529
+ /** All audio received, can close connection */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_COMPLETED"] = "transcriptions.message.completed";
4530
+ /** Received `input_audio_buffer.cleared` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEARED"] = "input_audio_buffer.cleared";
4531
+ /** Received `transcriptions.updated` event */ WebsocketsEventType["TRANSCRIPTIONS_UPDATED"] = "transcriptions.updated";
4532
+ // v1/chat
4533
+ /** Send chat config to server */ WebsocketsEventType["CHAT_UPDATE"] = "chat.update";
4534
+ /** Send tool outputs to server */ WebsocketsEventType["CONVERSATION_CHAT_SUBMIT_TOOL_OUTPUTS"] = "conversation.chat.submit_tool_outputs";
4535
+ /** After chat created */ WebsocketsEventType["CHAT_CREATED"] = "chat.created";
4536
+ /** After chat updated */ WebsocketsEventType["CHAT_UPDATED"] = "chat.updated";
4537
+ /** Audio AST completed, chat started */ WebsocketsEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
4538
+ /** Message created */ WebsocketsEventType["CONVERSATION_MESSAGE_CREATE"] = "conversation.message.create";
4539
+ /** Clear conversation */ WebsocketsEventType["CONVERSATION_CLEAR"] = "conversation.clear";
4540
+ /** Chat in progress */ WebsocketsEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
4541
+ /** Get agent text message update */ WebsocketsEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
4542
+ /** Need plugin submit */ WebsocketsEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
4543
+ /** Message completed */ WebsocketsEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
4544
+ /** Get agent audio message update */ WebsocketsEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
4545
+ /** Audio message completed */ WebsocketsEventType["CONVERSATION_AUDIO_COMPLETED"] = "conversation.audio.completed";
4546
+ /** All message received, can close connection */ WebsocketsEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
4547
+ /** Chat failed */ WebsocketsEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
4548
+ /** Received `conversation.cleared` event */ WebsocketsEventType["CONVERSATION_CLEARED"] = "conversation.cleared";
4549
+ return WebsocketsEventType;
4550
+ }({});
4551
+ class WebSocketAPI {
4552
+ // Standard WebSocket properties
4553
+ get readyState() {
4554
+ return this.rws.readyState;
4555
+ }
4556
+ // Standard WebSocket methods
4557
+ send(data) {
4558
+ return this.rws.send(JSON.stringify(data));
4559
+ }
4560
+ close(code, reason) {
4561
+ return this.rws.close(code, reason);
4562
+ }
4563
+ reconnect(code, reason) {
4564
+ return this.rws.reconnect(code, reason);
4565
+ }
4566
+ // Event listener methods
4567
+ addEventListener(type, listener) {
4568
+ this.rws.addEventListener(type, listener);
4569
+ }
4570
+ removeEventListener(type, listener) {
4571
+ this.rws.removeEventListener(type, listener);
4572
+ }
4573
+ constructor(url, options = {}){
4574
+ // Event handler methods
4575
+ this.onmessage = null;
4576
+ this.onopen = null;
4577
+ this.onclose = null;
4578
+ this.onerror = null;
4579
+ const separator = url.includes('?') ? '&' : '?';
4580
+ const { authorization } = options.headers || {};
4581
+ this.rws = new reconnecting_websocket_mjs(`${url}${separator}authorization=${authorization}`, [], {
4582
+ WebSocket: utils_isBrowser() ? window.WebSocket : class extends browser_default() {
4583
+ constructor(url2, protocols){
4584
+ super(url2, protocols, {
4585
+ headers: options.headers
4586
+ });
4587
+ }
4588
+ },
4589
+ ...options
4590
+ });
4591
+ this.rws.addEventListener('message', (event)=>{
4592
+ try {
4593
+ var _this_onmessage, _this;
4594
+ const data = JSON.parse(event.data);
4595
+ null === (_this_onmessage = (_this = this).onmessage) || void 0 === _this_onmessage || _this_onmessage.call(_this, data, event);
4596
+ } catch (error) {
4597
+ console.error('WebSocketAPI onmessage error', error);
4598
+ }
4599
+ });
4600
+ this.rws.addEventListener('open', (event)=>{
4601
+ var _this_onopen, _this;
4602
+ null === (_this_onopen = (_this = this).onopen) || void 0 === _this_onopen || _this_onopen.call(_this, event);
4603
+ });
4604
+ this.rws.addEventListener('close', (event)=>{
4605
+ var _this_onclose, _this;
4606
+ null === (_this_onclose = (_this = this).onclose) || void 0 === _this_onclose || _this_onclose.call(_this, event);
4607
+ });
4608
+ this.rws.addEventListener('error', (event)=>{
4609
+ var _event_target__req_res, _event_target__req, _event_target, _event_target__req_res1, _event_target__req1, _event_target1, _this_onerror, _this;
4610
+ const statusCode = null === (_event_target = event.target) || void 0 === _event_target ? void 0 : null === (_event_target__req = _event_target._req) || void 0 === _event_target__req ? void 0 : null === (_event_target__req_res = _event_target__req.res) || void 0 === _event_target__req_res ? void 0 : _event_target__req_res.statusCode;
4611
+ const rawHeaders = (null === (_event_target1 = event.target) || void 0 === _event_target1 ? void 0 : null === (_event_target__req1 = _event_target1._req) || void 0 === _event_target__req1 ? void 0 : null === (_event_target__req_res1 = _event_target__req1.res) || void 0 === _event_target__req_res1 ? void 0 : _event_target__req_res1.rawHeaders) || [];
4612
+ const logidIndex = rawHeaders.findIndex((header)=>'X-Tt-Logid' === header);
4613
+ const logid = -1 !== logidIndex ? rawHeaders[logidIndex + 1] : void 0;
4614
+ const error = {
4615
+ id: '0',
4616
+ event_type: types_WebsocketsEventType.ERROR,
4617
+ data: {
4618
+ code: -1,
4619
+ msg: 'WebSocket error'
4620
+ },
4621
+ detail: {
4622
+ logid
4623
+ }
4624
+ };
4625
+ if (401 === statusCode) {
4626
+ error.data.code = 401;
4627
+ error.data.msg = 'Unauthorized';
4628
+ } else if (403 === statusCode) {
4629
+ error.data.code = 403;
4630
+ error.data.msg = 'Forbidden';
4631
+ } else {
4632
+ error.data.code = 500;
4633
+ error.data.msg = String(null == event ? void 0 : event.error) || 'WebSocket error';
4634
+ }
4635
+ null === (_this_onerror = (_this = this).onerror) || void 0 === _this_onerror || _this_onerror.call(_this, error, event);
4636
+ });
4637
+ }
4638
+ }
3929
4639
  // EXTERNAL MODULE: os (ignored)
3930
4640
  var os_ignored_ = __webpack_require__("?9050");
3931
4641
  var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3932
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.16","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":"./src/index.ts"},"main":"src/index.ts","module":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"src/index.ts","files":["dist","LICENSE","README.md","README.zh-CN.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
4642
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.21-beta.2","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":"./src/index.ts","./ws-tools":"./src/ws-tools/index.ts"},"main":"src/index.ts","module":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false,"node-fetch":false},"typesVersions":{"*":{".":["dist/types/index.d.ts"],"ws-tools":["dist/types/ws-tools/ws-tools/index.d.ts"]}},"files":["dist","LICENSE","README.md","README.zh-CN.md"],"scripts":{"build":"rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2","node-fetch":"^2.x","reconnecting-websocket":"^4.4.0","uuid":"^10.0.0","ws":"^8.11.0"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/node-fetch":"^2.x","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@types/ws":"^8.5.1","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"},"./ws-tools":{"require":"./dist/cjs/ws-tools/index.cjs","import":"./dist/esm/ws-tools/index.js","types":"./dist/types/ws-tools/ws-tools/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
3933
4643
  const { version: version_version } = package_namespaceObject;
3934
4644
  const getEnv = ()=>{
3935
4645
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
@@ -4028,6 +4738,9 @@ const getBrowserClientUserAgent = ()=>{
4028
4738
  };
4029
4739
  return JSON.stringify(ua);
4030
4740
  };
4741
+ // EXTERNAL MODULE: node-fetch (ignored)
4742
+ var node_fetch_ignored_ = __webpack_require__("?8dee");
4743
+ var node_fetch_ignored_default = /*#__PURE__*/ __webpack_require__.n(node_fetch_ignored_);
4031
4744
  /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
4032
4745
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
4033
4746
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
@@ -4040,6 +4753,23 @@ const getBrowserClientUserAgent = ()=>{
4040
4753
  return error_APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
4041
4754
  }
4042
4755
  };
4756
+ // node-fetch is used for streaming requests
4757
+ const adapterFetch = async (options)=>{
4758
+ const response = await node_fetch_ignored_default()(options.url, {
4759
+ body: options.data,
4760
+ ...options
4761
+ });
4762
+ return {
4763
+ data: response.body,
4764
+ ...response
4765
+ };
4766
+ };
4767
+ const isSupportNativeFetch = ()=>{
4768
+ if (utils_isBrowser()) return true;
4769
+ // native fetch is supported in node 18.0.0 or higher
4770
+ const version = process.version.slice(1);
4771
+ return compareVersions(version, '18.0.0') >= 0;
4772
+ };
4043
4773
  async function fetchAPI(url) {
4044
4774
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
4045
4775
  const axiosInstance = options.axiosInstance || lib_axios;
@@ -4051,7 +4781,7 @@ async function fetchAPI(url) {
4051
4781
  const response = await axiosInstance({
4052
4782
  url,
4053
4783
  responseType: options.isStreaming ? 'stream' : 'json',
4054
- adapter: options.isStreaming ? 'fetch' : void 0,
4784
+ adapter: options.isStreaming ? isSupportNativeFetch() ? 'fetch' : adapterFetch : void 0,
4055
4785
  ...options
4056
4786
  }).catch((error)=>{
4057
4787
  throw fetcher_handleError(error);
@@ -4117,6 +4847,9 @@ function isAxiosStatic(instance) {
4117
4847
  /**
4118
4848
  * default coze base URL is api.coze.com
4119
4849
  */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
4850
+ /**
4851
+ * default base websocket URL is wss://ws.coze.com
4852
+ */ const COZE_COM_BASE_WS_URL = 'wss://ws.coze.com';
4120
4853
  /* eslint-disable max-params */ class core_APIClient {
4121
4854
  async getToken() {
4122
4855
  if ('function' == typeof this.token) return await this.token();
@@ -4141,6 +4874,26 @@ function isAxiosStatic(instance) {
4141
4874
  config.data = body;
4142
4875
  return config;
4143
4876
  }
4877
+ async buildWebsocketOptions(options) {
4878
+ const token = await this.getToken();
4879
+ const headers = {
4880
+ authorization: `Bearer ${token}`
4881
+ };
4882
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4883
+ else {
4884
+ headers['User-Agent'] = getUserAgent();
4885
+ headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
4886
+ }
4887
+ var _this__config_debug;
4888
+ const config = mergeConfig({
4889
+ debug: null !== (_this__config_debug = this._config.debug) && void 0 !== _this__config_debug && _this__config_debug
4890
+ }, this._config.websocketOptions, options, {
4891
+ headers
4892
+ }, {
4893
+ headers: this.headers || {}
4894
+ });
4895
+ return config;
4896
+ }
4144
4897
  async makeRequest(apiUrl, method, body, isStream, options) {
4145
4898
  const fullUrl = `${this.baseURL}${apiUrl}`;
4146
4899
  const fetchOptions = await this.buildOptions(method, body, options);
@@ -4188,6 +4941,14 @@ function isAxiosStatic(instance) {
4188
4941
  async delete(apiUrl, isStream, options) {
4189
4942
  return this.makeRequest(apiUrl, 'DELETE', void 0, isStream, options);
4190
4943
  }
4944
+ async makeWebsocket(apiUrl, options) {
4945
+ const fullUrl = `${this.baseWsURL}${apiUrl}`;
4946
+ const websocketOptions = await this.buildWebsocketOptions(options);
4947
+ this.debugLog(null == options ? void 0 : options.debug, `--- websocket url: ${fullUrl}`);
4948
+ this.debugLog(null == options ? void 0 : options.debug, '--- websocket options:', websocketOptions);
4949
+ const ws = new WebSocketAPI(fullUrl, websocketOptions);
4950
+ return ws;
4951
+ }
4191
4952
  getConfig() {
4192
4953
  return this._config;
4193
4954
  }
@@ -4200,6 +4961,7 @@ function isAxiosStatic(instance) {
4200
4961
  constructor(config){
4201
4962
  this._config = config;
4202
4963
  this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4964
+ this.baseWsURL = config.baseWsURL || COZE_COM_BASE_WS_URL;
4203
4965
  this.token = config.token;
4204
4966
  this.axiosOptions = config.axiosOptions || {};
4205
4967
  this.axiosInstance = config.axiosInstance;
@@ -4227,7 +4989,7 @@ class CozeAPI extends core_APIClient {
4227
4989
  constructor(...args){
4228
4990
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4229
4991
  * @deprecated
4230
- */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this), this.templates = new Templates(this);
4992
+ */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this), this.templates = new Templates(this), this.websockets = new Websockets(this);
4231
4993
  }
4232
4994
  }
4233
4995
  /**
@@ -42377,12 +43139,24 @@ class RealtimeClient extends RealtimeEventHandler {
42377
43139
  let roomInfo;
42378
43140
  try {
42379
43141
  // Step1 get token
43142
+ let config;
43143
+ if (this._config.videoConfig) config = isScreenShareDevice(this._config.videoConfig.videoInputDeviceId) ? {
43144
+ video_config: {
43145
+ stream_video_type: 'screen'
43146
+ }
43147
+ } : {
43148
+ video_config: {
43149
+ stream_video_type: 'main'
43150
+ }
43151
+ };
42380
43152
  roomInfo = await this._api.audio.rooms.create({
42381
43153
  bot_id: botId,
42382
43154
  conversation_id: conversationId || void 0,
42383
43155
  voice_id: voiceId && voiceId.length > 0 ? voiceId : void 0,
42384
43156
  connector_id: this._config.connectorId,
42385
- uid: this._config.userId || void 0
43157
+ uid: this._config.userId || void 0,
43158
+ workflow_id: this._config.workflowId || void 0,
43159
+ config
42386
43160
  });
42387
43161
  } catch (error) {
42388
43162
  this.dispatch(event_handler_EventNames.ERROR, error);