clankit 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.
- clankit/__init__.py +3 -0
- clankit/__main__.py +7 -0
- clankit/agent/__init__.py +0 -0
- clankit/agent/context.py +107 -0
- clankit/agent/events.py +391 -0
- clankit/agent/loop.py +609 -0
- clankit/agent/permissions.py +174 -0
- clankit/agent/prompts.py +255 -0
- clankit/agent/session.py +590 -0
- clankit/agent/state.py +346 -0
- clankit/agent/store.py +158 -0
- clankit/cli.py +257 -0
- clankit/commands.py +271 -0
- clankit/config/__init__.py +0 -0
- clankit/config/actions.py +182 -0
- clankit/config/catalog.py +631 -0
- clankit/config/fields.py +303 -0
- clankit/config/kdl.py +504 -0
- clankit/config/kdledit.py +386 -0
- clankit/config/kdllayout.py +541 -0
- clankit/config/kdlstarter.py +228 -0
- clankit/config/kdlsyntax.py +307 -0
- clankit/config/schema.py +267 -0
- clankit/config/store.py +167 -0
- clankit/headless.py +91 -0
- clankit/llm/__init__.py +0 -0
- clankit/llm/anthropic_provider.py +949 -0
- clankit/llm/compat/__init__.py +13 -0
- clankit/llm/compat/arguments.py +113 -0
- clankit/llm/compat/errors.py +298 -0
- clankit/llm/compat/models.py +94 -0
- clankit/llm/compat/profiles.py +185 -0
- clankit/llm/compat/stream.py +561 -0
- clankit/llm/compat/text_tools.py +269 -0
- clankit/llm/compat/wire.py +195 -0
- clankit/llm/openai_compat.py +208 -0
- clankit/llm/provider.py +105 -0
- clankit/llm/registry.py +212 -0
- clankit/llm/scripted.py +184 -0
- clankit/llm/types.py +409 -0
- clankit/orchestration/__init__.py +77 -0
- clankit/orchestration/architect.py +601 -0
- clankit/orchestration/base.py +112 -0
- clankit/orchestration/best_of_n.py +1129 -0
- clankit/orchestration/common.py +346 -0
- clankit/orchestration/demo.py +409 -0
- clankit/orchestration/escalate.py +623 -0
- clankit/orchestration/review.py +179 -0
- clankit/orchestration/review_loop.py +465 -0
- clankit/orchestration/solo.py +82 -0
- clankit/orchestration/task_tree.py +977 -0
- clankit/orchestration/test_loop.py +920 -0
- clankit/orchestration/ultra.py +463 -0
- clankit/orchestration/workflow/__init__.py +60 -0
- clankit/orchestration/workflow/account.py +173 -0
- clankit/orchestration/workflow/builtin/implement.py +117 -0
- clankit/orchestration/workflow/builtin/research.py +70 -0
- clankit/orchestration/workflow/builtin/review.py +90 -0
- clankit/orchestration/workflow/builtin/understand.py +105 -0
- clankit/orchestration/workflow/engine.py +935 -0
- clankit/orchestration/workflow/errors.py +30 -0
- clankit/orchestration/workflow/journal.py +84 -0
- clankit/orchestration/workflow/patterns.py +617 -0
- clankit/orchestration/workflow/saved.py +97 -0
- clankit/orchestration/workflow/script.py +553 -0
- clankit/orchestration/workflow/worker.py +283 -0
- clankit/orchestration/worktree.py +563 -0
- clankit/paths.py +41 -0
- clankit/runtime.py +207 -0
- clankit/skills/__init__.py +8 -0
- clankit/skills/candidate.py +217 -0
- clankit/skills/document.py +260 -0
- clankit/skills/evidence.py +427 -0
- clankit/skills/forge.py +471 -0
- clankit/skills/library.py +591 -0
- clankit/skills/redaction.py +114 -0
- clankit/skills/safety.py +195 -0
- clankit/skills/tool.py +143 -0
- clankit/themes/__init__.py +76 -0
- clankit/themes/colour.py +105 -0
- clankit/themes/custom.py +99 -0
- clankit/themes/legibility.py +134 -0
- clankit/themes/model.py +162 -0
- clankit/themes/palettes.py +468 -0
- clankit/themes/syntax.py +192 -0
- clankit/themes/textual.py +209 -0
- clankit/themes/web.py +59 -0
- clankit/tools/__init__.py +48 -0
- clankit/tools/base.py +388 -0
- clankit/tools/files.py +957 -0
- clankit/tools/search.py +842 -0
- clankit/tools/shell.py +594 -0
- clankit/tools/web.py +462 -0
- clankit/tui/__init__.py +31 -0
- clankit/tui/app.py +278 -0
- clankit/tui/composer.py +229 -0
- clankit/tui/editors.py +292 -0
- clankit/tui/entries.py +263 -0
- clankit/tui/format.py +173 -0
- clankit/tui/main.py +691 -0
- clankit/tui/pickers.py +338 -0
- clankit/tui/pump.py +70 -0
- clankit/tui/requests.py +305 -0
- clankit/tui/screens.py +229 -0
- clankit/tui/settings.py +925 -0
- clankit/tui/styles.py +266 -0
- clankit/tui/tasktree.py +619 -0
- clankit/tui/transcript.py +908 -0
- clankit/web/__init__.py +11 -0
- clankit/web/app.py +127 -0
- clankit/web/context.py +108 -0
- clankit/web/guard.py +149 -0
- clankit/web/markdown.py +106 -0
- clankit/web/payloads.py +195 -0
- clankit/web/server.py +174 -0
- clankit/web/sessions.py +224 -0
- clankit/web/static/api.js +39 -0
- clankit/web/static/app.css +1522 -0
- clankit/web/static/app.js +521 -0
- clankit/web/static/chrome.js +121 -0
- clankit/web/static/composer.js +190 -0
- clankit/web/static/dom.js +77 -0
- clankit/web/static/format.js +79 -0
- clankit/web/static/panels.js +146 -0
- clankit/web/static/popup.js +219 -0
- clankit/web/static/settings.js +608 -0
- clankit/web/static/store.js +310 -0
- clankit/web/static/transcript.js +343 -0
- clankit/web/static/tree.js +256 -0
- clankit/web/stream.py +292 -0
- clankit/web/templates/index.jinja2 +39 -0
- clankit/web/views.py +537 -0
- clankit-0.1.0.dist-info/METADATA +347 -0
- clankit-0.1.0.dist-info/RECORD +136 -0
- clankit-0.1.0.dist-info/WHEEL +4 -0
- clankit-0.1.0.dist-info/entry_points.txt +2 -0
clankit/__init__.py
ADDED
clankit/__main__.py
ADDED
|
File without changes
|
clankit/agent/context.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Context-window housekeeping for the agent loop: estimates, truncation, compaction text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import random
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from clankit.llm.types import Message, TextBlock, ThinkingBlock, ToolResultBlock, ToolUseBlock
|
|
9
|
+
|
|
10
|
+
MAX_RETRIES = 4
|
|
11
|
+
CHARS_PER_TOKEN = 3.5
|
|
12
|
+
|
|
13
|
+
#: Asked of the model when its context is nearly full. The closing sentence matters: the
|
|
14
|
+
#: request still carries the agent's tools, and without it models sometimes call one.
|
|
15
|
+
SUMMARY_PROMPT = """\
|
|
16
|
+
Your context window is nearly full, so this conversation will continue in a fresh one that \
|
|
17
|
+
starts from a summary. Write that summary now, inside <summary></summary> tags.
|
|
18
|
+
|
|
19
|
+
Include what is needed to continue without redoing work or being told the constraints again. \
|
|
20
|
+
Be sure to preserve:
|
|
21
|
+
1. The task exactly as given, including every acceptance criterion and constraint.
|
|
22
|
+
2. Exactly where things stand: what is finished, what is in progress, what remains.
|
|
23
|
+
3. Every file created or changed, with its path and what changed in it.
|
|
24
|
+
4. Decisions made and approaches tried, including ones that failed and why.
|
|
25
|
+
5. Problems encountered and how they were resolved, or that they are still open.
|
|
26
|
+
6. Details that would be hard to reconstruct: names, signatures, commands and their results, \
|
|
27
|
+
error messages, numbers - quoted exactly.
|
|
28
|
+
7. What you were about to do next.
|
|
29
|
+
|
|
30
|
+
Be complete on these points even at the cost of length; keep everything else brief. \
|
|
31
|
+
Do not call any tools while writing this summary; respond with text only."""
|
|
32
|
+
|
|
33
|
+
_SUMMARY_RE = re.compile(r"<summary>(.*?)</summary>", re.DOTALL | re.IGNORECASE)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def backoff_delay(attempt: int) -> float:
|
|
37
|
+
"""Exponential backoff with jitter: about 2s, 4s, 8s, 16s."""
|
|
38
|
+
return min(60.0, 2.0**attempt) + random.uniform(0, 1)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def estimate_tokens(system: str, messages: list[Message]) -> int:
|
|
42
|
+
"""Rough token count for when a provider reports no usage."""
|
|
43
|
+
chars = len(system)
|
|
44
|
+
for message in messages:
|
|
45
|
+
for block in message.content:
|
|
46
|
+
if isinstance(block, (TextBlock, ThinkingBlock)):
|
|
47
|
+
chars += len(block.text)
|
|
48
|
+
elif isinstance(block, ToolUseBlock):
|
|
49
|
+
chars += len(block.name) + len(str(block.input))
|
|
50
|
+
elif isinstance(block, ToolResultBlock):
|
|
51
|
+
chars += len(block.content)
|
|
52
|
+
return int(chars / CHARS_PER_TOKEN)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def elide_middle(text: str, limit: int) -> str:
|
|
56
|
+
"""Keep the head and tail of `text` within `limit` characters, noting what was cut."""
|
|
57
|
+
if len(text) <= limit:
|
|
58
|
+
return text
|
|
59
|
+
head = int(limit * 0.6)
|
|
60
|
+
tail = limit - head
|
|
61
|
+
cut = len(text) - head - tail
|
|
62
|
+
return (
|
|
63
|
+
f"{text[:head]}\n\n[... {cut:,} characters omitted. Narrow the request "
|
|
64
|
+
f"(a line range, a more specific pattern, a filter) to see them ...]\n\n{text[-tail:]}"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render_transcript(messages: list[Message], *, budget: int) -> str:
|
|
69
|
+
"""Plain-text rendering of a conversation, shortened to about `budget` characters.
|
|
70
|
+
|
|
71
|
+
Individual tool results are clipped first; if the whole is still too long the middle of
|
|
72
|
+
the conversation is dropped, keeping the opening (the task) and the most recent work.
|
|
73
|
+
"""
|
|
74
|
+
parts: list[str] = []
|
|
75
|
+
for message in messages:
|
|
76
|
+
for block in message.content:
|
|
77
|
+
if isinstance(block, TextBlock):
|
|
78
|
+
parts.append(f"[{message.role}]\n{block.text}")
|
|
79
|
+
elif isinstance(block, ToolUseBlock):
|
|
80
|
+
parts.append(
|
|
81
|
+
f"[assistant called {block.name}]\n{elide_middle(str(block.input), 2000)}"
|
|
82
|
+
)
|
|
83
|
+
elif isinstance(block, ToolResultBlock):
|
|
84
|
+
label = "tool error" if block.is_error else "tool result"
|
|
85
|
+
parts.append(f"[{label}]\n{elide_middle(block.content, 2000)}")
|
|
86
|
+
text = "\n\n".join(parts)
|
|
87
|
+
if len(text) <= budget:
|
|
88
|
+
return text
|
|
89
|
+
head = int(budget * 0.25)
|
|
90
|
+
tail = budget - head
|
|
91
|
+
return f"{text[:head]}\n\n[... earlier work omitted ...]\n\n{text[-tail:]}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def extract_summary(text: str) -> str:
|
|
95
|
+
match = _SUMMARY_RE.search(text)
|
|
96
|
+
return (match.group(1) if match else text).strip()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def continuation_message(task: str, summary: str) -> str:
|
|
100
|
+
"""The first message of the fresh conversation that follows a compaction."""
|
|
101
|
+
return (
|
|
102
|
+
"You are continuing a task. The earlier part of this conversation was replaced by the "
|
|
103
|
+
"summary below because the context window filled up; files on disk are as you left them.\n\n"
|
|
104
|
+
f"<original_task>\n{task}\n</original_task>\n\n"
|
|
105
|
+
f"<summary_of_work_so_far>\n{summary}\n</summary_of_work_so_far>\n\n"
|
|
106
|
+
"Continue from where you left off. Re-read any file before editing it."
|
|
107
|
+
)
|
clankit/agent/events.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""Everything a user interface can observe, as serialisable events.
|
|
2
|
+
|
|
3
|
+
The engine publishes events on a session's `EventBus`; the terminal UI, the web UI, the headless
|
|
4
|
+
printer and the session log are all just subscribers. No UI ever reaches into engine objects.
|
|
5
|
+
|
|
6
|
+
Events are small dataclasses. `to_dict()` gives the JSON wire form used by the web UI's event
|
|
7
|
+
stream and by the session log; `event_from_dict()` reverses it.
|
|
8
|
+
|
|
9
|
+
Events marked ``transient`` (streaming deltas) are neither logged nor replayed: every delta
|
|
10
|
+
sequence is followed by a complete `AssistantMessage`, which is what replays use.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
from collections import deque
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from dataclasses import dataclass, field, fields
|
|
21
|
+
from typing import Any, ClassVar, Literal
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
NodeStatus = Literal[
|
|
26
|
+
"pending", # created, waiting for a free slot or for a dependency
|
|
27
|
+
"running", # its agent is working (sizing up the task, or building as a leaf)
|
|
28
|
+
"waiting", # delegated; its subtasks are running
|
|
29
|
+
"integrating", # subtasks returned; reviewing, resolving conflicts, gluing together
|
|
30
|
+
"done",
|
|
31
|
+
"failed",
|
|
32
|
+
"cancelled",
|
|
33
|
+
]
|
|
34
|
+
TERMINAL_STATUSES: frozenset[str] = frozenset({"done", "failed", "cancelled"})
|
|
35
|
+
|
|
36
|
+
RunStatus = Literal["completed", "failed", "cancelled"]
|
|
37
|
+
NoticeLevel = Literal["info", "warning", "error"]
|
|
38
|
+
PermissionChoice = Literal["allow", "allow_session", "deny"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(slots=True)
|
|
42
|
+
class NodeInfo:
|
|
43
|
+
"""One node of the task tree: a unit of work owned by one agent.
|
|
44
|
+
|
|
45
|
+
`role` is free-form but conventional: "root", "branch" (has delegated), "leaf", and for other
|
|
46
|
+
orchestration methods "planner", "worker", "reviewer", "judge", "candidate", "explorer".
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
id: str
|
|
50
|
+
parent_id: str | None
|
|
51
|
+
depth: int
|
|
52
|
+
title: str
|
|
53
|
+
role: str = "leaf"
|
|
54
|
+
model: str = ""
|
|
55
|
+
status: NodeStatus = "pending"
|
|
56
|
+
brief: str = ""
|
|
57
|
+
summary: str = ""
|
|
58
|
+
|
|
59
|
+
def to_dict(self) -> dict[str, Any]:
|
|
60
|
+
return {f.name: getattr(self, f.name) for f in fields(self)}
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_dict(cls, data: dict[str, Any]) -> NodeInfo:
|
|
64
|
+
names = {f.name for f in fields(cls)}
|
|
65
|
+
return cls(**{k: v for k, v in data.items() if k in names})
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# --------------------------------------------------------------------------------------------
|
|
69
|
+
# Event base
|
|
70
|
+
# --------------------------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
_REGISTRY: dict[str, type[Event]] = {}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(kw_only=True)
|
|
76
|
+
class Event:
|
|
77
|
+
kind: ClassVar[str] = "event"
|
|
78
|
+
transient: ClassVar[bool] = False
|
|
79
|
+
|
|
80
|
+
seq: int = 0 # assigned by the bus, strictly increasing from 1 within a session
|
|
81
|
+
ts: float = 0.0 # assigned by the bus, unix seconds
|
|
82
|
+
|
|
83
|
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
|
84
|
+
super().__init_subclass__(**kwargs)
|
|
85
|
+
kind = cls.__dict__.get("kind")
|
|
86
|
+
if isinstance(kind, str):
|
|
87
|
+
_REGISTRY[kind] = cls
|
|
88
|
+
|
|
89
|
+
def to_dict(self) -> dict[str, Any]:
|
|
90
|
+
data: dict[str, Any] = {"kind": self.kind}
|
|
91
|
+
for f in fields(self):
|
|
92
|
+
value = getattr(self, f.name)
|
|
93
|
+
data[f.name] = value.to_dict() if isinstance(value, NodeInfo) else value
|
|
94
|
+
return data
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def event_from_dict(data: dict[str, Any]) -> Event:
|
|
98
|
+
cls = _REGISTRY.get(data.get("kind", ""))
|
|
99
|
+
if cls is None:
|
|
100
|
+
raise ValueError(f"unknown event kind: {data.get('kind')!r}")
|
|
101
|
+
names = {f.name for f in fields(cls)}
|
|
102
|
+
kwargs = {k: v for k, v in data.items() if k in names}
|
|
103
|
+
if cls is NodeAdded and isinstance(kwargs.get("node"), dict):
|
|
104
|
+
kwargs["node"] = NodeInfo.from_dict(kwargs["node"])
|
|
105
|
+
return cls(**kwargs)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# --------------------------------------------------------------------------------------------
|
|
109
|
+
# Run lifecycle
|
|
110
|
+
# --------------------------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(kw_only=True)
|
|
114
|
+
class RunStarted(Event):
|
|
115
|
+
"""The user submitted a prompt and an orchestrator started working on it."""
|
|
116
|
+
|
|
117
|
+
kind: ClassVar[str] = "run_started"
|
|
118
|
+
run_id: str
|
|
119
|
+
prompt: str
|
|
120
|
+
method: str
|
|
121
|
+
model: str
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(kw_only=True)
|
|
125
|
+
class RunFinished(Event):
|
|
126
|
+
kind: ClassVar[str] = "run_finished"
|
|
127
|
+
run_id: str
|
|
128
|
+
status: RunStatus
|
|
129
|
+
answer: str = ""
|
|
130
|
+
error: str = ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# --------------------------------------------------------------------------------------------
|
|
134
|
+
# Task tree
|
|
135
|
+
# --------------------------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass(kw_only=True)
|
|
139
|
+
class NodeAdded(Event):
|
|
140
|
+
kind: ClassVar[str] = "node_added"
|
|
141
|
+
node: NodeInfo
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass(kw_only=True)
|
|
145
|
+
class NodeChanged(Event):
|
|
146
|
+
"""Partial update: only the fields that are not None changed."""
|
|
147
|
+
|
|
148
|
+
kind: ClassVar[str] = "node_changed"
|
|
149
|
+
node_id: str
|
|
150
|
+
status: NodeStatus | None = None
|
|
151
|
+
title: str | None = None
|
|
152
|
+
role: str | None = None
|
|
153
|
+
model: str | None = None
|
|
154
|
+
summary: str | None = None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# --------------------------------------------------------------------------------------------
|
|
158
|
+
# Agent transcript (always scoped to a node)
|
|
159
|
+
# --------------------------------------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(kw_only=True)
|
|
163
|
+
class UserMessage(Event):
|
|
164
|
+
"""Text handed to a node's agent: the user's prompt for the root, a brief for a subtask."""
|
|
165
|
+
|
|
166
|
+
kind: ClassVar[str] = "user_message"
|
|
167
|
+
node_id: str
|
|
168
|
+
text: str
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass(kw_only=True)
|
|
172
|
+
class AgentTextDelta(Event):
|
|
173
|
+
kind: ClassVar[str] = "text_delta"
|
|
174
|
+
transient: ClassVar[bool] = True
|
|
175
|
+
node_id: str
|
|
176
|
+
message_id: str
|
|
177
|
+
text: str
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass(kw_only=True)
|
|
181
|
+
class AgentThinkingDelta(Event):
|
|
182
|
+
kind: ClassVar[str] = "thinking_delta"
|
|
183
|
+
transient: ClassVar[bool] = True
|
|
184
|
+
node_id: str
|
|
185
|
+
message_id: str
|
|
186
|
+
text: str
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass(kw_only=True)
|
|
190
|
+
class AssistantMessage(Event):
|
|
191
|
+
"""A complete assistant turn's prose. Follows (and supersedes) its deltas.
|
|
192
|
+
|
|
193
|
+
Published for every model response that contains text or reasoning, including responses
|
|
194
|
+
that also call tools.
|
|
195
|
+
"""
|
|
196
|
+
|
|
197
|
+
kind: ClassVar[str] = "assistant_message"
|
|
198
|
+
node_id: str
|
|
199
|
+
message_id: str
|
|
200
|
+
text: str
|
|
201
|
+
thinking: str = ""
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass(kw_only=True)
|
|
205
|
+
class ToolStarted(Event):
|
|
206
|
+
kind: ClassVar[str] = "tool_started"
|
|
207
|
+
node_id: str
|
|
208
|
+
call_id: str
|
|
209
|
+
tool: str
|
|
210
|
+
summary: str # one line, e.g. "edit src/app.py" or "$ pytest -q"
|
|
211
|
+
input: dict[str, Any] = field(default_factory=dict)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dataclass(kw_only=True)
|
|
215
|
+
class ToolFinished(Event):
|
|
216
|
+
"""`output` is a preview (truncated for display); the model saw the full result.
|
|
217
|
+
|
|
218
|
+
`display` is an optional structured payload for richer rendering:
|
|
219
|
+
``{"type": "diff", "path": str, "diff": str}`` for edits and writes.
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
kind: ClassVar[str] = "tool_finished"
|
|
223
|
+
node_id: str
|
|
224
|
+
call_id: str
|
|
225
|
+
output: str
|
|
226
|
+
is_error: bool = False
|
|
227
|
+
duration: float = 0.0
|
|
228
|
+
display: dict[str, Any] | None = None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass(kw_only=True)
|
|
232
|
+
class UsageChanged(Event):
|
|
233
|
+
"""Token usage after a model call. `usage` is the node's running total, `total` the session's.
|
|
234
|
+
|
|
235
|
+
`context_tokens` is the size of the node's latest prompt, i.e. how full its context is.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
kind: ClassVar[str] = "usage_changed"
|
|
239
|
+
node_id: str
|
|
240
|
+
usage: dict[str, int]
|
|
241
|
+
total: dict[str, int]
|
|
242
|
+
context_tokens: int = 0
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# --------------------------------------------------------------------------------------------
|
|
246
|
+
# Interaction
|
|
247
|
+
# --------------------------------------------------------------------------------------------
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@dataclass(kw_only=True)
|
|
251
|
+
class PermissionRequested(Event):
|
|
252
|
+
"""An agent wants to do something the permission policy does not allow outright.
|
|
253
|
+
|
|
254
|
+
Answer with `Session.resolve_permission(request_id, choice)`.
|
|
255
|
+
"""
|
|
256
|
+
|
|
257
|
+
kind: ClassVar[str] = "permission_requested"
|
|
258
|
+
request_id: str
|
|
259
|
+
node_id: str
|
|
260
|
+
tool: str
|
|
261
|
+
category: str # "read" | "edit" | "shell" | "network"
|
|
262
|
+
summary: str
|
|
263
|
+
detail: str = ""
|
|
264
|
+
#: What "allow for this session" would permit from now on, e.g. "shell:pytest *".
|
|
265
|
+
session_rule: str = ""
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@dataclass(kw_only=True)
|
|
269
|
+
class PermissionResolved(Event):
|
|
270
|
+
kind: ClassVar[str] = "permission_resolved"
|
|
271
|
+
request_id: str
|
|
272
|
+
choice: PermissionChoice
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@dataclass(kw_only=True)
|
|
276
|
+
class QuestionAsked(Event):
|
|
277
|
+
"""The root agent needs a decision from the user.
|
|
278
|
+
|
|
279
|
+
Answer with `Session.answer_question(request_id, text)`. `options` are suggestions; free
|
|
280
|
+
text is always acceptable.
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
kind: ClassVar[str] = "question_asked"
|
|
284
|
+
request_id: str
|
|
285
|
+
node_id: str
|
|
286
|
+
question: str
|
|
287
|
+
options: list[str] = field(default_factory=list)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@dataclass(kw_only=True)
|
|
291
|
+
class QuestionAnswered(Event):
|
|
292
|
+
kind: ClassVar[str] = "question_answered"
|
|
293
|
+
request_id: str
|
|
294
|
+
answer: str
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# --------------------------------------------------------------------------------------------
|
|
298
|
+
# Miscellaneous
|
|
299
|
+
# --------------------------------------------------------------------------------------------
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
@dataclass(kw_only=True)
|
|
303
|
+
class Notice(Event):
|
|
304
|
+
"""Something the user should see that is not agent output (retries, compaction, limits)."""
|
|
305
|
+
|
|
306
|
+
kind: ClassVar[str] = "notice"
|
|
307
|
+
level: NoticeLevel
|
|
308
|
+
text: str
|
|
309
|
+
node_id: str = ""
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@dataclass(kw_only=True)
|
|
313
|
+
class SkillSaved(Event):
|
|
314
|
+
"""A skill was written by the skill generator.
|
|
315
|
+
|
|
316
|
+
"proposed" means it is staged and waiting for the user's approval; "created" and
|
|
317
|
+
"updated" mean it is live in the skill library.
|
|
318
|
+
"""
|
|
319
|
+
|
|
320
|
+
kind: ClassVar[str] = "skill_saved"
|
|
321
|
+
name: str
|
|
322
|
+
path: str
|
|
323
|
+
action: Literal["proposed", "created", "updated"] = "created"
|
|
324
|
+
description: str = ""
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
# --------------------------------------------------------------------------------------------
|
|
328
|
+
# Bus
|
|
329
|
+
# --------------------------------------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
Listener = Callable[[Event], None]
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class EventBus:
|
|
335
|
+
"""Synchronous fan-out of a session's events, with a bounded replay buffer.
|
|
336
|
+
|
|
337
|
+
`publish` stamps the event and calls every listener in the publishing thread; listeners
|
|
338
|
+
must return quickly and must not raise (exceptions are logged and swallowed, so a broken
|
|
339
|
+
UI cannot take the engine down). Subscribing and publishing are thread-safe, which lets
|
|
340
|
+
web-server threads subscribe while the engine publishes from its event-loop thread; such
|
|
341
|
+
listeners should only hand the event to a thread-safe queue.
|
|
342
|
+
"""
|
|
343
|
+
|
|
344
|
+
def __init__(self, buffer_size: int = 8192) -> None:
|
|
345
|
+
self._lock = threading.Lock()
|
|
346
|
+
self._listeners: list[Listener] = []
|
|
347
|
+
self._buffer: deque[Event] = deque(maxlen=buffer_size)
|
|
348
|
+
self._seq = 0
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def last_seq(self) -> int:
|
|
352
|
+
return self._seq
|
|
353
|
+
|
|
354
|
+
def publish(self, event: Event) -> Event:
|
|
355
|
+
with self._lock:
|
|
356
|
+
self._seq += 1
|
|
357
|
+
event.seq = self._seq
|
|
358
|
+
event.ts = time.time()
|
|
359
|
+
self._buffer.append(event)
|
|
360
|
+
listeners = tuple(self._listeners)
|
|
361
|
+
for listener in listeners:
|
|
362
|
+
try:
|
|
363
|
+
listener(event)
|
|
364
|
+
except Exception: # a subscriber bug must never break the engine
|
|
365
|
+
log.exception("event listener failed on %s", event.kind)
|
|
366
|
+
return event
|
|
367
|
+
|
|
368
|
+
def subscribe(self, listener: Listener) -> Callable[[], None]:
|
|
369
|
+
"""Register `listener`; returns a function that unsubscribes it."""
|
|
370
|
+
with self._lock:
|
|
371
|
+
self._listeners.append(listener)
|
|
372
|
+
|
|
373
|
+
def unsubscribe() -> None:
|
|
374
|
+
with self._lock:
|
|
375
|
+
if listener in self._listeners:
|
|
376
|
+
self._listeners.remove(listener)
|
|
377
|
+
|
|
378
|
+
return unsubscribe
|
|
379
|
+
|
|
380
|
+
def since(self, seq: int) -> list[Event] | None:
|
|
381
|
+
"""Buffered events with a sequence number greater than `seq`.
|
|
382
|
+
|
|
383
|
+
Returns None when events after `seq` have already been evicted, in which case the
|
|
384
|
+
caller must resynchronise from a full snapshot instead.
|
|
385
|
+
"""
|
|
386
|
+
with self._lock:
|
|
387
|
+
if seq >= self._seq:
|
|
388
|
+
return []
|
|
389
|
+
if not self._buffer or self._buffer[0].seq > seq + 1:
|
|
390
|
+
return None
|
|
391
|
+
return [e for e in self._buffer if e.seq > seq]
|