Files
aichat/src/bridge/index.ts
T
2026-11-05 10:46:36 +08:00

61 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { AiBridge, ApplyResult, PolicyContext } from './contracts'
import { createBrowserBridge } from './browser'
import { createWebView2Bridge } from './webview2'
import { SyncCall } from './ai-rpc'
export * from './contracts'
export { createBrowserBridge }
export { createWebView2Bridge }
export { SyncCall }
/** CEF 宿主桥:四个数据/动作方法走 `ai-rpc` 的通用 `SyncCall`。 */
function createCefAiCallBridge(): AiBridge {
return {
getPolicyContext: async () => {
const r = await SyncCall('getPolicyContext')
if (r.ok === false) throw new Error(String(r.message))
return r as unknown as PolicyContext
},
applyStrategy: async (json: string) => {
const r = await SyncCall('applyStrategy', json)
// applyStrategy 的 ok:false 不是"异常",是正常业务结果(重命名/校验失败/解析失败),
// 整个对象按 ApplyResult 返回,调用方自行分流。
return r as unknown as ApplyResult
},
getSkills: async () => {
const r = await SyncCall('getSkills')
if (r.ok === false) throw new Error(String(r.message))
return String(r.md)
},
loadSkill: async (skillName: string) => {
const r = await SyncCall('loadSkill', skillName)
if (r.ok === false) throw new Error(String(r.message))
return String(r.md)
},
}
}
/** 宿主探测用的最小窗口形状,避免 `any`。 */
interface HostWindow extends Window {
chrome?: { webview?: unknown }
}
/**
* 统一入口:页面只认 `AiBridge` 这组自定接口,
* 底下用一薄层适配到具体宿主(`AGENTS.md §4.2`)。
* 迁移到别的引擎时**只改这里**,页面不动。
*/
export function getAiBridge(): AiBridge {
const host = window as unknown as HostWindow
// CEF 宿主
if (typeof host.cefApp === 'object' && host.cefApp !== null) {
return createCefAiCallBridge()
}
// WebView2 宿主
if (host.chrome?.webview) {
return createWebView2Bridge()
}
// 浏览器(Phase 1/2)
return createBrowserBridge()
}