MCPcopy
hub / github.com/7836246/cursor2api / handleOpenAIIncrementalTextStream

Function handleOpenAIIncrementalTextStream

src/openai-handler.ts:607–756  ·  view source on GitHub ↗
(
    res: Response,
    cursorReq: CursorChatRequest,
    body: OpenAIChatRequest,
    anthropicReq: AnthropicRequest,
    streamMeta: { id: string; created: number; model: string },
    log: RequestLogger,
)

Source from the content-addressed store, hash-verified

605}
606
607async function handleOpenAIIncrementalTextStream(
608 res: Response,
609 cursorReq: CursorChatRequest,
610 body: OpenAIChatRequest,
611 anthropicReq: AnthropicRequest,
612 streamMeta: { id: string; created: number; model: string },
613 log: RequestLogger,
614): Promise<void> {
615 let activeCursorReq = cursorReq;
616 let retryCount = 0;
617 const thinkingEnabled = anthropicReq.thinking?.type === 'enabled';
618 let finalRawResponse = '';
619 let finalVisibleText = '';
620 let finalReasoningContent = '';
621 let streamer = createIncrementalTextStreamer({
622 transform: sanitizeResponse,
623 isBlockedPrefix: (text) => isRefusal(text.substring(0, 300)),
624 });
625 let reasoningSent = false;
626
627 const executeAttempt = async (): Promise<{
628 rawResponse: string;
629 visibleText: string;
630 reasoningContent: string;
631 streamer: ReturnType<typeof createIncrementalTextStreamer>;
632 }> => {
633 let rawResponse = '';
634 let visibleText = '';
635 let leadingBuffer = '';
636 let leadingResolved = false;
637 let reasoningContent = '';
638 const attemptStreamer = createIncrementalTextStreamer({
639 transform: sanitizeResponse,
640 isBlockedPrefix: (text) => isRefusal(text.substring(0, 300)),
641 });
642
643 const flushVisible = (chunk: string): void => {
644 if (!chunk) return;
645 visibleText += chunk;
646 const delta = attemptStreamer.push(chunk);
647 if (!delta) return;
648
649 if (thinkingEnabled && reasoningContent && !reasoningSent) {
650 writeOpenAIReasoningDelta(res, streamMeta.id, streamMeta.created, streamMeta.model, reasoningContent);
651 reasoningSent = true;
652 }
653 writeOpenAITextDelta(res, streamMeta.id, streamMeta.created, streamMeta.model, delta);
654 };
655
656 await sendCursorRequest(activeCursorReq, (event: CursorSSEEvent) => {
657 if (event.type !== 'text-delta' || !event.delta) return;
658
659 rawResponse += event.delta;
660
661 if (!leadingResolved) {
662 leadingBuffer += event.delta;
663 const split = splitLeadingThinkingBlocks(leadingBuffer);
664

Callers 1

handleOpenAIStreamFunction · 0.85

Calls 15

isRefusalFunction · 0.90
buildRetryRequestFunction · 0.85
convertToCursorRequestFunction · 0.85
isToolCapabilityQuestionFunction · 0.85
writeOpenAITextDeltaFunction · 0.85
writeOpenAISSEFunction · 0.85
buildOpenAIUsageFunction · 0.85
sanitizeResponseFunction · 0.85
hasSentTextMethod · 0.80
finishMethod · 0.80

Tested by

no test coverage detected