@iinm/plain-agent 1.8.2 → 1.8.4

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 (86) hide show
  1. package/README.md +6 -2
  2. package/bin/plain +1 -1
  3. package/config/config.predefined.json +1 -1
  4. package/config/prompts.predefined/shortcuts/configure.md +1 -1
  5. package/dist/main.mjs +473 -0
  6. package/dist/main.mjs.map +7 -0
  7. package/package.json +5 -7
  8. package/src/agent.d.ts +0 -52
  9. package/src/agent.mjs +0 -204
  10. package/src/agentLoop.mjs +0 -419
  11. package/src/agentState.mjs +0 -41
  12. package/src/claudeCodePlugin.mjs +0 -164
  13. package/src/cliArgs.mjs +0 -175
  14. package/src/cliBatch.mjs +0 -144
  15. package/src/cliCommands.mjs +0 -283
  16. package/src/cliCompleter.mjs +0 -227
  17. package/src/cliCost.mjs +0 -309
  18. package/src/cliFormatter.mjs +0 -413
  19. package/src/cliInteractive.mjs +0 -526
  20. package/src/cliInterruptTransform.mjs +0 -51
  21. package/src/cliMuteTransform.mjs +0 -26
  22. package/src/cliPasteTransform.mjs +0 -183
  23. package/src/config.d.ts +0 -36
  24. package/src/config.mjs +0 -197
  25. package/src/context/loadAgentRoles.mjs +0 -283
  26. package/src/context/loadPrompts.mjs +0 -324
  27. package/src/context/loadUserMessageContext.mjs +0 -147
  28. package/src/costTracker.mjs +0 -210
  29. package/src/env.mjs +0 -44
  30. package/src/main.mjs +0 -278
  31. package/src/mcpClient.mjs +0 -351
  32. package/src/mcpIntegration.mjs +0 -160
  33. package/src/model.d.ts +0 -109
  34. package/src/modelCaller.mjs +0 -32
  35. package/src/modelDefinition.d.ts +0 -92
  36. package/src/prompt.mjs +0 -138
  37. package/src/providers/anthropic.d.ts +0 -248
  38. package/src/providers/anthropic.mjs +0 -587
  39. package/src/providers/bedrock.d.ts +0 -249
  40. package/src/providers/bedrock.mjs +0 -700
  41. package/src/providers/gemini.d.ts +0 -208
  42. package/src/providers/gemini.mjs +0 -754
  43. package/src/providers/openai.d.ts +0 -281
  44. package/src/providers/openai.mjs +0 -544
  45. package/src/providers/openaiCompatible.d.ts +0 -147
  46. package/src/providers/openaiCompatible.mjs +0 -652
  47. package/src/providers/platform/awsSigV4.mjs +0 -184
  48. package/src/providers/platform/azure.mjs +0 -42
  49. package/src/providers/platform/bedrock.mjs +0 -78
  50. package/src/providers/platform/googleCloud.mjs +0 -34
  51. package/src/subagent.mjs +0 -265
  52. package/src/tmpfile.mjs +0 -27
  53. package/src/tool.d.ts +0 -74
  54. package/src/toolExecutor.mjs +0 -236
  55. package/src/toolInputValidator.mjs +0 -183
  56. package/src/toolUseApprover.mjs +0 -99
  57. package/src/tools/askURL.mjs +0 -209
  58. package/src/tools/askWeb.mjs +0 -208
  59. package/src/tools/compactContext.d.ts +0 -4
  60. package/src/tools/compactContext.mjs +0 -87
  61. package/src/tools/delegateToSubagent.d.ts +0 -4
  62. package/src/tools/delegateToSubagent.mjs +0 -48
  63. package/src/tools/execCommand.d.ts +0 -22
  64. package/src/tools/execCommand.mjs +0 -200
  65. package/src/tools/patchFile.d.ts +0 -4
  66. package/src/tools/patchFile.mjs +0 -133
  67. package/src/tools/reportAsSubagent.d.ts +0 -3
  68. package/src/tools/reportAsSubagent.mjs +0 -44
  69. package/src/tools/tmuxCommand.d.ts +0 -14
  70. package/src/tools/tmuxCommand.mjs +0 -194
  71. package/src/tools/writeFile.d.ts +0 -4
  72. package/src/tools/writeFile.mjs +0 -56
  73. package/src/usageStore.mjs +0 -167
  74. package/src/utils/evalJSONConfig.mjs +0 -72
  75. package/src/utils/matchValue.d.ts +0 -6
  76. package/src/utils/matchValue.mjs +0 -40
  77. package/src/utils/noThrow.mjs +0 -31
  78. package/src/utils/notify.mjs +0 -29
  79. package/src/utils/parseFileRange.mjs +0 -18
  80. package/src/utils/readFileRange.mjs +0 -33
  81. package/src/utils/retryOnError.mjs +0 -41
  82. package/src/voiceInput.mjs +0 -61
  83. package/src/voiceInputGemini.mjs +0 -105
  84. package/src/voiceInputOpenAI.mjs +0 -104
  85. package/src/voiceInputSession.mjs +0 -543
  86. package/src/voiceToggleKey.mjs +0 -62
