execute method
Execute the tool with the given input.
Implementation
@override
Future<ToolResult> execute(Map<String, dynamic> input) async {
final parsed = PowerShellInput.fromMap(input);
final errors = parsed.validate();
if (errors.isNotEmpty) {
return ToolResult.error(errors.join('; '));
}
// Safety check.
if (enableSafetyChecks) {
final safetyError = _checkCommandSafety(parsed.command);
if (safetyError != null) {
return ToolResult.error(safetyError);
}
}
// Resolve the PowerShell executable.
final executable = _findPowerShell();
if (executable == null) {
return ToolResult.error(
'PowerShell not found. Install PowerShell Core (pwsh) from '
'https://github.com/PowerShell/PowerShell',
);
}
// Build arguments.
final args = <String>[];
final policy = parsed.executionPolicy ?? defaultExecutionPolicy;
if (policy != null) {
args.addAll(['-ExecutionPolicy', policy]);
}
args.addAll(['-NoProfile', '-NonInteractive', '-Command', parsed.command]);
// Resolve working directory.
final effectiveWorkDir = parsed.workDir ?? workingDirectory;
// Build environment.
final effectiveEnv = <String, String>{
...Platform.environment,
if (environment != null) ...environment!,
};
// Execute.
final stopwatch = Stopwatch()..start();
try {
final result = await Process.run(
executable,
args,
workingDirectory: effectiveWorkDir,
environment: effectiveEnv,
).timeout(parsed.timeout);
stopwatch.stop();
final output = PowerShellOutput(
exitCode: result.exitCode,
stdout: (result.stdout as String).trim(),
stderr: (result.stderr as String).trim(),
duration: stopwatch.elapsed,
);
if (!output.isSuccess) {
return ToolResult(
content: output.toString(),
isError: true,
metadata: output.toMetadata(),
);
}
return ToolResult.success(
output.toString(),
metadata: output.toMetadata(),
);
} on ProcessException catch (e) {
stopwatch.stop();
return ToolResult.error('PowerShell process error: ${e.message}');
} on TimeoutException {
stopwatch.stop();
return ToolResult.error(
'PowerShell command timed out after '
'${parsed.timeout.inSeconds}s',
);
} catch (e) {
stopwatch.stop();
return ToolResult.error('PowerShell execution error: $e');
}
}