-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathindex.ts
More file actions
2530 lines (2234 loc) · 79.1 KB
/
Copy pathindex.ts
File metadata and controls
2530 lines (2234 loc) · 79.1 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
/**
* @file This file exports a class that implements the InferenceExtension interface from the @janhq/core package.
* The class provides methods for initializing and stopping a model, and for making inference requests.
* It also subscribes to events emitted by the @janhq/core package and handles new message requests.
* @version 1.0.0
* @module llamacpp-extension/src/index
*/
import {
AIEngine,
getJanDataFolderPath,
fs,
joinPath,
modelInfo,
SessionInfo,
UnloadResult,
chatCompletion,
chatCompletionChunk,
ImportOptions,
chatCompletionRequest,
events,
AppEvent,
DownloadEvent,
} from '@janhq/core'
import { error, info, warn } from '@tauri-apps/plugin-log'
import { listen } from '@tauri-apps/api/event'
import {
listSupportedBackends,
downloadBackend,
isBackendInstalled,
getBackendExePath,
getBackendDir,
} from './backend'
import { invoke } from '@tauri-apps/api/core'
import { getProxyConfig } from './util'
import { basename } from '@tauri-apps/api/path'
import {
GgufMetadata,
readGgufMetadata,
} from '@janhq/tauri-plugin-llamacpp-api'
import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
type LlamacppConfig = {
version_backend: string
auto_update_engine: boolean
auto_unload: boolean
llamacpp_env: string
memory_util: string
chat_template: string
n_gpu_layers: number
offload_mmproj: boolean
override_tensor_buffer_t: string
ctx_size: number
threads: number
threads_batch: number
n_predict: number
batch_size: number
ubatch_size: number
device: string
split_mode: string
main_gpu: number
flash_attn: boolean
cont_batching: boolean
no_mmap: boolean
mlock: boolean
no_kv_offload: boolean
cache_type_k: string
cache_type_v: string
defrag_thold: number
rope_scaling: string
rope_scale: number
rope_freq_base: number
rope_freq_scale: number
ctx_shift: boolean
}
type ModelPlan = {
gpuLayers: number
maxContextLength: number
noOffloadKVCache: boolean
offloadMmproj?: boolean
mode: 'GPU' | 'Hybrid' | 'CPU' | 'Unsupported'
}
interface DownloadItem {
url: string
save_path: string
proxy?: Record<string, string | string[] | boolean>
sha256?: string
size?: number
}
interface ModelConfig {
model_path: string
mmproj_path?: string
name: string // user-friendly
// some model info that we cache upon import
size_bytes: number
sha256?: string
mmproj_sha256?: string
mmproj_size_bytes?: number
}
interface EmbeddingResponse {
model: string
object: string
usage: {
prompt_tokens: number
total_tokens: number
}
data: EmbeddingData[]
}
interface EmbeddingData {
embedding: number[]
index: number
object: string
}
interface DeviceList {
id: string
name: string
mem: number
free: number
}
interface SystemMemory {
totalVRAM: number
totalRAM: number
totalMemory: number
}
/**
* Override the default app.log function to use Jan's logging system.
* @param args
*/
const logger = {
info: function (...args: any[]) {
console.log(...args)
info(args.map((arg) => ` ${arg}`).join(` `))
},
warn: function (...args: any[]) {
console.warn(...args)
warn(args.map((arg) => ` ${arg}`).join(` `))
},
error: function (...args: any[]) {
console.error(...args)
error(args.map((arg) => ` ${arg}`).join(` `))
},
}
/**
* A class that implements the InferenceExtension interface from the @janhq/core package.
* The class provides methods for initializing and stopping a model, and for making inference requests.
* It also subscribes to events emitted by the @janhq/core package and handles new message requests.
*/
// Folder structure for llamacpp extension:
// <Jan's data folder>/llamacpp
// - models/<modelId>/
// - model.yml (required)
// - model.gguf (optional, present if downloaded from URL)
// - mmproj.gguf (optional, present if mmproj exists and it was downloaded from URL)
// Contents of model.yml can be found in ModelConfig interface
//
// - backends/<backend_version>/<backend_type>/
// - build/bin/llama-server (or llama-server.exe on Windows)
//
// - lib/
// - e.g. libcudart.so.12
export default class llamacpp_extension extends AIEngine {
provider: string = 'llamacpp'
autoUnload: boolean = true
llamacpp_env: string = ''
memoryMode: string = 'high'
readonly providerId: string = 'llamacpp'
private config: LlamacppConfig
private providerPath!: string
private apiSecret: string = 'JustAskNow'
private pendingDownloads: Map<string, Promise<void>> = new Map()
private isConfiguringBackends: boolean = false
private loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promises
private unlistenValidationStarted?: () => void
override async onLoad(): Promise<void> {
super.onLoad() // Calls registerEngine() from AIEngine
let settings = structuredClone(SETTINGS) // Clone to modify settings definition before registration
// This makes the settings (including the backend options and initial value) available to the Jan UI.
this.registerSettings(settings)
let loadedConfig: any = {}
for (const item of settings) {
const defaultValue = item.controllerProps.value
// Use the potentially updated default value from the settings array as the fallback for getSetting
loadedConfig[item.key] = await this.getSetting<typeof defaultValue>(
item.key,
defaultValue
)
}
this.config = loadedConfig as LlamacppConfig
this.autoUnload = this.config.auto_unload
this.llamacpp_env = this.config.llamacpp_env
this.memoryMode = this.config.memory_util
// This sets the base directory where model files for this provider are stored.
this.providerPath = await joinPath([
await getJanDataFolderPath(),
this.providerId,
])
// Set up validation event listeners to bridge Tauri events to frontend
this.unlistenValidationStarted = await listen<{
modelId: string
downloadType: string
}>('onModelValidationStarted', (event) => {
console.debug(
'LlamaCPP: bridging onModelValidationStarted event',
event.payload
)
events.emit(DownloadEvent.onModelValidationStarted, event.payload)
})
this.configureBackends()
}
private getStoredBackendType(): string | null {
try {
return localStorage.getItem('llama_cpp_backend_type')
} catch (error) {
logger.warn('Failed to read backend type from localStorage:', error)
return null
}
}
private setStoredBackendType(backendType: string): void {
try {
localStorage.setItem('llama_cpp_backend_type', backendType)
logger.info(`Stored backend type preference: ${backendType}`)
} catch (error) {
logger.warn('Failed to store backend type in localStorage:', error)
}
}
private clearStoredBackendType(): void {
try {
localStorage.removeItem('llama_cpp_backend_type')
logger.info('Cleared stored backend type preference')
} catch (error) {
logger.warn('Failed to clear backend type from localStorage:', error)
}
}
private findLatestVersionForBackend(
version_backends: { version: string; backend: string }[],
backendType: string
): string | null {
const matchingBackends = version_backends.filter(
(vb) => vb.backend === backendType
)
if (matchingBackends.length === 0) {
return null
}
// Sort by version (newest first) and get the latest
matchingBackends.sort((a, b) => b.version.localeCompare(a.version))
return `${matchingBackends[0].version}/${matchingBackends[0].backend}`
}
async configureBackends(): Promise<void> {
if (this.isConfiguringBackends) {
logger.info(
'configureBackends already in progress, skipping duplicate call'
)
return
}
this.isConfiguringBackends = true
try {
let version_backends: { version: string; backend: string }[] = []
try {
version_backends = await listSupportedBackends()
if (version_backends.length === 0) {
throw new Error(
'No supported backend binaries found for this system. Backend selection and auto-update will be unavailable.'
)
} else {
version_backends.sort((a, b) => b.version.localeCompare(a.version))
}
} catch (error) {
throw new Error(
`Failed to fetch supported backends: ${
error instanceof Error ? error.message : error
}`
)
}
// Get stored backend preference
const storedBackendType = this.getStoredBackendType()
let bestAvailableBackendString = ''
if (storedBackendType) {
// Find the latest version of the stored backend type
const preferredBackendString = this.findLatestVersionForBackend(
version_backends,
storedBackendType
)
if (preferredBackendString) {
bestAvailableBackendString = preferredBackendString
logger.info(
`Using stored backend preference: ${bestAvailableBackendString}`
)
} else {
logger.warn(
`Stored backend type '${storedBackendType}' not available, falling back to best backend`
)
// Clear the invalid stored preference
this.clearStoredBackendType()
bestAvailableBackendString =
await this.determineBestBackend(version_backends)
}
} else {
bestAvailableBackendString = await this.determineBestBackend(version_backends)
}
let settings = structuredClone(SETTINGS)
const backendSettingIndex = settings.findIndex(
(item) => item.key === 'version_backend'
)
let originalDefaultBackendValue = ''
if (backendSettingIndex !== -1) {
const backendSetting = settings[backendSettingIndex]
originalDefaultBackendValue = backendSetting.controllerProps
.value as string
backendSetting.controllerProps.options = version_backends.map((b) => {
const key = `${b.version}/${b.backend}`
return { value: key, name: key }
})
// Set the recommended backend based on bestAvailableBackendString
if (bestAvailableBackendString) {
backendSetting.controllerProps.recommended =
bestAvailableBackendString
}
const savedBackendSetting = await this.getSetting<string>(
'version_backend',
originalDefaultBackendValue
)
// Determine initial UI default based on priority:
// 1. Saved setting (if valid and not original default)
// 2. Best available for stored backend type
// 3. Original default
let initialUiDefault = originalDefaultBackendValue
if (
savedBackendSetting &&
savedBackendSetting !== originalDefaultBackendValue
) {
initialUiDefault = savedBackendSetting
// Store the backend type from the saved setting only if different
const [, backendType] = savedBackendSetting.split('/')
if (backendType) {
const currentStoredBackend = this.getStoredBackendType()
if (currentStoredBackend !== backendType) {
this.setStoredBackendType(backendType)
logger.info(
`Stored backend type preference from saved setting: ${backendType}`
)
}
}
} else if (bestAvailableBackendString) {
initialUiDefault = bestAvailableBackendString
// Store the backend type from the best available only if different
const [, backendType] = bestAvailableBackendString.split('/')
if (backendType) {
const currentStoredBackend = this.getStoredBackendType()
if (currentStoredBackend !== backendType) {
this.setStoredBackendType(backendType)
logger.info(
`Stored backend type preference from best available: ${backendType}`
)
}
}
}
backendSetting.controllerProps.value = initialUiDefault
logger.info(
`Initial UI default for version_backend set to: ${initialUiDefault}`
)
} else {
logger.error(
'Critical setting "version_backend" definition not found in SETTINGS.'
)
throw new Error('Critical setting "version_backend" not found.')
}
this.registerSettings(settings)
let effectiveBackendString = this.config.version_backend
let backendWasDownloaded = false
// Handle fresh installation case where version_backend might be 'none' or invalid
if (
(!effectiveBackendString ||
effectiveBackendString === 'none' ||
!effectiveBackendString.includes('/') ||
// If the selected backend is not in the list of supported backends
// Need to reset too
!version_backends.some(
(e) => `${e.version}/${e.backend}` === effectiveBackendString
)) &&
// Ensure we have a valid best available backend
bestAvailableBackendString
) {
effectiveBackendString = bestAvailableBackendString
logger.info(
`Fresh installation or invalid backend detected, using: ${effectiveBackendString}`
)
// Update the config immediately
this.config.version_backend = effectiveBackendString
// Update the settings to reflect the change in UI
const updatedSettings = await this.getSettings()
await this.updateSettings(
updatedSettings.map((item) => {
if (item.key === 'version_backend') {
item.controllerProps.value = effectiveBackendString
}
return item
})
)
logger.info(`Updated UI settings to show: ${effectiveBackendString}`)
// Emit for updating fe
if (events && typeof events.emit === 'function') {
logger.info(
`Emitting settingsChanged event for version_backend with value: ${effectiveBackendString}`
)
events.emit('settingsChanged', {
key: 'version_backend',
value: effectiveBackendString,
})
}
}
// Download and install the backend if not already present
if (effectiveBackendString) {
const [version, backend] = effectiveBackendString.split('/')
if (version && backend) {
const isInstalled = await isBackendInstalled(backend, version)
if (!isInstalled) {
logger.info(`Installing initial backend: ${effectiveBackendString}`)
await this.ensureBackendReady(backend, version)
backendWasDownloaded = true
logger.info(
`Successfully installed initial backend: ${effectiveBackendString}`
)
}
}
}
if (this.config.auto_update_engine) {
const updateResult = await this.handleAutoUpdate(
bestAvailableBackendString
)
if (updateResult.wasUpdated) {
effectiveBackendString = updateResult.newBackend
backendWasDownloaded = true
}
}
if (!backendWasDownloaded && effectiveBackendString) {
await this.ensureFinalBackendInstallation(effectiveBackendString)
}
} finally {
this.isConfiguringBackends = false
}
}
private async determineBestBackend(
version_backends: { version: string; backend: string }[]
): Promise<string> {
if (version_backends.length === 0) return ''
// Check GPU memory availability
let hasEnoughGpuMemory = false
try {
const sysInfo = await getSystemInfo()
for (const gpuInfo of sysInfo.gpus) {
if (gpuInfo.total_memory >= 6 * 1024) {
hasEnoughGpuMemory = true
break
}
}
} catch (error) {
logger.warn('Failed to get system info for GPU memory check:', error)
// Default to false if we can't determine GPU memory
hasEnoughGpuMemory = false
}
// Priority list for backend types (more specific/performant ones first)
// Vulkan will be conditionally prioritized based on GPU memory
const backendPriorities: string[] = hasEnoughGpuMemory
? [
'cuda-cu12.0',
'cuda-cu11.7',
'vulkan', // Include vulkan if we have enough GPU memory
'avx512',
'avx2',
'avx',
'noavx',
'arm64',
'x64',
]
: [
'cuda-cu12.0',
'cuda-cu11.7',
'avx512',
'avx2',
'avx',
'noavx',
'arm64',
'x64',
'vulkan', // demote to last if we don't have enough memory
]
// Helper to map backend string to a priority category
const getBackendCategory = (backendString: string): string | undefined => {
if (backendString.includes('cu12.0')) return 'cuda-cu12.0'
if (backendString.includes('cu11.7')) return 'cuda-cu11.7'
if (backendString.includes('vulkan')) return 'vulkan'
if (backendString.includes('avx512')) return 'avx512'
if (backendString.includes('avx2')) return 'avx2'
if (
backendString.includes('avx') &&
!backendString.includes('avx2') &&
!backendString.includes('avx512')
)
return 'avx'
if (backendString.includes('noavx')) return 'noavx'
if (backendString.endsWith('arm64')) return 'arm64'
if (backendString.endsWith('x64')) return 'x64'
return undefined
}
let foundBestBackend: { version: string; backend: string } | undefined
for (const priorityCategory of backendPriorities) {
const matchingBackends = version_backends.filter((vb) => {
const category = getBackendCategory(vb.backend)
return category === priorityCategory
})
if (matchingBackends.length > 0) {
foundBestBackend = matchingBackends[0]
logger.info(
`Determined best available backend: ${foundBestBackend.version}/${foundBestBackend.backend} (Category: "${priorityCategory}")`
)
break
}
}
if (foundBestBackend) {
return `${foundBestBackend.version}/${foundBestBackend.backend}`
} else {
// Fallback to newest version
logger.info(
`Fallback to: ${version_backends[0].version}/${version_backends[0].backend}`
)
return `${version_backends[0].version}/${version_backends[0].backend}`
}
}
async updateBackend(
targetBackendString: string
): Promise<{ wasUpdated: boolean; newBackend: string }> {
try {
if (!targetBackendString)
throw new Error(
`Invalid backend string: ${targetBackendString} supplied to update function`
)
const [version, backend] = targetBackendString.split('/')
logger.info(
`Updating backend to ${targetBackendString} (backend type: ${backend})`
)
// Download new backend
await this.ensureBackendReady(backend, version)
// Add delay on Windows
if (IS_WINDOWS) {
await new Promise((resolve) => setTimeout(resolve, 1000))
}
// Update configuration
this.config.version_backend = targetBackendString
// Store the backend type preference only if it changed
const currentStoredBackend = this.getStoredBackendType()
if (currentStoredBackend !== backend) {
this.setStoredBackendType(backend)
logger.info(`Updated stored backend type preference: ${backend}`)
}
// Update settings
const settings = await this.getSettings()
await this.updateSettings(
settings.map((item) => {
if (item.key === 'version_backend') {
item.controllerProps.value = targetBackendString
}
return item
})
)
logger.info(`Successfully updated to backend: ${targetBackendString}`)
// Emit for updating frontend
if (events && typeof events.emit === 'function') {
logger.info(
`Emitting settingsChanged event for version_backend with value: ${targetBackendString}`
)
events.emit('settingsChanged', {
key: 'version_backend',
value: targetBackendString,
})
}
// Clean up old versions of the same backend type
if (IS_WINDOWS) {
await new Promise((resolve) => setTimeout(resolve, 500))
}
await this.removeOldBackend(version, backend)
return { wasUpdated: true, newBackend: targetBackendString }
} catch (error) {
logger.error('Backend update failed:', error)
return { wasUpdated: false, newBackend: this.config.version_backend }
}
}
private async handleAutoUpdate(
bestAvailableBackendString: string
): Promise<{ wasUpdated: boolean; newBackend: string }> {
logger.info(
`Auto-update engine is enabled. Current backend: ${this.config.version_backend}. Best available: ${bestAvailableBackendString}`
)
if (!bestAvailableBackendString) {
logger.warn(
'Auto-update enabled, but no best available backend determined'
)
return { wasUpdated: false, newBackend: this.config.version_backend }
}
// If version_backend is empty, invalid, or 'none', use the best available backend
if (
!this.config.version_backend ||
this.config.version_backend === '' ||
this.config.version_backend === 'none' ||
!this.config.version_backend.includes('/')
) {
logger.info(
'No valid backend currently selected, using best available backend'
)
return await this.updateBackend(bestAvailableBackendString)
}
// Parse current backend configuration
const [currentVersion, currentBackend] = (
this.config.version_backend || ''
).split('/')
if (!currentVersion || !currentBackend) {
logger.warn(
`Invalid current backend format: ${this.config.version_backend}`
)
return { wasUpdated: false, newBackend: this.config.version_backend }
}
// Find the latest version for the currently selected backend type
const version_backends = await listSupportedBackends()
const targetBackendString = this.findLatestVersionForBackend(
version_backends,
currentBackend
)
if (!targetBackendString) {
logger.warn(
`No available versions found for current backend type: ${currentBackend}`
)
return { wasUpdated: false, newBackend: this.config.version_backend }
}
const [latestVersion] = targetBackendString.split('/')
// Check if update is needed (only version comparison for same backend type)
if (currentVersion === latestVersion) {
logger.info(
'Auto-update: Already using the latest version of the selected backend'
)
return { wasUpdated: false, newBackend: this.config.version_backend }
}
// Perform version update for the same backend type
logger.info(
`Auto-updating from ${this.config.version_backend} to ${targetBackendString} (preserving backend type)`
)
return await this.updateBackend(targetBackendString)
}
private parseBackendVersion(v: string): number {
// Remove any leading non‑digit characters (e.g. the "b")
const numeric = v.replace(/^[^\d]*/, '')
const n = Number(numeric)
return Number.isNaN(n) ? 0 : n
}
async checkBackendForUpdates(): Promise<{
updateNeeded: boolean
newVersion: string
}> {
// Parse current backend configuration
const [currentVersion, currentBackend] = (
this.config.version_backend || ''
).split('/')
if (!currentVersion || !currentBackend) {
logger.warn(
`Invalid current backend format: ${this.config.version_backend}`
)
return { updateNeeded: false, newVersion: '0' }
}
// Find the latest version for the currently selected backend type
const version_backends = await listSupportedBackends()
const targetBackendString = this.findLatestVersionForBackend(
version_backends,
currentBackend
)
const [latestVersion] = targetBackendString.split('/')
if (
this.parseBackendVersion(latestVersion) >
this.parseBackendVersion(currentVersion)
) {
logger.info(`New update available: ${latestVersion}`)
return { updateNeeded: true, newVersion: latestVersion }
} else {
logger.info(
`Already at latest version: ${currentVersion} = ${latestVersion}`
)
return { updateNeeded: false, newVersion: '0' }
}
}
private async removeOldBackend(
latestVersion: string,
backendType: string
): Promise<void> {
try {
const janDataFolderPath = await getJanDataFolderPath()
const backendsDir = await joinPath([
janDataFolderPath,
'llamacpp',
'backends',
])
if (!(await fs.existsSync(backendsDir))) {
return
}
const versionDirs = await fs.readdirSync(backendsDir)
for (const versionDir of versionDirs) {
const versionPath = await joinPath([backendsDir, versionDir])
const versionName = await basename(versionDir)
// Skip the latest version
if (versionName === latestVersion) {
continue
}
// Check if this version has the specific backend type we're interested in
const backendTypePath = await joinPath([versionPath, backendType])
if (await fs.existsSync(backendTypePath)) {
const isInstalled = await isBackendInstalled(backendType, versionName)
if (isInstalled) {
try {
await fs.rm(backendTypePath)
logger.info(
`Removed old version of ${backendType}: ${backendTypePath}`
)
} catch (e) {
logger.warn(
`Failed to remove old backend version: ${backendTypePath}`,
e
)
}
}
}
}
} catch (error) {
logger.error('Error during old backend version cleanup:', error)
}
}
private async ensureFinalBackendInstallation(
backendString: string
): Promise<void> {
if (!backendString) {
logger.warn('No backend specified for final installation check')
return
}
const [selectedVersion, selectedBackend] = backendString
.split('/')
.map((part) => part?.trim())
if (!selectedVersion || !selectedBackend) {
logger.warn(`Invalid backend format: ${backendString}`)
return
}
try {
const isInstalled = await isBackendInstalled(
selectedBackend,
selectedVersion
)
if (!isInstalled) {
logger.info(`Final check: Installing backend ${backendString}`)
await this.ensureBackendReady(selectedBackend, selectedVersion)
logger.info(`Successfully installed backend: ${backendString}`)
} else {
logger.info(
`Final check: Backend ${backendString} is already installed`
)
}
} catch (error) {
logger.error(
`Failed to ensure backend ${backendString} installation:`,
error
)
throw error // Re-throw as this is critical
}
}
async getProviderPath(): Promise<string> {
if (!this.providerPath) {
this.providerPath = await joinPath([
await getJanDataFolderPath(),
this.providerId,
])
}
return this.providerPath
}
override async onUnload(): Promise<void> {
// Terminate all active sessions
// Clean up validation event listeners
if (this.unlistenValidationStarted) {
this.unlistenValidationStarted()
}
}
onSettingUpdate<T>(key: string, value: T): void {
this.config[key] = value
if (key === 'version_backend') {
const valueStr = value as string
const [version, backend] = valueStr.split('/')
// Store the backend type preference in localStorage only if it changed
if (backend) {
const currentStoredBackend = this.getStoredBackendType()
if (currentStoredBackend !== backend) {
this.setStoredBackendType(backend)
logger.info(`Updated backend type preference to: ${backend}`)
}
}
// Reset device setting when backend changes
this.config.device = ''
const closure = async () => {
await this.ensureBackendReady(backend, version)
}
closure()
} else if (key === 'auto_unload') {
this.autoUnload = value as boolean
} else if (key === 'llamacpp_env') {
this.llamacpp_env = value as string
} else if (key === 'memory_util') {
this.memoryMode = value as string
}
}
private async generateApiKey(modelId: string, port: string): Promise<string> {
const hash = await invoke<string>('plugin:llamacpp|generate_api_key', {
modelId: modelId + port,
apiSecret: this.apiSecret,
})
return hash
}
// Implement the required LocalProvider interface methods
override async list(): Promise<modelInfo[]> {
const modelsDir = await joinPath([await this.getProviderPath(), 'models'])
if (!(await fs.existsSync(modelsDir))) {
await fs.mkdir(modelsDir)
}
await this.migrateLegacyModels()
let modelIds: string[] = []
// DFS
let stack = [modelsDir]
while (stack.length > 0) {
const currentDir = stack.pop()
// check if model.yml exists
const modelConfigPath = await joinPath([currentDir, 'model.yml'])
if (await fs.existsSync(modelConfigPath)) {
// +1 to remove the leading slash
// NOTE: this does not handle Windows path \\
modelIds.push(currentDir.slice(modelsDir.length + 1))
continue
}
// otherwise, look into subdirectories
const children = await fs.readdirSync(currentDir)
for (const child of children) {
// skip files
const dirInfo = await fs.fileStat(child)
if (!dirInfo.isDirectory) {
continue
}
stack.push(child)
}
}
let modelInfos: modelInfo[] = []
for (const modelId of modelIds) {
const path = await joinPath([modelsDir, modelId, 'model.yml'])
const modelConfig = await invoke<ModelConfig>('read_yaml', { path })
const modelInfo = {
id: modelId,
name: modelConfig.name ?? modelId,
quant_type: undefined, // TODO: parse quantization type from model.yml or model.gguf
providerId: this.provider,
port: 0, // port is not known until the model is loaded
sizeBytes: modelConfig.size_bytes ?? 0,
} as modelInfo
modelInfos.push(modelInfo)
}
return modelInfos
}
private async migrateLegacyModels() {
// Attempt to migrate only once
if (localStorage.getItem('cortex_models_migrated') === 'true') return
const janDataFolderPath = await getJanDataFolderPath()
const modelsDir = await joinPath([janDataFolderPath, 'models'])
if (!(await fs.existsSync(modelsDir))) return
// DFS
let stack = [modelsDir]
while (stack.length > 0) {
const currentDir = stack.pop()
const files = await fs.readdirSync(currentDir)
for (const child of files) {
try {
const childPath = await joinPath([currentDir, child])
const stat = await fs.fileStat(childPath)
if (
files.some((e) => e.endsWith('model.yml')) &&
!child.endsWith('model.yml')