@volcengine/ark-runtime 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/LICENSE.txt +202 -0
  2. package/README.md +104 -0
  3. package/dist/cjs/index.js +1717 -0
  4. package/dist/esm/client.d.ts +97 -0
  5. package/dist/esm/client.d.ts.map +1 -0
  6. package/dist/esm/config.d.ts +46 -0
  7. package/dist/esm/config.d.ts.map +1 -0
  8. package/dist/esm/encryption/encrypt-chat.d.ts +24 -0
  9. package/dist/esm/encryption/encrypt-chat.d.ts.map +1 -0
  10. package/dist/esm/encryption/index.d.ts +4 -0
  11. package/dist/esm/encryption/index.d.ts.map +1 -0
  12. package/dist/esm/encryption/key-agreement.d.ts +73 -0
  13. package/dist/esm/encryption/key-agreement.d.ts.map +1 -0
  14. package/dist/esm/index.d.ts +11 -0
  15. package/dist/esm/index.d.ts.map +1 -0
  16. package/dist/esm/index.mjs +1476 -0
  17. package/dist/esm/rslib-runtime.mjs +37 -0
  18. package/dist/esm/types/bot.d.ts +109 -0
  19. package/dist/esm/types/bot.d.ts.map +1 -0
  20. package/dist/esm/types/chat-completion.d.ts +167 -0
  21. package/dist/esm/types/chat-completion.d.ts.map +1 -0
  22. package/dist/esm/types/common.d.ts +29 -0
  23. package/dist/esm/types/common.d.ts.map +1 -0
  24. package/dist/esm/types/content-generation.d.ts +118 -0
  25. package/dist/esm/types/content-generation.d.ts.map +1 -0
  26. package/dist/esm/types/context.d.ts +49 -0
  27. package/dist/esm/types/context.d.ts.map +1 -0
  28. package/dist/esm/types/embeddings.d.ts +44 -0
  29. package/dist/esm/types/embeddings.d.ts.map +1 -0
  30. package/dist/esm/types/error.d.ts +45 -0
  31. package/dist/esm/types/error.d.ts.map +1 -0
  32. package/dist/esm/types/file.d.ts +66 -0
  33. package/dist/esm/types/file.d.ts.map +1 -0
  34. package/dist/esm/types/http-request-error.d.ts +13 -0
  35. package/dist/esm/types/http-request-error.d.ts.map +1 -0
  36. package/dist/esm/types/images.d.ts +78 -0
  37. package/dist/esm/types/images.d.ts.map +1 -0
  38. package/dist/esm/types/index.d.ts +13 -0
  39. package/dist/esm/types/index.d.ts.map +1 -0
  40. package/dist/esm/types/multimodal-embedding.d.ts +56 -0
  41. package/dist/esm/types/multimodal-embedding.d.ts.map +1 -0
  42. package/dist/esm/types/responses/enums.d.ts +38 -0
  43. package/dist/esm/types/responses/enums.d.ts.map +1 -0
  44. package/dist/esm/types/responses/helpers.d.ts +22 -0
  45. package/dist/esm/types/responses/helpers.d.ts.map +1 -0
  46. package/dist/esm/types/responses/index.d.ts +4 -0
  47. package/dist/esm/types/responses/index.d.ts.map +1 -0
  48. package/dist/esm/types/responses/types.d.ts +906 -0
  49. package/dist/esm/types/responses/types.d.ts.map +1 -0
  50. package/dist/esm/types/tokenization.d.ts +22 -0
  51. package/dist/esm/types/tokenization.d.ts.map +1 -0
  52. package/dist/esm/utils/breaker-provider.d.ts +9 -0
  53. package/dist/esm/utils/breaker-provider.d.ts.map +1 -0
  54. package/dist/esm/utils/breaker.d.ts +28 -0
  55. package/dist/esm/utils/breaker.d.ts.map +1 -0
  56. package/dist/esm/utils/normalize.d.ts +51 -0
  57. package/dist/esm/utils/normalize.d.ts.map +1 -0
  58. package/dist/esm/utils/request-builder.d.ts +15 -0
  59. package/dist/esm/utils/request-builder.d.ts.map +1 -0
  60. package/dist/esm/utils/request-id.d.ts +5 -0
  61. package/dist/esm/utils/request-id.d.ts.map +1 -0
  62. package/dist/esm/utils/retry.d.ts +11 -0
  63. package/dist/esm/utils/retry.d.ts.map +1 -0
  64. package/dist/esm/utils/sse-decoder.d.ts +23 -0
  65. package/dist/esm/utils/sse-decoder.d.ts.map +1 -0
  66. package/dist/esm/utils/stream-reader.d.ts +67 -0
  67. package/dist/esm/utils/stream-reader.d.ts.map +1 -0
  68. package/dist/tsconfig.tsbuildinfo +1 -0
  69. package/example/README.md +118 -0
  70. package/example/batch-chat.ts +64 -0
  71. package/example/bot-chat.ts +66 -0
  72. package/example/chat-completion-function-call.ts +141 -0
  73. package/example/chat-completion-reasoning.ts +64 -0
  74. package/example/chat-completion-vision.ts +70 -0
  75. package/example/chat-completion.ts +62 -0
  76. package/example/content-generation.ts +70 -0
  77. package/example/context.ts +69 -0
  78. package/example/embeddings.ts +31 -0
  79. package/example/file-upload.ts +53 -0
  80. package/example/images.ts +74 -0
  81. package/example/list-input-items.ts +34 -0
  82. package/example/multimodal-embeddings.ts +36 -0
  83. package/example/responses/basic.ts +75 -0
  84. package/example/responses/doubao-app.ts +53 -0
  85. package/example/responses/mcp.ts +66 -0
  86. package/example/responses/streaming.ts +45 -0
  87. package/example/responses/video.ts +74 -0
  88. package/example/responses/web-search.ts +52 -0
  89. package/example/structured-outputs.ts +71 -0
  90. package/example/tokenization.ts +30 -0
  91. package/package.json +47 -0
  92. package/src/client.ts +1199 -0
  93. package/src/config.ts +68 -0
  94. package/src/encryption/encrypt-chat.ts +146 -0
  95. package/src/encryption/index.ts +21 -0
  96. package/src/encryption/key-agreement.ts +270 -0
  97. package/src/index.ts +10 -0
  98. package/src/types/ark.d.ts +9 -0
  99. package/src/types/bot.ts +127 -0
  100. package/src/types/chat-completion.ts +228 -0
  101. package/src/types/common.ts +37 -0
  102. package/src/types/content-generation.ts +135 -0
  103. package/src/types/context.ts +59 -0
  104. package/src/types/embeddings.ts +74 -0
  105. package/src/types/error.ts +93 -0
  106. package/src/types/file.ts +76 -0
  107. package/src/types/http-request-error.ts +34 -0
  108. package/src/types/images.ts +102 -0
  109. package/src/types/index.ts +12 -0
  110. package/src/types/multimodal-embedding.ts +67 -0
  111. package/src/types/responses/enums.ts +163 -0
  112. package/src/types/responses/helpers.ts +67 -0
  113. package/src/types/responses/index.ts +3 -0
  114. package/src/types/responses/types.ts +1335 -0
  115. package/src/types/tokenization.ts +24 -0
  116. package/src/utils/breaker-provider.ts +17 -0
  117. package/src/utils/breaker.ts +56 -0
  118. package/src/utils/normalize.ts +154 -0
  119. package/src/utils/request-builder.ts +51 -0
  120. package/src/utils/request-id.ts +17 -0
  121. package/src/utils/retry.ts +76 -0
  122. package/src/utils/sse-decoder.ts +140 -0
  123. package/src/utils/stream-reader.ts +270 -0
