@agentunion/kite 1.3.2 → 1.4.0

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +200 -0
  2. package/cli.js +76 -0
  3. package/extensions/agents/assistant/entry.py +111 -1
  4. package/extensions/agents/assistant/server.py +263 -215
  5. package/extensions/channels/acp_channel/entry.py +111 -1
  6. package/extensions/channels/acp_channel/module.md +23 -22
  7. package/extensions/channels/acp_channel/server.py +263 -215
  8. package/extensions/event_hub_bench/entry.py +107 -1
  9. package/extensions/services/backup/entry.py +299 -21
  10. package/extensions/services/backup/module.md +24 -22
  11. package/extensions/services/model_service/entry.py +145 -19
  12. package/extensions/services/model_service/module.md +21 -22
  13. package/extensions/services/watchdog/entry.py +188 -25
  14. package/extensions/services/watchdog/monitor.py +144 -34
  15. package/extensions/services/web/WEBSOCKET_STATUS.md +143 -0
  16. package/extensions/services/web/config_example.py +35 -0
  17. package/extensions/services/web/config_loader.py +110 -0
  18. package/extensions/services/web/entry.py +114 -26
  19. package/extensions/services/web/module.md +35 -24
  20. package/extensions/services/web/pairing.py +250 -0
  21. package/extensions/services/web/pairing_codes.jsonl +16 -0
  22. package/extensions/services/web/relay.py +643 -0
  23. package/extensions/services/web/relay_config.json5 +67 -0
  24. package/extensions/services/web/routes/routes_management_ws.py +127 -0
  25. package/extensions/services/web/routes/routes_rpc.py +89 -0
  26. package/extensions/services/web/routes/routes_test.py +61 -0
  27. package/extensions/services/web/routes/schemas.py +0 -22
  28. package/extensions/services/web/server.py +421 -98
  29. package/extensions/services/web/static/css/style.css +67 -28
  30. package/extensions/services/web/static/index.html +234 -44
  31. package/extensions/services/web/static/js/app.js +1335 -48
  32. package/extensions/services/web/static/js/kernel-client-example.js +161 -0
  33. package/extensions/services/web/static/js/kernel-client.js +383 -0
  34. package/extensions/services/web/static/js/registry-tests.js +558 -0
  35. package/extensions/services/web/static/js/token-manager.js +175 -0
  36. package/extensions/services/web/static/pairing.html +248 -0
  37. package/extensions/services/web/static/test_registry.html +262 -0
  38. package/extensions/services/web/web_config.json5 +29 -0
  39. package/kernel/entry.py +120 -32
  40. package/kernel/event_hub.py +141 -16
  41. package/kernel/module.md +36 -33
  42. package/kernel/registry_store.py +48 -15
  43. package/kernel/rpc_router.py +120 -53
  44. package/kernel/server.py +219 -12
  45. package/kite_cli/__init__.py +3 -0
  46. package/kite_cli/__main__.py +5 -0
  47. package/kite_cli/commands/__init__.py +1 -0
  48. package/kite_cli/commands/clean.py +101 -0
  49. package/kite_cli/commands/doctor.py +35 -0
  50. package/kite_cli/commands/history.py +111 -0
  51. package/kite_cli/commands/info.py +96 -0
  52. package/kite_cli/commands/install.py +313 -0
  53. package/kite_cli/commands/list.py +143 -0
  54. package/kite_cli/commands/log.py +81 -0
  55. package/kite_cli/commands/rollback.py +88 -0
  56. package/kite_cli/commands/search.py +73 -0
  57. package/kite_cli/commands/uninstall.py +85 -0
  58. package/kite_cli/commands/update.py +118 -0
  59. package/kite_cli/core/__init__.py +1 -0
  60. package/kite_cli/core/checker.py +142 -0
  61. package/kite_cli/core/dependency.py +229 -0
  62. package/kite_cli/core/downloader.py +209 -0
  63. package/kite_cli/core/install_info.py +40 -0
  64. package/kite_cli/core/tool_installer.py +397 -0
  65. package/kite_cli/core/validator.py +78 -0
  66. package/kite_cli/main.py +289 -0
  67. package/kite_cli/utils/__init__.py +1 -0
  68. package/kite_cli/utils/i18n.py +252 -0
  69. package/kite_cli/utils/interactive.py +63 -0
  70. package/kite_cli/utils/operation_log.py +77 -0
  71. package/kite_cli/utils/paths.py +34 -0
  72. package/kite_cli/utils/version.py +308 -0
  73. package/launcher/entry.py +819 -158
  74. package/launcher/logging_setup.py +104 -0
  75. package/launcher/module.md +37 -37
  76. package/package.json +2 -1
  77. package/scripts/plan_manager.py +315 -0
  78. package/extensions/services/web/routes/routes_modules.py +0 -249
