python-agent-harness 1.5.4.9__tar.gz → 1.5.5.1__tar.gz
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.
- {python_agent_harness-1.5.4.9/python_agent_harness.egg-info → python_agent_harness-1.5.5.1}/PKG-INFO +20 -3
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/README.md +19 -2
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/pyproject.toml +2 -2
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/__init__.py +1 -1
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/agent.py +4 -1
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/cli.py +21 -7
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/client.py +37 -13
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/commands.py +0 -5
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/config.py +27 -4
- python_agent_harness-1.5.5.1/python_agent_harness/prompts/agents/reviewer.md +12 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts.py +57 -2
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/session.py +60 -4
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tool_runner.py +82 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/base.py +5 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/filesystem.py +9 -3
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/glob.py +1 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/grep.py +1 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/read.py +1 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/skill.py +1 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tui/commands.py +78 -1
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tui/core.py +36 -19
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tui/input.py +1 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tui/render.py +23 -8
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1/python_agent_harness.egg-info}/PKG-INFO +20 -3
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness.egg-info/SOURCES.txt +2 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_client.py +128 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_commands.py +0 -1
- python_agent_harness-1.5.5.1/tests/test_custom_agents.py +359 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_session.py +1 -1
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/LICENSE +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/__main__.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/context_manager.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/diffrender.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/mcp/__init__.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/mcp/client.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/mcp/config.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/mcp/manager.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/models.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/persistence.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/planmode.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/agent.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/build-switch.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/commands/explain.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/compact.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/initialize.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/plan-mode.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/plan.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/review.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/subagent.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/summary.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/task-completion-rules.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts/title.md +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/subagent.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/token_estimator.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/__init__.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/agent_tool.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/bash.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/diffapply.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/edit.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/edit_mac.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/glob_mac.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/grep_mac.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/insert.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/mcp.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/mkdir.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/planexit.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/question.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/todo.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tools/write.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/tui/__init__.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness.egg-info/dependency_links.txt +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness.egg-info/entry_points.txt +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness.egg-info/requires.txt +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness.egg-info/top_level.txt +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/setup.cfg +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_agents_md.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_cli.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_concurrent_subagents.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_config.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_context_rules.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_diffrender.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_filesystem.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_invariants.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_mcp.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_models.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_persistence.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_planmode.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_prompts.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_scenarios.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_subagent.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_subagent_isolation.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_todos_scope.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_token_estimator.py +0 -0
- {python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/tests/test_tools_misc.py +0 -0
{python_agent_harness-1.5.4.9/python_agent_harness.egg-info → python_agent_harness-1.5.5.1}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-agent-harness
|
|
3
|
-
Version: 1.5.
|
|
3
|
+
Version: 1.5.5.1
|
|
4
4
|
Summary: A lightweight, hackable mini-OpenCode written in Python.
|
|
5
5
|
Author: huming
|
|
6
6
|
License-Expression: MIT
|
|
@@ -91,14 +91,15 @@ Edit `~/.config/python-agent-harness/config.json` and set your `base_url`, `api_
|
|
|
91
91
|
|
|
92
92
|
## Features
|
|
93
93
|
|
|
94
|
-
- **FSM-driven execution** — explicit `WAIT` / `TOOL` / `TRET` / `SUPERVISE` / `DONE` / `ERRS` / `ABRT` states. Completion supervision nudges the model when it stops early, while failed tool calls are sanitized so they never strand the agent. Transient API failures (`429` / `5xx`) retry with exponential backoff and jitter.
|
|
94
|
+
- **FSM-driven execution** — explicit `WAIT` / `TOOL` / `TRET` / `SUPERVISE` / `DONE` / `ERRS` / `ABRT` states. Completion supervision nudges the model when it stops early, while failed tool calls are sanitized so they never strand the agent. Transient API failures (`429` / `5xx`) retry with exponential backoff and jitter. Auth-expired status codes (configurable via `AUTH_REFRESH_STATUS_CODES` in `config.py`; defaults to `[401, 502]`) trigger automatic API key re-read from config/env — some API gateways return `502` instead of `401` when the backend auth token has expired. Note: codes in this list are treated as auth-expired exclusively and will not be retried with backoff, so only include codes that are unambiguously auth-related in your environment.
|
|
95
95
|
- **Context management** — CJK-aware token estimation, per-model context windows, and automatic compaction at 70% usage.
|
|
96
|
-
- **Coding tools** — `Agent`, `TodoWrite`, `Glob`, `Grep`, `Read`, `Insert`, `Edit` (including unified diffs), `Write`, `Mkdir`, `Bash`, `Skill`, `Question`, and `PlanExit`. Synchronous tools execute sequentially; asynchronous tools such as `Bash` and `Agent` can run concurrently
|
|
96
|
+
- **Coding tools** — `Agent`, `TodoWrite`, `Glob`, `Grep`, `Read`, `Insert`, `Edit` (including unified diffs), `Write`, `Mkdir`, `Bash`, `Skill`, `Question`, and `PlanExit`. Synchronous tools execute sequentially, but a round made up entirely of read-only tools (`Read`, `Glob`, `Grep`, `Skill`) is dispatched concurrently via a bounded thread pool; asynchronous tools such as `Bash` and `Agent` can run concurrently as well. Results are always delivered in the model's emitted order.
|
|
97
97
|
- **Plan / Build modes** — plan mode is read-only except for the per-session plan file.
|
|
98
98
|
- **Persistent sessions** — sessions are automatically saved after every response to `~/.local/share/python-agent-harness/sessions/`, with LLM-generated titles and support for `/restore --latest` and `/sessions`.
|
|
99
99
|
- **Focused TUI** — a Rich-based interface with a pinned status bar, Todos panel, inline red/green diff rendering for `Edit` and `Write`, and a `prompt_toolkit` editor with history and completion. `Esc+Enter` submits, `Ctrl-D` quits, and `Ctrl-C` cancels without leaving the application.
|
|
100
100
|
- **MCP support** — optional MCP integration through the `[mcp]` extra. MCP tools become ordinary agent tools such as `mcp__<server>__<tool>`. Supports `stdio`, `streamable-http`, and `sse` transports.
|
|
101
101
|
- **Slash commands** — built-in `/init`, `/review`, `/explain`, and other commands, plus custom commands loaded from `prompts/commands/*.md`.
|
|
102
|
+
- **Custom agents** — switch the main agent's system prompt at runtime with `/agent`. Agent prompt files live in `prompts/agents/*.md`. Use `default_agent` in the config file to start sessions with a specific agent.
|
|
102
103
|
|
|
103
104
|
## Inspired by opencode
|
|
104
105
|
|
|
@@ -160,6 +161,7 @@ All LLM settings live in a single JSON configuration file. Environment variables
|
|
|
160
161
|
"reasoning_effort": null,
|
|
161
162
|
"stream": null
|
|
162
163
|
},
|
|
164
|
+
"default_agent": null,
|
|
163
165
|
"paths": {
|
|
164
166
|
"context_path": null,
|
|
165
167
|
"skill_path": null
|
|
@@ -190,6 +192,7 @@ All LLM settings live in a single JSON configuration file. Environment variables
|
|
|
190
192
|
- **`models`** — named LLM profiles for runtime switching with `/model`. A profile is a partial settings dictionary; unset keys inherit from the main `llm`. `default` restores the main LLM configuration.
|
|
191
193
|
- **`context_windows`** — optional per-model context-window overrides (tokens). Keys are model names or substrings (e.g., `deepseek-v4`); matched in file order, first match wins. Overrides the built-in `CONTEXT_WINDOWS` table in `config.py`.
|
|
192
194
|
- **`subagent_llm`** — LLM configuration for `Agent` tool requests. Unset values inherit from the main `llm`. Set `profile` to reuse a profile from `models`. Precedence is: profile settings > explicit `subagent_llm` settings > main `llm` > environment variables.
|
|
195
|
+
- **`default_agent`** — name of the agent to use at session start (instead of the built-in `agent.md`). The agent must exist as a `.md` file in the `prompts/agents/` directory. When unset or `null`, the built-in default agent is used. Use `/agent default` in the TUI to switch back to the built-in at any time.
|
|
193
196
|
- **`paths.context_path` / `paths.skill_path`** — locations from which to load context files and skills. When unset, the project-local `<project>/contexts` and `<project>/skills` directories are used.
|
|
194
197
|
- **`mcp.servers`** — MCP server configuration. Requires the `[mcp]` extra. Each server supports `transport`, `command`, `args`, `env`, `url`, `headers`, `parallel`, `timeout`, and `enabled`.
|
|
195
198
|
- **Configuration precedence** — code defaults < config file < `OPENAI_*` environment variables. Sub-agent settings also support `OPENAI_SUBAGENT_*` (`_BASE_URL`, `_API_KEY`, `_MODEL`).
|
|
@@ -219,10 +222,24 @@ Launches the interactive TUI agent. If `project-dir` is omitted, the current dir
|
|
|
219
222
|
| `/restore [path\|title\|--latest\|latest]` | Restore a session; title matching uses substring search |
|
|
220
223
|
| `/clear` | Start a fresh conversation |
|
|
221
224
|
| `/model [name]` | Switch LLM profiles; `default` restores the session's original model |
|
|
225
|
+
| `/agent [name]` | Switch agent system prompt; `default` restores the built-in `agent.md` |
|
|
222
226
|
| `/exit` | Quit |
|
|
223
227
|
|
|
224
228
|
Custom commands from `prompts/commands/*.md` are registered as slash commands as well (TUI only).
|
|
225
229
|
|
|
230
|
+
### Custom agents
|
|
231
|
+
|
|
232
|
+
Agent prompt files are markdown files (`.md`) placed in the `prompts/agents/` directory. Each file becomes a switchable agent profile available via the `/agent` TUI command.
|
|
233
|
+
|
|
234
|
+
#### Commands vs Agents
|
|
235
|
+
|
|
236
|
+
| | Commands (`/review`) | Agents (`/agent reviewer`) |
|
|
237
|
+
|---|---|---|
|
|
238
|
+
| **Scope** | One-shot (prompt resets after run) | Persistent (stays until next `/agent`) |
|
|
239
|
+
| **Kickoff** | Hardcoded kickoff message | User types their own prompt |
|
|
240
|
+
| **Tools** | Can restrict (`allow_planexit=False`) | All tools |
|
|
241
|
+
| **Ctrl-C** | Restores to default prompt | Stays on the custom agent |
|
|
242
|
+
|
|
226
243
|
## Project layout
|
|
227
244
|
|
|
228
245
|
```text
|
|
@@ -68,14 +68,15 @@ Edit `~/.config/python-agent-harness/config.json` and set your `base_url`, `api_
|
|
|
68
68
|
|
|
69
69
|
## Features
|
|
70
70
|
|
|
71
|
-
- **FSM-driven execution** — explicit `WAIT` / `TOOL` / `TRET` / `SUPERVISE` / `DONE` / `ERRS` / `ABRT` states. Completion supervision nudges the model when it stops early, while failed tool calls are sanitized so they never strand the agent. Transient API failures (`429` / `5xx`) retry with exponential backoff and jitter.
|
|
71
|
+
- **FSM-driven execution** — explicit `WAIT` / `TOOL` / `TRET` / `SUPERVISE` / `DONE` / `ERRS` / `ABRT` states. Completion supervision nudges the model when it stops early, while failed tool calls are sanitized so they never strand the agent. Transient API failures (`429` / `5xx`) retry with exponential backoff and jitter. Auth-expired status codes (configurable via `AUTH_REFRESH_STATUS_CODES` in `config.py`; defaults to `[401, 502]`) trigger automatic API key re-read from config/env — some API gateways return `502` instead of `401` when the backend auth token has expired. Note: codes in this list are treated as auth-expired exclusively and will not be retried with backoff, so only include codes that are unambiguously auth-related in your environment.
|
|
72
72
|
- **Context management** — CJK-aware token estimation, per-model context windows, and automatic compaction at 70% usage.
|
|
73
|
-
- **Coding tools** — `Agent`, `TodoWrite`, `Glob`, `Grep`, `Read`, `Insert`, `Edit` (including unified diffs), `Write`, `Mkdir`, `Bash`, `Skill`, `Question`, and `PlanExit`. Synchronous tools execute sequentially; asynchronous tools such as `Bash` and `Agent` can run concurrently
|
|
73
|
+
- **Coding tools** — `Agent`, `TodoWrite`, `Glob`, `Grep`, `Read`, `Insert`, `Edit` (including unified diffs), `Write`, `Mkdir`, `Bash`, `Skill`, `Question`, and `PlanExit`. Synchronous tools execute sequentially, but a round made up entirely of read-only tools (`Read`, `Glob`, `Grep`, `Skill`) is dispatched concurrently via a bounded thread pool; asynchronous tools such as `Bash` and `Agent` can run concurrently as well. Results are always delivered in the model's emitted order.
|
|
74
74
|
- **Plan / Build modes** — plan mode is read-only except for the per-session plan file.
|
|
75
75
|
- **Persistent sessions** — sessions are automatically saved after every response to `~/.local/share/python-agent-harness/sessions/`, with LLM-generated titles and support for `/restore --latest` and `/sessions`.
|
|
76
76
|
- **Focused TUI** — a Rich-based interface with a pinned status bar, Todos panel, inline red/green diff rendering for `Edit` and `Write`, and a `prompt_toolkit` editor with history and completion. `Esc+Enter` submits, `Ctrl-D` quits, and `Ctrl-C` cancels without leaving the application.
|
|
77
77
|
- **MCP support** — optional MCP integration through the `[mcp]` extra. MCP tools become ordinary agent tools such as `mcp__<server>__<tool>`. Supports `stdio`, `streamable-http`, and `sse` transports.
|
|
78
78
|
- **Slash commands** — built-in `/init`, `/review`, `/explain`, and other commands, plus custom commands loaded from `prompts/commands/*.md`.
|
|
79
|
+
- **Custom agents** — switch the main agent's system prompt at runtime with `/agent`. Agent prompt files live in `prompts/agents/*.md`. Use `default_agent` in the config file to start sessions with a specific agent.
|
|
79
80
|
|
|
80
81
|
## Inspired by opencode
|
|
81
82
|
|
|
@@ -137,6 +138,7 @@ All LLM settings live in a single JSON configuration file. Environment variables
|
|
|
137
138
|
"reasoning_effort": null,
|
|
138
139
|
"stream": null
|
|
139
140
|
},
|
|
141
|
+
"default_agent": null,
|
|
140
142
|
"paths": {
|
|
141
143
|
"context_path": null,
|
|
142
144
|
"skill_path": null
|
|
@@ -167,6 +169,7 @@ All LLM settings live in a single JSON configuration file. Environment variables
|
|
|
167
169
|
- **`models`** — named LLM profiles for runtime switching with `/model`. A profile is a partial settings dictionary; unset keys inherit from the main `llm`. `default` restores the main LLM configuration.
|
|
168
170
|
- **`context_windows`** — optional per-model context-window overrides (tokens). Keys are model names or substrings (e.g., `deepseek-v4`); matched in file order, first match wins. Overrides the built-in `CONTEXT_WINDOWS` table in `config.py`.
|
|
169
171
|
- **`subagent_llm`** — LLM configuration for `Agent` tool requests. Unset values inherit from the main `llm`. Set `profile` to reuse a profile from `models`. Precedence is: profile settings > explicit `subagent_llm` settings > main `llm` > environment variables.
|
|
172
|
+
- **`default_agent`** — name of the agent to use at session start (instead of the built-in `agent.md`). The agent must exist as a `.md` file in the `prompts/agents/` directory. When unset or `null`, the built-in default agent is used. Use `/agent default` in the TUI to switch back to the built-in at any time.
|
|
170
173
|
- **`paths.context_path` / `paths.skill_path`** — locations from which to load context files and skills. When unset, the project-local `<project>/contexts` and `<project>/skills` directories are used.
|
|
171
174
|
- **`mcp.servers`** — MCP server configuration. Requires the `[mcp]` extra. Each server supports `transport`, `command`, `args`, `env`, `url`, `headers`, `parallel`, `timeout`, and `enabled`.
|
|
172
175
|
- **Configuration precedence** — code defaults < config file < `OPENAI_*` environment variables. Sub-agent settings also support `OPENAI_SUBAGENT_*` (`_BASE_URL`, `_API_KEY`, `_MODEL`).
|
|
@@ -196,10 +199,24 @@ Launches the interactive TUI agent. If `project-dir` is omitted, the current dir
|
|
|
196
199
|
| `/restore [path\|title\|--latest\|latest]` | Restore a session; title matching uses substring search |
|
|
197
200
|
| `/clear` | Start a fresh conversation |
|
|
198
201
|
| `/model [name]` | Switch LLM profiles; `default` restores the session's original model |
|
|
202
|
+
| `/agent [name]` | Switch agent system prompt; `default` restores the built-in `agent.md` |
|
|
199
203
|
| `/exit` | Quit |
|
|
200
204
|
|
|
201
205
|
Custom commands from `prompts/commands/*.md` are registered as slash commands as well (TUI only).
|
|
202
206
|
|
|
207
|
+
### Custom agents
|
|
208
|
+
|
|
209
|
+
Agent prompt files are markdown files (`.md`) placed in the `prompts/agents/` directory. Each file becomes a switchable agent profile available via the `/agent` TUI command.
|
|
210
|
+
|
|
211
|
+
#### Commands vs Agents
|
|
212
|
+
|
|
213
|
+
| | Commands (`/review`) | Agents (`/agent reviewer`) |
|
|
214
|
+
|---|---|---|
|
|
215
|
+
| **Scope** | One-shot (prompt resets after run) | Persistent (stays until next `/agent`) |
|
|
216
|
+
| **Kickoff** | Hardcoded kickoff message | User types their own prompt |
|
|
217
|
+
| **Tools** | Can restrict (`allow_planexit=False`) | All tools |
|
|
218
|
+
| **Ctrl-C** | Restores to default prompt | Stays on the custom agent |
|
|
219
|
+
|
|
203
220
|
## Project layout
|
|
204
221
|
|
|
205
222
|
```text
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "python-agent-harness"
|
|
7
|
-
version = "1.5.
|
|
7
|
+
version = "1.5.5.1"
|
|
8
8
|
description = "A lightweight, hackable mini-OpenCode written in Python."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -49,7 +49,7 @@ python-agent-harness = "python_agent_harness.cli:main"
|
|
|
49
49
|
include = ["python_agent_harness*"]
|
|
50
50
|
|
|
51
51
|
[tool.setuptools.package-data]
|
|
52
|
-
python_agent_harness = ["prompts/*.md", "prompts/commands/*.md"]
|
|
52
|
+
python_agent_harness = ["prompts/*.md", "prompts/commands/*.md", "prompts/agents/*.md"]
|
|
53
53
|
|
|
54
54
|
[tool.ruff]
|
|
55
55
|
line-length = 100
|
|
@@ -493,7 +493,10 @@ class AgentLoop:
|
|
|
493
493
|
return # cancelled (Ctrl-C), not an error
|
|
494
494
|
self.error = f"Error: {e}"
|
|
495
495
|
self.info["error"] = self.error
|
|
496
|
-
|
|
496
|
+
# the detail travels with the notification so the TUI can
|
|
497
|
+
# show WHAT failed (e.g. "no quota") in the status bar
|
|
498
|
+
# instead of a bare red "error"
|
|
499
|
+
session.notify("error", self.error)
|
|
497
500
|
return
|
|
498
501
|
|
|
499
502
|
if self._is_cancelled():
|
|
@@ -20,6 +20,7 @@ import sys
|
|
|
20
20
|
|
|
21
21
|
from . import config
|
|
22
22
|
from .client import Client
|
|
23
|
+
from .prompts import RESERVED_AGENT_NAME
|
|
23
24
|
from .session import Session
|
|
24
25
|
from .tools import default_registry
|
|
25
26
|
|
|
@@ -91,13 +92,14 @@ def make_session(
|
|
|
91
92
|
# (same precedence as the main agent's stream).
|
|
92
93
|
effective_stream = settings["stream"] if stream is None else stream
|
|
93
94
|
model_profiles = config.load_models_config(config_path)
|
|
95
|
+
default_agent = config.load_default_agent(config_path)
|
|
94
96
|
# Base settings for /model switching: the main llm settings as
|
|
95
97
|
# resolved at session start (incl. the CLI --model/--no-stream
|
|
96
98
|
# overrides above), so a profile's unset keys inherit these
|
|
97
99
|
# instead of values drifted by earlier switches.
|
|
98
100
|
llm_settings = dict(settings)
|
|
99
101
|
llm_settings["stream"] = effective_stream
|
|
100
|
-
|
|
102
|
+
session = Session(
|
|
101
103
|
project_dir=abs_project,
|
|
102
104
|
client=client,
|
|
103
105
|
model=model,
|
|
@@ -117,9 +119,18 @@ def make_session(
|
|
|
117
119
|
skill_path=paths.get("skill_path"),
|
|
118
120
|
mcp=mcp_config,
|
|
119
121
|
model_profiles=model_profiles,
|
|
122
|
+
default_agent=default_agent,
|
|
120
123
|
llm_settings=llm_settings,
|
|
121
124
|
config_path=config_path,
|
|
122
125
|
)
|
|
126
|
+
if default_agent and default_agent != RESERVED_AGENT_NAME:
|
|
127
|
+
ok, msg = session.switch_agent(default_agent)
|
|
128
|
+
if not ok:
|
|
129
|
+
# A typo'd/missing default_agent must not silently start the
|
|
130
|
+
# session with the built-in prompt — record the config error
|
|
131
|
+
# so the TUI can surface it (see Tui.run).
|
|
132
|
+
session.startup_warnings.append(f"default_agent: {msg}")
|
|
133
|
+
return session
|
|
123
134
|
|
|
124
135
|
|
|
125
136
|
def make_session_with_mcp(
|
|
@@ -132,14 +143,14 @@ def make_session_with_mcp(
|
|
|
132
143
|
|
|
133
144
|
Wraps ``make_session``: the session's MCP servers are connected and
|
|
134
145
|
their tools registered before the session is returned (discovery
|
|
135
|
-
happens once, at session start). Per-server failures are
|
|
136
|
-
|
|
137
|
-
keeps working with the
|
|
146
|
+
happens once, at session start). Per-server failures are recorded
|
|
147
|
+
as startup warnings (rendered by the TUI banner) and never prevent
|
|
148
|
+
the session from running — the agent keeps working with the
|
|
149
|
+
built-in tools.
|
|
138
150
|
"""
|
|
139
151
|
session = make_session(project_dir, config_path=config_path, model=model, stream=stream)
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
print(f"python-agent-harness: [{server}] {err}", file=sys.stderr)
|
|
152
|
+
for server, err in session.connect_mcp():
|
|
153
|
+
session.startup_warnings.append(f"MCP [{server}]: {err}")
|
|
143
154
|
return session
|
|
144
155
|
|
|
145
156
|
|
|
@@ -228,6 +239,9 @@ def cmd_config(args: argparse.Namespace) -> int:
|
|
|
228
239
|
print(f" {pattern}: {size}")
|
|
229
240
|
else:
|
|
230
241
|
print("context_windows: (none configured — built-in table in config.py applies)")
|
|
242
|
+
# Show default agent
|
|
243
|
+
default_agent = config.load_default_agent(args.path)
|
|
244
|
+
print(f"default_agent: {default_agent or '(default: agent.md)'}")
|
|
231
245
|
return 0
|
|
232
246
|
|
|
233
247
|
|
{python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/client.py
RENAMED
|
@@ -36,6 +36,14 @@ class ApiError(Exception):
|
|
|
36
36
|
"""Raised when the API call itself fails (network/HTTP)."""
|
|
37
37
|
|
|
38
38
|
|
|
39
|
+
# Grace between shutdown(SHUT_RDWR) and close() of an in-flight socket
|
|
40
|
+
# on macOS (see _shutdown_and_close): 50ms proved too tight under load
|
|
41
|
+
# (the woken thread can still be parked in select() when the fd is
|
|
42
|
+
# released, losing the wakeup). 200ms keeps Ctrl-C responsive while
|
|
43
|
+
# making the fd-reuse race vanishingly unlikely.
|
|
44
|
+
_ABORT_SHUTDOWN_GRACE_S = 0.2
|
|
45
|
+
|
|
46
|
+
|
|
39
47
|
class RetryableApiError(ApiError):
|
|
40
48
|
"""A transient failure (rate limit, server error) safe to retry.
|
|
41
49
|
|
|
@@ -49,9 +57,12 @@ class RetryableApiError(ApiError):
|
|
|
49
57
|
|
|
50
58
|
|
|
51
59
|
class AuthExpiredError(ApiError):
|
|
52
|
-
"""Raised on HTTP
|
|
60
|
+
"""Raised on auth-expired HTTP status codes.
|
|
53
61
|
|
|
54
|
-
|
|
62
|
+
By default HTTP 401, but customizable via
|
|
63
|
+
``config.AUTH_REFRESH_STATUS_CODES`` — some API gateways return 502
|
|
64
|
+
or other codes when the backend auth token has expired. Handled
|
|
65
|
+
specially in the retry loop: the API key is re-read from
|
|
55
66
|
config/environment (an external process may have refreshed the
|
|
56
67
|
token) and the request is retried once with the new key. If the
|
|
57
68
|
key hasn't changed, the error is permanent and propagated as a
|
|
@@ -60,7 +71,13 @@ class AuthExpiredError(ApiError):
|
|
|
60
71
|
|
|
61
72
|
|
|
62
73
|
def _retryable_status(status: int) -> bool:
|
|
63
|
-
"""429 and 5xx are transient; every other error is permanent.
|
|
74
|
+
"""429 and 5xx are transient; every other error is permanent.
|
|
75
|
+
|
|
76
|
+
Status codes in ``config.AUTH_REFRESH_STATUS_CODES`` are excluded —
|
|
77
|
+
they are handled as auth-expired, not retried with backoff.
|
|
78
|
+
"""
|
|
79
|
+
if status in config.AUTH_REFRESH_STATUS_CODES:
|
|
80
|
+
return False
|
|
64
81
|
return status == 429 or status >= 500
|
|
65
82
|
|
|
66
83
|
|
|
@@ -508,12 +525,14 @@ class Client:
|
|
|
508
525
|
if self._sleep_backoff(attempt, e.retry_after, cancel_check):
|
|
509
526
|
raise
|
|
510
527
|
except AuthExpiredError as e:
|
|
511
|
-
#
|
|
512
|
-
#
|
|
513
|
-
#
|
|
514
|
-
#
|
|
515
|
-
#
|
|
516
|
-
#
|
|
528
|
+
# Auth-expired status code (401, or any code in
|
|
529
|
+
# config.AUTH_REFRESH_STATUS_CODES): the credential
|
|
530
|
+
# (often a JWT with a short TTL) may have expired.
|
|
531
|
+
# Re-read the API key from the config file / environment
|
|
532
|
+
# — an external token-refresh process may have written a
|
|
533
|
+
# new one. Poll for up to 30s waiting for the key to
|
|
534
|
+
# change; retry once if it does. Fail immediately if
|
|
535
|
+
# already refreshed once
|
|
517
536
|
# (prevents infinite loops).
|
|
518
537
|
self._reset_http()
|
|
519
538
|
if auth_refreshed or not self._refresh_api_key(cancel_check):
|
|
@@ -635,7 +654,7 @@ class Client:
|
|
|
635
654
|
if resp.status_code >= 400:
|
|
636
655
|
body = resp.read().decode("utf-8", "replace")
|
|
637
656
|
message = f"API error {resp.status_code}: {body[:500]}"
|
|
638
|
-
if resp.status_code
|
|
657
|
+
if resp.status_code in config.AUTH_REFRESH_STATUS_CODES:
|
|
639
658
|
raise AuthExpiredError(message)
|
|
640
659
|
if _retryable_status(resp.status_code):
|
|
641
660
|
raise RetryableApiError(message, resp.headers.get("Retry-After"))
|
|
@@ -697,7 +716,7 @@ class Client:
|
|
|
697
716
|
resp = self._http.post(self._url(), headers=self._headers(stream=False), json=payload)
|
|
698
717
|
if resp.status_code >= 400:
|
|
699
718
|
message = f"API error {resp.status_code}: {resp.text[:500]}"
|
|
700
|
-
if resp.status_code
|
|
719
|
+
if resp.status_code in config.AUTH_REFRESH_STATUS_CODES:
|
|
701
720
|
raise AuthExpiredError(message)
|
|
702
721
|
if _retryable_status(resp.status_code):
|
|
703
722
|
raise RetryableApiError(message, resp.headers.get("Retry-After"))
|
|
@@ -854,12 +873,17 @@ def _shutdown_and_close(sock: _socket.socket) -> None:
|
|
|
854
873
|
settimeout for the read timeout), so a blocked recv parks in
|
|
855
874
|
select(); closing the fd before that select has processed the
|
|
856
875
|
shutdown wakeup can lose the wakeup and leave the read parked
|
|
857
|
-
forever.
|
|
876
|
+
forever. Worse, ``abort()`` swaps in a fresh httpx client right
|
|
877
|
+
after, so a new socket could reuse the fd number before the
|
|
878
|
+
reader observed the EOF. The grace sleep delays the fd release
|
|
879
|
+
so the woken thread can observe the EOF on the old fd first.
|
|
858
880
|
"""
|
|
859
881
|
with contextlib.suppress(OSError):
|
|
860
882
|
sock.shutdown(_socket.SHUT_RDWR)
|
|
861
883
|
if sys.platform == "darwin":
|
|
862
|
-
|
|
884
|
+
# macOS only; on Linux shutdown() alone reliably wakes the
|
|
885
|
+
# blocked recv (measured: <200ms unblock, no sleeps needed).
|
|
886
|
+
time.sleep(_ABORT_SHUTDOWN_GRACE_S)
|
|
863
887
|
with contextlib.suppress(OSError):
|
|
864
888
|
sock.close()
|
|
865
889
|
|
{python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/commands.py
RENAMED
|
@@ -63,7 +63,6 @@ class SessionCommand:
|
|
|
63
63
|
name: str,
|
|
64
64
|
prompt_file: str,
|
|
65
65
|
kickoff: str,
|
|
66
|
-
buffer_name: str,
|
|
67
66
|
status: str,
|
|
68
67
|
validate_dir: bool = False,
|
|
69
68
|
allow_planexit: bool = True,
|
|
@@ -71,7 +70,6 @@ class SessionCommand:
|
|
|
71
70
|
self.name = name
|
|
72
71
|
self.prompt_file = prompt_file
|
|
73
72
|
self.kickoff = kickoff
|
|
74
|
-
self.buffer_name = buffer_name
|
|
75
73
|
self.status = status
|
|
76
74
|
self.validate_dir = validate_dir
|
|
77
75
|
self.allow_planexit = allow_planexit
|
|
@@ -99,7 +97,6 @@ def initialize_command() -> SessionCommand:
|
|
|
99
97
|
name="initialize",
|
|
100
98
|
prompt_file="initialize.md",
|
|
101
99
|
kickoff="Analyze the repository at ${path} and create/update AGENTS.md.\n",
|
|
102
|
-
buffer_name="*gptel-agent-init:*",
|
|
103
100
|
status=" Initializing...",
|
|
104
101
|
validate_dir=True,
|
|
105
102
|
allow_planexit=False,
|
|
@@ -111,7 +108,6 @@ def review_command() -> SessionCommand:
|
|
|
111
108
|
name="review",
|
|
112
109
|
prompt_file="review.md",
|
|
113
110
|
kickoff="Review the requested code changes.",
|
|
114
|
-
buffer_name="*gptel-agent-review*",
|
|
115
111
|
status=" Reviewing...",
|
|
116
112
|
allow_planexit=False,
|
|
117
113
|
)
|
|
@@ -161,7 +157,6 @@ def load_custom_commands() -> list[SessionCommand]:
|
|
|
161
157
|
name=name,
|
|
162
158
|
prompt_file=str(f.relative_to(PROMPTS_DIR)),
|
|
163
159
|
kickoff="Proceed with the task described in your instructions.\n",
|
|
164
|
-
buffer_name=f"*gptel-agent-{name}*",
|
|
165
160
|
status=f" Running {name}...",
|
|
166
161
|
)
|
|
167
162
|
)
|
{python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/config.py
RENAMED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
"""Configuration defaults for python-agent-harness.
|
|
2
|
-
|
|
3
|
-
Mirrors the defcustom defaults of the Emacs gptel-agent-harness.
|
|
4
|
-
"""
|
|
1
|
+
"""Configuration defaults for python-agent-harness."""
|
|
5
2
|
|
|
6
3
|
from __future__ import annotations
|
|
7
4
|
|
|
@@ -131,6 +128,14 @@ API_RETRY_MAX = 3 # max attempts per request (initial + retries)
|
|
|
131
128
|
API_RETRY_BASE_DELAY = 1.0 # base backoff (seconds), doubled per attempt
|
|
132
129
|
API_RETRY_MAX_DELAY = 30.0 # per-attempt backoff cap (seconds)
|
|
133
130
|
|
|
131
|
+
# HTTP status codes that should trigger auth-refresh (key re-read from
|
|
132
|
+
# config/env) instead of being treated as transient retryable errors.
|
|
133
|
+
# 401 is always included (standard "Unauthorized"). Some API gateways
|
|
134
|
+
# return 502 or other 5xx codes when the backend auth token has expired
|
|
135
|
+
# rather than a proper 401 — add those here so the client refreshes the
|
|
136
|
+
# key instead of pointlessly retrying the same expired credential.
|
|
137
|
+
AUTH_REFRESH_STATUS_CODES: list[int] = [401, 502]
|
|
138
|
+
|
|
134
139
|
# ---- tool execution ----------------------------------------------------------
|
|
135
140
|
SUBAGENT_MAX_ROUNDS = 60
|
|
136
141
|
# Tool execution mirrors gptel's `gptel--handle-tool-use': synchronous
|
|
@@ -234,6 +239,7 @@ CONFIG_TEMPLATE = """\
|
|
|
234
239
|
"reasoning_effort": null,
|
|
235
240
|
"stream": null
|
|
236
241
|
}},
|
|
242
|
+
"default_agent": null,
|
|
237
243
|
"paths": {{
|
|
238
244
|
"_comment": "Optional overrides for context and skill directories. Absolute paths or ~ expansion supported.",
|
|
239
245
|
"context_path": null,
|
|
@@ -453,6 +459,23 @@ def load_models_config(path: str | os.PathLike | None = None) -> dict[str, dict]
|
|
|
453
459
|
return profiles
|
|
454
460
|
|
|
455
461
|
|
|
462
|
+
def load_default_agent(path: str | os.PathLike | None = None) -> str | None:
|
|
463
|
+
"""Load the default agent name from the config file's ``default_agent`` key.
|
|
464
|
+
|
|
465
|
+
Returns the agent name (str) when set, or None when unset (meaning
|
|
466
|
+
use the built-in ``default`` agent, i.e. ``prompts/agent.md``).
|
|
467
|
+
"""
|
|
468
|
+
data = _read_config(path)
|
|
469
|
+
val = data.get("default_agent")
|
|
470
|
+
if val is None:
|
|
471
|
+
return None
|
|
472
|
+
if not isinstance(val, str) or not val.strip():
|
|
473
|
+
raise ValueError(
|
|
474
|
+
f"config file {_config_path(path)}: default_agent must be a non-empty string"
|
|
475
|
+
)
|
|
476
|
+
return val.strip()
|
|
477
|
+
|
|
478
|
+
|
|
456
479
|
def mask_secret(value: str | None) -> str:
|
|
457
480
|
return "****" if value else "(unset)"
|
|
458
481
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Role and Behavior
|
|
2
|
+
You are a code reviewer agent. Your job is to review code changes
|
|
3
|
+
thoroughly and provide constructive feedback.
|
|
4
|
+
|
|
5
|
+
Focus on:
|
|
6
|
+
- Correctness and potential bugs
|
|
7
|
+
- Code style and readability
|
|
8
|
+
- Performance implications
|
|
9
|
+
- Security concerns
|
|
10
|
+
- Test coverage
|
|
11
|
+
|
|
12
|
+
Always provide actionable suggestions with specific file and line references.
|
{python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/prompts.py
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Prompt loading and assembly.
|
|
2
2
|
|
|
3
3
|
Ported from gptel-agent-harness.el: loads bundled prompt files
|
|
4
|
-
(agent/subagent/commands), strips YAML frontmatter, discovers skills
|
|
4
|
+
(agent/subagent/commands/custom agents), strips YAML frontmatter, discovers skills
|
|
5
5
|
for the {{SKILLS}} placeholder, assembles the effective system prompt
|
|
6
6
|
from project context files + task-completion rules + agent prompt, and
|
|
7
7
|
provides the compaction flow helpers (summarize the conversation with
|
|
@@ -22,10 +22,16 @@ from typing import Any
|
|
|
22
22
|
from . import config
|
|
23
23
|
from .models import Message
|
|
24
24
|
|
|
25
|
+
PROMPTS_DIR = Path(__file__).parent / "prompts"
|
|
26
|
+
AGENTS_DIR = PROMPTS_DIR / "agents"
|
|
27
|
+
# Reserved pseudo-name that restores the built-in agent (prompts/agent.md);
|
|
28
|
+
# custom agent files cannot claim it (see discover_agents).
|
|
29
|
+
RESERVED_AGENT_NAME = "default"
|
|
30
|
+
|
|
25
31
|
|
|
26
32
|
def read_prompt_file(name: str) -> str:
|
|
27
33
|
"""Read a prompt file from the package prompts dir."""
|
|
28
|
-
path =
|
|
34
|
+
path = PROMPTS_DIR / name
|
|
29
35
|
return path.read_text(encoding="utf-8")
|
|
30
36
|
|
|
31
37
|
|
|
@@ -496,3 +502,52 @@ def compacted_messages(summary: str, prompts: list[str]) -> list[Message]:
|
|
|
496
502
|
Message(role="user", content=frame),
|
|
497
503
|
*[Message(role="user", content=p) for p in prompts],
|
|
498
504
|
]
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
# ---- custom agent discovery -----------------------------------------------
|
|
508
|
+
# Agent prompt files are markdown files (``*.md``) in
|
|
509
|
+
# ``prompts/agents/``. Each file becomes a switchable agent profile
|
|
510
|
+
# available via the ``/agent`` TUI command. The file's stem (e.g.
|
|
511
|
+
# ``reviewer.md`` → ``reviewer``) is the agent name; an optional YAML
|
|
512
|
+
# frontmatter ``name:`` can override it. The built-in ``default``
|
|
513
|
+
# agent (``prompts/agent.md``) is always available and cannot be
|
|
514
|
+
# overridden by a file in this directory.
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _agent_name_from_file(path: Path) -> str:
|
|
518
|
+
"""Derive agent name from a file: frontmatter ``name:`` if present,
|
|
519
|
+
otherwise the file stem (lowercased, non-alphanumerics → ``-``)."""
|
|
520
|
+
try:
|
|
521
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
522
|
+
except OSError:
|
|
523
|
+
return ""
|
|
524
|
+
m = _FRONTMATTER_RE.match(text)
|
|
525
|
+
if m:
|
|
526
|
+
for line in m.group(0).splitlines():
|
|
527
|
+
if line.startswith("name:"):
|
|
528
|
+
name = line[len("name:") :].strip()
|
|
529
|
+
if name:
|
|
530
|
+
return name
|
|
531
|
+
base = path.stem.lower()
|
|
532
|
+
base = re.sub(r"[^a-z0-9]+", "-", base)
|
|
533
|
+
return base.strip("-")
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def discover_agents() -> dict[str, str]:
|
|
537
|
+
"""Discover all custom agents in the ``prompts/agents/`` directory.
|
|
538
|
+
|
|
539
|
+
Returns a dict mapping agent name → absolute path to the prompt
|
|
540
|
+
file. Files without a valid name are skipped. The built-in
|
|
541
|
+
``default`` agent is NOT included here — callers add it separately.
|
|
542
|
+
A file claiming the reserved name ``default`` (via stem or
|
|
543
|
+
frontmatter) is skipped: the built-in agent always wins.
|
|
544
|
+
"""
|
|
545
|
+
if not AGENTS_DIR.is_dir():
|
|
546
|
+
return {}
|
|
547
|
+
agents: dict[str, str] = {}
|
|
548
|
+
for f in sorted(AGENTS_DIR.glob("*.md")):
|
|
549
|
+
name = _agent_name_from_file(f)
|
|
550
|
+
if not name or name == RESERVED_AGENT_NAME:
|
|
551
|
+
continue
|
|
552
|
+
agents[name] = str(f.resolve())
|
|
553
|
+
return agents
|
{python_agent_harness-1.5.4.9 → python_agent_harness-1.5.5.1}/python_agent_harness/session.py
RENAMED
|
@@ -22,7 +22,7 @@ from .mcp.manager import MCPManager
|
|
|
22
22
|
from .models import AgentMode
|
|
23
23
|
from .persistence import SessionPersistence, escape_role_headers
|
|
24
24
|
from .planmode import PlanMode
|
|
25
|
-
from .prompts import index_skills
|
|
25
|
+
from .prompts import RESERVED_AGENT_NAME, discover_agents, index_skills
|
|
26
26
|
from .subagent import run_subagent
|
|
27
27
|
from .token_estimator import TokenCalibrator
|
|
28
28
|
from .tools import Registry, ToolContext
|
|
@@ -89,6 +89,7 @@ class Session:
|
|
|
89
89
|
mcp: MCPConfig | None = None,
|
|
90
90
|
mcp_manager: MCPManager | None = None,
|
|
91
91
|
model_profiles: dict[str, dict] | None = None,
|
|
92
|
+
default_agent: str | None = None,
|
|
92
93
|
llm_settings: dict | None = None,
|
|
93
94
|
config_path: str | None = None,
|
|
94
95
|
) -> None:
|
|
@@ -156,6 +157,11 @@ class Session:
|
|
|
156
157
|
# active clones are tracked so cancel()/close() can reach them.
|
|
157
158
|
self._subagent_clients_lock = threading.Lock()
|
|
158
159
|
self._active_subagent_clients: list[Client] = []
|
|
160
|
+
# guards _skill_index_cache: parallel readonly tool threads
|
|
161
|
+
# (e.g. multiple Skill calls in one round) can hit the lazy
|
|
162
|
+
# cache build simultaneously — double-checked locking prevents
|
|
163
|
+
# redundant filesystem scans and the data race on the cache tuple
|
|
164
|
+
self._skill_index_lock = threading.Lock()
|
|
159
165
|
self.store = SessionPersistence(
|
|
160
166
|
project_dir=project_dir,
|
|
161
167
|
model=model,
|
|
@@ -178,6 +184,17 @@ class Session:
|
|
|
178
184
|
# model profile's unset keys inherit these values, so switching
|
|
179
185
|
# between profiles never drifts settings from earlier switches.
|
|
180
186
|
self.llm_settings: dict = dict(llm_settings) if llm_settings else {}
|
|
187
|
+
# Default agent name: when set, the session starts with this
|
|
188
|
+
# agent's prompt instead of the built-in default (agent.md).
|
|
189
|
+
# ``/agent default`` restores the built-in, not this setting.
|
|
190
|
+
self.default_agent = default_agent
|
|
191
|
+
# Non-fatal startup warnings (e.g. a default_agent that could not
|
|
192
|
+
# be applied); the TUI renders these in its banner so they are
|
|
193
|
+
# visible inside the interface rather than on stderr.
|
|
194
|
+
self.startup_warnings: list[str] = []
|
|
195
|
+
# Original system prompt assembled at session start — used by
|
|
196
|
+
# /agent default to restore the original agent.md prompt.
|
|
197
|
+
self._default_system_prompt = system_prompt
|
|
181
198
|
# Monotonic cancel identity: cancel() bumps this counter, so a
|
|
182
199
|
# worker from a cancelled run can tell it was cancelled even
|
|
183
200
|
# after the next run clears the shared event.
|
|
@@ -377,10 +394,18 @@ class Session:
|
|
|
377
394
|
return hit[0] if hit else None
|
|
378
395
|
|
|
379
396
|
def _skill_index(self) -> dict[str, tuple[str, str]]:
|
|
380
|
-
"""Return the cached name -> (path, description) skill index.
|
|
397
|
+
"""Return the cached name -> (path, description) skill index.
|
|
398
|
+
|
|
399
|
+
Thread-safe via double-checked locking: parallel readonly tool
|
|
400
|
+
threads (e.g. multiple Skill calls in one round) can reach the
|
|
401
|
+
lazy cache build simultaneously — the lock ensures only one
|
|
402
|
+
thread scans the filesystem and writes the cache tuple.
|
|
403
|
+
"""
|
|
381
404
|
key = self._skill_dir
|
|
382
405
|
if self._skill_index_cache is None or self._skill_index_cache[0] != key:
|
|
383
|
-
self.
|
|
406
|
+
with self._skill_index_lock:
|
|
407
|
+
if self._skill_index_cache is None or self._skill_index_cache[0] != key:
|
|
408
|
+
self._skill_index_cache = (key, index_skills(key))
|
|
384
409
|
return self._skill_index_cache[1]
|
|
385
410
|
|
|
386
411
|
def _find_skill_dir(self) -> str | None:
|
|
@@ -695,6 +720,37 @@ class Session:
|
|
|
695
720
|
self.stream = merged["stream"]
|
|
696
721
|
return True, f"switched to {name} ({self.model})"
|
|
697
722
|
|
|
723
|
+
def switch_agent(self, name: str) -> tuple[bool, str]:
|
|
724
|
+
"""Switch the main agent's system prompt to a named agent.
|
|
725
|
+
|
|
726
|
+
Agent prompt files are discovered from the ``prompts/agents/`` package
|
|
727
|
+
directory (see ``python_agent_harness.prompts.discover_agents``).
|
|
728
|
+
The pseudo-name ``default`` restores the original system prompt
|
|
729
|
+
saved at session construction. Returns (success, message).
|
|
730
|
+
"""
|
|
731
|
+
if name == RESERVED_AGENT_NAME:
|
|
732
|
+
self.system_prompt = self._default_system_prompt
|
|
733
|
+
self.store.system_prompt = self._default_system_prompt
|
|
734
|
+
return True, "switched to default agent"
|
|
735
|
+
|
|
736
|
+
agents = discover_agents()
|
|
737
|
+
prompt_file = agents.get(name)
|
|
738
|
+
if prompt_file is None:
|
|
739
|
+
available = ", ".join(sorted([RESERVED_AGENT_NAME, *agents.keys()]))
|
|
740
|
+
return False, f"unknown agent: {name} (available: {available})"
|
|
741
|
+
from .prompts import assemble_agent_prompt, load_agent_prompt
|
|
742
|
+
|
|
743
|
+
agent_prompt = load_agent_prompt(prompt_file, skill_dir=self._skill_dir)
|
|
744
|
+
if agent_prompt is None:
|
|
745
|
+
return False, f"agent {name}: prompt file not found or empty: {prompt_file}"
|
|
746
|
+
self.system_prompt = assemble_agent_prompt(
|
|
747
|
+
self.project_dir,
|
|
748
|
+
agent_prompt,
|
|
749
|
+
context_path=self._configured_context_path,
|
|
750
|
+
)
|
|
751
|
+
self.store.system_prompt = self.system_prompt
|
|
752
|
+
return True, f"switched to {name}"
|
|
753
|
+
|
|
698
754
|
# ------------------------------------------------------------------
|
|
699
755
|
# direct commands: compact / summary (no agent loop)
|
|
700
756
|
# ------------------------------------------------------------------
|
|
@@ -739,7 +795,7 @@ class Session:
|
|
|
739
795
|
self.last_messages = compacted_messages(summary, user_prompt_texts(messages))
|
|
740
796
|
self.auto_save(self.last_messages, self.system_prompt)
|
|
741
797
|
self.notify("compact")
|
|
742
|
-
return True, "
|
|
798
|
+
return True, "Session compacted successfully."
|
|
743
799
|
except Exception as e: # noqa: BLE001 - compaction failure is non-fatal
|
|
744
800
|
self.log(f"compaction failed: {e}")
|
|
745
801
|
return False, f"Compaction failed: {e}"
|