Skip to content
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

refactor!: uncouple agent and network protocol from hivemind protocol #24

Merged
merged 3 commits into from
Dec 28, 2024

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Dec 28, 2024

closes #21
closes #22
paves the way for #23

example implementation of custom agent protocol: JarbasHiveMind/hivemind-persona#1

Summary by CodeRabbit

  • New Features
    • Introduced OVOSProtocol for enhanced messaging framework communication.
    • Added HiveMindWebsocketProtocol for WebSocket communication and client management.
  • Improvements
    • Enhanced HiveMindService structure using dataclasses for better attribute management.
    • Updated message handling and logging for clarity within protocol handling.
  • Bug Fixes
    • Improved error handling and logging for invalid keys and protocol versions.

Copy link

coderabbitai bot commented Dec 28, 2024

Warning

Rate limit exceeded

@JarbasAl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 29a489f and 1815baa.

📒 Files selected for processing (1)
  • hivemind_core/scripts.py (2 hunks)

Walkthrough

The pull request introduces a comprehensive refactoring of the HiveMind core architecture, focusing on protocol abstraction and modularization. The changes involve creating new protocol classes (OVOSProtocol, HiveMindWebsocketProtocol), updating the HiveMindService to use dataclasses, and introducing more flexible protocol handling mechanisms. The modifications aim to decouple the network transport from the core messaging logic, allowing for more flexible communication protocols and easier extensibility of the HiveMind system.

Changes

File Changes
hivemind_core/__main__.py Updated main() function to accept agent_protocol and network_protocol parameters
hivemind_core/agents.py Added OVOSProtocol class with message handling and bus connection logic
hivemind_core/protocol.py Introduced new protocol base classes, updated HiveMindClientConnection and HiveMindListenerProtocol
hivemind_core/server.py Added HiveMindWebsocketProtocol and HiveMindTornadoWebSocket for WebSocket-based communication
hivemind_core/service.py Refactored HiveMindService to use dataclasses, removed MessageBusEventHandler

Assessment against linked issues

Objective Addressed Explanation
Abstract protocol from websockets
Support multiple transport protocols Current implementation focuses on WebSocket, but architecture allows future extensions
Use event handlers for protocol New protocol classes use event-driven approach

Poem

🐰 In the warren of code, protocols dance free,
Websockets whisper, messages leap with glee
Abstraction's magic, a rabbit's delight
HiveMind protocols now shine so bright!
Flexibility blooms like spring's first flower 🌱


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (10)
hivemind_core/agents.py (3)

20-31: Add error handling for bus connectivity
When using bus.run_in_thread() and bus.connected_event.wait(), consider a timeout or exception handling mechanism to avoid hanging indefinitely if the bus fails to connect.


33-34: Guard the catch-all bus message handler
Using the "message" event as a catch-all can cause unexpected overhead if many events flow through here. If performance becomes a concern, consider filtering or using more specific event names.


38-60: Clarify silent ignore for ESCALATE
Currently, ESCALATE messages are silently ignored. It might be beneficial to add at least a debug log or comment to explain that ignoring escalation here is intentional, preventing confusion for future maintainers.

hivemind_core/service.py (2)

38-60: Improve documentation of dataclass fields
The docstring explains the attributes well. As the service grows, consider adding short type hints or docstrings directly on each field for clearer reference in IDEs and auto-generated docs.


117-140: Scope for error handling in service run
In the run method, operations like _presence.start() or network_protocol.run() could fail unexpectedly. Consider wrapping them with try/except blocks to properly trigger error_hook and gracefully shut down the service in an emergency.

hivemind_core/server.py (2)

58-58: Remove extraneous “f” prefix
Since the string has no placeholders, remove the f to adhere to style and prevent confusion.

- LOG.info(f"generating self-signed SSL certificate")
+ LOG.info("generating self-signed SSL certificate")
🧰 Tools
🪛 Ruff (0.8.2)

58-58: f-string without any placeholders

Remove extraneous f prefix

(F541)


114-115: Use a context manager when writing cert files
Applying a with open(...) as f: pattern ensures proper resource cleanup and is generally safer.

- open(cert_path, "wb").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
- open(key_path, "wb").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
+ with open(cert_path, "wb") as cert_file_out:
+     cert_file_out.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
+ with open(key_path, "wb") as key_file_out:
+     key_file_out.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
🧰 Tools
🪛 Ruff (0.8.2)

114-114: Use a context manager for opening files

(SIM115)


115-115: Use a context manager for opening files

(SIM115)

hivemind_core/protocol.py (2)

58-60: Document send_msg and disconnect usage
These callables significantly affect the connection lifecycle. To aid maintainers, highlight their expected behaviors (sync/async, blocking, re-entrancy) in a brief docstring or comment.


226-228: Relocate assignment for agent_protocol.hm_protocol
If there is a possibility of overriding agent_protocol in sub-classes or different contexts, ensure that line 227 is performed consistently. Otherwise, it’s fine as is.

hivemind_core/__main__.py (1)

7-8: Add configuration from CLI or environment
You may consider making agent_protocol=OVOSProtocol and network_protocol=HiveMindWebsocketProtocol configurable via CLI or environment variables, so advanced users can swap protocols without modifying core code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b1e2878 and e555061.

📒 Files selected for processing (5)
  • hivemind_core/__main__.py (1 hunks)
  • hivemind_core/agents.py (1 hunks)
  • hivemind_core/protocol.py (15 hunks)
  • hivemind_core/server.py (1 hunks)
  • hivemind_core/service.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
hivemind_core/server.py

58-58: f-string without any placeholders

Remove extraneous f prefix

(F541)


114-114: Use a context manager for opening files

(SIM115)


115-115: Use a context manager for opening files

