@1xops/command-center 0.4.0
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.
Potentially problematic release.
This version of @1xops/command-center might be problematic. Click here for more details.
- package/LICENSE +191 -0
- package/README.md +141 -0
- package/dist/config.js +126 -0
- package/dist/files.js +200 -0
- package/dist/index.js +66 -0
- package/dist/log.js +5 -0
- package/dist/policy.js +141 -0
- package/dist/processes.js +206 -0
- package/dist/search-worker.js +14 -0
- package/dist/search.js +339 -0
- package/dist/server.js +296 -0
- package/dist/system.js +71 -0
- package/dist/version.js +5 -0
- package/icon.png +0 -0
- package/package.json +59 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { loadConfig, setLaunchDirectories } from './config.js';
|
|
5
|
+
import { log } from './log.js';
|
|
6
|
+
import { stopAll as stopSessions } from './processes.js';
|
|
7
|
+
import { stopAllSearches } from './search.js';
|
|
8
|
+
import { createServer } from './server.js';
|
|
9
|
+
import { VERSION } from './version.js';
|
|
10
|
+
/** Stops every session and background search; safe to call more than once. */
|
|
11
|
+
function stopAll() {
|
|
12
|
+
stopSessions();
|
|
13
|
+
stopAllSearches();
|
|
14
|
+
}
|
|
15
|
+
const USAGE = `Usage: command-center [folder ...]
|
|
16
|
+
|
|
17
|
+
Runs the 1xOps Command Center MCP server on stdio.
|
|
18
|
+
Folders given here become allowedDirectories for this session, overriding the config file
|
|
19
|
+
(~/.command-center/config.json). With none, the config file decides.
|
|
20
|
+
|
|
21
|
+
--version print the version
|
|
22
|
+
--help print this help`;
|
|
23
|
+
async function main() {
|
|
24
|
+
const args = process.argv.slice(2);
|
|
25
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
26
|
+
process.stdout.write(`${USAGE}\n`);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (args.includes('--version')) {
|
|
30
|
+
process.stdout.write(`${VERSION}\n`);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const unknown = args.filter((a) => a.startsWith('-'));
|
|
34
|
+
if (unknown.length)
|
|
35
|
+
throw new Error(`unknown option ${unknown.join(' ')}\n${USAGE}`);
|
|
36
|
+
for (const dir of args)
|
|
37
|
+
if (!existsSync(dir))
|
|
38
|
+
log('warn', `launch folder ${dir} does not exist yet`);
|
|
39
|
+
await loadConfig();
|
|
40
|
+
setLaunchDirectories(args);
|
|
41
|
+
const server = createServer();
|
|
42
|
+
const transport = new StdioServerTransport();
|
|
43
|
+
let closing = false;
|
|
44
|
+
const shutdown = async (reason) => {
|
|
45
|
+
if (closing)
|
|
46
|
+
return;
|
|
47
|
+
closing = true;
|
|
48
|
+
log('info', `shutting down (${reason})`);
|
|
49
|
+
stopAll();
|
|
50
|
+
await server.close().catch(() => undefined);
|
|
51
|
+
process.exit(0);
|
|
52
|
+
};
|
|
53
|
+
// Sessions run in their own process groups, so they must be stopped on every way out.
|
|
54
|
+
process.on('exit', stopAll);
|
|
55
|
+
process.on('SIGINT', () => void shutdown('SIGINT'));
|
|
56
|
+
process.on('SIGTERM', () => void shutdown('SIGTERM'));
|
|
57
|
+
// The client closing stdin is the normal end of a stdio session.
|
|
58
|
+
process.stdin.on('end', () => void shutdown('client closed stdin'));
|
|
59
|
+
await server.connect(transport);
|
|
60
|
+
log('info', `version ${VERSION} ready on stdio`);
|
|
61
|
+
}
|
|
62
|
+
main().catch((error) => {
|
|
63
|
+
log('error', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
|
64
|
+
stopAll();
|
|
65
|
+
process.exit(1);
|
|
66
|
+
});
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// stdout carries JSON-RPC only (MCP stdio transport). Every diagnostic goes to stderr,
|
|
2
|
+
// which MCP clients capture as the server log.
|
|
3
|
+
export function log(level, message) {
|
|
4
|
+
process.stderr.write(`${new Date().toISOString()} command-center ${level}: ${message}\n`);
|
|
5
|
+
}
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { lstat, readlink, realpath } from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { allowedDirectoriesSource, configDir, configPath, getConfig } from './config.js';
|
|
5
|
+
const CASE_INSENSITIVE_FS = process.platform === 'darwin' || process.platform === 'win32';
|
|
6
|
+
const MAX_LINK_HOPS = 40;
|
|
7
|
+
export function expandHome(p) {
|
|
8
|
+
if (p === '~')
|
|
9
|
+
return os.homedir();
|
|
10
|
+
if (p.startsWith('~/') || p.startsWith('~\\'))
|
|
11
|
+
return path.join(os.homedir(), p.slice(2));
|
|
12
|
+
return p;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Where file operations on `absolute` actually land, even when the path does not exist yet.
|
|
16
|
+
* Existing parts are resolved with realpath. A missing part that is a dangling symlink is
|
|
17
|
+
* followed to its target (a write through it would create the target), up to MAX_LINK_HOPS.
|
|
18
|
+
* The still-missing tail is appended to the resolved existing part.
|
|
19
|
+
*/
|
|
20
|
+
async function resolveReal(absolute, hops = 0) {
|
|
21
|
+
if (hops > MAX_LINK_HOPS)
|
|
22
|
+
throw new Error(`too many symbolic links resolving ${absolute}`);
|
|
23
|
+
const missing = [];
|
|
24
|
+
let probe = absolute;
|
|
25
|
+
for (;;) {
|
|
26
|
+
try {
|
|
27
|
+
const real = await realpath(probe);
|
|
28
|
+
return missing.length ? path.join(real, ...missing.reverse()) : real;
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
const code = error.code;
|
|
32
|
+
if (code !== 'ENOENT' && code !== 'ENOTDIR')
|
|
33
|
+
throw error;
|
|
34
|
+
const link = await lstat(probe).then((s) => s.isSymbolicLink(), () => false);
|
|
35
|
+
if (link) {
|
|
36
|
+
const target = path.resolve(path.dirname(probe), await readlink(probe));
|
|
37
|
+
return resolveReal(missing.length ? path.join(target, ...[...missing].reverse()) : target, hops + 1);
|
|
38
|
+
}
|
|
39
|
+
const parent = path.dirname(probe);
|
|
40
|
+
if (parent === probe)
|
|
41
|
+
return absolute;
|
|
42
|
+
missing.push(path.basename(probe));
|
|
43
|
+
probe = parent;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function isInside(child, parent) {
|
|
48
|
+
const [c, p] = CASE_INSENSITIVE_FS ? [child.toLowerCase(), parent.toLowerCase()] : [child, parent];
|
|
49
|
+
const rel = path.relative(p, c);
|
|
50
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Returns the canonical (symlink-resolved) path when it is inside `allowedDirectories`.
|
|
54
|
+
* An empty list allows the whole filesystem, as documented. The config folder is always
|
|
55
|
+
* refused: an agent must not edit its own limits with the file tools.
|
|
56
|
+
*/
|
|
57
|
+
export async function validatePath(requested) {
|
|
58
|
+
if (!requested || requested.includes('\0'))
|
|
59
|
+
throw new Error('path is empty or contains a NUL byte');
|
|
60
|
+
const absolute = path.resolve(expandHome(requested));
|
|
61
|
+
const real = await resolveReal(absolute);
|
|
62
|
+
if (isInside(real, await resolveReal(path.resolve(configDir())))) {
|
|
63
|
+
throw new Error(`refused: ${requested} is in the Command Center settings folder; only a person can change ${configPath()}`);
|
|
64
|
+
}
|
|
65
|
+
const allowed = getConfig().allowedDirectories;
|
|
66
|
+
if (allowed.length === 0)
|
|
67
|
+
return real;
|
|
68
|
+
for (const dir of allowed) {
|
|
69
|
+
if (isInside(real, await resolveReal(path.resolve(expandHome(dir)))))
|
|
70
|
+
return real;
|
|
71
|
+
}
|
|
72
|
+
throw new Error(`refused: ${requested} is outside allowedDirectories (${allowed.join(', ')}). ` +
|
|
73
|
+
`allowedDirectories is set in ${allowedDirectoriesSource()}; only a person can change it.`);
|
|
74
|
+
}
|
|
75
|
+
/** Shells: a command that starts one gets its later input checked as command lines too. */
|
|
76
|
+
export const SHELLS = new Set([
|
|
77
|
+
'sh', 'bash', 'zsh', 'dash', 'ksh', 'fish', 'csh', 'tcsh', 'nu', 'xonsh', 'script',
|
|
78
|
+
'powershell', 'pwsh', 'cmd',
|
|
79
|
+
]);
|
|
80
|
+
// Words that run a later word as the command: POSIX wrappers, shells given a command, and
|
|
81
|
+
// their Windows equivalents. After one of these, every later word is checked.
|
|
82
|
+
const PREFIX_WORDS = new Set([
|
|
83
|
+
'exec', 'command', 'builtin', 'env', 'nohup', 'time', 'nice', 'xargs', 'stdbuf', 'timeout', 'doas',
|
|
84
|
+
...SHELLS, 'start', 'start-process', 'call',
|
|
85
|
+
]);
|
|
86
|
+
// Shell grammar words that may precede the command in a simple command.
|
|
87
|
+
const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{', '}', 'fi', 'done', 'case', 'esac', 'in', 'function']);
|
|
88
|
+
// Words whose argument is itself a command line the check cannot see into. (`source` and `.`
|
|
89
|
+
// run a file; files are not inspected, as documented, so they are not refused here.)
|
|
90
|
+
const OPAQUE_WORDS = new Set(['eval', 'invoke-expression', 'iex']);
|
|
91
|
+
/**
|
|
92
|
+
* The program a word names, compared case-insensitively and without a Windows executable
|
|
93
|
+
* extension, so `/usr/bin/sudo`, `C:\Windows\System32\DISKPART.EXE` and `diskpart` all match.
|
|
94
|
+
*/
|
|
95
|
+
export function programName(word) {
|
|
96
|
+
const unquoted = word.replace(/^['"&]+|['"]+$/g, '');
|
|
97
|
+
const base = unquoted.split(/[\\/]/).pop() ?? unquoted;
|
|
98
|
+
return base.toLowerCase().replace(/\.(exe|cmd|bat|com|ps1)$/, '');
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Guardrail, not a sandbox (see SECURITY.md). The command line is split into simple commands
|
|
102
|
+
* on ; & | newline $( ( ) and backticks. In each, leading assignments and shell keywords are
|
|
103
|
+
* skipped and the program name is compared with blockedCommands; after a wrapper word (env,
|
|
104
|
+
* timeout, sh -c, cmd /c, ...) every later word is compared too. A program reached any other
|
|
105
|
+
* way (a script file, another interpreter, a string built at runtime) is not seen.
|
|
106
|
+
* Returns the program names it found, so callers can tell when a command starts a shell.
|
|
107
|
+
*/
|
|
108
|
+
export function checkCommand(commandLine) {
|
|
109
|
+
const blocked = new Set(getConfig().blockedCommands.map((c) => c.toLowerCase()));
|
|
110
|
+
const refuse = (name) => {
|
|
111
|
+
if (OPAQUE_WORDS.has(name))
|
|
112
|
+
throw new Error(`refused: \`${name}\` runs text the command check cannot read; run the command directly`);
|
|
113
|
+
if (blocked.has(name))
|
|
114
|
+
throw new Error(`refused: \`${name}\` is in blockedCommands. A person can change blockedCommands in ${configPath()}.`);
|
|
115
|
+
};
|
|
116
|
+
const programs = [];
|
|
117
|
+
for (const segment of commandLine.split(/;|&&?|\|\|?|\n|\$\(|`|\(|\)/)) {
|
|
118
|
+
const words = segment.trim().split(/\s+/).filter(Boolean);
|
|
119
|
+
let i = 0;
|
|
120
|
+
while (i < words.length && (KEYWORDS.has(words[i] ?? '') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i] ?? '')))
|
|
121
|
+
i++;
|
|
122
|
+
const first = words[i];
|
|
123
|
+
if (!first)
|
|
124
|
+
continue;
|
|
125
|
+
const name = programName(first);
|
|
126
|
+
programs.push(name);
|
|
127
|
+
refuse(name);
|
|
128
|
+
if (PREFIX_WORDS.has(name)) {
|
|
129
|
+
// Wrapper flags and their values are not reliably told apart from the command they run
|
|
130
|
+
// (`timeout -s KILL 5 sudo`), so every later non-flag word is checked as a program.
|
|
131
|
+
for (const word of words.slice(i + 1)) {
|
|
132
|
+
if (/^(-|\/[a-z]$)/i.test(word))
|
|
133
|
+
continue;
|
|
134
|
+
const later = programName(word);
|
|
135
|
+
programs.push(later);
|
|
136
|
+
refuse(later);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return programs;
|
|
141
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { getConfig } from './config.js';
|
|
3
|
+
import { log } from './log.js';
|
|
4
|
+
import { checkCommand, programName, SHELLS, validatePath } from './policy.js';
|
|
5
|
+
const MAX_BUFFER = 1024 * 1024; // keep the last 1 MiB of output per session
|
|
6
|
+
const MAX_SESSIONS = 50;
|
|
7
|
+
const IDLE_MS = 400; // output is "settled" after this long without new bytes
|
|
8
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
9
|
+
const PS_EXIT = 'if (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }';
|
|
10
|
+
/** How each shell is told to run one command line. */
|
|
11
|
+
export function shellArgs(shell, command) {
|
|
12
|
+
const name = programName(shell);
|
|
13
|
+
// Windows PowerShell 5.1 ends -Command with exit code 1 for any failure, hiding a program's
|
|
14
|
+
// own code; this line after the command passes the real code on (pwsh 7 behaves the same way).
|
|
15
|
+
if (name === 'powershell' || name === 'pwsh')
|
|
16
|
+
return ['-NoLogo', '-NoProfile', '-Command', `${command}\n${PS_EXIT}`];
|
|
17
|
+
// With /s, cmd strips the first and last quote of the line, so the whole line is wrapped in
|
|
18
|
+
// quotes (as Node does for shell: true) and arguments are passed verbatim.
|
|
19
|
+
if (name === 'cmd')
|
|
20
|
+
return ['/d', '/s', '/c', `"${command}"`];
|
|
21
|
+
return ['-c', command];
|
|
22
|
+
}
|
|
23
|
+
const sessions = new Map();
|
|
24
|
+
function notify(session) {
|
|
25
|
+
for (const listener of session.listeners)
|
|
26
|
+
listener();
|
|
27
|
+
}
|
|
28
|
+
function append(session, chunk) {
|
|
29
|
+
session.output += chunk;
|
|
30
|
+
// Trim in steps (not on every chunk) and never between the halves of a surrogate pair.
|
|
31
|
+
if (session.output.length > MAX_BUFFER * 1.25) {
|
|
32
|
+
let cut = session.output.length - MAX_BUFFER;
|
|
33
|
+
const code = session.output.charCodeAt(cut);
|
|
34
|
+
if (code >= 0xdc00 && code <= 0xdfff)
|
|
35
|
+
cut++;
|
|
36
|
+
session.output = session.output.slice(cut);
|
|
37
|
+
session.dropped += cut;
|
|
38
|
+
}
|
|
39
|
+
notify(session);
|
|
40
|
+
}
|
|
41
|
+
function prune() {
|
|
42
|
+
if (sessions.size < MAX_SESSIONS)
|
|
43
|
+
return;
|
|
44
|
+
const finished = [...sessions.values()].filter((s) => s.exited).sort((a, b) => a.startedAt - b.startedAt);
|
|
45
|
+
for (const s of finished.slice(0, sessions.size - MAX_SESSIONS + 1))
|
|
46
|
+
sessions.delete(s.pid);
|
|
47
|
+
if (sessions.size >= MAX_SESSIONS)
|
|
48
|
+
throw new Error(`${MAX_SESSIONS} sessions are running; stop one with force_terminate first`);
|
|
49
|
+
}
|
|
50
|
+
/** Waits until the process exits, its output has been idle for IDLE_MS, or the timeout passes. */
|
|
51
|
+
function settle(session, timeoutMs) {
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
if (session.exited || timeoutMs <= 0)
|
|
54
|
+
return resolve();
|
|
55
|
+
let idle;
|
|
56
|
+
const finish = () => {
|
|
57
|
+
clearTimeout(deadline);
|
|
58
|
+
clearTimeout(idle);
|
|
59
|
+
session.listeners.delete(onChange);
|
|
60
|
+
resolve();
|
|
61
|
+
};
|
|
62
|
+
const onChange = () => {
|
|
63
|
+
if (session.exited)
|
|
64
|
+
return finish();
|
|
65
|
+
clearTimeout(idle);
|
|
66
|
+
idle = setTimeout(finish, IDLE_MS);
|
|
67
|
+
};
|
|
68
|
+
const deadline = setTimeout(finish, timeoutMs);
|
|
69
|
+
session.listeners.add(onChange);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function take(session) {
|
|
73
|
+
const start = Math.max(session.cursor - session.dropped, 0);
|
|
74
|
+
const truncated = session.cursor < session.dropped;
|
|
75
|
+
const output = session.output.slice(start);
|
|
76
|
+
session.cursor = session.dropped + session.output.length;
|
|
77
|
+
return { pid: session.pid, output, running: !session.exited, exitCode: session.exitCode, truncated };
|
|
78
|
+
}
|
|
79
|
+
function get(pid) {
|
|
80
|
+
const session = sessions.get(pid);
|
|
81
|
+
if (!session)
|
|
82
|
+
throw new Error(`no session with pid ${pid}; list_sessions shows the live ones`);
|
|
83
|
+
return session;
|
|
84
|
+
}
|
|
85
|
+
export async function startProcess(command, timeoutMs, cwd) {
|
|
86
|
+
const programs = checkCommand(command);
|
|
87
|
+
prune();
|
|
88
|
+
// Without a cwd, start in the first allowed folder (Claude Desktop starts servers in /).
|
|
89
|
+
const workdir = await validatePath(cwd ?? getConfig().allowedDirectories[0] ?? process.cwd());
|
|
90
|
+
const shell = getConfig().defaultShell;
|
|
91
|
+
// POSIX: detached makes the child lead its own process group, so force_terminate stops its
|
|
92
|
+
// children too. Windows: taskkill /T stops the tree instead, and windowsHide keeps it consoleless.
|
|
93
|
+
const child = spawn(shell, shellArgs(shell, command), {
|
|
94
|
+
cwd: workdir, detached: !IS_WINDOWS, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: process.env,
|
|
95
|
+
// cmd.exe parses its own quoting; Node's default escaping would break `cmd /s /c "..."`.
|
|
96
|
+
windowsVerbatimArguments: IS_WINDOWS && programName(shell) === 'cmd',
|
|
97
|
+
});
|
|
98
|
+
const pid = child.pid;
|
|
99
|
+
if (pid === undefined) {
|
|
100
|
+
const error = await new Promise((resolve) => child.once('error', resolve));
|
|
101
|
+
throw new Error(`could not start ${shell}: ${error.message}`);
|
|
102
|
+
}
|
|
103
|
+
const session = {
|
|
104
|
+
pid, command, cwd: workdir, child, startedAt: Date.now(), output: '', dropped: 0, cursor: 0,
|
|
105
|
+
exitCode: null, signal: null, exited: false, checkInput: programs.some((p) => SHELLS.has(p)), listeners: new Set(),
|
|
106
|
+
};
|
|
107
|
+
sessions.set(pid, session);
|
|
108
|
+
child.stdout?.setEncoding('utf8').on('data', (chunk) => append(session, chunk));
|
|
109
|
+
child.stderr?.setEncoding('utf8').on('data', (chunk) => append(session, chunk));
|
|
110
|
+
// Needed so a broken pipe never crashes the server; interact() reports the failed write itself.
|
|
111
|
+
child.stdin?.on('error', () => undefined);
|
|
112
|
+
child.on('error', (error) => append(session, `\n[command-center] process error: ${error.message}\n`));
|
|
113
|
+
child.on('close', (code, signal) => {
|
|
114
|
+
session.exited = true;
|
|
115
|
+
session.exitCode = code;
|
|
116
|
+
session.signal = signal;
|
|
117
|
+
notify(session);
|
|
118
|
+
});
|
|
119
|
+
await settle(session, timeoutMs);
|
|
120
|
+
return take(session);
|
|
121
|
+
}
|
|
122
|
+
export async function interact(pid, input, timeoutMs) {
|
|
123
|
+
const session = get(pid);
|
|
124
|
+
if (session.exited)
|
|
125
|
+
throw new Error(`process ${pid} has exited (code ${session.exitCode}); start a new one`);
|
|
126
|
+
if (session.checkInput)
|
|
127
|
+
checkCommand(input);
|
|
128
|
+
const stdin = session.child.stdin;
|
|
129
|
+
if (!stdin || !stdin.writable)
|
|
130
|
+
throw new Error(`process ${pid} is running but no longer reads input (its stdin is closed)`);
|
|
131
|
+
// Resolves once the bytes reach the pipe; rejects (EPIPE) if the process closed its input.
|
|
132
|
+
await new Promise((resolve, reject) => {
|
|
133
|
+
stdin.write(input.endsWith('\n') ? input : `${input}\n`, (error) => (error ? reject(new Error(`input not delivered to ${pid}: ${error.message}`)) : resolve()));
|
|
134
|
+
});
|
|
135
|
+
// The result includes any output not yet read, followed by the reply to this input.
|
|
136
|
+
await settle(session, timeoutMs);
|
|
137
|
+
return take(session);
|
|
138
|
+
}
|
|
139
|
+
export async function readOutput(pid, timeoutMs) {
|
|
140
|
+
const session = get(pid);
|
|
141
|
+
if (session.cursor === session.dropped + session.output.length)
|
|
142
|
+
await settle(session, timeoutMs);
|
|
143
|
+
return take(session);
|
|
144
|
+
}
|
|
145
|
+
export async function terminate(pid) {
|
|
146
|
+
const session = get(pid);
|
|
147
|
+
if (!session.exited) {
|
|
148
|
+
signalGroup(session, 'SIGTERM');
|
|
149
|
+
await settle(session, 2000);
|
|
150
|
+
if (!session.exited) {
|
|
151
|
+
signalGroup(session, 'SIGKILL');
|
|
152
|
+
await settle(session, 2000);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (!session.exited) {
|
|
156
|
+
// Keep the session so the caller can see it and retry; never report a live process as stopped.
|
|
157
|
+
throw new Error(`process ${pid} did not exit after SIGTERM and SIGKILL; it is still listed by list_sessions`);
|
|
158
|
+
}
|
|
159
|
+
const result = take(session);
|
|
160
|
+
sessions.delete(pid);
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
function signalGroup(session, signal) {
|
|
164
|
+
if (IS_WINDOWS) {
|
|
165
|
+
// No process groups or POSIX signals on Windows: taskkill stops the whole tree (/T).
|
|
166
|
+
// /F always: without it taskkill sends WM_CLOSE, which windowless console processes ignore.
|
|
167
|
+
const args = ['/PID', String(session.pid), '/T', '/F'];
|
|
168
|
+
spawn('taskkill', args, { windowsHide: true, stdio: 'ignore' })
|
|
169
|
+
.on('error', (error) => {
|
|
170
|
+
log('warn', `taskkill could not run (${error.message}); stopping only the shell of ${session.pid}`);
|
|
171
|
+
session.child.kill();
|
|
172
|
+
})
|
|
173
|
+
.on('close', (code) => {
|
|
174
|
+
// 128 = no such process (already gone); anything else is a real failure.
|
|
175
|
+
if (code !== 0 && code !== 128 && !session.exited)
|
|
176
|
+
log('warn', `taskkill ${args.join(' ')} exited ${code}`);
|
|
177
|
+
});
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
process.kill(-session.pid, signal);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
try {
|
|
185
|
+
session.child.kill(signal);
|
|
186
|
+
}
|
|
187
|
+
catch { /* already gone */ }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
export function listSessions() {
|
|
191
|
+
return [...sessions.values()].map((s) => ({
|
|
192
|
+
pid: s.pid,
|
|
193
|
+
command: s.command,
|
|
194
|
+
cwd: s.cwd,
|
|
195
|
+
running: !s.exited,
|
|
196
|
+
exitCode: s.exitCode,
|
|
197
|
+
runtimeMs: Date.now() - s.startedAt,
|
|
198
|
+
unreadChars: s.dropped + s.output.length - s.cursor,
|
|
199
|
+
}));
|
|
200
|
+
}
|
|
201
|
+
/** Stops every session; called when the client disconnects or the server is signalled. */
|
|
202
|
+
export function stopAll() {
|
|
203
|
+
for (const session of sessions.values())
|
|
204
|
+
if (!session.exited)
|
|
205
|
+
signalGroup(session, 'SIGKILL');
|
|
206
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Runs the built-in search off the main thread, so a slow regular expression can be stopped
|
|
2
|
+
// (worker.terminate) instead of freezing the server. Matches go to the parent in batches as they
|
|
3
|
+
// are found, so a paged search shows results while it runs; the final message carries the rest.
|
|
4
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
5
|
+
import { nodeSearch } from './search.js';
|
|
6
|
+
const BATCH = 100; // matches per message: few messages, and a page of results arrives quickly
|
|
7
|
+
const { root, input } = workerData;
|
|
8
|
+
let batch = [];
|
|
9
|
+
const flush = () => { if (batch.length) {
|
|
10
|
+
parentPort?.postMessage({ batch });
|
|
11
|
+
batch = [];
|
|
12
|
+
} };
|
|
13
|
+
nodeSearch(root, input, (match) => { batch.push(match); if (batch.length >= BATCH)
|
|
14
|
+
flush(); }).then((result) => { flush(); parentPort?.postMessage({ ok: true, result: { ...result, matches: [] } }); }, (error) => { flush(); parentPort?.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) }); });
|