ken-agent 2.0.1__tar.gz

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.
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: ken-agent
3
+ Version: 2.0.1
4
+ Summary: KEN AGENT - Autonomous Desktop AI Runner (HPD Ecosystem)
5
+ Home-page: https://api.haiphongdeveloper.com
6
+ Author: Ken Do
7
+ Author-email: admin@haiphongdeveloper.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: websockets>=11.0
14
+ Dynamic: author
15
+ Dynamic: author-email
16
+ Dynamic: classifier
17
+ Dynamic: description
18
+ Dynamic: description-content-type
19
+ Dynamic: home-page
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # KEN AGENT
25
+
26
+ > **Autonomous Desktop AI Runner** — Điều khiển máy tính từ xa qua Telegram/Zalo thuộc hệ sinh thái **HPD Developer**.
27
+
28
+ ---
29
+
30
+ ## 🚀 Cài Đặt Qua PIP
31
+
32
+ ```bash
33
+ pip install ken-agent
34
+ ```
35
+
36
+ ---
37
+
38
+ ## ⚡ Hướng Dẫn Sử Dụng
39
+
40
+ ### 1. Khởi chạy
41
+ ```bash
42
+ ken-agent
43
+ ```
44
+
45
+ ### 2. Chạy nhanh kèm Token
46
+ ```bash
47
+ ken-agent --token YOUR_API_TOKEN
48
+ ```
49
+
50
+ ### 3. Cấu hình Token vĩnh viễn
51
+ ```bash
52
+ ken-agent config --token YOUR_API_TOKEN
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 📱 Ghép Đôi Telegram
58
+ 1. Khi chạy `ken-agent`, lấy mã ghép đôi (ví dụ: `A8F3K9`).
59
+ 2. Nhắn tin tới Bot trên Telegram: `/pair A8F3K9` để liên kết và bắt đầu ra lệnh.
60
+
61
+ - **Website:** https://api.haiphongdeveloper.com
@@ -0,0 +1,38 @@
1
+ # KEN AGENT
2
+
3
+ > **Autonomous Desktop AI Runner** — Điều khiển máy tính từ xa qua Telegram/Zalo thuộc hệ sinh thái **HPD Developer**.
4
+
5
+ ---
6
+
7
+ ## 🚀 Cài Đặt Qua PIP
8
+
9
+ ```bash
10
+ pip install ken-agent
11
+ ```
12
+
13
+ ---
14
+
15
+ ## ⚡ Hướng Dẫn Sử Dụng
16
+
17
+ ### 1. Khởi chạy
18
+ ```bash
19
+ ken-agent
20
+ ```
21
+
22
+ ### 2. Chạy nhanh kèm Token
23
+ ```bash
24
+ ken-agent --token YOUR_API_TOKEN
25
+ ```
26
+
27
+ ### 3. Cấu hình Token vĩnh viễn
28
+ ```bash
29
+ ken-agent config --token YOUR_API_TOKEN
30
+ ```
31
+
32
+ ---
33
+
34
+ ## 📱 Ghép Đôi Telegram
35
+ 1. Khi chạy `ken-agent`, lấy mã ghép đôi (ví dụ: `A8F3K9`).
36
+ 2. Nhắn tin tới Bot trên Telegram: `/pair A8F3K9` để liên kết và bắt đầu ra lệnh.
37
+
38
+ - **Website:** https://api.haiphongdeveloper.com
@@ -0,0 +1,4 @@
1
+ """
2
+ KEN AGENT Core Module
3
+ """
4
+ from .cli import main
@@ -0,0 +1,240 @@
1
+ import os
2
+ import sys
3
+ import json
4
+ import time
5
+ import asyncio
6
+ import argparse
7
+ import subprocess
8
+
9
+ try:
10
+ import websockets
11
+ except ImportError:
12
+ try:
13
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "--break-system-packages", "--quiet", "websockets"])
14
+ import websockets
15
+ except Exception:
16
+ pass
17
+
18
+ APP_DIR = os.path.expanduser("~/.ken-agent")
19
+ os.makedirs(APP_DIR, exist_ok=True)
20
+ CONFIG_FILE = os.path.join(APP_DIR, "config.json")
21
+ DEFAULT_SERVER_URL = "wss://api.haiphongdeveloper.com/ws/hermes-relay"
22
+
23
+ def load_config():
24
+ if os.path.exists(CONFIG_FILE):
25
+ try:
26
+ with open(CONFIG_FILE, "r", encoding="utf-8") as f:
27
+ return json.load(f)
28
+ except Exception:
29
+ pass
30
+ return {"server_url": DEFAULT_SERVER_URL, "token": "", "device_name": "My-Computer"}
31
+
32
+ def save_config(config_data):
33
+ with open(CONFIG_FILE, "w", encoding="utf-8") as f:
34
+ json.dump(config_data, f, indent=2, ensure_ascii=False)
35
+ print(f"✅ Đã lưu cấu hình tại: {CONFIG_FILE}")
36
+
37
+ async def run_command_on_system(command):
38
+ try:
39
+ if sys.platform == "win32":
40
+ proc = await asyncio.create_subprocess_exec(
41
+ "powershell.exe", "-NoProfile", "-Command", command,
42
+ stdout=asyncio.subprocess.PIPE,
43
+ stderr=asyncio.subprocess.PIPE
44
+ )
45
+ elif sys.platform == "darwin":
46
+ if command.startswith("osascript:") or command.startswith("apple:"):
47
+ script = command.split(":", 1)[1].strip()
48
+ proc = await asyncio.create_subprocess_exec(
49
+ "osascript", "-e", script,
50
+ stdout=asyncio.subprocess.PIPE,
51
+ stderr=asyncio.subprocess.PIPE
52
+ )
53
+ else:
54
+ proc = await asyncio.create_subprocess_shell(
55
+ command,
56
+ stdout=asyncio.subprocess.PIPE,
57
+ stderr=asyncio.subprocess.PIPE,
58
+ executable="/bin/zsh"
59
+ )
60
+ else:
61
+ proc = await asyncio.create_subprocess_shell(
62
+ command,
63
+ stdout=asyncio.subprocess.PIPE,
64
+ stderr=asyncio.subprocess.PIPE,
65
+ executable="/bin/bash"
66
+ )
67
+
68
+ stdout, stderr = await proc.communicate()
69
+ out = stdout.decode('utf-8', errors='ignore').strip()
70
+ err = stderr.decode('utf-8', errors='ignore').strip()
71
+
72
+ if proc.returncode == 0:
73
+ return out if out else "✅ Lệnh thực thi thành công (Không có output)."
74
+ else:
75
+ return f"⚠️ Lỗi (Mã {proc.returncode}):\n{err if err else out}"
76
+ except Exception as e:
77
+ return f"❌ Lỗi thực thi hệ thống: {str(e)}"
78
+
79
+ async def handle_agent_task(prompt):
80
+ prompt_strip = prompt.strip()
81
+ prompt_lower = prompt_strip.lower()
82
+
83
+ if prompt_lower.startswith("cmd:") or prompt_lower.startswith("run:"):
84
+ cmd = prompt_strip.split(":", 1)[1].strip()
85
+ return await run_command_on_system(cmd)
86
+
87
+ if sys.platform == "darwin" and prompt_lower.startswith("open:"):
88
+ app = prompt_strip.split(":", 1)[1].strip()
89
+ return await run_command_on_system(f"open -a '{app}'")
90
+
91
+ if sys.platform == "darwin" and prompt_lower.startswith("notify:"):
92
+ msg = prompt_strip.split(":", 1)[1].strip()
93
+ return await run_command_on_system(f'osascript -e \'display notification "{msg}" with title "KEN AGENT"\'')
94
+
95
+ return await run_command_on_system(prompt_strip)
96
+
97
+ async def start_relay_loop(token, server_url):
98
+ full_url = f"{server_url}?token={token}"
99
+
100
+ print("\n" + "=" * 65)
101
+ print(" 🚀 KEN AGENT - TRỢ LÝ AI ĐIỀU KHIỂN TỰ HÀNH (PyPI CLI)")
102
+ print(f" 🌐 Relay Server: {server_url}")
103
+ print(f" 🔑 Token: {token[:8]}...{token[-4:] if len(token) > 12 else ''}")
104
+ print(f" 💻 Hệ điều hành: {sys.platform.upper()}")
105
+ print("=" * 65)
106
+
107
+ retry_count = 0
108
+ while True:
109
+ try:
110
+ print(f"\n🔄 Đang kết nối tới Relay Server...")
111
+ async with websockets.connect(full_url, ping_interval=20, ping_timeout=20) as ws:
112
+ retry_count = 0
113
+ print("⚡ [ONLINE] Đã kết nối thành công tới KEN AGENT Hub!\n")
114
+
115
+ async for message in ws:
116
+ try:
117
+ data = json.loads(message)
118
+ except Exception:
119
+ continue
120
+
121
+ msg_type = data.get("type")
122
+
123
+ if msg_type == "INIT_SUCCESS":
124
+ name = data.get("name", "Khách hàng")
125
+ code = data.get("pairing_code")
126
+ paired = data.get("paired_channels", [])
127
+
128
+ print("┌" + "─" * 63 + "┐")
129
+ print(f"│ 👤 Tài khoản: {name:<46} │")
130
+ if code:
131
+ print(f"│ 👉 MÃ GHÉP ĐÔI CỦA BẠN: [ \033[1;32m{code}\033[0m ] │")
132
+ print("│ 📌 Mở Telegram/Zalo và nhắn: /pair " + f"{code:<27} │")
133
+ else:
134
+ print(f"│ ✅ Trạng thái: Đã kết nối với {len(paired)} kênh chat. │")
135
+ for p in paired:
136
+ print(f"│ • {p.get('platform').upper()}: {p.get('user_name')} ({p.get('user_channel_id')})")
137
+ print("└" + "─" * 63 + "┘")
138
+
139
+ elif msg_type == "PAIR_SUCCESS":
140
+ print(f"\n🎉 [GHÉP ĐÔI THÀNH CÔNG] Đã liên kết với {data.get('platform').upper()}: {data.get('user_name')}!")
141
+
142
+ elif msg_type == "EXECUTE_TASK":
143
+ task_id = data.get("task_id")
144
+ platform = data.get("platform")
145
+ user_channel_id = data.get("user_channel_id")
146
+ prompt = data.get("prompt")
147
+ sender = data.get("sender", {})
148
+
149
+ print(f"\n📥 [NHẬN TÁC VỤ] [{platform.upper()}] {sender.get('user_name', 'User')}: {prompt}")
150
+
151
+ output = await handle_agent_task(prompt)
152
+ print(f"📤 [KẾT QUẢ]: {output[:120]}..." if len(output) > 120 else f"📤 [KẾT QUẢ]: {output}")
153
+
154
+ await ws.send(json.dumps({
155
+ "type": "TASK_RESPONSE",
156
+ "task_id": task_id,
157
+ "platform": platform,
158
+ "user_channel_id": user_channel_id,
159
+ "text": output
160
+ }))
161
+
162
+ except websockets.exceptions.InvalidStatusCode as e:
163
+ if e.status_code == 401:
164
+ print("\n❌ Lỗi: Token không hợp lệ hoặc đã hết hạn!")
165
+ print("👉 Vui lòng kiểm tra lại Token tại https://api.haiphongdeveloper.com")
166
+ sys.exit(1)
167
+ print(f"⚠️ Lỗi kết nối HTTP {e.status_code}. Thử lại sau 5s...")
168
+ await asyncio.sleep(5)
169
+ except Exception as e:
170
+ retry_count += 1
171
+ wait_time = min(retry_count * 2, 10)
172
+ print(f"⚠️ Mất kết nối ({str(e)}). Tự động kết nối lại sau {wait_time}s...")
173
+ await asyncio.sleep(wait_time)
174
+
175
+ def main():
176
+ parser = argparse.ArgumentParser(
177
+ prog="ken-agent",
178
+ description="KEN AGENT CLI - Trợ lý AI tự hành điều khiển máy tính qua Telegram/Zalo"
179
+ )
180
+ subparsers = parser.add_subparsers(dest="action", help="Lệnh thao tác")
181
+
182
+ start_parser = subparsers.add_parser("start", help="Khởi động KEN AGENT Runner")
183
+ start_parser.add_argument("--token", "-t", type=str, help="API Token tài khoản của bạn")
184
+ start_parser.add_argument("--server", "-s", type=str, help="URL Relay Server")
185
+
186
+ cfg_parser = subparsers.add_parser("config", help="Cấu hình Token hoặc Server URL")
187
+ cfg_parser.add_argument("--token", "-t", type=str, help="Lưu Token tài khoản")
188
+ cfg_parser.add_argument("--server", "-s", type=str, help="Lưu Relay Server URL")
189
+ cfg_parser.add_argument("--show", action="store_true", help="Hiển thị cấu hình hiện tại")
190
+
191
+ parser.add_argument("--token", "-t", type=str, help="API Token để chạy nhanh")
192
+ parser.add_argument("--version", "-v", action="version", version="KEN AGENT v2.0.0 (HPD Ecosystem 2026)")
193
+
194
+ args = parser.parse_args()
195
+ config = load_config()
196
+
197
+ if args.action == "config":
198
+ if args.show:
199
+ print("\n📋 CẤU HÌNH KEN AGENT HIỆN TẠI:")
200
+ print(f" • File cấu hình : {CONFIG_FILE}")
201
+ print(f" • Server URL : {config.get('server_url', DEFAULT_SERVER_URL)}")
202
+ tok = config.get('token', '')
203
+ print(f" • Token : {tok[:8]}...{tok[-4:] if len(tok) > 12 else ''}" if tok else " • Token : (Chưa cấu hình)")
204
+ return
205
+ if args.token:
206
+ config["token"] = args.token.strip()
207
+ if args.server:
208
+ config["server_url"] = args.server.strip()
209
+ save_config(config)
210
+ return
211
+
212
+ token = args.token or getattr(args, "token", None) or config.get("token", "")
213
+ server_url = getattr(args, "server", None) or config.get("server_url", DEFAULT_SERVER_URL)
214
+
215
+ if not token or token == "YOUR_CLIENT_TOKEN_HERE":
216
+ print("\n" + "=" * 60)
217
+ print(" ⚡ CHÀO MỪNG BẠN ĐẾN VỚI KEN AGENT")
218
+ print("=" * 60)
219
+ print("👉 Chưa tìm thấy API Token trên máy của bạn.")
220
+ print("📌 Hãy nhập API Token từ https://api.haiphongdeveloper.com để bắt đầu:\n")
221
+ try:
222
+ token_input = input("🔑 Nhập API Token: ").strip()
223
+ if token_input:
224
+ config["token"] = token_input
225
+ save_config(config)
226
+ token = token_input
227
+ else:
228
+ print("❌ Không có Token được nhập. Hủy khởi động.")
229
+ sys.exit(1)
230
+ except (KeyboardInterrupt, EOFError):
231
+ print("\n👋 Đã thoát.")
232
+ sys.exit(0)
233
+
234
+ try:
235
+ asyncio.run(start_relay_loop(token, server_url))
236
+ except KeyboardInterrupt:
237
+ print("\n👋 Đã dừng KEN AGENT.")
238
+
239
+ if __name__ == "__main__":
240
+ main()
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: ken-agent
3
+ Version: 2.0.1
4
+ Summary: KEN AGENT - Autonomous Desktop AI Runner (HPD Ecosystem)
5
+ Home-page: https://api.haiphongdeveloper.com
6
+ Author: Ken Do
7
+ Author-email: admin@haiphongdeveloper.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: websockets>=11.0
14
+ Dynamic: author
15
+ Dynamic: author-email
16
+ Dynamic: classifier
17
+ Dynamic: description
18
+ Dynamic: description-content-type
19
+ Dynamic: home-page
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # KEN AGENT
25
+
26
+ > **Autonomous Desktop AI Runner** — Điều khiển máy tính từ xa qua Telegram/Zalo thuộc hệ sinh thái **HPD Developer**.
27
+
28
+ ---
29
+
30
+ ## 🚀 Cài Đặt Qua PIP
31
+
32
+ ```bash
33
+ pip install ken-agent
34
+ ```
35
+
36
+ ---
37
+
38
+ ## ⚡ Hướng Dẫn Sử Dụng
39
+
40
+ ### 1. Khởi chạy
41
+ ```bash
42
+ ken-agent
43
+ ```
44
+
45
+ ### 2. Chạy nhanh kèm Token
46
+ ```bash
47
+ ken-agent --token YOUR_API_TOKEN
48
+ ```
49
+
50
+ ### 3. Cấu hình Token vĩnh viễn
51
+ ```bash
52
+ ken-agent config --token YOUR_API_TOKEN
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 📱 Ghép Đôi Telegram
58
+ 1. Khi chạy `ken-agent`, lấy mã ghép đôi (ví dụ: `A8F3K9`).
59
+ 2. Nhắn tin tới Bot trên Telegram: `/pair A8F3K9` để liên kết và bắt đầu ra lệnh.
60
+
61
+ - **Website:** https://api.haiphongdeveloper.com
@@ -0,0 +1,10 @@
1
+ README.md
2
+ setup.py
3
+ ken_agent/__init__.py
4
+ ken_agent/cli.py
5
+ ken_agent.egg-info/PKG-INFO
6
+ ken_agent.egg-info/SOURCES.txt
7
+ ken_agent.egg-info/dependency_links.txt
8
+ ken_agent.egg-info/entry_points.txt
9
+ ken_agent.egg-info/requires.txt
10
+ ken_agent.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ken-agent = ken_agent.cli:main
@@ -0,0 +1 @@
1
+ websockets>=11.0
@@ -0,0 +1 @@
1
+ ken_agent
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,27 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="ken-agent",
5
+ version="2.0.1",
6
+ description="KEN AGENT - Autonomous Desktop AI Runner (HPD Ecosystem)",
7
+ long_description=open("README.md", "r", encoding="utf-8").read(),
8
+ long_description_content_type="text/markdown",
9
+ author="Ken Do",
10
+ author_email="admin@haiphongdeveloper.com",
11
+ url="https://api.haiphongdeveloper.com",
12
+ packages=find_packages(),
13
+ install_requires=[
14
+ "websockets>=11.0",
15
+ ],
16
+ entry_points={
17
+ "console_scripts": [
18
+ "ken-agent=ken_agent.cli:main",
19
+ ],
20
+ },
21
+ classifiers=[
22
+ "Programming Language :: Python :: 3",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Operating System :: OS Independent",
25
+ ],
26
+ python_requires=">=3.8",
27
+ )