import { newOperationID } from './operationKey' export type KBEnvironment = 'test' | 'production' export interface KBEnvironmentBinding { environment: KBEnvironment revision: number base_url: string key_configured: boolean key_source: string internal_kb_id: string internal_kb_name: string external_kb_id: string external_kb_name: string verification: string checked_at: string | null updated_by: string updated_at: string | null source: 'web' | 'legacy' storage_ready: boolean replanned: number retired_duplicates: number } export interface KBBindingSnapshot { test: KBEnvironmentBinding production: KBEnvironmentBinding storage_ready: boolean } export interface KBCatalogOption { id: string name: string knowledge_count: number } export type KBCatalogStatus = 'ok' | 'empty' | 'unauthorized' | 'unreachable' | 'unsupported' export interface KBCatalog { status: KBCatalogStatus message: string page: number page_size: number total: number options: KBCatalogOption[] } export interface KBCatalogInput { base_revision: number base_url: string key_action: 'keep' | 'replace' api_key?: string page: number page_size: number } export interface KBBindingSaveInput { base_revision: number base_url: string key_action: 'keep' | 'replace' api_key?: string internal_kb_id: string external_kb_id: string } export class KBBindingError extends Error { readonly status: number constructor(message: string, status: number) { super(message) this.name = 'KBBindingError' this.status = status } } const record = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) const text = (value: unknown): string => (typeof value === 'string' ? value : '') const bool = (value: unknown): boolean => value === true const count = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0) function parseBinding(value: unknown): KBEnvironmentBinding { if (!record(value) || (value.environment !== 'test' && value.environment !== 'production')) { throw new Error('知识库绑定响应无效') } return { environment: value.environment, revision: count(value.revision), base_url: text(value.base_url), key_configured: bool(value.key_configured), key_source: text(value.key_source), internal_kb_id: text(value.internal_kb_id), internal_kb_name: text(value.internal_kb_name), external_kb_id: text(value.external_kb_id), external_kb_name: text(value.external_kb_name), verification: text(value.verification), checked_at: typeof value.checked_at === 'string' ? value.checked_at : null, updated_by: text(value.updated_by), updated_at: typeof value.updated_at === 'string' ? value.updated_at : null, source: value.source === 'web' ? 'web' : 'legacy', storage_ready: bool(value.storage_ready), replanned: count(value.replanned), retired_duplicates: count(value.retired_duplicates), } } export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot { if (!record(value) || !record(value.data) || !Array.isArray(value.data.environments)) { throw new Error('知识库绑定响应无效') } const byEnvironment = new Map() for (const item of value.data.environments) { const binding = parseBinding(item) byEnvironment.set(binding.environment, binding) } const test = byEnvironment.get('test') const production = byEnvironment.get('production') if (!test || !production) throw new Error('知识库绑定响应缺少环境') return { test, production, storage_ready: bool(value.data.storage_ready) } } // 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。 export function shortKnowledgeBaseID(value: string): string { return value.length > 8 ? `${value.slice(0, 8)}…` : value } export function knowledgeBaseLabel(id: string, name: string): string { if (!id) return '未绑定' return name ? `${name}(${shortKnowledgeBaseID(id)})` : shortKnowledgeBaseID(id) } export function duplicateSelection(internal: string, external: string): boolean { return internal !== '' && internal === external } // Keep is only legal for exactly the saved address; any other draft address // needs a freshly typed key. This mirrors the server rule so the button state // cannot promise something the server will refuse. export function keyActionFor(saved: KBEnvironmentBinding, baseURL: string, replace: boolean): 'keep' | 'replace' { if (replace || !saved.key_configured) return 'replace' return baseURL.trim() === saved.base_url ? 'keep' : 'replace' } function failureMessage(value: unknown, fallback: string): string { if (record(value) && typeof value.error === 'string' && value.error.trim() !== '') return value.error return fallback } async function readResponse(response: Response): Promise> { if (response.ok) { const payload: unknown = await response.json() return record(payload) ? payload : {} } const failure: unknown = await response.json().catch(() => null) throw new KBBindingError(failureMessage(failure, `知识库绑定请求失败(HTTP ${response.status})`), response.status) } export async function fetchKBBindings(signal?: AbortSignal): Promise { const response = await fetch('/api/v1/kb-bindings', { signal, headers: { Accept: 'application/json' } }) return parseKBBindingSnapshot(await readResponse(response)) } export async function fetchKBCatalog( environment: KBEnvironment, input: KBCatalogInput, signal?: AbortSignal ): Promise { const response = await fetch(`/api/v1/kb-bindings/${environment}/catalog`, { method: 'POST', signal, headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-Governance-Action': 'kb-bindings', 'Idempotency-Key': newOperationID(), }, body: JSON.stringify(input), }) const payload = await readResponse(response) if (!record(payload.data)) throw new Error('知识库列表响应无效') const item = payload.data const status = text(item.status) if (!['ok', 'empty', 'unauthorized', 'unreachable', 'unsupported'].includes(status)) { throw new Error('知识库列表响应无效') } const options = Array.isArray(item.options) ? item.options .filter(record) .map((option) => ({ id: text(option.id), name: text(option.name), knowledge_count: count(option.knowledge_count), })) .filter((option) => option.id) : [] return { status: status as KBCatalogStatus, message: text(item.message), page: count(item.page) || 1, page_size: count(item.page_size) || 20, total: count(item.total), options, } } export async function saveKBBinding( environment: KBEnvironment, input: KBBindingSaveInput, signal?: AbortSignal ): Promise { const response = await fetch(`/api/v1/kb-bindings/${environment}`, { method: 'PUT', signal, headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-Governance-Action': 'kb-bindings', 'Idempotency-Key': newOperationID(), }, body: JSON.stringify(input), }) const payload = await readResponse(response) return parseBinding(payload.data) }