Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:52:50 +08:00
commit caae91ec55
17 changed files with 2063 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
# Assets
Bundled resources for websocket-server-builder skill
- [ ] template_socketio.py: Template file for a basic WebSocket server using Socket.IO.
- [ ] template_native_ws.py: Template file for a basic WebSocket server using native WebSockets.
- [ ] example_client.html: Example HTML client for testing the WebSocket server.

View File

@@ -0,0 +1,32 @@
{
"skill": {
"name": "skill-name",
"version": "1.0.0",
"enabled": true,
"settings": {
"verbose": false,
"autoActivate": true,
"toolRestrictions": true
}
},
"triggers": {
"keywords": [
"example-trigger-1",
"example-trigger-2"
],
"patterns": []
},
"tools": {
"allowed": [
"Read",
"Grep",
"Bash"
],
"restricted": []
},
"metadata": {
"author": "Plugin Author",
"category": "general",
"tags": []
}
}

View File

@@ -0,0 +1,140 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client Example</title>
<style>
/* Basic Styling */
body {
font-family: sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
width: 80%;
max-width: 600px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
}
h1 {
color: #333;
}
#messages {
margin-top: 20px;
text-align: left;
}
#message-input {
width: 70%;
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
#send-button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#send-button:hover {
background-color: #0056b3;
}
/* Responsive Design */
@media (max-width: 600px) {
.container {
width: 95%;
}
#message-input {
width: 60%;
}
}
</style>
</head>
<body>
<div class="container">
<h1>WebSocket Client</h1>
<p>Connect to WebSocket server at: <code>{{websocket_url}}</code></p>
<div id="messages">
<!-- Messages will be displayed here -->
</div>
<div>
<input type="text" id="message-input" placeholder="Enter message">
<button id="send-button">Send</button>
</div>
</div>
<script>
// JavaScript to handle WebSocket connection and messages
const websocketUrl = "{{websocket_url}}"; // Replace with your WebSocket server URL
const messagesDiv = document.getElementById('messages');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
let websocket;
function connectWebSocket() {
websocket = new WebSocket(websocketUrl);
websocket.onopen = () => {
console.log('Connected to WebSocket server');
appendMessage('Connected to server.');
};
websocket.onmessage = (event) => {
console.log('Received message:', event.data);
appendMessage('Server: ' + event.data);
};
websocket.onclose = () => {
console.log('Disconnected from WebSocket server');
appendMessage('Disconnected from server.');
};
websocket.onerror = (error) => {
console.error('WebSocket error:', error);
appendMessage('Error: ' + error);
};
}
function appendMessage(message) {
const messageElement = document.createElement('p');
messageElement.textContent = message;
messagesDiv.appendChild(messageElement);
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Auto-scroll to bottom
}
sendButton.addEventListener('click', () => {
const message = messageInput.value;
if (message) {
websocket.send(message);
appendMessage('You: ' + message);
messageInput.value = ''; // Clear the input
}
});
// Connect to the WebSocket server when the page loads
connectWebSocket();
</script>
</body>
</html>

View File

@@ -0,0 +1,28 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Claude Skill Configuration",
"type": "object",
"required": ["name", "description"],
"properties": {
"name": {
"type": "string",
"pattern": "^[a-z0-9-]+$",
"maxLength": 64,
"description": "Skill identifier (lowercase, hyphens only)"
},
"description": {
"type": "string",
"maxLength": 1024,
"description": "What the skill does and when to use it"
},
"allowed-tools": {
"type": "string",
"description": "Comma-separated list of allowed tools"
},
"version": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$",
"description": "Semantic version (x.y.z)"
}
}
}

View File

