// 本体平台后端交互的轻量封装(使用 fetch,无需额外依赖)。 const BASE = '/api/v1' async function request(method, path, body) { const opts = { method, headers: { 'Content-Type': 'application/json' }, credentials: 'include' // 携带 cookie 用于 session 鉴权 } if (body !== undefined) { opts.body = JSON.stringify(body) } const resp = await fetch(BASE + path, opts) const text = await resp.text() let data = null try { data = text ? JSON.parse(text) : null } catch (e) { data = text } if (!resp.ok) { const msg = (data && data.error) ? data.error : `请求失败(${resp.status})` throw new Error(msg) } return data } export const api = { // 版本自描述(公开) getVersion: () => request('GET', '/version'), getChangelog: () => request('GET', '/version/changelog'), // 返回 Markdown 原文 // 本体 listObjectTypes: () => request('GET', '/ontology/object-types'), // 类型梳理 (analyze / merge / delete-zero-inst) — 仅 manager analyzeTypes: () => request('POST', '/ontology/types/analyze'), mergePreview: (body) => request('POST', '/ontology/types/merge-preview', body), mergeExecute: (body) => request('POST', '/ontology/types/merge-execute', body), deleteZeroInstTypes: () => request('POST', '/ontology/types/delete-zero-inst'), getObjectType: (name) => request('GET', `/ontology/object-types/${name}`), createObjectType: (body) => request('POST', '/ontology/object-types', body), updateObjectType: (name, body) => request('PUT', `/ontology/object-types/${name}`, body), deleteObjectType: (name) => request('DELETE', `/ontology/object-types/${name}`), addProperty: (name, body) => request('POST', `/ontology/object-types/${name}/properties`, body), updateProperty: (id, body) => request('PUT', `/ontology/properties/${id}`, body), deleteProperty: (id) => request('DELETE', `/ontology/properties/${id}`), listLinkTypes: () => request('GET', '/ontology/link-types'), createLinkType: (body) => request('POST', '/ontology/link-types', body), deleteLinkType: (name) => request('DELETE', `/ontology/link-types/${name}`), listActionTypes: () => request('GET', '/ontology/action-types'), createActionType: (body) => request('POST', '/ontology/action-types', body), // Function 元原语(Kinetic ⑤) listFunctionTypes: () => request('GET', '/ontology/function-types'), getFunctionType: (name) => request('GET', `/ontology/function-types/${name}`), createFunctionType: (body) => request('POST', '/ontology/function-types', body), deleteFunctionType: (name) => request('DELETE', `/ontology/function-types/${name}`), invokeFunction: (name, body) => request('POST', `/ontology/function-types/${name}/invoke`, body), // 链接属性(链接本身带字段,P1-3) listLinkProperties: (apiName) => request('GET', `/ontology/link-types/${apiName}/properties`), addLinkProperty: (apiName, body) => request('POST', `/ontology/link-types/${apiName}/properties`, body), deleteLinkProperty: (id) => request('DELETE', `/ontology/link-properties/${id}`), // 物化层(P2-1) listMaterializations: () => request('GET', '/ontology/materializations'), createMaterialization: (body) => request('POST', '/ontology/materializations', body), deleteMaterialization: (name) => request('DELETE', `/ontology/materializations/${name}`), refreshMaterialization: (name) => request('POST', `/ontology/materializations/${name}/refresh`, {}), listMaterializationRows: (name, limit) => request('GET', `/ontology/materializations/${name}/rows?limit=${limit || 100}`), // Backing Sources(P2-2) listBackingSources: () => request('GET', '/ontology/backing-sources'), createBackingSource: (body) => request('POST', '/ontology/backing-sources', body), deleteBackingSource: (name) => request('DELETE', `/ontology/backing-sources/${name}`), // 提示调度:按当前上下文返回 Function/Action 建议列表(2026-08-24) listSuggestions: (params) => { const qs = new URLSearchParams(params || {}).toString() return request('GET', `/ontology/suggestions${qs ? '?' + qs : ''}`) }, // 提交 Action 到目标对象(P0-3:完整契约 + FBA 执行链路) applyAction: (type, pk, actionName, body) => request('POST', `/objects/${type}/${pk}/actions/${actionName}`, body), // Interface 元原语(Semantic ⑦) listInterfaceTypes: () => request('GET', '/ontology/interface-types'), getInterfaceType: (name) => request('GET', `/ontology/interface-types/${name}`), createInterfaceType: (body) => request('POST', '/ontology/interface-types', body), deleteInterfaceType: (name) => request('DELETE', `/ontology/interface-types/${name}`), getGraph: () => request('GET', '/ontology/graph'), // 关系总数(按主体可见性过滤)。getGraph 要把全部节点+边序列化,太重; // 概览只关心数字时用这个(毫秒级返回)。 countLinks: () => request('GET', '/ontology/links/count'), // 实例 listObjects: (params = {}) => { const q = new URLSearchParams(params).toString() return request('GET', '/objects' + (q ? '?' + q : '')) }, getObject: (type, pk) => request('GET', `/objects/${type}/${encodeURIComponent(pk)}`), createObject: (body) => request('POST', '/objects', body), updateObject: (type, pk, body) => request('PUT', `/objects/${type}/${encodeURIComponent(pk)}`, body), deleteObject: (type, pk) => request('DELETE', `/objects/${type}/${encodeURIComponent(pk)}`), // 实例治理(2026-09-05):批量写入 / 变更历史 / 软删除回滚 / 重复扫描 batchCreateObjects: (body) => request('POST', '/objects/batch', body), batchCreateLinks: (body) => request('POST', '/links/batch', body), getObjectHistory: (type, pk) => request('GET', `/objects/${type}/${encodeURIComponent(pk)}/history`), restoreObject: (type, pk) => request('POST', `/objects/${type}/${encodeURIComponent(pk)}/restore`, {}), findDuplicates: (type, threshold=0.9) => request('GET', `/objects/duplicates?type=${encodeURIComponent(type)}&threshold=${threshold}`), listObjectChanges: (params) => request('GET', '/objects/changes?' + new URLSearchParams(params||{}).toString()), createLink: (body) => request('POST', '/links', body), deleteLink: (id) => request('DELETE', `/links/${id}`), // AI 摄取 aiIngest: (body) => request('POST', '/ai/ingest', body), listIngestions: () => request('GET', '/ai/ingest'), getIngestion: (id) => request('GET', `/ai/ingest/${id}`), // 连接器 connObjectTypes: () => request('GET', '/connector/object-types'), connObjects: (type) => request('GET', `/connector/objects/${type}`), connSearch: (q) => request('GET', `/connector/search?q=${encodeURIComponent(q)}`), connQuery: (body) => request('POST', '/connector/query', body), mcpManifest: () => request('GET', '/mcp/manifest'), // 知识管理 kmTree: () => request('GET', '/km/tree'), kmListFiles: (folder = '', opts = {}) => { const q = new URLSearchParams({ folder, ...opts }).toString() return request('GET', '/km/files?' + q) }, kmCreateFolder: (body) => request('POST', '/km/folders', body), kmUpload: (folder, files) => { const fd = new FormData() for (const f of files) fd.append('files', f) return fetch(BASE + '/km/upload?folder=' + encodeURIComponent(folder), { method: 'POST', body: fd }) .then(r => r.json()) }, kmFileMeta: (rel) => request('GET', '/km/file?rel=' + encodeURIComponent(rel)), kmExtract: (body) => request('POST', '/km/extract', body), kmDeleteFiles: (body) => request('DELETE', '/km/files', body), kmSetExcluded: (rel_paths, excluded, reason='') => request('POST', '/km/exclude', {rel_paths, excluded, reason}), kmListConnections: () => request('GET', '/km/connections'), kmCreateConnection: (body) => request('POST', '/km/connections', body), kmConnectionDetail: (id) => request('GET', `/km/connections/${id}`), kmDeleteConnection: (id) => request('DELETE', `/km/connections/${id}`), kmImportConnection: (id) => request('POST', `/km/connections/${id}/import`), kmExtractConnections: (body) => request('POST', '/km/connections/extract', body), // 访问控制 whoami: () => request('GET', '/access/whoami'), listPrincipals: () => request('GET', '/access/principals'), getPrincipal: (name) => request('GET', `/access/principals/${name}`), createPrincipal: (body) => request('POST', '/access/principals', body), updatePrincipal: (name, body) => request('PUT', `/access/principals/${name}`, body), deletePrincipal: (name) => request('DELETE', `/access/principals/${name}`), getClearances: (name) => request('GET', `/access/principals/${name}/clearances`), putClearances: (name, body) => request('PUT', `/access/principals/${name}/clearances`, body), listGrants: () => request('GET', '/access/grants'), createGrant: (body) => request('POST', '/access/grants', body), deleteGrant: (id) => request('DELETE', `/access/grants/${id}`), listMarkings: () => request('GET', '/access/markings'), getObjectMarkings: (type, pk) => request('GET', `/access/objects/${type}/${encodeURIComponent(pk)}/markings`), putObjectMarkings: (type, pk, body) => request('PUT', `/access/objects/${type}/${encodeURIComponent(pk)}/markings`, body), listFieldPolicies: () => request('GET', '/access/field-policies'), createFieldPolicy: (body) => request('POST', '/access/field-policies', body), deleteFieldPolicy: (id) => request('DELETE', `/access/field-policies/${id}`), previewAsPrincipal: (principal) => request('GET', `/access/preview?principal=${encodeURIComponent(principal)}`), listAccessLog: (params = {}) => { const q = new URLSearchParams(params).toString() return request('GET', '/access/log' + (q ? '?' + q : '')) }, accessLogStats: () => request('GET', '/access/log/stats'), // 使用分析(2026-09-11):本体总体/分项使用、用户活跃、共享情况 analyticsOverview: (days = 30) => request('GET', `/analytics/overview?days=${days}`), analyticsTypes: (days = 30) => request('GET', `/analytics/types?days=${days}`), analyticsUsers: (days = 30) => request('GET', `/analytics/users?days=${days}`), analyticsSharing: (days = 30) => request('GET', `/analytics/sharing?days=${days}`), // ---- 账号密码登录与会话 ---- // dev 模式下也支持登录(与 X-API-Key 并存)。登录后浏览器自动带 cookie; // 后端 principalFromRequest 优先识别 cookie → 命名主体。 authLogin: (name, password) => request('POST', '/auth/login', { name, password }), authLogout: () => request('POST', '/auth/logout'), authMe: () => request('GET', '/auth/me'), changePassword: (body) => request('POST', '/auth/change-password', body), // ---- MCP JSON-RPC over SSE(供 ReviewView 等前端组件调用)---- // 用法:api.mcpCall('tools/call', { name, arguments }) // 端点默认走当前 SPA 同源(window.location.origin + '/api/v1/mcp'), // 必要时可通过 api.setMcpEndpoint(url) 覆盖;apiKey 走同源管理器(暂不持久化)。 _mcp: { endpoint: null, apiKey: '' }, setMcpEndpoint(url) { api._mcp.endpoint = url }, setMcpApiKey(key) { api._mcp.apiKey = key }, _mcpEndpoint() { if (api._mcp.endpoint) return api._mcp.endpoint return (typeof location !== 'undefined' ? location.origin : '') + '/api/v1/mcp' }, async mcpCall(method, params, opts = {}) { const endpoint = opts.endpoint || api._mcpEndpoint() const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream' } if (opts.apiKey || api._mcp.apiKey) headers['X-API-Key'] = opts.apiKey || api._mcp.apiKey let res try { res = await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }) }) } catch (netErr) { throw new Error(`网络层失败:${netErr.message}。请检查 MCP 可达 / 是否经代理(见 ReviewView 使用说明)。`) } if (!res.ok) { let body = ''; try { body = await res.text() } catch (e) {} throw new Error(`HTTP ${res.status} ${res.statusText}${body ? ' | ' + body.slice(0, 200) : ''}`) } const text = await res.text() const lines = text.split(/\r?\n/) for (const line of lines) { const t = line.trim() if (t.startsWith('data:')) { const data = t.slice(5).trim() if (data === '[DONE]') continue try { return JSON.parse(data) } catch (e) { throw new Error(`SSE data 非有效 JSON: ${data.slice(0, 120)}... (${e.message})`) } } } try { return JSON.parse(text) } catch (e) { throw new Error('响应不是有效 JSON-RPC') } }, async mcpTools(opts) { const r = await api.mcpCall('tools/list', {}, opts) if (r.error) throw new Error(JSON.stringify(r.error)) return r.result?.tools || [] }, async mcpWhoami(opts) { const tools = await api.mcpTools(opts) if (!tools.find(t => t.name === 'whoami')) return { hasWhoami: false } const r = await api.mcpCall('tools/call', { name: 'whoami', arguments: {} }, opts) if (r.error) throw new Error(JSON.stringify(r.error)) const text = (r.result?.content?.[0]?.text) || JSON.stringify(r.result) const info = JSON.parse(text) return { hasWhoami: true, principal: info.principal, can_write: !!info.can_write, clearances: info.clearances } }, mcpUnwrapText(r) { const c = r?.result?.content if (Array.isArray(c) && c.length) return c[0].text if (typeof r?.result === 'string') return r.result if (r?.result) return JSON.stringify(r.result) return JSON.stringify(r?.error ?? r) } }