We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
command console.choose.cmd crashes when given no arguments
Enter mitmproxy console, issue a command like:

    console.choose.cmd

... and press return. 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mitmproxy/command.py`
Content:
```
1 """
2     This module manges and invokes typed commands.
3 """
4 import inspect
5 import typing
6 import shlex
7 import textwrap
8 import functools
9 import sys
10 
11 from mitmproxy.utils import typecheck
12 from mitmproxy import exceptions
13 from mitmproxy import flow
14 
15 
16 Cuts = typing.Sequence[
17     typing.Sequence[typing.Union[str, bytes]]
18 ]
19 
20 
21 def typename(t: type, ret: bool) -> str:
22     """
23         Translates a type to an explanatory string. If ret is True, we're
24         looking at a return type, else we're looking at a parameter type.
25     """
26     if issubclass(t, (str, int, bool)):
27         return t.__name__
28     elif t == typing.Sequence[flow.Flow]:
29         return "[flow]" if ret else "flowspec"
30     elif t == typing.Sequence[str]:
31         return "[str]"
32     elif t == Cuts:
33         return "[cuts]" if ret else "cutspec"
34     elif t == flow.Flow:
35         return "flow"
36     else:  # pragma: no cover
37         raise NotImplementedError(t)
38 
39 
40 class Command:
41     def __init__(self, manager, path, func) -> None:
42         self.path = path
43         self.manager = manager
44         self.func = func
45         sig = inspect.signature(self.func)
46         self.help = None
47         if func.__doc__:
48             txt = func.__doc__.strip()
49             self.help = "\n".join(textwrap.wrap(txt))
50 
51         self.has_positional = False
52         for i in sig.parameters.values():
53             # This is the kind for *args paramters
54             if i.kind == i.VAR_POSITIONAL:
55                 self.has_positional = True
56         self.paramtypes = [v.annotation for v in sig.parameters.values()]
57         self.returntype = sig.return_annotation
58 
59     def paramnames(self) -> typing.Sequence[str]:
60         v = [typename(i, False) for i in self.paramtypes]
61         if self.has_positional:
62             v[-1] = "*" + v[-1]
63         return v
64 
65     def retname(self) -> str:
66         return typename(self.returntype, True) if self.returntype else ""
67 
68     def signature_help(self) -> str:
69         params = " ".join(self.paramnames())
70         ret = self.retname()
71         if ret:
72             ret = " -> " + ret
73         return "%s %s%s" % (self.path, params, ret)
74 
75     def call(self, args: typing.Sequence[str]):
76         """
77             Call the command with a list of arguments. At this point, all
78             arguments are strings.
79         """
80         if not self.has_positional and (len(self.paramtypes) != len(args)):
81             raise exceptions.CommandError("Usage: %s" % self.signature_help())
82 
83         remainder = []  # type: typing.Sequence[str]
84         if self.has_positional:
85             remainder = args[len(self.paramtypes) - 1:]
86             args = args[:len(self.paramtypes) - 1]
87 
88         pargs = []
89         for i in range(len(args)):
90             if typecheck.check_command_type(args[i], self.paramtypes[i]):
91                 pargs.append(args[i])
92             else:
93                 pargs.append(parsearg(self.manager, args[i], self.paramtypes[i]))
94 
95         if remainder:
96             chk = typecheck.check_command_type(
97                 remainder,
98                 typing.Sequence[self.paramtypes[-1]]  # type: ignore
99             )
100             if chk:
101                 pargs.extend(remainder)
102             else:
103                 raise exceptions.CommandError("Invalid value type.")
104 
105         with self.manager.master.handlecontext():
106             ret = self.func(*pargs)
107 
108         if not typecheck.check_command_type(ret, self.returntype):
109             raise exceptions.CommandError("Command returned unexpected data")
110 
111         return ret
112 
113 
114 class CommandManager:
115     def __init__(self, master):
116         self.master = master
117         self.commands = {}
118 
119     def collect_commands(self, addon):
120         for i in dir(addon):
121             if not i.startswith("__"):
122                 o = getattr(addon, i)
123                 if hasattr(o, "command_path"):
124                     self.add(o.command_path, o)
125 
126     def add(self, path: str, func: typing.Callable):
127         self.commands[path] = Command(self, path, func)
128 
129     def call_args(self, path, args):
130         """
131             Call a command using a list of string arguments. May raise CommandError.
132         """
133         if path not in self.commands:
134             raise exceptions.CommandError("Unknown command: %s" % path)
135         return self.commands[path].call(args)
136 
137     def call(self, cmdstr: str):
138         """
139             Call a command using a string. May raise CommandError.
140         """
141         parts = shlex.split(cmdstr)
142         if not len(parts) >= 1:
143             raise exceptions.CommandError("Invalid command: %s" % cmdstr)
144         return self.call_args(parts[0], parts[1:])
145 
146     def dump(self, out=sys.stdout) -> None:
147         cmds = list(self.commands.values())
148         cmds.sort(key=lambda x: x.signature_help())
149         for c in cmds:
150             for hl in (c.help or "").splitlines():
151                 print("# " + hl, file=out)
152             print(c.signature_help(), file=out)
153             print(file=out)
154 
155 
156 def parsearg(manager: CommandManager, spec: str, argtype: type) -> typing.Any:
157     """
158         Convert a string to a argument to the appropriate type.
159     """
160     if issubclass(argtype, str):
161         return spec
162     elif argtype == bool:
163         if spec == "true":
164             return True
165         elif spec == "false":
166             return False
167         else:
168             raise exceptions.CommandError(
169                 "Booleans are 'true' or 'false', got %s" % spec
170             )
171     elif issubclass(argtype, int):
172         try:
173             return int(spec)
174         except ValueError as e:
175             raise exceptions.CommandError("Expected an integer, got %s." % spec)
176     elif argtype == typing.Sequence[flow.Flow]:
177         return manager.call_args("view.resolve", [spec])
178     elif argtype == Cuts:
179         return manager.call_args("cut", [spec])
180     elif argtype == flow.Flow:
181         flows = manager.call_args("view.resolve", [spec])
182         if len(flows) != 1:
183             raise exceptions.CommandError(
184                 "Command requires one flow, specification matched %s." % len(flows)
185             )
186         return flows[0]
187     elif argtype == typing.Sequence[str]:
188         return [i.strip() for i in spec.split(",")]
189     else:
190         raise exceptions.CommandError("Unsupported argument type: %s" % argtype)
191 
192 
193 def command(path):
194     def decorator(function):
195         @functools.wraps(function)
196         def wrapper(*args, **kwargs):
197             return function(*args, **kwargs)
198         wrapper.__dict__["command_path"] = path
199         return wrapper
200     return decorator
201
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mitmproxy/command.py b/mitmproxy/command.py
--- a/mitmproxy/command.py
+++ b/mitmproxy/command.py
@@ -190,10 +190,19 @@
         raise exceptions.CommandError("Unsupported argument type: %s" % argtype)
 
 
