接口联调
This commit is contained in:
1 parent
43df9175df
commit
8673eb5eca
148 files changed
+2050
-37963
No files matched your search
@@ -3,10 +3,27 @@ import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
export type ThreadIdMap = Record<string, string>;
|
||||
|
||||
export interface SeatReadyEvent {
|
||||
agentName: string;
|
||||
threadId: string;
|
||||
displayName: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface CoordinatorReadyEvent {
|
||||
mainAgentName: string;
|
||||
threadId: string;
|
||||
}
|
||||
|
||||
export interface InitMultiAgentRequest {
|
||||
agentNames: string[];
|
||||
mainAgentName: string;
|
||||
model?: string;
|
||||
/** Fires the moment each sub-agent's thread is ready (real completion order). */
|
||||
onSeatReady?: (event: SeatReadyEvent) => void;
|
||||
/** Fires when the coordinator's thread + agent have been created. */
|
||||
onCoordinatorReady?: (event: CoordinatorReadyEvent) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface InitMultiAgentResponse {
|
||||
@@ -15,6 +32,12 @@ export interface InitMultiAgentResponse {
|
||||
thread_ids: ThreadIdMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the /api/multi-agent/init SSE stream. Fires per-seat / coordinator
|
||||
* callbacks as events arrive so the UI can light up roles individually, and
|
||||
* resolves with the final {main_agent_name, thread_ids} once init_done lands.
|
||||
* If the server emits an "error" frame mid-stream, the promise rejects.
|
||||
*/
|
||||
export async function initMultiAgent(
|
||||
payload: InitMultiAgentRequest,
|
||||
): Promise<InitMultiAgentResponse> {
|
||||
@@ -26,18 +49,114 @@ export async function initMultiAgent(
|
||||
main_agent_name: payload.mainAgentName,
|
||||
model: payload.model,
|
||||
}),
|
||||
signal: payload.signal,
|
||||
});
|
||||
if (!res.ok) {
|
||||
if (!res.ok || !res.body) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(`init multi-agent failed (${res.status}): ${text}`);
|
||||
}
|
||||
return (await res.json()) as InitMultiAgentResponse;
|
||||
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let mainAgentName = "";
|
||||
let threadIds: ThreadIdMap | null = null;
|
||||
let aborted = false;
|
||||
let errorDetail: string | null = null;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (!line.startsWith("data:")) continue;
|
||||
const data = line.slice(5).trim();
|
||||
if (!data) continue;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(data);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!parsed || typeof parsed !== "object") continue;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
const event = typeof obj.event === "string" ? obj.event : "";
|
||||
switch (event) {
|
||||
case "seat_ready": {
|
||||
payload.onSeatReady?.({
|
||||
agentName: String(obj.agent_name ?? ""),
|
||||
threadId: String(obj.thread_id ?? ""),
|
||||
displayName: String(obj.display_name ?? ""),
|
||||
description: String(obj.description ?? ""),
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "coordinator_ready": {
|
||||
payload.onCoordinatorReady?.({
|
||||
mainAgentName: String(obj.main_agent_name ?? ""),
|
||||
threadId: String(obj.thread_id ?? ""),
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "init_done": {
|
||||
mainAgentName = String(obj.main_agent_name ?? "");
|
||||
threadIds = (obj.thread_ids ?? {}) as ThreadIdMap;
|
||||
break;
|
||||
}
|
||||
case "error": {
|
||||
errorDetail = String(obj.detail ?? "unknown init error");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Unknown event — ignore for forward-compat.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
aborted = (err as Error)?.name === "AbortError" || payload.signal?.aborted === true;
|
||||
if (!aborted) throw err;
|
||||
}
|
||||
|
||||
if (errorDetail) {
|
||||
throw new Error(`init multi-agent failed: ${errorDetail}`);
|
||||
}
|
||||
if (aborted) {
|
||||
throw new DOMException("init aborted", "AbortError");
|
||||
}
|
||||
if (!threadIds || !mainAgentName) {
|
||||
throw new Error("init multi-agent stream ended without init_done");
|
||||
}
|
||||
return {
|
||||
status: "success",
|
||||
main_agent_name: mainAgentName,
|
||||
thread_ids: threadIds,
|
||||
};
|
||||
}
|
||||
|
||||
export type StreamAgentType = "leader" | "special";
|
||||
|
||||
export type LeaderDispatch = [string, string];
|
||||
|
||||
/**
|
||||
* High-level phases the SSE stream goes through. Used by the UI to show
|
||||
* "what the backend is doing" while the user waits — most of the time before
|
||||
* a first token is upstream/LLM latency, which feels like a stall otherwise.
|
||||
*
|
||||
* - `connecting` — fetch sent, no frames yet
|
||||
* - `connected` — got the `event: metadata` frame (run_id assigned)
|
||||
* - `streaming` — first AI text chunk arrived; tokens flowing
|
||||
* - `tool_calling` — model emitted a tool_call chunk (e.g. agent_orchestration,
|
||||
* present_files); usually means the run is about to interrupt
|
||||
* - `tool_result` — a tool result message came back; brief, may go back to streaming
|
||||
*/
|
||||
export type StreamPhase = "connecting" | "connected" | "streaming" | "tool_calling" | "tool_result";
|
||||
|
||||
export interface StreamMultiAgentRequest {
|
||||
agentType: StreamAgentType;
|
||||
dAgentThreadId: ThreadIdMap;
|
||||
@@ -54,6 +173,25 @@ export interface StreamMultiAgentRequest {
|
||||
* `messageId` is stable per AI message so callers can group deltas.
|
||||
*/
|
||||
onTextDelta?: (text: string, messageId: string) => void;
|
||||
/**
|
||||
* Fires whenever the inferred SSE phase changes. The UI can use this to
|
||||
* show progressive status messages during the inevitable first-token wait.
|
||||
* `name` is the tool name when phase is `tool_calling` (or empty otherwise).
|
||||
*/
|
||||
onPhaseChange?: (phase: StreamPhase, name?: string) => void;
|
||||
}
|
||||
|
||||
export interface ClarificationPayload {
|
||||
/** Raw question text from the model's ask_clarification args. */
|
||||
question: string;
|
||||
/** Optional category hint from the model (e.g. "missing_info"). */
|
||||
clarificationType: string;
|
||||
/** Free-text reason the model needs clarification. */
|
||||
context: string;
|
||||
/** Suggested answer chips (may be empty). */
|
||||
options: unknown[];
|
||||
/** Whether the user is allowed to type a custom answer. */
|
||||
allowCustom: boolean;
|
||||
}
|
||||
|
||||
export interface StreamMultiAgentResult {
|
||||
@@ -65,6 +203,14 @@ export interface StreamMultiAgentResult {
|
||||
content: string;
|
||||
/** Echoed agent_name of the agent that produced this run. */
|
||||
agentName: string | null;
|
||||
/**
|
||||
* Populated when the leader called ask_clarification — the run ended without
|
||||
* dispatching, and the model is asking the user a question instead. When
|
||||
* present, callers should render `content` (or `clarification.question` as
|
||||
* a fallback) as a question and collect a user reply rather than treating
|
||||
* an empty `dispatched` as consensus.
|
||||
*/
|
||||
clarification: ClarificationPayload | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,6 +222,11 @@ function isFinalStatusFrame(value: unknown): value is {
|
||||
status: LeaderDispatch[] | string;
|
||||
content?: string;
|
||||
agent_name?: string;
|
||||
question?: string;
|
||||
clarification_type?: string;
|
||||
clarification_context?: string;
|
||||
options?: unknown[];
|
||||
allow_custom?: boolean;
|
||||
} {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
if (!("status" in value) || !("content" in value)) return false;
|
||||
@@ -125,6 +276,44 @@ function extractAiTextDelta(parsed: unknown): { text: string; id: string } | nul
|
||||
return { text, id };
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a browser download for a text blob. No-op outside the browser.
|
||||
* Used by streamMultiAgent's dump-to-file debug mode.
|
||||
*/
|
||||
function downloadTextBlob(filename: string, text: string): void {
|
||||
if (typeof window === "undefined" || typeof document === "undefined") return;
|
||||
try {
|
||||
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.style.display = "none";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
// Defer revoke so the browser has a chance to start the download.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
} catch (err) {
|
||||
// Downloads must never break the actual stream — just log and continue.
|
||||
console.warn("[stream] downloadTextBlob failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether streamMultiAgent should auto-download the raw SSE transcript to a
|
||||
* .txt when each call ends. Default ON for now because we're debugging the
|
||||
* "sub-agent stream looks empty" issue and the browser console truncates
|
||||
* large message logs. Toggle from devtools:
|
||||
* window.__MULTI_AGENT_DUMP__ = false
|
||||
*/
|
||||
function isDumpEnabled(): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
const flag = (window as unknown as { __MULTI_AGENT_DUMP__?: boolean }).__MULTI_AGENT_DUMP__;
|
||||
// Default: enabled. Only disabled if explicitly set to false.
|
||||
return flag !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open an SSE connection to /api/multi-agent/run/stream and resolve once the
|
||||
* stream completes. The final frame (`{status: ...}`) is interpreted; every
|
||||
@@ -168,66 +357,184 @@ export async function streamMultiAgent(
|
||||
typeof window !== "undefined" &&
|
||||
(window as unknown as { __MULTI_AGENT_DEBUG__?: boolean }).__MULTI_AGENT_DEBUG__ !== false;
|
||||
|
||||
const result: StreamMultiAgentResult = { dispatched: [], message: null, content: "", agentName: null };
|
||||
// Raw SSE transcript buffer. Every raw line read from the stream (event:,
|
||||
// data:, blank framing lines, anything) is appended verbatim so the dumped
|
||||
// .txt is byte-for-byte what the frontend received off the socket. This is
|
||||
// independent of parsing: even malformed/non-JSON frames end up in the file.
|
||||
const dumpEnabled = isDumpEnabled();
|
||||
const transcript: string[] = dumpEnabled
|
||||
? [
|
||||
`# multi-agent stream transcript`,
|
||||
`# agent_type: ${req.agentType}`,
|
||||
`# agent_name: ${req.agentName}`,
|
||||
`# started_at: ${new Date().toISOString()}`,
|
||||
`# new_message: ${req.newMessage.replace(/\n/g, " ⏎ ")}`,
|
||||
`# model: ${req.model ?? "(default)"}`,
|
||||
`# ---- raw SSE follows ----`,
|
||||
"",
|
||||
]
|
||||
: [];
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const result: StreamMultiAgentResult = {
|
||||
dispatched: [],
|
||||
message: null,
|
||||
content: "",
|
||||
agentName: null,
|
||||
clarification: null,
|
||||
};
|
||||
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
// Inferred SSE phase + a tiny helper so we only fire onPhaseChange when the
|
||||
// value actually changes (the reader loop sees many frames per phase).
|
||||
let currentPhase: StreamPhase = "connecting";
|
||||
req.onPhaseChange?.("connecting");
|
||||
const setPhase = (next: StreamPhase, name?: string) => {
|
||||
if (next === currentPhase && !name) return;
|
||||
currentPhase = next;
|
||||
req.onPhaseChange?.(next, name);
|
||||
};
|
||||
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (!line) continue;
|
||||
if (line.startsWith("event:")) {
|
||||
lastEvent = line.slice(6).trim();
|
||||
continue;
|
||||
}
|
||||
if (!line.startsWith("data:")) continue;
|
||||
const payload = line.slice(5).trim();
|
||||
if (!payload) continue;
|
||||
// Wrap the read loop so we always flush the transcript to disk, even on
|
||||
// abort / network failure. Otherwise an interrupted run would lose the very
|
||||
// evidence we want to inspect.
|
||||
const finishDump = (reason: string) => {
|
||||
if (!dumpEnabled) return;
|
||||
transcript.push("");
|
||||
transcript.push(`# ---- stream ended (${reason}) ----`);
|
||||
transcript.push(`# ended_at: ${new Date().toISOString()}`);
|
||||
transcript.push(`# frames_parsed: ${frameSeq}`);
|
||||
transcript.push(`# final_content_length: ${result.content.length}`);
|
||||
transcript.push(`# dispatched_count: ${result.dispatched.length}`);
|
||||
const tsSafe = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const nameSafe = req.agentName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const filename = `multi-agent_${req.agentType}_${nameSafe}_${tsSafe}.txt`;
|
||||
downloadTextBlob(filename, transcript.join("\n"));
|
||||
};
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(payload);
|
||||
} catch {
|
||||
if (debugEnabled) console.debug(debugLabel, `bad JSON in event=${lastEvent}:`, payload.slice(0, 200));
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
const chunk = decoder.decode(value, { stream: true });
|
||||
buffer += chunk;
|
||||
|
||||
frameSeq += 1;
|
||||
if (debugEnabled) console.debug(debugLabel, `frame#${frameSeq} event=${lastEvent}`, parsed);
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
|
||||
if (isFinalStatusFrame(parsed)) {
|
||||
if (Array.isArray(parsed.status)) {
|
||||
result.dispatched = parsed.status;
|
||||
} else {
|
||||
result.message = parsed.status;
|
||||
for (const rawLine of lines) {
|
||||
// Record EVERY raw line — including blank framing lines and event:
|
||||
// headers — so the dumped transcript matches what the socket sent.
|
||||
if (dumpEnabled) transcript.push(rawLine);
|
||||
|
||||
const line = rawLine.trimEnd();
|
||||
if (!line) continue;
|
||||
if (line.startsWith("event:")) {
|
||||
lastEvent = line.slice(6).trim();
|
||||
// First metadata frame = run accepted by upstream. Move phase out
|
||||
// of "connecting" so the UI can switch from "调度中" to "已连接".
|
||||
if (lastEvent === "metadata" && currentPhase === "connecting") {
|
||||
setPhase("connected");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (typeof parsed.content === "string") {
|
||||
result.content = parsed.content;
|
||||
}
|
||||
if (typeof parsed.agent_name === "string") {
|
||||
result.agentName = parsed.agent_name;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!line.startsWith("data:")) continue;
|
||||
const payload = line.slice(5).trim();
|
||||
if (!payload) continue;
|
||||
|
||||
const delta = extractAiTextDelta(parsed);
|
||||
if (delta) {
|
||||
if (debugEnabled) console.debug(debugLabel, `→ delta (${delta.text.length} chars)`);
|
||||
req.onTextDelta?.(delta.text, delta.id);
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(payload);
|
||||
} catch {
|
||||
if (debugEnabled) console.debug(debugLabel, `bad JSON in event=${lastEvent}:`, payload.slice(0, 200));
|
||||
continue;
|
||||
}
|
||||
|
||||
req.onUpstreamFrame?.(parsed);
|
||||
frameSeq += 1;
|
||||
if (debugEnabled) console.debug(debugLabel, `frame#${frameSeq} event=${lastEvent}`, parsed);
|
||||
|
||||
// Phase inference from LangGraph messages-tuple frames. We only flip
|
||||
// to tool_calling/tool_result on chunks that clearly indicate them;
|
||||
// everything else with non-empty AI text means we're streaming.
|
||||
if (lastEvent === "messages" && Array.isArray(parsed) && parsed.length > 0) {
|
||||
const chunk = parsed[0];
|
||||
if (chunk && typeof chunk === "object") {
|
||||
const chunkObj = chunk as Record<string, unknown>;
|
||||
const chunkType = String(chunkObj.type ?? "").toLowerCase();
|
||||
const toolCalls = chunkObj.tool_calls;
|
||||
const toolCallChunks = chunkObj.tool_call_chunks;
|
||||
const content = chunkObj.content;
|
||||
const hasToolCall =
|
||||
(Array.isArray(toolCalls) && toolCalls.length > 0) ||
|
||||
(Array.isArray(toolCallChunks) && toolCallChunks.length > 0);
|
||||
if (chunkType === "tool") {
|
||||
setPhase("tool_result");
|
||||
} else if (hasToolCall) {
|
||||
// Pick the most informative name we can find in either field.
|
||||
const firstCall = Array.isArray(toolCalls) && toolCalls.length > 0
|
||||
? (toolCalls[0] as Record<string, unknown>)
|
||||
: Array.isArray(toolCallChunks) && toolCallChunks.length > 0
|
||||
? (toolCallChunks[0] as Record<string, unknown>)
|
||||
: null;
|
||||
const toolName = firstCall && typeof firstCall.name === "string" ? firstCall.name : "";
|
||||
setPhase("tool_calling", toolName);
|
||||
} else if (
|
||||
(chunkType === "ai" || chunkType === "aimessagechunk" || chunkType === "aimessage") &&
|
||||
((typeof content === "string" && content.length > 0) || (Array.isArray(content) && content.length > 0))
|
||||
) {
|
||||
setPhase("streaming");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isFinalStatusFrame(parsed)) {
|
||||
if (Array.isArray(parsed.status)) {
|
||||
result.dispatched = parsed.status;
|
||||
} else {
|
||||
result.message = parsed.status;
|
||||
// "clarification" status carries the leader's ask_clarification
|
||||
// payload. Extract the structured fields so the page can render
|
||||
// a question (or chip choices) instead of mistaking the run for
|
||||
// a consensus.
|
||||
if (parsed.status === "clarification") {
|
||||
result.clarification = {
|
||||
question: typeof parsed.question === "string" ? parsed.question : "",
|
||||
clarificationType:
|
||||
typeof parsed.clarification_type === "string" ? parsed.clarification_type : "",
|
||||
context:
|
||||
typeof parsed.clarification_context === "string" ? parsed.clarification_context : "",
|
||||
options: Array.isArray(parsed.options) ? parsed.options : [],
|
||||
allowCustom: parsed.allow_custom !== false,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (typeof parsed.content === "string") {
|
||||
result.content = parsed.content;
|
||||
}
|
||||
if (typeof parsed.agent_name === "string") {
|
||||
result.agentName = parsed.agent_name;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const delta = extractAiTextDelta(parsed);
|
||||
if (delta) {
|
||||
if (debugEnabled) console.debug(debugLabel, `→ delta (${delta.text.length} chars)`);
|
||||
req.onTextDelta?.(delta.text, delta.id);
|
||||
}
|
||||
|
||||
req.onUpstreamFrame?.(parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (debugEnabled) {
|
||||
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
|
||||
if (debugEnabled) {
|
||||
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
|
||||
}
|
||||
finishDump("normal");
|
||||
return result;
|
||||
} catch (err) {
|
||||
// Flush whatever we got so the user can still inspect the transcript on
|
||||
// abort / network drop. Then rethrow so callers' own handling runs.
|
||||
const aborted = (err as Error)?.name === "AbortError" || req.signal?.aborted === true;
|
||||
finishDump(aborted ? "aborted" : `error: ${(err as Error)?.message ?? String(err)}`);
|
||||
throw err;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user