Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a0010e7f0f | |||
| d65e1ed4f6 | |||
| e61b352576 | |||
| b7882ef60f | |||
| cd5194c365 | |||
| 71cc64b6d9 | |||
| f254a9e078 | |||
| 3d6a33f8d2 | |||
| d37071dae0 |
Binary file not shown.
@@ -1,68 +0,0 @@
|
||||
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||
# * For C, use cpp
|
||||
# * For JavaScript, use typescript
|
||||
# Special requirements:
|
||||
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||
language: typescript
|
||||
|
||||
# whether to use the project's gitignore file to ignore files
|
||||
# Added on 2025-04-07
|
||||
ignore_all_files_in_gitignore: true
|
||||
# list of additional paths to ignore
|
||||
# same syntax as gitignore, so you can use * and **
|
||||
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||
# Added (renamed) on 2025-04-07
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
|
||||
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project by name.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_lines`: Deletes a range of lines within a file.
|
||||
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||
# Should only be used in settings where the system prompt cannot be set,
|
||||
# e.g. in clients you have no control over, like Claude Desktop.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||
# * `remove_project`: Removes a project from the Serena configuration.
|
||||
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||
# * `switch_modes`: Activates modes by providing a list of their names
|
||||
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||
excluded_tools: []
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
project_name: "smartshell"
|
||||
@@ -32,8 +32,8 @@
|
||||
"@git.zone/cli": {
|
||||
"release": {
|
||||
"registries": [
|
||||
"https://verdaccio.lossleess.digital",
|
||||
"https://registry.npmjs.org"
|
||||
"https://registry.npmjs.org",
|
||||
"https://verdaccio.lossless.digital"
|
||||
],
|
||||
"accessLevel": "public"
|
||||
}
|
||||
Vendored
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["/npmextra.json"],
|
||||
"fileMatch": ["/.smartconfig.json"],
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-05-09 - 3.4.0 - feat(smartshell)
|
||||
add cwd-aware execution options, structured strict-mode errors, and safer process tree termination
|
||||
|
||||
- adds cwd and env runtime options across exec, spawn, interactive, wait-for-line, and PTY execution APIs
|
||||
- introduces SmartshellError with exit code, signal, stdout, stderr, and combined result details for strict-mode failures
|
||||
- terminates timed-out commands via process tree killing to prevent detached child processes from continuing after timeout
|
||||
|
||||
## 2026-03-15 - 3.3.8 - fix(repo)
|
||||
remove obsolete Serena project configuration files
|
||||
|
||||
- Deletes the .serena project configuration from the repository
|
||||
- Cleans up editor or tooling metadata that is not part of the package runtime or source code
|
||||
|
||||
## 2026-03-05 - 3.3.7 - fix(smartshell)
|
||||
avoid triple shell nesting, improve WSL path filtering, and use chunked log buffer to reduce memory usage
|
||||
|
||||
- Spawn uses the executor shell binary directly (e.g. /bin/bash) and removes extra bash -c wrapping to avoid triple shell nesting
|
||||
- Only filter out /mnt/c/ and other WSL-specific PATH entries when running under WSL (adds _isWSL detection)
|
||||
- Replace single concatenated Buffer with chunked buffering in ShellLog (lazy concatenation, logLength property) and update checks to use logLength
|
||||
- Remove unused dependency "tree-kill" from package.json
|
||||
|
||||
## 2026-03-04 - 3.3.6 - fix(smartshell)
|
||||
use 'close' event on child processes to ensure exit handling and update dependency versions
|
||||
|
||||
- Replace child_process 'exit' listeners with 'close' in ts/classes.smartshell.ts (two occurrences) to ensure handlers run after stdio streams are closed.
|
||||
- Bump devDependencies: @git.zone/tsbuild ^2.7.3 -> ^4.1.2, @git.zone/tsrun ^1.6.2 -> ^2.0.1, @git.zone/tstest ^2.8.3 -> ^3.2.0, @types/node ^22.19.13 -> ^25.3.3.
|
||||
- Bump dependencies: @push.rocks/smartexit ^2.0.1 -> ^2.0.3, which ^5.0.0 -> ^6.0.1.
|
||||
|
||||
## 2026-03-03 - 3.3.2 - fix(release)
|
||||
add @git.zone/cli release configuration with registries and public access
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Task Venture Capital GmbH
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+10
-11
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@push.rocks/smartshell",
|
||||
"private": false,
|
||||
"version": "3.3.4",
|
||||
"version": "3.4.0",
|
||||
"description": "A library for executing shell commands using promises.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
@@ -33,18 +33,17 @@
|
||||
},
|
||||
"homepage": "https://code.foss.global/push.rocks/smartshell",
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.7.3",
|
||||
"@git.zone/tsrun": "^1.6.2",
|
||||
"@git.zone/tstest": "^2.8.3",
|
||||
"@types/node": "^22.19.13"
|
||||
"@git.zone/tsbuild": "^4.4.1",
|
||||
"@git.zone/tsrun": "^2.0.4",
|
||||
"@git.zone/tstest": "^3.6.6",
|
||||
"@types/node": "^25.6.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartexit": "^2.0.1",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smartdelay": "^3.1.0",
|
||||
"@push.rocks/smartexit": "^2.0.3",
|
||||
"@push.rocks/smartpromise": "^4.2.4",
|
||||
"@types/which": "^3.0.4",
|
||||
"tree-kill": "^1.2.2",
|
||||
"which": "^5.0.0"
|
||||
"which": "^7.0.0"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@@ -55,7 +54,7 @@
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
".smartconfig.json",
|
||||
"readme.md"
|
||||
],
|
||||
"browserslist": [
|
||||
|
||||
Generated
+3012
-4218
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,8 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
const getErrorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error);
|
||||
|
||||
tap.test('should handle EPIPE errors gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
@@ -40,7 +42,7 @@ tap.test('should handle strict mode with non-zero exit codes', async () => {
|
||||
await testSmartshell.execStrict('exit 42');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
@@ -65,13 +67,39 @@ tap.test('should handle strict mode with signal termination', async () => {
|
||||
await result;
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('terminated by signal');
|
||||
});
|
||||
|
||||
tap.test('strict mode errors should expose command result details', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let caughtError: smartshell.SmartshellError | null = null;
|
||||
|
||||
try {
|
||||
await testSmartshell.execSpawn('bash', ['-c', 'echo stdout-value; echo stderr-value >&2; exit 7'], {
|
||||
strict: true,
|
||||
silent: true,
|
||||
});
|
||||
} catch (error) {
|
||||
caughtError = error as smartshell.SmartshellError;
|
||||
}
|
||||
|
||||
expect(caughtError).toBeInstanceOf(smartshell.SmartshellError);
|
||||
expect(caughtError!.command).toEqual('bash');
|
||||
expect(caughtError!.exitCode).toEqual(7);
|
||||
expect(caughtError!.stdout).toContain('stdout-value');
|
||||
expect(caughtError!.combinedOutput).toContain('stderr-value');
|
||||
expect(caughtError!.stderr).toContain('stderr-value');
|
||||
expect(caughtError!.result.exitCode).toEqual(7);
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with timeout should reject properly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
@@ -90,7 +118,7 @@ tap.test('execAndWaitForLine with timeout should reject properly', async () => {
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
@@ -133,7 +161,7 @@ tap.test('should handle process ending without matching pattern', async () => {
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
@@ -169,7 +197,7 @@ tap.test('should handle write after stream destroyed', async () => {
|
||||
await interactive.sendLine('This should fail');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.message).toContain('destroyed');
|
||||
expect(getErrorMessage(error)).toContain('destroyed');
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as smartshell from '../ts/index.js';
|
||||
// Helper to check if node-pty is available
|
||||
const isPtyAvailable = async (): Promise<boolean> => {
|
||||
try {
|
||||
// @ts-ignore - node-pty is an optional runtime dependency.
|
||||
await import('node-pty');
|
||||
return true;
|
||||
} catch {
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ tap.test('execStreamingSilent should capture streaming output without console di
|
||||
const streamingResult = await testSmartshell.execStreamingSilent('echo "Line 1" && sleep 0.1 && echo "Line 2"');
|
||||
|
||||
let capturedData = '';
|
||||
streamingResult.childProcess.stdout.on('data', (data) => {
|
||||
streamingResult.childProcess.stdout!.on('data', (data) => {
|
||||
capturedData += data.toString();
|
||||
});
|
||||
|
||||
|
||||
+81
-1
@@ -1,5 +1,8 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
|
||||
tap.test('execSpawn should execute commands with args array (shell:false)', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
@@ -13,6 +16,41 @@ tap.test('execSpawn should execute commands with args array (shell:false)', asyn
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should run in the configured cwd', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartshell-cwd-'));
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSpawn('node', ['-e', 'console.log(process.cwd())'], {
|
||||
cwd: tmpDir,
|
||||
silent: true,
|
||||
});
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout.trim()).toEqual(tmpDir);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('execSilent should run shell commands in the configured cwd', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartshell-shell-cwd-'));
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSilent('pwd', { cwd: tmpDir });
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout.trim()).toEqual(tmpDir);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('execSpawn should handle command not found errors', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
@@ -24,7 +62,7 @@ tap.test('execSpawn should handle command not found errors', async () => {
|
||||
await testSmartshell.execSpawn('nonexistentcommand123', ['arg1']);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.code).toEqual('ENOENT');
|
||||
expect((error as NodeJS.ErrnoException).code).toEqual('ENOENT');
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
@@ -99,6 +137,48 @@ tap.test('execSpawn with timeout should terminate process', async () => {
|
||||
expect(result.signal).toBeTruthy(); // Should have been killed by signal
|
||||
});
|
||||
|
||||
tap.test('execSpawn timeout should terminate the spawned process tree', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const markerPath = path.join(os.tmpdir(), `smartshell-spawn-timeout-${process.pid}-${Date.now()}`);
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSpawn(
|
||||
'bash',
|
||||
['-c', `(sleep 0.6; touch "${markerPath}") & wait`],
|
||||
{ timeout: 100, silent: true },
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(fs.existsSync(markerPath)).toBeFalse();
|
||||
} finally {
|
||||
fs.rmSync(markerPath, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('exec timeout should terminate the shell process tree', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const markerPath = path.join(os.tmpdir(), `smartshell-shell-timeout-${process.pid}-${Date.now()}`);
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSilent(`(sleep 0.6; touch "${markerPath}") & wait`, {
|
||||
timeout: 100,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(fs.existsSync(markerPath)).toBeFalse();
|
||||
} finally {
|
||||
fs.rmSync(markerPath, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('execSpawn with maxBuffer should truncate output', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ tap.test('smartshell should run async and silent', async () => {
|
||||
tap.test('smartshell should stream a shell execution', async () => {
|
||||
let done = smartpromise.defer();
|
||||
let execStreamingResponse = await testSmartshell.execStreaming('npm -v');
|
||||
execStreamingResponse.childProcess.stdout.on('data', (data) => {
|
||||
execStreamingResponse.childProcess.stdout!.on('data', (data) => {
|
||||
done.resolve(data);
|
||||
});
|
||||
let data = await done.promise;
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartshell',
|
||||
version: '3.3.2',
|
||||
version: '3.4.0',
|
||||
description: 'A library for executing shell commands using promises.'
|
||||
}
|
||||
|
||||
+23
-16
@@ -28,29 +28,38 @@ export class ShellEnv {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect if running under Windows Subsystem for Linux
|
||||
*/
|
||||
private static _isWSL(): boolean {
|
||||
return !!(
|
||||
process.env.WSL_DISTRO_NAME ||
|
||||
process.env.WSLENV ||
|
||||
(process.platform === 'linux' && process.env.PATH?.includes('/mnt/c/'))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* imports path into the shell from env if available and returns it with
|
||||
*/
|
||||
private _setPath(commandStringArg: string): string {
|
||||
let commandResult = commandStringArg;
|
||||
let commandPaths: string[] = [];
|
||||
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
|
||||
commandPaths = commandPaths.concat(process.env.PATH?.split(':') ?? []);
|
||||
if (process.env.SMARTSHELL_PATH) {
|
||||
commandPaths = commandPaths.concat(process.env.SMARTSHELL_PATH.split(':'));
|
||||
}
|
||||
|
||||
// lets filter for unwanted paths
|
||||
// Windows WSL
|
||||
// Only filter out WSL-specific paths when actually running under WSL
|
||||
if (ShellEnv._isWSL()) {
|
||||
commandPaths = commandPaths.filter((commandPathArg) => {
|
||||
const filterResult =
|
||||
return (
|
||||
!commandPathArg.startsWith('/mnt/c/') &&
|
||||
!commandPathArg.startsWith('Files/1E') &&
|
||||
!commandPathArg.includes(' ');
|
||||
if (!filterResult) {
|
||||
// console.log(`${commandPathArg} will be filtered!`);
|
||||
}
|
||||
return filterResult;
|
||||
!commandPathArg.includes(' ')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
commandResult = `PATH=${commandPaths.join(':')} && ${commandStringArg}`;
|
||||
return commandResult;
|
||||
@@ -89,14 +98,12 @@ export class ShellEnv {
|
||||
}
|
||||
pathString += ` && `;
|
||||
|
||||
switch (this.executor) {
|
||||
case 'bash':
|
||||
commandResult = `bash -c '${pathString}${sourceString}${commandArg}'`;
|
||||
break;
|
||||
case 'sh':
|
||||
// For both bash and sh executors, build the command string directly.
|
||||
// The shell nesting is handled by spawn() using the appropriate shell binary.
|
||||
// Previously bash executor wrapped in `bash -c '...'` which caused triple
|
||||
// shell nesting (Node spawn sh -> bash -c -> command). Now spawn() uses
|
||||
// shell: '/bin/bash' directly, so we don't need the extra wrapping.
|
||||
commandResult = `${pathString}${sourceString}${commandArg}`;
|
||||
break;
|
||||
}
|
||||
commandResult = this._setPath(commandResult);
|
||||
return commandResult;
|
||||
}
|
||||
|
||||
+38
-8
@@ -5,7 +5,41 @@ import * as plugins from './plugins.js';
|
||||
* making sure the process doesn't run out of memory
|
||||
*/
|
||||
export class ShellLog {
|
||||
public logStore = Buffer.from('');
|
||||
private chunks: Buffer[] = [];
|
||||
private totalLength = 0;
|
||||
|
||||
/**
|
||||
* Get the accumulated log as a single Buffer.
|
||||
* Concatenation happens lazily only when accessed.
|
||||
*/
|
||||
public get logStore(): Buffer {
|
||||
if (this.chunks.length === 0) {
|
||||
return Buffer.alloc(0);
|
||||
}
|
||||
if (this.chunks.length === 1) {
|
||||
return this.chunks[0];
|
||||
}
|
||||
// Flatten chunks into a single buffer
|
||||
const combined = Buffer.concat(this.chunks, this.totalLength);
|
||||
// Replace chunks array with the single combined buffer for future access
|
||||
this.chunks = [combined];
|
||||
return combined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the log store directly (used for truncation).
|
||||
*/
|
||||
public set logStore(value: Buffer) {
|
||||
this.chunks = [value];
|
||||
this.totalLength = value.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current total length of buffered data without concatenating.
|
||||
*/
|
||||
public get logLength(): number {
|
||||
return this.totalLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* log data to console
|
||||
@@ -22,13 +56,9 @@ export class ShellLog {
|
||||
*/
|
||||
public addToBuffer(dataArg: string | Buffer): void {
|
||||
// make sure we have the data as Buffer
|
||||
const dataBuffer: Buffer = (() => {
|
||||
if (!Buffer.isBuffer(dataArg)) {
|
||||
return Buffer.from(dataArg);
|
||||
}
|
||||
return dataArg;
|
||||
})();
|
||||
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
|
||||
const dataBuffer: Buffer = Buffer.isBuffer(dataArg) ? dataArg : Buffer.from(dataArg);
|
||||
this.chunks.push(dataBuffer);
|
||||
this.totalLength += dataBuffer.length;
|
||||
}
|
||||
|
||||
public logAndAdd(dataArg: string | Buffer): void {
|
||||
|
||||
@@ -8,8 +8,8 @@ export interface IDeferred<T> {
|
||||
}
|
||||
|
||||
export class SmartExecution {
|
||||
public smartshell: Smartshell;
|
||||
public currentStreamingExecution: IExecResultStreaming;
|
||||
public smartshell!: Smartshell;
|
||||
public currentStreamingExecution!: IExecResultStreaming;
|
||||
public commandString: string;
|
||||
|
||||
private isRestartInProgress = false;
|
||||
|
||||
+181
-81
@@ -8,10 +8,37 @@ import * as cp from 'child_process';
|
||||
export interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
/** stdout currently preserves smartshell's legacy combined stdout/stderr buffer. */
|
||||
combinedOutput?: string;
|
||||
signal?: NodeJS.Signals;
|
||||
stderr?: string;
|
||||
}
|
||||
|
||||
export class SmartshellError extends Error {
|
||||
public command: string;
|
||||
public result: IExecResult;
|
||||
public exitCode: number;
|
||||
public stdout: string;
|
||||
public combinedOutput?: string;
|
||||
public stderr?: string;
|
||||
public signal?: NodeJS.Signals;
|
||||
|
||||
constructor(command: string, result: IExecResult) {
|
||||
const reason = result.signal
|
||||
? `terminated by signal ${result.signal}`
|
||||
: `exited with code ${result.exitCode}`;
|
||||
super(`Command "${command}" ${reason}`);
|
||||
this.name = 'SmartshellError';
|
||||
this.command = command;
|
||||
this.result = result;
|
||||
this.exitCode = result.exitCode;
|
||||
this.stdout = result.stdout;
|
||||
this.combinedOutput = result.combinedOutput;
|
||||
this.stderr = result.stderr;
|
||||
this.signal = result.signal;
|
||||
}
|
||||
}
|
||||
|
||||
export interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
@@ -31,15 +58,7 @@ export interface IExecResultStreaming {
|
||||
endInput: () => void;
|
||||
}
|
||||
|
||||
interface IExecOptions {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
export interface IExecRuntimeOptions {
|
||||
ptyCols?: number;
|
||||
ptyRows?: number;
|
||||
ptyTerm?: string;
|
||||
@@ -49,14 +68,35 @@ interface IExecOptions {
|
||||
timeout?: number;
|
||||
debug?: boolean;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
cwd?: string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface ISpawnOptions extends Omit<IExecOptions, 'commandString'> {
|
||||
interface IExecOptions extends IExecRuntimeOptions {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
}
|
||||
|
||||
export interface ISpawnOptions extends IExecRuntimeOptions {
|
||||
command: string;
|
||||
args?: string[];
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
}
|
||||
|
||||
export type TExecCommandOptions = IExecRuntimeOptions;
|
||||
|
||||
export class Smartshell {
|
||||
public shellEnv: ShellEnv;
|
||||
public smartexit = new plugins.smartexit.SmartExit();
|
||||
@@ -68,9 +108,13 @@ export class Smartshell {
|
||||
/**
|
||||
* Executes a given command asynchronously.
|
||||
*/
|
||||
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | void> {
|
||||
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive | void> {
|
||||
if (options.interactive) {
|
||||
return await this._execInteractive({ commandString: options.commandString });
|
||||
return await this._execInteractive({
|
||||
commandString: options.commandString,
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
});
|
||||
}
|
||||
return await this._execCommand(options);
|
||||
}
|
||||
@@ -78,7 +122,7 @@ export class Smartshell {
|
||||
/**
|
||||
* Executes an interactive command.
|
||||
*/
|
||||
private async _execInteractive(options: Pick<IExecOptions, 'commandString'>): Promise<void> {
|
||||
private async _execInteractive(options: Pick<IExecOptions, 'commandString' | 'cwd' | 'env'>): Promise<void> {
|
||||
// Skip interactive execution in CI environments.
|
||||
if (process.env.CI) {
|
||||
return;
|
||||
@@ -89,6 +133,8 @@ export class Smartshell {
|
||||
stdio: 'inherit',
|
||||
shell: true,
|
||||
detached: true,
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(shell);
|
||||
@@ -117,9 +163,9 @@ export class Smartshell {
|
||||
|
||||
const execChildProcess = cp.spawn(options.command, options.args || [], {
|
||||
shell: false, // SECURITY: Never use shell with untrusted input
|
||||
cwd: process.cwd(),
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
detached: false,
|
||||
detached: true, // Own process group — immune to terminal SIGINT, managed by smartexit
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
@@ -132,7 +178,7 @@ export class Smartshell {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
execChildProcess.kill('SIGTERM');
|
||||
void this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
@@ -182,7 +228,7 @@ export class Smartshell {
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
@@ -203,7 +249,7 @@ export class Smartshell {
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
@@ -232,24 +278,23 @@ export class Smartshell {
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const combinedOutput = shellLogInstance.logStore.toString();
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
stdout: combinedOutput,
|
||||
combinedOutput,
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
const errorMsg = signal
|
||||
? `Command "${options.command}" terminated by signal ${signal}`
|
||||
: `Command "${options.command}" exited with code ${exitCode}`;
|
||||
reject(new Error(errorMsg));
|
||||
reject(new SmartshellError(options.command, execResult));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('exit', handleExit);
|
||||
execChildProcess.once('close', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
@@ -296,25 +341,25 @@ export class Smartshell {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGKILL', options.debug);
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGINT', options.debug);
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
|
||||
await this.killProcessTree(execChildProcess.pid, signal, options.debug);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
@@ -338,11 +383,15 @@ export class Smartshell {
|
||||
return await this._execCommandPty(options, commandToExecute, shellLogInstance);
|
||||
}
|
||||
|
||||
// Use the executor's shell binary directly to avoid triple shell nesting.
|
||||
// Previously: Node spawn(shell:true) → /bin/sh → bash -c → command (3 layers)
|
||||
// Now: Node spawn(shell:bash) → command (1 layer)
|
||||
const shellBinary = this.shellEnv.executor === 'bash' ? '/bin/bash' : true;
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: true,
|
||||
cwd: process.cwd(),
|
||||
shell: shellBinary,
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
detached: false,
|
||||
detached: true, // Own process group — immune to terminal SIGINT, managed by smartexit
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
@@ -355,7 +404,7 @@ export class Smartshell {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
execChildProcess.kill('SIGTERM');
|
||||
void this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
@@ -405,7 +454,7 @@ export class Smartshell {
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
@@ -426,7 +475,7 @@ export class Smartshell {
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
@@ -455,24 +504,23 @@ export class Smartshell {
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const combinedOutput = shellLogInstance.logStore.toString();
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
stdout: combinedOutput,
|
||||
combinedOutput,
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
const errorMsg = signal
|
||||
? `Command "${options.commandString}" terminated by signal ${signal}`
|
||||
: `Command "${options.commandString}" exited with code ${exitCode}`;
|
||||
reject(new Error(errorMsg));
|
||||
reject(new SmartshellError(options.commandString, execResult));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('exit', handleExit);
|
||||
execChildProcess.once('close', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
@@ -519,25 +567,25 @@ export class Smartshell {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGKILL', options.debug);
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGINT', options.debug);
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
|
||||
await this.killProcessTree(execChildProcess.pid, signal, options.debug);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
@@ -546,58 +594,87 @@ export class Smartshell {
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
public async exec(commandString: string): Promise<IExecResult> {
|
||||
const result = await this._exec({ commandString });
|
||||
private async killProcessTree(
|
||||
pid: number | undefined,
|
||||
signal: plugins.smartexit.TProcessSignal,
|
||||
debug?: boolean,
|
||||
): Promise<void> {
|
||||
if (!pid) {
|
||||
return;
|
||||
}
|
||||
if (debug) {
|
||||
console.log(`[smartshell] Killing process tree ${pid} with ${signal}`);
|
||||
}
|
||||
try {
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(pid, signal);
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.log(`[smartshell] Tree kill failed for ${pid}: ${error}`);
|
||||
}
|
||||
try {
|
||||
process.kill(pid, signal as NodeJS.Signals);
|
||||
} catch {
|
||||
// Process already exited or is not accessible.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async exec(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
const result = await this._exec({ commandString, ...options });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
public async execSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: true })) as IExecResult;
|
||||
public async execSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, ...options, silent: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrict(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, strict: true })) as IExecResult;
|
||||
public async execStrict(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, ...options, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrictSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult;
|
||||
public async execStrictSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, ...options, silent: true, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreaming(commandString: string, silent: boolean = false): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
|
||||
public async execStreaming(
|
||||
commandString: string,
|
||||
silent: boolean = false,
|
||||
options: TExecCommandOptions = {},
|
||||
): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, ...options, silent, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, silent: true, streaming: true })) as IExecResultStreaming;
|
||||
public async execStreamingSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, ...options, silent: true, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractive(commandString: string): Promise<void> {
|
||||
await this._exec({ commandString, interactive: true });
|
||||
public async execInteractive(commandString: string, options: TExecCommandOptions = {}): Promise<void> {
|
||||
await this._exec({ commandString, ...options, interactive: true });
|
||||
}
|
||||
|
||||
public async execPassthrough(commandString: string): Promise<IExecResult> {
|
||||
return await this._exec({ commandString, passthrough: true }) as IExecResult;
|
||||
public async execPassthrough(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return await this._exec({ commandString, ...options, passthrough: true }) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreamingPassthrough(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, passthrough: true }) as IExecResultStreaming;
|
||||
public async execStreamingPassthrough(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, ...options, streaming: true, passthrough: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControl(commandString: string): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, interactiveControl: true }) as IExecResultInteractive;
|
||||
public async execInteractiveControl(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, ...options, interactiveControl: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControl(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, interactiveControl: true }) as IExecResultStreaming;
|
||||
public async execStreamingInteractiveControl(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, ...options, streaming: true, interactiveControl: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControlPty(commandString: string): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, interactiveControl: true, usePty: true }) as IExecResultInteractive;
|
||||
public async execInteractiveControlPty(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, ...options, interactiveControl: true, usePty: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControlPty(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, interactiveControl: true, usePty: true }) as IExecResultStreaming;
|
||||
public async execStreamingInteractiveControlPty(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, ...options, streaming: true, interactiveControl: true, usePty: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -614,23 +691,31 @@ export class Smartshell {
|
||||
* Executes a command with args array in streaming mode
|
||||
*/
|
||||
public async execSpawnStreaming(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'streaming'> = {}): Promise<IExecResultStreaming> {
|
||||
return await this._execSpawn({ command, args, streaming: true, ...options }) as IExecResultStreaming;
|
||||
return await this._execSpawn({ command, args, ...options, streaming: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array with interactive control
|
||||
*/
|
||||
public async execSpawnInteractiveControl(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'interactiveControl'> = {}): Promise<IExecResultInteractive> {
|
||||
return await this._execSpawn({ command, args, interactiveControl: true, ...options }) as IExecResultInteractive;
|
||||
return await this._execSpawn({ command, args, ...options, interactiveControl: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execAndWaitForLine(
|
||||
commandString: string,
|
||||
regex: RegExp,
|
||||
silent: boolean = false,
|
||||
options: { timeout?: number; terminateOnMatch?: boolean } = {}
|
||||
options: { timeout?: number; terminateOnMatch?: boolean; cwd?: string; env?: NodeJS.ProcessEnv } = {}
|
||||
): Promise<void> {
|
||||
const execStreamingResult = await this.execStreaming(commandString, silent);
|
||||
const execStreamingResult = await this.execStreaming(commandString, silent, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
});
|
||||
const stdout = execStreamingResult.childProcess.stdout;
|
||||
if (!stdout) {
|
||||
await execStreamingResult.terminate();
|
||||
throw new Error('stdout is not available for this process');
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let matched = false;
|
||||
@@ -642,7 +727,7 @@ export class Smartshell {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
// Remove listener to prevent memory leak
|
||||
execStreamingResult.childProcess.stdout.removeAllListeners('data');
|
||||
stdout.removeAllListeners('data');
|
||||
await execStreamingResult.terminate();
|
||||
reject(new Error(`Timeout waiting for pattern after ${options.timeout}ms`));
|
||||
}
|
||||
@@ -660,7 +745,7 @@ export class Smartshell {
|
||||
}
|
||||
|
||||
// Remove listener to prevent memory leak
|
||||
execStreamingResult.childProcess.stdout.removeListener('data', dataHandler);
|
||||
stdout.removeListener('data', dataHandler);
|
||||
|
||||
// Terminate process if requested
|
||||
if (options.terminateOnMatch) {
|
||||
@@ -672,7 +757,7 @@ export class Smartshell {
|
||||
}
|
||||
};
|
||||
|
||||
execStreamingResult.childProcess.stdout.on('data', dataHandler);
|
||||
stdout.on('data', dataHandler);
|
||||
|
||||
// Also resolve/reject when process ends
|
||||
execStreamingResult.finalPromise.then(() => {
|
||||
@@ -695,7 +780,7 @@ export class Smartshell {
|
||||
});
|
||||
}
|
||||
|
||||
public async execAndWaitForLineSilent(commandString: string, regex: RegExp, options?: { timeout?: number; terminateOnMatch?: boolean }): Promise<void> {
|
||||
public async execAndWaitForLineSilent(commandString: string, regex: RegExp, options?: { timeout?: number; terminateOnMatch?: boolean; cwd?: string; env?: NodeJS.ProcessEnv }): Promise<void> {
|
||||
return this.execAndWaitForLine(commandString, regex, true, options);
|
||||
}
|
||||
|
||||
@@ -765,7 +850,7 @@ export class Smartshell {
|
||||
name: options.ptyTerm || 'xterm-256color',
|
||||
cols: options.ptyCols || 120,
|
||||
rows: options.ptyRows || 30,
|
||||
cwd: process.cwd(),
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
});
|
||||
|
||||
@@ -780,18 +865,33 @@ export class Smartshell {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for PTY process ${ptyProcess.pid}, terminating...`);
|
||||
}
|
||||
ptyProcess.kill('SIGTERM');
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Wrap PTY termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
ptyProcess.onExit(({ exitCode, signal }: { exitCode: number; signal?: number }) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
const combinedOutput = shellLogInstance.logStore.toString();
|
||||
const execResult: IExecResult = {
|
||||
exitCode: exitCode ?? (signal ? 1 : 0),
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
stdout: combinedOutput,
|
||||
combinedOutput,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
reject(new Error(`Command "${options.commandString}" exited with code ${exitCode}`));
|
||||
reject(new SmartshellError(options.commandString, execResult));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"types": ["node"],
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user