miaopanel
1import { ApiError, api, getCsrf, triggerUnauthorized } from './api'
2import type { AITerminalSuggestion } from './types'
3
4/**
5 * POST a JSON body and consume the server's SSE response. EventSource cannot
6 * carry the CSRF header, so the panel uses fetch + ReadableStream instead.
7 */
8export async function streamChat(
9 path: string,
10 body: unknown,
11 onEvent: (event: string, data: any) => void,
12 signal?: AbortSignal,
13): Promise<void> {
14 let res: Response
15 try {
16 res = await fetch(path, {
17 method: 'POST',
18 headers: {
19 'Content-Type': 'application/json',
20 'X-CSRF-Token': getCsrf(),
21 },
22 credentials: 'same-origin',
23 body: JSON.stringify(body ?? {}),
24 signal,
25 })
26 } catch (e) {
27 if ((e as Error).name === 'AbortError') return
28 throw new ApiError('无法连接面板,请检查网络或服务状态', 0)
29 }
30
31 if (res.status === 401) {
32 triggerUnauthorized()
33 throw new ApiError('登录已过期,请重新登录', 401)
34 }
35
36 const ctype = res.headers.get('Content-Type') ?? ''
37 if (!res.ok || !ctype.includes('text/event-stream')) {
38 let message = `请求失败 (HTTP ${res.status})`
39 try {
40 const env = await res.json()
41 if (env?.msg) message = env.msg
42 } catch {
43 /* non JSON error */
44 }
45 throw new ApiError(message, res.status)
46 }
47
48 const reader = res.body?.getReader()
49 if (!reader) throw new ApiError('当前浏览器不支持流式响应', 0)
50 const decoder = new TextDecoder()
51 let buffer = ''
52 try {
53 for (;;) {
54 const { done, value } = await reader.read()
55 if (done) break
56 buffer += decoder.decode(value, { stream: true })
57 buffer = buffer.replace(/\r\n/g, '\n')
58 let cut = buffer.indexOf('\n\n')
59 while (cut >= 0) {
60 dispatch(buffer.slice(0, cut), onEvent)
61 buffer = buffer.slice(cut + 2)
62 cut = buffer.indexOf('\n\n')
63 }
64 }
65 if (buffer.trim()) dispatch(buffer, onEvent)
66 } catch (e) {
67 if ((e as Error).name === 'AbortError') return
68 throw e
69 } finally {
70 reader.releaseLock()
71 }
72}
73
74function dispatch(chunk: string, onEvent: (event: string, data: any) => void) {
75 let event = 'message'
76 const dataLines: string[] = []
77 for (const line of chunk.split('\n')) {
78 if (line.startsWith('event:')) event = line.slice(6).trim()
79 else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^\s/, ''))
80 }
81 if (dataLines.length === 0) return
82 const raw = dataLines.join('\n')
83 let data: any = raw
84 try {
85 data = JSON.parse(raw)
86 } catch {
87 /* keep raw text */
88 }
89 onEvent(event, data)
90}
91
92/** Ask the terminal assistant for a command suggestion. */
93export function assistTerminal(line: string, mode: string, context: string): Promise<AITerminalSuggestion> {
94 return api.post<AITerminalSuggestion>('api/v1/ai/terminal/assist', { line, mode, context })
95}
96
97/** Ask the assistant to explain the output and optionally propose one next step. */
98export function interpretTerminal(
99 question: string,
100 command: string,
101 output: string,
102): Promise<AITerminalSuggestion> {
103 return api.post<AITerminalSuggestion>('api/v1/ai/terminal/interpret', { question, command, output })
104}