(SIM115)

hivemind_core/service.py

15-15: hivemind_core.server.HiveMindWebsocketProtocol imported but unused

Remove unused import: hivemind_core.server.HiveMindWebsocketProtocol

(F401)

🔇 Additional comments (7)
hivemind_core/agents.py (2)

17-19: Ensure config defaults handle edge cases
The default factory for config loads only the "websocket" part of the OVOS configuration. If that section is missing or malformed, you'll get an empty dictionary. Consider handling fallback or logging a warning if no valid settings are found.


78-102: Consider synchronization for self.clients
Accessing self.clients inside the loop in handle_internal_mycroft presumably happens in a safe single-threaded context. If concurrency is possible, ensure it’s thread-safe or confirm that only one event loop thread manipulates self.clients.

hivemind_core/service.py (2)

15-15: False positive from static analysis
Although Ruff suggests that HiveMindWebsocketProtocol is unused, it’s actually instantiated at line 128. You can safely ignore or suppress this warning.

🧰 Tools
🪛 Ruff (0.8.2)

15-15: hivemind_core.server.HiveMindWebsocketProtocol imported but unused

Remove unused import: hivemind_core.server.HiveMindWebsocketProtocol

(F401)


81-93: Validate _status initialization
Inside __post_init__, _status is created if missing, but no exception handling is in place if callbacks fail. Ensure these hooks can gracefully handle exceptions or potential misconfiguration to avoid partial initialization states.

hivemind_core/protocol.py (2)

88-90: Handle bus errors if handshake fails
In __post_init__, if hm_protocol fails to provide a valid private key for the handshake, the code might raise uncaught exceptions. Consider verifying the existence/validity of hm_protocol.identity.private_key before instantiating the handshake.


517-519: Leverage “agent_bus_callback” more widely
You already update the _status with the bus in HiveMindService. If the system grows, consider hooking more advanced bus monitoring logic here to keep agent-level operations well-contained.

hivemind_core/__main__.py (1)

2-3: Ensure modular usage
Passing OVOSProtocol and HiveMindWebsocketProtocol to HiveMindService is a sound approach for decoupling. As you expand with additional protocols, verify that you thoroughly handle fallback or default scenarios in the main() function.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
hivemind_core/server.py (6)

29-37: Consider concurrency safeguards for hm_protocol.
While hm_protocol is declared as a shared attribute, if different coroutines or threads modify it concurrently, potential race conditions may arise. Ensure that you apply proper synchronization if runtime mutation is expected.


58-58: Remove extraneous f prefix.
There's no placeholder in this string, so using an f-string is unnecessary and may trigger warnings.

- LOG.info(f"generating self-signed SSL certificate")
+ LOG.info("generating self-signed SSL certificate")
🧰 Tools
🪛 Ruff (0.8.2)

58-58: f-string without any placeholders

Remove extraneous f prefix

(F541)


114-115: Use context managers for file operations.
Using context managers ensures files are closed reliably, even if an error occurs.

- open(cert_path, "wb").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
- open(key_path, "wb").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
+ with open(cert_path, "wb") as f:
+     f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
+ with open(key_path, "wb") as f:
+     f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
🧰 Tools
🪛 Ruff (0.8.2)

114-114: Use a context manager for opening files

(SIM115)


115-115: Use a context manager for opening files

(SIM115)


145-161: Avoid logging sensitive message contents.
Currently, user messages (including audio or text) are logged verbosely, possibly leaking private or PII data. Consider redacting or summarizing sensitive fields in logs.


162-177: Avoid sending credentials via query parameters.
Line 166 uses a /?authorization= approach, which can be insecure because URLs may be logged. Passing credentials in headers or a secure handshake would be safer.


231-232: Validate the WebSocket origin.
Currently, check_origin() unconditionally returns True, exposing the server to potential cross-site attacks. Consider restricting or verifying trusted origins.

hivemind_core/protocol.py (1)

471-471: Remove or finalize commented-out code.
Stray commented code at this line may indicate an unfinished feature or debugging artifact. Consider clarifying or removing it.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e555061 and 29a489f.

📒 Files selected for processing (2)
  • hivemind_core/protocol.py (16 hunks)
  • hivemind_core/server.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
hivemind_core/server.py

58-58: f-string without any placeholders

Remove extraneous f prefix

(F541)


114-114: Use a context manager for opening files

(SIM115)


115-115: Use a context manager for opening files

(SIM115)

🔇 Additional comments (4)
hivemind_core/server.py (1)

129-143: Guard against invalid base64 strings.
A malformed or malicious “auth” value can break pybase64.b64decode. An exception handler or validation would prevent runtime errors.

hivemind_core/protocol.py (3)

58-60: Approve new callback attributes with concurrency in mind.
Storing send_msg and disconnect callables in the data class is clean. Just ensure they are safe to invoke across multiple coroutines or threads.


86-88: Good use of __post_init__ to initialize the handshake.
This is a concise pattern for customizing data class behavior after initialization.


171-204: Subprotocol abstraction looks good.
These new classes (_SubProtocol, AgentProtocol, NetworkProtocol) provide a clear extension pattern for specialized behaviors.

@JarbasAl JarbasAl merged commit e0c8d0c into dev Dec 28, 2024
1 of 2 checks passed
JarbasAl added a commit to JarbasHiveMind/hivemind-persona that referenced this pull request Dec 28, 2024
…#1)

* refactor!: uncouple agent and network protocol from hivemind protocol

companion to JarbasHiveMind/HiveMind-core#24

* refactor!: uncouple agent and network protocol from hivemind protocol

companion to JarbasHiveMind/HiveMind-core#24

* .
@coderabbitai coderabbitai bot mentioned this pull request Jan 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
1 participant