pyharnx 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.
- pyharnx/__init__.py +0 -0
- pyharnx/agent/__init__.py +24 -0
- pyharnx/agent/agent.py +210 -0
- pyharnx/agent/loop.py +783 -0
- pyharnx/agent/types.py +275 -0
- pyharnx/cli/__init__.py +5 -0
- pyharnx/cli/approval.py +119 -0
- pyharnx/cli/commands.py +312 -0
- pyharnx/cli/export.html +777 -0
- pyharnx/cli/export.py +634 -0
- pyharnx/cli/json_sink.py +31 -0
- pyharnx/cli/main.py +545 -0
- pyharnx/cli/renderers.py +734 -0
- pyharnx/cli/terminal.py +860 -0
- pyharnx/cli/usage.py +203 -0
- pyharnx/config.py +1050 -0
- pyharnx/llm/__init__.py +34 -0
- pyharnx/llm/catalog.toml +373 -0
- pyharnx/llm/events.py +107 -0
- pyharnx/llm/fake.py +240 -0
- pyharnx/llm/provider.py +81 -0
- pyharnx/llm/providers/__init__.py +130 -0
- pyharnx/llm/providers/_http.py +361 -0
- pyharnx/llm/providers/_single.py +221 -0
- pyharnx/llm/providers/_trace.py +48 -0
- pyharnx/llm/providers/anthropic.py +585 -0
- pyharnx/llm/providers/chat_completions.py +644 -0
- pyharnx/llm/providers/responses.py +705 -0
- pyharnx/llm/registry.py +72 -0
- pyharnx/llm/serde.py +92 -0
- pyharnx/llm/types.py +171 -0
- pyharnx/logs.py +109 -0
- pyharnx/prompts/__init__.py +24 -0
- pyharnx/prompts/environment.py +68 -0
- pyharnx/prompts/project.py +78 -0
- pyharnx/prompts/prompts.toml +116 -0
- pyharnx/prompts/system.py +137 -0
- pyharnx/session/__init__.py +53 -0
- pyharnx/session/recorder.py +160 -0
- pyharnx/session/resume.py +139 -0
- pyharnx/session/store.py +102 -0
- pyharnx/session/transcript.py +416 -0
- pyharnx/tools/__init__.py +43 -0
- pyharnx/tools/base.py +155 -0
- pyharnx/tools/fs.py +309 -0
- pyharnx/tools/html_text.py +179 -0
- pyharnx/tools/registry.py +53 -0
- pyharnx/tools/search.py +270 -0
- pyharnx/tools/shell.py +264 -0
- pyharnx/tools/skills.py +254 -0
- pyharnx/tools/web.py +394 -0
- pyharnx-0.1.0.dist-info/METADATA +269 -0
- pyharnx-0.1.0.dist-info/RECORD +56 -0
- pyharnx-0.1.0.dist-info/WHEEL +4 -0
- pyharnx-0.1.0.dist-info/entry_points.txt +3 -0
- pyharnx-0.1.0.dist-info/licenses/LICENSE +21 -0
pyharnx/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""The agent runtime: a pure loop and a stateful wrapper around it."""
|
|
2
|
+
|
|
3
|
+
from pyharnx.agent.agent import Agent, AgentState
|
|
4
|
+
from pyharnx.agent.loop import run_agent_loop
|
|
5
|
+
from pyharnx.agent.types import (
|
|
6
|
+
AgentContext,
|
|
7
|
+
AgentEvent,
|
|
8
|
+
AgentTool,
|
|
9
|
+
LoopConfig,
|
|
10
|
+
ToolContext,
|
|
11
|
+
ToolResult,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Agent",
|
|
16
|
+
"AgentContext",
|
|
17
|
+
"AgentEvent",
|
|
18
|
+
"AgentState",
|
|
19
|
+
"AgentTool",
|
|
20
|
+
"LoopConfig",
|
|
21
|
+
"ToolContext",
|
|
22
|
+
"ToolResult",
|
|
23
|
+
"run_agent_loop",
|
|
24
|
+
]
|
pyharnx/agent/agent.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Stateful wrapper around the agent loop.
|
|
2
|
+
|
|
3
|
+
Owns the transcript, fans events out to subscribers, and exposes abort. This is
|
|
4
|
+
the object a frontend talks to; `run_agent_loop` stays pure.
|
|
5
|
+
|
|
6
|
+
One run at a time, by design. `prompt()` raises if a run is already in flight
|
|
7
|
+
rather than coordinating with it. That removes the machinery a concurrent model
|
|
8
|
+
would need — a message queue, injection at turn boundaries, an idle barrier —
|
|
9
|
+
and with it the state-divergence bugs that machinery invites. A terminal that
|
|
10
|
+
wants to accept typing mid-run buffers the text itself and calls `prompt()`
|
|
11
|
+
when the run finishes.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import logging
|
|
16
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
from pyharnx.agent.loop import run_agent_loop
|
|
20
|
+
from pyharnx.agent.types import (
|
|
21
|
+
AfterToolCallContext,
|
|
22
|
+
AfterToolCallResult,
|
|
23
|
+
AgentContext,
|
|
24
|
+
AgentEvent,
|
|
25
|
+
AgentTool,
|
|
26
|
+
BeforeToolCallContext,
|
|
27
|
+
BeforeToolCallResult,
|
|
28
|
+
FinishTurnContext,
|
|
29
|
+
FinishTurnResult,
|
|
30
|
+
LoopConfig,
|
|
31
|
+
MessageEnd,
|
|
32
|
+
MessageStart,
|
|
33
|
+
PrepareRequestContext,
|
|
34
|
+
RequestUpdate,
|
|
35
|
+
)
|
|
36
|
+
from pyharnx.config import Config, load_config
|
|
37
|
+
from pyharnx.llm.provider import Provider
|
|
38
|
+
from pyharnx.llm.types import AssistantMessage, Message, Model, UserMessage, text
|
|
39
|
+
|
|
40
|
+
_log = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
Listener = Callable[[AgentEvent], Awaitable[None]]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class AgentState:
|
|
47
|
+
system_prompt: str
|
|
48
|
+
model: Model
|
|
49
|
+
#: Declared to the model on every request, in this order.
|
|
50
|
+
tools: tuple[AgentTool, ...] = ()
|
|
51
|
+
messages: list[Message] = field(default_factory=list)
|
|
52
|
+
is_running: bool = False
|
|
53
|
+
#: Text accumulated for the in-flight assistant message, for renderers that
|
|
54
|
+
#: want the whole thing rather than deltas.
|
|
55
|
+
streaming_message: str = ""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Agent:
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
model: Model,
|
|
63
|
+
provider: Provider,
|
|
64
|
+
system_prompt: str = "",
|
|
65
|
+
tools: tuple[AgentTool, ...] = (),
|
|
66
|
+
config: Config | None = None,
|
|
67
|
+
cwd: str = ".",
|
|
68
|
+
before_tool_call: (
|
|
69
|
+
Callable[[BeforeToolCallContext], Awaitable[BeforeToolCallResult | None]] | None
|
|
70
|
+
) = None,
|
|
71
|
+
after_tool_call: (
|
|
72
|
+
Callable[[AfterToolCallContext], Awaitable[AfterToolCallResult | None]] | None
|
|
73
|
+
) = None,
|
|
74
|
+
prepare_request: (
|
|
75
|
+
Callable[[PrepareRequestContext], Awaitable[RequestUpdate | None]] | None
|
|
76
|
+
) = None,
|
|
77
|
+
finish_turn: (
|
|
78
|
+
Callable[[FinishTurnContext], Awaitable[FinishTurnResult | None]] | None
|
|
79
|
+
) = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
self.state = AgentState(system_prompt=system_prompt, model=model, tools=tools)
|
|
82
|
+
self._provider = provider
|
|
83
|
+
#: Resolved configuration. Public, because a frontend may change what
|
|
84
|
+
#: applies between runs — `/tools` and `/skills` replace it — and the
|
|
85
|
+
#: tools read their settings from it on every call.
|
|
86
|
+
self.config = config if config is not None else load_config()
|
|
87
|
+
self._cwd = cwd
|
|
88
|
+
self._before_tool_call = before_tool_call
|
|
89
|
+
self._after_tool_call = after_tool_call
|
|
90
|
+
self._prepare_request = prepare_request
|
|
91
|
+
self._finish_turn = finish_turn
|
|
92
|
+
self._listeners: list[Listener] = []
|
|
93
|
+
self._signal: asyncio.Event | None = None
|
|
94
|
+
|
|
95
|
+
def restore(self, messages: Sequence[Message]) -> None:
|
|
96
|
+
"""Seed the transcript from a saved session, or rewind it.
|
|
97
|
+
|
|
98
|
+
Deliberately silent: these messages are already on disk, so announcing
|
|
99
|
+
them would make a resumed session re-record its own history on the
|
|
100
|
+
first write. Call it before any `prompt()` to resume, or between runs
|
|
101
|
+
with an earlier part of the same history to rewind: the next run's
|
|
102
|
+
`agent_start` says how much history it starts from, which is what a
|
|
103
|
+
session recorder needs. Messages the session never held cannot be
|
|
104
|
+
recorded that way — start a new session for those.
|
|
105
|
+
"""
|
|
106
|
+
if self.state.is_running:
|
|
107
|
+
raise RuntimeError("Cannot restore while a run is in flight.")
|
|
108
|
+
_log.debug("Restored %d message(s)", len(messages))
|
|
109
|
+
self.state.messages = list(messages)
|
|
110
|
+
|
|
111
|
+
# --- subscriptions ----------------------------------------------------
|
|
112
|
+
|
|
113
|
+
def subscribe(self, listener: Listener) -> Callable[[], None]:
|
|
114
|
+
"""Register an event listener. Returns an unsubscribe callable."""
|
|
115
|
+
self._listeners.append(listener)
|
|
116
|
+
|
|
117
|
+
def unsubscribe() -> None:
|
|
118
|
+
if listener in self._listeners:
|
|
119
|
+
self._listeners.remove(listener)
|
|
120
|
+
|
|
121
|
+
return unsubscribe
|
|
122
|
+
|
|
123
|
+
async def _emit(self, event: AgentEvent) -> None:
|
|
124
|
+
self._reduce(event)
|
|
125
|
+
# Snapshot: a listener may subscribe or unsubscribe while being called.
|
|
126
|
+
for listener in list(self._listeners):
|
|
127
|
+
try:
|
|
128
|
+
await listener(event)
|
|
129
|
+
except Exception:
|
|
130
|
+
# A broken renderer must not take down the run.
|
|
131
|
+
_log.exception("Event listener raised; continuing")
|
|
132
|
+
|
|
133
|
+
def _reduce(self, event: AgentEvent) -> None:
|
|
134
|
+
"""Fold an event into agent state before listeners see it.
|
|
135
|
+
|
|
136
|
+
This owns every append to `state.messages` — including the user
|
|
137
|
+
message, which `prompt()` hands to the loop rather than appending, so
|
|
138
|
+
that this stays the only writer. Every message is announced exactly
|
|
139
|
+
once, so appending anywhere else would duplicate it.
|
|
140
|
+
"""
|
|
141
|
+
if isinstance(event, MessageEnd):
|
|
142
|
+
self.state.messages.append(event.message)
|
|
143
|
+
if isinstance(event.message, AssistantMessage):
|
|
144
|
+
self.state.streaming_message = ""
|
|
145
|
+
elif isinstance(event, MessageStart):
|
|
146
|
+
if isinstance(event.message, AssistantMessage):
|
|
147
|
+
self.state.streaming_message = ""
|
|
148
|
+
elif event.type == "message_update":
|
|
149
|
+
self.state.streaming_message += event.delta
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def cwd(self) -> str:
|
|
153
|
+
"""The working directory tools run in — `--cwd`, else the process's."""
|
|
154
|
+
return self._cwd
|
|
155
|
+
|
|
156
|
+
# --- running ----------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
async def prompt(self, message: str | Message) -> list[Message]:
|
|
159
|
+
"""Send a message and run until the agent stops.
|
|
160
|
+
|
|
161
|
+
Raises if a run is already in flight.
|
|
162
|
+
"""
|
|
163
|
+
# Claim the run in the same synchronous step as the check, so there is
|
|
164
|
+
# no await between testing the flag and setting it.
|
|
165
|
+
if self.state.is_running:
|
|
166
|
+
raise RuntimeError("Agent is already running; wait for prompt() to return.")
|
|
167
|
+
self.state.is_running = True
|
|
168
|
+
self._signal = asyncio.Event()
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
user = UserMessage(content=text(message)) if isinstance(message, str) else message
|
|
172
|
+
# Deliberately not appended here. The loop announces it, and
|
|
173
|
+
# `_reduce` appends it on the way through — keeping `_reduce` the
|
|
174
|
+
# single writer to state.messages with no special case. It still
|
|
175
|
+
# has to reach the provider on this turn, hence `messages` below.
|
|
176
|
+
ctx = AgentContext(
|
|
177
|
+
system_prompt=self.state.system_prompt,
|
|
178
|
+
messages=(*self.state.messages, user),
|
|
179
|
+
tools=self.state.tools,
|
|
180
|
+
unannounced=(user,),
|
|
181
|
+
)
|
|
182
|
+
cfg = LoopConfig(
|
|
183
|
+
model=self.state.model,
|
|
184
|
+
provider=self._provider,
|
|
185
|
+
config=self.config,
|
|
186
|
+
cwd=self._cwd,
|
|
187
|
+
before_tool_call=self._before_tool_call,
|
|
188
|
+
after_tool_call=self._after_tool_call,
|
|
189
|
+
prepare_request=self._prepare_request,
|
|
190
|
+
finish_turn=self._finish_turn,
|
|
191
|
+
signal=self._signal,
|
|
192
|
+
)
|
|
193
|
+
# The loop returns only what it produced; `_reduce` has already
|
|
194
|
+
# appended each of those to state.messages via MessageEnd.
|
|
195
|
+
return await run_agent_loop(ctx, cfg, self._emit)
|
|
196
|
+
finally:
|
|
197
|
+
self.state.is_running = False
|
|
198
|
+
self._signal = None
|
|
199
|
+
|
|
200
|
+
# --- control ----------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
def abort(self) -> None:
|
|
203
|
+
"""Stop the in-flight run. The transcript stays valid to continue from.
|
|
204
|
+
|
|
205
|
+
The signal is cleared when the run ends, so the next `prompt()` starts
|
|
206
|
+
clean rather than being born aborted.
|
|
207
|
+
"""
|
|
208
|
+
if self._signal is not None:
|
|
209
|
+
_log.debug("Abort requested")
|
|
210
|
+
self._signal.set()
|