@huyooo/ai-chat-bridge-electron 0.1.4 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,507 @@
1
+ /**
2
+ * Electron 渲染进程 Adapter
3
+ *
4
+ * 在渲染进程中使用,创建 ChatAdapter
5
+ */
6
+
7
+ import type { AiChatBridge } from '../preload';
8
+
9
+ // 事件类型
10
+ export type ChatEventType =
11
+ | 'thinking_start'
12
+ | 'thinking_delta'
13
+ | 'thinking_end'
14
+ | 'search_start'
15
+ | 'search_result'
16
+ | 'search_end'
17
+ | 'tool_approval_request'
18
+ | 'tool_call_start'
19
+ | 'tool_call_result'
20
+ | 'text_delta'
21
+ | 'image'
22
+ | 'video'
23
+ | 'stream_start'
24
+ | 'done'
25
+ | 'error'
26
+ | 'abort'
27
+ | 'step_start'
28
+ | 'step_end';
29
+
30
+ // ChatEvent 接口
31
+ export interface ChatEvent {
32
+ type: ChatEventType;
33
+ data: unknown;
34
+ }
35
+
36
+ // 对话模式
37
+ export type ChatMode = 'agent' | 'plan' | 'ask';
38
+
39
+ // 供应商类型
40
+ export type ProviderType = 'ark' | 'qwen' | 'gemini' | 'openrouter';
41
+
42
+ // 深度思考模式
43
+ export type ThinkingMode = 'enabled' | 'disabled';
44
+
45
+ // 自动运行模式
46
+ export type AutoRunMode = 'run-everything' | 'manual';
47
+
48
+ // 自动运行配置
49
+ export interface AutoRunConfig {
50
+ /**
51
+ * 自动运行模式
52
+ * - 'run-everything': 运行所有内容(自动执行)
53
+ * - 'manual': 手动批准(每次执行前询问)
54
+ */
55
+ mode?: AutoRunMode;
56
+ }
57
+
58
+ /** 聊天历史消息(无状态架构) */
59
+ export interface ChatHistoryMessage {
60
+ role: 'user' | 'assistant' | 'system' | 'tool';
61
+ content: string;
62
+ }
63
+
64
+ // 聊天选项
65
+ export interface ChatOptions {
66
+ mode?: ChatMode;
67
+ model?: string;
68
+ provider?: ProviderType;
69
+ enableWebSearch?: boolean;
70
+ /** 深度思考开关(每个 provider 内部使用最优参数) */
71
+ thinkingMode?: ThinkingMode;
72
+ /** 自动运行配置 */
73
+ autoRunConfig?: AutoRunConfig;
74
+ /** 对话历史(无状态架构,历史从前端传入) */
75
+ history?: ChatHistoryMessage[];
76
+ }
77
+
78
+ /**
79
+ * 简化的模型配置
80
+ */
81
+ export interface ModelOption {
82
+ /** 模型 ID(发送给 API) */
83
+ modelId: string;
84
+ /** 显示名称 */
85
+ displayName: string;
86
+ /** 分组名称(由后端决定,前端只负责渲染,必填) */
87
+ group: string;
88
+ /** 是否来自 OpenRouter(保留用于兼容,后续可能移除) */
89
+ isOpenRouter?: boolean;
90
+ /** 提供商名称(保留用于兼容,后续可能移除) */
91
+ provider?: string;
92
+ }
93
+
94
+ // 会话记录
95
+ export interface SessionRecord {
96
+ id: string;
97
+ appId: string | null;
98
+ userId: string | null;
99
+ title: string;
100
+ model: string;
101
+ mode: ChatMode;
102
+ webSearchEnabled: boolean;
103
+ thinkingEnabled: boolean;
104
+ /** 是否在 tab 栏隐藏(关闭但不删除) */
105
+ hidden: boolean;
106
+ createdAt: Date;
107
+ updatedAt: Date;
108
+ }
109
+
110
+ // 消息记录
111
+ export interface MessageRecord {
112
+ id: string;
113
+ sessionId: string;
114
+ role: 'user' | 'assistant';
115
+ content: string;
116
+ /** 生成此消息时使用的模型 */
117
+ model?: string | null;
118
+ /** 生成此消息时使用的模式 (ask/agent) */
119
+ mode?: string | null;
120
+ /** 生成此消息时是否启用 web 搜索 */
121
+ webSearchEnabled?: boolean | null;
122
+ /** 生成此消息时是否启用深度思考 */
123
+ thinkingEnabled?: boolean | null;
124
+ /** 执行步骤列表 JSON */
125
+ steps?: string | null;
126
+ operationIds?: string | null;
127
+ timestamp: Date;
128
+ }
129
+
130
+ // 操作记录
131
+ export interface OperationRecord {
132
+ id: string;
133
+ sessionId: string;
134
+ messageId?: string | null;
135
+ command: string;
136
+ operationType: string;
137
+ affectedFiles: string;
138
+ status: string;
139
+ timestamp: Date;
140
+ }
141
+
142
+ // 回收站记录
143
+ export interface TrashRecord {
144
+ id: string;
145
+ sessionId: string;
146
+ originalPath: string;
147
+ trashPath: string;
148
+ deletedAt: Date;
149
+ autoDeleteAt: Date;
150
+ }
151
+
152
+ // 文件信息
153
+ export interface FileInfo {
154
+ name: string;
155
+ path: string;
156
+ isDirectory: boolean;
157
+ size: number;
158
+ modifiedAt: Date;
159
+ extension: string;
160
+ }
161
+
162
+ // ChatAdapter 接口
163
+ export interface ChatAdapter {
164
+ // ============ Chat API ============
165
+ /** 获取可用模型 */
166
+ getModels(): Promise<ModelOption[]>;
167
+ /** 发送消息,返回异步迭代器 */
168
+ sendMessage(message: string, options?: ChatOptions, images?: string[], sessionId?: string): AsyncIterable<ChatEvent>;
169
+ /** 取消当前请求 */
170
+ cancel(): void;
171
+ // 无状态架构:历史通过 ChatOptions.history 传入
172
+ /** 设置当前工作目录 */
173
+ setCwd?(dir: string): void;
174
+
175
+ // ============ Sessions API ============
176
+ /** 获取会话列表 */
177
+ getSessions(): Promise<SessionRecord[]>;
178
+ /** 获取单个会话 */
179
+ getSession(id: string): Promise<SessionRecord | null>;
180
+ /** 创建会话 */
181
+ createSession(params?: { title?: string; model?: string; mode?: string; webSearchEnabled?: boolean; thinkingEnabled?: boolean; hidden?: boolean }): Promise<SessionRecord>;
182
+ /** 更新会话 */
183
+ updateSession(id: string, data: { title?: string; model?: string; mode?: string; webSearchEnabled?: boolean; thinkingEnabled?: boolean; hidden?: boolean }): Promise<SessionRecord | null>;
184
+ /** 删除会话 */
185
+ deleteSession(id: string): Promise<void>;
186
+
187
+ // ============ Messages API ============
188
+ /** 获取会话消息 */
189
+ getMessages(sessionId: string): Promise<MessageRecord[]>;
190
+ /** 保存消息 */
191
+ saveMessage(params: {
192
+ /** 消息 ID(可选,如果不传则自动生成) */
193
+ id?: string;
194
+ sessionId: string;
195
+ role: 'user' | 'assistant';
196
+ content: string;
197
+ /** 生成此消息时使用的模型 */
198
+ model?: string;
199
+ /** 生成此消息时使用的模式 (ask/agent) */
200
+ mode?: string;
201
+ /** 生成此消息时是否启用 web 搜索 */
202
+ webSearchEnabled?: boolean;
203
+ /** 生成此消息时是否启用深度思考 */
204
+ thinkingEnabled?: boolean;
205
+ /** 执行步骤列表 JSON */
206
+ steps?: string;
207
+ operationIds?: string;
208
+ }): Promise<MessageRecord>;
209
+ /** 更新消息(增量保存) */
210
+ updateMessage(params: {
211
+ id: string;
212
+ content?: string;
213
+ steps?: string;
214
+ }): Promise<void>;
215
+ /** 删除指定时间之后的消息(用于分叉) */
216
+ deleteMessagesAfter(sessionId: string, timestamp: number): Promise<void>;
217
+
218
+ // ============ Operations API ============
219
+ /** 获取操作日志 */
220
+ getOperations(sessionId: string): Promise<OperationRecord[]>;
221
+
222
+ // ============ Trash API ============
223
+ /** 获取回收站 */
224
+ getTrashItems(): Promise<TrashRecord[]>;
225
+ /** 恢复回收站项目 */
226
+ restoreFromTrash(id: string): Promise<TrashRecord | undefined>;
227
+
228
+ // ============ File System API ============
229
+ /** 列出目录内容 */
230
+ listDir?(dirPath: string): Promise<FileInfo[]>;
231
+ /** 检查路径是否存在 */
232
+ exists?(filePath: string): Promise<boolean>;
233
+ /** 获取文件信息 */
234
+ stat?(filePath: string): Promise<FileInfo | null>;
235
+ /** 读取文件内容(文本) */
236
+ readFile?(filePath: string): Promise<string | null>;
237
+ /** 读取文件为 base64 */
238
+ readFileBase64?(filePath: string): Promise<string | null>;
239
+ /** 获取用户主目录 */
240
+ homeDir?(): Promise<string>;
241
+ /** 解析路径(处理 ~) */
242
+ resolvePath?(inputPath: string): Promise<string>;
243
+ /** 获取父目录 */
244
+ parentDir?(dirPath: string): Promise<string>;
245
+ /** 监听目录变化 */
246
+ watchDir?(dirPath: string): Promise<boolean>;
247
+ /** 停止监听目录 */
248
+ unwatchDir?(dirPath: string): Promise<void>;
249
+ /** 监听目录变化事件 */
250
+ onDirChange?(callback: (data: { dirPath: string; eventType: string; filename: string | null }) => void): () => void;
251
+
252
+ // ============ Settings API ============
253
+ /** 获取用户设置 */
254
+ getSetting?(key: string): Promise<string | null>;
255
+ /** 设置用户设置 */
256
+ setSetting?(key: string, value: string): Promise<void>;
257
+ /** 获取所有用户设置 */
258
+ getAllSettings?(): Promise<Record<string, string>>;
259
+ /** 删除用户设置 */
260
+ deleteSetting?(key: string): Promise<void>;
261
+
262
+ // ============ Tool Approval API ============
263
+ /** 监听工具批准请求(manual 模式) */
264
+ onToolApprovalRequest?(callback: (request: { id: string; name: string; args: Record<string, unknown> }) => void): () => void;
265
+ /** 响应工具批准请求 */
266
+ respondToolApproval?(id: string, approved: boolean): Promise<void>;
267
+ }
268
+
269
+ // 声明 window 上的 bridge
270
+ declare global {
271
+ interface Window {
272
+ aiChatBridge?: AiChatBridge;
273
+ }
274
+ }
275
+
276
+ export interface CreateAdapterOptions {
277
+ /** 全局变量名 */
278
+ bridgeName?: string;
279
+ }
280
+
281
+ /**
282
+ * 创建 Electron Adapter
283
+ */
284
+ export function createElectronAdapter(options: CreateAdapterOptions = {}): ChatAdapter {
285
+ const { bridgeName = 'aiChatBridge' } = options;
286
+
287
+ const getBridge = (): AiChatBridge => {
288
+ const bridge = (window as unknown as Record<string, unknown>)[bridgeName] as AiChatBridge | undefined;
289
+ if (!bridge) {
290
+ throw new Error(`AI Chat Bridge not found. Make sure to call exposeElectronBridge() in preload.`);
291
+ }
292
+ return bridge;
293
+ };
294
+
295
+ return {
296
+ // ============ Chat API ============
297
+ async getModels(): Promise<ModelOption[]> {
298
+ const bridge = getBridge();
299
+ return bridge.getModels();
300
+ },
301
+
302
+ async *sendMessage(
303
+ message: string,
304
+ options?: ChatOptions,
305
+ images?: string[],
306
+ sessionId?: string
307
+ ): AsyncGenerator<ChatEvent> {
308
+ const bridge = getBridge();
309
+
310
+ const queue: ChatEvent[] = [];
311
+ let resolveNext: (() => void) | null = null;
312
+ let done = false;
313
+
314
+ const cleanup = bridge.onProgress((progress) => {
315
+ const eventWithSession = progress as ChatEvent & { sessionId?: string };
316
+
317
+ // 过滤:只处理属于当前会话的事件(或没有 sessionId 的旧事件)
318
+ if (sessionId && eventWithSession.sessionId && eventWithSession.sessionId !== sessionId) {
319
+ return; // 忽略不属于当前会话的事件
320
+ }
321
+
322
+ queue.push(progress as ChatEvent);
323
+ resolveNext?.();
324
+
325
+ if ((progress as ChatEvent).type === 'done' || (progress as ChatEvent).type === 'error') {
326
+ done = true;
327
+ }
328
+ });
329
+
330
+ bridge.send({ message, images, options, sessionId });
331
+
332
+ try {
333
+ while (!done || queue.length > 0) {
334
+ while (queue.length === 0 && !done) {
335
+ await new Promise<void>(r => resolveNext = r);
336
+ }
337
+
338
+ if (queue.length > 0) {
339
+ const progress = queue.shift()!;
340
+ yield progress;
341
+
342
+ if (progress.type === 'done' || progress.type === 'error') {
343
+ break;
344
+ }
345
+ }
346
+ }
347
+ } finally {
348
+ cleanup();
349
+ }
350
+ },
351
+
352
+ cancel() {
353
+ getBridge().cancel();
354
+ },
355
+
356
+ // 无状态架构:历史通过 ChatOptions.history 传入
357
+
358
+ setCwd(dir: string) {
359
+ getBridge().setCwd(dir);
360
+ },
361
+
362
+ // ============ Sessions API ============
363
+ async getSessions(): Promise<SessionRecord[]> {
364
+ return getBridge().getSessions();
365
+ },
366
+
367
+ async getSession(id: string): Promise<SessionRecord | null> {
368
+ return getBridge().getSession(id);
369
+ },
370
+
371
+ async createSession(params): Promise<SessionRecord> {
372
+ return getBridge().createSession(params);
373
+ },
374
+
375
+ async updateSession(id: string, data): Promise<SessionRecord | null> {
376
+ return getBridge().updateSession(id, data);
377
+ },
378
+
379
+ async deleteSession(id: string): Promise<void> {
380
+ await getBridge().deleteSession(id);
381
+ },
382
+
383
+ // ============ Messages API ============
384
+ async getMessages(sessionId: string): Promise<MessageRecord[]> {
385
+ return getBridge().getMessages(sessionId);
386
+ },
387
+
388
+ async saveMessage(params): Promise<MessageRecord> {
389
+ return getBridge().saveMessage(params);
390
+ },
391
+
392
+ async updateMessage(params): Promise<void> {
393
+ await getBridge().updateMessage(params);
394
+ },
395
+
396
+ async deleteMessagesAfter(sessionId: string, timestamp: number): Promise<void> {
397
+ await getBridge().deleteMessagesAfter(sessionId, timestamp);
398
+ },
399
+
400
+ // ============ Operations API ============
401
+ async getOperations(sessionId: string): Promise<OperationRecord[]> {
402
+ return getBridge().getOperations(sessionId);
403
+ },
404
+
405
+ // ============ Trash API ============
406
+ async getTrashItems(): Promise<TrashRecord[]> {
407
+ return getBridge().getTrashItems();
408
+ },
409
+
410
+ async restoreFromTrash(id: string): Promise<TrashRecord | undefined> {
411
+ return getBridge().restoreFromTrash(id);
412
+ },
413
+
414
+ // ============ File System API ============
415
+ async listDir(dirPath: string): Promise<FileInfo[]> {
416
+ return getBridge().listDir(dirPath);
417
+ },
418
+
419
+ async exists(filePath: string): Promise<boolean> {
420
+ return getBridge().exists(filePath);
421
+ },
422
+
423
+ async stat(filePath: string): Promise<FileInfo | null> {
424
+ return getBridge().stat(filePath);
425
+ },
426
+
427
+ async readFile(filePath: string): Promise<string | null> {
428
+ return getBridge().readFile(filePath);
429
+ },
430
+
431
+ async readFileBase64(filePath: string): Promise<string | null> {
432
+ return getBridge().readFileBase64(filePath);
433
+ },
434
+
435
+ async homeDir(): Promise<string> {
436
+ return getBridge().homeDir();
437
+ },
438
+
439
+ async resolvePath(inputPath: string): Promise<string> {
440
+ return getBridge().resolvePath(inputPath);
441
+ },
442
+
443
+ async parentDir(dirPath: string): Promise<string> {
444
+ return getBridge().parentDir(dirPath);
445
+ },
446
+
447
+ async watchDir(dirPath: string): Promise<boolean> {
448
+ return getBridge().watchDir(dirPath);
449
+ },
450
+
451
+ async unwatchDir(dirPath: string): Promise<void> {
452
+ return getBridge().unwatchDir(dirPath);
453
+ },
454
+
455
+ onDirChange(callback: (data: { dirPath: string; eventType: string; filename: string | null }) => void): () => void {
456
+ return getBridge().onDirChange(callback);
457
+ },
458
+
459
+ // ============ Settings API ============
460
+ async getSetting(key: string): Promise<string | null> {
461
+ const bridge = getBridge();
462
+ if (bridge.getSetting) {
463
+ return bridge.getSetting(key);
464
+ }
465
+ return null;
466
+ },
467
+
468
+ async setSetting(key: string, value: string): Promise<void> {
469
+ const bridge = getBridge();
470
+ if (bridge.setSetting) {
471
+ await bridge.setSetting(key, value);
472
+ }
473
+ },
474
+
475
+ async getAllSettings(): Promise<Record<string, string>> {
476
+ const bridge = getBridge();
477
+ if (bridge.getAllSettings) {
478
+ return bridge.getAllSettings();
479
+ }
480
+ return {};
481
+ },
482
+
483
+ async deleteSetting(key: string): Promise<void> {
484
+ const bridge = getBridge();
485
+ if (bridge.deleteSetting) {
486
+ await bridge.deleteSetting(key);
487
+ }
488
+ },
489
+
490
+ // ============ Tool Approval API ============
491
+ onToolApprovalRequest(callback: (request: { id: string; name: string; args: Record<string, unknown> }) => void): () => void {
492
+ const bridge = getBridge();
493
+ if (bridge.onToolApprovalRequest) {
494
+ return bridge.onToolApprovalRequest(callback);
495
+ }
496
+ // 如果没有实现,返回空清理函数
497
+ return () => {};
498
+ },
499
+
500
+ async respondToolApproval(id: string, approved: boolean): Promise<void> {
501
+ const bridge = getBridge();
502
+ if (bridge.respondToolApproval) {
503
+ return bridge.respondToolApproval(id, approved);
504
+ }
505
+ },
506
+ };
507
+ }