keska-agent-kit 0.1.0__py3-none-any.whl

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,26 @@
1
+ from keska_agent_kit.env import MatrixIdentity, from_env
2
+ from keska_agent_kit.session import AgentKit, ChatMessage, ConversationInfo, ReasoningNote, RoomDelivery
3
+ from keska_agent_kit.wire.constants import SCHEMA_V
4
+ from keska_agent_kit.wire.envelope import (
5
+ VersionMismatchError,
6
+ assert_readable,
7
+ live_reasoning,
8
+ map_run,
9
+ resume_content,
10
+ )
11
+
12
+ __all__ = [
13
+ "SCHEMA_V",
14
+ "VersionMismatchError",
15
+ "assert_readable",
16
+ "map_run",
17
+ "live_reasoning",
18
+ "resume_content",
19
+ "MatrixIdentity",
20
+ "from_env",
21
+ "AgentKit",
22
+ "ChatMessage",
23
+ "ConversationInfo",
24
+ "ReasoningNote",
25
+ "RoomDelivery",
26
+ ]
keska_agent_kit/acp.py ADDED
@@ -0,0 +1,560 @@
1
+ """One ACP process. The kit is the client on its stdio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Protocol
11
+
12
+ from keska_agent_kit.matrix import txn
13
+ from keska_agent_kit.model import ChatMessage
14
+ from keska_agent_kit.transcript import messages_by_room, novel_user_lines
15
+ from keska_agent_kit.wire.constants import SYNC_WAIT_MS
16
+ from keska_agent_kit.wire.kinds import EnvelopeKind, ReasoningMode, Role, SessionScope
17
+
18
+ PERMISSION_MS = 60_000
19
+
20
+
21
+ class AcpError(RuntimeError):
22
+ """The ACP process rejected a request or closed its stdout."""
23
+
24
+
25
+ class AcpClient:
26
+ """Newline JSON-RPC. Requests we send, and requests the process sends back."""
27
+
28
+ def __init__(self) -> None:
29
+ self._proc: asyncio.subprocess.Process | None = None
30
+ self._reader: asyncio.StreamReader | None = None
31
+ self._writer: asyncio.StreamWriter | None = None
32
+ self._next = 1
33
+ self._write_lock = asyncio.Lock()
34
+ self._pending: dict[str, tuple[object, asyncio.Future]] = {}
35
+ self._reader_task: asyncio.Task | None = None
36
+ self.drop_updates = False
37
+ self.on_update = None
38
+ self.on_permission = None
39
+
40
+ async def start(self, command: list[str]) -> None:
41
+ """Spawn the ACP process. stdout is the protocol. stderr is discarded."""
42
+ self._proc = await asyncio.create_subprocess_exec(
43
+ *command,
44
+ stdin=asyncio.subprocess.PIPE,
45
+ stdout=asyncio.subprocess.PIPE,
46
+ stderr=asyncio.subprocess.DEVNULL,
47
+ )
48
+ self._reader = self._proc.stdout
49
+ self._writer = self._proc.stdin
50
+ self._reader_task = asyncio.create_task(self._read())
51
+
52
+ async def close(self) -> None:
53
+ """Stop the process. A prompt still waiting ends with an error."""
54
+ if self._reader_task is not None:
55
+ self._reader_task.cancel()
56
+ try:
57
+ await self._reader_task
58
+ except asyncio.CancelledError:
59
+ pass
60
+ self._reader_task = None
61
+ proc = self._proc
62
+ self._proc = None
63
+ if proc is not None and proc.returncode is None:
64
+ proc.terminate()
65
+ try:
66
+ await asyncio.wait_for(proc.wait(), 2)
67
+ except TimeoutError:
68
+ proc.kill()
69
+ self._fail_pending(AcpError("ACP process closed"))
70
+
71
+ async def request(self, method: str, params: dict) -> dict:
72
+ """Send one request and wait for its result."""
73
+ if self._writer is None:
74
+ raise AcpError("ACP process is not running")
75
+ loop = asyncio.get_running_loop()
76
+ future: asyncio.Future = loop.create_future()
77
+ rpc_id = self._next
78
+ self._next += 1
79
+ self._pending[str(rpc_id)] = (rpc_id, future)
80
+ await self._write({"jsonrpc": "2.0", "id": rpc_id, "method": method, "params": params})
81
+ return await future
82
+
83
+ async def notify(self, method: str, params: dict) -> None:
84
+ """Send a notification. session/cancel has no id and no result."""
85
+ await self._write({"jsonrpc": "2.0", "method": method, "params": params})
86
+
87
+ async def respond(self, rpc_id: object, result: dict) -> None:
88
+ """Answer a request the process sent, such as a permission."""
89
+ await self._write({"jsonrpc": "2.0", "id": rpc_id, "result": result})
90
+
91
+ async def _write(self, frame: dict) -> None:
92
+ if self._writer is None:
93
+ raise AcpError("ACP process is not running")
94
+ payload = json.dumps(frame).encode() + b"\n"
95
+ async with self._write_lock:
96
+ self._writer.write(payload)
97
+ await self._writer.drain()
98
+
99
+ async def _read(self) -> None:
100
+ """Dispatch lines. A permission is handed off so this loop can keep reading."""
101
+ assert self._reader is not None
102
+ try:
103
+ while True:
104
+ line = await self._reader.readline()
105
+ if not line:
106
+ break
107
+ frame = json.loads(line)
108
+ method = frame.get("method")
109
+ if method and "id" in frame:
110
+ if method == "session/request_permission" and self.on_permission is not None:
111
+ asyncio.create_task(self.on_permission(frame["id"], frame.get("params") or {}))
112
+ else:
113
+ await self._write(
114
+ {
115
+ "jsonrpc": "2.0",
116
+ "id": frame["id"],
117
+ "error": {"code": -32601, "message": f"{method} is not supported"},
118
+ }
119
+ )
120
+ continue
121
+ if method:
122
+ if not self.drop_updates and self.on_update is not None:
123
+ self.on_update(frame.get("params") or {})
124
+ # The stream task posts this chunk before the next line, which may be the result.
125
+ await asyncio.sleep(0)
126
+ continue
127
+ if "id" not in frame:
128
+ continue
129
+ found = self._pending.pop(str(frame["id"]), None)
130
+ if found is None or found[1].done():
131
+ continue
132
+ if frame.get("error"):
133
+ found[1].set_exception(AcpError(_error_text(frame["error"])))
134
+ else:
135
+ found[1].set_result(frame.get("result") or {})
136
+ except asyncio.CancelledError:
137
+ raise
138
+ except Exception as err:
139
+ self._fail_pending(err)
140
+ else:
141
+ self._fail_pending(AcpError("ACP process closed"))
142
+
143
+ def _fail_pending(self, err: Exception) -> None:
144
+ for _rpc_id, future in self._pending.values():
145
+ if not future.done():
146
+ future.set_exception(err)
147
+ self._pending.clear()
148
+
149
+
150
+ def _error_text(error: dict) -> str:
151
+ """The JSON-RPC message, plus error.data.details when the process sent it."""
152
+ message = str(error.get("message") or "ACP request failed")
153
+ data = error.get("data")
154
+ detail = data.get("details") if isinstance(data, dict) else None
155
+ if detail:
156
+ return f"{message}: {detail}"
157
+ return message
158
+
159
+
160
+ class AcpHost(Protocol):
161
+ """What the runner needs from a session. It is not part of the public kit."""
162
+
163
+ user_id: str
164
+
165
+ def reply(
166
+ self, room_id: str, *, run_id: str, answered_through: str | None = None, reasoning: str = ReasoningMode.LIVE
167
+ ): ...
168
+
169
+ async def send_events(
170
+ self,
171
+ room_id: str,
172
+ events: list[dict],
173
+ *,
174
+ run_id: str,
175
+ answered_through: str | None = None,
176
+ reasoning: str = ReasoningMode.LIVE,
177
+ ) -> list[str]: ...
178
+
179
+ async def unanswered(self) -> list[tuple[str, list[ChatMessage]]]: ...
180
+
181
+ async def collect(self, timeout_ms: int) -> tuple: ...
182
+
183
+ def note(self, pos: str, pages: int, cold: bool) -> None: ...
184
+
185
+ def flush(self, room_ids: list[str] | None = None) -> None: ...
186
+
187
+
188
+ def close_prompt(
189
+ *,
190
+ saw: bool,
191
+ text_open: bool,
192
+ thought_open: bool,
193
+ cancelled: bool,
194
+ message_id: str,
195
+ ) -> list[dict]:
196
+ """Events that end a prompt. A cancel leaves streamed text unmarked."""
197
+ out: list[dict] = []
198
+ if thought_open:
199
+ out.append({"type": "REASONING_END"})
200
+ if text_open:
201
+ out.append({"type": "TEXT_MESSAGE_END"})
202
+ elif not saw and not cancelled:
203
+ out.append({"type": "TEXT_MESSAGE_START", "messageId": message_id})
204
+ out.append({"type": "TEXT_MESSAGE_END"})
205
+ if not cancelled:
206
+ out.append({"type": "RUN_FINISHED"})
207
+ return out
208
+
209
+
210
+ def _split_resumes(messages: list[ChatMessage]) -> tuple[list[ChatMessage], list[ChatMessage]]:
211
+ """User lines to prompt, and resume envelopes that answer a permission."""
212
+ lines: list[ChatMessage] = []
213
+ resumes: list[ChatMessage] = []
214
+ for message in messages:
215
+ if message.envelope is not None and message.envelope.kind == EnvelopeKind.RESUME:
216
+ resumes.append(message)
217
+ elif message.role == Role.USER:
218
+ lines.append(message)
219
+ return lines, resumes
220
+
221
+
222
+ def _permission_option(options: list[str], status: str) -> str:
223
+ """allow_once when the end user approved. deny when they refused."""
224
+ if status == "approved":
225
+ if "allow_once" in options:
226
+ return "allow_once"
227
+ return next((option for option in options if option.startswith("allow")), "")
228
+ if "deny" in options:
229
+ return "deny"
230
+ return ""
231
+
232
+
233
+ async def run_acp(host: AcpHost, client: AcpClient, session: str, running, sessions_path: str | None) -> None:
234
+ """The ACP loop. listen, subscribe, serve_agui, and this method share one sync cursor."""
235
+ still = running or (lambda: True)
236
+ path = Path(sessions_path or os.environ.get("KESKA_ACP_SESSIONS", "/work/.keska/acp-sessions.json"))
237
+ stored = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
238
+ sessions: dict[str, str] = {str(key): str(value) for key, value in stored.items()}
239
+ permissions: dict[str, dict] = {}
240
+ sinks: dict[str, asyncio.Queue] = {}
241
+ lanes: dict[str, dict] = {}
242
+
243
+ def remember(params: dict) -> None:
244
+ update = params.get("update") or params
245
+ kind = update.get("sessionUpdate")
246
+ session_id = str(params.get("sessionId") or update.get("sessionId") or "")
247
+ sink = sinks.get(session_id)
248
+ if sink is None:
249
+ return
250
+ if kind == "agent_thought_chunk":
251
+ content = update.get("content") or {}
252
+ text = content.get("text") if isinstance(content, dict) else ""
253
+ if text:
254
+ sink.put_nowait({"thought": str(text)})
255
+ return
256
+ if kind == "agent_message_chunk":
257
+ content = update.get("content") or {}
258
+ text = content.get("text") if isinstance(content, dict) else ""
259
+ if text:
260
+ sink.put_nowait({"text": str(text)})
261
+ return
262
+ if kind == "tool_call":
263
+ sink.put_nowait({"tool": update})
264
+ return
265
+ if kind == "tool_call_update" and update.get("status") in {"completed", "failed"}:
266
+ content = update.get("content") or update.get("rawOutput") or ""
267
+ if isinstance(content, list):
268
+ content = " ".join(str(item.get("text") or "") for item in content if isinstance(item, dict))
269
+ sink.put_nowait({"result": {"id": str(update.get("toolCallId") or ""), "content": str(content or "")}})
270
+
271
+ async def on_permission(rpc_id, params: dict) -> None:
272
+ options = [str(item.get("optionId")) for item in params.get("options") or [] if item.get("optionId")]
273
+ tool = params.get("toolCall") or {}
274
+ title = str(tool.get("title") or "Approval needed")
275
+ interrupt_id = f"perm_{rpc_id}"
276
+ expires = int(time.time() * 1000) + PERMISSION_MS
277
+ permissions[interrupt_id] = {"id": rpc_id, "options": options, "expires": expires}
278
+ room_id = str(params.get("sessionId") or "")
279
+ for known_room, known_session in sessions.items():
280
+ if known_session == params.get("sessionId"):
281
+ room_id = known_room
282
+ break
283
+ if session == SessionScope.AGENT:
284
+ room_id = next(iter(pending_room), room_id)
285
+ key = host.user_id if session == SessionScope.AGENT else room_id
286
+ open_run = str(lane_for(key).get("run_id") or "")
287
+ await host.send_events(
288
+ room_id,
289
+ [
290
+ {
291
+ "type": "RUN_FINISHED",
292
+ "interrupts": [{"id": interrupt_id, "message": title, "expiresAt": expires}],
293
+ }
294
+ ],
295
+ run_id=open_run or f"run_{txn()}",
296
+ )
297
+
298
+ client.on_update = remember
299
+ client.on_permission = on_permission
300
+ pending_room: list[str] = []
301
+ initialized = await client.request("initialize", {"protocolVersion": 1, "clientCapabilities": {}})
302
+ can_load = bool(((initialized.get("agentCapabilities") or {}).get("loadSession")))
303
+
304
+ def save() -> None:
305
+ path.parent.mkdir(parents=True, exist_ok=True)
306
+ path.write_text(json.dumps(sessions), encoding="utf-8")
307
+
308
+ if can_load:
309
+ client.drop_updates = True
310
+ try:
311
+ for key, session_id in list(sessions.items()):
312
+ try:
313
+ await client.request(
314
+ "session/load",
315
+ {"sessionId": session_id, "cwd": "/work", "mcpServers": []},
316
+ )
317
+ except Exception:
318
+ sessions.pop(key, None)
319
+ finally:
320
+ client.drop_updates = False
321
+ save()
322
+ else:
323
+ sessions.clear()
324
+ save()
325
+
326
+ async def ensure(key: str) -> str:
327
+ current = sessions.get(key)
328
+ if current:
329
+ return current
330
+ created = await client.request("session/new", {"cwd": "/work", "mcpServers": []})
331
+ session_id = str(created.get("sessionId") or "")
332
+ sessions[key] = session_id
333
+ save()
334
+ return session_id
335
+
336
+ def lane_for(key: str) -> dict:
337
+ return lanes.setdefault(
338
+ key,
339
+ {
340
+ "queued": [],
341
+ "task": None,
342
+ "inflight": False,
343
+ "cancel_sent": False,
344
+ "session_id": "",
345
+ "run_id": "",
346
+ },
347
+ )
348
+
349
+ def enqueue(room_id: str, lines: list[ChatMessage]) -> None:
350
+ key = host.user_id if session == SessionScope.AGENT else room_id
351
+ lane = lane_for(key)
352
+ if lane["inflight"]:
353
+ lane["queued"] = [(room_id, lines)]
354
+ if lane["session_id"] and not lane["cancel_sent"]:
355
+ lane["cancel_sent"] = True
356
+ asyncio.create_task(client.notify("session/cancel", {"sessionId": lane["session_id"]}))
357
+ return
358
+ lane["queued"].append((room_id, lines))
359
+
360
+ async def prompt(key: str, room_id: str, lines: list[ChatMessage]) -> None:
361
+ lane = lanes[key]
362
+ session_id = ""
363
+ queue: asyncio.Queue | None = None
364
+ stream_task: asyncio.Task | None = None
365
+ run_id = ""
366
+ end = {"abandoned": False}
367
+ try:
368
+ pending_room[:] = [room_id]
369
+ session_id = await ensure(key)
370
+ lane["session_id"] = session_id
371
+ text = "\n".join(line.body for line in lines)
372
+ if session == SessionScope.AGENT:
373
+ text = f"[{room_id}] {text}"
374
+ run_id = f"run_{txn()}"
375
+ lane["run_id"] = run_id
376
+ answered = lines[-1].event_id
377
+ queue = asyncio.Queue()
378
+ sinks[session_id] = queue
379
+ lane["inflight"] = True
380
+
381
+ async def events():
382
+ text_open = False
383
+ thought_open = False
384
+ saw = False
385
+ segment = 0
386
+ parent_id = ""
387
+
388
+ while True:
389
+ item = await queue.get()
390
+ if item is None:
391
+ break
392
+ if item.get("thought"):
393
+ saw = True
394
+ if not thought_open:
395
+ thought_open = True
396
+ yield {"type": "REASONING_START"}
397
+ yield {"type": "REASONING_MESSAGE_START"}
398
+ yield {"type": "REASONING_MESSAGE_CONTENT", "delta": item["thought"]}
399
+ continue
400
+ if item.get("text"):
401
+ saw = True
402
+ if not text_open:
403
+ segment += 1
404
+ text_open = True
405
+ parent_id = f"{run_id}:{segment}"
406
+ yield {"type": "TEXT_MESSAGE_START", "messageId": parent_id}
407
+ yield {"type": "TEXT_MESSAGE_CONTENT", "delta": item["text"]}
408
+ continue
409
+ tool = item.get("tool")
410
+ if tool:
411
+ saw = True
412
+ if text_open:
413
+ yield {"type": "TEXT_MESSAGE_END"}
414
+ text_open = False
415
+ call_id = str(tool.get("toolCallId") or "")
416
+ start = {
417
+ "type": "TOOL_CALL_START",
418
+ "toolCallId": call_id,
419
+ "toolCallName": str(tool.get("title") or "tool"),
420
+ }
421
+ if parent_id:
422
+ start["parentMessageId"] = parent_id
423
+ yield start
424
+ raw = tool.get("rawInput")
425
+ if raw not in (None, ""):
426
+ args = raw if isinstance(raw, str) else json.dumps(raw)
427
+ yield {"type": "TOOL_CALL_ARGS", "toolCallId": call_id, "delta": args}
428
+ yield {"type": "TOOL_CALL_END", "toolCallId": call_id}
429
+ continue
430
+ result = item.get("result")
431
+ if result:
432
+ saw = True
433
+ call_id = str(result.get("id") or "")
434
+ yield {
435
+ "type": "TOOL_CALL_RESULT",
436
+ "toolCallId": call_id,
437
+ "messageId": f"{call_id}:out",
438
+ "content": str(result.get("content") or ""),
439
+ }
440
+ for event in close_prompt(
441
+ saw=saw,
442
+ text_open=text_open,
443
+ thought_open=thought_open,
444
+ cancelled=end["abandoned"],
445
+ message_id=run_id,
446
+ ):
447
+ yield event
448
+
449
+ user_id = lines[-1].sender if lines else None
450
+ stream_task = asyncio.create_task(
451
+ host.reply(room_id, run_id=run_id, answered_through=answered).stream(events(), user_id=user_id)
452
+ )
453
+ result = await client.request(
454
+ "session/prompt",
455
+ {"sessionId": session_id, "prompt": [{"type": "text", "text": text}]},
456
+ )
457
+ end["abandoned"] = str(result.get("stopReason") or "") == "cancelled"
458
+ queue.put_nowait(None)
459
+ await stream_task
460
+ except Exception as err:
461
+ end["abandoned"] = True
462
+ if queue is not None:
463
+ queue.put_nowait(None)
464
+ if stream_task is not None:
465
+ try:
466
+ await stream_task
467
+ except Exception:
468
+ pass
469
+ await host.send_events(
470
+ room_id,
471
+ [{"type": "RUN_ERROR", "message": str(err) or "The reply failed."}],
472
+ run_id=run_id or f"run_{txn()}",
473
+ answered_through=lines[-1].event_id,
474
+ )
475
+ finally:
476
+ if session_id:
477
+ sinks.pop(session_id, None)
478
+ lane["run_id"] = ""
479
+ lane["inflight"] = False
480
+ lane["cancel_sent"] = False
481
+ lane["task"] = None
482
+
483
+ def start_ready() -> None:
484
+ for key, lane in lanes.items():
485
+ if lane["task"] is not None or not lane["queued"] or not still():
486
+ continue
487
+ room_id, lines = lane["queued"].pop(0)
488
+ lane["task"] = asyncio.create_task(prompt(key, room_id, lines))
489
+
490
+ def answer_permission(message: ChatMessage) -> None:
491
+ agui = message.agui or {}
492
+ interrupt_id = str(agui.get("interruptId") or "")
493
+ waiting = permissions.pop(interrupt_id, None)
494
+ if waiting is None:
495
+ return
496
+ status = str(agui.get("status") or "")
497
+ option = _permission_option(waiting["options"], status)
498
+ outcome = {"outcome": "selected", "optionId": option} if option else {"outcome": "cancelled"}
499
+ asyncio.create_task(client.respond(waiting["id"], {"outcome": outcome}))
500
+
501
+ def expire_permissions() -> None:
502
+ now = int(time.time() * 1000)
503
+ for interrupt_id, waiting in list(permissions.items()):
504
+ if waiting["expires"] > now:
505
+ continue
506
+ permissions.pop(interrupt_id, None)
507
+ asyncio.create_task(client.respond(waiting["id"], {"outcome": {"outcome": "cancelled"}}))
508
+
509
+ accepted: set[str] = set()
510
+
511
+ def accept(room_id: str, messages: list[ChatMessage]) -> None:
512
+ fresh = novel_user_lines(messages, accepted)
513
+ lines, resumes = _split_resumes(fresh)
514
+ for resume in resumes:
515
+ accepted.add(resume.event_id)
516
+ answer_permission(resume)
517
+ if not lines:
518
+ return
519
+ for line in lines:
520
+ accepted.add(line.event_id)
521
+ enqueue(room_id, lines)
522
+
523
+ def take(batch: dict) -> None:
524
+ for room_id, messages in messages_by_room(batch, host.user_id).items():
525
+ accept(room_id, messages)
526
+
527
+ for room_id, messages in await host.unanswered():
528
+ accept(room_id, messages)
529
+ print("listening", flush=True)
530
+ try:
531
+ while still():
532
+ # A prompt task has to run while this loop also pulls sync.
533
+ await asyncio.sleep(0)
534
+ for lane in lanes.values():
535
+ task = lane["task"]
536
+ if task is not None and task.done():
537
+ await task
538
+ lane["task"] = None
539
+ start_ready()
540
+ if not any(lane["task"] is not None for lane in lanes.values()):
541
+ host.flush()
542
+ if not still():
543
+ break
544
+ batch, pos, pages, cold = await host.collect(200 if permissions else SYNC_WAIT_MS)
545
+ take(batch)
546
+ host.note(pos, pages, cold)
547
+ expire_permissions()
548
+ finally:
549
+ for lane in lanes.values():
550
+ task = lane["task"]
551
+ if task is not None and not task.done():
552
+ task.cancel()
553
+ for lane in lanes.values():
554
+ task = lane["task"]
555
+ if task is None:
556
+ continue
557
+ try:
558
+ await task
559
+ except asyncio.CancelledError:
560
+ pass
@@ -0,0 +1,23 @@
1
+ """The only AG-UI harness this kit wraps.
2
+
3
+ A Pydantic agent does not keep the conversation. serve_agui therefore sends the
4
+ room (history full). Install it with `keska-agent-kit[agui]`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+
11
+
12
+ def pydantic_ai(agent):
13
+ """Turn a Pydantic AI agent into the callable serve_agui runs.
14
+
15
+ serve_agui passes one dict per turn. This parses it and returns that agent's event stream.
16
+ """
17
+ from pydantic_ai.ui.ag_ui import AGUIAdapter
18
+
19
+ def run(run_input: dict):
20
+ parsed = AGUIAdapter.build_run_input(json.dumps(run_input).encode())
21
+ return AGUIAdapter(agent=agent, run_input=parsed).run_stream()
22
+
23
+ return run