mcp-gm 3.4.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.gitattributes +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +66 -0
  4. package/package.json +42 -0
  5. package/server.json +20 -0
  6. package/src/background-tasks.js +98 -0
  7. package/src/index.js +120 -0
  8. package/src/recovery-state.js +45 -0
  9. package/src/rpc-client.js +56 -0
  10. package/src/runner-supervisor.js +124 -0
  11. package/src/task-runner.js +132 -0
  12. package/src/tools/execute-code-isolated.js +20 -0
  13. package/src/tools/executor-tool-isolated.js +139 -0
  14. package/src/tools-registry.js +114 -0
  15. package/src/workers/isolation-worker.js +497 -0
  16. package/src/workers/worker-pool.js +277 -0
  17. package/tmp/playwriter-screenshot-1770021779355-69ck.jpg +0 -0
  18. package/tmp/playwriter-screenshot-1770021786127-r4n7.jpg +0 -0
  19. package/tmp/playwriter-screenshot-1770021792088-n22l.jpg +0 -0
  20. package/tmp/playwriter-screenshot-1770021798215-2c62.jpg +0 -0
  21. package/tmp/playwriter-screenshot-1770021809450-3w8m.jpg +0 -0
  22. package/tmp/playwriter-screenshot-1770021814006-9ydf.jpg +0 -0
  23. package/tmp/playwriter-screenshot-1770021819728-3ba8.jpg +0 -0
  24. package/tmp/playwriter-screenshot-1770021837236-jy89.jpg +0 -0
  25. package/tmp/playwriter-screenshot-1770021842582-ugtx.jpg +0 -0
  26. package/tmp/playwriter-screenshot-1770021867754-thcl.jpg +0 -0
  27. package/tmp/playwriter-screenshot-1770021873864-fpqk.jpg +0 -0
  28. package/tmp/playwriter-screenshot-1770021879378-3tqw.jpg +0 -0
  29. package/tmp/playwriter-screenshot-1770021897685-xwo4.jpg +0 -0
  30. package/tmp/playwriter-screenshot-1770021914159-gp06.jpg +0 -0
  31. package/tmp/playwriter-screenshot-1770021921332-new5.jpg +0 -0
  32. package/tmp/playwriter-screenshot-1770021931151-2i9a.jpg +0 -0
  33. package/tmp/playwriter-screenshot-1770021955223-fohh.jpg +0 -0
  34. package/tmp/playwriter-screenshot-1770021962887-trmf.jpg +0 -0
  35. package/tmp/playwriter-screenshot-1770021972452-sl2q.jpg +0 -0
  36. package/tmp/playwriter-screenshot-1770022222379-ympr.jpg +0 -0
  37. package/tmp/playwriter-screenshot-1770022254512-m8la.jpg +0 -0
  38. package/tmp/playwriter-screenshot-1770022263852-eenb.jpg +0 -0