@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""
Template for a basic WebSocket server using native WebSockets.
This script provides a foundation for building real-time bidirectional
communication applications using Python's built-in `websockets` library.
It includes basic connection handling, message reception, and sending.
Example usage:
1. Install the `websockets` library: `pip install websockets`
2. Run the script: `python template_native_ws.py`
3. Connect to the server using a WebSocket client (e.g., a browser-based client).
"""
import asyncio
import websockets
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
async def handle_client(websocket, path):
"""
Handles a single WebSocket client connection.
Args:
websocket: The WebSocket connection object.
path: The path requested by the client (unused in this example).
"""
try:
logging.info(f"Client connected from {websocket.remote_address}")
async for message in websocket:
logging.info(f"Received message: {message}")
try:
# Process the message (replace with your application logic)
response = f"Server received: {message}"
await websocket.send(response)
logging.info(f"Sent message: {response}")
except Exception as e:
logging.error(f"Error processing message: {e}")
await websocket.send(f"Error: {e}")
except websockets.exceptions.ConnectionClosedError as e:
logging.info(f"Client disconnected abruptly: {e}")
except websockets.exceptions.ConnectionClosedOK as e:
logging.info(f"Client disconnected gracefully: {e}")
except Exception as e:
logging.error(f"Error handling client: {e}")
finally:
logging.info(f"Connection with {websocket.remote_address} closed.")
async def main():
"""
Starts the WebSocket server.
"""
try:
server = await websockets.serve(handle_client, "localhost", 8765)
logging.info("WebSocket server started on ws://localhost:8765")
await server.wait_closed()
except OSError as e:
logging.error(f"Could not start server: {e}")
except Exception as e:
logging.error(f"Unexpected error: {e}")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info("Server stopped by keyboard interrupt.")
except Exception as e:
logging.error(f"Unhandled exception during server startup: {e}")

View File

@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""
Template for a basic WebSocket server using Socket.IO.
This script provides a foundation for building real-time bidirectional
communication applications. It includes error handling, example usage,
and follows PEP 8 style guidelines.
"""
import os
import logging
import socketio
from aiohttp import web
# Configure logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# Initialize Socket.IO server
sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*')
# Create AIOHTTP application
app = web.Application()
# Bind Socket.IO to the application
sio.attach(app)
# Define event handlers
@sio.event
async def connect(sid, environ):
"""
Handles a new client connection.
Args:
sid (str): Session ID of the client.
environ (dict): Environment variables.
"""
logging.info(f"Client connected: {sid}")
try:
await sio.emit('my_response', {'data': 'Connected', 'count': 0}, room=sid)
except Exception as e:
logging.error(f"Error emitting connect message: {e}")
@sio.event
async def disconnect(sid):
"""
Handles a client disconnection.
Args:
sid (str): Session ID of the client.
"""
logging.info(f"Client disconnected: {sid}")
@sio.event
async def my_message(sid, message):
"""
Handles a custom message event.
Args:
sid (str): Session ID of the client.
message (str): The received message.
"""
logging.info(f"Received message from {sid}: {message}")
try:
await sio.emit('my_response', {'data': message}, room=sid)
except Exception as e:
logging.error(f"Error emitting my_response: {e}")
@sio.event
async def my_broadcast_event(sid, message):
"""
Handles a broadcast event.
Args:
sid (str): Session ID of the client.
message (str): The message to broadcast.
"""
logging.info(f"Received broadcast request from {sid}: {message}")
try:
await sio.emit('my_response', {'data': message}) # Broadcast to all clients
except Exception as e:
logging.error(f"Error emitting broadcast message: {e}")
@sio.event
async def join_room(sid, room):
"""
Handles a request to join a room.
Args:
sid (str): Session ID of the client.
room (str): The room to join.
"""
logging.info(f"Client {sid} joining room {room}")
try:
sio.enter_room(sid, room)
await sio.emit('my_response', {'data': 'Entered room: ' + room}, room=sid)
except Exception as e:
logging.error(f"Error joining room: {e}")
@sio.event
async def leave_room(sid, room):
"""
Handles a request to leave a room.
Args:
sid (str): Session ID of the client.
room (str): The room to leave.
"""
logging.info(f"Client {sid} leaving room {room}")
try:
sio.leave_room(sid, room)
await sio.emit('my_response', {'data': 'Left room: ' + room}, room=sid)
except Exception as e:
logging.error(f"Error leaving room: {e}")
async def index(request):
"""
Serves the index.html file.
Args:
request (aiohttp.web.Request): The request object.
Returns:
aiohttp.web.Response: The response object containing the HTML content.
"""
try:
with open('index.html') as f:
return web.Response(content_type='text/html', text=f.read())
except FileNotFoundError:
return web.Response(status=404, text="index.html not found")
except Exception as e:
logging.error(f"Error serving index.html: {e}")
return web.Response(status=500, text=f"Internal Server Error: {e}")
if __name__ == '__main__':
"""
Main entry point of the application.
"""
try:
# Serve static files (e.g., index.html)
app.router.add_get('/', index)
app.router.add_static('/static', './static') # Assuming a 'static' directory
# Start the web server
port = int(os.environ.get('PORT', 5000)) # Default port 5000 or from environment
logging.info(f"Starting server on port {port}")
web.run_app(app, port=port)
except Exception as e:
logging.error(f"Failed to start the server: {e}")

View File

@@ -0,0 +1,27 @@
{
"testCases": [
{
"name": "Basic activation test",
"input": "trigger phrase example",
"expected": {
"activated": true,
"toolsUsed": ["Read", "Grep"],
"success": true
}
},
{
"name": "Complex workflow test",
"input": "multi-step trigger example",
"expected": {
"activated": true,
"steps": 3,
"toolsUsed": ["Read", "Write", "Bash"],
"success": true
}
}
],
"fixtures": {
"sampleInput": "example data",
"expectedOutput": "processed result"
}
}