-
Notifications
You must be signed in to change notification settings - Fork 2.3k
chore: implement daemon client #1037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import {spawn} from 'node:child_process'; | ||
| import fs from 'node:fs'; | ||
| import net from 'node:net'; | ||
|
|
||
| import {logger} from '../logger.js'; | ||
| import {PipeTransport} from '../third_party/index.js'; | ||
|
|
||
| import type {DaemonMessage} from './types.js'; | ||
| import { | ||
| DAEMON_SCRIPT_PATH, | ||
| getSocketPath, | ||
| getPidFilePath, | ||
| isDaemonRunning, | ||
| } from './utils.js'; | ||
|
|
||
| /** | ||
| * Waits for a file to be created and populated. | ||
| */ | ||
| function waitForFile(filePath: string, timeout = 5000) { | ||
| return new Promise<void>((resolve, reject) => { | ||
| if (fs.existsSync(filePath) && fs.statSync(filePath).size > 0) { | ||
| resolve(); | ||
| return; | ||
| } | ||
|
|
||
| const timer = setTimeout(() => { | ||
| fs.unwatchFile(filePath); | ||
| reject( | ||
| new Error(`Timeout: file ${filePath} not found within ${timeout}ms`), | ||
| ); | ||
| }, timeout); | ||
|
|
||
| fs.watchFile(filePath, {interval: 500}, curr => { | ||
| if (curr.size > 0) { | ||
| clearTimeout(timer); | ||
| fs.unwatchFile(filePath); // Always clean up your listeners! | ||
| resolve(); | ||
| } | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| export async function startDaemon(mcpArgs: string[] = []) { | ||
| if (isDaemonRunning()) { | ||
| logger('Daemon is already running'); | ||
| return; | ||
| } | ||
|
|
||
| logger('Starting daemon...'); | ||
| const child = spawn(process.execPath, [DAEMON_SCRIPT_PATH, ...mcpArgs], { | ||
|
OrKoN marked this conversation as resolved.
|
||
| detached: true, | ||
| stdio: 'ignore', | ||
| cwd: process.cwd(), | ||
| }); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| child.on('error', err => { | ||
| reject(err); | ||
| }); | ||
| child.on('exit', code => { | ||
| logger(`Child exited with code ${code}`); | ||
| reject(new Error(`Daemon process exited prematurely with code ${code}`)); | ||
| }); | ||
|
|
||
| waitForFile(getPidFilePath()).then(resolve).catch(reject); | ||
| }); | ||
|
|
||
| child.unref(); | ||
| logger(`Pid file found ${getPidFilePath()}`); | ||
| } | ||
|
|
||
| const SEND_COMMAND_TIMEOUT = 60_000; // ms | ||
|
|
||
| /** | ||
| * `sendCommand` opens a socket connection sends a single command and disconnects. | ||
| */ | ||
| async function sendCommand(command: DaemonMessage) { | ||
| const socketPath = getSocketPath(); | ||
|
|
||
| const socket = net.createConnection({ | ||
| path: socketPath, | ||
| }); | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| const timer = setTimeout(() => { | ||
| socket.destroy(); | ||
| reject(new Error('Timeout waiting for daemon response')); | ||
| }, SEND_COMMAND_TIMEOUT); | ||
|
|
||
| const transport = new PipeTransport(socket, socket); | ||
| transport.onmessage = async (message: string) => { | ||
| clearTimeout(timer); | ||
| logger('onmessage', message); | ||
| resolve(JSON.parse(message)); | ||
| }; | ||
| socket.on('error', error => { | ||
|
OrKoN marked this conversation as resolved.
|
||
| clearTimeout(timer); | ||
| logger('Socket error:', error); | ||
| reject(error); | ||
| }); | ||
| socket.on('close', () => { | ||
| clearTimeout(timer); | ||
| logger('Socket closed:'); | ||
| reject(new Error('Socket closed')); | ||
| }); | ||
| logger('Sending message', command); | ||
| transport.send(JSON.stringify(command)); | ||
| }); | ||
| } | ||
|
|
||
| export async function stopDaemon() { | ||
| if (!isDaemonRunning()) { | ||
| logger('Daemon is not running'); | ||
| return; | ||
| } | ||
|
|
||
| await sendCommand({method: 'stop'}); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| export type DaemonMessage = | ||
| | { | ||
| method: 'stop'; | ||
| } | ||
| | { | ||
| method: 'invoke_tool'; | ||
| tool: string; | ||
| args?: Record<string, unknown>; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import assert from 'node:assert'; | ||
| import {describe, it, afterEach} from 'node:test'; | ||
|
|
||
| import {startDaemon, stopDaemon} from '../../src/daemon/client.js'; | ||
| import {isDaemonRunning} from '../../src/daemon/utils.js'; | ||
|
|
||
| describe('daemon client', () => { | ||
| afterEach(async () => { | ||
| if (isDaemonRunning()) { | ||
| await stopDaemon(); | ||
| // Wait a bit for the daemon to fully terminate and clean up its files. | ||
| await new Promise(resolve => setTimeout(resolve, 1000)); | ||
| } | ||
| }); | ||
|
|
||
| it('should start and stop daemon', async () => { | ||
| assert.ok(!isDaemonRunning(), 'Daemon should not be running initially'); | ||
|
|
||
| await startDaemon(); | ||
| assert.ok(isDaemonRunning(), 'Daemon should be running after start'); | ||
|
|
||
| await stopDaemon(); | ||
| await new Promise(resolve => setTimeout(resolve, 1000)); | ||
| assert.ok(!isDaemonRunning(), 'Daemon should not be running after stop'); | ||
| }); | ||
|
|
||
| it('should handle starting daemon when already running', async () => { | ||
| await startDaemon(); | ||
| assert.ok(isDaemonRunning(), 'Daemon should be running'); | ||
|
|
||
| // Starting again should be a no-op | ||
| await startDaemon(); | ||
| assert.ok(isDaemonRunning(), 'Daemon should still be running'); | ||
| }); | ||
|
|
||
| it('should handle stopping daemon when not running', async () => { | ||
| assert.ok(!isDaemonRunning(), 'Daemon should not be running initially'); | ||
|
|
||
| // Stopping when not running should be a no-op | ||
| await stopDaemon(); | ||
| assert.ok(!isDaemonRunning(), 'Daemon should still not be running'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.