2026-05-24 23:30:32 +08:00
|
|
|
import { API_URL, API_KEY, PRO_STREAM_URL, TTS_URL, TTS_STATUS_URL, TTS_CONFIG_URL } from './config.js'
|
2026-02-25 19:00:17 +08:00
|
|
|
import { useSettingsStore } from '../stores/settings'
|
|
|
|
|
|
|
|
|
|
function generateRequestId() {
|
2026-04-11 10:04:34 +08:00
|
|
|
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
|
|
|
return crypto.randomUUID()
|
|
|
|
|
}
|
|
|
|
|
return `${Date.now()}-${Math.random().toString(16).slice(2)}`
|
2026-02-25 19:00:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getCancelUrl(apiUrl) {
|
2026-04-11 10:04:34 +08:00
|
|
|
const normalized = String(apiUrl || '').replace(/\/+$/, '')
|
|
|
|
|
if (!normalized) return '/v1/completions/cancel'
|
2026-05-24 23:30:32 +08:00
|
|
|
if (/\/v1\/pro\/completions\/stream$/i.test(normalized)) {
|
|
|
|
|
return normalized.replace(/\/v1\/pro\/completions\/stream$/i, '/v1/completions/cancel')
|
|
|
|
|
}
|
2026-04-11 10:04:34 +08:00
|
|
|
if (normalized.endsWith('/v1/completions')) {
|
2026-02-25 19:00:17 +08:00
|
|
|
return `${normalized}/cancel`
|
2026-04-11 10:04:34 +08:00
|
|
|
}
|
|
|
|
|
return `${normalized}/cancel`
|
2026-02-25 19:00:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function normalizeAbortReason(reason) {
|
2026-04-11 10:04:34 +08:00
|
|
|
if (typeof reason === 'string' && reason.trim()) {
|
|
|
|
|
return reason.trim().slice(0, 64)
|
|
|
|
|
}
|
|
|
|
|
return 'abort'
|
2026-02-25 19:00:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function sendCancelRequest(cancelUrl, requestId, reason) {
|
2026-04-11 10:04:34 +08:00
|
|
|
try {
|
|
|
|
|
await fetch(cancelUrl, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
'X-API-Key': API_KEY,
|
|
|
|
|
},
|
|
|
|
|
body: JSON.stringify({
|
|
|
|
|
request_id: requestId,
|
|
|
|
|
reason,
|
|
|
|
|
}),
|
|
|
|
|
})
|
|
|
|
|
} catch {
|
|
|
|
|
// Cancel request failed silently
|
|
|
|
|
}
|
2026-02-25 19:00:17 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-24 23:30:32 +08:00
|
|
|
function createAbortError(message = 'Request aborted') {
|
|
|
|
|
const error = new Error(message)
|
|
|
|
|
error.name = 'AbortError'
|
|
|
|
|
return error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function buildCompletionBody(settings, prefix, suffix, languageId, extra = {}) {
|
|
|
|
|
return {
|
|
|
|
|
prefix,
|
|
|
|
|
suffix,
|
|
|
|
|
languageId,
|
|
|
|
|
model_thinking: settings.modelThinking,
|
|
|
|
|
privacy_mode: settings.privacyMode,
|
|
|
|
|
user_preferences: {
|
|
|
|
|
language: settings.language,
|
|
|
|
|
currency: settings.currency,
|
|
|
|
|
timezone: settings.detectedTimezone,
|
|
|
|
|
},
|
|
|
|
|
...extra,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function parseSseEvent(rawEvent) {
|
|
|
|
|
const lines = String(rawEvent || '').replace(/\r/g, '').split('\n')
|
|
|
|
|
let event = 'message'
|
|
|
|
|
const dataLines = []
|
|
|
|
|
|
|
|
|
|
for (const line of lines) {
|
|
|
|
|
if (!line) continue
|
|
|
|
|
if (line.startsWith('event:')) {
|
|
|
|
|
event = line.slice(6).trim() || 'message'
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if (line.startsWith('data:')) {
|
|
|
|
|
dataLines.push(line.slice(5).trimStart())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
event,
|
|
|
|
|
data: dataLines.join('\n'),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-14 18:20:39 +08:00
|
|
|
export async function fetchSuggestion(prefix, suffix, languageId, signal, apiUrl = API_URL) {
|
2026-04-11 10:04:34 +08:00
|
|
|
let normalizedLanguageId = 'markdown'
|
|
|
|
|
if (typeof languageId === 'string' && languageId.trim()) {
|
|
|
|
|
normalizedLanguageId = languageId.trim()
|
|
|
|
|
} else if (languageId && typeof languageId === 'object' && 'aborted' in languageId) {
|
|
|
|
|
signal = languageId
|
|
|
|
|
}
|
|
|
|
|
if (typeof signal === 'string') {
|
|
|
|
|
apiUrl = signal
|
|
|
|
|
signal = undefined
|
|
|
|
|
}
|
|
|
|
|
const requestId = generateRequestId()
|
|
|
|
|
const cancelUrl = getCancelUrl(apiUrl)
|
|
|
|
|
|
|
|
|
|
const onAbort = () => {
|
|
|
|
|
const reason = normalizeAbortReason(signal?.reason)
|
|
|
|
|
void sendCancelRequest(cancelUrl, requestId, reason)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (signal) {
|
|
|
|
|
if (signal.aborted) {
|
|
|
|
|
onAbort()
|
|
|
|
|
} else {
|
|
|
|
|
signal.addEventListener('abort', onAbort, { once: true })
|
2026-03-14 18:20:39 +08:00
|
|
|
}
|
2026-04-11 10:04:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const settings = useSettingsStore()
|
|
|
|
|
const headers = {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
'X-Request-Id': requestId,
|
|
|
|
|
'X-API-Key': API_KEY,
|
2026-03-14 18:20:39 +08:00
|
|
|
}
|
2026-02-25 19:00:17 +08:00
|
|
|
|
2026-05-24 23:30:32 +08:00
|
|
|
const body = buildCompletionBody(settings, prefix, suffix, normalizedLanguageId)
|
2026-02-25 19:00:17 +08:00
|
|
|
|
2026-04-05 23:22:00 +08:00
|
|
|
const res = await fetch(apiUrl, {
|
2026-04-11 10:04:34 +08:00
|
|
|
method: 'POST',
|
|
|
|
|
headers,
|
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
|
signal,
|
2026-04-05 23:22:00 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (!res.ok) {
|
2026-04-11 10:04:34 +08:00
|
|
|
const errorText = await res.text()
|
|
|
|
|
throw new Error(`HTTP ${res.status}: ${errorText}`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const data = await res.json()
|
|
|
|
|
return data.content || ''
|
|
|
|
|
} catch (e) {
|
|
|
|
|
if (e.name === 'AbortError') {
|
|
|
|
|
// ignore abort
|
|
|
|
|
} else {
|
|
|
|
|
throw e
|
|
|
|
|
}
|
|
|
|
|
} finally {
|
|
|
|
|
if (signal) {
|
|
|
|
|
signal.removeEventListener('abort', onAbort)
|
2026-04-05 23:22:00 +08:00
|
|
|
}
|
2026-04-11 10:04:34 +08:00
|
|
|
}
|
|
|
|
|
}
|
2026-04-05 23:22:00 +08:00
|
|
|
|
2026-05-24 23:30:32 +08:00
|
|
|
export async function fetchProSuggestionStream(payload, apiUrl = PRO_STREAM_URL) {
|
|
|
|
|
const {
|
|
|
|
|
prefix = '',
|
|
|
|
|
suffix = '',
|
|
|
|
|
languageId = 'markdown',
|
|
|
|
|
signal,
|
|
|
|
|
model = '',
|
|
|
|
|
temperature = 0.7,
|
|
|
|
|
timeoutMs = 600000,
|
|
|
|
|
onChunk,
|
|
|
|
|
} = payload || {}
|
|
|
|
|
|
|
|
|
|
const settings = useSettingsStore()
|
|
|
|
|
const requestId = generateRequestId()
|
|
|
|
|
const cancelUrl = getCancelUrl(apiUrl)
|
|
|
|
|
const requestController = new AbortController()
|
|
|
|
|
const timeoutId = setTimeout(() => {
|
|
|
|
|
requestController.abort('timeout')
|
|
|
|
|
}, timeoutMs)
|
|
|
|
|
|
|
|
|
|
const relayAbort = () => {
|
|
|
|
|
requestController.abort(signal?.reason || 'abort')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const onAbort = () => {
|
|
|
|
|
const reason = normalizeAbortReason(requestController.signal.reason)
|
|
|
|
|
void sendCancelRequest(cancelUrl, requestId, reason)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
requestController.signal.addEventListener('abort', onAbort, { once: true })
|
|
|
|
|
|
|
|
|
|
if (signal) {
|
|
|
|
|
if (signal.aborted) {
|
|
|
|
|
relayAbort()
|
|
|
|
|
} else {
|
|
|
|
|
signal.addEventListener('abort', relayAbort, { once: true })
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const res = await fetch(apiUrl, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
'X-Request-Id': requestId,
|
|
|
|
|
'X-API-Key': API_KEY,
|
|
|
|
|
},
|
|
|
|
|
body: JSON.stringify(
|
|
|
|
|
buildCompletionBody(settings, prefix, suffix, String(languageId || 'markdown').trim() || 'markdown', {
|
|
|
|
|
model,
|
|
|
|
|
temperature,
|
|
|
|
|
})
|
|
|
|
|
),
|
|
|
|
|
signal: requestController.signal,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
const errorText = await res.text()
|
|
|
|
|
throw new Error(`HTTP ${res.status}: ${errorText}`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!res.body) {
|
|
|
|
|
throw new Error('PRO 模式流式响应不可用')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const reader = res.body.getReader()
|
|
|
|
|
const decoder = new TextDecoder()
|
|
|
|
|
let buffer = ''
|
|
|
|
|
let finalContent = ''
|
|
|
|
|
|
|
|
|
|
while (true) {
|
|
|
|
|
const { done, value } = await reader.read()
|
|
|
|
|
if (done) break
|
|
|
|
|
|
|
|
|
|
buffer += decoder.decode(value, { stream: true })
|
|
|
|
|
|
|
|
|
|
let boundary = buffer.indexOf('\n\n')
|
|
|
|
|
while (boundary >= 0) {
|
|
|
|
|
const chunk = buffer.slice(0, boundary)
|
|
|
|
|
buffer = buffer.slice(boundary + 2)
|
|
|
|
|
|
|
|
|
|
const parsed = parseSseEvent(chunk)
|
|
|
|
|
if (parsed.event === 'chunk' && parsed.data) {
|
|
|
|
|
const data = JSON.parse(parsed.data)
|
|
|
|
|
const delta = String(data.delta || '')
|
|
|
|
|
if (delta) {
|
|
|
|
|
finalContent += delta
|
|
|
|
|
onChunk?.(delta)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (parsed.event === 'done' && parsed.data) {
|
|
|
|
|
const data = JSON.parse(parsed.data)
|
|
|
|
|
return String(data.content || finalContent || '')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (parsed.event === 'error' && parsed.data) {
|
|
|
|
|
const data = JSON.parse(parsed.data)
|
|
|
|
|
throw new Error(String(data.error || 'PRO 模式请求失败'))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (parsed.event === 'cancelled') {
|
|
|
|
|
throw createAbortError('PRO 模式请求已取消')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
boundary = buffer.indexOf('\n\n')
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (requestController.signal.aborted) {
|
|
|
|
|
throw createAbortError('PRO 模式请求已中止')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return finalContent
|
|
|
|
|
} catch (e) {
|
|
|
|
|
if (e?.name === 'AbortError') {
|
|
|
|
|
throw e
|
|
|
|
|
}
|
|
|
|
|
throw e
|
|
|
|
|
} finally {
|
|
|
|
|
clearTimeout(timeoutId)
|
|
|
|
|
requestController.signal.removeEventListener('abort', onAbort)
|
|
|
|
|
if (signal) {
|
|
|
|
|
signal.removeEventListener('abort', relayAbort)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-11 10:04:34 +08:00
|
|
|
export async function fetchTTS(text, instruct = '', apiUrl = TTS_URL) {
|
|
|
|
|
const res = await fetch(apiUrl, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
'X-API-Key': API_KEY,
|
|
|
|
|
},
|
|
|
|
|
body: JSON.stringify({ text, instruct, speaker: 'Vivian', format: 'wav' }),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
const errorText = await res.text()
|
|
|
|
|
throw new Error(`TTS HTTP ${res.status}: ${errorText}`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return res.json()
|
2026-04-05 23:22:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function fetchTTSStatus(apiUrl = TTS_STATUS_URL) {
|
2026-04-11 10:04:34 +08:00
|
|
|
const res = await fetch(apiUrl, {
|
|
|
|
|
headers: { 'X-API-Key': API_KEY },
|
|
|
|
|
})
|
2026-04-05 23:22:00 +08:00
|
|
|
|
2026-04-11 10:04:34 +08:00
|
|
|
if (!res.ok) {
|
|
|
|
|
throw new Error(`TTS Status HTTP ${res.status}`)
|
|
|
|
|
}
|
2026-04-05 23:22:00 +08:00
|
|
|
|
2026-04-11 10:04:34 +08:00
|
|
|
return res.json()
|
2026-04-05 23:22:00 +08:00
|
|
|
}
|
2026-04-07 12:47:16 +08:00
|
|
|
|
|
|
|
|
export async function fetchTTSConfig(apiUrl = TTS_CONFIG_URL) {
|
2026-04-11 10:04:34 +08:00
|
|
|
const res = await fetch(apiUrl, {
|
|
|
|
|
headers: { 'X-API-Key': API_KEY },
|
|
|
|
|
})
|
2026-04-07 12:47:16 +08:00
|
|
|
|
2026-04-11 10:04:34 +08:00
|
|
|
if (!res.ok) {
|
|
|
|
|
throw new Error(`TTS Config HTTP ${res.status}`)
|
|
|
|
|
}
|
2026-04-07 12:47:16 +08:00
|
|
|
|
2026-04-11 10:04:34 +08:00
|
|
|
return res.json()
|
2026-04-07 12:47:16 +08:00
|
|
|
}
|