@@ -0,0 +1,1476 @@
1
+ import { __webpack_require__ } from "./rslib-runtime.mjs";
2
+ import axios from "axios";
3
+ import { createReadStream, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
4
+ import { Agent } from "https";
5
+ import { X509Certificate, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from "crypto";
6
+ import { join } from "path";
7
+ import { homedir } from "os";
8
+ var responses_namespaceObject = {};
9
+ __webpack_require__.r(responses_namespaceObject);
10
+ __webpack_require__.d(responses_namespaceObject, {
11
+ ContentItemType_input_audio: ()=>ContentItemType_input_audio,
12
+ ContentItemType_input_file: ()=>ContentItemType_input_file,
13
+ ContentItemType_input_image: ()=>ContentItemType_input_image,
14
+ ContentItemType_input_text: ()=>ContentItemType_input_text,
15
+ ContentItemType_input_video: ()=>ContentItemType_input_video,
16
+ ContentItemType_output_text: ()=>ContentItemType_output_text,
17
+ ContentItemType_summary_text: ()=>ContentItemType_summary_text,
18
+ MessageRole_assistant: ()=>MessageRole_assistant,
19
+ MessageRole_developer: ()=>MessageRole_developer,
20
+ MessageRole_system: ()=>"system",
21
+ MessageRole_user: ()=>"user",
22
+ getEventType: ()=>getEventType,
23
+ isDelta: ()=>isDelta,
24
+ isDeltaDone: ()=>isDeltaDone,
25
+ isResponseDone: ()=>isResponseDone
26
+ });
27
+ function genRequestId() {
28
+ const now = new Date();
29
+ const ts = now.getFullYear().toString() + String(now.getMonth() + 1).padStart(2, "0") + String(now.getDate()).padStart(2, "0") + String(now.getHours()).padStart(2, "0") + String(now.getMinutes()).padStart(2, "0") + String(now.getSeconds()).padStart(2, "0");
30
+ const hex = randomBytes(10).toString("hex");
31
+ return ts + hex;
32
+ }
33
+ function calculateRetryDelay(attemptNumber, minRetryDelay, maxRetryDelay) {
34
+ const base = Math.min(minRetryDelay * Math.pow(2, attemptNumber - 1), maxRetryDelay);
35
+ return Math.floor(Math.min(maxRetryDelay, base + Math.random() * base));
36
+ }
37
+ async function retry(policy, fn, isRetryable, signal) {
38
+ let lastError;
39
+ for(let attempt = 0; attempt <= policy.maxAttempts; attempt++)try {
40
+ return await fn();
41
+ } catch (err) {
42
+ lastError = err;
43
+ if (!isRetryable(err)) throw err;
44
+ if (attempt === policy.maxAttempts) break;
45
+ const delayMs = calculateRetryDelay(attempt + 1, policy.initialBackoffMs, policy.maxBackoffMs);
46
+ await sleep(delayMs, signal);
47
+ }
48
+ throw lastError;
49
+ }
50
+ function sleep(ms, signal) {
51
+ return new Promise((resolve, reject)=>{
52
+ if (signal?.aborted) return void reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
53
+ const timer = setTimeout(resolve, ms);
54
+ signal?.addEventListener("abort", ()=>{
55
+ clearTimeout(timer);
56
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
57
+ }, {
58
+ once: true
59
+ });
60
+ });
61
+ }
62
+ function _define_property(obj, key, value) {
63
+ if (key in obj) Object.defineProperty(obj, key, {
64
+ value: value,
65
+ enumerable: true,
66
+ configurable: true,
67
+ writable: true
68
+ });
69
+ else obj[key] = value;
70
+ return obj;
71
+ }
72
+ class Breaker {
73
+ allow(waitIndex) {
74
+ const elapsed = (Date.now() - this.allowTime) / 1000;
75
+ if (elapsed <= 0) return false;
76
+ if (elapsed > 10) return true;
77
+ return waitIndex < Math.pow(2, elapsed);
78
+ }
79
+ getAllowedDelayMs() {
80
+ const delay = this.allowTime - Date.now();
81
+ return delay < 1000 ? 1000 : delay;
82
+ }
83
+ reset(durationMs) {
84
+ this.allowTime = Date.now() + durationMs;
85
+ }
86
+ async wait() {
87
+ const id = String(this.nextIndex++);
88
+ const idx = this.waiters.size;
89
+ this.waiters.set(id, idx);
90
+ try {
91
+ while(!this.allow(idx))await new Promise((r)=>setTimeout(r, this.getAllowedDelayMs()));
92
+ } finally{
93
+ this.waiters.delete(id);
94
+ }
95
+ }
96
+ constructor(){
97
+ _define_property(this, "allowTime", void 0);
98
+ _define_property(this, "waiters", new Map());
99
+ _define_property(this, "nextIndex", 0);
100
+ this.allowTime = Date.now();
101
+ }
102
+ }
103
+ function breaker_provider_define_property(obj, key, value) {
104
+ if (key in obj) Object.defineProperty(obj, key, {
105
+ value: value,
106
+ enumerable: true,
107
+ configurable: true,
108
+ writable: true
109
+ });
110
+ else obj[key] = value;
111
+ return obj;
112
+ }
113
+ class ModelBreakerProvider {
114
+ getOrCreate(model) {
115
+ let breaker = this.breakers.get(model);
116
+ if (!breaker) {
117
+ breaker = new Breaker();
118
+ this.breakers.set(model, breaker);
119
+ }
120
+ return breaker;
121
+ }
122
+ constructor(){
123
+ breaker_provider_define_property(this, "breakers", new Map());
124
+ }
125
+ }
126
+ function sse_decoder_define_property(obj, key, value) {
127
+ if (key in obj) Object.defineProperty(obj, key, {
128
+ value: value,
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true
132
+ });
133
+ else obj[key] = value;
134
+ return obj;
135
+ }
136
+ var _computedKey;
137
+ _computedKey = Symbol.asyncIterator;
138
+ let _computedKey1 = _computedKey;
139
+ class EventStreamDecoder {
140
+ async *[_computedKey1]() {
141
+ const lines = this.readLines();
142
+ let event = "";
143
+ let dataLines = [];
144
+ for await (const line of lines){
145
+ if ("" === line) {
146
+ if (dataLines.length > 0) yield {
147
+ event,
148
+ data: dataLines.join("\n")
149
+ };
150
+ event = "";
151
+ dataLines = [];
152
+ continue;
153
+ }
154
+ if (line.startsWith(":")) continue;
155
+ const colonIdx = line.indexOf(":");
156
+ let field;
157
+ let value;
158
+ if (-1 === colonIdx) {
159
+ field = line;
160
+ value = "";
161
+ } else {
162
+ field = line.slice(0, colonIdx);
163
+ value = line.slice(colonIdx + 1);
164
+ if (value.startsWith(" ")) value = value.slice(1);
165
+ }
166
+ switch(field){
167
+ case "event":
168
+ event = value;
169
+ break;
170
+ case "data":
171
+ dataLines.push(value);
172
+ break;
173
+ }
174
+ }
175
+ if (dataLines.length > 0) yield {
176
+ event,
177
+ data: dataLines.join("\n")
178
+ };
179
+ }
180
+ async *readLines() {
181
+ const chunks = this.iterateStream();
182
+ for await (const chunk of chunks){
183
+ this.buffer += "string" == typeof chunk ? chunk : this.decoder.decode(chunk, {
184
+ stream: true
185
+ });
186
+ const lines = this.buffer.split("\n");
187
+ this.buffer = lines.pop() ?? "";
188
+ for (const line of lines)yield line.endsWith("\r") ? line.slice(0, -1) : line;
189
+ }
190
+ if (this.buffer.length > 0) {
191
+ yield this.buffer;
192
+ this.buffer = "";
193
+ }
194
+ }
195
+ async *iterateStream() {
196
+ const stream = this.stream;
197
+ if ("function" == typeof stream.getReader) {
198
+ this.reader = stream.getReader();
199
+ try {
200
+ while(true){
201
+ const { done, value } = await this.reader.read();
202
+ if (done) break;
203
+ if (value) yield value;
204
+ }
205
+ } finally{
206
+ this.reader.releaseLock();
207
+ this.reader = null;
208
+ }
209
+ return;
210
+ }
211
+ if (Symbol.asyncIterator in stream) {
212
+ for await (const chunk of stream)yield chunk;
213
+ return;
214
+ }
215
+ throw new Error("Unsupported stream type");
216
+ }
217
+ cancel() {
218
+ this.reader?.cancel();
219
+ }
220
+ constructor(stream){
221
+ sse_decoder_define_property(this, "stream", void 0);
222
+ sse_decoder_define_property(this, "reader", void 0);
223
+ sse_decoder_define_property(this, "decoder", void 0);
224
+ sse_decoder_define_property(this, "buffer", void 0);
225
+ this.stream = stream;
226
+ this.reader = null;
227
+ this.decoder = new TextDecoder();
228
+ this.buffer = "";
229
+ }
230
+ }
231
+ function http_request_error_define_property(obj, key, value) {
232
+ if (key in obj) Object.defineProperty(obj, key, {
233
+ value: value,
234
+ enumerable: true,
235
+ configurable: true,
236
+ writable: true
237
+ });
238
+ else obj[key] = value;
239
+ return obj;
240
+ }
241
+ class HttpRequestError extends Error {
242
+ constructor(name = "Exception", message, status, data, originalError){
243
+ super(message), http_request_error_define_property(this, "status", void 0), http_request_error_define_property(this, "data", void 0), http_request_error_define_property(this, "originalError", void 0), http_request_error_define_property(this, "name", void 0);
244
+ this.name = name;
245
+ this.status = status;
246
+ this.data = data;
247
+ this.originalError = originalError;
248
+ if (Error.captureStackTrace) Error.captureStackTrace(this, HttpRequestError);
249
+ }
250
+ }
251
+ function error_define_property(obj, key, value) {
252
+ if (key in obj) Object.defineProperty(obj, key, {
253
+ value: value,
254
+ enumerable: true,
255
+ configurable: true,
256
+ writable: true
257
+ });
258
+ else obj[key] = value;
259
+ return obj;
260
+ }
261
+ class ArkAPIError extends HttpRequestError {
262
+ get httpStatusCode() {
263
+ return this.status ?? 0;
264
+ }
265
+ toString() {
266
+ return `Error code: ${this.httpStatusCode} - ${JSON.stringify({
267
+ code: this.code,
268
+ message: this.message,
269
+ param: this.param,
270
+ type: this.type,
271
+ request_id: this.requestId
272
+ })}`;
273
+ }
274
+ constructor(opts){
275
+ super("ApiException", opts.message, opts.httpStatusCode, void 0, void 0), error_define_property(this, "code", void 0), error_define_property(this, "param", void 0), error_define_property(this, "type", void 0), error_define_property(this, "requestId", void 0);
276
+ this.name = "ArkAPIError";
277
+ this.code = opts.code;
278
+ this.param = opts.param;
279
+ this.type = opts.type;
280
+ this.requestId = opts.requestId;
281
+ }
282
+ }
283
+ class ArkRequestError extends HttpRequestError {
284
+ get httpStatusCode() {
285
+ return this.status ?? 0;
286
+ }
287
+ toString() {
288
+ return `RequestError code: ${this.httpStatusCode}, err: ${this.originalError?.message ?? this.message}, request_id: ${this.requestId}`;
289
+ }
290
+ constructor(opts){
291
+ super("NetworkError", opts.message, opts.httpStatusCode, void 0, opts.cause), error_define_property(this, "requestId", void 0);
292
+ this.name = "ArkRequestError";
293
+ this.requestId = opts.requestId;
294
+ }
295
+ }
296
+ const ErrTooManyEmptyStreamMessages = new Error("stream has sent too many empty messages");
297
+ const ErrChatCompletionStreamNotSupported = new Error("streaming is not supported with this method, please use CreateChatCompletionStream");
298
+ const ErrContentFieldsMisused = new Error("can't use both Content and MultiContent properties simultaneously");
299
+ const ErrBodyWithoutEndpoint = new Error("can't fetch endpoint sts token without endpoint");
300
+ const ErrBodyWithoutBot = new Error("can't fetch bot sts token without bot id");
301
+ const ErrAKSKNotSupported = new Error("ak&sk authentication is currently not supported for this method, please use api key instead");
302
+ const ErrBodyWithoutProjectName = new Error("project name is required for preset endpoint");
303
+ function key_agreement_define_property(obj, key, value) {
304
+ if (key in obj) Object.defineProperty(obj, key, {
305
+ value: value,
306
+ enumerable: true,
307
+ configurable: true,
308
+ writable: true
309
+ });
310
+ else obj[key] = value;
311
+ return obj;
312
+ }
313
+ const AES_KEY_SIZE = 32;
314
+ const AES_NONCE_SIZE = 12;
315
+ const CIPHER_VERSION_AICC_V01 = "AICCv01";
316
+ class KeyAgreementClient {
317
+ generateECIESKeyPair() {
318
+ const ecdh = createECDH("prime256v1");
319
+ ecdh.generateKeys();
320
+ const serverPubKeyDer = this.serverPublicKey.export({
321
+ type: "spki",
322
+ format: "der"
323
+ });
324
+ const serverPubKey = extractRawPublicKeyFromSPKI(serverPubKeyDer);
325
+ const sharedSecret = ecdh.computeSecret(serverPubKey);
326
+ const keyMaterial = hkdfExpand(sharedSecret, AES_KEY_SIZE + AES_NONCE_SIZE);
327
+ const sessionToken = ecdh.getPublicKey("base64");
328
+ return [
329
+ keyMaterial,
330
+ sessionToken
331
+ ];
332
+ }
333
+ constructor(pemCert){
334
+ key_agreement_define_property(this, "serverPublicKey", void 0);
335
+ const x509 = new X509Certificate(pemCert);
336
+ this.serverPublicKey = x509.publicKey;
337
+ }
338
+ }
339
+ function extractRawPublicKeyFromSPKI(spkiDer) {
340
+ const uncompressedKeyLen = 65;
341
+ if (spkiDer.length >= uncompressedKeyLen) return spkiDer.subarray(spkiDer.length - uncompressedKeyLen);
342
+ return spkiDer;
343
+ }
344
+ function hkdfExpand(ikm, length) {
345
+ const derivedKey = hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.alloc(0), length);
346
+ return Buffer.from(derivedKey);
347
+ }
348
+ function aesGcmEncrypt(key, nonce, plaintext) {
349
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
350
+ const encrypted = Buffer.concat([
351
+ cipher.update(plaintext),
352
+ cipher.final()
353
+ ]);
354
+ const tag = cipher.getAuthTag();
355
+ return Buffer.concat([
356
+ encrypted,
357
+ tag
358
+ ]);
359
+ }
360
+ function aesGcmDecrypt(key, nonce, ciphertext) {
361
+ const tagLength = 16;
362
+ const encrypted = ciphertext.subarray(0, ciphertext.length - tagLength);
363
+ const tag = ciphertext.subarray(ciphertext.length - tagLength);
364
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
365
+ decipher.setAuthTag(tag);
366
+ return Buffer.concat([
367
+ decipher.update(encrypted),
368
+ decipher.final()
369
+ ]);
370
+ }
371
+ function aesGcmEncryptBase64(key, nonce, plaintext) {
372
+ const encrypted = aesGcmEncrypt(key, nonce, Buffer.from(plaintext, "utf-8"));
373
+ return encrypted.toString("base64");
374
+ }
375
+ function aesGcmDecryptBase64(key, nonce, ciphertext) {
376
+ const cipherBuf = Buffer.from(ciphertext, "base64");
377
+ const decrypted = aesGcmDecrypt(key, nonce, cipherBuf);
378
+ return decrypted.toString("utf-8");
379
+ }
380
+ function getCertInfo(certPem) {
381
+ try {
382
+ const x509 = new X509Certificate(certPem);
383
+ const altNames = x509.subjectAltName ?? "";
384
+ const dnsNames = [];
385
+ for (const part of altNames.split(",")){
386
+ const trimmed = part.trim();
387
+ if (trimmed.startsWith("DNS:")) dnsNames.push(trimmed.substring(4));
388
+ }
389
+ const expireTime = Math.floor(new Date(x509.validTo).getTime() / 1000);
390
+ if (dnsNames.length > 1 && dnsNames[0].startsWith("ring.") && dnsNames[1].startsWith("key.")) return {
391
+ ringId: dnsNames[0].substring(5),
392
+ keyId: dnsNames[1].substring(4),
393
+ expireTime
394
+ };
395
+ return {
396
+ ringId: "",
397
+ keyId: "",
398
+ expireTime
399
+ };
400
+ } catch {
401
+ return {
402
+ ringId: "",
403
+ keyId: "",
404
+ expireTime: 0
405
+ };
406
+ }
407
+ }
408
+ function checkIsModeAICC() {
409
+ return "AICC" === process.env.VOLC_ARK_ENCRYPTION;
410
+ }
411
+ function loadLocalCertificate(model) {
412
+ if (!model || /[/\\:..]/.test(model)) return null;
413
+ const dir = join(homedir(), ".ark", "certificates");
414
+ const certPath = join(dir, `${model}.pem`);
415
+ try {
416
+ const stat = statSync(certPath);
417
+ const age = Date.now() - stat.mtimeMs;
418
+ if (age > 1209600000) {
419
+ unlinkSync(certPath);
420
+ return null;
421
+ }
422
+ const certPem = readFileSync(certPath, "utf-8");
423
+ const { ringId, keyId } = getCertInfo(certPem);
424
+ const aiccEnabled = checkIsModeAICC();
425
+ if (("" === ringId || "" === keyId) && !aiccEnabled) return certPem;
426
+ if ("" !== ringId && "" !== keyId && aiccEnabled) return certPem;
427
+ unlinkSync(certPath);
428
+ return null;
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+ function saveToLocalCertificate(model, certPem) {
434
+ if (!model || /[/\\:..]/.test(model)) return;
435
+ const dir = join(homedir(), ".ark", "certificates");
436
+ mkdirSync(dir, {
437
+ recursive: true
438
+ });
439
+ const certPath = join(dir, `${model}.pem`);
440
+ writeFileSync(certPath, certPem, "utf-8");
441
+ }
442
+ class E2eeClient {
443
+ generateECIESKeyPair() {
444
+ return this.cipher.generateECIESKeyPair();
445
+ }
446
+ getEncryptInfo() {
447
+ return JSON.stringify(this.info);
448
+ }
449
+ getExpireTime() {
450
+ return this.info.expire_time;
451
+ }
452
+ constructor(certificate){
453
+ key_agreement_define_property(this, "certificate", void 0);
454
+ key_agreement_define_property(this, "cipher", void 0);
455
+ key_agreement_define_property(this, "info", void 0);
456
+ key_agreement_define_property(this, "isAICC", void 0);
457
+ this.certificate = certificate;
458
+ this.cipher = new KeyAgreementClient(certificate);
459
+ const { ringId, keyId, expireTime } = getCertInfo(certificate);
460
+ this.info = {
461
+ expire_time: expireTime
462
+ };
463
+ this.isAICC = false;
464
+ if (ringId && keyId) {
465
+ this.info.version = CIPHER_VERSION_AICC_V01;
466
+ this.info.ring_id = ringId;
467
+ this.info.key_id = keyId;
468
+ this.isAICC = true;
469
+ }
470
+ }
471
+ }
472
+ const encrypt_chat_AES_KEY_SIZE = 32;
473
+ const encrypt_chat_AES_NONCE_SIZE = 12;
474
+ function encryptURL(urlString, fn) {
475
+ try {
476
+ const parsed = new URL(urlString);
477
+ if ([
478
+ "https:",
479
+ "http:",
480
+ "file:",
481
+ "ftp:"
482
+ ].includes(parsed.protocol)) return urlString;
483
+ } catch {}
484
+ if (urlString.startsWith("data:")) return fn(urlString);
485
+ return urlString;
486
+ }
487
+ function processMessageContent(content, fn) {
488
+ if (null == content) return content;
489
+ if ("string" == typeof content) return fn(content);
490
+ for (const part of content){
491
+ if ("text" === part.type && part.text) part.text = fn(part.text);
492
+ if ("image_url" === part.type && part.image_url?.url) part.image_url.url = encryptURL(part.image_url.url, fn);
493
+ }
494
+ return content;
495
+ }
496
+ function deepCopyRequest(request) {
497
+ return JSON.parse(JSON.stringify(request));
498
+ }
499
+ function encryptChatRequest(keyNonce, request) {
500
+ if (keyNonce.length !== encrypt_chat_AES_KEY_SIZE + encrypt_chat_AES_NONCE_SIZE) throw new Error(`keyNonce must be ${encrypt_chat_AES_KEY_SIZE + encrypt_chat_AES_NONCE_SIZE} bytes, got ${keyNonce.length}`);
501
+ const key = keyNonce.subarray(0, encrypt_chat_AES_KEY_SIZE);
502
+ const nonce = keyNonce.subarray(encrypt_chat_AES_KEY_SIZE);
503
+ const fn = (text)=>aesGcmEncryptBase64(key, nonce, text);
504
+ for (const msg of request.messages ?? [])if (null != msg.content) msg.content = processMessageContent(msg.content, fn);
505
+ }
506
+ function decryptChatResponse(keyNonce, response) {
507
+ if (keyNonce.length !== encrypt_chat_AES_KEY_SIZE + encrypt_chat_AES_NONCE_SIZE) throw new Error(`keyNonce must be ${encrypt_chat_AES_KEY_SIZE + encrypt_chat_AES_NONCE_SIZE} bytes, got ${keyNonce.length}`);
508
+ const key = keyNonce.subarray(0, encrypt_chat_AES_KEY_SIZE);
509
+ const nonce = keyNonce.subarray(encrypt_chat_AES_KEY_SIZE);
510
+ const fn = (text)=>aesGcmDecryptBase64(key, nonce, text);
511
+ for (const choice of response.choices ?? [])if ("content_filter" !== choice.finish_reason) {
512
+ if (choice.message?.content != null) choice.message.content = processMessageContent(choice.message.content, fn);
513
+ }
514
+ }
515
+ function decryptChatStreamResponse(keyNonce, response) {
516
+ if (keyNonce.length !== encrypt_chat_AES_KEY_SIZE + encrypt_chat_AES_NONCE_SIZE) throw new Error(`keyNonce must be ${encrypt_chat_AES_KEY_SIZE + encrypt_chat_AES_NONCE_SIZE} bytes, got ${keyNonce.length}`);
517
+ const key = keyNonce.subarray(0, encrypt_chat_AES_KEY_SIZE);
518
+ const nonce = keyNonce.subarray(encrypt_chat_AES_KEY_SIZE);
519
+ const fn = (text)=>aesGcmDecryptBase64(key, nonce, text);
520
+ for (const choice of response.choices ?? [])if ("content_filter" !== choice.finish_reason) {
521
+ if (choice.delta?.content && "string" == typeof choice.delta.content) choice.delta.content = fn(choice.delta.content);
522
+ }
523
+ }
524
+ function normalizeChatCompletionResponse(resp) {
525
+ if (resp.choices) for (const choice of resp.choices)normalizeChatCompletionChoice(choice);
526
+ return resp;
527
+ }
528
+ function normalizeChatCompletionChoice(choice) {
529
+ if (choice.message && !("name" in choice.message)) choice.message.name = null;
530
+ if ("logprobs" in choice && (null === choice.logprobs || void 0 === choice.logprobs)) delete choice.logprobs;
531
+ if (!("finish_reason" in choice)) choice.finish_reason = null;
532
+ }
533
+ function normalizeChatCompletionStreamChunk(chunk) {
534
+ if (chunk.choices) for (const choice of chunk.choices)normalizeStreamChoice(choice);
535
+ if ("usage" in chunk && (null === chunk.usage || void 0 === chunk.usage)) delete chunk.usage;
536
+ return chunk;
537
+ }
538
+ function normalizeStreamChoice(choice) {
539
+ if (!("finish_reason" in choice)) choice.finish_reason = null;
540
+ if ("logprobs" in choice && (null === choice.logprobs || void 0 === choice.logprobs)) delete choice.logprobs;
541
+ if (choice.delta) {
542
+ if ("content" in choice.delta && "" === choice.delta.content) delete choice.delta.content;
543
+ if ("role" in choice.delta && "" === choice.delta.role) delete choice.delta.role;
544
+ }
545
+ }
546
+ function normalizeEmbeddingResponse(resp) {
547
+ if (resp.usage) normalizeUsage(resp.usage);
548
+ return resp;
549
+ }
550
+ function normalizeUsage(usage) {
551
+ if (void 0 === usage.completion_tokens || null === usage.completion_tokens) usage.completion_tokens = 0;
552
+ if (!usage.prompt_tokens_details) usage.prompt_tokens_details = {
553
+ cached_tokens: 0
554
+ };
555
+ if (!usage.completion_tokens_details) usage.completion_tokens_details = {
556
+ reasoning_tokens: 0
557
+ };
558
+ }
559
+ function stream_reader_define_property(obj, key, value) {
560
+ if (key in obj) Object.defineProperty(obj, key, {
561
+ value: value,
562
+ enumerable: true,
563
+ configurable: true,
564
+ writable: true
565
+ });
566
+ else obj[key] = value;
567
+ return obj;
568
+ }
569
+ var stream_reader_computedKey, stream_reader_computedKey1, _computedKey2, _computedKey3;
570
+ const ERROR_PREFIX = '{"error":';
571
+ class BaseStreamReader {
572
+ close() {
573
+ this.isFinished = true;
574
+ this.cleanup?.();
575
+ this.cleanup = void 0;
576
+ }
577
+ constructor(stream, emptyMessagesLimit, headers, cleanup){
578
+ stream_reader_define_property(this, "stream", void 0);
579
+ stream_reader_define_property(this, "emptyMessagesLimit", void 0);
580
+ stream_reader_define_property(this, "headers", void 0);
581
+ stream_reader_define_property(this, "isFinished", void 0);
582
+ stream_reader_define_property(this, "emptyMessagesCount", void 0);
583
+ stream_reader_define_property(this, "cleanup", void 0);
584
+ this.stream = stream;
585
+ this.emptyMessagesLimit = emptyMessagesLimit;
586
+ this.headers = headers;
587
+ this.isFinished = false;
588
+ this.emptyMessagesCount = 0;
589
+ this.cleanup = cleanup;
590
+ }
591
+ }
592
+ stream_reader_computedKey = Symbol.asyncIterator;
593
+ let _computedKey4 = stream_reader_computedKey;
594
+ class DataLineStreamReader extends BaseStreamReader {
595
+ async *[_computedKey4]() {
596
+ const chunks = this.iterateChunks();
597
+ let errBuffer = "";
598
+ let hasError = false;
599
+ for await (const rawLine of this.readLines(chunks)){
600
+ if (this.isFinished) return;
601
+ const trimmed = rawLine.trim();
602
+ if ("" === trimmed) continue;
603
+ let dataContent = null;
604
+ if (trimmed.startsWith("data:")) dataContent = trimmed.slice(5).trim();
605
+ if (dataContent && dataContent.startsWith(ERROR_PREFIX)) {
606
+ hasError = true;
607
+ errBuffer += dataContent;
608
+ continue;
609
+ }
610
+ if (hasError) {
611
+ errBuffer += trimmed.startsWith("data:") ? trimmed.slice(5).trim() : trimmed;
612
+ continue;
613
+ }
614
+ if (null === dataContent) {
615
+ this.emptyMessagesCount++;
616
+ if (this.emptyMessagesCount > this.emptyMessagesLimit) throw ErrTooManyEmptyStreamMessages;
617
+ continue;
618
+ }
619
+ if ("[DONE]" === dataContent) return void this.close();
620
+ const parsed = JSON.parse(dataContent);
621
+ this.emptyMessagesCount = 0;
622
+ yield parsed;
623
+ }
624
+ if (hasError && errBuffer) {
625
+ const errResp = JSON.parse(errBuffer);
626
+ if (errResp.error) throw new ArkAPIError({
627
+ message: errResp.error.message,
628
+ code: errResp.error.code,
629
+ param: errResp.error.param,
630
+ type: errResp.error.type,
631
+ httpStatusCode: 0,
632
+ requestId: errResp.error.request_id ?? this.headers?.["x-client-request-id"] ?? ""
633
+ });
634
+ }
635
+ }
636
+ async *readLines(chunks) {
637
+ for await (const chunk of chunks){
638
+ this.buffer += chunk;
639
+ const lines = this.buffer.split("\n");
640
+ this.buffer = lines.pop() ?? "";
641
+ for (const line of lines)yield line;
642
+ }
643
+ if (this.buffer) {
644
+ yield this.buffer;
645
+ this.buffer = "";
646
+ }
647
+ }
648
+ async *iterateChunks() {
649
+ const stream = this.stream;
650
+ if ("function" == typeof stream.getReader) {
651
+ const reader = stream.getReader();
652
+ try {
653
+ while(true){
654
+ const { done, value } = await reader.read();
655
+ if (done) break;
656
+ yield "string" == typeof value ? value : this.decoder.decode(value, {
657
+ stream: true
658
+ });
659
+ }
660
+ } finally{
661
+ reader.releaseLock();
662
+ }
663
+ } else if (Symbol.asyncIterator in stream) for await (const chunk of stream)yield "string" == typeof chunk ? chunk : this.decoder.decode(chunk, {
664
+ stream: true
665
+ });
666
+ }
667
+ constructor(...args){
668
+ super(...args), stream_reader_define_property(this, "decoder", new TextDecoder()), stream_reader_define_property(this, "buffer", "");
669
+ }
670
+ }
671
+ stream_reader_computedKey1 = Symbol.asyncIterator;
672
+ let _computedKey5 = stream_reader_computedKey1;
673
+ class ChatCompletionStreamReader extends DataLineStreamReader {
674
+ async *[_computedKey5]() {
675
+ for await (const chunk of this.iterateBase()){
676
+ if (this.keyNonce.length > 0) decryptChatStreamResponse(this.keyNonce, chunk);
677
+ yield normalizeChatCompletionStreamChunk(chunk);
678
+ }
679
+ }
680
+ async *iterateBase() {
681
+ yield* super[Symbol.asyncIterator]();
682
+ }
683
+ constructor(stream, emptyMessagesLimit, headers, keyNonce, cleanup){
684
+ super(stream, emptyMessagesLimit, headers, cleanup), stream_reader_define_property(this, "keyNonce", void 0);
685
+ this.keyNonce = keyNonce ?? Buffer.alloc(0);
686
+ }
687
+ }
688
+ _computedKey2 = Symbol.asyncIterator;
689
+ class BotChatCompletionStreamReader extends DataLineStreamReader {
690
+ async *[_computedKey2]() {
691
+ for await (const chunk of this.iterateBase())yield normalizeChatCompletionStreamChunk(chunk);
692
+ }
693
+ async *iterateBase() {
694
+ yield* super[Symbol.asyncIterator]();
695
+ }
696
+ }
697
+ class ImageGenerationStreamReader extends DataLineStreamReader {
698
+ }
699
+ _computedKey3 = Symbol.asyncIterator;
700
+ let _computedKey6 = _computedKey3;
701
+ class ResponsesStreamReader extends BaseStreamReader {
702
+ async *[_computedKey6]() {
703
+ for await (const sseEvent of this.decoder){
704
+ if (this.isFinished) return;
705
+ const data = sseEvent.data.trim();
706
+ if (data.startsWith(ERROR_PREFIX)) {
707
+ const errResp = JSON.parse(data);
708
+ if (errResp.error) throw new ArkAPIError({
709
+ message: errResp.error.message,
710
+ code: errResp.error.code,
711
+ param: errResp.error.param,
712
+ type: errResp.error.type,
713
+ httpStatusCode: 0,
714
+ requestId: errResp.error.request_id ?? this.headers?.["x-client-request-id"] ?? ""
715
+ });
716
+ continue;
717
+ }
718
+ if (data.startsWith("[DONE]")) return void this.close();
719
+ const parsed = JSON.parse(data);
720
+ yield parsed;
721
+ }
722
+ }
723
+ close() {
724
+ super.close();
725
+ this.decoder.cancel();
726
+ }
727
+ constructor(stream, emptyMessagesLimit, headers, cleanup){
728
+ super(stream, emptyMessagesLimit, headers, cleanup), stream_reader_define_property(this, "decoder", void 0);
729
+ this.decoder = new EventStreamDecoder(stream);
730
+ }
731
+ }
732
+ const defaultBaseURL = "https://ark.cn-beijing.volces.com/api/v3";
733
+ const defaultRegion = "cn-beijing";
734
+ const defaultEmptyMessagesLimit = 300;
735
+ const defaultRetryTimes = 2;
736
+ const defaultTimeoutMs = 600000;
737
+ const defaultBatchMaxParallel = 3000;
738
+ const resourceTypeEndpoint = "endpoint";
739
+ const resourceTypePresetEndpoint = "presetendpoint";
740
+ function resolveConfig(config) {
741
+ let baseURL = config.baseURL ?? process.env.ARK_BASE_URL ?? defaultBaseURL;
742
+ if (baseURL.endsWith("/")) baseURL = baseURL.slice(0, -1);
743
+ return {
744
+ apiKey: config.apiKey ?? process.env.ARK_API_KEY ?? "",
745
+ ak: config.ak ?? "",
746
+ sk: config.sk ?? "",
747
+ region: config.region ?? defaultRegion,
748
+ baseURL,
749
+ httpClient: config.httpClient,
750
+ emptyMessagesLimit: config.emptyMessagesLimit ?? defaultEmptyMessagesLimit,
751
+ retryTimes: config.retryTimes ?? defaultRetryTimes,
752
+ timeout: config.timeout ?? defaultTimeoutMs,
753
+ batchMaxParallel: config.batchMaxParallel ?? defaultBatchMaxParallel
754
+ };
755
+ }
756
+ const ClientRequestHeader = "X-Client-Request-Id";
757
+ const RetryAfterHeader = "Retry-After";
758
+ const ClientSessionTokenHeader = "X-Session-Token";
759
+ const ClientEncryptInfoHeader = "X-Encrypt-Info";
760
+ const ClientIsEncryptedHeader = "x-is-encrypted";
761
+ const PurposeUserData = "user_data";
762
+ const FileStatusProcessing = "processing";
763
+ function client_define_property(obj, key, value) {
764
+ if (key in obj) Object.defineProperty(obj, key, {
765
+ value: value,
766
+ enumerable: true,
767
+ configurable: true,
768
+ writable: true
769
+ });
770
+ else obj[key] = value;
771
+ return obj;
772
+ }
773
+ const chatCompletionsSuffix = "/chat/completions";
774
+ const botChatCompletionsSuffix = "/bots/chat/completions";
775
+ const embeddingsSuffix = "/embeddings";
776
+ const multimodalEmbeddingsSuffix = "/embeddings/multimodal";
777
+ const generateImagesPath = "/images/generations";
778
+ const tokenizationSuffix = "/tokenization";
779
+ const contextCreateSuffix = "/context/create";
780
+ const contextChatSuffix = "/context/chat/completions";
781
+ const contentGenerationTaskPath = "/contents/generations/tasks";
782
+ const filePrefix = "/files";
783
+ const batchChatCompletionsSuffix = "/batch/chat/completions";
784
+ const batchEmbeddingsSuffix = "/batch/embeddings";
785
+ const batchMultiModalEmbeddingsSuffix = "/batch/embeddings/multimodal";
786
+ const e2eGetCertificatePath = "/e2e/get/certificate";
787
+ const FILE_SCHEME = "file";
788
+ const POLL_INTERVAL_MS = 3000;
789
+ const MAX_WAIT_TIME_MS = 600000;
790
+ class ArkRuntimeClient {
791
+ static withApiKey(apiKey, config = {}) {
792
+ return new ArkRuntimeClient({
793
+ ...config,
794
+ apiKey
795
+ });
796
+ }
797
+ static withAkSk(ak, sk, config = {}) {
798
+ return new ArkRuntimeClient({
799
+ ...config,
800
+ ak,
801
+ sk
802
+ });
803
+ }
804
+ fullURL(suffix) {
805
+ return `${this.config.baseURL}${suffix}`;
806
+ }
807
+ isAPIKeyAuth() {
808
+ return this.config.apiKey.length > 0;
809
+ }
810
+ getResourceTypeById(resourceId) {
811
+ if (resourceId.startsWith("ep-m-")) return resourceTypePresetEndpoint;
812
+ if (resourceId.startsWith("ep-")) return resourceTypeEndpoint;
813
+ if (resourceId.startsWith("bot-")) return "bot";
814
+ return resourceTypePresetEndpoint;
815
+ }
816
+ stsKey(resourceType, resourceId) {
817
+ return `${resourceType}#${resourceId}`;
818
+ }
819
+ needRefresh(resourceType, resourceId, delta) {
820
+ const info = this.resourceStsTokens.get(this.stsKey(resourceType, resourceId));
821
+ if (!info) return true;
822
+ return info.expiredTime - Math.floor(Date.now() / 1000) < delta;
823
+ }
824
+ async refreshToken(resourceType, resourceId, projectName) {
825
+ if (!this.needRefresh(resourceType, resourceId, this.advisoryRefreshTimeout)) return;
826
+ if (this.refreshPromise) {
827
+ await this.refreshPromise;
828
+ if (!this.needRefresh(resourceType, resourceId, this.advisoryRefreshTimeout)) return;
829
+ }
830
+ this.refreshPromise = this.doRefresh(resourceType, resourceId, projectName);
831
+ try {
832
+ await this.refreshPromise;
833
+ } finally{
834
+ this.refreshPromise = null;
835
+ }
836
+ }
837
+ async doRefresh(resourceType, resourceId, projectName) {
838
+ try {
839
+ const { ARKClient } = await import("@volcengine/ark");
840
+ const { GetApiKeyCommand } = await import("@volcengine/ark");
841
+ const arkClient = new ARKClient({
842
+ accessKeyId: this.config.ak,
843
+ secretAccessKey: this.config.sk,
844
+ region: this.config.region
845
+ });
846
+ const input = {
847
+ DurationSeconds: 604800,
848
+ ResourceIds: [
849
+ resourceId
850
+ ],
851
+ ResourceType: resourceType,
852
+ ...projectName ? {
853
+ ProjectName: projectName
854
+ } : {}
855
+ };
856
+ const resp = await arkClient.send(new GetApiKeyCommand(input));
857
+ const result = resp.Result;
858
+ if (result?.ApiKey && result?.ExpiredTime) this.resourceStsTokens.set(this.stsKey(resourceType, resourceId), {
859
+ token: result.ApiKey,
860
+ expiredTime: result.ExpiredTime
861
+ });
862
+ } catch (err) {
863
+ const isMandatory = this.needRefresh(resourceType, resourceId, this.mandatoryRefreshTimeout);
864
+ if (isMandatory) throw err;
865
+ }
866
+ }
867
+ async getEndpointStsToken(endpointId) {
868
+ return this.getResourceStsToken(resourceTypeEndpoint, endpointId);
869
+ }
870
+ async getResourceStsToken(resourceType, resourceId, projectName) {
871
+ await this.refreshToken(resourceType, resourceId, projectName ?? "");
872
+ const info = this.resourceStsTokens.get(this.stsKey(resourceType, resourceId));
873
+ return info?.token ?? "";
874
+ }
875
+ async getAuthHeader(resourceType, resourceId, projectName) {
876
+ if (this.isAPIKeyAuth()) return {
877
+ Authorization: `Bearer ${this.config.apiKey}`
878
+ };
879
+ resourceType = this.getResourceTypeById(resourceId);
880
+ await this.refreshToken(resourceType, resourceId, projectName ?? "");
881
+ const info = this.resourceStsTokens.get(this.stsKey(resourceType, resourceId));
882
+ return {
883
+ Authorization: `Bearer ${info?.token ?? ""}`
884
+ };
885
+ }
886
+ retryPolicy() {
887
+ return {
888
+ maxAttempts: this.config.retryTimes,
889
+ initialBackoffMs: 500,
890
+ maxBackoffMs: 8000
891
+ };
892
+ }
893
+ isRetryable(err) {
894
+ if (err instanceof ArkAPIError) return err.httpStatusCode >= 500 || 429 === err.httpStatusCode;
895
+ if (err instanceof ArkRequestError) return err.httpStatusCode >= 500;
896
+ return false;
897
+ }
898
+ async executeRequest(method, url, resourceType, resourceId, opts) {
899
+ const authHeader = await this.getAuthHeader(resourceType, resourceId, opts?.projectName);
900
+ const requestId = genRequestId();
901
+ const headers = {
902
+ [ClientRequestHeader]: requestId,
903
+ "Content-Type": "application/json",
904
+ Accept: opts?.stream ? "text/event-stream" : "application/json",
905
+ ...authHeader,
906
+ ...opts?.customHeaders
907
+ };
908
+ if (opts?.stream) {
909
+ headers["Cache-Control"] = "no-cache";
910
+ headers["Connection"] = "keep-alive";
911
+ }
912
+ if (opts?.projectName) headers["X-Project-Name"] = opts.projectName;
913
+ const axiosConfig = {
914
+ method: method,
915
+ url,
916
+ headers,
917
+ data: opts?.body,
918
+ params: opts?.query,
919
+ signal: opts?.signal,
920
+ responseType: opts?.stream ? "stream" : "json",
921
+ validateStatus: ()=>true
922
+ };
923
+ const resp = await this.httpClient.request(axiosConfig);
924
+ if (resp.status < 200 || resp.status >= 400) this.handleErrorResponse(resp, requestId);
925
+ return resp;
926
+ }
927
+ handleErrorResponse(resp, requestId) {
928
+ let errData;
929
+ try {
930
+ errData = "string" == typeof resp.data ? JSON.parse(resp.data) : resp.data;
931
+ } catch {
932
+ throw new ArkRequestError({
933
+ httpStatusCode: resp.status,
934
+ message: `Request failed with status ${resp.status}`,
935
+ requestId
936
+ });
937
+ }
938
+ if (errData?.error) throw new ArkAPIError({
939
+ message: errData.error.message ?? "Unknown error",
940
+ code: errData.error.code,
941
+ param: errData.error.param,
942
+ type: errData.error.type ?? "unknown",
943
+ httpStatusCode: resp.status,
944
+ requestId: errData.error.request_id ?? resp.headers?.[ClientRequestHeader.toLowerCase()] ?? requestId
945
+ });
946
+ throw new ArkRequestError({
947
+ httpStatusCode: resp.status,
948
+ message: `Request failed with status ${resp.status}`,
949
+ requestId
950
+ });
951
+ }
952
+ async getE2eeClient(resourceId, authorization) {
953
+ const cached = this.e2eeManager.get(resourceId);
954
+ if (cached && cached.isAICC === checkIsModeAICC()) return cached;
955
+ const existing = this.e2eeFlightMap.get(resourceId);
956
+ if (existing) return existing;
957
+ const promise = this.doLoadE2eeClient(resourceId, authorization);
958
+ this.e2eeFlightMap.set(resourceId, promise);
959
+ try {
960
+ const client = await promise;
961
+ return client;
962
+ } finally{
963
+ this.e2eeFlightMap.delete(resourceId);
964
+ }
965
+ }
966
+ async doLoadE2eeClient(resourceId, authorization) {
967
+ const cached = this.e2eeManager.get(resourceId);
968
+ if (cached && cached.isAICC === checkIsModeAICC()) return cached;
969
+ let certPem = loadLocalCertificate(resourceId);
970
+ if (!certPem) {
971
+ certPem = await this.loadServerCertificate(resourceId, authorization);
972
+ saveToLocalCertificate(resourceId, certPem);
973
+ }
974
+ const client = new E2eeClient(certPem);
975
+ this.e2eeManager.set(resourceId, client);
976
+ return client;
977
+ }
978
+ async loadServerCertificate(resourceId, authorization) {
979
+ const url = this.fullURL(e2eGetCertificatePath);
980
+ const body = {
981
+ model: resourceId
982
+ };
983
+ if (checkIsModeAICC()) body.type = "AICCv0.1";
984
+ const resp = await this.httpClient.request({
985
+ method: "POST",
986
+ url,
987
+ headers: {
988
+ "Content-Type": "application/json",
989
+ Accept: "application/json",
990
+ Authorization: authorization,
991
+ [ClientSessionTokenHeader]: e2eGetCertificatePath
992
+ },
993
+ data: body,
994
+ validateStatus: ()=>true
995
+ });
996
+ if (resp.status < 200 || resp.status >= 400) throw new Error(`getting Certificate failed: HTTP ${resp.status}`);
997
+ const cr = resp.data;
998
+ if (cr.error && Object.keys(cr.error).length > 0) throw new Error(`getting Certificate failed: ${JSON.stringify(cr.error)}`);
999
+ return cr.Certificate;
1000
+ }
1001
+ async encryptRequestBody(resourceId, requestId, authorization, request) {
1002
+ const e2eeClient = await this.getE2eeClient(resourceId, authorization);
1003
+ const [keyNonce, sessionToken] = e2eeClient.generateECIESKeyPair();
1004
+ const extraHeaders = {
1005
+ [ClientSessionTokenHeader]: sessionToken
1006
+ };
1007
+ if (checkIsModeAICC()) extraHeaders[ClientEncryptInfoHeader] = e2eeClient.getEncryptInfo();
1008
+ this.keyNonceMap.set(requestId, keyNonce);
1009
+ const requestCopy = deepCopyRequest(request);
1010
+ encryptChatRequest(keyNonce, requestCopy);
1011
+ return {
1012
+ body: requestCopy,
1013
+ extraHeaders
1014
+ };
1015
+ }
1016
+ async preprocessResponseInput(input) {
1017
+ if (!input || "string" == typeof input || !Array.isArray(input)) return;
1018
+ await this.preprocessResponseMultiModal(input);
1019
+ }
1020
+ async preprocessResponseMultiModal(inputItems) {
1021
+ const tasks = [];
1022
+ for (const item of inputItems){
1023
+ if (!item || "message" !== item.type && !("role" in item && "content" in item)) continue;
1024
+ const inputMessage = item;
1025
+ if (inputMessage.content && Array.isArray(inputMessage.content)) for (const contentItem of inputMessage.content){
1026
+ const fileUrl = this.getMultiModalFileUrl(contentItem);
1027
+ if (fileUrl) tasks.push(this.preprocessResponseFile(contentItem, fileUrl));
1028
+ }
1029
+ }
1030
+ if (tasks.length > 0) await Promise.all(tasks);
1031
+ }
1032
+ getMultiModalFileUrl(contentItem) {
1033
+ if ("input_video" === contentItem.type) {
1034
+ const video = contentItem;
1035
+ if (video.video_url) return video.video_url;
1036
+ } else if ("input_image" === contentItem.type) {
1037
+ const image = contentItem;
1038
+ if (image.image_url) return image.image_url;
1039
+ } else if ("input_file" === contentItem.type) {
1040
+ const file = contentItem;
1041
+ if (file.file_url) return file.file_url;
1042
+ }
1043
+ return null;
1044
+ }
1045
+ parseFileUrl(rawUrl) {
1046
+ try {
1047
+ const parsed = new URL(rawUrl);
1048
+ if (parsed.protocol !== `${FILE_SCHEME}:`) return null;
1049
+ return parsed.pathname;
1050
+ } catch {
1051
+ return null;
1052
+ }
1053
+ }
1054
+ async preprocessResponseFile(contentItem, rawUrl) {
1055
+ const localPath = this.parseFileUrl(rawUrl);
1056
+ if (!localPath) return;
1057
+ const fileStream = createReadStream(localPath);
1058
+ try {
1059
+ let fileMeta = await this.uploadFile({
1060
+ file: fileStream,
1061
+ purpose: PurposeUserData
1062
+ });
1063
+ const deadline = Date.now() + MAX_WAIT_TIME_MS;
1064
+ while(fileMeta.status === FileStatusProcessing && Date.now() < deadline){
1065
+ await new Promise((resolve)=>setTimeout(resolve, POLL_INTERVAL_MS));
1066
+ fileMeta = await this.retrieveFile(fileMeta.id);
1067
+ }
1068
+ if ("input_video" === contentItem.type) {
1069
+ const video = contentItem;
1070
+ video.video_url = "";
1071
+ video.file_id = fileMeta.id;
1072
+ } else if ("input_image" === contentItem.type) {
1073
+ const image = contentItem;
1074
+ delete image.image_url;
1075
+ image.file_id = fileMeta.id;
1076
+ } else if ("input_file" === contentItem.type) {
1077
+ const file = contentItem;
1078
+ delete file.file_url;
1079
+ file.file_id = fileMeta.id;
1080
+ }
1081
+ } finally{
1082
+ fileStream.destroy();
1083
+ }
1084
+ }
1085
+ async doRequest(method, url, resourceType, resourceId, opts) {
1086
+ return retry(this.retryPolicy(), async ()=>{
1087
+ const resp = await this.executeRequest(method, url, resourceType, resourceId, opts);
1088
+ return resp.data;
1089
+ }, (err)=>this.isRetryable(err), opts?.signal);
1090
+ }
1091
+ async doStreamRequest(method, url, resourceType, resourceId, opts) {
1092
+ const resp = await retry(this.retryPolicy(), async ()=>this.executeRequest(method, url, resourceType, resourceId, {
1093
+ ...opts,
1094
+ stream: true
1095
+ }), (err)=>this.isRetryable(err), opts?.signal);
1096
+ const headers = {};
1097
+ if (resp.headers) {
1098
+ for (const [k, v] of Object.entries(resp.headers))if ("string" == typeof v) headers[k] = v;
1099
+ }
1100
+ return {
1101
+ stream: resp.data,
1102
+ headers
1103
+ };
1104
+ }
1105
+ async createChatCompletion(request, opts) {
1106
+ if (request.stream) throw ErrChatCompletionStreamNotSupported;
1107
+ const resp = await this.doRequest("POST", this.fullURL(chatCompletionsSuffix), resourceTypeEndpoint, request.model, {
1108
+ ...opts,
1109
+ body: request
1110
+ });
1111
+ return normalizeChatCompletionResponse(resp);
1112
+ }
1113
+ async createChatCompletionStream(request, opts) {
1114
+ let body = {
1115
+ ...request,
1116
+ stream: true
1117
+ };
1118
+ let extraHeaders;
1119
+ const isEncrypted = opts?.customHeaders?.[ClientIsEncryptedHeader] === "true";
1120
+ const requestId = genRequestId();
1121
+ if (isEncrypted) {
1122
+ const authHeader = await this.getAuthHeader(resourceTypeEndpoint, request.model, opts?.projectName);
1123
+ const result = await this.encryptRequestBody(request.model, requestId, authHeader.Authorization, body);
1124
+ body = result.body;
1125
+ extraHeaders = result.extraHeaders;
1126
+ }
1127
+ const mergedOpts = {
1128
+ ...opts,
1129
+ body,
1130
+ customHeaders: {
1131
+ ...opts?.customHeaders,
1132
+ ...extraHeaders
1133
+ }
1134
+ };
1135
+ const { stream, headers } = await this.doStreamRequest("POST", this.fullURL(chatCompletionsSuffix), resourceTypeEndpoint, request.model, mergedOpts);
1136
+ const keyNonce = this.keyNonceMap.get(requestId);
1137
+ const cleanup = keyNonce ? ()=>{
1138
+ this.keyNonceMap.delete(requestId);
1139
+ } : void 0;
1140
+ return new ChatCompletionStreamReader(stream, this.config.emptyMessagesLimit, headers, keyNonce, cleanup);
1141
+ }
1142
+ async createBotChatCompletion(request, opts) {
1143
+ if (request.stream) throw ErrChatCompletionStreamNotSupported;
1144
+ const model = request.bot_id || request.model;
1145
+ const resp = await this.doRequest("POST", this.fullURL(botChatCompletionsSuffix), "bot", model, {
1146
+ ...opts,
1147
+ body: {
1148
+ ...request,
1149
+ model
1150
+ }
1151
+ });
1152
+ return normalizeChatCompletionResponse(resp);
1153
+ }
1154
+ async createBotChatCompletionStream(request, opts) {
1155
+ const model = request.bot_id || request.model;
1156
+ const body = {
1157
+ ...request,
1158
+ model,
1159
+ stream: true
1160
+ };
1161
+ const { stream, headers } = await this.doStreamRequest("POST", this.fullURL(botChatCompletionsSuffix), "bot", model, {
1162
+ ...opts,
1163
+ body
1164
+ });
1165
+ return new BotChatCompletionStreamReader(stream, this.config.emptyMessagesLimit, headers);
1166
+ }
1167
+ async createEmbeddings(request, opts) {
1168
+ const resp = await this.doRequest("POST", this.fullURL(embeddingsSuffix), resourceTypeEndpoint, request.model, {
1169
+ ...opts,
1170
+ body: request
1171
+ });
1172
+ return normalizeEmbeddingResponse(resp);
1173
+ }
1174
+ async createMultiModalEmbeddings(request, opts) {
1175
+ return this.doRequest("POST", this.fullURL(multimodalEmbeddingsSuffix), resourceTypeEndpoint, request.model, {
1176
+ ...opts,
1177
+ body: request
1178
+ });
1179
+ }
1180
+ async generateImages(request, opts) {
1181
+ if (!this.isAPIKeyAuth()) throw ErrAKSKNotSupported;
1182
+ return this.doRequest("POST", this.fullURL(generateImagesPath), resourceTypeEndpoint, request.model, {
1183
+ ...opts,
1184
+ body: request
1185
+ });
1186
+ }
1187
+ async generateImagesStream(request, opts) {
1188
+ if (!this.isAPIKeyAuth()) throw ErrAKSKNotSupported;
1189
+ const body = {
1190
+ ...request,
1191
+ stream: true
1192
+ };
1193
+ const { stream, headers } = await this.doStreamRequest("POST", this.fullURL(generateImagesPath), resourceTypeEndpoint, request.model, {
1194
+ ...opts,
1195
+ body
1196
+ });
1197
+ return new ImageGenerationStreamReader(stream, this.config.emptyMessagesLimit, headers);
1198
+ }
1199
+ async createTokenization(request, opts) {
1200
+ return this.doRequest("POST", this.fullURL(tokenizationSuffix), resourceTypeEndpoint, request.model, {
1201
+ ...opts,
1202
+ body: request
1203
+ });
1204
+ }
1205
+ async createContext(request, opts) {
1206
+ return this.doRequest("POST", this.fullURL(contextCreateSuffix), resourceTypeEndpoint, request.model, {
1207
+ ...opts,
1208
+ body: request
1209
+ });
1210
+ }
1211
+ async createContextChatCompletion(request, opts) {
1212
+ if (request.stream) throw ErrChatCompletionStreamNotSupported;
1213
+ const resp = await this.doRequest("POST", this.fullURL(contextChatSuffix), resourceTypeEndpoint, request.model, {
1214
+ ...opts,
1215
+ body: request
1216
+ });
1217
+ return normalizeChatCompletionResponse(resp);
1218
+ }
1219
+ async createContextChatCompletionStream(request, opts) {
1220
+ const body = {
1221
+ ...request,
1222
+ stream: true
1223
+ };
1224
+ const { stream, headers } = await this.doStreamRequest("POST", this.fullURL(contextChatSuffix), resourceTypeEndpoint, request.model, {
1225
+ ...opts,
1226
+ body
1227
+ });
1228
+ return new ChatCompletionStreamReader(stream, this.config.emptyMessagesLimit, headers);
1229
+ }
1230
+ async createContentGenerationTask(request, opts) {
1231
+ if (!this.isAPIKeyAuth()) throw ErrAKSKNotSupported;
1232
+ return this.doRequest("POST", this.fullURL(contentGenerationTaskPath), resourceTypeEndpoint, request.model, {
1233
+ ...opts,
1234
+ body: request
1235
+ });
1236
+ }
1237
+ async getContentGenerationTask(taskId, opts) {
1238
+ if (!this.isAPIKeyAuth()) throw ErrAKSKNotSupported;
1239
+ return this.doRequest("GET", `${this.fullURL(contentGenerationTaskPath)}/${taskId}`, resourceTypeEndpoint, "", opts);
1240
+ }
1241
+ async deleteContentGenerationTask(taskId, opts) {
1242
+ if (!this.isAPIKeyAuth()) throw ErrAKSKNotSupported;
1243
+ await this.doRequest("DELETE", `${this.fullURL(contentGenerationTaskPath)}/${taskId}`, resourceTypeEndpoint, "", opts);
1244
+ }
1245
+ async listContentGenerationTasks(request, opts) {
1246
+ if (!this.isAPIKeyAuth()) throw ErrAKSKNotSupported;
1247
+ const query = {};
1248
+ if (null != request.page_num) query.page_num = String(request.page_num);
1249
+ if (null != request.page_size) query.page_size = String(request.page_size);
1250
+ if (request.filter) {
1251
+ if (request.filter.status) query["filter.status"] = request.filter.status;
1252
+ if (request.filter.model) query["filter.model"] = request.filter.model;
1253
+ if (request.filter.service_tier) query["filter.service_tier"] = request.filter.service_tier;
1254
+ if (request.filter.task_ids?.length) query["filter.task_ids"] = request.filter.task_ids;
1255
+ }
1256
+ return this.doRequest("GET", this.fullURL(contentGenerationTaskPath), resourceTypeEndpoint, "", {
1257
+ ...opts,
1258
+ query: query
1259
+ });
1260
+ }
1261
+ async createResponses(body, opts) {
1262
+ await this.preprocessResponseInput(body.input);
1263
+ return this.doRequest("POST", this.fullURL("/responses"), resourceTypeEndpoint, body.model, {
1264
+ ...opts,
1265
+ body
1266
+ });
1267
+ }
1268
+ async createResponsesStream(body, opts) {
1269
+ await this.preprocessResponseInput(body.input);
1270
+ const streamBody = {
1271
+ ...body,
1272
+ stream: true
1273
+ };
1274
+ const { stream, headers } = await this.doStreamRequest("POST", this.fullURL("/responses"), resourceTypeEndpoint, body.model, {
1275
+ ...opts,
1276
+ body: streamBody
1277
+ });
1278
+ return new ResponsesStreamReader(stream, this.config.emptyMessagesLimit, headers);
1279
+ }
1280
+ async getResponses(responseId, query, opts) {
1281
+ if (!responseId) throw new Error("missing required response_id parameter");
1282
+ return this.doRequest("GET", this.fullURL(`/responses/${responseId}`), "", "", {
1283
+ ...opts,
1284
+ query: query
1285
+ });
1286
+ }
1287
+ async deleteResponse(responseId, opts) {
1288
+ if (!responseId) throw new Error("missing required response_id parameter");
1289
+ await this.doRequest("DELETE", this.fullURL(`/responses/${responseId}`), "", "", opts);
1290
+ }
1291
+ async listResponseInputItems(responseId, query, opts) {
1292
+ if (!responseId) throw new Error("missing required response_id parameter");
1293
+ return this.doRequest("GET", this.fullURL(`/responses/${responseId}/input_items`), "", "", {
1294
+ ...opts,
1295
+ query: query
1296
+ });
1297
+ }
1298
+ async uploadFile(request, opts) {
1299
+ const formData = new FormData();
1300
+ formData.append("file", request.file);
1301
+ formData.append("purpose", request.purpose);
1302
+ if (request.preprocess_configs) formData.append("preprocess_configs", JSON.stringify(request.preprocess_configs));
1303
+ if (null != request.expire_at) formData.append("expire_at", String(request.expire_at));
1304
+ const authHeader = await this.getAuthHeader("", "");
1305
+ const requestId = genRequestId();
1306
+ const resp = await this.httpClient.request({
1307
+ method: "POST",
1308
+ url: this.fullURL(filePrefix),
1309
+ headers: {
1310
+ [ClientRequestHeader]: requestId,
1311
+ ...authHeader,
1312
+ ...opts?.customHeaders
1313
+ },
1314
+ data: formData,
1315
+ signal: opts?.signal,
1316
+ validateStatus: ()=>true
1317
+ });
1318
+ if (resp.status < 200 || resp.status >= 400) this.handleErrorResponse(resp, requestId);
1319
+ return resp.data;
1320
+ }
1321
+ async retrieveFile(fileId, opts) {
1322
+ if (!fileId) throw new Error("missing required file_id parameter");
1323
+ return this.doRequest("GET", this.fullURL(`${filePrefix}/${fileId}`), "", "", opts);
1324
+ }
1325
+ async listFiles(request, opts) {
1326
+ const query = {};
1327
+ if (request?.purpose) query.purpose = request.purpose;
1328
+ if (request?.after) query.after = request.after;
1329
+ if (request?.limit != null) query.limit = String(request.limit);
1330
+ if (request?.order) query.order = request.order;
1331
+ return this.doRequest("GET", this.fullURL(filePrefix), "", "", {
1332
+ ...opts,
1333
+ query
1334
+ });
1335
+ }
1336
+ async deleteFile(fileId, opts) {
1337
+ if (!fileId) throw new Error("missing required file_id parameter");
1338
+ return this.doRequest("DELETE", this.fullURL(`${filePrefix}/${fileId}`), "", "", opts);
1339
+ }
1340
+ async createBatchChatCompletion(request, opts) {
1341
+ if (request.stream) throw ErrChatCompletionStreamNotSupported;
1342
+ const breaker = this.modelBreakerProvider.getOrCreate(request.model);
1343
+ await breaker.wait();
1344
+ const resp = await this.doRequest("POST", this.fullURL(batchChatCompletionsSuffix), resourceTypeEndpoint, request.model, {
1345
+ ...opts,
1346
+ body: request
1347
+ });
1348
+ return normalizeChatCompletionResponse(resp);
1349
+ }
1350
+ async createBatchEmbeddings(request, opts) {
1351
+ const breaker = this.modelBreakerProvider.getOrCreate(request.model);
1352
+ await breaker.wait();
1353
+ const resp = await this.doRequest("POST", this.fullURL(batchEmbeddingsSuffix), resourceTypeEndpoint, request.model, {
1354
+ ...opts,
1355
+ body: request
1356
+ });
1357
+ return normalizeEmbeddingResponse(resp);
1358
+ }
1359
+ async createBatchMultiModalEmbeddings(request, opts) {
1360
+ const breaker = this.modelBreakerProvider.getOrCreate(request.model);
1361
+ await breaker.wait();
1362
+ return this.doRequest("POST", this.fullURL(batchMultiModalEmbeddingsSuffix), resourceTypeEndpoint, request.model, {
1363
+ ...opts,
1364
+ body: request
1365
+ });
1366
+ }
1367
+ constructor(config){
1368
+ client_define_property(this, "config", void 0);
1369
+ client_define_property(this, "httpClient", void 0);
1370
+ client_define_property(this, "batchHttpClient", void 0);
1371
+ client_define_property(this, "resourceStsTokens", new Map());
1372
+ client_define_property(this, "refreshPromise", null);
1373
+ client_define_property(this, "advisoryRefreshTimeout", 1800);
1374
+ client_define_property(this, "mandatoryRefreshTimeout", 600);
1375
+ client_define_property(this, "modelBreakerProvider", new ModelBreakerProvider());
1376
+ client_define_property(this, "e2eeManager", new Map());
1377
+ client_define_property(this, "keyNonceMap", new Map());
1378
+ client_define_property(this, "e2eeFlightMap", new Map());
1379
+ this.config = resolveConfig(config);
1380
+ this.httpClient = this.config.httpClient ?? axios.create({
1381
+ timeout: this.config.timeout,
1382
+ httpsAgent: new Agent({
1383
+ keepAlive: true
1384
+ }),
1385
+ paramsSerializer: (params)=>{
1386
+ const parts = [];
1387
+ for (const [key, value] of Object.entries(params))if (Array.isArray(value)) for (const v of value)parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(v)}`);
1388
+ else if (null != value) parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
1389
+ return parts.join("&");
1390
+ }
1391
+ });
1392
+ this.batchHttpClient = axios.create({
1393
+ timeout: this.config.timeout,
1394
+ httpsAgent: new Agent({
1395
+ keepAlive: true
1396
+ })
1397
+ });
1398
+ }
1399
+ }
1400
+ const ChatMessageRoleAssistant = "assistant";
1401
+ const ToolChoiceRequired = "required";
1402
+ function decodeBase64Embedding(b64) {
1403
+ const buf = Buffer.from(b64, "base64");
1404
+ const floats = [];
1405
+ for(let i = 0; i < buf.length; i += 4)floats.push(buf.readFloatLE(i));
1406
+ return floats;
1407
+ }
1408
+ function base64ToEmbeddingResponse(resp) {
1409
+ return {
1410
+ id: "",
1411
+ created: 0,
1412
+ object: resp.object,
1413
+ model: resp.model,
1414
+ usage: resp.usage,
1415
+ data: resp.data.map((item)=>({
1416
+ object: item.object,
1417
+ embedding: decodeBase64Embedding(item.embedding),
1418
+ index: item.index
1419
+ }))
1420
+ };
1421
+ }
1422
+ const GenerateImagesResponseFormatBase64 = "b64_json";
1423
+ const GenerateImagesSizeAdaptive = "adaptive";
1424
+ const ImageGenerationStreamEventPartialSucceeded = "image_generation.partial_succeeded";
1425
+ const ImageGenerationStreamEventPartialFailed = "image_generation.partial_failed";
1426
+ const ImageGenerationStreamEventCompleted = "image_generation.completed";
1427
+ const StatusSucceeded = "succeeded";
1428
+ const StatusCancelled = "cancelled";
1429
+ const StatusRunning = "running";
1430
+ const MessageRole_developer = "developer";
1431
+ const MessageRole_assistant = "assistant";
1432
+ const ContentItemType_input_text = "input_text";
1433
+ const ContentItemType_input_image = "input_image";
1434
+ const ContentItemType_input_video = "input_video";
1435
+ const ContentItemType_input_audio = "input_audio";
1436
+ const ContentItemType_input_file = "input_file";
1437
+ const ContentItemType_output_text = "output_text";
1438
+ const ContentItemType_summary_text = "summary_text";
1439
+ function getEventType(event) {
1440
+ if (!event) return "";
1441
+ return event.type ?? "";
1442
+ }
1443
+ function isDelta(event) {
1444
+ const t = event.type;
1445
+ return "response.output_text.delta" === t || "response.reasoning_summary_text.delta" === t || "response.function_call_arguments.delta" === t || "response.transcription_text.delta" === t || "response.output_text.annotation.added" === t || "response.web_search_call.in_progress" === t || "response.web_search_call.searching" === t || "response.web_search_call.completed" === t || "response.image_process_call.in_progress" === t || "response.image_process_call.completed" === t || "response.mcp_list_tools.completed" === t || "response.mcp_call.in_progress" === t || "response.mcp_call.arguments_delta" === t || "response.mcp_call.arguments_done" === t || "response.mcp_call.completed" === t || "response.mcp_call.failed" === t || "response.knowledge_search_call.in_progress" === t || "response.knowledge_search_call.searching" === t || "response.knowledge_search_call.completed" === t || "response.knowledge_search_call.failed" === t;
1446
+ }
1447
+ function isDeltaDone(event) {
1448
+ const t = event.type;
1449
+ return "response.output_text.done" === t || "response.reasoning_summary_text.done" === t || "response.function_call_arguments.done" === t || "response.transcription_text.done" === t;
1450
+ }
1451
+ function isResponseDone(event) {
1452
+ const t = event.type;
1453
+ return "response.completed" === t || "response.failed" === t || "response.incomplete" === t;
1454
+ }
1455
+ var src_ChatMessageRoleSystem = "system";
1456
+ var src_ChatMessageRoleTool = "tool";
1457
+ var src_ChatMessageRoleUser = "user";
1458
+ var src_DefaultAdvisoryRefreshTimeout = 1800;
1459
+ var src_DefaultMandatoryRefreshTimeout = 600;
1460
+ var src_DefaultStsTimeout = 604800;
1461
+ var src_ErrorRetryBaseDelayMs = 500;
1462
+ var src_ErrorRetryMaxDelayMs = 8000;
1463
+ var src_FileStatusActive = "active";
1464
+ var src_FileStatusFailed = "failed";
1465
+ var src_GenerateImagesResponseFormatURL = "url";
1466
+ var src_InitialRetryDelay = 0.5;
1467
+ var src_MaxRetryDelay = 8;
1468
+ var src_ObjectTypeFile = "file";
1469
+ var src_ObjectTypeList = "list";
1470
+ var src_OrderAsc = "asc";
1471
+ var src_OrderDesc = "desc";
1472
+ var src_StatusFailed = "failed";
1473
+ var src_StatusQueued = "queued";
1474
+ var src_ToolChoiceAuto = "auto";
1475
+ var src_ToolChoiceNone = "none";
1476
+ export { ArkAPIError, ArkRequestError, ArkRuntimeClient, BotChatCompletionStreamReader, Breaker, ChatCompletionStreamReader, ChatMessageRoleAssistant, ClientEncryptInfoHeader, ClientIsEncryptedHeader, ClientRequestHeader, ClientSessionTokenHeader, E2eeClient, ErrAKSKNotSupported, ErrBodyWithoutBot, ErrBodyWithoutEndpoint, ErrBodyWithoutProjectName, ErrChatCompletionStreamNotSupported, ErrContentFieldsMisused, ErrTooManyEmptyStreamMessages, EventStreamDecoder, FileStatusProcessing, GenerateImagesResponseFormatBase64, GenerateImagesSizeAdaptive, ImageGenerationStreamEventCompleted, ImageGenerationStreamEventPartialFailed, ImageGenerationStreamEventPartialSucceeded, ImageGenerationStreamReader, KeyAgreementClient, ModelBreakerProvider, PurposeUserData, ResponsesStreamReader, RetryAfterHeader, StatusCancelled, StatusRunning, StatusSucceeded, ToolChoiceRequired, aesGcmDecrypt, aesGcmDecryptBase64, aesGcmEncrypt, aesGcmEncryptBase64, base64ToEmbeddingResponse, checkIsModeAICC, decodeBase64Embedding, decryptChatResponse, decryptChatStreamResponse, deepCopyRequest, encryptChatRequest, genRequestId, getCertInfo, loadLocalCertificate, responses_namespaceObject as responses, retry, saveToLocalCertificate, src_ChatMessageRoleSystem as ChatMessageRoleSystem, src_ChatMessageRoleTool as ChatMessageRoleTool, src_ChatMessageRoleUser as ChatMessageRoleUser, src_DefaultAdvisoryRefreshTimeout as DefaultAdvisoryRefreshTimeout, src_DefaultMandatoryRefreshTimeout as DefaultMandatoryRefreshTimeout, src_DefaultStsTimeout as DefaultStsTimeout, src_ErrorRetryBaseDelayMs as ErrorRetryBaseDelayMs, src_ErrorRetryMaxDelayMs as ErrorRetryMaxDelayMs, src_FileStatusActive as FileStatusActive, src_FileStatusFailed as FileStatusFailed, src_GenerateImagesResponseFormatURL as GenerateImagesResponseFormatURL, src_InitialRetryDelay as InitialRetryDelay, src_MaxRetryDelay as MaxRetryDelay, src_ObjectTypeFile as ObjectTypeFile, src_ObjectTypeList as ObjectTypeList, src_OrderAsc as OrderAsc, src_OrderDesc as OrderDesc, src_StatusFailed as StatusFailed, src_StatusQueued as StatusQueued, src_ToolChoiceAuto as ToolChoiceAuto, src_ToolChoiceNone as ToolChoiceNone };