-
Notifications
You must be signed in to change notification settings - Fork 974
Expand file tree
/
Copy pathengine.py
More file actions
329 lines (285 loc) · 11.2 KB
/
engine.py
File metadata and controls
329 lines (285 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
from __future__ import annotations
import asyncio
import re
import time
import uuid
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
from kimi_cli import logger
from kimi_cli.hooks.config import HookDef, HookEventType
from kimi_cli.hooks.runner import HookResult, run_hook
# Callback signatures for wire integration
type OnTriggered = Callable[[str, str, int], None]
"""(event, target, hook_count) -> None"""
type OnResolved = Callable[[str, str, str, str, int], None]
"""(event, target, action, reason, duration_ms) -> None"""
type OnWireHookRequest = Callable[[WireHookHandle], Awaitable[None]]
"""Called when a wire hook needs client handling. The callback should send
the request over the wire and resolve the handle when the client responds."""
@dataclass
class WireHookSubscription:
"""A client-side hook subscription registered via wire initialize."""
id: str
event: str
matcher: str = ""
timeout: int = 30
@dataclass
class WireHookHandle:
"""A pending wire hook request waiting for client response."""
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
subscription_id: str = ""
event: str = ""
target: str = ""
input_data: dict[str, Any] = field(default_factory=lambda: {})
_future: asyncio.Future[HookResult] | None = field(default=None, repr=False)
def _get_future(self) -> asyncio.Future[HookResult]:
if self._future is None:
self._future = asyncio.get_event_loop().create_future()
return self._future
async def wait(self) -> HookResult:
"""Wait for the client to respond."""
return await self._get_future()
def resolve(self, action: str = "allow", reason: str = "") -> None:
"""Resolve with client's decision."""
result = HookResult(action=action, reason=reason) # type: ignore[arg-type]
future = self._get_future()
if not future.done():
future.set_result(result)
class HookEngine:
"""Loads hook definitions and executes matching hooks in parallel.
Supports two hook sources:
- Server-side (config.toml): shell commands executed locally
- Client-side (wire subscriptions): forwarded to client via HookRequest
"""
def __init__(
self,
hooks: list[HookDef] | None = None,
cwd: str | None = None,
*,
on_triggered: OnTriggered | None = None,
on_resolved: OnResolved | None = None,
on_wire_hook: OnWireHookRequest | None = None,
):
self._hooks: list[HookDef] = list(hooks) if hooks else []
self._wire_subs: list[WireHookSubscription] = []
self._cwd = cwd
self._on_triggered = on_triggered
self._on_resolved = on_resolved
self._on_wire_hook = on_wire_hook
self._by_event: dict[str, list[HookDef]] = {}
self._wire_by_event: dict[str, list[WireHookSubscription]] = {}
self._rebuild_index()
def _rebuild_index(self) -> None:
self._by_event.clear()
for h in self._hooks:
self._by_event.setdefault(h.event, []).append(h)
self._wire_by_event.clear()
for s in self._wire_subs:
self._wire_by_event.setdefault(s.event, []).append(s)
def add_hooks(self, hooks: list[HookDef]) -> None:
"""Add server-side hooks at runtime. Rebuilds index."""
self._hooks.extend(hooks)
self._rebuild_index()
def add_wire_subscriptions(self, subs: list[WireHookSubscription]) -> None:
"""Register client-side hook subscriptions from wire initialize."""
self._wire_subs.extend(subs)
self._rebuild_index()
def set_callbacks(
self,
on_triggered: OnTriggered | None = None,
on_resolved: OnResolved | None = None,
on_wire_hook: OnWireHookRequest | None = None,
) -> None:
"""Set wire event callbacks."""
self._on_triggered = on_triggered
self._on_resolved = on_resolved
self._on_wire_hook = on_wire_hook
@property
def has_hooks(self) -> bool:
return bool(self._hooks) or bool(self._wire_subs)
def has_hooks_for(self, event: HookEventType) -> bool:
return bool(self._by_event.get(event)) or bool(self._wire_by_event.get(event))
@property
def summary(self) -> dict[str, int]:
"""Event -> total count of hooks (server + wire)."""
counts: dict[str, int] = {}
for event, hooks in self._by_event.items():
counts[event] = counts.get(event, 0) + len(hooks)
for event, subs in self._wire_by_event.items():
counts[event] = counts.get(event, 0) + len(subs)
return counts
def details(self) -> dict[str, list[dict[str, str]]]:
"""Event -> list of {matcher, command/type} for display."""
result: dict[str, list[dict[str, str]]] = {}
for event, hooks in self._by_event.items():
entries = result.setdefault(event, [])
for h in hooks:
entries.append(
{
"matcher": h.matcher or "(all)",
"source": "server",
"command": h.command,
}
)
for event, subs in self._wire_by_event.items():
entries = result.setdefault(event, [])
for s in subs:
entries.append(
{
"matcher": s.matcher or "(all)",
"source": "wire",
"command": "(client-side)",
}
)
return result
def _match_regex(self, pattern: str, value: str) -> bool:
if not pattern:
return True
try:
return bool(re.search(pattern, value))
except re.error:
logger.warning("Invalid regex in hook matcher: {}", pattern)
return False
async def trigger(
self,
event: HookEventType,
*,
matcher_value: str = "",
input_data: dict[str, Any],
) -> list[HookResult]:
"""Run all matching hooks (server + wire) in parallel."""
# --- Match server-side hooks ---
seen_commands: set[str] = set()
server_matched: list[HookDef] = []
for h in self._by_event.get(event, []):
if not self._match_regex(h.matcher, matcher_value):
continue
if h.command in seen_commands:
continue
seen_commands.add(h.command)
server_matched.append(h)
# --- Match wire subscriptions ---
wire_matched: list[WireHookSubscription] = []
for s in self._wire_by_event.get(event, []):
if not self._match_regex(s.matcher, matcher_value):
continue
wire_matched.append(s)
total = len(server_matched) + len(wire_matched)
if total == 0:
return []
try:
results = await self._execute_hooks(
event, matcher_value, server_matched, wire_matched, input_data
)
from kimi_cli.telemetry import track
has_block = any(r.action == "block" for r in results)
track("kimi_hook_triggered", event_type=event, action="block" if has_block else "allow")
return results
except Exception:
logger.warning("Hook engine error for {}, failing open", event)
return []
async def _execute_hooks(
self,
event: str,
matcher_value: str,
server_matched: list[HookDef],
wire_matched: list[WireHookSubscription],
input_data: dict[str, Any],
) -> list[HookResult]:
"""Run matched hooks and emit wire events. Separated for fail-open wrapping."""
total = len(server_matched) + len(wire_matched)
logger.debug(
"Triggering {} hooks for {} ({} server, {} wire)",
total,
event,
len(server_matched),
len(wire_matched),
)
# --- HookTriggered ---
if self._on_triggered:
try:
self._on_triggered(event, matcher_value, total)
except Exception as e:
logger.warning(
"HookTriggered callback failed for {event}: {error}, continuing",
event=event,
error=e,
)
t0 = time.monotonic()
tasks: list[asyncio.Task[HookResult]] = []
# Server-side: run shell commands
for h in server_matched:
tasks.append(
asyncio.create_task(
run_hook(h.command, input_data, timeout=h.timeout, cwd=self._cwd)
)
)
# Wire-side: send request to client, wait for response
for s in wire_matched:
tasks.append(
asyncio.create_task(
self._dispatch_wire_hook(
s.id, event, matcher_value, input_data, timeout=s.timeout
)
)
)
results = list(await asyncio.gather(*tasks))
duration_ms = int((time.monotonic() - t0) * 1000)
# Aggregate: block if any hook blocked
action = "allow"
reason = ""
for r in results:
if r.action == "block":
action = "block"
reason = r.reason
logger.warning(
"Hook blocked {event} (matcher={matcher}): {reason}",
event=event,
matcher=matcher_value,
reason=reason,
)
break
# --- HookResolved ---
if self._on_resolved:
try:
self._on_resolved(event, matcher_value, action, reason, duration_ms)
except Exception as e:
logger.warning(
"HookResolved callback failed for {event}: {error}, continuing",
event=event,
error=e,
)
return results
async def _dispatch_wire_hook(
self,
subscription_id: str,
event: str,
target: str,
input_data: dict[str, Any],
*,
timeout: int = 30,
) -> HookResult:
"""Send a hook request to the wire client and wait for response."""
if not self._on_wire_hook:
return HookResult(action="allow")
handle = WireHookHandle(
subscription_id=subscription_id,
event=event,
target=target,
input_data=input_data,
)
# Run the callback in background so timeout applies to the
# full client round-trip, not just handle.wait().
hook_task: asyncio.Task[None] = asyncio.ensure_future(self._on_wire_hook(handle))
hook_task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None)
try:
return await asyncio.wait_for(handle.wait(), timeout=timeout)
except TimeoutError:
hook_task.cancel()
logger.warning("Wire hook timed out: {} {}", event, target)
return HookResult(action="allow", timed_out=True)
except Exception as e:
hook_task.cancel()
logger.warning("Wire hook failed: {} {}: {}", event, target, e)
return HookResult(action="allow")