/** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */ /** 前台可见内容摘要,提示词不会下发。 */ export type Card = { id: string; name: string; kind: "character" | "worldbook" | "preset"; version: number; description: string; greeting: string; alternateGreetings: string[]; gender: string; age: number; cover: string; tags: string[]; source: string; entriesCount: number; }; /** 用户自己的身份资料。 */ export type Profile = { favorites: string[]; persona: string; userName: string; /** 登录账号的成人内容偏好;旧服务未返回时沿用默认开启。 */ nsfwEnabled?: boolean; }; /** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */ export type Message = { id: string; role: "user" | "assistant"; content: string; status: string; pinned: boolean; sequenceId?: number; }; /** 不含实验配置的会话偏好。 */ export type Settings = { persona: string; userName: string; memory: string; presetId?: string; bookIds: string[]; }; /** 对话详情。 */ export type Conversation = { id: string; characterId: string; title: string; settings: Settings; busy: boolean; messages: Message[]; }; /** 通用请求保留服务端错误文本,401 自动返回登录。 */ export async function digital( path: string, method = "GET", body?: unknown, signal?: AbortSignal, ): Promise { const response = await fetch(`/api/digital/${path}`, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), signal, }); const data = await response.json(); if (response.status === 401) { window.location.assign("/login"); throw new Error("登录已过期"); } if (!response.ok || data.success === false) throw new Error(data.error?.message ?? data.message ?? "请求失败"); return data.data as T; } /** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */ export async function readStream( response: Response, onEvent: (event: string, data: Record) => void, ) { if (!response.ok) { const p = await response.json(); throw new Error(p.error?.message ?? p.message ?? "发送失败"); } if (!response.body) throw new Error("浏览器不支持流式连接"); const reader = response.body.getReader(), decoder = new TextDecoder(); let buffer = ""; try { for (;;) { const { value, done } = await reader.read(); buffer += ( done ? decoder.decode() : decoder.decode(value, { stream: true }) ).replaceAll("\r\n", "\n"); let end: number; while ((end = buffer.indexOf("\n\n")) >= 0) { const block = buffer.slice(0, end); buffer = buffer.slice(end + 2); const event = block .split("\n") .find((s) => s.startsWith("event:")) ?.slice(6) .trim(); const data = block .split("\n") .filter((s) => s.startsWith("data:")) .map((s) => s.slice(5).trim()) .join("\n"); if (event && data) onEvent(event, JSON.parse(data)); } if (done) break; } } finally { reader.releaseLock(); } } /** 会话列表摘要。 */ export type Summary = { id: string; characterId: string; title: string; updatedAt: string; }; /** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */ export type Bootstrap = { catalog: Card[]; profile: Profile; decision: { variant: string | null; value?: unknown; fallbackValue?: unknown; decisionId: string | null; expiresAt: number; fallbackVariant: string | null; }; serverNow: number; };