import {z} from 'zod' export type MessageType = 'text' | 'markdown' | 'code' | 'image' | 'file' | 'tool_call' | 'tool_result' | 'system_event' | 'thinking'; export type ToolCallPayload = {callId?: string | undefined, toolName?: string | undefined, arguments?: Record | undefined}; export type ToolResultPayload = {callId?: string | undefined, toolName?: string | undefined, result: unknown, isError?: boolean | undefined}; export type MessageMetadata = {language?: string | undefined, fileName?: string | undefined, fileSize?: number | undefined, mimeType?: string | undefined, fileUrl?: string | undefined, toolCall?: ToolCallPayload | undefined, toolResult?: ToolResultPayload | undefined, systemEvent?: ({event?: string | undefined, data?: Record | undefined}) | undefined, isStreaming?: boolean | undefined, streamId?: string | undefined, thinkingStep?: number | undefined}; export type SendMessageRequest = {type?: MessageType | undefined, content?: string | undefined, metadata?: MessageMetadata | undefined, parentId?: string | undefined}; export type CreateApiMessagesConversationIdArgs = {conversationId: string, body: SendMessageRequest}; export type CreateApiMessagesConversationIdOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const messageType = z.enum(["text", "markdown", "code", "image", "file", "tool_call", "tool_result", "system_event", "thinking"]); export const toolCallPayload = z.object({callId: z.string().optional(), toolName: z.string().optional(), arguments: z.object({}).optional()}); export const toolResultPayload = z.object({callId: z.string().optional(), toolName: z.string().optional(), result: z.unknown(), isError: z.boolean().optional()}); export const messageMetadata = z.object({language: z.string().optional(), fileName: z.string().optional(), fileSize: z.number().int().optional(), mimeType: z.string().optional(), fileUrl: z.string().optional(), toolCall: toolCallPayload.optional(), toolResult: toolResultPayload.optional(), systemEvent: z.object({event: z.string().optional(), data: z.object({}).optional()}).optional(), isStreaming: z.boolean().optional(), streamId: z.string().optional(), thinkingStep: z.number().int().optional()}); export const messageStatus = z.enum(["sending", "sent", "delivered", "read", "failed"]); export const message = z.object({id: z.string().optional(), conversationId: z.string().optional(), senderId: z.string().optional(), type: messageType.optional(), content: z.string().optional(), metadata: messageMetadata.optional(), parentId: z.string().optional(), status: messageStatus.optional(), createdAt: z.string().optional(), updatedAt: z.string().optional()}); export const messageResponse = z.object({ok: z.boolean().optional(), data: message.optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * 发送消息 * * POST /messages/{conversationId} */ export const createApiMessagesConversationId = async (args: CreateApiMessagesConversationIdArgs, options?: CreateApiMessagesConversationIdOptions) => { const {baseUrl = "http://localhost:3200/api", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/messages/${encodeURIComponent(String(args.conversationId))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(messageResponse, await res.json()) };