package/.gitattributes ADDED
@@ -0,0 +1,10 @@
1
+ # Ensure Unix line endings for all text files
2
+ * text=auto eol=lf
3
+
4
+ # Source code
5
+ *.js text eol=lf
6
+ *.json text eol=lf
7
+ *.md text eol=lf
8
+
9
+ # Scripts should always have LF
10
+ *.sh text eol=lf
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AnEntrypoint
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # mcp-glootie
2
+
3
+ MCP server for executing code in JavaScript/TypeScript, Python, Go, Rust, C, C++, and Deno. Includes process management, recovery mechanisms, and automatic cleanup.
4
+
5
+ ## Quick Start
6
+
7
+ Just one command with Bun:
8
+
9
+ ```bash
10
+ bunx mcp-glootie
11
+ ```
12
+
13
+ That's it. Starts the MCP server immediately and connects to Claude Code or your MCP client.
14
+
15
+ ### For Development
16
+
17
+ Clone and run locally:
18
+
19
+ ```bash
20
+ git clone https://github.com/AnEntrypoint/mcp-glootie.git
21
+ cd mcp-glootie
22
+ bun install
23
+ bun run src/index.js
24
+ ```
25
+
26
+ ## Features
27
+
28
+ - Multi-language code execution (JS/TS, Python, Go, Rust, C, C++, Deno)
29
+ - Process management with backgrounding support
30
+ - Automatic error recovery
31
+ - Built-in cleanup and resource limits
32
+ - Stdin write capability for interactive processes
33
+ - Status checking for background processes
34
+
35
+ ## Tools Available
36
+
37
+ - `execute` - Run code in any supported language
38
+ - `bash` - Execute shell commands
39
+ - `process_status` - Check background process status
40
+ - `process_close` - Terminate a process
41
+ - `sleep` - Pause execution
42
+
43
+ ## Troubleshooting
44
+
45
+ ### Bun not installed
46
+
47
+ If you see `Bun is required but not installed`, install Bun:
48
+
49
+ ```bash
50
+ curl -fsSL https://bun.sh | bash
51
+ ```
52
+
53
+ Then run mcp-glootie again.
54
+
55
+ ### Port conflicts
56
+
57
+ If the server fails to start with a port error:
58
+
59
+ ```bash
60
+ # Find what's using the port
61
+ lsof -i :3001
62
+
63
+ # Kill it if needed
64
+ kill -9 <PID>
65
+ ```
66
+ # Triggered npm publishing
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "mcp-gm",
3
+ "version": "3.4.95",
4
+ "description": "MCP GM - Code execution tool for MCP clients. Multi-language support (JS/TS, Go, Rust, Python, C/C++, bash). Works with Claude Code, Cursor, Copilot, VSCode.",
5
+ "main": "src/index.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "mcp-gm": "src/index.js"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "scripts": {
14
+ "start": "bun run src/index.js",
15
+ "dev": "bun run src/index.js ./test"
16
+ },
17
+ "dependencies": {
18
+ "@modelcontextprotocol/sdk": "^1.18.2"
19
+ },
20
+ "engines": {
21
+ "bun": ">=1.0.0"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/AnEntrypoint/mcp-gm.git"
26
+ },
27
+ "keywords": [
28
+ "mcp",
29
+ "code-execution",
30
+ "javascript",
31
+ "typescript",
32
+ "go",
33
+ "rust",
34
+ "python",
35
+ "c",
36
+ "cpp",
37
+ "bash"
38
+ ],
39
+ "author": "",
40
+ "license": "MIT",
41
+ "mcpName": "io.github.AnEntrypoint/gm"
42
+ }
package/server.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-09-16/server.schema.json",
3
+ "name": "io.github.AnEntrypoint/glootie",
4
+ "description": "Code execution tool for MCP clients. JS/TS, Go, Rust, Python, C/C++, bash.",
5
+ "repository": {
6
+ "url": "https://github.com/AnEntrypoint/mcp-glootie",
7
+ "source": "github"
8
+ },
9
+ "version": "3.4.84",
10
+ "packages": [
11
+ {
12
+ "registryType": "npm",
13
+ "identifier": "mcp-glootie",
14
+ "version": "3.4.84",
15
+ "transport": {
16
+ "type": "stdio"
17
+ }
18
+ }
19
+ ]
20
+ }
@@ -0,0 +1,98 @@
1
+ export class BackgroundTaskStore {
2
+ constructor() {
3
+ this.tasks = new Map();
4
+ this.taskCounter = 0;
5
+ this.maxAge = 30 * 60 * 1000;
6
+ this.maxTasks = 1000;
7
+ this.maxOutputSize = 100 * 1024;
8
+ this.cleanupTimer = setInterval(() => this.cleanup(), 5 * 60 * 1000);
9
+ if (this.cleanupTimer.unref) this.cleanupTimer.unref();
10
+ }
11
+
12
+ cleanup() {
13
+ const now = Date.now();
14
+ for (const [id, task] of this.tasks) {
15
+ if ((task.status === 'completed' || task.status === 'failed') &&
16
+ task.completedAt && (now - task.completedAt > this.maxAge)) {
17
+ this.tasks.delete(id);
18
+ }
19
+ }
20
+ if (this.tasks.size > this.maxTasks) {
21
+ const expired = [...this.tasks.entries()]
22
+ .filter(([, t]) => t.status === 'completed' || t.status === 'failed')
23
+ .sort((a, b) => a[1].completedAt - b[1].completedAt);
24
+ for (const [id] of expired) {
25
+ this.tasks.delete(id);
26
+ if (this.tasks.size <= this.maxTasks) break;
27
+ }
28
+ }
29
+ }
30
+
31
+ shutdown() {
32
+ if (this.cleanupTimer) {
33
+ clearInterval(this.cleanupTimer);
34
+ this.cleanupTimer = null;
35
+ }
36
+ for (const [, task] of this.tasks) {
37
+ if (task.status === 'running' || task.status === 'pending') {
38
+ task.completedAt = Date.now();
39
+ task.result = { error: 'Process shutting down' };
40
+ task.status = 'failed';
41
+ }
42
+ }
43
+ }
44
+
45
+ createTask(code, runtime, workingDirectory) {
46
+ const taskId = ++this.taskCounter;
47
+ this.tasks.set(taskId, {
48
+ id: taskId, code, runtime, workingDirectory,
49
+ createdAt: Date.now(), startedAt: null,
50
+ completedAt: null, result: null, status: 'pending',
51
+ outputLog: []
52
+ });
53
+ return taskId;
54
+ }
55
+
56
+ startTask(taskId) {
57
+ const task = this.tasks.get(taskId);
58
+ if (task) { task.startedAt = Date.now(); task.status = 'running'; }
59
+ }
60
+
61
+ completeTask(taskId, result) {
62
+ const task = this.tasks.get(taskId);
63
+ if (task) { task.completedAt = Date.now(); task.result = result; task.status = 'completed'; }
64
+ }
65
+
66
+ failTask(taskId, error) {
67
+ const task = this.tasks.get(taskId);
68
+ if (task) { task.completedAt = Date.now(); task.result = { error: error.message }; task.status = 'failed'; }
69
+ }
70
+
71
+ appendOutput(taskId, type, data) {
72
+ const task = this.tasks.get(taskId);
73
+ if (!task || (task.status !== 'running' && task.status !== 'pending')) return;
74
+ const timestamp = Date.now();
75
+ task.outputLog.push({ t: timestamp, s: type, d: data });
76
+ const totalLen = task.outputLog.reduce((sum, e) => sum + e.d.length, 0);
77
+ if (totalLen > this.maxOutputSize) {
78
+ while (task.outputLog.length > 1 &&
79
+ task.outputLog.reduce((sum, e) => sum + e.d.length, 0) > this.maxOutputSize * 0.5) {
80
+ task.outputLog.shift();
81
+ }
82
+ }
83
+ }
84
+
85
+ getAndClearOutput(taskId) {
86
+ const task = this.tasks.get(taskId);
87
+ if (!task) return [];
88
+ const log = task.outputLog;
89
+ task.outputLog = [];
90
+ return log;
91
+ }
92
+
93
+ getTask(taskId) { return this.tasks.get(taskId); }
94
+ deleteTask(taskId) { this.tasks.delete(taskId); }
95
+ getAllTasks() { return Array.from(this.tasks.values()); }
96
+ }
97
+
98
+ export const backgroundStore = new BackgroundTaskStore();
package/src/index.js ADDED
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
6
+
7
+ (async () => {
8
+ const isRemoteUrl = import.meta.url.includes('raw.githubusercontent.com');
9
+ const baseUrl = isRemoteUrl
10
+ ? 'https://raw.githubusercontent.com/AnEntrypoint/mcp-glootie/main/src/'
11
+ : new URL('./', import.meta.url).pathname;
12
+
13
+ const { allTools } = await import(baseUrl + 'tools-registry.js');
14
+ const { recoveryState } = await import(baseUrl + 'recovery-state.js');
15
+ const { startRunner, stopRunner } = await import(baseUrl + 'runner-supervisor.js');
16
+
17
+ const server = new Server(
18
+ { name: 'glootie', version: '3.4.72', description: 'Code execution for programming agents' },
19
+ { capabilities: { tools: {} } }
20
+ );
21
+
22
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
23
+ try {
24
+ return { tools: allTools.map(t => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) };
25
+ } catch (error) {
26
+ console.error('[ListTools] Error:', error);
27
+ return { tools: [] };
28
+ }
29
+ });
30
+
31
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
32
+ try {
33
+ if (!request?.params?.name) {
34
+ return { content: [{ type: 'text', text: 'Invalid request parameters' }], isError: true };
35
+ }
36
+ const { name, arguments: args } = request.params;
37
+ const tool = allTools.find(t => t.name === name);
38
+ if (!tool) {
39
+ return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };
40
+ }
41
+ try {
42
+ return await tool.handler(args || {});
43
+ } catch (toolError) {
44
+ return { content: [{ type: 'text', text: `Tool error: ${toolError?.message || String(toolError)}` }], isError: true };
45
+ }
46
+ } catch (error) {
47
+ console.error('[CallTool] Error:', error);
48
+ return { content: [{ type: 'text', text: `Server error: ${error?.message || 'Unknown error'}` }], isError: true };
49
+ }
50
+ });
51
+
52
+ process.on('uncaughtException', (error) => {
53
+ try {
54
+ console.error('[UNCAUGHT_EXCEPTION]', { name: error?.name, message: error?.message, stack: error?.stack });
55
+ } catch (e) {
56
+ process.stderr.write(`Fatal error logging exception: ${e}\n`);
57
+ }
58
+ });
59
+
60
+ process.on('unhandledRejection', (reason) => {
61
+ try {
62
+ console.error('[UNHANDLED_REJECTION]', { reason: String(reason), type: typeof reason, stack: reason?.stack });
63
+ } catch (e) {
64
+ process.stderr.write(`Fatal error logging rejection: ${e}\n`);
65
+ }
66
+ });
67
+
68
+ process.on('warning', (warning) => {
69
+ try { console.error('[WARNING]', warning.name, warning.message); } catch (e) {}
70
+ });
71
+
72
+ process.on('exit', (code) => {
73
+ try { console.error(`[EXIT] Process exiting with code ${code}`); } catch (e) {}
74
+ });
75
+
76
+ let shuttingDown = false;
77
+ let backoffTimer = null;
78
+
79
+ async function gracefulShutdown(signal) {
80
+ if (shuttingDown) return;
81
+ shuttingDown = true;
82
+ try {
83
+ console.error(`[${signal}] Shutting down gracefully`);
84
+ if (backoffTimer) { clearTimeout(backoffTimer); backoffTimer = null; }
85
+ await stopRunner();
86
+ process.exit(0);
87
+ } catch (e) {
88
+ try { await stopRunner(); } catch (_) {}
89
+ process.exit(1);
90
+ }
91
+ }
92
+
93
+ process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
94
+ process.on('SIGINT', () => gracefulShutdown('SIGINT'));
95
+ process.on('SIGHUP', () => gracefulShutdown('SIGHUP'));
96
+
97
+ async function startupWithRecovery() {
98
+ await startRunner();
99
+ while (recoveryState.canRetry()) {
100
+ try {
101
+ const transport = new StdioServerTransport();
102
+ await server.connect(transport);
103
+ recoveryState.recordSuccess();
104
+ console.error('[STARTUP] Connected successfully');
105
+ return;
106
+ } catch (error) {
107
+ recoveryState.recordStartupAttempt(error);
108
+ const delay = recoveryState.getBackoffDelay();
109
+ console.error(`[STARTUP] Attempt ${recoveryState.startupAttempts} failed: ${error?.message || String(error)}. Retrying in ${delay}ms...`);
110
+ await new Promise(resolve => { backoffTimer = setTimeout(resolve, delay); });
111
+ backoffTimer = null;
112
+ }
113
+ }
114
+ console.error(`[STARTUP] Failed after ${recoveryState.maxStartupAttempts} attempts. Last error: ${recoveryState.lastError}`);
115
+ }
116
+
117
+ startupWithRecovery().catch(error => {
118
+ console.error('[STARTUP] Unhandled error during recovery:', error);
119
+ });
120
+ })();
@@ -0,0 +1,45 @@
1
+ const MAX_BUFFER = 10 * 1024 * 1024;
2
+
3
+ export const recoveryState = {
4
+ startupAttempts: 0,
5
+ maxStartupAttempts: 5,
6
+ backoffDelayMs: 1000,
7
+ lastError: null,
8
+ connected: false,
9
+
10
+ recordStartupAttempt(error) {
11
+ this.startupAttempts += 1;
12
+ this.lastError = error?.message || String(error);
13
+ this.connected = false;
14
+ },
15
+
16
+ recordSuccess() {
17
+ this.startupAttempts = 0;
18
+ this.lastError = null;
19
+ this.connected = true;
20
+ },
21
+
22
+ canRetry() {
23
+ return this.startupAttempts < this.maxStartupAttempts;
24
+ },
25
+
26
+ getBackoffDelay() {
27
+ return Math.min(this.backoffDelayMs * Math.pow(2, this.startupAttempts - 1), 30000);
28
+ },
29
+
30
+ shouldTrimBuffer(bufferSize) {
31
+ return bufferSize > MAX_BUFFER;
32
+ },
33
+
34
+ trimBuffer(bufferString) {
35
+ if (bufferString.length <= MAX_BUFFER) return bufferString;
36
+ const keepSize = Math.ceil(MAX_BUFFER * 0.5);
37
+ return bufferString.slice(-keepSize);
38
+ },
39
+
40
+ reset() {
41
+ this.startupAttempts = 0;
42
+ this.lastError = null;
43
+ this.connected = false;
44
+ }
45
+ };
@@ -0,0 +1,56 @@
1
+ import http from 'http';
2
+ import { readFileSync } from 'fs';
3
+
4
+ function getPort() {
5
+ try {
6
+ return parseInt(readFileSync('/tmp/glootie-runner.port', 'utf8').trim(), 10);
7
+ } catch {
8
+ throw new Error('task runner not available');
9
+ }
10
+ }
11
+
12
+ function rpcCall(method, params, timeoutMs = 10000) {
13
+ return new Promise((resolve, reject) => {
14
+ const port = getPort();
15
+ const body = JSON.stringify({ method, params });
16
+ const req = http.request(
17
+ { hostname: '127.0.0.1', port, path: '/rpc', method: 'POST',
18
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
19
+ (res) => {
20
+ let data = '';
21
+ res.on('data', chunk => { data += chunk; });
22
+ res.on('end', () => {
23
+ if (res.statusCode !== 200) return reject(new Error(`task runner HTTP ${res.statusCode}: ${data}`));
24
+ try {
25
+ const parsed = JSON.parse(data);
26
+ if (parsed.error) return reject(new Error(parsed.error));
27
+ resolve(parsed.result);
28
+ } catch {
29
+ reject(new Error(`task runner invalid response: ${data}`));
30
+ }
31
+ });
32
+ }
33
+ );
34
+ const timer = setTimeout(() => { req.destroy(); reject(new Error('task runner request timed out')); }, timeoutMs);
35
+ req.on('error', (e) => { clearTimeout(timer); reject(new Error(`task runner not available: ${e.message}`)); });
36
+ req.on('close', () => clearTimeout(timer));
37
+ req.write(body);
38
+ req.end();
39
+ });
40
+ }
41
+
42
+ export async function executeCode(code, runtime, workingDirectory, timeout = 30000, backgroundTaskId = null) {
43
+ const r = await rpcCall('execute', { code, runtime, workingDirectory, timeout, backgroundTaskId }, timeout + 5000);
44
+ return r?.result ?? r;
45
+ }
46
+
47
+ export const backgroundStore = {
48
+ createTask: (code, runtime, workingDirectory) => rpcCall('createTask', { code, runtime, workingDirectory }).then(r => r?.taskId ?? r),
49
+ startTask: (taskId) => rpcCall('startTask', { taskId }),
50
+ completeTask: (taskId, result) => rpcCall('completeTask', { taskId, result }),
51
+ failTask: (taskId, error) => rpcCall('failTask', { taskId, error }),
52
+ getTask: (taskId) => rpcCall('getTask', { taskId }).then(r => r?.task ?? r),
53
+ deleteTask: (taskId) => rpcCall('deleteTask', { taskId }),
54
+ appendOutput: (taskId, type, data) => rpcCall('appendOutput', { taskId, type, data }),
55
+ getAndClearOutput: (taskId) => rpcCall('getAndClearOutput', { taskId }).then(r => r?.output ?? r),
56
+ };
@@ -0,0 +1,124 @@
1
+ import { spawn } from 'child_process';
2
+ import http from 'http';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
8
+ const RUNNER_PATH = path.join(__dirname, 'task-runner.js');
9
+
10
+ const PORT_FILE = '/tmp/glootie-runner.port';
11
+ const MAX_RESTARTS = 10;
12
+ const RESTART_WINDOW_MS = 5 * 60 * 1000;
13
+
14
+ let runnerProcess = null;
15
+ let healthPollInterval = null;
16
+ let healthy = false;
17
+ let consecutiveFailures = 0;
18
+ let restartTimestamps = [];
19
+
20
+ function getPort() {
21
+ try {
22
+ const val = fs.readFileSync(PORT_FILE, 'utf8').trim();
23
+ const n = Number(val);
24
+ return isNaN(n) ? null : n;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ function healthCheck(port) {
31
+ return new Promise((resolve) => {
32
+ const req = http.get({ hostname: '127.0.0.1', port, path: '/health', timeout: 3000 }, (res) => {
33
+ resolve(res.statusCode === 200);
34
+ });
35
+ req.on('error', () => resolve(false));
36
+ req.on('timeout', () => { req.destroy(); resolve(false); });
37
+ });
38
+ }
39
+
40
+ function withinWindow() {
41
+ const now = Date.now();
42
+ restartTimestamps = restartTimestamps.filter(t => now - t < RESTART_WINDOW_MS);
43
+ return restartTimestamps.length;
44
+ }
45
+
46
+ async function startRunner() {
47
+ try { fs.unlinkSync(PORT_FILE); } catch {}
48
+
49
+ runnerProcess = spawn('node', [RUNNER_PATH], {
50
+ env: process.env,
51
+ stdio: ['ignore', 'inherit', 'inherit']
52
+ });
53
+
54
+ runnerProcess.on('exit', (code) => {
55
+ healthy = false;
56
+ runnerProcess = null;
57
+ const count = withinWindow();
58
+ if (count >= MAX_RESTARTS) {
59
+ console.error('[runner-supervisor] max restarts exceeded, stopping');
60
+ return;
61
+ }
62
+ const delay = Math.min(1000 * Math.pow(2, count), 30000);
63
+ restartTimestamps.push(Date.now());
64
+ setTimeout(() => startRunner().catch(e => console.error('[runner-supervisor] restart failed', e)), delay);
65
+ });
66
+
67
+ const deadline = Date.now() + 10000;
68
+ while (Date.now() < deadline) {
69
+ await new Promise(r => setTimeout(r, 200));
70
+ const port = getPort();
71
+ if (port && await healthCheck(port)) {
72
+ healthy = true;
73
+ consecutiveFailures = 0;
74
+ startHealthPoll();
75
+ return;
76
+ }
77
+ }
78
+ throw new Error('runner did not become healthy within 10s');
79
+ }
80
+
81
+ function startHealthPoll() {
82
+ if (healthPollInterval) clearInterval(healthPollInterval);
83
+ healthPollInterval = setInterval(async () => {
84
+ const port = getPort();
85
+ const ok = port ? await healthCheck(port) : false;
86
+ if (ok) {
87
+ healthy = true;
88
+ consecutiveFailures = 0;
89
+ } else {
90
+ consecutiveFailures++;
91
+ if (consecutiveFailures >= 3) {
92
+ healthy = false;
93
+ const count = withinWindow();
94
+ if (count >= MAX_RESTARTS) {
95
+ console.error('[runner-supervisor] max restarts exceeded');
96
+ clearInterval(healthPollInterval);
97
+ healthPollInterval = null;
98
+ return;
99
+ }
100
+ restartTimestamps.push(Date.now());
101
+ const delay = Math.min(1000 * Math.pow(2, count), 30000);
102
+ await stopRunner();
103
+ setTimeout(() => startRunner().catch(e => console.error('[runner-supervisor] restart failed', e)), delay);
104
+ }
105
+ }
106
+ }, 5000);
107
+ }
108
+
109
+ async function stopRunner() {
110
+ if (healthPollInterval) { clearInterval(healthPollInterval); healthPollInterval = null; }
111
+ if (!runnerProcess) return;
112
+ const proc = runnerProcess;
113
+ return new Promise((resolve) => {
114
+ const kill = setTimeout(() => { proc.kill('SIGKILL'); }, 3000);
115
+ proc.on('exit', () => { clearTimeout(kill); resolve(); });
116
+ proc.kill('SIGTERM');
117
+ });
118
+ }
119
+
120
+ function isRunnerHealthy() {
121
+ return healthy;
122
+ }
123
+
124
+ export { startRunner, stopRunner, isRunnerHealthy };