hackagent 0.1.0__py3-none-any.whl
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.
- hackagent/__init__.py +23 -0
- hackagent/agent.py +193 -0
- hackagent/api/__init__.py +1 -0
- hackagent/api/agent/__init__.py +1 -0
- hackagent/api/agent/agent_create.py +340 -0
- hackagent/api/agent/agent_destroy.py +136 -0
- hackagent/api/agent/agent_list.py +234 -0
- hackagent/api/agent/agent_partial_update.py +354 -0
- hackagent/api/agent/agent_retrieve.py +227 -0
- hackagent/api/agent/agent_update.py +354 -0
- hackagent/api/attack/__init__.py +1 -0
- hackagent/api/attack/attack_create.py +264 -0
- hackagent/api/attack/attack_destroy.py +140 -0
- hackagent/api/attack/attack_list.py +242 -0
- hackagent/api/attack/attack_partial_update.py +278 -0
- hackagent/api/attack/attack_retrieve.py +235 -0
- hackagent/api/attack/attack_update.py +278 -0
- hackagent/api/key/__init__.py +1 -0
- hackagent/api/key/key_create.py +168 -0
- hackagent/api/key/key_destroy.py +97 -0
- hackagent/api/key/key_list.py +158 -0
- hackagent/api/key/key_retrieve.py +150 -0
- hackagent/api/prompt/__init__.py +1 -0
- hackagent/api/prompt/prompt_create.py +160 -0
- hackagent/api/prompt/prompt_destroy.py +98 -0
- hackagent/api/prompt/prompt_list.py +173 -0
- hackagent/api/prompt/prompt_partial_update.py +174 -0
- hackagent/api/prompt/prompt_retrieve.py +151 -0
- hackagent/api/prompt/prompt_update.py +174 -0
- hackagent/api/result/__init__.py +1 -0
- hackagent/api/result/result_create.py +160 -0
- hackagent/api/result/result_destroy.py +98 -0
- hackagent/api/result/result_list.py +233 -0
- hackagent/api/result/result_partial_update.py +178 -0
- hackagent/api/result/result_retrieve.py +151 -0
- hackagent/api/result/result_trace_create.py +178 -0
- hackagent/api/result/result_update.py +174 -0
- hackagent/api/run/__init__.py +1 -0
- hackagent/api/run/run_create.py +172 -0
- hackagent/api/run/run_destroy.py +104 -0
- hackagent/api/run/run_list.py +260 -0
- hackagent/api/run/run_partial_update.py +186 -0
- hackagent/api/run/run_result_create.py +178 -0
- hackagent/api/run/run_retrieve.py +163 -0
- hackagent/api/run/run_run_tests_create.py +172 -0
- hackagent/api/run/run_update.py +186 -0
- hackagent/attacks/AdvPrefix/README.md +7 -0
- hackagent/attacks/AdvPrefix/__init__.py +0 -0
- hackagent/attacks/AdvPrefix/completer.py +438 -0
- hackagent/attacks/AdvPrefix/config.py +59 -0
- hackagent/attacks/AdvPrefix/preprocessing.py +521 -0
- hackagent/attacks/AdvPrefix/scorer.py +259 -0
- hackagent/attacks/AdvPrefix/scorer_parser.py +498 -0
- hackagent/attacks/AdvPrefix/selector.py +246 -0
- hackagent/attacks/AdvPrefix/step1_generate.py +324 -0
- hackagent/attacks/AdvPrefix/step4_compute_ce.py +293 -0
- hackagent/attacks/AdvPrefix/step6_get_completions.py +387 -0
- hackagent/attacks/AdvPrefix/step7_evaluate_responses.py +289 -0
- hackagent/attacks/AdvPrefix/step8_aggregate_evaluations.py +177 -0
- hackagent/attacks/AdvPrefix/step9_select_prefixes.py +59 -0
- hackagent/attacks/AdvPrefix/utils.py +192 -0
- hackagent/attacks/__init__.py +6 -0
- hackagent/attacks/advprefix.py +1136 -0
- hackagent/attacks/base.py +50 -0
- hackagent/attacks/strategies.py +539 -0
- hackagent/branding.py +143 -0
- hackagent/client.py +328 -0
- hackagent/errors.py +31 -0
- hackagent/logger.py +67 -0
- hackagent/models/__init__.py +71 -0
- hackagent/models/agent.py +240 -0
- hackagent/models/agent_request.py +169 -0
- hackagent/models/agent_type_enum.py +12 -0
- hackagent/models/attack.py +154 -0
- hackagent/models/attack_request.py +82 -0
- hackagent/models/evaluation_status_enum.py +14 -0
- hackagent/models/organization_minimal.py +68 -0
- hackagent/models/paginated_agent_list.py +123 -0
- hackagent/models/paginated_attack_list.py +123 -0
- hackagent/models/paginated_prompt_list.py +123 -0
- hackagent/models/paginated_result_list.py +123 -0
- hackagent/models/paginated_run_list.py +123 -0
- hackagent/models/paginated_user_api_key_list.py +123 -0
- hackagent/models/patched_agent_request.py +176 -0
- hackagent/models/patched_attack_request.py +92 -0
- hackagent/models/patched_prompt_request.py +162 -0
- hackagent/models/patched_result_request.py +237 -0
- hackagent/models/patched_run_request.py +138 -0
- hackagent/models/prompt.py +226 -0
- hackagent/models/prompt_request.py +155 -0
- hackagent/models/result.py +294 -0
- hackagent/models/result_list_evaluation_status.py +14 -0
- hackagent/models/result_request.py +232 -0
- hackagent/models/run.py +233 -0
- hackagent/models/run_list_status.py +12 -0
- hackagent/models/run_request.py +133 -0
- hackagent/models/status_enum.py +12 -0
- hackagent/models/step_type_enum.py +14 -0
- hackagent/models/trace.py +121 -0
- hackagent/models/trace_request.py +94 -0
- hackagent/models/user_api_key.py +201 -0
- hackagent/models/user_api_key_request.py +73 -0
- hackagent/models/user_profile_minimal.py +76 -0
- hackagent/py.typed +1 -0
- hackagent/router/__init__.py +11 -0
- hackagent/router/adapters/__init__.py +5 -0
- hackagent/router/adapters/google_adk.py +658 -0
- hackagent/router/adapters/litellm_adapter.py +290 -0
- hackagent/router/base.py +48 -0
- hackagent/router/router.py +753 -0
- hackagent/types.py +46 -0
- hackagent/utils.py +61 -0
- hackagent/vulnerabilities/__init__.py +0 -0
- hackagent-0.1.0.dist-info/LICENSE +202 -0
- hackagent-0.1.0.dist-info/METADATA +173 -0
- hackagent-0.1.0.dist-info/RECORD +117 -0
- hackagent-0.1.0.dist-info/WHEEL +4 -0
hackagent/branding.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
from rich.console import Console
|
|
2
|
+
from rich.panel import Panel
|
|
3
|
+
from rich.text import Text
|
|
4
|
+
# Align is no longer needed for the main panel
|
|
5
|
+
# from rich.align import Align
|
|
6
|
+
|
|
7
|
+
# ASCII Art definitions for "HACKAGENT" (7 lines high)
|
|
8
|
+
# Using '|||', '///', '\\\', '___' for strokes, ' ' for spaces.
|
|
9
|
+
|
|
10
|
+
LETTER_H = [
|
|
11
|
+
r"||| |||",
|
|
12
|
+
r"||| |||",
|
|
13
|
+
r"||| |||",
|
|
14
|
+
r"|||||||||",
|
|
15
|
+
r"||| |||",
|
|
16
|
+
r"||| |||",
|
|
17
|
+
r"||| |||",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
LETTER_A = [
|
|
21
|
+
r" ///\\\ ",
|
|
22
|
+
r" /// \\\ ",
|
|
23
|
+
r"/// \\\ ",
|
|
24
|
+
r"||||||||||| ",
|
|
25
|
+
r"||| ||| ",
|
|
26
|
+
r"||| ||| ",
|
|
27
|
+
r"||| ||| ",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
LETTER_C = [
|
|
31
|
+
r" /////// ",
|
|
32
|
+
r" /// ",
|
|
33
|
+
r"||| ",
|
|
34
|
+
r"||| ",
|
|
35
|
+
r"||| ",
|
|
36
|
+
r" \\\ ",
|
|
37
|
+
r" \\\\\\\ ",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
LETTER_K = [
|
|
41
|
+
r"||| /// ",
|
|
42
|
+
r"||| /// ",
|
|
43
|
+
r"||| /// ",
|
|
44
|
+
r"|||||| ",
|
|
45
|
+
r"||| \\\ ",
|
|
46
|
+
r"||| \\\ ",
|
|
47
|
+
r"||| \\\ ",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
LETTER_G = [
|
|
51
|
+
r" //////// ",
|
|
52
|
+
r" /// ",
|
|
53
|
+
r"||| ",
|
|
54
|
+
r"||| |||||",
|
|
55
|
+
r"||| |||",
|
|
56
|
+
r" \\\ /// ",
|
|
57
|
+
r" \\\\//// ",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
LETTER_E = [
|
|
61
|
+
r"|||||||||",
|
|
62
|
+
r"||| ",
|
|
63
|
+
r"||| ",
|
|
64
|
+
r"|||||||||",
|
|
65
|
+
r"||| ",
|
|
66
|
+
r"||| ",
|
|
67
|
+
r"|||||||||",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
LETTER_N = [
|
|
71
|
+
r"||| |||",
|
|
72
|
+
r"||||\ |||",
|
|
73
|
+
r"||| \\ |||",
|
|
74
|
+
r"||| \\ |||",
|
|
75
|
+
r"||| \\|||",
|
|
76
|
+
r"||| \|||",
|
|
77
|
+
r"||| |||",
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
LETTER_T = [
|
|
81
|
+
r"|||||||||||",
|
|
82
|
+
r" ||| ",
|
|
83
|
+
r" ||| ",
|
|
84
|
+
r" ||| ",
|
|
85
|
+
r" ||| ",
|
|
86
|
+
r" ||| ",
|
|
87
|
+
r" ||| ",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Map letters to their ASCII art
|
|
92
|
+
CHAR_MAP = {
|
|
93
|
+
"H": LETTER_H,
|
|
94
|
+
"A": LETTER_A,
|
|
95
|
+
"C": LETTER_C,
|
|
96
|
+
"K": LETTER_K,
|
|
97
|
+
"G": LETTER_G,
|
|
98
|
+
"E": LETTER_E,
|
|
99
|
+
"N": LETTER_N,
|
|
100
|
+
"T": LETTER_T,
|
|
101
|
+
" ": [r" "] * 7, # Reduced space width (e.g., 4 spaces)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def generate_block_text(text: str, char_map: dict) -> str:
|
|
106
|
+
"""Generates a single multi-line string for the block text."""
|
|
107
|
+
output_lines = [""] * 7 # Assuming all letters are 7 lines high
|
|
108
|
+
letter_spacing = " " # Reduced to one space between letters
|
|
109
|
+
|
|
110
|
+
for i, char_in_text in enumerate(text.upper()):
|
|
111
|
+
# Default to space art if char not in map (should not happen for HACKAGENT)
|
|
112
|
+
char_art_lines = char_map.get(char_in_text, char_map[" "])
|
|
113
|
+
for line_num in range(7):
|
|
114
|
+
if (
|
|
115
|
+
i > 0
|
|
116
|
+
): # Add spacing BEFORE the character, but not for the first character
|
|
117
|
+
output_lines[line_num] += letter_spacing
|
|
118
|
+
output_lines[line_num] += char_art_lines[line_num]
|
|
119
|
+
|
|
120
|
+
return "\n".join(output_lines)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def display_hackagent_splash():
|
|
124
|
+
"""Displays the HackAgent splash screen with HUGE block text, using slashes and more compact spacing."""
|
|
125
|
+
console = Console()
|
|
126
|
+
|
|
127
|
+
hack_text_str = generate_block_text("HACK", CHAR_MAP)
|
|
128
|
+
agent_text_str = generate_block_text("AGENT", CHAR_MAP)
|
|
129
|
+
|
|
130
|
+
full_block_text_str = f"{hack_text_str}\n\n{agent_text_str}"
|
|
131
|
+
|
|
132
|
+
title_content = Text(full_block_text_str, style="bold dark_red")
|
|
133
|
+
|
|
134
|
+
splash_panel = Panel(
|
|
135
|
+
title_content,
|
|
136
|
+
# title="[dim]Welcome to[/dim]", # Title removed by user previously
|
|
137
|
+
border_style="red",
|
|
138
|
+
padding=(2, 2),
|
|
139
|
+
expand=False,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
console.print(splash_panel)
|
|
143
|
+
console.print()
|
hackagent/client.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import ssl
|
|
2
|
+
from typing import Any, Optional, Union
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
from attrs import define, evolve, field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# New: Custom HTTP client to fix multipart boundary issues
|
|
9
|
+
class MultipartFixClient(httpx.Client):
|
|
10
|
+
def request(
|
|
11
|
+
self, method: str, url: Union[str, httpx.URL], **kwargs: Any
|
|
12
|
+
) -> httpx.Response:
|
|
13
|
+
# Check if this is a multipart request being prepared by openapi-python-client
|
|
14
|
+
# The key indicators are the presence of 'files' in kwargs and a manually set
|
|
15
|
+
# Content-Type header that might be missing the boundary.
|
|
16
|
+
headers = kwargs.get("headers")
|
|
17
|
+
if kwargs.get("files") is not None and headers is not None:
|
|
18
|
+
content_type = headers.get("Content-Type")
|
|
19
|
+
# If Content-Type is exactly "multipart/form-data" (without a boundary),
|
|
20
|
+
# httpx might not overwrite it correctly. We remove it to let httpx
|
|
21
|
+
# generate the full header including the boundary from the 'files' kwarg.
|
|
22
|
+
if content_type == "multipart/form-data":
|
|
23
|
+
# Create a new dict for headers to avoid modifying the original in an unexpected way
|
|
24
|
+
new_headers = {k: v for k, v in headers.items() if k != "Content-Type"}
|
|
25
|
+
kwargs["headers"] = new_headers
|
|
26
|
+
# If Content-Type includes a boundary but is still problematic,
|
|
27
|
+
# more specific checks might be needed, but usually httpx handles it if 'files' is present
|
|
28
|
+
# and no conflicting Content-Type is explicitly set without a boundary.
|
|
29
|
+
|
|
30
|
+
return super().request(method, url, **kwargs)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# New: Async version of the custom client
|
|
34
|
+
class AsyncMultipartFixClient(httpx.AsyncClient):
|
|
35
|
+
async def request(
|
|
36
|
+
self, method: str, url: Union[str, httpx.URL], **kwargs: Any
|
|
37
|
+
) -> httpx.Response:
|
|
38
|
+
headers = kwargs.get("headers")
|
|
39
|
+
if kwargs.get("files") is not None and headers is not None:
|
|
40
|
+
content_type = headers.get("Content-Type")
|
|
41
|
+
if content_type == "multipart/form-data":
|
|
42
|
+
new_headers = {k: v for k, v in headers.items() if k != "Content-Type"}
|
|
43
|
+
kwargs["headers"] = new_headers
|
|
44
|
+
return await super().request(method, url, **kwargs)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@define
|
|
48
|
+
class Client:
|
|
49
|
+
"""A class for keeping track of data related to the API
|
|
50
|
+
|
|
51
|
+
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
|
|
52
|
+
|
|
53
|
+
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
|
|
54
|
+
|
|
55
|
+
``cookies``: A dictionary of cookies to be sent with every request
|
|
56
|
+
|
|
57
|
+
``headers``: A dictionary of headers to be sent with every request
|
|
58
|
+
|
|
59
|
+
``timeout``: The maximum amount of a time a request can take. API functions will raise
|
|
60
|
+
httpx.TimeoutException if this is exceeded.
|
|
61
|
+
|
|
62
|
+
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
|
|
63
|
+
but can be set to False for testing purposes.
|
|
64
|
+
|
|
65
|
+
``follow_redirects``: Whether or not to follow redirects. Default value is False.
|
|
66
|
+
|
|
67
|
+
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
Attributes:
|
|
71
|
+
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
|
|
72
|
+
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
|
|
73
|
+
argument to the constructor.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
|
|
77
|
+
_base_url: str = field(alias="base_url")
|
|
78
|
+
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
|
|
79
|
+
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
|
|
80
|
+
_timeout: Optional[httpx.Timeout] = field(
|
|
81
|
+
default=None, kw_only=True, alias="timeout"
|
|
82
|
+
)
|
|
83
|
+
_verify_ssl: Union[str, bool, ssl.SSLContext] = field(
|
|
84
|
+
default=True, kw_only=True, alias="verify_ssl"
|
|
85
|
+
)
|
|
86
|
+
_follow_redirects: bool = field(
|
|
87
|
+
default=False, kw_only=True, alias="follow_redirects"
|
|
88
|
+
)
|
|
89
|
+
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
|
|
90
|
+
_client: Optional[httpx.Client] = field(default=None, init=False)
|
|
91
|
+
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
|
|
92
|
+
|
|
93
|
+
def with_headers(self, headers: dict[str, str]) -> "Client":
|
|
94
|
+
"""Get a new client matching this one with additional headers"""
|
|
95
|
+
if self._client is not None:
|
|
96
|
+
self._client.headers.update(headers)
|
|
97
|
+
if self._async_client is not None:
|
|
98
|
+
self._async_client.headers.update(headers)
|
|
99
|
+
return evolve(self, headers={**self._headers, **headers})
|
|
100
|
+
|
|
101
|
+
def with_cookies(self, cookies: dict[str, str]) -> "Client":
|
|
102
|
+
"""Get a new client matching this one with additional cookies"""
|
|
103
|
+
if self._client is not None:
|
|
104
|
+
self._client.cookies.update(cookies)
|
|
105
|
+
if self._async_client is not None:
|
|
106
|
+
self._async_client.cookies.update(cookies)
|
|
107
|
+
return evolve(self, cookies={**self._cookies, **cookies})
|
|
108
|
+
|
|
109
|
+
def with_timeout(self, timeout: httpx.Timeout) -> "Client":
|
|
110
|
+
"""Get a new client matching this one with a new timeout (in seconds)"""
|
|
111
|
+
if self._client is not None:
|
|
112
|
+
self._client.timeout = timeout
|
|
113
|
+
if self._async_client is not None:
|
|
114
|
+
self._async_client.timeout = timeout
|
|
115
|
+
return evolve(self, timeout=timeout)
|
|
116
|
+
|
|
117
|
+
def set_httpx_client(self, client: httpx.Client) -> "Client":
|
|
118
|
+
"""Manually set the underlying httpx.Client
|
|
119
|
+
|
|
120
|
+
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
|
|
121
|
+
"""
|
|
122
|
+
self._client = client
|
|
123
|
+
return self
|
|
124
|
+
|
|
125
|
+
def get_httpx_client(self) -> httpx.Client:
|
|
126
|
+
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
|
|
127
|
+
if self._client is None:
|
|
128
|
+
self._client = httpx.Client(
|
|
129
|
+
base_url=self._base_url,
|
|
130
|
+
cookies=self._cookies,
|
|
131
|
+
headers=self._headers,
|
|
132
|
+
timeout=self._timeout,
|
|
133
|
+
verify=self._verify_ssl,
|
|
134
|
+
follow_redirects=self._follow_redirects,
|
|
135
|
+
**self._httpx_args,
|
|
136
|
+
)
|
|
137
|
+
return self._client
|
|
138
|
+
|
|
139
|
+
def __enter__(self) -> "Client":
|
|
140
|
+
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
|
|
141
|
+
self.get_httpx_client().__enter__()
|
|
142
|
+
return self
|
|
143
|
+
|
|
144
|
+
def __exit__(self, *args: Any, **kwargs: Any) -> None:
|
|
145
|
+
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
|
|
146
|
+
self.get_httpx_client().__exit__(*args, **kwargs)
|
|
147
|
+
|
|
148
|
+
def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":
|
|
149
|
+
"""Manually the underlying httpx.AsyncClient
|
|
150
|
+
|
|
151
|
+
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
|
|
152
|
+
"""
|
|
153
|
+
self._async_client = async_client
|
|
154
|
+
return self
|
|
155
|
+
|
|
156
|
+
def get_async_httpx_client(self) -> httpx.AsyncClient:
|
|
157
|
+
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
|
|
158
|
+
if self._async_client is None:
|
|
159
|
+
self._async_client = httpx.AsyncClient(
|
|
160
|
+
base_url=self._base_url,
|
|
161
|
+
cookies=self._cookies,
|
|
162
|
+
headers=self._headers,
|
|
163
|
+
timeout=self._timeout,
|
|
164
|
+
verify=self._verify_ssl,
|
|
165
|
+
follow_redirects=self._follow_redirects,
|
|
166
|
+
**self._httpx_args,
|
|
167
|
+
)
|
|
168
|
+
return self._async_client
|
|
169
|
+
|
|
170
|
+
async def __aenter__(self) -> "Client":
|
|
171
|
+
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
|
|
172
|
+
await self.get_async_httpx_client().__aenter__()
|
|
173
|
+
return self
|
|
174
|
+
|
|
175
|
+
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
|
|
176
|
+
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
|
|
177
|
+
await self.get_async_httpx_client().__aexit__(*args, **kwargs)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@define
|
|
181
|
+
class AuthenticatedClient:
|
|
182
|
+
"""A Client which has been authenticated for use on secured endpoints
|
|
183
|
+
|
|
184
|
+
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
|
|
185
|
+
|
|
186
|
+
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
|
|
187
|
+
|
|
188
|
+
``cookies``: A dictionary of cookies to be sent with every request
|
|
189
|
+
|
|
190
|
+
``headers``: A dictionary of headers to be sent with every request
|
|
191
|
+
|
|
192
|
+
``timeout``: The maximum amount of a time a request can take. API functions will raise
|
|
193
|
+
httpx.TimeoutException if this is exceeded.
|
|
194
|
+
|
|
195
|
+
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
|
|
196
|
+
but can be set to False for testing purposes.
|
|
197
|
+
|
|
198
|
+
``follow_redirects``: Whether or not to follow redirects. Default value is False.
|
|
199
|
+
|
|
200
|
+
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
Attributes:
|
|
204
|
+
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
|
|
205
|
+
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
|
|
206
|
+
argument to the constructor.
|
|
207
|
+
token: The token to use for authentication
|
|
208
|
+
prefix: The prefix to use for the Authorization header
|
|
209
|
+
auth_header_name: The name of the Authorization header
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
token: str
|
|
213
|
+
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
|
|
214
|
+
_base_url: str = field(
|
|
215
|
+
default="https://hackagent-webapp-260146888364.europe-west1.run.app/",
|
|
216
|
+
alias="base_url",
|
|
217
|
+
)
|
|
218
|
+
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
|
|
219
|
+
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
|
|
220
|
+
_timeout: Optional[httpx.Timeout] = field(
|
|
221
|
+
default=None, kw_only=True, alias="timeout"
|
|
222
|
+
)
|
|
223
|
+
_verify_ssl: Union[str, bool, ssl.SSLContext] = field(
|
|
224
|
+
default=True, kw_only=True, alias="verify_ssl"
|
|
225
|
+
)
|
|
226
|
+
_follow_redirects: bool = field(
|
|
227
|
+
default=False, kw_only=True, alias="follow_redirects"
|
|
228
|
+
)
|
|
229
|
+
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
|
|
230
|
+
_client: Optional[httpx.Client] = field(default=None, init=False)
|
|
231
|
+
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
|
|
232
|
+
|
|
233
|
+
prefix: str = "Bearer"
|
|
234
|
+
auth_header_name: str = "Authorization"
|
|
235
|
+
|
|
236
|
+
def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
|
|
237
|
+
"""Get a new client matching this one with additional headers"""
|
|
238
|
+
if self._client is not None:
|
|
239
|
+
self._client.headers.update(headers)
|
|
240
|
+
if self._async_client is not None:
|
|
241
|
+
self._async_client.headers.update(headers)
|
|
242
|
+
return evolve(self, headers={**self._headers, **headers})
|
|
243
|
+
|
|
244
|
+
def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
|
|
245
|
+
"""Get a new client matching this one with additional cookies"""
|
|
246
|
+
if self._client is not None:
|
|
247
|
+
self._client.cookies.update(cookies)
|
|
248
|
+
if self._async_client is not None:
|
|
249
|
+
self._async_client.cookies.update(cookies)
|
|
250
|
+
return evolve(self, cookies={**self._cookies, **cookies})
|
|
251
|
+
|
|
252
|
+
def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
|
|
253
|
+
"""Get a new client matching this one with a new timeout (in seconds)"""
|
|
254
|
+
if self._client is not None:
|
|
255
|
+
self._client.timeout = timeout
|
|
256
|
+
if self._async_client is not None:
|
|
257
|
+
self._async_client.timeout = timeout
|
|
258
|
+
return evolve(self, timeout=timeout)
|
|
259
|
+
|
|
260
|
+
def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":
|
|
261
|
+
"""Manually set the underlying httpx.Client. Should be MultipartFixClient or compatible."""
|
|
262
|
+
if not isinstance(client, MultipartFixClient):
|
|
263
|
+
# Or log a warning, or be more flexible depending on desired strictness
|
|
264
|
+
pass # Consider raising TypeError if strict type is required
|
|
265
|
+
self._client = client
|
|
266
|
+
return self
|
|
267
|
+
|
|
268
|
+
def get_httpx_client(self) -> httpx.Client:
|
|
269
|
+
"""Get the underlying httpx.Client, constructing a new MultipartFixClient if not previously set"""
|
|
270
|
+
if self._client is None:
|
|
271
|
+
# Prepare auth headers to be part of the initial headers for MultipartFixClient
|
|
272
|
+
request_headers = (
|
|
273
|
+
self._headers.copy()
|
|
274
|
+
) # Start with base headers passed to AuthenticatedClient
|
|
275
|
+
auth_value = f"{self.prefix} {self.token}" if self.prefix else self.token
|
|
276
|
+
request_headers[self.auth_header_name] = auth_value
|
|
277
|
+
|
|
278
|
+
self._client = MultipartFixClient( # Use the custom client
|
|
279
|
+
base_url=self._base_url,
|
|
280
|
+
cookies=self._cookies,
|
|
281
|
+
headers=request_headers, # Pass combined headers
|
|
282
|
+
timeout=self._timeout,
|
|
283
|
+
verify=self._verify_ssl,
|
|
284
|
+
follow_redirects=self._follow_redirects,
|
|
285
|
+
**self._httpx_args,
|
|
286
|
+
)
|
|
287
|
+
return self._client
|
|
288
|
+
|
|
289
|
+
def __enter__(self) -> "AuthenticatedClient":
|
|
290
|
+
self.get_httpx_client().__enter__()
|
|
291
|
+
return self
|
|
292
|
+
|
|
293
|
+
def __exit__(self, *args: Any, **kwargs: Any) -> None:
|
|
294
|
+
self.get_httpx_client().__exit__(*args, **kwargs)
|
|
295
|
+
|
|
296
|
+
def set_async_httpx_client(
|
|
297
|
+
self, async_client: httpx.AsyncClient
|
|
298
|
+
) -> "AuthenticatedClient":
|
|
299
|
+
"""Manually set the underlying httpx.AsyncClient. Should be AsyncMultipartFixClient or compatible."""
|
|
300
|
+
if not isinstance(async_client, AsyncMultipartFixClient):
|
|
301
|
+
pass # Consider raising TypeError
|
|
302
|
+
self._async_client = async_client
|
|
303
|
+
return self
|
|
304
|
+
|
|
305
|
+
def get_async_httpx_client(self) -> httpx.AsyncClient:
|
|
306
|
+
"""Get the underlying httpx.AsyncClient, constructing new AsyncMultipartFixClient if not previously set"""
|
|
307
|
+
if self._async_client is None:
|
|
308
|
+
request_headers = self._headers.copy()
|
|
309
|
+
auth_value = f"{self.prefix} {self.token}" if self.prefix else self.token
|
|
310
|
+
request_headers[self.auth_header_name] = auth_value
|
|
311
|
+
|
|
312
|
+
self._async_client = AsyncMultipartFixClient( # Use the custom async client
|
|
313
|
+
base_url=self._base_url,
|
|
314
|
+
cookies=self._cookies,
|
|
315
|
+
headers=request_headers,
|
|
316
|
+
timeout=self._timeout,
|
|
317
|
+
verify=self._verify_ssl,
|
|
318
|
+
follow_redirects=self._follow_redirects,
|
|
319
|
+
**self._httpx_args,
|
|
320
|
+
)
|
|
321
|
+
return self._async_client
|
|
322
|
+
|
|
323
|
+
async def __aenter__(self) -> "AuthenticatedClient":
|
|
324
|
+
await self.get_async_httpx_client().__aenter__()
|
|
325
|
+
return self
|
|
326
|
+
|
|
327
|
+
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
|
|
328
|
+
await self.get_async_httpx_client().__aexit__(*args, **kwargs)
|
hackagent/errors.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Contains shared errors types that can be raised from API functions"""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class HackAgentError(Exception):
|
|
5
|
+
"""Base exception for all HackAgent library specific errors."""
|
|
6
|
+
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ApiError(HackAgentError):
|
|
11
|
+
"""Represents an error returned by the API or an issue with API communication."""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnexpectedStatusError(ApiError):
|
|
17
|
+
"""Raised when an API response has an unexpected HTTP status code."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, status_code: int, content: bytes):
|
|
20
|
+
self.status_code = status_code
|
|
21
|
+
self.content = content
|
|
22
|
+
super().__init__(
|
|
23
|
+
f"Unexpected status code: {status_code}, content: {content.decode('utf-8', errors='replace')}"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"HackAgentError",
|
|
29
|
+
"ApiError",
|
|
30
|
+
"UnexpectedStatusError",
|
|
31
|
+
]
|
hackagent/logger.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from rich.logging import RichHandler
|
|
4
|
+
|
|
5
|
+
_rich_handler_configured_for_package = False
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def setup_package_logging(
|
|
9
|
+
logger_name: str = "hackagent", default_level_str: str = "INFO"
|
|
10
|
+
):
|
|
11
|
+
"""Configures RichHandler for the specified logger if not already set."""
|
|
12
|
+
global _rich_handler_configured_for_package
|
|
13
|
+
|
|
14
|
+
package_logger = logging.getLogger(logger_name)
|
|
15
|
+
|
|
16
|
+
if logger_name == "hackagent" and _rich_handler_configured_for_package:
|
|
17
|
+
return
|
|
18
|
+
|
|
19
|
+
has_console_handler = any(
|
|
20
|
+
isinstance(h, logging.StreamHandler) for h in package_logger.handlers
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
if not has_console_handler:
|
|
24
|
+
log_level_env = os.getenv(
|
|
25
|
+
f"{logger_name.upper()}_LOG_LEVEL", default_level_str
|
|
26
|
+
).upper()
|
|
27
|
+
level = getattr(logging, log_level_env, logging.INFO)
|
|
28
|
+
package_logger.setLevel(level)
|
|
29
|
+
|
|
30
|
+
rich_handler = RichHandler(
|
|
31
|
+
show_time=True,
|
|
32
|
+
show_level=True,
|
|
33
|
+
show_path=False,
|
|
34
|
+
markup=True,
|
|
35
|
+
rich_tracebacks=True,
|
|
36
|
+
tracebacks_show_locals=False,
|
|
37
|
+
)
|
|
38
|
+
package_logger.addHandler(rich_handler)
|
|
39
|
+
package_logger.propagate = False # Avoid duplicate logs with root logger
|
|
40
|
+
|
|
41
|
+
if logger_name == "hackagent":
|
|
42
|
+
_rich_handler_configured_for_package = True
|
|
43
|
+
# Set default levels for common noisy libraries
|
|
44
|
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
45
|
+
logging.getLogger("litellm").setLevel(logging.WARNING)
|
|
46
|
+
# Add other libraries here if needed, e.g.:
|
|
47
|
+
# logging.getLogger("another_library").setLevel(logging.WARNING)
|
|
48
|
+
|
|
49
|
+
# package_logger.debug(f"RichHandler configured for '{logger_name}' logger at level {level}.")
|
|
50
|
+
|
|
51
|
+
elif any(isinstance(h, RichHandler) for h in package_logger.handlers):
|
|
52
|
+
if logger_name == "hackagent":
|
|
53
|
+
_rich_handler_configured_for_package = True
|
|
54
|
+
|
|
55
|
+
return package_logger
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def get_logger(name: str) -> logging.Logger:
|
|
59
|
+
"""
|
|
60
|
+
Retrieves a logger instance.
|
|
61
|
+
If the logger is 'hackagent' or starts with 'hackagent.',
|
|
62
|
+
it ensures the package logging is set up.
|
|
63
|
+
"""
|
|
64
|
+
if name == "hackagent" or name.startswith("hackagent."):
|
|
65
|
+
# Ensure base "hackagent" logger is configured first
|
|
66
|
+
setup_package_logging(logger_name="hackagent")
|
|
67
|
+
return logging.getLogger(name)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Contains all the data models used in inputs/outputs"""
|
|
2
|
+
|
|
3
|
+
from .agent import Agent
|
|
4
|
+
from .agent_request import AgentRequest
|
|
5
|
+
from .agent_type_enum import AgentTypeEnum
|
|
6
|
+
from .attack import Attack
|
|
7
|
+
from .attack_request import AttackRequest
|
|
8
|
+
from .evaluation_status_enum import EvaluationStatusEnum
|
|
9
|
+
from .organization_minimal import OrganizationMinimal
|
|
10
|
+
from .paginated_agent_list import PaginatedAgentList
|
|
11
|
+
from .paginated_attack_list import PaginatedAttackList
|
|
12
|
+
from .paginated_prompt_list import PaginatedPromptList
|
|
13
|
+
from .paginated_result_list import PaginatedResultList
|
|
14
|
+
from .paginated_run_list import PaginatedRunList
|
|
15
|
+
from .paginated_user_api_key_list import PaginatedUserAPIKeyList
|
|
16
|
+
from .patched_agent_request import PatchedAgentRequest
|
|
17
|
+
from .patched_attack_request import PatchedAttackRequest
|
|
18
|
+
from .patched_prompt_request import PatchedPromptRequest
|
|
19
|
+
from .patched_result_request import PatchedResultRequest
|
|
20
|
+
from .patched_run_request import PatchedRunRequest
|
|
21
|
+
from .prompt import Prompt
|
|
22
|
+
from .prompt_request import PromptRequest
|
|
23
|
+
from .result import Result
|
|
24
|
+
from .result_list_evaluation_status import ResultListEvaluationStatus
|
|
25
|
+
from .result_request import ResultRequest
|
|
26
|
+
from .run import Run
|
|
27
|
+
from .run_list_status import RunListStatus
|
|
28
|
+
from .run_request import RunRequest
|
|
29
|
+
from .status_enum import StatusEnum
|
|
30
|
+
from .step_type_enum import StepTypeEnum
|
|
31
|
+
from .trace import Trace
|
|
32
|
+
from .trace_request import TraceRequest
|
|
33
|
+
from .user_api_key import UserAPIKey
|
|
34
|
+
from .user_api_key_request import UserAPIKeyRequest
|
|
35
|
+
from .user_profile_minimal import UserProfileMinimal
|
|
36
|
+
|
|
37
|
+
__all__ = (
|
|
38
|
+
"Agent",
|
|
39
|
+
"AgentRequest",
|
|
40
|
+
"AgentTypeEnum",
|
|
41
|
+
"Attack",
|
|
42
|
+
"AttackRequest",
|
|
43
|
+
"EvaluationStatusEnum",
|
|
44
|
+
"OrganizationMinimal",
|
|
45
|
+
"PaginatedAgentList",
|
|
46
|
+
"PaginatedAttackList",
|
|
47
|
+
"PaginatedPromptList",
|
|
48
|
+
"PaginatedResultList",
|
|
49
|
+
"PaginatedRunList",
|
|
50
|
+
"PaginatedUserAPIKeyList",
|
|
51
|
+
"PatchedAgentRequest",
|
|
52
|
+
"PatchedAttackRequest",
|
|
53
|
+
"PatchedPromptRequest",
|
|
54
|
+
"PatchedResultRequest",
|
|
55
|
+
"PatchedRunRequest",
|
|
56
|
+
"Prompt",
|
|
57
|
+
"PromptRequest",
|
|
58
|
+
"Result",
|
|
59
|
+
"ResultListEvaluationStatus",
|
|
60
|
+
"ResultRequest",
|
|
61
|
+
"Run",
|
|
62
|
+
"RunListStatus",
|
|
63
|
+
"RunRequest",
|
|
64
|
+
"StatusEnum",
|
|
65
|
+
"StepTypeEnum",
|
|
66
|
+
"Trace",
|
|
67
|
+
"TraceRequest",
|
|
68
|
+
"UserAPIKey",
|
|
69
|
+
"UserAPIKeyRequest",
|
|
70
|
+
"UserProfileMinimal",
|
|
71
|
+
)
|