178 lines
5.5 KiB
JavaScript
178 lines
5.5 KiB
JavaScript
const REASONING_TAG_NAMES = ["think", "thinking", "reasoning", "analysis", "thought", "reflection"];
|
|
const REASONING_TAG_RE = /<\s*(\/?)\s*(think|thinking|reasoning|analysis|thought|reflection)\b[^>]*>/gi;
|
|
|
|
function withoutPartialReasoningTag(value) {
|
|
const start = value.lastIndexOf("<");
|
|
if (start < 0 || start < value.lastIndexOf(">")) return value;
|
|
const suffix = value.slice(start);
|
|
const match = suffix.match(/^<\s*\/?\s*([a-z]*)[^>]*$/i);
|
|
const candidate = match?.[1]?.toLowerCase();
|
|
if (candidate !== undefined && REASONING_TAG_NAMES.some((tag) => tag.startsWith(candidate))) {
|
|
return value.slice(0, start);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
/**
|
|
* Split raw streaming/complete assistant text into clean visible Markdown and extracted reasoning/thinking text.
|
|
* Supports both structured reasoning deltas and inline `<think>...</think>` blocks.
|
|
*/
|
|
export function splitCopilotResponse(value, structuredReasoning = "") {
|
|
const completeValue = withoutPartialReasoningTag(String(value ?? ""));
|
|
const answerParts = [];
|
|
const reasoningParts = [];
|
|
let currentReasoning = "";
|
|
let depth = 0;
|
|
let cursor = 0;
|
|
|
|
for (const match of completeValue.matchAll(REASONING_TAG_RE)) {
|
|
const index = match.index ?? cursor;
|
|
const content = completeValue.slice(cursor, index);
|
|
if (depth > 0) currentReasoning += content;
|
|
else answerParts.push(content);
|
|
|
|
const closing = Boolean(match[1]);
|
|
if (closing) {
|
|
if (depth === 0) {
|
|
answerParts.push(match[0]);
|
|
} else {
|
|
depth -= 1;
|
|
if (depth === 0) {
|
|
const trimmed = currentReasoning.trim();
|
|
if (trimmed) reasoningParts.push(trimmed);
|
|
currentReasoning = "";
|
|
}
|
|
}
|
|
} else {
|
|
if (depth === 0) currentReasoning = "";
|
|
depth += 1;
|
|
}
|
|
cursor = index + match[0].length;
|
|
}
|
|
|
|
const remainder = completeValue.slice(cursor);
|
|
if (depth > 0) {
|
|
currentReasoning += remainder;
|
|
const trimmed = currentReasoning.trim();
|
|
if (trimmed) reasoningParts.push(trimmed);
|
|
} else {
|
|
answerParts.push(remainder);
|
|
}
|
|
|
|
const structured = String(structuredReasoning ?? "").trim();
|
|
const tagged = reasoningParts.join("\n\n").trim();
|
|
const reasoning = structured && tagged && structured !== tagged
|
|
? `${structured}\n\n${tagged}`
|
|
: (structured || tagged);
|
|
|
|
return {
|
|
markdown: answerParts.join("").trim(),
|
|
reasoning,
|
|
reasoningActive: depth > 0,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Parse incremental SSE text buffer into complete `{ event, data }` frames and remaining unclosed tail.
|
|
*/
|
|
export function consumeSSEFrames(buffer, flush = false) {
|
|
const normalized = String(buffer ?? "").replace(/\r\n/g, "\n");
|
|
const chunks = normalized.split("\n\n");
|
|
const remainder = flush ? "" : (chunks.pop() ?? "");
|
|
const frames = [];
|
|
|
|
for (const chunk of chunks) {
|
|
if (!chunk.trim()) continue;
|
|
let event = "message";
|
|
const dataLines = [];
|
|
for (const line of chunk.split("\n")) {
|
|
if (line.startsWith(":")) continue;
|
|
if (line.startsWith("event:")) event = line.slice(6).trim() || "message";
|
|
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
}
|
|
if (dataLines.length > 0) {
|
|
frames.push({ event, data: dataLines.join("\n") });
|
|
}
|
|
}
|
|
|
|
return { frames, remainder };
|
|
}
|
|
|
|
/**
|
|
* Consume an SSE Response from `/api/v1/situational-awareness/sessions/{id}/turns/stream`.
|
|
*/
|
|
export async function consumeCopilotStream(
|
|
response,
|
|
callbacks = {},
|
|
{ signal } = {},
|
|
) {
|
|
if (!response?.body?.getReader) {
|
|
throw new Error("Copilot SSE stream response has no readable body");
|
|
}
|
|
|
|
const reader = response.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
let buffered = "";
|
|
let donePayload = null;
|
|
let failed = false;
|
|
|
|
const handleFrame = ({ event, data }) => {
|
|
if (!data || data === "[DONE]") return;
|
|
let parsed;
|
|
try {
|
|
parsed = JSON.parse(data);
|
|
} catch {
|
|
return;
|
|
}
|
|
if (!parsed || typeof parsed !== "object") return;
|
|
const eventName = event || parsed.event || "message";
|
|
|
|
if (eventName === "meta") {
|
|
callbacks.onMeta?.(parsed);
|
|
} else if (eventName === "reasoning") {
|
|
if (typeof parsed.delta === "string" && parsed.delta) {
|
|
callbacks.onReasoningDelta?.(parsed.delta, parsed);
|
|
}
|
|
} else if (eventName === "text") {
|
|
if (typeof parsed.delta === "string" && parsed.delta) {
|
|
callbacks.onTextDelta?.(parsed.delta, parsed);
|
|
}
|
|
} else if (eventName === "done") {
|
|
donePayload = parsed;
|
|
callbacks.onDone?.(parsed);
|
|
} else if (eventName === "error") {
|
|
const err = new Error(parsed.detail || "AI stream error");
|
|
err.partial = Boolean(parsed.partial);
|
|
throw err;
|
|
}
|
|
};
|
|
|
|
try {
|
|
while (true) {
|
|
if (signal?.aborted) {
|
|
const abortErr = typeof DOMException !== "undefined"
|
|
? new DOMException("Aborted", "AbortError")
|
|
: Object.assign(new Error("Aborted"), { name: "AbortError" });
|
|
throw abortErr;
|
|
}
|
|
const chunk = await reader.read();
|
|
if (chunk.done) break;
|
|
buffered += decoder.decode(chunk.value, { stream: true });
|
|
const { frames, remainder } = consumeSSEFrames(buffered, false);
|
|
buffered = remainder;
|
|
for (const frame of frames) handleFrame(frame);
|
|
}
|
|
buffered += decoder.decode();
|
|
for (const frame of consumeSSEFrames(buffered, true).frames) handleFrame(frame);
|
|
return donePayload;
|
|
} catch (err) {
|
|
failed = true;
|
|
throw err;
|
|
} finally {
|
|
if (failed || signal?.aborted) {
|
|
await reader.cancel().catch(() => {});
|
|
}
|
|
reader.releaseLock?.();
|
|
}
|
|
}
|