forked from omer-faruq/assistant.koplugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
1745 lines (1585 loc) · 66.5 KB
/
Copy pathmain.lua
File metadata and controls
1745 lines (1585 loc) · 66.5 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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local Device = require("device")
local logger = require("logger")
local Event = require("ui/event")
local InputContainer = require("ui/widget/container/inputcontainer")
local NetworkMgr = require("ui/network/manager")
local Dispatcher = require("dispatcher")
local UIManager = require("ui/uimanager")
local InfoMessage = require("ui/widget/infomessage")
local Font = require("ui/font")
local Trapper = require("ui/trapper")
local Language = require("ui/language")
local LuaSettings = require("luasettings")
local DataStorage = require("datastorage")
local ConfirmBox = require("ui/widget/confirmbox")
local T = require("ffi/util").template
local koutil = require("util")
local TextViewer = require("ui/widget/textviewer")
local ButtonDialog = require("ui/widget/buttondialog")
local MultiInputDialog = require("ui/widget/multiinputdialog")
local ffiutil = require("ffi/util")
local ToolExecutor = require("assistant_tool_executor")
local ASUtils = require("assistant_utils")
local Notebook = require("assistant_notebook")
local _ = require("assistant_gettext")
local N_ = _.ngettext
local AssistantDialog = require("assistant_dialog")
local Updater = require("assistant_updater")
local Prompts = require("assistant_prompts")
local SettingsDialog = require("assistant_settings")
local showDictionaryDialog = require("assistant_dictdialog")
local Registry = require("assistant_provider_registry")
local SearchRegistry = require("assistant_search_registry")
local Assistant = InputContainer:new {
name = "assistant",
meta = nil, -- reference to the _meta module
is_doc_only = false, -- available in both doc and filemanager models
settings_file = DataStorage:getSettingsDir() .. "/assistant.lua",
settings = nil,
querier = nil,
updated = false, -- flag to track if settings were updated
assistant_dialog = nil, -- reference to the main dialog instance
ui_language = nil,
ui_language_is_rtl = nil,
CONFIGURATION = nil, -- reference to the main configuration
}
-- Menu items carry an `assistant_item_id` marker so the Add Provider flow can
-- locate them in the live TouchMenu by identity instead of fixed indices
-- (see showAddProviderMenu and AGENTS.md "Provider menu paths").
local function testConfigFile(filePath)
local env = {}
setmetatable(env, {__index = _G})
local chunk, err = loadfile(filePath, "t", env) -- test mode to loadfile, check syntax errors
if not chunk then return false, err end
local success, result = pcall(chunk) -- run the code, checks runtime errors
if not success then return false, result end
return true, nil
end
-- configuration locations
local ASSISTANT_DIR = T("%1/plugins/%2.koplugin/", DataStorage:getDataDir(), Assistant.name)
local CONFIG_FILE_PATH = ASSISTANT_DIR .. "configuration.lua"
local META_FILE_PATH = ASSISTANT_DIR .. "_meta.lua"
local CONFIG_LOAD_ERROR = nil
local CONFIGURATION = nil
-- test the configuration.lua and store the error message if any
local ok, err = testConfigFile(CONFIG_FILE_PATH)
if not ok then CONFIG_LOAD_ERROR = err end
-- Load Configuration
local success, result = pcall(function() return dofile(CONFIG_FILE_PATH) end)
if success then CONFIGURATION = result
else logger.warn(result) end
-- Flag to ensure the update message is shown only once per session
local updateMessageShown = false
function Assistant:onDispatcherRegisterActions()
-- Register main AI ask action
Dispatcher:registerAction("ai_ask_question", {
category = "none",
event = "AskAIQuestion",
title = _("Ask the AI a question"),
general = true
})
-- Register AI recap action
Dispatcher:registerAction("ai_recap", {
category = "none",
event = "AskAIRecap",
title = _("AI Recaps"),
general = true
})
-- Register AI X-Ray action (available for gesture binding)
Dispatcher:registerAction("ai_xray", {
category = "none",
event = "AskAIXRay",
title = _("AI X-Ray"),
general = true
})
-- Register Quick Notes action (available for gesture binding)
Dispatcher:registerAction("ai_quick_note", {
category = "none",
event = "AskAIQuickNote",
title = _("Take Quick Notes"),
general = true
})
-- Register Book Information action (available for gesture binding)
Dispatcher:registerAction("ai_book_info", {
category = "none",
event = "AskAIBookInfo",
title = _("Book Summary & Recs"),
general = true
})
-- Register Annotations Analysis action (available for gesture binding)
Dispatcher:registerAction("ai_annotations", {
category = "none",
event = "AskAIAnnotations",
title = _("Highlight & Note Analysis"),
general = true
})
-- Register Annotations Analysis action (available for gesture binding)
Dispatcher:registerAction("ai_summary_using_annotations", {
category = "none",
event = "AskSummaryUsingAnnotations",
title = _("Summary Using Highlights & Notes"),
general = true,
separator = true
})
end
-- tricky hack: make our menu be the first under tools menu
table.insert(require("ui/elements/reader_menu_order").tools, 1, "ai_assistant")
table.insert(require("ui/elements/filemanager_menu_order").tools, 1, "ai_assistant")
function Assistant:addToMainMenu(menu_items)
local common_items_table = {
{
text = _("Ask a question"),
callback = function ()
self:onAskAIQuestion()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Enter a question to ask the AI.")
})
end
},
{
text = _("Take Quick Notes"),
callback = function ()
self:onAskAIQuickNote()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Take quick notes that will be saved to your notebook.")
})
end,
},
{
text_func = function ()
if not self.ui.doc_settings and Notebook.isEnabled(self) then
return T(
_("Notebook: %1"),
Notebook.getActiveDisplayName(self, 24)
)
end
return _("Notebook (AI Conversation Log)")
end,
callback = function ()
local is_general_mode = not self.ui.doc_settings
local notebookfile
if is_general_mode then
notebookfile = ASUtils.getGeneralNotebookFilePath(self)
else
notebookfile = self.ui.bookinfo:getNotebookFile(self.ui.doc_settings)
end
local other_buttons = {}
local notebook_dialog
if is_general_mode and Notebook.isEnabled(self) then
table.insert(other_buttons, {
text = _("Switch"),
callback = function ()
Notebook.showPicker(self, {
on_select = function ()
-- Close the old details dialog because it still
-- refers to the previously active notebook.
if notebook_dialog then
UIManager:close(notebook_dialog)
end
end,
})
end
})
end
table.insert(other_buttons, {
text = _("Delete"),
callback = function ()
UIManager:show(ConfirmBox:new{
text = T(_("Delete file?\n%1\nThis operation is not reversible."), notebookfile),
ok_text = _("Delete"),
ok_callback = function ()
local ok, err = koutil.removeFile(notebookfile)
if not ok then
UIManager:show(InfoMessage:new{ icon = "notice-warning", text = err })
return
end
if notebook_dialog then
UIManager:close(notebook_dialog)
end
end
})
end
})
-- KOReader's ShowNotebookFile event edits the current book
-- notebook. Do not expose it for a general notebook path.
if not is_general_mode then
table.insert(other_buttons, {
text = _("Edit"),
callback = function ()
UIManager:broadcastEvent(Event:new("ShowNotebookFile"))
end
})
end
notebook_dialog = ConfirmBox:new{
icon = "appbar.pageview",
face = Font:getFace("smallinfofont"),
text = ASUtils.bold_format(
T(_("<b>Notebook file:</b>\n\n%1"), notebookfile)
),
ok_text = _("View"),
ok_callback = function()
if not koutil.pathExists(notebookfile) then
UIManager:show(InfoMessage:new{
text = T(_("File does not exist.\n\n%1"), notebookfile)
})
return
end
TextViewer.openFile(notebookfile)
end,
other_buttons = { other_buttons },
}
UIManager:show(notebook_dialog)
end,
separator = true,
},
{
text_func = function ()
if not self.querier or not self.querier.handler then
return _("Provider ▸ NOT CONFIGURED")
end
local provider = self.querier.provider_setting
and self.querier.provider_setting.display_name
or self.querier.provider_name
local model = self.querier.handler.model or "?"
return T(_("Provider ▸ %1(%2)"), provider, model)
end,
keep_menu_open = true,
callback = function (touchmenu_instance)
self:showSettings(function ()
touchmenu_instance:updateItems()
end)
end,
},
{
text_func = function ()
local key = self.settings:readSetting("use_websearch", "none")
local text = ToolExecutor.ToolToText(key)
return T(_("Web Search ▸ %1"), text)
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Improves response accuracy with real-time web results. \nNote: Higher token usage and additional API charges apply.")
})
end,
sub_item_table = {},
},
{
text = _("Settings"),
assistant_item_id = "assistant_settings",
sub_item_table_func = function ()
return SettingsDialog.genMenuSettings(self)
end,
hold_callback = function ()
self:showAboutDialog()
end
}
}
-- append External Search tools menu item
for _, n in ipairs(ToolExecutor.SEARCH_API_NAMES) do
table.insert(common_items_table[5].sub_item_table,
SettingsDialog.genWebSearchSubMenuItem(self, n))
end
local book_level_items = {
{
text = _("Book Insights"),
sub_item_table = {
{
text_func = function()
return Prompts.getDisplayText(_("Book Summary & Recs"),
koutil.tableGetValue(Prompts.assistant_prompts, "book_info", "use_websearch") or false,
Prompts.isWebSearchEnabled(self.settings))
end,
callback = function ()
self:onAskAIBookInfo()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Summary of the book, author biography, historical context, and a list of similar book recommendations with descriptions.")
})
end
},
{
text_func = function()
return Prompts.getDisplayText(_("AI X-Ray"),
koutil.tableGetValue(Prompts.assistant_prompts, "xray", "use_websearch") or false,
Prompts.isWebSearchEnabled(self.settings))
end,
callback = function ()
self:onAskAIXRay()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("\"X-Ray\" summary for a book, structured into specific sections like Characters, Locations, Themes, Terms & Concepts, Timeline, and Re-immersion.")
})
end
},
{
text_func = function()
return Prompts.getDisplayText(_("AI Recaps"),
koutil.tableGetValue(Prompts.assistant_prompts, "recap", "use_websearch") or false,
Prompts.isWebSearchEnabled(self.settings))
end,
callback = function ()
self:onAskAIRecap()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("A very brief, spoiler-free summary of the book up to current reading progress.")
})
end,
},
{
text = _("Highlight & Note Analysis"),
callback = function ()
self:onAskAIAnnotations()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Analysis of your highlights, notes, and notebook content from the book.")
})
end,
},
{
text_func = function()
return Prompts.getDisplayText(_("Summary Using Highlights & Notes"),
koutil.tableGetValue(Prompts.assistant_prompts, "summary_using_annotations", "use_websearch") or false,
Prompts.isWebSearchEnabled(self.settings))
end,
callback = function ()
self:onAskSummaryUsingAnnotations()
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Summary of the book using your highlights and notes.")
})
end,
},
}
},
}
-- Only show the Custom Prompts entry when book_level_prompts are actually
-- configured. When absent, mark the Book Insights group with a trailing
-- separator so it doesn't visually run into the next menu item.
if koutil.tableGetValue(CONFIGURATION, "features", "book_level_prompts") then
table.insert(book_level_items, {
text = _("Custom Prompts"),
sub_item_table_func = function ()
return BookLevelCustomPrompts(self)
end,
hold_callback = function ()
UIManager:show(InfoMessage:new{
text = _("Your own prompts defined in the configuration file")
})
end,
separator = true,
})
else
book_level_items[1].separator = true
end
local reader_items_table = {}
-- shallow copy of the common_items_table
table.move(common_items_table, 1, #common_items_table, 1, reader_items_table)
for i = #book_level_items,1,-1 do
table.insert(reader_items_table, 2, book_level_items[i])
end
if self.ui.document then
-- Reader menu. No separator after "Ask a question": the book-level
-- items carry the trailing separator (on Custom Prompts when
-- configured, otherwise on Book Insights).
common_items_table[1].separator = false
menu_items.ai_assistant = {
text = _("AI Assistant"),
assistant_item_id = "assistant_ai_menu",
sorting_hint = "tools",
hold_callback = function ()
self:_help_dialog()
end,
sub_item_table = reader_items_table
}
else
-- Filemanager menu. Separate "Ask a question" from the notebook
-- items that follow it.
common_items_table[1].separator = true
menu_items.ai_assistant = {
text = _("AI Assistant"),
assistant_item_id = "assistant_ai_menu",
sorting_hint = "tools",
hold_callback = function ()
self:_help_dialog()
end,
sub_item_table = common_items_table
}
end
end
local function getDocumentInfo(document)
local DocSettings = require("docsettings")
local doc_settings = DocSettings:open(document.file)
local percent_finished = doc_settings:readSetting("percent_finished") or 0
local doc_props = doc_settings:child("doc_props")
local title = doc_props:readSetting("title") or document:getProps().title or "Unknown Title"
local authors = doc_props:readSetting("authors") or document:getProps().authors or "Unknown Author"
return {
title = title,
authors = authors,
percent_finished = percent_finished,
}
end
function BookLevelCustomPrompts(assistant)
local sub_item_table = {}
-- Read book_level_prompts from configuration
local book_level_prompts = koutil.tableGetValue(CONFIGURATION, "features", "book_level_prompts") or {}
for key, prompt_config in ffiutil.orderedPairs(book_level_prompts) do
if prompt_config.visible == true and prompt_config.type == "feature" then
local button = {
text = Prompts.getDisplayText(prompt_config.text or key,
koutil.tableGetValue(prompt_config, "use_websearch") or false,
Prompts.isWebSearchEnabled(assistant.settings)),
callback = function()
if not assistant:isConfigured() then return end
NetworkMgr:runWhenOnline(function()
local book = getDocumentInfo(assistant.ui.document)
local showFeatureDialog = require("assistant_featuredialog")
Trapper:wrap(function()
showFeatureDialog(assistant, prompt_config, book.title, book.authors, book.percent_finished)
end)
end)
end,
hold_callback = function()
UIManager:show(InfoMessage:new{
text = prompt_config.description or _("This is a custom prompt")
})
end,
}
table.insert(sub_item_table, button)
end
end
if #sub_item_table == 0 then
local button = {
text = _("No valid custom prompt found"),
enabled = false,
}
table.insert(sub_item_table, button)
local button = {
text = _("For details, visit the 'Configuration' wiki page on github."),
enabled = false,
}
table.insert(sub_item_table, button)
end
return sub_item_table
end
function Assistant:showSettings(close_callback)
if not self:isConfigured() then return end
if self._settings_dialog then
-- If settings dialog is already open, just show it again
UIManager:show(self._settings_dialog)
return
end
local settingDlg = SettingsDialog:new{
assistant = self,
CONFIGURATION = self.CONFIGURATION, -- merged config (file + UI providers)
settings = self.settings,
close_callback = close_callback,
}
self._settings_dialog = settingDlg -- store reference to the dialog
UIManager:show(settingDlg)
end
-- Menu-path helpers for showAddProviderMenu. Items carry `assistant_item_id`
-- markers (see the item tables in addToMainMenu and the "Provider API" item
-- in assistant_provider_registry.lua); indices are resolved against the live
-- TouchMenu layout instead of fixed path constants, so menu reordering or
-- conditional items cannot desync the navigation.
-- Note: MenuSorter keeps references to the item tables when it builds
-- tab_item_table, so markers set at menu-registration time survive.
-- 1-based index of the item carrying the marker in item_table, or nil.
local function findItemIndexByMarker(item_table, marker)
if not item_table then return nil end
for i, item in ipairs(item_table) do
if type(item) == "table" and item.assistant_item_id == marker then
return i
end
end
return nil
end
-- Computes the TouchMenu path (e.g. "4.1.7.1") to the "Provider API" item by
-- walking tab_item_table: tab -> AI Assistant -> Settings -> Provider API.
local function computeAddProviderMenuPath(tab_item_table)
if not tab_item_table then return nil end
for tab_nb, tab_items in ipairs(tab_item_table) do
local ai_idx = findItemIndexByMarker(tab_items, "assistant_ai_menu")
if ai_idx then
local ai_item = tab_items[ai_idx]
local ai_sub = ai_item.sub_item_table_func and ai_item.sub_item_table_func()
or ai_item.sub_item_table
local settings_idx = findItemIndexByMarker(ai_sub, "assistant_settings")
if settings_idx then
local settings_item = ai_sub[settings_idx]
local settings_sub = settings_item.sub_item_table_func
and settings_item.sub_item_table_func() or settings_item.sub_item_table
local provider_idx = findItemIndexByMarker(settings_sub, "assistant_add_provider")
if provider_idx then
return string.format("%d.%d.%d.%d", tab_nb, ai_idx, settings_idx, provider_idx)
end
end
end
end
return nil
end
-- Open the KOReader main menu and use TouchMenu's live path navigation to
-- walk to and highlight the existing "Provider API" menu item. On non-touch
-- devices the main menu is a plain Menu widget without path navigation, so
-- show directions to the item instead. Closes the menu again if navigation
-- is not possible.
function Assistant:showAddProviderMenu()
if not Device:isTouchDevice() then
UIManager:show(InfoMessage:new{
text = _("Add providers from the main menu:\n⚙ → AI Assistant → Settings → Provider API")
})
return
end
local menu = self.ui and self.ui.menu
if not menu or type(menu.onShowMenu) ~= "function" then return end
local function closeMenu()
if menu.onCloseReaderMenu then
menu:onCloseReaderMenu()
elseif menu.onCloseFileManagerMenu then
menu:onCloseFileManagerMenu()
end
end
-- If a main menu is already open (e.g. the one the settings dialog was
-- opened from), reuse its live TouchMenu instead of stacking a second one.
local touch_menu = menu.menu_container and menu.menu_container[1]
if not touch_menu or type(touch_menu.openMenu) ~= "function" then
menu:onShowMenu(nil, true)
touch_menu = menu.menu_container and menu.menu_container[1]
end
if not touch_menu or type(touch_menu.openMenu) ~= "function" then
closeMenu()
return
end
-- Resolve the path from the live layout (marker-based, no fixed indices).
local path = computeAddProviderMenuPath(touch_menu.tab_item_table)
if not path then
logger.warn("assistant: Provider API item not found in main menu")
closeMenu()
return
end
touch_menu:openMenu(path)
end
--- Show a unified dialog for adding or editing a provider (Name, Base URL, API Key, Model).
--- For preset providers: Name + Base URL are pre-filled from the preset.
--- For Custom (preset_name=nil): Base URL is pre-filled from the protocol sub-menu, Name is empty.
--- For Edit (edit_id ~= nil): all fields are pre-filled from the existing record.
---@param preset_name string|nil Preset display name, nil for Custom (or Edit)
---@param handler string API handler name (e.g. "openai")
---@param base_url string Pre-filled base URL
---@param additional_parameters table|nil Provider-specific additional_parameters
--- (preset defaults; Custom passes nil which is stored as {})
---@param edit_id string|nil When non-nil, edit the existing provider with this ID
function Assistant:_showAddProviderDialog(preset_name, handler, base_url, additional_parameters, edit_id)
local is_edit = edit_id ~= nil
local dialog_title
local default_name
local default_api_key = ""
local default_model = "auto"
if is_edit then
-- Pre-fill from the existing provider record
local ps = koutil.tableGetValue(self.CONFIGURATION, "provider_settings", edit_id)
dialog_title = T(_("Edit %1"), koutil.tableGetValue(ps, "display_name") or edit_id)
default_name = koutil.tableGetValue(ps, "display_name") or ""
base_url = koutil.tableGetValue(ps, "base_url") or base_url or ""
default_api_key = koutil.tableGetValue(ps, "api_key") or ""
default_model = koutil.tableGetValue(ps, "model") or "auto"
-- Preserve the existing additional_parameters (not exposed in dialog)
additional_parameters = koutil.tableGetValue(ps, "additional_parameters") or {}
-- Handler comes from the existing record, not the parameter
handler = koutil.tableGetValue(ps, "handler") or handler
else
dialog_title = preset_name and T(_("Add %1"), preset_name) or T(_("Add %1 Provider"), handler)
default_name = preset_name or ""
end
local dialog_ref = {} -- forward ref for enabled_func closure in buttons
local dialog
dialog = MultiInputDialog:new{
title = dialog_title,
fields = {
{ description = _("Provider Name"), hint = _("Display name"), text = default_name },
{ description = _("Base URL"), hint = _("https://..."), text = base_url },
{ description = _("API Key"), hint = _("Your API key"), text = default_api_key },
{ description = _("Model"), hint = _("Default: auto"), text = default_model },
},
buttons = {{
{
id = "cancel",
text = _("Cancel"),
callback = function() UIManager:close(dialog) end,
},
{
id = "browse_models",
text = _("Browse Models"),
enabled_func = function()
local d = dialog_ref[1]
if not d then return false end
return d:getFields()[3] ~= "" -- enabled when API key is filled
end,
callback = function()
local fields = dialog:getFields()
local api_key = fields[3]
local url = fields[2]
if api_key == "" or url == "" then return end
-- Fetch models through the provider handler's own
-- FetchModels (api_handlers), then reuse model_picker's
-- showPickerDialog. Each handler builds its endpoint,
-- auth headers and post-processing itself, and runs the
-- request behind a dismissable InfoMessage so a stalled
-- network can be cancelled by tapping.
NetworkMgr:runWhenOnline(function()
Trapper:wrap(function()
local mp = require("assistant_model_picker")
local model_list, err = mp.fetchModels(handler, url, api_key)
if err == ASUtils.HANDLERCODE.CODE_CANCELLED then
return -- user dismissed the InfoMessage
end
if err or not model_list or #model_list == 0 then
UIManager:show(InfoMessage:new{
icon = "notice-warning",
text = err or _("No models available."),
})
return
end
mp.showPickerDialog(self, model_list, nil, "", 1,
function(model_id)
if dialog.input_fields[4] then
dialog.input_fields[4]:setText(model_id)
dialog.input_fields[4]:moveCursorToCharPos(#model_id + 1)
end
end
)
end)
end)
end,
},
{
id = "save",
text = _("Save"),
is_enter_default = true,
callback = function()
local fields = dialog:getFields()
local name = fields[1]
local url = fields[2]
local api_key = fields[3]
local model = fields[4]
if name == "" then name = handler end
if url == "" then
UIManager:show(InfoMessage:new{ text = _("Base URL is required.") })
return
end
if api_key == "" then
UIManager:show(InfoMessage:new{ text = _("API key is required.") })
return
end
if is_edit then
Registry.updateProvider(self, edit_id, name, url, api_key, model)
else
Registry.installProvider(self, handler, url, name, api_key, model, additional_parameters)
end
UIManager:close(dialog)
-- Close any stale settings dialog, then open a fresh
-- Provider Settings window so the added/edited provider
-- is immediately visible and selectable.
if self._settings_dialog then
UIManager:close(self._settings_dialog)
self._settings_dialog = nil
end
UIManager:scheduleIn(0.15, function() self:showSettings() end)
end,
},
}},
}
dialog_ref[1] = dialog
UIManager:show(dialog)
end
--- Show a dialog for adding or editing a web search API tool.
--- Reuses MultiInputDialog style. Only shows the credential field:
--- - API key tools (SerpAPI, Tavily, Exa): API Key field only
--- - Base URL tools (SearXNG): Base URL field only
--- The display name comes from SEARCH_TOOLS and is not user-editable.
---@param tool_key string The fixed tool key (serpapi, tavilyapi, exaapi, searxngapi)
function Assistant:_showAddWebSearchDialog(tool_key)
local tool_def = SearchRegistry.SEARCH_TOOLS[tool_key]
if not tool_def then return end
-- Pre-fill from existing UI record if present
local existing = self._ui_search_data and self._ui_search_data.tools[tool_key]
local default_key = existing and existing.api_key or ""
local default_url = existing and existing.base_url or ""
local is_edit = SearchRegistry.is_deletable(
koutil.tableGetValue(self.CONFIGURATION, "provider_settings", tool_key))
local title = is_edit and T(_("Edit %1"), tool_def.display_name)
or T(_("Add %1"), tool_def.display_name)
-- Build fields based on credential type (no display_name field)
local fields
if tool_def.needs == "api_key" then
fields = {
{ description = _("API Key"), hint = _("Your API key"), text = default_key },
}
else -- base_url
fields = {
{ description = _("Base URL"), hint = _("https://..."), text = default_url },
}
end
local dialog_ref = {}
local dialog
dialog = MultiInputDialog:new{
title = title,
fields = fields,
buttons = {{
{
text = _("Cancel"),
callback = function() UIManager:close(dialog) end,
},
{
id = "save",
text = _("Save"),
is_enter_default = true,
callback = function()
local input_fields = dialog:getFields()
local api_key, base_url
if tool_def.needs == "api_key" then
api_key = input_fields[1]
if api_key == "" then
UIManager:show(InfoMessage:new{
text = T(_("API key is required for %1."), tool_def.display_name) })
return
end
else
base_url = input_fields[1]
if base_url == "" then
UIManager:show(InfoMessage:new{
text = T(_("Base URL is required for %1."), tool_def.display_name) })
return
end
end
local ok, err = SearchRegistry.installSearchTool(
self, tool_key, api_key, base_url)
if not ok then
UIManager:show(InfoMessage:new{
icon = "notice-warning",
text = err or _("Failed to save search tool."),
})
return
end
UIManager:close(dialog)
-- Refresh settings if open
if self._settings_dialog then
UIManager:close(self._settings_dialog)
self._settings_dialog = nil
UIManager:scheduleIn(0.15, function() self:showSettings() end)
end
end,
},
}},
}
dialog_ref[1] = dialog
UIManager:show(dialog)
end
function Assistant:getModelProvider()
if type(self.CONFIGURATION) ~= "table" then
return nil
end
local provider_settings = self.CONFIGURATION.provider_settings -- provider settings table from configuration.lua
if type(provider_settings) ~= "table" then
return nil
end
local setting_provider = self.settings:readSetting("provider")
local function is_provider_valid(key)
if not key then return false end
local provider = koutil.tableGetValue(self.CONFIGURATION, "provider_settings", key)
return provider and koutil.tableGetValue(provider, "model") and
koutil.tableGetValue(provider, "base_url") and
koutil.tableGetValue(provider, "api_key")
end
local function find_setting_provider(filter_func)
for key, tab in pairs(provider_settings) do
if is_provider_valid(key) then
if filter_func and filter_func(key, tab) then return key end
if not filter_func then return key end
end
end
return nil
end
if is_provider_valid(setting_provider) then
-- If the setting provider is valid, use it
return setting_provider
else
-- If the setting provider is invalid, delete this selection
self.settings:delSetting("provider")
local conf_provider = self.CONFIGURATION.provider -- provider name from configuration.lua
if is_provider_valid(conf_provider) then
-- if the configuration provider is valid, use it
setting_provider = conf_provider
else
-- try to find the one defined with `default = true`
setting_provider = find_setting_provider(function(key, tab)
return koutil.tableGetValue(tab, "default") == true
end)
-- still invalid (none of them defined `default`)
if not setting_provider then
setting_provider = find_setting_provider()
logger.warn("Invalid provider setting found, using a random one: ", setting_provider)
end
end
if not setting_provider then
CONFIG_LOAD_ERROR = _("No valid model provider is found in the configuration.lua")
return nil
end -- if still not found, the configuration is wrong
self.settings:saveSetting("provider", setting_provider)
self.updated = true -- mark settings as updated
end
return setting_provider
end
-- Flush settings to disk, triggered by koreader
function Assistant:onFlushSettings()
if self.updated then
self.settings:flush()
self.updated = nil
end
end
function Assistant:isConfigured()
local err_text = ASUtils.bold_format(
_("<b>No provider set up yet.</b>\nPlease add a provider in Settings or configuration.lua.")
)
local function show_config_error()
UIManager:show(ConfirmBox:new{
icon = "notice-warning",
text = err_text,
ok_text = _("OK"),
ok_callback = function()
self:showAddProviderMenu()
end,
cancel_text = _("Cancel"),
})
end
-- handle error message during loading
if CONFIG_LOAD_ERROR and type(CONFIG_LOAD_ERROR) == "string" then
-- keep the error message clean
local cut = CONFIG_LOAD_ERROR:find("configuration.lua", 1, true) or 0 -- find as plain
err_text = string.format("%s\n\n%s", err_text,
(cut > 0) and CONFIG_LOAD_ERROR:sub(cut) or CONFIG_LOAD_ERROR)
show_config_error()
return nil
end
if not self.CONFIGURATION or not self.querier or not self.querier.handler then
show_config_error()
return nil
end
return true
end
function Assistant:init()
-- loading our own _meta.lua
self.meta = dofile(META_FILE_PATH)
-- init settings
self.settings = LuaSettings:open(self.settings_file)
-- Initialize UI state independently of provider configuration. Menus and
-- Settings can be opened before a provider is added through the UI.
local ui_locale = G_reader_settings:readSetting("language") or "en"
self.ui_language = Language:getLanguageName(ui_locale) or "English"
self.ui_language_is_rtl = Language:isLanguageRTL(ui_locale)
-- Load UI providers from settings and merge with file config
local ui_data = Registry.load(self.settings)
local merged_ps = Registry.merge(CONFIGURATION, ui_data)
self._ui_provider_data = ui_data -- kept for Add/Delete from Settings UI
-- Load UI search tools from settings and merge with file config
local ui_search_data = SearchRegistry.load(self.settings)
local merged_search = SearchRegistry.merge(CONFIGURATION, ui_search_data)
self._ui_search_data = ui_search_data -- kept for Add/Delete from Settings UI
-- Build effective CONFIGURATION (file config as base + merged provider_settings)
local effective = {}
if CONFIGURATION then
for k, v in pairs(CONFIGURATION) do
effective[k] = v
end
end
-- Merge AI providers and search tools into provider_settings.
-- Search tool keys (serpapi, tavilyapi, exaapi, searxngapi) are separate
-- from AI provider keys and do not appear in the AI provider radio because
-- is_valid_provider filters by handler presence.
effective.provider_settings = merged_ps or {}
if merged_search then
for key, record in pairs(merged_search) do
effective.provider_settings[key] = record
end
end
self.CONFIGURATION = effective
-- Register actions with dispatcher for gesture assignment
self:onDispatcherRegisterActions()
-- Register menu to main menu (under "tools") - for both reader and filemanager
self.ui.menu:registerToMainMenu(self)
if self.ui.document then