+def verify_arg_signature(f: typing.Callable, args: list, kwargs: dict) -> None:
+    sig = inspect.signature(f)
+    try:
+        sig.bind(*args, **kwargs)
+    except TypeError as v:
+        raise exceptions.CommandError("Argument mismatch: %s" % v.args[0])
+
+
 def command(path):
     def decorator(function):
         @functools.wraps(function)
         def wrapper(*args, **kwargs):
+            verify_arg_signature(function, args, kwargs)
             return function(*args, **kwargs)
         wrapper.__dict__["command_path"] = path
         return wrapper

{"golden_diff": "diff --git a/mitmproxy/command.py b/mitmproxy/command.py\n--- a/mitmproxy/command.py\n+++ b/mitmproxy/command.py\n@@ -190,10 +190,19 @@\n         raise exceptions.CommandError(\"Unsupported argument type: %s\" % argtype)\n \n \n+def verify_arg_signature(f: typing.Callable, args: list, kwargs: dict) -> None:\n+    sig = inspect.signature(f)\n+    try:\n+        sig.bind(*args, **kwargs)\n+    except TypeError as v:\n+        raise exceptions.CommandError(\"Argument mismatch: %s\" % v.args[0])\n+\n+\n def command(path):\n     def decorator(function):\n         @functools.wraps(function)\n         def wrapper(*args, **kwargs):\n+            verify_arg_signature(function, args, kwargs)\n             return function(*args, **kwargs)\n         wrapper.__dict__[\"command_path\"] = path\n         return wrapper\n", "issue": "command console.choose.cmd crashes when given no arguments\nEnter mitmproxy console, issue a command like:\r\n\r\n    console.choose.cmd\r\n\r\n... and press return. \n", "before_files": [{"content": "\"\"\"\n    This module manges and invokes typed commands.\n\"\"\"\nimport inspect\nimport typing\nimport shlex\nimport textwrap\nimport functools\nimport sys\n\nfrom mitmproxy.utils import typecheck\nfrom mitmproxy import exceptions\nfrom mitmproxy import flow\n\n\nCuts = typing.Sequence[\n    typing.Sequence[typing.Union[str, bytes]]\n]\n\n\ndef typename(t: type, ret: bool) -> str:\n    \"\"\"\n        Translates a type to an explanatory string. If ret is True, we're\n        looking at a return type, else we're looking at a parameter type.\n    \"\"\"\n    if issubclass(t, (str, int, bool)):\n        return t.__name__\n    elif t == typing.Sequence[flow.Flow]:\n        return \"[flow]\" if ret else \"flowspec\"\n    elif t == typing.Sequence[str]:\n        return \"[str]\"\n    elif t == Cuts:\n        return \"[cuts]\" if ret else \"cutspec\"\n    elif t == flow.Flow:\n        return \"flow\"\n    else:  # pragma: no cover\n        raise NotImplementedError(t)\n\n\nclass Command:\n    def __init__(self, manager, path, func) -> None:\n        self.path = path\n        self.manager = manager\n        self.func = func\n        sig = inspect.signature(self.func)\n        self.help = None\n        if func.__doc__:\n            txt = func.__doc__.strip()\n            self.help = \"\\n\".join(textwrap.wrap(txt))\n\n        self.has_positional = False\n        for i in sig.parameters.values():\n            # This is the kind for *args paramters\n            if i.kind == i.VAR_POSITIONAL:\n                self.has_positional = True\n        self.paramtypes = [v.annotation for v in sig.parameters.values()]\n        self.returntype = sig.return_annotation\n\n    def paramnames(self) -> typing.Sequence[str]:\n        v = [typename(i, False) for i in self.paramtypes]\n        if self.has_positional:\n            v[-1] = \"*\" + v[-1]\n        return v\n\n    def retname(self) -> str:\n        return typename(self.returntype, True) if self.returntype else \"\"\n\n    def signature_help(self) -> str:\n        params = \" \".join(self.paramnames())\n        ret = self.retname()\n        if ret:\n            ret = \" -> \" + ret\n        return \"%s %s%s\" % (self.path, params, ret)\n\n    def call(self, args: typing.Sequence[str]):\n        \"\"\"\n            Call the command with a list of arguments. At this point, all\n            arguments are strings.\n        \"\"\"\n        if not self.has_positional and (len(self.paramtypes) != len(args)):\n            raise exceptions.CommandError(\"Usage: %s\" % self.signature_help())\n\n        remainder = []  # type: typing.Sequence[str]\n        if self.has_positional:\n            remainder = args[len(self.paramtypes) - 1:]\n            args = args[:len(self.paramtypes) - 1]\n\n        pargs = []\n        for i in range(len(args)):\n            if typecheck.check_command_type(args[i], self.paramtypes[i]):\n                pargs.append(args[i])\n            else:\n                pargs.append(parsearg(self.manager, args[i], self.paramtypes[i]))\n\n        if remainder:\n            chk = typecheck.check_command_type(\n                remainder,\n                typing.Sequence[self.paramtypes[-1]]  # type: ignore\n            )\n            if chk:\n                pargs.extend(remainder)\n            else:\n                raise exceptions.CommandError(\"Invalid value type.\")\n\n        with self.manager.master.handlecontext():\n            ret = self.func(*pargs)\n\n        if not typecheck.check_command_type(ret, self.returntype):\n            raise exceptions.CommandError(\"Command returned unexpected data\")\n\n        return ret\n\n\nclass CommandManager:\n    def __init__(self, master):\n        self.master = master\n        self.commands = {}\n\n    def collect_commands(self, addon):\n        for i in dir(addon):\n            if not i.startswith(\"__\"):\n                o = getattr(addon, i)\n                if hasattr(o, \"command_path\"):\n                    self.add(o.command_path, o)\n\n    def add(self, path: str, func: typing.Callable):\n        self.commands[path] = Command(self, path, func)\n\n    def call_args(self, path, args):\n        \"\"\"\n            Call a command using a list of string arguments. May raise CommandError.\n        \"\"\"\n        if path not in self.commands:\n            raise exceptions.CommandError(\"Unknown command: %s\" % path)\n        return self.commands[path].call(args)\n\n    def call(self, cmdstr: str):\n        \"\"\"\n            Call a command using a string. May raise CommandError.\n        \"\"\"\n        parts = shlex.split(cmdstr)\n        if not len(parts) >= 1:\n            raise exceptions.CommandError(\"Invalid command: %s\" % cmdstr)\n        return self.call_args(parts[0], parts[1:])\n\n    def dump(self, out=sys.stdout) -> None:\n        cmds = list(self.commands.values())\n        cmds.sort(key=lambda x: x.signature_help())\n        for c in cmds:\n            for hl in (c.help or \"\").splitlines():\n                print(\"# \" + hl, file=out)\n            print(c.signature_help(), file=out)\n            print(file=out)\n\n\ndef parsearg(manager: CommandManager, spec: str, argtype: type) -> typing.Any:\n    \"\"\"\n        Convert a string to a argument to the appropriate type.\n    \"\"\"\n    if issubclass(argtype, str):\n        return spec\n    elif argtype == bool:\n        if spec == \"true\":\n            return True\n        elif spec == \"false\":\n            return False\n        else:\n            raise exceptions.CommandError(\n                \"Booleans are 'true' or 'false', got %s\" % spec\n            )\n    elif issubclass(argtype, int):\n        try:\n            return int(spec)\n        except ValueError as e:\n            raise exceptions.CommandError(\"Expected an integer, got %s.\" % spec)\n    elif argtype == typing.Sequence[flow.Flow]:\n        return manager.call_args(\"view.resolve\", [spec])\n    elif argtype == Cuts:\n        return manager.call_args(\"cut\", [spec])\n    elif argtype == flow.Flow:\n        flows = manager.call_args(\"view.resolve\", [spec])\n        if len(flows) != 1:\n            raise exceptions.CommandError(\n                \"Command requires one flow, specification matched %s.\" % len(flows)\n            )\n        return flows[0]\n    elif argtype == typing.Sequence[str]:\n        return [i.strip() for i in spec.split(\",\")]\n    else:\n        raise exceptions.CommandError(\"Unsupported argument type: %s\" % argtype)\n\n\ndef command(path):\n    def decorator(function):\n        @functools.wraps(function)\n        def wrapper(*args, **kwargs):\n            return function(*args, **kwargs)\n        wrapper.__dict__[\"command_path\"] = path\n        return wrapper\n    return decorator\n", "path": "mitmproxy/command.py"}], "after_files": [{"content": "\"\"\"\n    This module manges and invokes typed commands.\n\"\"\"\nimport inspect\nimport typing\nimport shlex\nimport textwrap\nimport functools\nimport sys\n\nfrom mitmproxy.utils import typecheck\nfrom mitmproxy import exceptions\nfrom mitmproxy import flow\n\n\nCuts = typing.Sequence[\n    typing.Sequence[typing.Union[str, bytes]]\n]\n\n\ndef typename(t: type, ret: bool) -> str:\n    \"\"\"\n        Translates a type to an explanatory string. If ret is True, we're\n        looking at a return type, else we're looking at a parameter type.\n    \"\"\"\n    if issubclass(t, (str, int, bool)):\n        return t.__name__\n    elif t == typing.Sequence[flow.Flow]:\n        return \"[flow]\" if ret else \"flowspec\"\n    elif t == typing.Sequence[str]:\n        return \"[str]\"\n    elif t == Cuts:\n        return \"[cuts]\" if ret else \"cutspec\"\n    elif t == flow.Flow:\n        return \"flow\"\n    else:  # pragma: no cover\n        raise NotImplementedError(t)\n\n\nclass Command:\n    def __init__(self, manager, path, func) -> None:\n        self.path = path\n        self.manager = manager\n        self.func = func\n        sig = inspect.signature(self.func)\n        self.help = None\n        if func.__doc__:\n            txt = func.__doc__.strip()\n            self.help = \"\\n\".join(textwrap.wrap(txt))\n\n        self.has_positional = False\n        for i in sig.parameters.values():\n            # This is the kind for *args paramters\n            if i.kind == i.VAR_POSITIONAL:\n                self.has_positional = True\n        self.paramtypes = [v.annotation for v in sig.parameters.values()]\n        self.returntype = sig.return_annotation\n\n    def paramnames(self) -> typing.Sequence[str]:\n        v = [typename(i, False) for i in self.paramtypes]\n        if self.has_positional:\n            v[-1] = \"*\" + v[-1]\n        return v\n\n    def retname(self) -> str:\n        return typename(self.returntype, True) if self.returntype else \"\"\n\n    def signature_help(self) -> str:\n        params = \" \".join(self.paramnames())\n        ret = self.retname()\n        if ret:\n            ret = \" -> \" + ret\n        return \"%s %s%s\" % (self.path, params, ret)\n\n    def call(self, args: typing.Sequence[str]):\n        \"\"\"\n            Call the command with a list of arguments. At this point, all\n            arguments are strings.\n        \"\"\"\n        if not self.has_positional and (len(self.paramtypes) != len(args)):\n            raise exceptions.CommandError(\"Usage: %s\" % self.signature_help())\n\n        remainder = []  # type: typing.Sequence[str]\n        if self.has_positional:\n            remainder = args[len(self.paramtypes) - 1:]\n            args = args[:len(self.paramtypes) - 1]\n\n        pargs = []\n        for i in range(len(args)):\n            if typecheck.check_command_type(args[i], self.paramtypes[i]):\n                pargs.append(args[i])\n            else:\n                pargs.append(parsearg(self.manager, args[i], self.paramtypes[i]))\n\n        if remainder:\n            chk = typecheck.check_command_type(\n                remainder,\n                typing.Sequence[self.paramtypes[-1]]  # type: ignore\n            )\n            if chk:\n                pargs.extend(remainder)\n            else:\n                raise exceptions.CommandError(\"Invalid value type.\")\n\n        with self.manager.master.handlecontext():\n            ret = self.func(*pargs)\n\n        if not typecheck.check_command_type(ret, self.returntype):\n            raise exceptions.CommandError(\"Command returned unexpected data\")\n\n        return ret\n\n\nclass CommandManager:\n    def __init__(self, master):\n        self.master = master\n        self.commands = {}\n\n    def collect_commands(self, addon):\n        for i in dir(addon):\n            if not i.startswith(\"__\"):\n                o = getattr(addon, i)\n                if hasattr(o, \"command_path\"):\n                    self.add(o.command_path, o)\n\n    def add(self, path: str, func: typing.Callable):\n        self.commands[path] = Command(self, path, func)\n\n    def call_args(self, path, args):\n        \"\"\"\n            Call a command using a list of string arguments. May raise CommandError.\n        \"\"\"\n        if path not in self.commands:\n            raise exceptions.CommandError(\"Unknown command: %s\" % path)\n        return self.commands[path].call(args)\n\n    def call(self, cmdstr: str):\n        \"\"\"\n            Call a command using a string. May raise CommandError.\n        \"\"\"\n        parts = shlex.split(cmdstr)\n        if not len(parts) >= 1:\n            raise exceptions.CommandError(\"Invalid command: %s\" % cmdstr)\n        return self.call_args(parts[0], parts[1:])\n\n    def dump(self, out=sys.stdout) -> None:\n        cmds = list(self.commands.values())\n        cmds.sort(key=lambda x: x.signature_help())\n        for c in cmds:\n            for hl in (c.help or \"\").splitlines():\n                print(\"# \" + hl, file=out)\n            print(c.signature_help(), file=out)\n            print(file=out)\n\n\ndef parsearg(manager: CommandManager, spec: str, argtype: type) -> typing.Any:\n    \"\"\"\n        Convert a string to a argument to the appropriate type.\n    \"\"\"\n    if issubclass(argtype, str):\n        return spec\n    elif argtype == bool:\n        if spec == \"true\":\n            return True\n        elif spec == \"false\":\n            return False\n        else:\n            raise exceptions.CommandError(\n                \"Booleans are 'true' or 'false', got %s\" % spec\n            )\n    elif issubclass(argtype, int):\n        try:\n            return int(spec)\n        except ValueError as e:\n            raise exceptions.CommandError(\"Expected an integer, got %s.\" % spec)\n    elif argtype == typing.Sequence[flow.Flow]:\n        return manager.call_args(\"view.resolve\", [spec])\n    elif argtype == Cuts:\n        return manager.call_args(\"cut\", [spec])\n    elif argtype == flow.Flow:\n        flows = manager.call_args(\"view.resolve\", [spec])\n        if len(flows) != 1:\n            raise exceptions.CommandError(\n                \"Command requires one flow, specification matched %s.\" % len(flows)\n            )\n        return flows[0]\n    elif argtype == typing.Sequence[str]:\n        return [i.strip() for i in spec.split(\",\")]\n    else:\n        raise exceptions.CommandError(\"Unsupported argument type: %s\" % argtype)\n\n\ndef verify_arg_signature(f: typing.Callable, args: list, kwargs: dict) -> None:\n    sig = inspect.signature(f)\n    try:\n        sig.bind(*args, **kwargs)\n    except TypeError as v:\n        raise exceptions.CommandError(\"Argument mismatch: %s\" % v.args[0])\n\n\ndef command(path):\n    def decorator(function):\n        @functools.wraps(function)\n        def wrapper(*args, **kwargs):\n            verify_arg_signature(function, args, kwargs)\n            return function(*args, **kwargs)\n        wrapper.__dict__[\"command_path\"] = path\n        return wrapper\n    return decorator\n", "path": "mitmproxy/command.py"}]}