-
Notifications
You must be signed in to change notification settings - Fork 0
PoC: Local Scan #55
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
henchaves
wants to merge
8
commits into
main
Choose a base branch
from
poc/local-scan
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
PoC: Local Scan #55
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6bc6397
feat: add local scan with WebSocket support
henchaves eb4bbb8
lint files
henchaves a39c61b
replace websocket with polling mechanism
henchaves 138a274
clean up poll mechanism
henchaves 8ca73f7
update docstrings and comments
henchaves b50da72
reduce code duplication
henchaves 77599c8
fix issues raised by gemini
henchaves 8ced29d
Merge branch 'main' into poc/local-scan
henchaves File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| """Polling client for local-agent scan execution.""" | ||
|
|
||
| import time | ||
| import asyncio | ||
| import inspect | ||
| import logging | ||
| from typing import Any, Callable, Awaitable | ||
|
|
||
| import httpx | ||
|
|
||
| from ..types.chat import ChatMessage | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _TERMINAL_STATES = frozenset({"finished", "error", "canceled"}) | ||
|
|
||
|
|
||
| def _normalize_output(value: Any) -> dict[str, object]: | ||
| from ._helpers_types import normalize_agent_output | ||
|
|
||
| return normalize_agent_output(value).to_dict() | ||
|
|
||
|
|
||
| def _parse_messages(raw_messages: list[dict[str, Any]]) -> list[ChatMessage]: | ||
| return [ChatMessage(role=m["role"], content=m.get("content", "")) for m in raw_messages] | ||
|
|
||
|
|
||
| def run_poll_scan( | ||
| base_url: str, | ||
| api_key: str, | ||
| scan_id: str, | ||
| agent: Callable[[list[ChatMessage]], Any], | ||
| http_client: httpx.Client, | ||
| poll_interval: float = 0.5, | ||
| ) -> None: | ||
| """Poll for invocations, call the local agent, submit responses. | ||
|
|
||
| Blocks until the scan reaches a terminal state. | ||
| """ | ||
| headers = {"X-API-Key": api_key} | ||
| url = f"{base_url}/v2/scans/{scan_id}/invocations" | ||
|
|
||
| while True: | ||
| resp = http_client.get(url, params={"status": "pending"}, headers=headers) | ||
| resp.raise_for_status() | ||
| data = resp.json()["data"] | ||
|
|
||
| for inv in data["invocations"]: | ||
| messages = _parse_messages(inv["messages"]) | ||
| try: | ||
| body: dict[str, Any] = {"output": _normalize_output(agent(messages))} | ||
| except Exception as exc: | ||
| logger.exception("Agent invocation failed") | ||
| body = {"error": {"message": str(exc)}} | ||
|
|
||
| http_client.post(f"{url}/{inv['id']}/respond", json=body, headers=headers).raise_for_status() | ||
|
|
||
| if data["scan_status"] in _TERMINAL_STATES: | ||
| break | ||
|
|
||
| time.sleep(poll_interval) | ||
|
|
||
|
|
||
| async def arun_poll_scan( | ||
| base_url: str, | ||
| api_key: str, | ||
| scan_id: str, | ||
| agent: Callable[[list[ChatMessage]], Any | Awaitable[Any]], | ||
| http_client: httpx.AsyncClient, | ||
| poll_interval: float = 0.5, | ||
| ) -> None: | ||
| """Async version of the polling loop.""" | ||
| headers = {"X-API-Key": api_key} | ||
| url = f"{base_url}/v2/scans/{scan_id}/invocations" | ||
|
|
||
| while True: | ||
| resp = await http_client.get(url, params={"status": "pending"}, headers=headers) | ||
| resp.raise_for_status() | ||
| data = resp.json()["data"] | ||
|
|
||
| async def _process(inv: dict[str, Any]) -> None: | ||
| messages = _parse_messages(inv["messages"]) | ||
| try: | ||
| result = agent(messages) | ||
| if inspect.isawaitable(result): | ||
| result = await result | ||
| body: dict[str, Any] = {"output": _normalize_output(result)} | ||
| except Exception as exc: | ||
| logger.exception("Agent invocation failed") | ||
| body = {"error": {"message": str(exc)}} | ||
|
henchaves marked this conversation as resolved.
|
||
|
|
||
| (await http_client.post(f"{url}/{inv['id']}/respond", json=body, headers=headers)).raise_for_status() | ||
|
|
||
| await asyncio.gather(*(_process(inv) for inv in data["invocations"])) | ||
|
|
||
| if data["scan_status"] in _TERMINAL_STATES: | ||
| break | ||
|
|
||
| await asyncio.sleep(poll_interval) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.