Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
968 lines (853 loc) · 42.8 KB
/
Copy pathbackground.js
File metadata and controls
968 lines (853 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
if (typeof importScripts === "function") importScripts("src/model-parameters.js");
const extensionApi = globalThis.browser || globalThis.chrome;
let workspaceOpenQueue = Promise.resolve();
let lastCreatedWorkspace;
extensionApi.action.onClicked.addListener((tab) => {
openChatWorkspace(tab.windowId).catch(console.error);
});
extensionApi.sidePanel?.onOpened?.addListener(({ windowId, tabId }) => {
if (tabId === undefined) {
extensionApi.storage.session.set({ [`workspaceSidePanel:${windowId}`]: true }).catch(console.error);
}
});
extensionApi.sidePanel?.onClosed?.addListener(({ windowId, tabId }) => {
if (tabId === undefined) {
extensionApi.storage.session.remove(`workspaceSidePanel:${windowId}`).catch(console.error);
}
});
function openChatWorkspace(windowId) {
const url = extensionApi.runtime.getURL("chat.html");
const open = async () => {
if (extensionApi.runtime.getContexts) {
const contexts = await extensionApi.runtime.getContexts({ contextTypes: ["TAB"], documentUrls: [url] });
const workspace = contexts.find((context) => context.windowId === windowId) || contexts[0];
const tab = workspace || (!lastCreatedWorkspace
? null
: await extensionApi.tabs.get(lastCreatedWorkspace.id).catch(() => null));
const stillLoading = !workspace && tab?.status === "loading" && !tab.url && !tab.pendingUrl
&& Date.now() - lastCreatedWorkspace.createdAt < 2000;
if (tab && (workspace || tab.url === url || tab.pendingUrl === url || stillLoading)) {
try {
await extensionApi.tabs.update(workspace ? tab.tabId : tab.id, { active: true });
await extensionApi.windows.update(tab.windowId, { focused: true });
return;
} catch {
// The tab or window may have closed between lookup and activation.
}
}
}
const created = await extensionApi.tabs.create({ url });
lastCreatedWorkspace = { id: created.id, createdAt: Date.now() };
};
const pending = workspaceOpenQueue.then(open);
workspaceOpenQueue = pending.catch(() => {});
return pending;
}
const BG_TEXT = {
"zh-CN": {
titleFailed: "标题生成失败。",
healthFailed: "连接检查失败。",
ollamaFailed: "无法连接 Ollama。",
requestFailed: "请求失败,请检查接口配置。",
missingEndpointModel: "请先在设置中填写接口地址和模型名。",
missingOllamaEndpoint: "请先填写 Ollama 接口地址。",
missingEndpointModelShort: "请先填写接口地址和模型名。",
ollamaModelMissing: "Ollama 可连接,但未找到模型 {model}。",
modelAvailable: "{model} 可用",
titlePrompt: "请为以上对话生成一个简洁标题。只输出标题,不要解释,最多 12 个中文字符或 8 个英文单词。",
thinkingPrompt: "请在回答前进行充分分析,但只输出结论、必要推理摘要和可执行建议,不要输出完整隐藏思维过程。",
nonJson: "接口返回的不是 JSON:{text}",
ollamaModelNotFound: "Ollama 模型不存在:{message}。请点击“测试 Ollama”,从本地模型列表里选择已安装模型后保存。",
custom404: "自定义 API 返回 404,当前地址不是聊天接口:{url}。OpenAI 兼容服务通常需要 /v1/chat/completions;如果你的服务是 Ollama 格式,请在设置里把接口格式改为 Ollama /api/chat。",
ollama403: "Ollama 拒绝了扩展来源。请设置 OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" 后完全重启 Ollama。",
ollamaFetchFailed: "无法连接 Ollama:{message}。请确认 Ollama 已启动,接口地址为 http://127.0.0.1:11434/api/chat,并允许扩展来源。",
apiKeyInvalid: "API Key 包含非英文字符或备注文字,请重新粘贴纯 API Key 后保存。",
endpointInvalid: "请输入有效的 HTTP 或 HTTPS 接口地址。",
endpointPermissionRequired: "请在模型设置中保存接口地址并允许访问该域名。",
answerLanguagePrompt: "除非用户明确要求其他语言,请默认使用{language}回答。",
statusFailed: "请求失败 {status}:{message}"
},
"en-US": {
titleFailed: "Title generation failed.",
healthFailed: "Connection check failed.",
ollamaFailed: "Could not connect to Ollama.",
requestFailed: "Request failed. Please check the API settings.",
missingEndpointModel: "Please fill in the endpoint and model in settings first.",
missingOllamaEndpoint: "Please fill in the Ollama endpoint first.",
missingEndpointModelShort: "Please fill in the endpoint and model first.",
ollamaModelMissing: "Ollama is reachable, but model {model} was not found.",
modelAvailable: "{model} available",
titlePrompt: "Generate a concise title for the conversation above. Output only the title, no explanation. Maximum 8 English words or 12 Chinese characters.",
thinkingPrompt: "Analyze carefully before answering, but only output the conclusion, a necessary reasoning summary, and actionable suggestions. Do not reveal hidden chain-of-thought.",
nonJson: "The API did not return JSON: {text}",
ollamaModelNotFound: "Ollama model not found: {message}. Click \"Test Ollama\", choose an installed local model, then save.",
custom404: "Custom API returned 404. The current URL is not a chat endpoint: {url}. OpenAI-compatible services usually need /v1/chat/completions. If this is an Ollama-format service, change API Format to Ollama /api/chat in settings.",
ollama403: "Ollama rejected the extension origin. Set OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" and fully restart Ollama.",
ollamaFetchFailed: "Could not connect to Ollama: {message}. Make sure Ollama is running, the endpoint is http://127.0.0.1:11434/api/chat, and the extension origin is allowed.",
apiKeyInvalid: "The API key contains non-English characters or notes. Paste the raw API key and save again.",
endpointInvalid: "Enter a valid HTTP or HTTPS endpoint.",
endpointPermissionRequired: "Save the endpoint in Model Settings and allow access to its host.",
answerLanguagePrompt: "Unless the user explicitly asks for another language, answer in {language} by default.",
statusFailed: "Request failed {status}: {message}"
}
};
Object.assign(BG_TEXT, {
"zh-TW": {
titleFailed: "標題生成失敗。",
healthFailed: "連線檢查失敗。",
ollamaFailed: "無法連線 Ollama。",
requestFailed: "請求失敗,請檢查介面設定。",
missingEndpointModel: "請先在設定中填寫介面位址和模型名稱。",
missingOllamaEndpoint: "請先填寫 Ollama 介面位址。",
missingEndpointModelShort: "請先填寫介面位址和模型名稱。",
ollamaModelMissing: "Ollama 可連線,但找不到模型 {model}。",
modelAvailable: "{model} 可用",
titlePrompt: "請為以上對話生成一個簡潔標題。只輸出標題,不要解釋,最多 12 個中文字元或 8 個英文單字。",
thinkingPrompt: "請在回答前充分分析,但只輸出結論、必要推理摘要和可執行建議,不要輸出完整隱藏思維過程。",
nonJson: "介面回傳的不是 JSON:{text}",
ollamaModelNotFound: "Ollama 模型不存在:{message}。請點選「測試 Ollama」,從本機模型清單選擇已安裝模型後儲存。",
custom404: "自訂 API 回傳 404,目前位址不是聊天介面:{url}。OpenAI 相容服務通常需要 /v1/chat/completions;如果你的服務是 Ollama 格式,請在設定中把介面格式改為 Ollama /api/chat。",
ollama403: "Ollama 拒絕了擴充功能來源。請設定 OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" 後完整重新啟動 Ollama。",
ollamaFetchFailed: "無法連線 Ollama:{message}。請確認 Ollama 已啟動,介面位址為 http://127.0.0.1:11434/api/chat,並允許擴充功能來源。",
apiKeyInvalid: "API 金鑰包含不支援的字元,請重新貼上原始金鑰後儲存。",
endpointInvalid: "請輸入有效的 HTTP 或 HTTPS 介面位址。",
endpointPermissionRequired: "請在模型設定中儲存介面位址並允許存取該網域。",
answerLanguagePrompt: "除非使用者明確要求其他語言,請預設使用{language}回答。",
statusFailed: "請求失敗 {status}:{message}"
},
"ja-JP": {
titleFailed: "タイトル生成に失敗しました。",
healthFailed: "接続確認に失敗しました。",
ollamaFailed: "Ollama に接続できません。",
requestFailed: "リクエストに失敗しました。API 設定を確認してください。",
missingEndpointModel: "先に設定でエンドポイントとモデル名を入力してください。",
missingOllamaEndpoint: "先に Ollama エンドポイントを入力してください。",
missingEndpointModelShort: "先にエンドポイントとモデル名を入力してください。",
ollamaModelMissing: "Ollama には接続できますが、モデル {model} が見つかりません。",
modelAvailable: "{model} は利用可能です",
titlePrompt: "上の会話に短いタイトルを付けてください。タイトルだけを出力し、説明は不要です。最大 8 英単語または 12 中国語文字。",
thinkingPrompt: "回答前に十分分析してください。ただし出力は結論、必要な推論要約、実行可能な提案だけにし、隠れた思考過程は出力しないでください。",
nonJson: "API が JSON を返しませんでした: {text}",
ollamaModelNotFound: "Ollama モデルが見つかりません: {message}。「Ollama をテスト」をクリックし、インストール済みのローカルモデルを選んで保存してください。",
custom404: "カスタム API が 404 を返しました。現在の URL はチャットエンドポイントではありません: {url}。OpenAI 互換サービスでは通常 /v1/chat/completions が必要です。Ollama 形式のサービスなら、設定で API 形式を Ollama /api/chat に変更してください。",
ollama403: "Ollama が拡張機能の origin を拒否しました。OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" を設定し、Ollama を完全に再起動してください。",
ollamaFetchFailed: "Ollama に接続できません: {message}。Ollama が起動していること、エンドポイントが http://127.0.0.1:11434/api/chat であること、拡張機能の origin が許可されていることを確認してください。",
apiKeyInvalid: "API キーに使用できない文字が含まれています。API キーのみを貼り付けて保存してください。",
endpointInvalid: "有効な HTTP または HTTPS エンドポイントを入力してください。",
endpointPermissionRequired: "モデル設定でエンドポイントを保存し、ホストへのアクセスを許可してください。",
answerLanguagePrompt: "ユーザーが明示的に別の言語を求めない限り、既定では{language}で回答してください。",
statusFailed: "リクエスト失敗 {status}: {message}"
},
"ko-KR": {
titleFailed: "제목 생성에 실패했습니다.",
healthFailed: "연결 확인에 실패했습니다.",
ollamaFailed: "Ollama에 연결할 수 없습니다.",
requestFailed: "요청 실패. API 설정을 확인하세요.",
missingEndpointModel: "먼저 설정에서 엔드포인트와 모델 이름을 입력하세요.",
missingOllamaEndpoint: "먼저 Ollama 엔드포인트를 입력하세요.",
missingEndpointModelShort: "먼저 엔드포인트와 모델 이름을 입력하세요.",
ollamaModelMissing: "Ollama에 연결되지만 모델 {model}을 찾을 수 없습니다.",
modelAvailable: "{model} 사용 가능",
titlePrompt: "위 대화의 간결한 제목을 생성하세요. 제목만 출력하고 설명하지 마세요. 최대 영어 8단어 또는 중국어 12자.",
thinkingPrompt: "답변 전 충분히 분석하되, 결론, 필요한 추론 요약, 실행 가능한 제안만 출력하세요. 숨겨진 사고 과정은 출력하지 마세요.",
nonJson: "API가 JSON을 반환하지 않았습니다: {text}",
ollamaModelNotFound: "Ollama 모델을 찾을 수 없습니다: {message}. “Ollama 테스트”를 클릭하고 설치된 로컬 모델을 선택한 뒤 저장하세요.",
custom404: "사용자 지정 API가 404를 반환했습니다. 현재 URL은 채팅 엔드포인트가 아닙니다: {url}. OpenAI 호환 서비스는 보통 /v1/chat/completions가 필요합니다. Ollama 형식 서비스라면 설정에서 API 형식을 Ollama /api/chat으로 바꾸세요.",
ollama403: "Ollama가 확장 프로그램 origin을 거부했습니다. OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" 를 설정하고 Ollama를 완전히 다시 시작하세요.",
ollamaFetchFailed: "Ollama에 연결할 수 없습니다: {message}. Ollama가 실행 중이고 엔드포인트가 http://127.0.0.1:11434/api/chat 이며 확장 프로그램 origin이 허용되었는지 확인하세요.",
apiKeyInvalid: "API 키에 사용할 수 없는 문자가 포함되어 있습니다. API 키만 다시 붙여넣고 저장하세요.",
endpointInvalid: "유효한 HTTP 또는 HTTPS 엔드포인트를 입력하세요.",
endpointPermissionRequired: "모델 설정에서 엔드포인트를 저장하고 호스트에 대한 접근을 허용하세요.",
answerLanguagePrompt: "사용자가 명시적으로 다른 언어를 요청하지 않는 한 기본적으로 {language}로 답변하세요。",
statusFailed: "요청 실패 {status}: {message}"
},
"fr-FR": {
titleFailed: "La génération du titre a échoué.",
healthFailed: "La vérification de connexion a échoué.",
ollamaFailed: "Impossible de se connecter à Ollama.",
requestFailed: "La requête a échoué. Vérifiez les paramètres API.",
missingEndpointModel: "Renseignez d’abord le point d’accès et le modèle dans les paramètres.",
missingOllamaEndpoint: "Renseignez d’abord le point d’accès Ollama.",
missingEndpointModelShort: "Renseignez d’abord le point d’accès et le modèle.",
ollamaModelMissing: "Ollama est joignable, mais le modèle {model} est introuvable.",
modelAvailable: "{model} disponible",
titlePrompt: "Génère un titre concis pour la conversation ci-dessus. Réponds uniquement par le titre, sans explication. Maximum 8 mots anglais ou 12 caractères chinois.",
thinkingPrompt: "Analyse soigneusement avant de répondre, mais n’affiche que la conclusion, un résumé de raisonnement nécessaire et des suggestions actionnables. Ne révèle pas la chaîne de pensée cachée.",
nonJson: "L’API n’a pas renvoyé de JSON : {text}",
ollamaModelNotFound: "Modèle Ollama introuvable : {message}. Cliquez sur « Tester Ollama », choisissez un modèle local installé, puis enregistrez.",
custom404: "L’API personnalisée a renvoyé 404. L’URL actuelle n’est pas un point d’accès de chat : {url}. Les services compatibles OpenAI utilisent généralement /v1/chat/completions. Si le service est au format Ollama, changez le format API en Ollama /api/chat dans les paramètres.",
ollama403: "Ollama a rejeté l’origine de l’extension. Définissez OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" puis redémarrez complètement Ollama.",
ollamaFetchFailed: "Impossible de se connecter à Ollama : {message}. Vérifiez qu’Ollama est lancé, que le point d’accès est http://127.0.0.1:11434/api/chat et que l’origine de l’extension est autorisée.",
apiKeyInvalid: "La clé API contient des caractères non pris en charge. Collez uniquement la clé API, puis enregistrez.",
endpointInvalid: "Saisissez une adresse HTTP ou HTTPS valide.",
endpointPermissionRequired: "Enregistrez cette adresse dans les paramètres du modèle et autorisez l’accès à son hôte.",
answerLanguagePrompt: "Sauf demande explicite d’une autre langue, réponds par défaut en {language}.",
statusFailed: "Requête échouée {status} : {message}"
},
"es-ES": {
titleFailed: "Error al generar el título.",
healthFailed: "Error al comprobar la conexión.",
ollamaFailed: "No se pudo conectar con Ollama.",
requestFailed: "La solicitud falló. Revisa los ajustes de API.",
missingEndpointModel: "Primero completa el endpoint y el modelo en ajustes.",
missingOllamaEndpoint: "Primero completa el endpoint de Ollama.",
missingEndpointModelShort: "Primero completa el endpoint y el modelo.",
ollamaModelMissing: "Ollama responde, pero no se encontró el modelo {model}.",
modelAvailable: "{model} disponible",
titlePrompt: "Genera un título breve para la conversación anterior. Devuelve solo el título, sin explicación. Máximo 8 palabras en inglés o 12 caracteres chinos.",
thinkingPrompt: "Analiza con cuidado antes de responder, pero muestra solo la conclusión, un resumen de razonamiento necesario y sugerencias accionables. No reveles razonamiento oculto.",
nonJson: "La API no devolvió JSON: {text}",
ollamaModelNotFound: "Modelo de Ollama no encontrado: {message}. Haz clic en “Probar Ollama”, elige un modelo local instalado y guarda.",
custom404: "La API personalizada devolvió 404. La URL actual no es un endpoint de chat: {url}. Los servicios compatibles con OpenAI suelen necesitar /v1/chat/completions. Si el servicio usa formato Ollama, cambia el Formato API a Ollama /api/chat en ajustes.",
ollama403: "Ollama rechazó el origen de la extensión. Configura OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" y reinicia Ollama por completo.",
ollamaFetchFailed: "No se pudo conectar con Ollama: {message}. Comprueba que Ollama esté iniciado, que el endpoint sea http://127.0.0.1:11434/api/chat y que el origen de la extensión esté permitido.",
apiKeyInvalid: "La clave de API contiene caracteres no admitidos. Pega solo la clave de API y guarda.",
endpointInvalid: "Introduce una URL HTTP o HTTPS válida.",
endpointPermissionRequired: "Guarda esta URL en los ajustes del modelo y permite el acceso a su host.",
answerLanguagePrompt: "A menos que el usuario pida explícitamente otro idioma, responde por defecto en {language}.",
statusFailed: "Solicitud fallida {status}: {message}"
},
"de-DE": {
titleFailed: "Titelgenerierung fehlgeschlagen.",
healthFailed: "Verbindungsprüfung fehlgeschlagen.",
ollamaFailed: "Keine Verbindung zu Ollama möglich.",
requestFailed: "Anfrage fehlgeschlagen. Bitte API-Einstellungen prüfen.",
missingEndpointModel: "Bitte zuerst Endpunkt und Modell in den Einstellungen ausfüllen.",
missingOllamaEndpoint: "Bitte zuerst den Ollama-Endpunkt ausfüllen.",
missingEndpointModelShort: "Bitte zuerst Endpunkt und Modell ausfüllen.",
ollamaModelMissing: "Ollama ist erreichbar, aber Modell {model} wurde nicht gefunden.",
modelAvailable: "{model} verfügbar",
titlePrompt: "Erzeuge einen kurzen Titel für die obige Unterhaltung. Gib nur den Titel aus, keine Erklärung. Maximal 8 englische Wörter oder 12 chinesische Zeichen.",
thinkingPrompt: "Analysiere vor der Antwort sorgfältig, gib aber nur Schlussfolgerung, notwendige Begründungszusammenfassung und umsetzbare Vorschläge aus. Keine verborgene Gedankenkette ausgeben.",
nonJson: "Die API hat kein JSON zurückgegeben: {text}",
ollamaModelNotFound: "Ollama-Modell nicht gefunden: {message}. Klicke auf „Ollama testen“, wähle ein installiertes lokales Modell und speichere.",
custom404: "Benutzerdefinierte API gab 404 zurück. Die aktuelle URL ist kein Chat-Endpunkt: {url}. OpenAI-kompatible Dienste benötigen meist /v1/chat/completions. Wenn dein Dienst Ollama-Format nutzt, stelle in den Einstellungen API-Format auf Ollama /api/chat.",
ollama403: "Ollama hat den Ursprung der Erweiterung abgelehnt. Setze OLLAMA_ORIGINS=\"chrome-extension://*,moz-extension://*\" und starte Ollama vollständig neu.",
ollamaFetchFailed: "Keine Verbindung zu Ollama: {message}. Prüfe, ob Ollama läuft, der Endpunkt http://127.0.0.1:11434/api/chat ist und der Ursprung der Erweiterung erlaubt ist.",
apiKeyInvalid: "Der API-Schlüssel enthält nicht unterstützte Zeichen. Füge nur den API-Schlüssel ein und speichere erneut.",
endpointInvalid: "Gib eine gültige HTTP- oder HTTPS-Adresse ein.",
endpointPermissionRequired: "Speichere die Adresse in den Modelleinstellungen und erlaube den Zugriff auf ihren Host.",
answerLanguagePrompt: "Sofern der Nutzer nicht ausdrücklich eine andere Sprache verlangt, standardmäßig auf {language} antworten.",
statusFailed: "Anfrage fehlgeschlagen {status}: {message}"
}
});
Object.assign(BG_TEXT["zh-CN"], { contextLimitExceeded: "当前输入及系统提示词超过模型上下文预算,请缩短内容或调低输出上限。" });
Object.assign(BG_TEXT["zh-TW"], { contextLimitExceeded: "目前輸入與系統提示詞超過模型上下文預算,請縮短內容或降低輸出上限。" });
Object.assign(BG_TEXT["en-US"], { contextLimitExceeded: "The input and system instructions exceed the model context budget. Shorten them or lower the output limit." });
Object.assign(BG_TEXT["ja-JP"], { contextLimitExceeded: "入力とシステム指示がコンテキスト上限を超えています。内容を短くするか出力上限を下げてください。" });
Object.assign(BG_TEXT["ko-KR"], { contextLimitExceeded: "입력과 시스템 지침이 컨텍스트 한도를 초과합니다. 내용을 줄이거나 출력 한도를 낮추세요." });
Object.assign(BG_TEXT["fr-FR"], { contextLimitExceeded: "L’entrée et les consignes dépassent le contexte disponible. Raccourcissez-les ou réduisez la limite de sortie." });
Object.assign(BG_TEXT["es-ES"], { contextLimitExceeded: "La entrada y las instrucciones superan el contexto disponible. Acórtalas o reduce el límite de salida." });
Object.assign(BG_TEXT["de-DE"], { contextLimitExceeded: "Eingabe und Systemanweisungen überschreiten das Kontextbudget. Kürzen Sie sie oder senken Sie das Ausgabelimit." });
const OLLAMA_CORS_RULE_ID = 11434;
let activeOllamaCorsOrigin = "";
function bt(configOrLang, key, replacements = {}) {
const lang = typeof configOrLang === "string"
? configOrLang
: configOrLang?.language;
const template = BG_TEXT[lang]?.[key] || BG_TEXT["en-US"][key] || key;
return Object.entries(replacements).reduce(
(text, [name, value]) => text.replaceAll(`{${name}}`, String(value)),
template
);
}
extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "workspace:open-tab") {
openChatWorkspace(sender.tab?.windowId)
.then(() => sendResponse({ ok: true }))
.catch(() => sendResponse({ ok: false }));
return true;
}
if (message?.type === "llm:title") {
generateChatTitle(message.payload)
.then((title) => sendResponse({ ok: true, title }))
.catch((error) => sendResponse({ ok: false, error: error.message || bt(message.payload?.config, "titleFailed") }));
return true;
}
if (message?.type === "llm:health") {
checkModelHealth(message.payload)
.then((result) => sendResponse({ ok: true, ...result }))
.catch((error) => sendResponse({ ok: false, error: error.message || bt(message.payload?.config, "healthFailed") }));
return true;
}
if (message?.type === "ollama:tags") {
getOllamaTags(message.payload)
.then((models) => sendResponse({ ok: true, models }))
.catch((error) => sendResponse({ ok: false, error: error.message || bt(message.payload?.language, "ollamaFailed") }));
return true;
}
if (message?.type !== "llm:chat") {
return false;
}
handleChatRequest(message.payload)
.then((content) => sendResponse({ ok: true, content }))
.catch((error) => sendResponse({ ok: false, error: error.message || bt(message.payload?.config, "requestFailed") }));
return true;
});
extensionApi.runtime.onConnect.addListener((port) => {
if (port.name !== "llm-stream") {
return;
}
let controller = null;
port.onMessage.addListener((message) => {
if (message?.type === "llm:chat:stop") {
controller?.abort();
return;
}
if (message?.type !== "llm:chat:stream") {
return;
}
controller = new AbortController();
handleChatStream(message.payload, port, controller.signal)
.finally(() => {
controller = null;
});
});
port.onDisconnect.addListener(() => {
controller?.abort();
});
});
async function handleChatRequest(payload) {
const config = normalizeConfig(payload?.config || {});
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
if (!config.endpoint || !config.model) {
throw new Error(bt(config, "missingEndpointModel"));
}
return config.provider === "ollama"
? callOllama(config, messages)
: callCustomApi(config, messages);
}
async function getOllamaTags(payload) {
const endpoint = String(payload?.endpoint || "").trim();
if (!endpoint) {
throw new Error(bt(payload?.language, "missingOllamaEndpoint"));
}
await requireEndpointPermission(endpoint, payload);
const tagsUrl = ollamaEndpointToTagsUrl(endpoint);
const response = await fetchOllamaDirect(tagsUrl, {}, payload);
const data = await readJsonResponse(response, "ollama", payload);
return Array.isArray(data.models)
? data.models.map((model) => model.name).filter(Boolean)
: [];
}
async function checkModelHealth(payload) {
const config = normalizeConfig(payload?.config || {});
if (!config.endpoint || !config.model) {
throw new Error(bt(config, "missingEndpointModelShort"));
}
await requireEndpointPermission(config.endpoint, config);
if (config.apiFormat === "ollama" || config.provider === "ollama") {
const tagsUrl = ollamaEndpointToTagsUrl(config.endpoint);
const response = await fetchOllamaDirect(tagsUrl, {}, config);
const data = await readJsonResponse(response, "ollama", config);
const models = Array.isArray(data.models) ? data.models.map((model) => model.name).filter(Boolean) : [];
if (!models.includes(config.model)) {
throw new Error(bt(config, "ollamaModelMissing", { model: config.model }));
}
return { status: "ok", detail: bt(config, "modelAvailable", { model: config.model }) };
}
const headers = createJsonHeaders(config);
const response = await fetch(config.endpoint, {
method: "POST",
headers,
body: JSON.stringify(createChatBody({ ...config, temperature: 0, maxTokens: 128, thinkingEnabled: false }, [{ role: "user", content: "Reply OK." }]))
});
await readJsonResponse(response, "custom", config);
return { status: "ok", detail: bt(config, "modelAvailable", { model: config.model }) };
}
async function generateChatTitle(payload) {
const config = normalizeConfig(payload?.config || {});
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
const titlePrompt = [
...messages.slice(0, 4),
{
role: "user",
content: bt(config, "titlePrompt")
}
];
const titleConfig = { ...config, thinkingEnabled: false, temperature: 0.2, maxTokens: ModelParameters.requiresThinking(config) ? 1024 : 256 };
const title = config.apiFormat === "ollama" || config.provider === "ollama"
? await callOllama(titleConfig, titlePrompt)
: await callCustomApi(titleConfig, titlePrompt);
return String(title || "").replace(/^["“”']|["“”']$/g, "").trim().slice(0, 40);
}
function ollamaEndpointToTagsUrl(endpoint) {
const url = new URL(endpoint);
url.pathname = "/api/tags";
url.search = "";
url.hash = "";
return url.toString();
}
function ollamaEndpointToChatUrl(endpoint) {
const url = new URL(endpoint);
url.pathname = "/api/chat";
url.search = "";
url.hash = "";
return url.toString();
}
async function handleChatStream(payload, port, signal) {
const config = normalizeConfig(payload?.config || {});
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
try {
const meta = {
promptTokens: estimateTokens(messages.map((message) => message.content).join("\n")),
completionTokens: 0,
totalDurationMs: null,
loadDurationMs: null,
promptEvalDurationMs: null,
evalDurationMs: null
};
if (!config.endpoint || !config.model) {
throw new Error(bt(config, "missingEndpointModel"));
}
if (config.provider === "ollama" || config.apiFormat === "ollama") {
await streamOllama(config, messages, port, signal, meta);
} else {
await streamCustomApi(config, messages, port, signal, meta);
}
port.postMessage({ type: "done", meta });
} catch (error) {
if (error.name === "AbortError") {
port.postMessage({ type: "aborted" });
return;
}
console.error("[lemon cha] stream request failed", {
message: error.message || bt(config, "requestFailed"),
provider: config.provider,
apiFormat: config.apiFormat,
endpoint: config.endpoint,
model: config.model,
messageCount: messages.length
});
port.postMessage({ type: "error", error: error.message || bt(config, "requestFailed") });
}
}
function normalizeConfig(config) {
return ModelParameters.normalize({
provider: config.provider === "ollama" ? "ollama" : "custom",
endpoint: String(config.endpoint || "").trim(),
model: String(config.model || "").trim(),
apiKey: String(config.apiKey || "").trim(),
apiFormat: config.apiFormat === "ollama" ? "ollama" : "openai",
temperature: config.temperature,
maxTokens: config.maxTokens,
systemPrompt: String(config.systemPrompt || "").trim(),
thinkingEnabled: Boolean(config.thinkingEnabled),
language: Object.hasOwn(BG_TEXT, config.language) ? config.language : "en-US",
answerLanguage: String(config.answerLanguage || "").trim(),
translationLanguage: String(config.translationLanguage || "").trim()
});
}
function clamp(value, min, max, fallback) {
if (!Number.isFinite(value)) return fallback;
return Math.min(max, Math.max(min, value));
}
function createJsonHeaders(config) {
const headers = {
"Content-Type": "application/json"
};
const apiKey = sanitizeApiKey(config);
if (apiKey) {
headers.Authorization = `Bearer ${apiKey}`;
}
return headers;
}
function sanitizeApiKey(config) {
const value = String(config.apiKey || "")
.replace(/[\s\u200B-\u200D\uFEFF]+/g, "")
.trim();
if (!value) {
return "";
}
if (!isHeaderByteString(value)) {
throw new Error(bt(config, "apiKeyInvalid"));
}
return value;
}
function isHeaderByteString(value) {
for (let index = 0; index < value.length; index += 1) {
if (value.charCodeAt(index) > 255) {
return false;
}
}
return true;
}
function createChatBody(config, messages, stream = false) {
let prepared;
try {
prepared = ModelParameters.fitContext(ModelParameters.wireMessages(prepareMessages(config, messages), config), config);
} catch (error) {
if (error.message === "contextLimitExceeded") throw new Error(bt(config, "contextLimitExceeded"));
throw error;
}
return {
model: config.model,
messages: prepared,
...ModelParameters.requestParameters(config),
...(stream ? { stream: true, stream_options: { include_usage: true } } : {})
};
}
async function callCustomApi(config, messages) {
if (config.apiFormat === "ollama") {
return callOllama(config, messages);
}
await requireEndpointPermission(config.endpoint, config);
const headers = createJsonHeaders(config);
const response = await fetch(config.endpoint, {
method: "POST",
headers,
body: JSON.stringify(createChatBody(config, messages))
});
const data = await readJsonResponse(response, "custom", config);
return data?.choices?.[0]?.message?.content
|| data?.choices?.[0]?.text
|| data?.message?.content
|| data?.content
|| "";
}
async function streamCustomApi(config, messages, port, signal, meta) {
await requireEndpointPermission(config.endpoint, config);
const headers = createJsonHeaders(config);
const body = createChatBody(config, messages, true);
const send = () => fetch(config.endpoint, {
method: "POST",
headers,
body: JSON.stringify(body),
signal
});
let response = await send();
if (await rejectsRequestOption(response, /\b(?:stream_options|include_usage)\b/i)) {
delete body.stream_options;
response = await send();
}
if (!response.ok) {
await throwResponseError(response, "custom", config);
}
let hasExactCompletionUsage = false;
await readServerSentEvents(response, (data) => {
if (data === "[DONE]") {
return;
}
const parsed = safeParseJson(data);
if (parsed?.error) {
throw new Error(parsed.error.message || parsed.error);
}
const choice = parsed?.choices?.[0];
const delta = choice?.delta?.content || choice?.message?.content || choice?.text;
const reasoning = choice?.delta?.reasoning_content;
if (choice?.finish_reason) meta.finishReason = choice.finish_reason;
if (Number.isFinite(parsed?.usage?.prompt_tokens)) {
meta.promptTokens = parsed.usage.prompt_tokens;
}
if (Number.isFinite(parsed?.usage?.completion_tokens)) {
meta.completionTokens = parsed.usage.completion_tokens;
hasExactCompletionUsage = true;
}
if (!hasExactCompletionUsage) {
meta.completionTokens += estimateTokens(delta) + estimateTokens(reasoning);
}
postStreamDelta(port, delta, reasoning);
});
}
async function callOllama(config, messages) {
const response = await sendOllamaChat(config, messages, false);
const data = await readJsonResponse(response, "ollama", config);
return data?.message?.content || data?.response || "";
}
async function streamOllama(config, messages, port, signal, meta) {
const response = await sendOllamaChat(config, messages, true, signal);
if (!response.ok) {
await throwResponseError(response, "ollama", config);
}
await readNewlineJson(response, (data) => {
if (data.error) {
throw new Error(data.error);
}
const delta = data.message?.content || data.response;
const reasoning = data.message?.thinking;
meta.completionTokens += estimateTokens(delta) + estimateTokens(reasoning);
postStreamDelta(port, delta, reasoning);
if (data.done) {
meta.finishReason = data.done_reason || "stop";
meta.promptTokens = data.prompt_eval_count ?? meta.promptTokens;
meta.completionTokens = data.eval_count ?? meta.completionTokens;
meta.totalDurationMs = nanosToMs(data.total_duration);
meta.loadDurationMs = nanosToMs(data.load_duration);
meta.promptEvalDurationMs = nanosToMs(data.prompt_eval_duration);
meta.evalDurationMs = nanosToMs(data.eval_duration);
}
});
}
function postStreamDelta(port, content, reasoning) {
if (typeof reasoning === "string" && reasoning) {
port.postMessage({ type: "reasoning", content: reasoning });
}
if (typeof content === "string" && content) {
port.postMessage({ type: "delta", content });
}
}
async function sendOllamaChat(config, messages, stream, signal) {
await requireEndpointPermission(config.endpoint, config);
const url = ollamaEndpointToChatUrl(config.endpoint);
const body = createOllamaChatBody(config, messages, stream);
const send = () => fetchOllamaDirect(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal
}, config);
const response = await send();
if (Object.hasOwn(body, "think") && await rejectsRequestOption(response, /\bthink(?:ing)?\b/i)) {
delete body.think;
return send();
}
return response;
}
async function rejectsRequestOption(response, option) {
if (response.status !== 400 && response.status !== 422) return false;
const text = await response.clone().text();
return option.test(text) && /(?:unsupported|unknown|unexpected|unrecognized|not (?:supported|permitted|allowed)|does not support|extra[_ ](?:inputs|fields))/i.test(text);
}
async function requireEndpointPermission(endpoint, config) {
if (!extensionApi.permissions?.contains) return;
let url;
try {
url = new URL(endpoint);
} catch {
throw new Error(bt(config, "endpointInvalid"));
}
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hostname.includes("*")) {
throw new Error(bt(config, "endpointInvalid"));
}
const origin = `${url.protocol}//${url.hostname}/*`;
if (!await extensionApi.permissions.contains({ origins: [origin] })) {
throw new Error(bt(config, "endpointPermissionRequired"));
}
}
async function fetchOllamaDirect(url, options = {}, config = {}) {
try {
await ensureOllamaCorsRule(url);
return await fetch(url, options);
} catch (error) {
if (error.name === "AbortError") throw error;
return createJsonResponse(502, {
error: bt(config, "ollamaFetchFailed", { message: error.message })
});
}
}
async function ensureOllamaCorsRule(url) {
const origin = getLocalOllamaOrigin(url);
if (!origin || activeOllamaCorsOrigin === origin || !extensionApi.declarativeNetRequest?.updateDynamicRules) {
return;
}
const rule = {
id: OLLAMA_CORS_RULE_ID,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: [
{
header: "Origin",
operation: "set",
value: origin
}
]
},
condition: {
regexFilter: `^${escapeRegExp(origin)}/.*`,
resourceTypes: ["xmlhttprequest", "other"]
}
};
await updateDynamicRules({
removeRuleIds: [OLLAMA_CORS_RULE_ID],
addRules: [rule]
});
activeOllamaCorsOrigin = origin;
}
function getLocalOllamaOrigin(url) {
try {
const parsed = new URL(url);
if (parsed.protocol !== "http:") return "";
if (parsed.hostname !== "127.0.0.1" && parsed.hostname !== "localhost") return "";
if (parsed.hostname === "localhost") {
parsed.hostname = "127.0.0.1";
}
return parsed.origin;
} catch (error) {
return "";
}
}
function updateDynamicRules(options) {
return new Promise((resolve, reject) => {
if (globalThis.browser?.declarativeNetRequest) {
extensionApi.declarativeNetRequest.updateDynamicRules(options).then(resolve, reject);
return;
}
extensionApi.declarativeNetRequest.updateDynamicRules(options, () => {
const error = extensionApi.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve();
});
});
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function createJsonResponse(status, payload) {
return new Response(JSON.stringify(payload), {
status,
headers: { "Content-Type": "application/json" }
});
}
function createOllamaChatBody(config, messages, stream) {
const body = {
model: config.model,
messages: prepareMessages(config, messages),
stream,
options: {
temperature: config.temperature,
num_predict: config.maxTokens
}
};
body.think = Boolean(config.thinkingEnabled);
return body;
}
function estimateTokens(text) {
const value = String(text || "").trim();
if (!value) return 0;
const cjk = (value.match(/[\u4e00-\u9fff]/g) || []).length;
const words = (value.replace(/[\u4e00-\u9fff]/g, " ").match(/[A-Za-z0-9_]+/g) || []).length;
return Math.max(1, Math.ceil(cjk * 0.6 + words * 1.3));
}
function nanosToMs(value) {
return Number.isFinite(value) ? Math.round(value / 1_000_000) : null;
}
function prepareMessages(config, messages) {
const prepared = [...messages];
if (config.systemPrompt) {
prepared.unshift({
role: "system",
content: config.systemPrompt
});
}
const answerLanguage = languageName(config.answerLanguage);
if (answerLanguage) {
prepared.unshift({
role: "system",
content: bt(config, "answerLanguagePrompt", { language: answerLanguage })
});
}
if (!config.thinkingEnabled || ModelParameters.profile(config).thinking !== "prompt") {
return prepared;
}
return [
{
role: "system",
content: bt(config, "thinkingPrompt")
},
...prepared
];
}
function languageName(language) {
const names = {
"zh-CN": "简体中文",
"zh-TW": "繁體中文",
"en-US": "English",
"ja-JP": "日本語",
"ko-KR": "한국어",
"fr-FR": "Français",
"es-ES": "Español",
"de-DE": "Deutsch"
};
return names[language] || "";
}
async function readJsonResponse(response, provider = "custom", config = {}) {
const text = await response.text();
let data = {};
if (text) {
try {
data = JSON.parse(text);
} catch (error) {
throw new Error(bt(config, "nonJson", { text: text.slice(0, 160) }));
}
}
if (!response.ok) {
throwFormattedResponseError(response, data, provider, config);
}
return data;
}
async function throwResponseError(response, provider, config = {}) {
const text = await response.text();
let data = {};
if (text) {
data = safeParseJson(text) || { message: text.slice(0, 240) };
}
throwFormattedResponseError(response, data, provider, config);
}
function throwFormattedResponseError(response, data, provider, config = {}) {
const message = data?.error?.message || data?.error || data?.message || response.statusText;
if (provider === "ollama" && response.status === 404 && String(message).includes("model")) {
throw new Error(bt(config, "ollamaModelNotFound", { message }));
}
if (provider === "custom" && response.status === 404) {
throw new Error(bt(config, "custom404", { url: response.url }));
}
if (provider === "ollama" && response.status === 403) {
throw new Error(bt(config, "ollama403"));
}
throw new Error(bt(config, "statusFailed", { status: response.status, message }));
}
async function readServerSentEvents(response, onData) {
let data = [];
for await (const line of readStreamLines(response)) {
if (!line) {
if (data.length) onData(data.join("\n").trim());
data = [];
} else if (line.startsWith("data:")) {
data.push(line.slice(5).replace(/^ /, ""));
}
}
// Some chat endpoints close the stream without writing the final blank line.
if (data.length) onData(data.join("\n").trim());
}
async function readNewlineJson(response, onData) {
for await (const line of readStreamLines(response)) {
const parsed = safeParseJson(line);
if (parsed) onData(parsed);
}
}
async function* readStreamLines(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let finished = false;
try {
while (true) {
const { value, done } = await reader.read();
finished = done;
buffer += decoder.decode(value, { stream: !done });
// Hold a trailing CR until the next read can distinguish it from CRLF.
const endsInCr = !done && buffer.endsWith("\r");
const lines = (endsInCr ? buffer.slice(0, -1) : buffer).split(/\r\n|\r|\n/);
buffer = lines.pop() + (endsInCr ? "\r" : "");
yield* lines;
if (done) {
if (buffer) yield buffer;
return;
}
}
} finally {
if (!finished) reader.cancel().catch(() => {});
reader.releaseLock();
}
}
function safeParseJson(value) {
try {
return JSON.parse(value);
} catch (error) {
return null;
}
}