@@ -1,22 +1,23 @@
1
- ---
2
- name: acp_channel
3
- display_name: ACP Channel
4
- version: "1.0"
5
- type: channel
6
- state: enabled
7
- runtime: python
8
- entry: entry.py
9
- events:
10
- - acp_channel.test
11
- subscriptions:
12
- - module.started
13
- - module.stopped
14
- - module.shutdown
15
- ---
16
-
17
- # ACP Channel(ACP 协议通道)
18
-
19
- ACP 协议通道模块,负责接入外部消息通道。
20
-
21
- - 消息接入 — 通过 ACP 协议接收和发送消息
22
- - 事件通知 — 通过 Kernel 发布通道状态事件
1
+ ---
2
+ name: acp_channel
3
+ display_name: ACP Channel
4
+ version: '1.0'
5
+ type: channel
6
+ state: enabled
7
+ runtime: python
8
+ entry: entry.py
9
+ events:
10
+ - acp_channel.test
11
+ subscriptions:
12
+ - module.started
13
+ - module.stopped
14
+ - module.shutdown
15
+ advertise_ip: 127.0.0.1
16
+ monitor: true
17
+ ---
18
+ # ACP Channel(ACP 协议通道)
19
+
20
+ ACP 协议通道模块,负责接入外部消息通道。
21
+
22
+ - 消息接入 — 通过 ACP 协议接收和发送消息
23
+ - 事件通知 — 通过 Kernel 发布通道状态事件
@@ -1,215 +1,263 @@
1
- """
2
- ACP Channel WebSocket client.
3
- Connects to Kernel via WebSocket JSON-RPC 2.0 for event publishing and subscription.
4
- """
5
-
6
- import asyncio
7
- import json
8
- import time
9
- import uuid
10
- from datetime import datetime, timezone
11
-
12
- import websockets
13
-
14
-
15
- class AcpChannelServer:
16
-
17
- def __init__(self, token: str = "", kernel_port: int = 0, boot_t0: float = 0):
18
- self.token = token
19
- self.kernel_port = kernel_port
20
- self.boot_t0 = boot_t0
21
- self._ws_task: asyncio.Task | None = None
22
- self._test_task: asyncio.Task | None = None
23
- self._ws: object | None = None
24
- self._shutting_down = False
25
- self._start_time = time.time()
26
-
27
- async def run(self):
28
- """Main entry point: start WebSocket loop and test event loop."""
29
- if self.kernel_port:
30
- self._ws_task = asyncio.create_task(self._ws_loop())
31
- self._test_task = asyncio.create_task(self._test_event_loop())
32
-
33
- # Wait for tasks to complete
34
- tasks = [t for t in [self._ws_task, self._test_task] if t]
35
- if tasks:
36
- await asyncio.gather(*tasks, return_exceptions=True)
37
-
38
- print("[acp_channel] Shutdown complete")
39
-
40
- # ── Kernel WebSocket client ──
41
-
42
- async def _ws_loop(self):
43
- """Connect to Kernel, subscribe, register, and listen. Reconnect on failure."""
44
- retry_delay = 0.3
45
- max_delay = 5.0
46
- max_retries = 10
47
- attempt = 0
48
- while not self._shutting_down:
49
- try:
50
- await self._ws_connect()
51
- retry_delay = 0.3
52
- attempt = 0
53
- except asyncio.CancelledError:
54
- return
55
- except Exception as e:
56
- attempt += 1
57
- # Auth failure — don't retry
58
- if hasattr(e, 'rcvd') and e.rcvd is not None:
59
- code = e.rcvd.code if hasattr(e.rcvd, 'code') else 0
60
- if code in (4001, 4003):
61
- print(f"[acp_channel] Kernel 认证失败 (code {code}),退出")
62
- import sys; sys.exit(1)
63
- if attempt >= max_retries:
64
- print(f"[acp_channel] Kernel 重连失败 {max_retries} 次,退出")
65
- import sys; sys.exit(1)
66
- print(f"[acp_channel] Kernel connection error: {e}, retrying in {retry_delay:.1f}s ({attempt}/{max_retries})")
67
- self._ws = None
68
- if self._shutting_down:
69
- return
70
- await asyncio.sleep(retry_delay)
71
- retry_delay = min(retry_delay * 2, max_delay)
72
-
73
- async def _ws_connect(self):
74
- """Single WebSocket session: connect, subscribe, register, ready, receive loop."""
75
- url = f"ws://127.0.0.1:{self.kernel_port}/ws?token={self.token}&id=acp_channel"
76
- print(f"[acp_channel] Connecting to Kernel (port {self.kernel_port})")
77
- async with websockets.connect(url, open_timeout=3, ping_interval=None, ping_timeout=None, close_timeout=10) as ws:
78
- self._ws = ws
79
- elapsed = time.monotonic() - self.boot_t0 if self.boot_t0 else 0
80
- elapsed_str = f" ({elapsed:.1f}s)" if elapsed else ""
81
- print(f"[acp_channel] Connected to Kernel{elapsed_str}")
82
-
83
- # Step 1: Subscribe to events (先订阅)
84
- await self._rpc_call(ws, "event.subscribe", {
85
- "events": ["module.started", "module.stopped", "module.shutdown"],
86
- })
87
-
88
- # Step 2: Register to Kernel (再注册)
89
- await self._rpc_call(ws, "registry.register", {
90
- "module_id": "acp_channel",
91
- "module_type": "channel",
92
- "name": "ACP Channel",
93
- "events_publish": {
94
- "acp_channel.test": {},
95
- },
96
- "events_subscribe": [
97
- "module.started",
98
- "module.stopped",
99
- "module.shutdown",
100
- ],
101
- })
102
-
103
- # Step 3: Publish module.ready (every reconnect)
104
- if not self._shutting_down:
105
- await self._rpc_call(ws, "event.publish", {
106
- "event_id": str(uuid.uuid4()),
107
- "event": "module.ready",
108
- "data": {
109
- "module_id": "acp_channel",
110
- "graceful_shutdown": True,
111
- },
112
- })
113
- elapsed = time.monotonic() - self.boot_t0 if self.boot_t0 else 0
114
- elapsed_str = f" ({elapsed:.1f}s)" if elapsed else ""
115
- print(f"[acp_channel] module.ready published{elapsed_str}")
116
-
117
- # Receive loop
118
- async for raw in ws:
119
- try:
120
- msg = json.loads(raw)
121
- except (json.JSONDecodeError, TypeError):
122
- continue
123
-
124
- try:
125
- has_method = "method" in msg
126
- has_id = "id" in msg
127
-
128
- if has_method and not has_id:
129
- # JSON-RPC Notification (event delivery)
130
- params = msg.get("params", {})
131
- event_name = params.get("event", "")
132
- if event_name == "module.shutdown":
133
- data = params.get("data", {})
134
- target = data.get("module_id", "")
135
- reason = data.get("reason", "")
136
- # Handle both targeted shutdown (module_id == "acp_channel") and broadcast shutdown (no module_id or launcher_lost)
137
- if target == "acp_channel" or not target or reason == "launcher_lost":
138
- await self._handle_shutdown(ws)
139
- return
140
- elif not has_method and has_id:
141
- # JSON-RPC Response (to our RPC calls)
142
- pass
143
- except Exception as e:
144
- print(f"[acp_channel] 事件处理异常(已忽略): {e}")
145
-
146
- async def _handle_shutdown(self, ws):
147
- """Handle module.shutdown: exiting → ack → cleanup → ready → exit."""
148
- print("[acp_channel] Received module.shutdown")
149
- self._shutting_down = True
150
-
151
- # Step 0: Send module.exiting
152
- await self._rpc_call(ws, "event.publish", {
153
- "event_id": str(uuid.uuid4()),
154
- "event": "module.exiting",
155
- "data": {"module_id": "acp_channel", "action": "none"},
156
- })
157
-
158
- # Step 1: Send ack
159
- await self._rpc_call(ws, "event.publish", {
160
- "event_id": str(uuid.uuid4()),
161
- "event": "module.shutdown.ack",
162
- "data": {"module_id": "acp_channel", "estimated_cleanup": 2},
163
- })
164
- print("[acp_channel] shutdown ack sent")
165
-
166
- # Step 2: Cleanup (cancel background tasks)
167
- if self._test_task:
168
- self._test_task.cancel()
169
-
170
- # Step 3: Send ready (before closing WS!)
171
- await self._rpc_call(ws, "event.publish", {
172
- "event_id": str(uuid.uuid4()),
173
- "event": "module.shutdown.ready",
174
- "data": {"module_id": "acp_channel"},
175
- })
176
- print("[acp_channel] Shutdown ready sent")
177
-
178
- # Step 4: Exit process
179
- import sys
180
- sys.exit(0)
181
-
182
- async def _rpc_call(self, ws, method: str, params: dict = None):
183
- """Send a JSON-RPC 2.0 request."""
184
- msg = {"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": method}
185
- if params:
186
- msg["params"] = params
187
- await ws.send(json.dumps(msg))
188
-
189
- async def _publish_event(self, event: dict):
190
- """Publish an event via JSON-RPC event.publish."""
191
- if not self._ws:
192
- return
193
- try:
194
- await self._rpc_call(self._ws, "event.publish", {
195
- "event_id": str(uuid.uuid4()),
196
- "event": event.get("event", ""),
197
- "data": event.get("data", {}),
198
- })
199
- except Exception as e:
200
- print(f"[acp_channel] Failed to publish event: {e}")
201
-
202
- # ── Test event loop ──
203
-
204
- async def _test_event_loop(self):
205
- """Publish a test event every 10 seconds."""
206
- while True:
207
- await asyncio.sleep(10)
208
- await self._publish_event({
209
- "event": "acp_channel.test",
210
- "data": {
211
- "message": "test event from acp_channel",
212
- "timestamp": datetime.now(timezone.utc).isoformat(),
213
- },
214
- })
215
- print("[acp_channel] test event published")
1
+ """
2
+ ACP Channel WebSocket client.
3
+ Connects to Kernel via WebSocket JSON-RPC 2.0 for event publishing and subscription.
4
+ """
5
+
6
+ import asyncio
7
+ import json
8
+ import os
9
+ import time
10
+ import uuid
11
+ from datetime import datetime, timezone
12
+
13
+ import websockets
14
+
15
+
16
+ # System broadcast events (received by all modules, may not need handling)
17
+ SYSTEM_BROADCAST_EVENTS = {
18
+ "module.ready", "module.registered", "module.started", "module.stopped",
19
+ "module.crashed", "module.exiting", "module.offline",
20
+ "module.shutdown.ack", "module.shutdown.ready",
21
+ "system.ready", "registry.updated",
22
+ }
23
+
24
+
25
+ class AcpChannelServer:
26
+
27
+ def __init__(self, token: str = "", kernel_port: int = 0, boot_t0: float = 0):
28
+ self.token = token
29
+ self.kernel_port = kernel_port
30
+ self.boot_t0 = boot_t0
31
+ self._ws_task: asyncio.Task | None = None
32
+ self._test_task: asyncio.Task | None = None
33
+ self._ws: object | None = None
34
+ self._shutting_down = False
35
+ self._exit_code = 0 # Exit code for main() to use
36
+ self._start_time = time.time()
37
+
38
+ async def run(self):
39
+ """Main entry point: start WebSocket loop and test event loop."""
40
+ if self.kernel_port:
41
+ self._ws_task = asyncio.create_task(self._ws_loop())
42
+ self._test_task = asyncio.create_task(self._test_event_loop())
43
+
44
+ # Wait for tasks to complete
45
+ tasks = [t for t in [self._ws_task, self._test_task] if t]
46
+ if tasks:
47
+ await asyncio.gather(*tasks, return_exceptions=True)
48
+
49
+ print("[acp_channel] Shutdown complete")
50
+
51
+ # ── Kernel WebSocket client ──
52
+
53
+ async def _ws_loop(self):
54
+ """Connect to Kernel, subscribe, register, and listen. Reconnect on failure."""
55
+ retry_delay = 0.3
56
+ max_delay = 5.0
57
+ max_retries = 10
58
+ attempt = 0
59
+ while not self._shutting_down:
60
+ try:
61
+ await self._ws_connect()
62
+ retry_delay = 0.3
63
+ attempt = 0
64
+ except asyncio.CancelledError:
65
+ return
66
+ except Exception as e:
67
+ attempt += 1
68
+ # Auth failure — don't retry
69
+ if hasattr(e, 'rcvd') and e.rcvd is not None:
70
+ code = e.rcvd.code if hasattr(e.rcvd, 'code') else 0
71
+ if code in (4001, 4003):
72
+ print(f"[acp_channel] Kernel 认证失败 (code {code}),退出")
73
+ self._exit_code = 1
74
+ self._shutting_down = True
75
+ return
76
+ if attempt >= max_retries:
77
+ print(f"[acp_channel] Kernel 重连失败 {max_retries} 次,退出")
78
+ self._exit_code = 1
79
+ self._shutting_down = True
80
+ return
81
+ print(f"[acp_channel] Kernel connection error: {e}, retrying in {retry_delay:.1f}s ({attempt}/{max_retries})")
82
+ self._ws = None
83
+ if self._shutting_down:
84
+ return
85
+ await asyncio.sleep(retry_delay)
86
+ retry_delay = min(retry_delay * 2, max_delay)
87
+
88
+ async def _ws_connect(self):
89
+ """Single WebSocket session: connect, subscribe, register, ready, receive loop."""
90
+ url = f"ws://127.0.0.1:{self.kernel_port}/ws?token={self.token}&id=acp_channel"
91
+ print(f"[acp_channel] Connecting to Kernel (port {self.kernel_port})")
92
+ async with websockets.connect(url, open_timeout=3, ping_interval=20, ping_timeout=20, close_timeout=10) as ws:
93
+ self._ws = ws
94
+ elapsed = time.monotonic() - self.boot_t0 if self.boot_t0 else 0
95
+ elapsed_str = f" ({elapsed:.1f}s)" if elapsed else ""
96
+ print(f"[acp_channel] Connected to Kernel{elapsed_str}")
97
+
98
+ # Step 1: Subscribe to events (先订阅)
99
+ await self._rpc_call(ws, "event.subscribe", {
100
+ "events": ["module.started", "module.stopped", "module.shutdown"],
101
+ })
102
+
103
+ # Step 2: Register to Kernel (再注册)
104
+ await self._rpc_call(ws, "registry.register", {
105
+ "module_id": "acp_channel",
106
+ "module_type": "channel",
107
+ "name": "ACP Channel",
108
+ "events_publish": {
109
+ "acp_channel": {
110
+ "test": {},
111
+ }
112
+ },
113
+ "events_subscribe": [
114
+ "module.started",
115
+ "module.stopped",
116
+ "module.shutdown",
117
+ ],
118
+ })
119
+
120
+ # Step 3: Publish module.ready (every reconnect)
121
+ if not self._shutting_down:
122
+ await self._rpc_call(ws, "event.publish", {
123
+ "event_id": str(uuid.uuid4()),
124
+ "event": "module.ready",
125
+ "data": {
126
+ "module_id": "acp_channel",
127
+ "graceful_shutdown": True,
128
+ },
129
+ })
130
+ elapsed = time.monotonic() - self.boot_t0 if self.boot_t0 else 0
131
+ elapsed_str = f" ({elapsed:.1f}s)" if elapsed else ""
132
+ print(f"[acp_channel] module.ready published{elapsed_str}")
133
+
134
+ # Receive loop
135
+ # CRITICAL: RPC 死锁防范
136
+ # - 入站 RPC 请求必须用 create_task() 异步执行,不可 await
137
+ # - 原因:如果 handler 内部调用 rpc_call() 发出站请求,出站响应需要本接收循环来分发
138
+ # - 如果接收循环被 await handler 阻塞,出站响应永远收不到 → 超时死锁
139
+ # - 事件通知和 RPC 响应可以同步处理(它们不会反向调用 rpc_call)
140
+
141
+ # Start heartbeat loop
142
+ heartbeat_task = asyncio.create_task(self._heartbeat_loop(ws))
143
+
144
+ async for raw in ws:
145
+ try:
146
+ msg = json.loads(raw)
147
+ except (json.JSONDecodeError, TypeError):
148
+ continue
149
+
150
+ try:
151
+ has_method = "method" in msg
152
+ has_id = "id" in msg
153
+
154
+ if has_method and not has_id:
155
+ # JSON-RPC Notification (event delivery)
156
+ params = msg.get("params", {})
157
+ event_type = params.get("event", "")
158
+ data = params.get("data", {})
159
+
160
+ # Layer 1: 处理订阅的事件
161
+ if event_type == "module.shutdown":
162
+ target = data.get("module_id", "")
163
+ reason = data.get("reason", "")
164
+ # Handle both targeted shutdown (module_id == "acp_channel") and broadcast shutdown (no module_id or launcher_lost)
165
+ if target == "acp_channel" or not target or reason == "launcher_lost":
166
+ await self._handle_shutdown(ws)
167
+ return
168
+
169
+ # Layer 2: 忽略系统广播事件
170
+ if event_type in SYSTEM_BROADCAST_EVENTS:
171
+ continue
172
+
173
+ # Layer 3: 警告未知事件(仅开发环境)
174
+ if os.environ.get("KITE_ENV") == "development":
175
+ print(f"[acp_channel] Debug: Unhandled event: {event_type}")
176
+
177
+ elif not has_method and has_id:
178
+ # JSON-RPC Response (to our RPC calls)
179
+ pass
180
+ except Exception as e:
181
+ print(f"[acp_channel] 事件处理异常(已忽略): {e}")
182
+
183
+ async def _handle_shutdown(self, ws):
184
+ """Handle module.shutdown: ack → exiting → cleanup → ready → exit."""
185
+ print("[acp_channel] Received module.shutdown")
186
+ self._shutting_down = True
187
+
188
+ # Step 1: Send ack (立即确认收到)
189
+ await self._rpc_call(ws, "event.publish", {
190
+ "event_id": str(uuid.uuid4()),
191
+ "event": "module.shutdown.ack",
192
+ "data": {"module_id": "acp_channel", "estimated_cleanup": 2},
193
+ })
194
+ print("[acp_channel] shutdown ack sent")
195
+
196
+ # Step 2: Send module.exiting (开始清理)
197
+ await self._rpc_call(ws, "event.publish", {
198
+ "event_id": str(uuid.uuid4()),
199
+ "event": "module.exiting",
200
+ "data": {"module_id": "acp_channel", "action": "none"},
201
+ })
202
+
203
+ # Step 3: Cleanup (cancel background tasks)
204
+ if self._test_task:
205
+ self._test_task.cancel()
206
+
207
+ # Step 4: Send ready (清理完成)
208
+ await self._rpc_call(ws, "event.publish", {
209
+ "event_id": str(uuid.uuid4()),
210
+ "event": "module.shutdown.ready",
211
+ "data": {"module_id": "acp_channel"},
212
+ })
213
+ print("[acp_channel] Shutdown ready sent")
214
+
215
+ # Step 4: Exit process
216
+ import sys
217
+ sys.exit(0)
218
+
219
+ async def _rpc_call(self, ws, method: str, params: dict = None):
220
+ """Send a JSON-RPC 2.0 request."""
221
+ msg = {"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": method}
222
+ if params:
223
+ msg["params"] = params
224
+ await ws.send(json.dumps(msg))
225
+
226
+ async def _heartbeat_loop(self, ws):
227
+ """Send registry.heartbeat every 30 seconds to prevent TTL expiration."""
228
+ while True:
229
+ try:
230
+ await asyncio.sleep(30)
231
+ if not self._shutting_down:
232
+ await self._rpc_call(ws, "registry.heartbeat", {"module_id": "acp_channel"})
233
+ except Exception as e:
234
+ print(f"[acp_channel] Heartbeat error: {e}")
235
+ break
236
+
237
+ async def _publish_event(self, event: dict):
238
+ """Publish an event via JSON-RPC event.publish."""
239
+ if not self._ws:
240
+ return
241
+ try:
242
+ await self._rpc_call(self._ws, "event.publish", {
243
+ "event_id": str(uuid.uuid4()),
244
+ "event": event.get("event", ""),
245
+ "data": event.get("data", {}),
246
+ })
247
+ except Exception as e:
248
+ print(f"[acp_channel] Failed to publish event: {e}")
249
+
250
+ # ── Test event loop ──
251
+
252
+ async def _test_event_loop(self):
253
+ """Publish a test event every 10 seconds."""
254
+ while True:
255
+ await asyncio.sleep(10)
256
+ await self._publish_event({
257
+ "event": "acp_channel.test",
258
+ "data": {
259
+ "message": "test event from acp_channel",
260
+ "timestamp": datetime.now(timezone.utc).isoformat(),
261
+ },
262
+ })
263
+ print("[acp_channel] test event published")
@@ -35,7 +35,113 @@ TAG = "[event_hub_bench]"
35
35
 
