|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2026 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import {spawn} from 'node:child_process'; |
| 8 | +import fs from 'node:fs'; |
| 9 | +import net from 'node:net'; |
| 10 | + |
| 11 | +import {logger} from '../logger.js'; |
| 12 | +import {PipeTransport} from '../third_party/index.js'; |
| 13 | + |
| 14 | +import type {DaemonMessage} from './types.js'; |
| 15 | +import { |
| 16 | + DAEMON_SCRIPT_PATH, |
| 17 | + getSocketPath, |
| 18 | + getPidFilePath, |
| 19 | + isDaemonRunning, |
| 20 | +} from './utils.js'; |
| 21 | + |
| 22 | +/** |
| 23 | + * Waits for a file to be created and populated. |
| 24 | + */ |
| 25 | +function waitForFile(filePath: string, timeout = 5000) { |
| 26 | + return new Promise<void>((resolve, reject) => { |
| 27 | + if (fs.existsSync(filePath) && fs.statSync(filePath).size > 0) { |
| 28 | + resolve(); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + const timer = setTimeout(() => { |
| 33 | + fs.unwatchFile(filePath); |
| 34 | + reject( |
| 35 | + new Error(`Timeout: file ${filePath} not found within ${timeout}ms`), |
| 36 | + ); |
| 37 | + }, timeout); |
| 38 | + |
| 39 | + fs.watchFile(filePath, {interval: 500}, curr => { |
| 40 | + if (curr.size > 0) { |
| 41 | + clearTimeout(timer); |
| 42 | + fs.unwatchFile(filePath); // Always clean up your listeners! |
| 43 | + resolve(); |
| 44 | + } |
| 45 | + }); |
| 46 | + }); |
| 47 | +} |
| 48 | + |
| 49 | +export async function startDaemon(mcpArgs: string[] = []) { |
| 50 | + if (isDaemonRunning()) { |
| 51 | + logger('Daemon is already running'); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + logger('Starting daemon...'); |
| 56 | + const child = spawn(process.execPath, [DAEMON_SCRIPT_PATH, ...mcpArgs], { |
| 57 | + detached: true, |
| 58 | + stdio: 'ignore', |
| 59 | + cwd: process.cwd(), |
| 60 | + }); |
| 61 | + |
| 62 | + await new Promise<void>((resolve, reject) => { |
| 63 | + child.on('error', err => { |
| 64 | + reject(err); |
| 65 | + }); |
| 66 | + child.on('exit', code => { |
| 67 | + logger(`Child exited with code ${code}`); |
| 68 | + reject(new Error(`Daemon process exited prematurely with code ${code}`)); |
| 69 | + }); |
| 70 | + |
| 71 | + waitForFile(getPidFilePath()).then(resolve).catch(reject); |
| 72 | + }); |
| 73 | + |
| 74 | + child.unref(); |
| 75 | + logger(`Pid file found ${getPidFilePath()}`); |
| 76 | +} |
| 77 | + |
| 78 | +const SEND_COMMAND_TIMEOUT = 60_000; // ms |
| 79 | + |
| 80 | +/** |
| 81 | + * `sendCommand` opens a socket connection sends a single command and disconnects. |
| 82 | + */ |
| 83 | +async function sendCommand(command: DaemonMessage) { |
| 84 | + const socketPath = getSocketPath(); |
| 85 | + |
| 86 | + const socket = net.createConnection({ |
| 87 | + path: socketPath, |
| 88 | + }); |
| 89 | + |
| 90 | + return new Promise((resolve, reject) => { |
| 91 | + const timer = setTimeout(() => { |
| 92 | + socket.destroy(); |
| 93 | + reject(new Error('Timeout waiting for daemon response')); |
| 94 | + }, SEND_COMMAND_TIMEOUT); |
| 95 | + |
| 96 | + const transport = new PipeTransport(socket, socket); |
| 97 | + transport.onmessage = async (message: string) => { |
| 98 | + clearTimeout(timer); |
| 99 | + logger('onmessage', message); |
| 100 | + resolve(JSON.parse(message)); |
| 101 | + }; |
| 102 | + socket.on('error', error => { |
| 103 | + clearTimeout(timer); |
| 104 | + logger('Socket error:', error); |
| 105 | + reject(error); |
| 106 | + }); |
| 107 | + socket.on('close', () => { |
| 108 | + clearTimeout(timer); |
| 109 | + logger('Socket closed:'); |
| 110 | + reject(new Error('Socket closed')); |
| 111 | + }); |
| 112 | + logger('Sending message', command); |
| 113 | + transport.send(JSON.stringify(command)); |
| 114 | + }); |
| 115 | +} |
| 116 | + |
| 117 | +export async function stopDaemon() { |
| 118 | + if (!isDaemonRunning()) { |
| 119 | + logger('Daemon is not running'); |
| 120 | + return; |
| 121 | + } |
| 122 | + |
| 123 | + await sendCommand({method: 'stop'}); |
| 124 | +} |
0 commit comments