-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtoolhive-manager.ts
More file actions
355 lines (312 loc) · 9.91 KB
/
toolhive-manager.ts
File metadata and controls
355 lines (312 loc) · 9.91 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
import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import path from 'node:path'
import net from 'node:net'
import { app } from 'electron'
import { updateTrayStatus } from './system-tray'
import log from './logger'
import * as Sentry from '@sentry/electron/main'
import { getQuittingState } from './app-state'
import { readSetting } from './db/readers/settings-reader'
import { createEnhancedPath } from './utils/enhanced-path'
import {
ALREADY_RUNNING,
REGISTRY_AUTH_REQUIRED,
type ToolhiveProcessError,
type ToolhiveStatus,
} from '../../common/types/toolhive-status'
const binName = process.platform === 'win32' ? 'thv.exe' : 'thv'
const binPath = app.isPackaged
? path.join(
process.resourcesPath,
'bin',
`${process.platform}-${process.arch}`,
binName
)
: path.resolve(
__dirname,
'..',
'..',
'bin',
`${process.platform}-${process.arch}`,
binName
)
let toolhiveProcess: ReturnType<typeof spawn> | undefined
let toolhivePort: number | undefined
let toolhiveMcpPort: number | undefined
let isRestarting = false
let killTimer: NodeJS.Timeout | undefined
let processError: ToolhiveProcessError | undefined
export function getToolhivePort(): number | undefined {
return toolhivePort
}
export function getToolhiveMcpPort(): number | undefined {
return toolhiveMcpPort
}
export function isToolhiveRunning(): boolean {
const isRunning = !!toolhiveProcess && !toolhiveProcess.killed
return isRunning
}
export function getToolhiveStatus(): ToolhiveStatus {
return {
isRunning: isToolhiveRunning(),
processError,
}
}
/**
* Returns whether the app is using a custom ToolHive port (externally managed thv).
*/
export function isUsingCustomPort(): boolean {
return !app.isPackaged && !!process.env.THV_PORT
}
async function findFreePort(
minPort?: number,
maxPort?: number
): Promise<number> {
const checkPort = (port: number): Promise<boolean> => {
return new Promise((resolve) => {
const server = net.createServer()
server.listen(port, () => {
server.close(() => resolve(true))
})
server.on('error', () => resolve(false))
})
}
const getRandomPort = (): Promise<number> => {
return new Promise((resolve, reject) => {
const server = net.createServer()
server.listen(0, () => {
const address = server.address()
if (typeof address === 'object' && address && address.port) {
const port = address.port
server.close(() => resolve(port))
} else {
reject(new Error('Failed to get random port'))
}
})
server.on('error', reject)
})
}
// If no range specified, use OS assignment directly
if (!minPort || !maxPort) {
return await getRandomPort()
}
// Try random ports within range for better distribution
const attempts = Math.min(20, maxPort - minPort + 1)
const triedPorts = new Set<number>()
for (let i = 0; i < attempts; i++) {
const port = Math.floor(Math.random() * (maxPort - minPort + 1)) + minPort
if (triedPorts.has(port)) continue
triedPorts.add(port)
if (await checkPort(port)) {
return port
}
}
// Fallback to OS-assigned random port
log.warn(
`No free port found in range ${minPort}-${maxPort}, falling back to random port`
)
return await getRandomPort()
}
export async function startToolhive(): Promise<void> {
Sentry.withScope<Promise<void>>(async (scope) => {
if (isUsingCustomPort()) {
const customPort = parseInt(process.env.THV_PORT!, 10)
if (isNaN(customPort)) {
log.error(
`Invalid THV_PORT environment variable: ${process.env.THV_PORT}`
)
return
}
toolhivePort = customPort
toolhiveMcpPort = process.env.THV_MCP_PORT
? parseInt(process.env.THV_MCP_PORT!, 10)
: undefined
log.info(`Using external ToolHive on port ${toolhivePort}`)
return
}
if (!existsSync(binPath)) {
log.error(`ToolHive binary not found at: ${binPath}`)
return
}
processError = undefined
toolhiveMcpPort = await findFreePort()
toolhivePort = await findFreePort(50000, 50100)
log.info(
`Starting ToolHive from: ${binPath} on port ${toolhivePort}, MCP on port ${toolhiveMcpPort}`
)
const serveArgs = [
'serve',
'--openapi',
'--experimental-mcp',
'--experimental-mcp-host=127.0.0.1',
`--experimental-mcp-port=${toolhiveMcpPort}`,
'--host=127.0.0.1',
`--port=${toolhivePort}`,
]
const isE2E = process.env.TOOLHIVE_E2E === 'true'
const sentryDsn = isE2E ? undefined : import.meta.env.VITE_SENTRY_THV_DSN
if (sentryDsn && readSetting('isTelemetryEnabled') !== 'false') {
const sentryEnvironment = app.isPackaged ? 'production' : 'development'
serveArgs.push(
`--sentry-dsn=${sentryDsn}`,
`--sentry-environment=${sentryEnvironment}`,
`--sentry-traces-sample-rate=1.0`
)
}
toolhiveProcess = spawn(binPath, serveArgs, {
stdio: ['ignore', 'ignore', 'pipe'],
detached: false,
// Ensure child process is killed when parent exits
// On Windows, this creates a job object to enforce cleanup
windowsHide: true,
env: {
...process.env,
PATH: createEnhancedPath(),
TOOLHIVE_SKIP_DESKTOP_CHECK: 'true',
},
})
log.info(`[startToolhive] Process spawned with PID: ${toolhiveProcess.pid}`)
scope.addBreadcrumb({
category: 'debug',
message: `Starting ToolHive from: ${binPath} on port ${toolhivePort}, MCP on port ${toolhiveMcpPort}, PID: ${toolhiveProcess.pid}`,
})
updateTrayStatus(!!toolhiveProcess)
// Capture and log stderr
if (toolhiveProcess.stderr) {
log.info(`[ToolHive] Capturing stderr enabled`)
toolhiveProcess.stderr.on('data', (data) => {
const output = data.toString().trim()
if (!output) return
if (output.includes('A new version of ToolHive is available')) {
return
}
if (output.includes('registry authentication required')) {
processError = REGISTRY_AUTH_REQUIRED
}
if (output.includes('another ToolHive server is already running')) {
processError = ALREADY_RUNNING
}
log.info(`[ToolHive stderr] ${output}`)
scope.addBreadcrumb({
category: 'debug',
message: `[ToolHive stderr] ${output}`,
level: 'log',
})
})
}
toolhiveProcess.on('error', (error) => {
log.error('Failed to start ToolHive: ', error)
Sentry.captureMessage(
`Failed to start ToolHive: ${JSON.stringify(error)}`,
'fatal'
)
updateTrayStatus(false)
})
toolhiveProcess.on('exit', (code) => {
log.warn(`ToolHive process exited with code: ${code}`)
toolhiveProcess = undefined
if (!isRestarting && !getQuittingState()) {
updateTrayStatus(false)
Sentry.captureMessage(
`ToolHive process exited with code: ${code}`,
'fatal'
)
}
})
})
}
export async function restartToolhive(): Promise<void> {
if (isRestarting) {
log.info('Restart already in progress, skipping...')
return
}
isRestarting = true
log.info('Restarting ToolHive...')
try {
// Stop existing process if running
if (toolhiveProcess && !toolhiveProcess.killed) {
log.info('Stopping existing ToolHive process...')
toolhiveProcess.kill()
}
// Start new process
await startToolhive()
log.info('ToolHive restarted successfully')
} catch (error) {
log.error('Failed to restart ToolHive: ', error)
Sentry.captureMessage(
`Failed to restart ToolHive: ${JSON.stringify(error)}`,
'fatal'
)
} finally {
// avoid another restart until process is stabilized
setTimeout(() => {
isRestarting = false
}, 5000)
}
}
/** Attempt to kill a process, returning true on success */
function tryKillProcess(
process: ReturnType<typeof spawn>,
signal: NodeJS.Signals,
logPrefix: string
): boolean {
try {
const result = process.kill(signal)
log.info(`${logPrefix} ${signal} sent, result: ${result}`)
return result
} catch (err) {
log.error(`${logPrefix} Failed to send ${signal}:`, err)
return false
}
}
/** Schedule delayed SIGKILL if process doesn't exit gracefully */
function scheduleForceKill(
process: ReturnType<typeof spawn>,
pid: number
): void {
killTimer = setTimeout(() => {
killTimer = undefined
if (!process.killed) {
log.warn(
`[stopToolhive] Process ${pid} did not exit gracefully, forcing SIGKILL...`
)
tryKillProcess(process, 'SIGKILL', '[stopToolhive]')
}
}, 2000)
}
export function stopToolhive(options?: { force?: boolean }): void {
const force = options?.force ?? false
// Clear any pending kill timer
if (killTimer) {
clearTimeout(killTimer)
killTimer = undefined
}
// Early return if no process to stop
if (!toolhiveProcess || toolhiveProcess.killed) {
log.info(
`[stopToolhive] No process to stop (process=${!!toolhiveProcess}, killed=${toolhiveProcess?.killed})`
)
return
}
const pidToKill = toolhiveProcess.pid
log.info(`Stopping ToolHive process (PID: ${pidToKill})...`)
// Capture process reference before clearing global
const processToKill = toolhiveProcess
toolhiveProcess = undefined
// Attempt to kill the process
const signal: NodeJS.Signals = force ? 'SIGKILL' : 'SIGTERM'
const killed = tryKillProcess(processToKill, signal, '[stopToolhive]')
// If graceful shutdown failed, try force kill immediately
if (!killed) {
tryKillProcess(processToKill, 'SIGKILL', '[stopToolhive]')
log.info(`[stopToolhive] Process cleanup completed`)
return
}
// For graceful shutdown, schedule delayed force kill
if (!force && pidToKill !== undefined) {
scheduleForceKill(processToKill, pidToKill)
}
log.info(`[stopToolhive] Process cleanup completed`)
}
export { binPath }