36
36
 
37
37
  # ── Module configuration ──
38
- MODULE_NAME = "event_hub_bench"
38
+
39
+ def _load_module_config() -> dict:
40
+ """Load module configuration from module.md frontmatter.
41
+
42
+ Returns:
43
+ Dict with keys: name, preferred_port, advertise_ip
44
+
45
+ Raises:
46
+ SystemExit: If module.md is invalid or name is non-compliant
47
+ """
48
+ _this_dir = os.path.dirname(os.path.abspath(__file__))
49
+ module_md = os.path.join(_this_dir, "module.md")
50
+
51
+ # Calculate relative path for error messages
52
+ project_root = os.environ.get("KITE_PROJECT", "")
53
+ if project_root and _this_dir.startswith(project_root):
54
+ rel_path = os.path.relpath(_this_dir, project_root)
55
+ else:
56
+ rel_path = _this_dir
57
+
58
+ # Default values (will be overridden if valid config exists)
59
+ result = {
60
+ "name": "",
61
+ "preferred_port": 0,
62
+ "advertise_ip": "0.0.0.0"
63
+ }
64
+
65
+ # Check if module.md exists
66
+ if not os.path.exists(module_md):
67
+ print(f"[{rel_path}] ERROR: Invalid module configuration in module.md")
68
+ print(f" Path: {rel_path}/module.md")
69
+ print(f" Reason: File not found")
70
+ sys.exit(1)
71
+
72
+ try:
73
+ with open(module_md, encoding="utf-8") as f:
74
+ text = f.read()
75
+
76
+ # Extract YAML frontmatter (between --- markers)
77
+ import re
78
+ m = re.match(r'^---\s*\n(.*?)\n---', text, re.DOTALL)
79
+ if not m:
80
+ print(f"[{rel_path}] ERROR: Invalid module configuration in module.md")
81
+ print(f" Path: {rel_path}/module.md")
82
+ print(f" Reason: Missing YAML frontmatter")
83
+ sys.exit(1)
84
+
85
+ # Parse YAML frontmatter
86
+ try:
87
+ import yaml
88
+ fm = yaml.safe_load(m.group(1)) or {}
89
+ except ImportError:
90
+ print(f"[{rel_path}] ERROR: PyYAML not installed, cannot parse module.md")
91
+ sys.exit(1)
92
+ except Exception as e:
93
+ print(f"[{rel_path}] ERROR: Invalid module configuration in module.md")
94
+ print(f" Path: {rel_path}/module.md")
95
+ print(f" Reason: YAML parse error: {e}")
96
+ sys.exit(1)
97
+
98
+ # Validate 'name' field (required)
99
+ if "name" not in fm:
100
+ print(f"[{rel_path}] ERROR: Invalid module configuration in module.md")
101
+ print(f" Path: {rel_path}/module.md")
102
+ print(f" Reason: Missing 'name' field")
103
+ sys.exit(1)
104
+
105
+ raw_name = str(fm["name"]).strip()
106
+
107
+ if not raw_name:
108
+ print(f"[{rel_path}] ERROR: Invalid module configuration in module.md")
109
+ print(f" Path: {rel_path}/module.md")
110
+ print(f" Reason: Empty module name")
111
+ sys.exit(1)
112
+
113
+ # Validate name characters
114
+ sanitized = re.sub(r'[^a-zA-Z0-9_\-]', '', raw_name)
115
+
116
+ if sanitized != raw_name:
117
+ invalid_chars = ''.join(sorted(set(c for c in raw_name if c not in sanitized)))
118
+ print(f"[{rel_path}] ERROR: Invalid module configuration in module.md")
119
+ print(f" Path: {rel_path}/module.md")
120
+ print(f" Reason: Invalid characters in name '{raw_name}': {repr(invalid_chars)}")
121
+ sys.exit(1)
122
+
123
+ result["name"] = sanitized
124
+
125
+ # Extract optional fields
126
+ if "preferred_port" in fm:
127
+ try:
128
+ result["preferred_port"] = int(fm["preferred_port"])
129
+ except (ValueError, TypeError):
130
+ pass
131
+
132
+ if "advertise_ip" in fm:
133
+ result["advertise_ip"] = str(fm["advertise_ip"])
134
+
135
+ except SystemExit:
136
+ raise # Re-raise exit to prevent catching by outer except
137
+ except Exception as e:
138
+ print(f"[{rel_path}] ERROR: Failed to read module.md: {e}")
139
+ sys.exit(1)
140
+
141
+ return result
142
+
143
+ _module_config = _load_module_config()
144
+ MODULE_NAME = _module_config["name"]
39
145
 
40
146
 
41
147
  # ── Timestamped print + log file writer ──