-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathOpenClawService.ts
More file actions
1043 lines (909 loc) · 36.3 KB
/
OpenClawService.ts
File metadata and controls
1043 lines (909 loc) · 36.3 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
import crypto from 'node:crypto'
import fs from 'node:fs'
import { Socket } from 'node:net'
import os from 'node:os'
import path from 'node:path'
import { exec } from '@expo/sudo-prompt'
import { loggerService } from '@logger'
import { isLinux, isMac, isWin } from '@main/constant'
import { isUserInChina } from '@main/utils/ipService'
import { crossPlatformSpawn, executeCommand, findExecutableInEnv } from '@main/utils/process'
import getShellEnv, { refreshShellEnv } from '@main/utils/shell-env'
import type { NodeCheckResult } from '@shared/config/types'
import { IpcChannel } from '@shared/IpcChannel'
import { hasAPIVersion, withoutTrailingSlash } from '@shared/utils'
import type { Model, Provider, ProviderType, VertexProvider } from '@types'
import { type ChildProcess, spawn } from 'child_process'
import semver from 'semver'
import VertexAIService from './VertexAIService'
import { windowService } from './WindowService'
const logger = loggerService.withContext('OpenClawService')
const NPM_MIRROR_CN = 'https://registry.npmmirror.com'
const OPENCLAW_CONFIG_DIR = path.join(os.homedir(), '.openclaw')
// Original user config (read-only, used as template for first-time setup)
const OPENCLAW_ORIGINAL_CONFIG_PATH = path.join(OPENCLAW_CONFIG_DIR, 'openclaw.json')
// Cherry Studio's isolated config (read/write) — OpenClaw reads the OPENCLAW_CONFIG_PATH env var to locate this
const OPENCLAW_CONFIG_PATH = path.join(OPENCLAW_CONFIG_DIR, 'openclaw.cherry.json')
const DEFAULT_GATEWAY_PORT = 18790
export type GatewayStatus = 'stopped' | 'starting' | 'running' | 'error'
export interface HealthInfo {
status: 'healthy' | 'unhealthy'
gatewayPort: number
uptime?: number
version?: string
}
export interface ChannelInfo {
id: string
name: string
type: string
status: 'connected' | 'disconnected' | 'error'
}
export interface OpenClawConfig {
gateway?: {
mode?: 'local' | 'remote'
port?: number
auth?: {
token?: string
}
}
agents?: {
defaults?: {
model?: {
primary?: string
}
}
}
models?: {
mode?: string
providers?: Record<string, OpenClawProviderConfig>
}
}
export interface OpenClawProviderConfig {
baseUrl: string
apiKey: string
api: string
models: Array<{
id: string
name: string
contextWindow?: number
}>
}
/**
* OpenClaw API types
* - 'openai-completions': For OpenAI-compatible chat completions API
* - 'anthropic-messages': For Anthropic Messages API format
*/
const OPENCLAW_API_TYPES = {
OPENAI: 'openai-completions',
ANTHROPIC: 'anthropic-messages',
OPENAI_RESPOSNE: 'openai-responses'
} as const
/**
* Providers that always use Anthropic API format
*/
const ANTHROPIC_ONLY_PROVIDERS: ProviderType[] = ['anthropic', 'vertex-anthropic']
/**
* Endpoint types that use Anthropic API format
* These are values from model.endpoint_type field
*/
const ANTHROPIC_ENDPOINT_TYPES = ['anthropic']
/**
* Check if a model should use Anthropic API based on endpoint_type
*/
function isAnthropicEndpointType(model: Model): boolean {
const endpointType = model.endpoint_type
return endpointType ? ANTHROPIC_ENDPOINT_TYPES.includes(endpointType) : false
}
/**
* Type guard to check if a provider is a VertexProvider
*/
function isVertexProvider(provider: Provider): provider is VertexProvider {
return provider.type === 'vertexai'
}
class OpenClawService {
private gatewayProcess: ChildProcess | null = null
private gatewayStatus: GatewayStatus = 'stopped'
private gatewayPort: number = DEFAULT_GATEWAY_PORT
private gatewayAuthToken: string = ''
private get gatewayUrl(): string {
return `ws://127.0.0.1:${this.gatewayPort}`
}
constructor() {
this.checkInstalled = this.checkInstalled.bind(this)
this.checkNodeVersion = this.checkNodeVersion.bind(this)
this.getNodeDownloadUrl = this.getNodeDownloadUrl.bind(this)
this.getGitDownloadUrl = this.getGitDownloadUrl.bind(this)
this.install = this.install.bind(this)
this.uninstall = this.uninstall.bind(this)
this.startGateway = this.startGateway.bind(this)
this.stopGateway = this.stopGateway.bind(this)
this.restartGateway = this.restartGateway.bind(this)
this.getStatus = this.getStatus.bind(this)
this.checkHealth = this.checkHealth.bind(this)
this.getDashboardUrl = this.getDashboardUrl.bind(this)
this.syncProviderConfig = this.syncProviderConfig.bind(this)
this.getChannelStatus = this.getChannelStatus.bind(this)
}
/**
* Check if OpenClaw is installed
*/
public async checkInstalled(): Promise<{ installed: boolean; path: string | null }> {
const binaryPath = await findExecutableInEnv('openclaw')
return { installed: binaryPath !== null, path: binaryPath }
}
/**
* Check if Node.js is available and meets the minimum version requirement (22.0+).
* Detects Node.js through the user's login shell environment (handles nvm, mise, fnm, etc.)
*
* Returns a discriminated union so callers can distinguish between:
* - Node.js not installed at all
* - Node.js installed but version too low
* - Node.js installed and version OK
*/
public async checkNodeVersion(): Promise<NodeCheckResult> {
const MINIMUM_VERSION = '22.0.0'
try {
await refreshShellEnv()
const nodePath = await findExecutableInEnv('node')
if (!nodePath) {
logger.debug('Node.js not found in environment')
return { status: 'not_found' }
}
const output = await executeCommand(nodePath, ['--version'], { capture: true, timeout: 5000 })
const version = semver.valid(semver.coerce(output.trim()))
if (!version || semver.lt(version, MINIMUM_VERSION)) {
logger.debug(`Node.js version too low: ${version} at ${nodePath}`)
return { status: 'version_low', version: version ?? output.trim(), path: nodePath }
}
logger.debug(`Node.js version OK: ${version} at ${nodePath}`)
return { status: 'ok', version, path: nodePath }
} catch (error) {
logger.warn('Failed to check Node.js version:', error as Error)
return { status: 'not_found' }
}
}
/**
* Get Node.js download URL based on current OS and architecture
*/
public getNodeDownloadUrl(): string {
const version = 'v22.13.1'
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
if (isWin) {
return `https://nodejs.org/dist/${version}/node-${version}-${arch}.msi`
} else if (isMac) {
// macOS: .pkg installer (universal)
return `https://nodejs.org/dist/${version}/node-${version}.pkg`
} else if (isLinux) {
return `https://nodejs.org/dist/${version}/node-${version}-linux-${arch}.tar.xz`
}
// Fallback to official download page
return 'https://nodejs.org/en/download'
}
/**
* Get Git download URL based on current OS and architecture
*/
public getGitDownloadUrl(): string {
const version = '2.53.0'
if (isWin) {
const winArch = process.arch === 'arm64' ? 'arm64' : '64-bit'
return `https://github.com/git-for-windows/git/releases/download/v${version}.windows.1/Git-${version}-${winArch}.exe`
} else if (isMac) {
return 'https://git-scm.com/download/mac'
} else if (isLinux) {
return 'https://git-scm.com/download/linux'
}
return 'https://git-scm.com/downloads'
}
/**
* Send install progress to renderer
*/
private sendInstallProgress(message: string, type: 'info' | 'warn' | 'error' = 'info') {
const win = windowService.getMainWindow()
win?.webContents.send(IpcChannel.OpenClaw_InstallProgress, { message, type })
}
/**
* Install OpenClaw using npm with China mirror acceleration
* For users in China, install @qingchencloud/openclaw-zh package instead
*/
public async install(): Promise<{ success: boolean; message: string }> {
const inChina = await isUserInChina()
const packageName = inChina ? '@qingchencloud/openclaw-zh@latest' : 'openclaw@latest'
const registryArg = inChina ? `--registry=${NPM_MIRROR_CN}` : ''
const npmPath = (await findExecutableInEnv('npm')) || 'npm'
const npmArgs = ['install', '-g', packageName]
if (registryArg) npmArgs.push(registryArg)
// Keep the command string for logging and sudo retry.
// On macOS/Linux, prepend npm's parent dir to PATH so that sudo (which runs in a
// clean environment without user PATH) can resolve `node` via npm's shebang
// (#!/usr/bin/env node).
const nodeDir = path.dirname(npmPath)
const npmCommand = isWin
? `"${npmPath}" install -g ${packageName} ${registryArg}`.trim()
: `PATH="${nodeDir}:$PATH" "${npmPath}" install -g ${packageName} ${registryArg}`.trim()
// On Windows, wrap npm path in quotes if it contains spaces and is not already quoted
const needsQuotes = isWin && npmPath.includes(' ') && !npmPath.startsWith('"')
const processedNpmPath = needsQuotes ? `"${npmPath}"` : npmPath
logger.info(`Installing OpenClaw with command: ${processedNpmPath} ${npmArgs.join(' ')}`)
this.sendInstallProgress(`Running: ${processedNpmPath} ${npmArgs.join(' ')}`)
const spawnEnv = await getShellEnv()
return new Promise((resolve) => {
try {
const installProcess = crossPlatformSpawn(processedNpmPath, npmArgs, { env: spawnEnv })
let stderr = ''
installProcess.stdout?.on('data', (data) => {
const msg = data.toString().trim()
if (msg) {
logger.info('OpenClaw install stdout:', msg)
this.sendInstallProgress(msg)
}
})
installProcess.stderr?.on('data', (data) => {
const msg = data.toString().trim()
stderr += data.toString()
if (msg) {
// npm warnings are not fatal errors
const isWarning = msg.includes('npm warn') || msg.includes('ExperimentalWarning')
logger.warn('OpenClaw install stderr:', msg)
this.sendInstallProgress(msg, isWarning ? 'warn' : 'info')
}
})
installProcess.on('error', (error) => {
logger.error('OpenClaw install error:', error)
this.sendInstallProgress(error.message, 'error')
resolve({ success: false, message: error.message })
})
installProcess.on('exit', (code) => {
if (code === 0) {
logger.info('OpenClaw installed successfully')
this.sendInstallProgress('OpenClaw installed successfully!')
resolve({ success: true, message: 'OpenClaw installed successfully' })
} else {
logger.error(`OpenClaw install failed with code ${code}`)
// Detect EACCES permission error and retry with sudo
if (stderr.includes('EACCES') || stderr.includes('permission denied')) {
logger.info('Permission denied, retrying with sudo-prompt...')
this.sendInstallProgress('Permission denied. Requesting administrator access...')
// Use full npm path since sudo runs in clean environment without user PATH
exec(npmCommand, { name: 'Cherry Studio' }, (error, stdout) => {
if (error) {
logger.error('Sudo install failed:', error)
this.sendInstallProgress(`Installation failed: ${error.message}`, 'error')
resolve({ success: false, message: error.message })
} else {
logger.info('OpenClaw installed successfully with sudo')
if (stdout) {
this.sendInstallProgress(stdout.toString())
}
this.sendInstallProgress('OpenClaw installed successfully!')
resolve({ success: true, message: 'OpenClaw installed successfully' })
}
})
} else {
this.sendInstallProgress(`Installation failed with exit code ${code}`, 'error')
resolve({
success: false,
message: stderr || `Installation failed with exit code ${code}`
})
}
}
})
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
logger.error('Failed to start OpenClaw installation:', error as Error)
this.sendInstallProgress(errorMessage, 'error')
resolve({ success: false, message: errorMessage })
}
})
}
/**
* Uninstall OpenClaw using npm
* Uninstalls both the standard and Chinese packages to ensure clean removal
*/
public async uninstall(): Promise<{ success: boolean; message: string }> {
// First stop the gateway if running
if (this.gatewayStatus === 'running') {
await this.stopGateway()
}
const npmPath = (await findExecutableInEnv('npm')) || 'npm'
const npmArgs = ['uninstall', '-g', 'openclaw', '@qingchencloud/openclaw-zh']
// Keep the command string for logging and sudo retry.
// On macOS/Linux, prepend npm's parent dir to PATH so that sudo can resolve `node`.
const nodeDir = path.dirname(npmPath)
const npmCommand = isWin
? `"${npmPath}" uninstall -g openclaw @qingchencloud/openclaw-zh`
: `PATH="${nodeDir}:$PATH" "${npmPath}" uninstall -g openclaw @qingchencloud/openclaw-zh`
// On Windows, wrap npm path in quotes if it contains spaces and is not already quoted
const needsQuotes = isWin && npmPath.includes(' ') && !npmPath.startsWith('"')
const processedNpmPath = needsQuotes ? `"${npmPath}"` : npmPath
logger.info(`Uninstalling OpenClaw with command: ${processedNpmPath} ${npmArgs.join(' ')}`)
this.sendInstallProgress(`Running: ${processedNpmPath} ${npmArgs.join(' ')}`)
const shellEnv = await getShellEnv()
return new Promise((resolve) => {
try {
const uninstallProcess = crossPlatformSpawn(processedNpmPath, npmArgs, { env: shellEnv })
let stderr = ''
uninstallProcess.stdout?.on('data', (data) => {
const msg = data.toString().trim()
if (msg) {
logger.info('OpenClaw uninstall stdout:', msg)
this.sendInstallProgress(msg)
}
})
uninstallProcess.stderr?.on('data', (data) => {
const msg = data.toString().trim()
stderr += data.toString()
if (msg) {
logger.warn('OpenClaw uninstall stderr:', msg)
this.sendInstallProgress(msg, 'warn')
}
})
uninstallProcess.on('error', (error) => {
logger.error('OpenClaw uninstall error:', error)
this.sendInstallProgress(error.message, 'error')
resolve({ success: false, message: error.message })
})
uninstallProcess.on('exit', (code) => {
if (code === 0) {
logger.info('OpenClaw uninstalled successfully')
this.sendInstallProgress('OpenClaw uninstalled successfully!')
resolve({ success: true, message: 'OpenClaw uninstalled successfully' })
} else {
logger.error(`OpenClaw uninstall failed with code ${code}`)
// Detect EACCES permission error and retry with sudo
if (stderr.includes('EACCES') || stderr.includes('permission denied')) {
logger.info('Permission denied, retrying uninstall with sudo-prompt...')
this.sendInstallProgress('Permission denied. Requesting administrator access...')
exec(npmCommand, { name: 'Cherry Studio' }, (error, stdout) => {
if (error) {
logger.error('Sudo uninstall failed:', error)
this.sendInstallProgress(`Uninstallation failed: ${error.message}`, 'error')
resolve({ success: false, message: error.message })
} else {
logger.info('OpenClaw uninstalled successfully with sudo')
if (stdout) {
this.sendInstallProgress(stdout.toString())
}
this.sendInstallProgress('OpenClaw uninstalled successfully!')
resolve({ success: true, message: 'OpenClaw uninstalled successfully' })
}
})
} else {
this.sendInstallProgress(`Uninstallation failed with exit code ${code}`, 'error')
resolve({
success: false,
message: stderr || `Uninstallation failed with exit code ${code}`
})
}
}
})
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
logger.error('Failed to start OpenClaw uninstallation:', error as Error)
this.sendInstallProgress(errorMessage, 'error')
resolve({ success: false, message: errorMessage })
}
})
}
/**
* Start the OpenClaw Gateway
*/
public async startGateway(
_: Electron.IpcMainInvokeEvent,
port?: number
): Promise<{ success: boolean; message: string }> {
this.gatewayPort = port ?? DEFAULT_GATEWAY_PORT
// Prevent concurrent startup calls
if (this.gatewayStatus === 'starting') {
return { success: false, message: 'Gateway is already starting' }
}
// Refresh shell env first so findExecutableInEnv and crossPlatformSpawn both use the same fresh env
const shellEnv = await refreshShellEnv()
const openclawPath = await findExecutableInEnv('openclaw')
if (!openclawPath) {
return {
success: false,
message: 'OpenClaw binary not found. Please install OpenClaw first.'
}
}
// Check if gateway is already running in the system (including external processes)
const alreadyRunning = await this.checkGatewayStatus(openclawPath, shellEnv)
if (alreadyRunning) {
// Reuse existing gateway instead of trying to restart
this.gatewayStatus = 'running'
logger.info(`Reusing existing gateway on port ${this.gatewayPort}`)
return { success: true, message: 'Gateway is already running' }
}
// No gateway running, start a new one
this.gatewayStatus = 'starting'
try {
await this.spawnAndWaitForGateway(openclawPath, shellEnv)
this.gatewayStatus = 'running'
logger.info(`Gateway started on port ${this.gatewayPort}`)
return { success: true, message: `Gateway started on port ${this.gatewayPort}` }
} catch (error) {
this.gatewayStatus = 'error'
const errorMessage = error instanceof Error ? error.message : String(error)
logger.error('Failed to start gateway:', error as Error)
return { success: false, message: errorMessage }
}
}
/**
* Spawn gateway process and wait for it to become ready
* Monitors process exit and stderr for early failure detection
*/
private async spawnAndWaitForGateway(openclawPath: string, shellEnv: Record<string, string>): Promise<void> {
// Track startup errors from stderr and process exit
let startupError: string | null = null
let processExited = false
const gatewayEnv = { ...shellEnv, OPENCLAW_CONFIG_PATH }
logger.info(`Spawning gateway process: ${openclawPath} gateway --port ${this.gatewayPort}`)
if (isWin) {
// Force UTF-8 code page to prevent garbled Chinese text from child processes. See #13384.
this.gatewayProcess = spawn(
'cmd',
['/c', `chcp 65001 >nul && "${openclawPath}" gateway --port ${this.gatewayPort}`],
{ env: gatewayEnv, stdio: 'pipe' }
)
} else {
this.gatewayProcess = crossPlatformSpawn(openclawPath, ['gateway', '--port', String(this.gatewayPort)], {
env: gatewayEnv
})
}
logger.info(`Gateway process spawned with pid: ${this.gatewayProcess.pid}`)
// Monitor stderr for error messages
this.gatewayProcess.stderr?.on('data', (data) => {
const msg = data.toString()
logger.warn('Gateway stderr:', msg)
// Extract specific error messages for better user feedback
if (msg.includes('already running')) {
startupError = 'Gateway already running (port conflict)'
} else if (msg.includes('already in use')) {
startupError = `Port ${this.gatewayPort} is already in use`
}
})
this.gatewayProcess.stdout?.on('data', (data) => {
logger.info('Gateway stdout:', data.toString())
})
// Monitor process exit during startup
this.gatewayProcess.on('exit', (code) => {
logger.info(`Gateway process exited with code ${code}`)
processExited = true
if (code !== 0 && !startupError) {
startupError = `Process exited with code ${code}`
}
this.gatewayProcess = null
})
this.gatewayProcess.on('error', (err) => {
logger.error('Gateway process error:', err)
processExited = true
startupError = err.message
})
// Wait for gateway to become ready (max 30 seconds)
const maxWaitMs = 30000
const pollIntervalMs = 1000
const startTime = Date.now()
let pollCount = 0
while (Date.now() - startTime < maxWaitMs) {
// Fast fail if process has already exited
if (processExited) {
throw new Error(startupError || 'Gateway process exited unexpectedly')
}
await new Promise((r) => setTimeout(r, pollIntervalMs))
pollCount++
logger.debug(`Polling gateway status (attempt ${pollCount})...`)
const isRunning = await this.checkGatewayStatus(openclawPath, shellEnv)
if (isRunning) {
logger.info(`Gateway is running (verified via CLI after ${pollCount} polls)`)
return
}
const portOpen = await this.checkPortOpen(this.gatewayPort)
if (portOpen) {
await new Promise((r) => setTimeout(r, 2000))
if (processExited) {
logger.info(`Spawned process exited but port ${this.gatewayPort} is open — reusing existing gateway`)
return
}
logger.info(`Gateway port ${this.gatewayPort} is open and process alive (verified after ${pollCount} polls)`)
return
}
}
// Timeout - process may still be starting but taking too long
throw new Error(`Gateway failed to start within ${maxWaitMs}ms (${pollCount} polls)`)
}
/**
* Stop the OpenClaw Gateway
* Handles both our process and external gateway processes
*/
public async stopGateway(): Promise<{ success: boolean; message: string }> {
try {
const openclawPath = await findExecutableInEnv('openclaw')
if (openclawPath) {
const shellEnv = await getShellEnv()
await this.runGatewayStop(openclawPath, shellEnv)
// Verify stop was successful
const stillRunning = await this.checkGatewayStatus(openclawPath, shellEnv)
if (stillRunning) {
// CLI stop failed — fall back to killing the process directly
if (this.gatewayProcess) {
logger.warn('Gateway still running after CLI stop, falling back to kill')
await this.killProcess(this.gatewayProcess)
} else {
logger.warn('Gateway still running after stop attempt and no process reference')
return {
success: false,
message: 'Failed to stop gateway. Try running: openclaw gateway stop'
}
}
}
} else if (this.gatewayProcess) {
// No CLI binary found — kill directly as last resort
logger.warn('OpenClaw binary not found, killing process directly')
await this.killProcess(this.gatewayProcess)
}
this.gatewayProcess = null
this.gatewayStatus = 'stopped'
logger.info('Gateway stopped')
return { success: true, message: 'Gateway stopped successfully' }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
logger.error('Failed to stop gateway:', error as Error)
return { success: false, message: errorMessage }
}
}
/**
* Kill a child process with SIGTERM, then SIGKILL after timeout
*/
private async killProcess(proc: ChildProcess): Promise<void> {
return new Promise((resolve) => {
const timeout = setTimeout(() => {
proc.kill('SIGKILL')
resolve()
}, 5000)
proc.once('exit', () => {
clearTimeout(timeout)
resolve()
})
proc.kill('SIGTERM')
})
}
/**
* Run `openclaw gateway stop` command
*/
private async runGatewayStop(openclawPath: string, env: Record<string, string>): Promise<void> {
return new Promise((resolve) => {
const proc = crossPlatformSpawn(openclawPath, ['gateway', 'stop', '--url', this.gatewayUrl], {
env: { ...env, OPENCLAW_CONFIG_PATH }
})
const timeout = setTimeout(() => {
proc.kill('SIGKILL')
resolve()
}, 5000)
proc.on('exit', () => {
clearTimeout(timeout)
// Wait for port to be released
setTimeout(resolve, 500)
})
proc.on('error', () => {
clearTimeout(timeout)
resolve()
})
})
}
/**
* Restart the OpenClaw Gateway
*/
public async restartGateway(event: Electron.IpcMainInvokeEvent): Promise<{ success: boolean; message: string }> {
await this.stopGateway()
return this.startGateway(event, this.gatewayPort)
}
/**
* Get Gateway status
*/
public getStatus(): { status: GatewayStatus; port: number } {
return {
status: this.gatewayStatus,
port: this.gatewayPort
}
}
/**
* Check Gateway health by verifying WebSocket connectivity
*/
public async checkHealth(): Promise<HealthInfo> {
// If we know the gateway is not running, return unhealthy immediately
if (this.gatewayStatus !== 'running' || !this.gatewayProcess) {
return {
status: 'unhealthy',
gatewayPort: this.gatewayPort
}
}
try {
// Check if the WebSocket port is accepting connections
const isAlive = await this.checkPortOpen(this.gatewayPort)
if (isAlive) {
return {
status: 'healthy',
gatewayPort: this.gatewayPort
}
}
} catch (error) {
logger.debug('Health check failed:', error as Error)
}
return {
status: 'unhealthy',
gatewayPort: this.gatewayPort
}
}
/**
* Check if a port is open and accepting connections
*/
private async checkPortOpen(port: number): Promise<boolean> {
return new Promise((resolve) => {
const socket = new Socket()
socket.setTimeout(2000)
socket.on('connect', () => {
socket.destroy()
resolve(true)
})
socket.on('timeout', () => {
socket.destroy()
resolve(false)
})
socket.on('error', () => {
socket.destroy()
resolve(false)
})
socket.connect(port, 'localhost')
})
}
/**
* Get OpenClaw Dashboard URL (for opening in minapp)
*/
public getDashboardUrl(): string {
let dashboardUrl = `http://localhost:${this.gatewayPort}`
// Include auth token in URL for dashboard authentication
if (this.gatewayAuthToken) {
dashboardUrl += `?token=${encodeURIComponent(this.gatewayAuthToken)}`
}
return dashboardUrl
}
/**
* Generate a cryptographically secure random auth token
*/
private generateAuthToken(): string {
return crypto.randomBytes(24).toString('base64url')
}
/**
* Sync Cherry Studio Provider configuration to OpenClaw
*/
public async syncProviderConfig(
_: Electron.IpcMainInvokeEvent,
provider: Provider,
primaryModel: Model
): Promise<{ success: boolean; message: string }> {
try {
// Ensure config directory exists
if (!fs.existsSync(OPENCLAW_CONFIG_DIR)) {
fs.mkdirSync(OPENCLAW_CONFIG_DIR, { recursive: true })
}
// Read existing cherry config, or copy from original openclaw.json as base
let config: OpenClawConfig = {}
if (fs.existsSync(OPENCLAW_CONFIG_PATH)) {
try {
const content = fs.readFileSync(OPENCLAW_CONFIG_PATH, 'utf-8')
config = JSON.parse(content)
} catch {
logger.warn('Failed to parse existing Cherry OpenClaw config, creating new one')
}
} else if (fs.existsSync(OPENCLAW_ORIGINAL_CONFIG_PATH)) {
try {
const content = fs.readFileSync(OPENCLAW_ORIGINAL_CONFIG_PATH, 'utf-8')
config = JSON.parse(content)
logger.info('Using original openclaw.json as base template for openclaw.cherry.json')
} catch {
logger.warn('Failed to parse original openclaw.json, creating new config')
}
}
// Build provider key
const providerKey = `cherry-${provider.id}`
// Determine the API type based on model, not provider type
// Mixed providers (cherryin, aihubmix, etc.) can have both OpenAI and Anthropic endpoints
const apiType = this.determineApiType(provider, primaryModel)
const baseUrl = this.getBaseUrlForApiType(provider, apiType)
// Get API key - for vertexai, get access token from VertexAIService
// If multiple API keys are configured (comma-separated), use the first one
// Some providers like Ollama and LM Studio don't require API keys
let apiKey = provider.apiKey ? provider.apiKey.split(',')[0].trim() : ''
if (isVertexProvider(provider)) {
try {
const vertexService = VertexAIService.getInstance()
apiKey = await vertexService.getAccessToken({
projectId: provider.project,
serviceAccount: {
privateKey: provider.googleCredentials.privateKey,
clientEmail: provider.googleCredentials.clientEmail
}
})
} catch (err) {
logger.warn('Failed to get VertexAI access token, using provider apiKey:', err as Error)
}
}
// Build OpenClaw provider config
const openclawProvider: OpenClawProviderConfig = {
baseUrl,
apiKey,
api: apiType,
models: provider.models.map((m) => ({
id: m.id,
name: m.name,
// FIXME: in v2
contextWindow: 128000
}))
}
// Set gateway mode to local (required for gateway to start)
config.gateway = config.gateway || {}
config.gateway.mode = 'local'
config.gateway.port = this.gatewayPort
// Auto-generate auth token if not already set, and store it for API calls
const token = this.gatewayAuthToken || this.generateAuthToken()
config.gateway.auth = { token }
this.gatewayAuthToken = token
// Update config
config.models = config.models || { mode: 'merge', providers: {} }
config.models.providers = config.models.providers || {}
config.models.providers[providerKey] = openclawProvider
// Set primary model
config.agents = config.agents || { defaults: {} }
config.agents.defaults = config.agents.defaults || {}
config.agents.defaults.model = {
primary: `${providerKey}/${primaryModel.id}`
}
// Write config file
fs.writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8')
logger.info(`Synced provider ${provider.id} to OpenClaw config`)
return { success: true, message: `Provider ${provider.name} synced to OpenClaw` }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
logger.error('Failed to sync provider config:', error as Error)
return { success: false, message: errorMessage }
}
}
/**
* Get connected channel status
*/
public async getChannelStatus(): Promise<ChannelInfo[]> {
try {
const response = await fetch(`http://localhost:${this.gatewayPort}/api/channels`, {
signal: AbortSignal.timeout(5000)
})
if (response.ok) {
const data = await response.json()
return data.channels || []
}
} catch (error) {
logger.debug('Failed to get channel status:', error as Error)
}
return []
}
/**
* Check gateway status using `openclaw gateway status` command
* Returns true if gateway is running
*/
private async checkGatewayStatus(openclawPath: string, env: Record<string, string>): Promise<boolean> {
return new Promise((resolve) => {
const statusProcess = crossPlatformSpawn(openclawPath, ['gateway', 'status', '--url', this.gatewayUrl], {
env: { ...env, OPENCLAW_CONFIG_PATH }
})
let stdout = ''
let resolved = false
const doResolve = (value: boolean) => {
if (resolved) return
resolved = true
resolve(value)
}
const timeoutId = setTimeout(() => {
// On timeout, check stdout accumulated so far before giving up
const lowerStdout = stdout.toLowerCase()
const isRunning = lowerStdout.includes('listening')
logger.debug(`Gateway status check timed out after 10s, stdout indicates running: ${isRunning}`)
statusProcess.kill('SIGKILL')
doResolve(isRunning)
}, 10_000)
statusProcess.stdout?.on('data', (data) => {
stdout += data.toString()
})
statusProcess.on('close', (code) => {
clearTimeout(timeoutId)
const lowerStdout = stdout.toLowerCase()
const isRunning = (code === 0 || code === null) && lowerStdout.includes('listening')
logger.debug('Gateway status check result:', { code, stdout: stdout.trim(), isRunning })
doResolve(isRunning)
})
statusProcess.on('error', () => {
clearTimeout(timeoutId)
doResolve(false)
})
})
}
/**
* Determine the API type based on model and provider
* This supports mixed providers (cherryin, aihubmix, new-api, etc.) that have both OpenAI and Anthropic endpoints
*
* Priority order:
* 1. Provider type (anthropic, vertex-anthropic always use Anthropic API)
* 2. Model endpoint_type (explicit endpoint configuration)
* 3. Provider has anthropicApiHost configured
* 4. Default to OpenAI-compatible
*/
private determineApiType(provider: Provider, model: Model): string {
// 1. Check if provider type is always Anthropic
if (ANTHROPIC_ONLY_PROVIDERS.includes(provider.type)) {
return OPENCLAW_API_TYPES.ANTHROPIC
}
// 2. Check model's endpoint_type (used by new-api and other mixed providers)
if (isAnthropicEndpointType(model)) {
return OPENCLAW_API_TYPES.ANTHROPIC
}
// 3. Check if provider has anthropicApiHost configured
if (provider.anthropicApiHost) {
return OPENCLAW_API_TYPES.ANTHROPIC
}
if (provider.type === 'openai-response') {
return OPENCLAW_API_TYPES.OPENAI_RESPOSNE
}
// 4. Default to OpenAI-compatible
return OPENCLAW_API_TYPES.OPENAI
}
/**
* Get the appropriate base URL for the given API type
* For anthropic-messages, prefer anthropicApiHost if available
* For openai-completions, use apiHost with proper formatting
*/
private getBaseUrlForApiType(provider: Provider, apiType: string): string {
if (apiType === OPENCLAW_API_TYPES.ANTHROPIC) {
// For Anthropic API type, prefer anthropicApiHost if available
const host = provider.anthropicApiHost || provider.apiHost
return this.formatAnthropicUrl(host)
}
// For OpenAI-compatible API type
return this.formatOpenAIUrl(provider)
}
/**
* Format URL for OpenAI-compatible APIs
* Provider-specific URL patterns:
* - VertexAI: {location}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{location}/endpoints/openapi