@@ -1,652 +0,0 @@
1
- /**
2
- * @import { ModelInput, Message, MessageContentText, AssistantMessage, ModelOutput, PartialMessageContent, MessageContentThinking, MessageContentToolUse } from "../model"
3
- * @import { OpenAIAssistantMessage, OpenAIMessage, OpenAIMessageToolCall, OpenAICompatibleModelConfig, OpenAIToolDefinition, OpenAIStreamData, OpenAIChatCompletion, OpenAIMessageContentImage, OpenAIChatCompletionRequest } from "./openaiCompatible"
4
- * @import { ToolDefinition } from "../tool"
5
- */
6
-
7
- import { styleText } from "node:util";
8
- import { noThrow } from "../utils/noThrow.mjs";
9
- import { retryOnError } from "../utils/retryOnError.mjs";
10
- import { loadAwsCredentials, signAwsRequest } from "./platform/awsSigV4.mjs";
11
- import { readBedrockStreamEvents } from "./platform/bedrock.mjs";
12
- import { getGoogleCloudAccessToken } from "./platform/googleCloud.mjs";
13
-
14
- /**
15
- * @param {import("../modelDefinition").PlatformConfig} platformConfig
16
- * @param {OpenAICompatibleModelConfig} modelConfig
17
- * @param {ModelInput} input
18
- * @param {number} retryCount
19
- * @returns {Promise<ModelOutput | Error>}
20
- */
21
- export async function callOpenAICompatibleModel(
22
- platformConfig,
23
- modelConfig,
24
- input,
25
- retryCount = 0,
26
- ) {
27
- const retryInterval = Math.min(2 * 2 ** retryCount, 16);
28
-
29
- return await noThrow(async () => {
30
- const messages = convertGenericMessageToOpenAIFormat(input.messages);
31
- const tools = convertGenericeToolDefinitionToOpenAIFormat(
32
- input.tools || [],
33
- );
34
-
35
- const url = (() => {
36
- const baseURL = platformConfig.baseURL;
37
-
38
- switch (platformConfig.name) {
39
- case "openai":
40
- case "openai-compatible":
41
- return `${baseURL}/v1/chat/completions`;
42
- case "bedrock":
43
- return `${baseURL}/model/${modelConfig.model}/invoke-with-response-stream`;
44
- case "vertex-ai":
45
- return `${baseURL}/endpoints/openapi/chat/completions`;
46
- default:
47
- throw new Error(`Unsupported platform: ${platformConfig.name}`);
48
- }
49
- })();
50
-
51
- /** @type {Record<string,string>} */
52
- const headers = await (async () => {
53
- switch (platformConfig.name) {
54
- case "openai":
55
- case "openai-compatible":
56
- return {
57
- ...platformConfig.customHeaders,
58
- Authorization: `Bearer ${platformConfig.apiKey}`,
59
- };
60
- case "bedrock":
61
- return platformConfig.customHeaders ?? {};
62
- case "vertex-ai":
63
- return {
64
- ...platformConfig.customHeaders,
65
- Authorization: `Bearer ${await getGoogleCloudAccessToken()}`,
66
- };
67
- }
68
- })();
69
-
70
- const { model: _, ...modelConfigWithoutName } = modelConfig;
71
- const platformRequest = (() => {
72
- switch (platformConfig.name) {
73
- case "openai":
74
- case "openai-compatible":
75
- return {
76
- ...modelConfig,
77
- stream: true,
78
- };
79
- case "bedrock":
80
- return {
81
- ...modelConfigWithoutName,
82
- };
83
- case "vertex-ai":
84
- return {
85
- ...modelConfig,
86
- model: modelConfig.model,
87
- stream: true,
88
- };
89
- }
90
- })();
91
-
92
- /** @type {OpenAIChatCompletionRequest} */
93
- const request = {
94
- ...platformRequest,
95
- messages,
96
- tools: tools.length ? tools : undefined,
97
- stream_options: {
98
- include_usage: true,
99
- },
100
- };
101
-
102
- const runFetchDefault = async () =>
103
- fetch(url, {
104
- method: "POST",
105
- headers: {
106
- ...headers,
107
- "Content-Type": "application/json",
108
- },
109
- body: JSON.stringify(request),
110
- signal: AbortSignal.timeout(8 * 60 * 1000),
111
- });
112
-
113
- // bedrock + sso profile
114
- const runFetchForBedrock = async () => {
115
- const region =
116
- url.match(/bedrock-runtime\.([\w-]+)\.amazonaws\.com/)?.[1] ?? "";
117
- const urlParsed = new URL(url);
118
- const { hostname, pathname } = urlParsed;
119
-
120
- const credentials = await loadAwsCredentials(
121
- platformConfig.name === "bedrock" ? platformConfig.awsProfile : "",
122
- );
123
-
124
- const signed = signAwsRequest(
125
- {
126
- method: "POST",
127
- hostname,
128
- path: pathname,
129
- headers: {
130
- host: hostname,
131
- "Content-Type": "application/json",
132
- },
133
- body: JSON.stringify(request),
134
- },
135
- { region, service: "bedrock", credentials },
136
- );
137
-
138
- return fetch(url, {
139
- method: signed.method,
140
- headers: signed.headers,
141
- body: signed.body,
142
- signal: AbortSignal.timeout(8 * 60 * 1000),
143
- });
144
- };
145
-
146
- const runFetch =
147
- platformConfig.name === "bedrock" ? runFetchForBedrock : runFetchDefault;
148
-
149
- const response = await retryOnError(() => runFetch(), {
150
- shouldRetry: (err) => err instanceof Error && err.name === "TimeoutError",
151
- beforeRetry: (err, interval) => {
152
- console.error(
153
- styleText(
154
- "yellow",
155
- `Failed to call model: ${String(err)}; Retry in ${interval} seconds...`,
156
- ),
157
- );
158
- return Promise.resolve();
159
- },
160
- initialInterval: 2,
161
- maxInterval: 16,
162
- multiplier: 2,
163
- maxAttempt: 5,
164
- });
165
-
166
- if (response.status === 429 || response.status >= 500) {
167
- console.error(
168
- styleText(
169
- "yellow",
170
- `Model rate limit exceeded. Retry in ${retryInterval} seconds...`,
171
- ),
172
- );
173
- await new Promise((resolve) => setTimeout(resolve, retryInterval * 1000));
174
- return callOpenAICompatibleModel(
175
- platformConfig,
176
- modelConfig,
177
- input,
178
- retryCount + 1,
179
- );
180
- }
181
-
182
- if (response.status !== 200) {
183
- throw new Error(
184
- `Failed to call OpenAI compatible model: status=${response.status}, body=${await response.text()}`,
185
- );
186
- }
187
-
188
- if (!response.body) {
189
- throw new Error("Response body is empty");
190
- }
191
-
192
- const reader = response.body.getReader();
193
- const eventStreamReader =
194
- platformConfig.name === "bedrock"
195
- ? /** @type {typeof readOpenAIStreamData} */ (readBedrockStreamEvents)
196
- : readOpenAIStreamData;
197
-
198
- /** @type {OpenAIStreamData[]} */
199
- const dataList = [];
200
- /** @type {PartialMessageContent | undefined} */
201
- let previousPartialContent;
202
- for await (const data of eventStreamReader(reader)) {
203
- dataList.push(data);
204
-
205
- const partialContents = convertOpenAIStreamDataToAgentPartialContent(
206
- data,
207
- previousPartialContent,
208
- );
209
-
210
- if (partialContents.length) {
211
- previousPartialContent = partialContents.at(-1);
212
- }
213
-
214
- if (input.onPartialMessageContent) {
215
- for (const partialContent of partialContents) {
216
- input.onPartialMessageContent(partialContent);
217
- }
218
- }
219
- }
220
-
221
- const chatCompletion = convertOpenAIStreamDataToChatCompletion(dataList);
222
- if (chatCompletion instanceof Error) {
223
- console.error(
224
- styleText(
225
- "yellow",
226
- `Failed to process stream: ${chatCompletion.message}; Retry in ${retryInterval} seconds...`,
227
- ),
228
- );
229
- await new Promise((resolve) => setTimeout(resolve, retryInterval * 1000));
230
- return callOpenAICompatibleModel(
231
- platformConfig,
232
- modelConfig,
233
- input,
234
- retryCount + 1,
235
- );
236
- }
237
-
238
- const openAIAssistantMessage = chatCompletion.choices[0].message;
239
-
240
- return {
241
- message: convertOpenAIAssistantMessageToGenericFormat(
242
- openAIAssistantMessage,
243
- ),
244
- providerTokenUsage: chatCompletion.usage,
245
- };
246
- });
247
- }
248
-
249
- /**
250
- * @param {Message[]} genericMessages
251
- * @returns {OpenAIMessage[]}
252
- */
253
- function convertGenericMessageToOpenAIFormat(genericMessages) {
254
- /** @type {OpenAIMessage[]} */
255
- const openAIMessages = [];
256
- for (const genericMessage of genericMessages) {
257
- switch (genericMessage.role) {
258
- case "system": {
259
- openAIMessages.push({
260
- role: "system",
261
- content: genericMessage.content.map((part) => ({
262
- type: "text",
263
- text: part.text,
264
- })),
265
- });
266
- break;
267
- }
268
- case "user": {
269
- const toolResults = genericMessage.content.filter(
270
- (part) => part.type === "tool_result",
271
- );
272
- const userContentParts = genericMessage.content.filter(
273
- (part) => part.type === "text" || part.type === "image",
274
- );
275
-
276
- // Tool Results
277
- let imageIndex = 0;
278
- for (const result of toolResults) {
279
- const toolResultContentString = result.content
280
- .map((part) => {
281
- switch (part.type) {
282
- case "text":
283
- return part.text;
284
- case "image":
285
- imageIndex += 1;
286
- return `(Image [${imageIndex}] omitted. See next message from user.)`;
287
- default:
288
- throw new Error(
289
- `Unsupported content part: ${JSON.stringify(part)}`,
290
- );
291
- }
292
- })
293
- .join("\n\n");
294
- openAIMessages.push({
295
- role: "tool",
296
- tool_call_id: result.toolUseId,
297
- content: toolResultContentString,
298
- });
299
- }
300
-
301
- /** @type {OpenAIMessageContentImage[]} */
302
- const imageParts = [];
303
- for (const result of toolResults) {
304
- for (const part of result.content) {
305
- if (part.type === "image") {
306
- imageParts.push({
307
- type: "image_url",
308
- image_url: {
309
- url: `data:${part.mimeType};base64,${part.data}`,
310
- },
311
- });
312
- }
313
- }
314
- }
315
-
316
- if (imageParts.length) {
317
- openAIMessages.push({
318
- role: "user",
319
- content: imageParts,
320
- });
321
- }
322
-
323
- // User Input Parts
324
- if (userContentParts.length) {
325
- openAIMessages.push({
326
- role: "user",
327
- content: userContentParts.map((part) => {
328
- if (part.type === "text") {
329
- return { type: "text", text: part.text };
330
- }
331
- if (part.type === "image") {
332
- return {
333
- type: "image_url",
334
- image_url: {
335
- url: `data:${part.mimeType};base64,${part.data}`,
336
- },
337
- };
338
- }
339
- throw new Error(
340
- `Unsupported content part: ${JSON.stringify(part)}`,
341
- );
342
- }),
343
- });
344
- }
345
-
346
- break;
347
- }
348
- case "assistant": {
349
- /** @type {MessageContentThinking[]} */
350
- const thinkingParts = genericMessage.content.filter(
351
- (part) => part.type === "thinking",
352
- );
353
- if (thinkingParts.length > 1) {
354
- console.error(
355
- `OpenAI Unsupported message format: ${JSON.stringify(genericMessage)}`,
356
- );
357
- }
358
- const thinking = thinkingParts.map((part) => part.thinking).join("\n");
359
-
360
- /** @type {MessageContentText[]} */
361
- const textParts = genericMessage.content.filter(
362
- (part) => part.type === "text",
363
- );
364
- if (textParts.length > 1) {
365
- console.error(
366
- `OpenAI Unsupported message format: ${JSON.stringify(genericMessage)}`,
367
- );
368
- }
369
- const text = textParts.map((part) => part.text).join("\n");
370
-
371
- /** @type {MessageContentToolUse[]} */
372
- const toolUseParts = genericMessage.content.filter(
373
- (part) => part.type === "tool_use",
374
- );
375
-
376
- /** @type {OpenAIMessageToolCall[]} */
377
- const toolCalls = toolUseParts.map((part) => ({
378
- id: part.toolUseId,
379
- type: "function",
380
- function: {
381
- name: part.toolName,
382
- arguments: JSON.stringify(part.input),
383
- },
384
- }));
385
-
386
- openAIMessages.push({
387
- role: "assistant",
388
- reasoning_content: thinking ? thinking : undefined,
389
- content: text ? text : undefined,
390
- tool_calls: toolCalls.length ? toolCalls : undefined,
391
- });
392
- }
393
- }
394
- }
395
-
396
- return openAIMessages;
397
- }
398
-
399
- /**
400
- * @param {ToolDefinition[]} genericToolDefs
401
- * @returns {OpenAIToolDefinition[]}
402
- */
403
- function convertGenericeToolDefinitionToOpenAIFormat(genericToolDefs) {
404
- /** @type {OpenAIToolDefinition[]} */
405
- const openAIToolDefs = [];
406
- for (const toolDef of genericToolDefs) {
407
- openAIToolDefs.push({
408
- type: "function",
409
- function: {
410
- name: toolDef.name,
411
- description: toolDef.description,
412
- parameters: toolDef.inputSchema,
413
- },
414
- });
415
- }
416
-
417
- return openAIToolDefs;
418
- }
419
-
420
- /**
421
- * @param {OpenAIAssistantMessage} openAIAsistantMessage
422
- * @returns {AssistantMessage}
423
- */
424
- function convertOpenAIAssistantMessageToGenericFormat(openAIAsistantMessage) {
425
- /** @type {AssistantMessage["content"]} */
426
- const content = [];
427
- if (openAIAsistantMessage.reasoning_content) {
428
- content.push({
429
- type: "thinking",
430
- thinking: openAIAsistantMessage.reasoning_content,
431
- });
432
- }
433
-
434
- if (openAIAsistantMessage.content) {
435
- content.push({ type: "text", text: openAIAsistantMessage.content });
436
- }
437
-
438
- if (openAIAsistantMessage.tool_calls) {
439
- for (const toolCall of openAIAsistantMessage.tool_calls) {
440
- if (toolCall.type === "function") {
441
- /** @type {Record<string, unknown>} */
442
- let args;
443
- try {
444
- args = JSON.parse(toolCall.function.arguments);
445
- } catch (err) {
446
- args = { err: String(err) };
447
- }
448
-
449
- content.push({
450
- type: "tool_use",
451
- toolUseId: toolCall.id,
452
- toolName: toolCall.function.name,
453
- input: args,
454
- });
455
- } else {
456
- throw new Error(
457
- `Unsupported tool call type: ${JSON.stringify(toolCall)}`,
458
- );
459
- }
460
- }
461
- }
462
-
463
- return {
464
- role: "assistant",
465
- content,
466
- };
467
- }
468
-
469
- /**
470
- * @param {OpenAIStreamData[]} dataList
471
- * @returns {OpenAIChatCompletion | Error}
472
- */
473
- function convertOpenAIStreamDataToChatCompletion(dataList) {
474
- const firstData = dataList.at(0);
475
- if (!firstData) {
476
- return new Error("No data found in the stream");
477
- }
478
-
479
- const fistChoice = firstData.choices.at(0);
480
- if (!fistChoice) {
481
- return new Error("No choice found in the first data");
482
- }
483
-
484
- const message = /** @type {OpenAIAssistantMessage} */ (fistChoice.delta);
485
-
486
- /** @type {Partial<OpenAIChatCompletion>} */
487
- const chatCompletion = {
488
- ...firstData,
489
- choices: [
490
- {
491
- index: fistChoice.index,
492
- message,
493
- finish_reason: /** @type {string} */ (fistChoice.finish_reason),
494
- },
495
- ],
496
- };
497
-
498
- for (let i = 1; i < dataList.length; i++) {
499
- const data = dataList[i];
500
- const firstChoice = data?.choices.at(0);
501
- if (firstChoice) {
502
- const delta = firstChoice.delta;
503
-
504
- if (delta.reasoning_content) {
505
- message.reasoning_content =
506
- (message.reasoning_content ?? "") + delta.reasoning_content;
507
- }
508
-
509
- if (delta.content) {
510
- message.content = (message.content ?? "") + delta.content;
511
- }
512
-
513
- if (delta.tool_calls) {
514
- for (const toolCallDelta of delta.tool_calls) {
515
- const toolCall = message.tool_calls?.at(toolCallDelta.index);
516
- if (!toolCall) {
517
- if (!message.tool_calls) {
518
- message.tool_calls = [];
519
- }
520
- /** @type {OpenAIMessageToolCall[]} */ (message.tool_calls).push(
521
- /** @type {OpenAIMessageToolCall} */
522
- (toolCallDelta),
523
- );
524
- }
525
- if (toolCall && toolCallDelta.function) {
526
- toolCall.function.arguments =
527
- (toolCall.function.arguments ?? "") +
528
- toolCallDelta.function.arguments;
529
- }
530
- }
531
- }
532
-
533
- if (firstChoice.finish_reason && chatCompletion.choices) {
534
- chatCompletion.choices[0].finish_reason = firstChoice.finish_reason;
535
- }
536
- }
537
-
538
- if (data.usage) {
539
- chatCompletion.usage = data.usage;
540
- }
541
- }
542
-
543
- return /** @type {OpenAIChatCompletion} */ (chatCompletion);
544
- }
545
-
546
- /**
547
- * @param {OpenAIStreamData} data
548
- * @param {PartialMessageContent | undefined} previousPartialContent
549
- * @returns {PartialMessageContent[]}
550
- */
551
- function convertOpenAIStreamDataToAgentPartialContent(
552
- data,
553
- previousPartialContent,
554
- ) {
555
- /** @type {PartialMessageContent[]} */
556
- const partialContents = [];
557
- const firstChoice = data.choices.at(0);
558
-
559
- if (firstChoice?.delta.reasoning_content) {
560
- partialContents.push({
561
- type: "thinking",
562
- content: firstChoice?.delta.reasoning_content,
563
- position: previousPartialContent?.type === "thinking" ? "delta" : "start",
564
- });
565
- }
566
-
567
- if (firstChoice?.delta.content) {
568
- partialContents.push({
569
- type: "text",
570
- content: firstChoice.delta.content,
571
- position: previousPartialContent?.type === "text" ? "delta" : "start",
572
- });
573
- }
574
-
575
- if (firstChoice?.delta.tool_calls) {
576
- partialContents.push({
577
- type: "tool_use",
578
- content: [
579
- firstChoice.delta.tool_calls.at(0)?.function?.name,
580
- firstChoice.delta.tool_calls.at(0)?.function?.arguments,
581
- ].join(" "),
582
- position: previousPartialContent?.type === "tool_use" ? "delta" : "start",
583
- });
584
- }
585
-
586
- if (firstChoice?.finish_reason) {
587
- partialContents.push({
588
- type: previousPartialContent?.type || "unknown",
589
- position: "stop",
590
- });
591
- }
592
-
593
- if (
594
- partialContents.length &&
595
- previousPartialContent &&
596
- partialContents[0].position !== "stop" &&
597
- partialContents[0].type !== previousPartialContent.type
598
- ) {
599
- partialContents.unshift({
600
- type: previousPartialContent.type,
601
- position: "stop",
602
- });
603
- }
604
-
605
- return partialContents;
606
- }
607
-
608
- /**
609
- * @param {ReadableStreamDefaultReader<Uint8Array>} reader
610
- */
611
- async function* readOpenAIStreamData(reader) {
612
- let buffer = new Uint8Array();
613
-
614
- while (true) {
615
- const { done, value } = await reader.read();
616
- if (done) {
617
- break;
618
- }
619
-
620
- const nextBuffer = new Uint8Array(buffer.length + value.length);
621
- nextBuffer.set(buffer);
622
- nextBuffer.set(value, buffer.length);
623
- buffer = nextBuffer;
624
-
625
- const lineFeed = "\n".charCodeAt(0);
626
- const dataEndIndices = [];
627
- for (let i = 0; i < buffer.length - 1; i++) {
628
- if (buffer[i] === lineFeed && buffer[i + 1] === lineFeed) {
629
- dataEndIndices.push(i);
630
- }
631
- }
632
-
633
- for (let i = 0; i < dataEndIndices.length; i++) {
634
- const dataStartIndex = i === 0 ? 0 : dataEndIndices[i - 1] + 2;
635
- const dataEndIndex = dataEndIndices[i];
636
- const data = buffer.slice(dataStartIndex, dataEndIndex);
637
- const decodedData = new TextDecoder().decode(data);
638
- if (decodedData === "data: [DONE]") {
639
- break;
640
- }
641
- if (decodedData.startsWith("data: ")) {
642
- /** @type {OpenAIStreamData} */
643
- const parsedData = JSON.parse(decodedData.slice("data: ".length));
644
- yield parsedData;
645
- }
646
- }
647
-
648
- if (dataEndIndices.length) {
649
- buffer = buffer.slice(dataEndIndices[dataEndIndices.length - 1] + 2);
650
- }
651
- }
652
- }