createPowerShellTool function

Tool<JsonMap, String> createPowerShellTool(
  1. Genkit ai, {
  2. required ToolRuntime runtime,
})

Builds the tool that runs PowerShell commands. Only registered on Windows.

Implementation

Tool<JsonMap, String> createPowerShellTool(
  Genkit ai, {
  required ToolRuntime runtime,
}) {
  return defineTextTool(
    ai,
    runtime: runtime,
    name: 'powershell',
    description: _description,
    properties: <String, Object?>{
      'command': stringProperty('The PowerShell command to execute.'),
    },
    required: <String>['command'],
    run: (input) async {
      final command = requireString(input, 'command').trim();
      final approved = await runtime.requestApproval(
        ToolApprovalRequest(toolName: 'powershell', reason: 'PowerShell commands require approval.', command: command),
      );
      if (!approved) {
        throw const ToolFailure('The user declined to run this command. Do not retry it.');
      }

      runtime.startTool('powershell', command);
      ProcessResult? result;
      for (final executable in <String>['pwsh', 'powershell']) {
        try {
          result = await Process.run(
            executable,
            <String>['-NoProfile', '-Command', command],
            workingDirectory: runtime.currentWorkingDirectory,
          );
          break;
        } on ProcessException {
          continue;
        }
      }
      if (result == null) {
        throw const ToolFailure('PowerShell is not available on this machine.');
      }

      final output = '${result.stdout}${result.stderr}'.trimRight();
      return 'exit_code: ${result.exitCode}\n${truncateMiddle(output, _maxOutputChars)}';
    },
  );
}