python-agent-harness 1.5.7.3__tar.gz → 1.5.7.5__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.
Files changed (87) hide show
  1. {python_agent_harness-1.5.7.3/python_agent_harness.egg-info → python_agent_harness-1.5.7.5}/PKG-INFO +5 -1
  2. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/README.md +4 -0
  3. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/pyproject.toml +1 -1
  4. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/__init__.py +1 -1
  5. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/agent.py +3 -1
  6. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/cli.py +1 -0
  7. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/__init__.py +1 -0
  8. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/agent.md +0 -9
  9. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/core.py +26 -14
  10. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/subagent.md +1 -14
  11. python_agent_harness-1.5.7.5/python_agent_harness/prompts/tool-usage-policy.md +9 -0
  12. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/session/config.py +33 -1
  13. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/session/session.py +3 -1
  14. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/filesystem.py +79 -7
  15. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5/python_agent_harness.egg-info}/PKG-INFO +5 -1
  16. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness.egg-info/SOURCES.txt +1 -0
  17. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/tests/test_scenarios.py +2 -1
  18. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/LICENSE +0 -0
  19. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/__main__.py +0 -0
  20. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/__init__.py +0 -0
  21. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/context_manager.py +0 -0
  22. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/models.py +0 -0
  23. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/planmode.py +0 -0
  24. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/subagent.py +0 -0
  25. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/token_estimator.py +0 -0
  26. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/core/tool_runner.py +0 -0
  27. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/__init__.py +0 -0
  28. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/controller.py +0 -0
  29. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/headless.py +0 -0
  30. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/restore.py +0 -0
  31. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/server.py +0 -0
  32. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/entry/view.py +0 -0
  33. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/io/__init__.py +0 -0
  34. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/io/attachments.py +0 -0
  35. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/io/diffrender.py +0 -0
  36. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/io/persistence.py +0 -0
  37. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/io/text_filter.py +0 -0
  38. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/llm/__init__.py +0 -0
  39. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/llm/client.py +0 -0
  40. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/mcp/__init__.py +0 -0
  41. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/mcp/client.py +0 -0
  42. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/mcp/config.py +0 -0
  43. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/mcp/manager.py +0 -0
  44. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/agents/reviewer.md +0 -0
  45. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/build-switch.md +0 -0
  46. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/commands/explain.md +0 -0
  47. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/compact.md +0 -0
  48. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/initialize.md +0 -0
  49. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/plan-mode.md +0 -0
  50. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/plan.md +0 -0
  51. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/review.md +0 -0
  52. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/summary.md +0 -0
  53. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/task-completion-rules.md +0 -0
  54. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/prompts/title.md +0 -0
  55. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/session/__init__.py +0 -0
  56. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/session/commands.py +0 -0
  57. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/session/hooks.py +0 -0
  58. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/__init__.py +0 -0
  59. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/agent_tool.py +0 -0
  60. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/base.py +0 -0
  61. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/bash.py +0 -0
  62. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/diffapply.py +0 -0
  63. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/edit.py +0 -0
  64. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/edit_mac.py +0 -0
  65. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/glob.py +0 -0
  66. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/glob_mac.py +0 -0
  67. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/grep.py +0 -0
  68. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/grep_mac.py +0 -0
  69. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/mcp.py +0 -0
  70. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/planexit.py +0 -0
  71. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/question.py +0 -0
  72. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/read.py +0 -0
  73. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/skill.py +0 -0
  74. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/todo.py +0 -0
  75. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tools/write.py +0 -0
  76. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tui/__init__.py +0 -0
  77. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tui/commands.py +0 -0
  78. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tui/core.py +0 -0
  79. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tui/input.py +0 -0
  80. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tui/mouse.py +0 -0
  81. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness/tui/render.py +0 -0
  82. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness.egg-info/dependency_links.txt +0 -0
  83. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness.egg-info/entry_points.txt +0 -0
  84. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness.egg-info/requires.txt +0 -0
  85. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/python_agent_harness.egg-info/top_level.txt +0 -0
  86. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/setup.cfg +0 -0
  87. {python_agent_harness-1.5.7.3 → python_agent_harness-1.5.7.5}/tests/test_invariants.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-agent-harness
3
- Version: 1.5.7.3
3
+ Version: 1.5.7.5
4
4
  Summary: A lightweight, hackable mini-OpenCode written in Python.
5
5
  Author-email: Huming Chen <chenhuming@gmail.com>
6
6
  License-Expression: MIT
@@ -164,6 +164,9 @@ All LLM settings live in `~/.config/python-agent-harness/config.json`. Environme
164
164
  "context_windows": {
165
165
  "deepseek-v4": 1000000
166
166
  },
167
+ "supervision": {
168
+ "max_nudges": 1
169
+ },
167
170
  "paths": {
168
171
  "context_path": null,
169
172
  "skill_path": null,
@@ -191,6 +194,7 @@ All LLM settings live in `~/.config/python-agent-harness/config.json`. Environme
191
194
  - **`llm`** — main LLM config. Optional keys: `temperature`, `max_tokens`, `timeout`, `reasoning_effort`, `stream`, `supports_image_input`. `run --no-stream` overrides `stream`. `supports_image_input` (default `false`) controls whether `@path` images are sent or stripped.
192
195
  - **`models`** — named LLM profiles for `/model` switching. Partial settings; unset keys inherit from `llm`. `default` restores the main config.
193
196
  - **`context_windows`** — per-model context-window overrides (tokens). Keys are model names or substrings; first match wins. Overrides `CONTEXT_WINDOWS` in `config.py`.
197
+ - **`supervision.max_nudges`** — completion-supervision budget: how many times the harness nudges the model back to work when it stops with a terminal answer. The budget is **per tool round** (it resets on every tool round), so the effective cap is `max_nudges × tool rounds`. Default `1`, which suits a model that rarely stops early; raise it for a weaker model that keeps stopping before the work is done, or set `0` to disable supervision. Each nudge costs one extra LLM round (a full history re-send), so a high value is expensive.
194
198
  - **`subagent_llm`** — LLM config for `Agent` tool. Unset values inherit from `llm`. Set `profile` to reuse a `models` entry. Precedence: profile > `subagent_llm` > `llm` > env vars.
195
199
  - **`default_agent`** — agent name to use at session start (must exist in the discovered agent set: bundled `prompts/agents/` plus `paths.agent_path`). `null` = built-in default.
196
200
  - **`paths.context_path` / `paths.skill_path`** — locations for context files and skills. Default: project-local `contexts/` and `skills/`.
@@ -130,6 +130,9 @@ All LLM settings live in `~/.config/python-agent-harness/config.json`. Environme
130
130
  "context_windows": {
131
131
  "deepseek-v4": 1000000
132
132
  },
133
+ "supervision": {
134
+ "max_nudges": 1
135
+ },
133
136
  "paths": {
134
137
  "context_path": null,
135
138
  "skill_path": null,
@@ -157,6 +160,7 @@ All LLM settings live in `~/.config/python-agent-harness/config.json`. Environme
157
160
  - **`llm`** — main LLM config. Optional keys: `temperature`, `max_tokens`, `timeout`, `reasoning_effort`, `stream`, `supports_image_input`. `run --no-stream` overrides `stream`. `supports_image_input` (default `false`) controls whether `@path` images are sent or stripped.
158
161
  - **`models`** — named LLM profiles for `/model` switching. Partial settings; unset keys inherit from `llm`. `default` restores the main config.
159
162
  - **`context_windows`** — per-model context-window overrides (tokens). Keys are model names or substrings; first match wins. Overrides `CONTEXT_WINDOWS` in `config.py`.
163
+ - **`supervision.max_nudges`** — completion-supervision budget: how many times the harness nudges the model back to work when it stops with a terminal answer. The budget is **per tool round** (it resets on every tool round), so the effective cap is `max_nudges × tool rounds`. Default `1`, which suits a model that rarely stops early; raise it for a weaker model that keeps stopping before the work is done, or set `0` to disable supervision. Each nudge costs one extra LLM round (a full history re-send), so a high value is expensive.
160
164
  - **`subagent_llm`** — LLM config for `Agent` tool. Unset values inherit from `llm`. Set `profile` to reuse a `models` entry. Precedence: profile > `subagent_llm` > `llm` > env vars.
161
165
  - **`default_agent`** — agent name to use at session start (must exist in the discovered agent set: bundled `prompts/agents/` plus `paths.agent_path`). `null` = built-in default.
162
166
  - **`paths.context_path` / `paths.skill_path`** — locations for context files and skills. Default: project-local `contexts/` and `skills/`.
@@ -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.3"
7
+ version = "1.5.7.5"
8
8
  description = "A lightweight, hackable mini-OpenCode written in Python."
9
9
  authors = [
10
10
  {name = "Huming Chen", email = "chenhuming@gmail.com"}
@@ -7,7 +7,7 @@ from .mcp.config import MCPConfig, MCPServerConfig
7
7
  from .mcp.manager import MCPManager
8
8
  from .session.session import Session
9
9
 
10
- __version__ = "1.5.7.3"
10
+ __version__ = "1.5.7.5"
11
11
 
12
12
  __all__ = [
13
13
  "Client",
@@ -64,6 +64,7 @@ class _SupervisorSession(Protocol):
64
64
 
65
65
  alive: bool
66
66
  compacting: bool
67
+ config_path: str | None
67
68
 
68
69
 
69
70
  class AgentLoop:
@@ -840,6 +841,7 @@ class Supervisor:
840
841
  def __init__(self, session: _SupervisorSession) -> None:
841
842
  self.session = session
842
843
  self.nudge_count = 0
844
+ self.max_nudges = config.load_max_nudges(getattr(session, "config_path", None))
843
845
 
844
846
  # -- helpers -----------------------------------------------------------
845
847
  @property
@@ -852,7 +854,7 @@ class Supervisor:
852
854
  A dead session can never record nudges, so without this guard
853
855
  the machine could loop forever on terminal responses.
854
856
  """
855
- return self.alive and self.nudge_count < config.MAX_NUDGES
857
+ return self.alive and self.nudge_count < self.max_nudges
856
858
 
857
859
  def inject_nudge(self) -> bool:
858
860
  """Increment the nudge counter. Returns True on success; never raises.
@@ -371,6 +371,7 @@ def cmd_config(args: argparse.Namespace) -> int:
371
371
  print("context_windows: (none configured — built-in table in config.py applies)")
372
372
  default_agent = config.load_default_agent(args.path)
373
373
  print(f"default_agent: {default_agent or '(default: agent.md)'}")
374
+ print(f"supervision.max_nudges: {config.load_max_nudges(args.path)}")
374
375
  max_rounds, timeout = config.load_headless_limits(args.path)
375
376
  if max_rounds is None and timeout is None:
376
377
  print(
@@ -9,6 +9,7 @@ from .core import ( # noqa: F401
9
9
  _SKILLS_FALLBACK,
10
10
  _SKILLS_PLACEHOLDER_RE,
11
11
  _TOOL_INSTRUCTIONS_PLACEHOLDER_RE,
12
+ _TOOL_USAGE_POLICY_FILE,
12
13
  AGENTS_DIR,
13
14
  PROMPTS_DIR,
14
15
  RESERVED_AGENT_NAME,
@@ -62,15 +62,6 @@ The user will primarily request you perform software engineering tasks. This inc
62
62
  - NEVER commit changes unless the user explicitly asks you to.
63
63
  - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
64
64
 
65
- # Tool usage policy
66
- - For file searches, prefer the Agent tool to reduce context usage.
67
- - For independent tasks, prefer running multiple Agent tools in parallel.
68
- - For multiple bash commands, issue all tool calls in one message so they run in parallel.
69
- - Batch independent tool calls in a single response to maximize parallelism.
70
-
71
- # Tool usage instructions
72
- {{TOOL_INSTRUCTIONS}}
73
-
74
65
  # Code References
75
66
  When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
76
67
 
@@ -46,6 +46,7 @@ def read_prompt_file(name: str) -> str:
46
46
  _FRONTMATTER_RE = re.compile(r"\A---\r?\n.*?\r?\n---\r?\n?", re.DOTALL)
47
47
  _SKILLS_PLACEHOLDER_RE = re.compile(r"\{\{\s*SKILLS\s*\}\}")
48
48
  _TOOL_INSTRUCTIONS_PLACEHOLDER_RE = re.compile(r"\{\{\s*TOOL_INSTRUCTIONS\s*\}\}")
49
+ _TOOL_USAGE_POLICY_FILE = PROMPTS_DIR / "tool-usage-policy.md"
49
50
  _SKILLS_FALLBACK = (
50
51
  "Invoke with a skill name and optional args; the tool reports an "
51
52
  "error if no matching skill is found."
@@ -197,17 +198,20 @@ def load_agent_prompt(
197
198
  """Load an opencode-style agent prompt file, or None if unavailable.
198
199
 
199
200
  Strips the YAML frontmatter header (name/description/tools) since
200
- that metadata isn't part of the prompt text, substitutes the
201
- ``{{TOOL_INSTRUCTIONS}}`` placeholder with per-tool instruction
202
- blocks assembled from *tool_instructions* (filtered by
203
- *excluded_tools*), and substitutes the ``{{SKILLS}}`` placeholder
204
- with the discovered skill listing from *skill_dir* (or a static
205
- fallback if no skills are found).
206
-
207
- The ``{{TOOL_INSTRUCTIONS}}`` substitution happens before
208
- ``{{SKILLS}}``: a tool's instructions may itself contain
209
- ``{{SKILLS}}`` (the Skill tool does), so the skills placeholder is
210
- resolved last to catch it wherever it appears.
201
+ that metadata isn't part of the prompt text.
202
+
203
+ Tool guidance is injected uniformly so switching profiles never
204
+ silently drops it: the shared fragment (``tool-usage-policy.md``) is
205
+ always appended, carrying the ``{{TOOL_INSTRUCTIONS}}`` placeholder,
206
+ which is then substituted with per-tool instruction blocks (assembled
207
+ from *tool_instructions*, filtered by *excluded_tools*). The
208
+ ``{{SKILLS}}`` placeholder is substituted with the discovered skill
209
+ listing from *skill_dir* (or a static fallback if no skills are found).
210
+
211
+ ``{{TOOL_INSTRUCTIONS}}`` is resolved before ``{{SKILLS}}``: a tool's
212
+ instructions may itself contain ``{{SKILLS}}`` (the Skill tool does),
213
+ so the skills placeholder is resolved last to catch it wherever it
214
+ appears.
211
215
 
212
216
  Missing files, unreadable files, and empty files all resolve to None
213
217
  so callers can fall back cleanly to no system prompt.
@@ -220,6 +224,14 @@ def load_agent_prompt(
220
224
  except OSError:
221
225
  return None
222
226
  text = strip_frontmatter(text)
227
+ if not text.strip():
228
+ return None
229
+ try:
230
+ fragment = _TOOL_USAGE_POLICY_FILE.read_text(encoding="utf-8").strip()
231
+ except OSError:
232
+ fragment = ""
233
+ if fragment:
234
+ text = text.rstrip() + "\n\n" + fragment
223
235
  tool_blocks = assemble_tool_instructions(tool_instructions, excluded_tools)
224
236
  # Use a lambda replacement to avoid re.sub interpreting backslashes
225
237
  # in tool instruction text (e.g. regex examples like \s, \w) as
@@ -406,9 +418,9 @@ def assemble_agent_prompt(
406
418
  ``subagent._subagent_system_prompt``). ``context_path`` overrides
407
419
  the default context directory discovery.
408
420
 
409
- *agent_prompt* is already fully resolved (``{{TOOL_INSTRUCTIONS}}``
410
- and ``{{SKILLS}}`` substituted by ``load_agent_prompt``); this
411
- function only layers context and rules around it.
421
+ *agent_prompt* is already fully resolved (tool guidance injected and
422
+ ``{{SKILLS}}`` substituted by ``load_agent_prompt``); this function
423
+ only layers context and rules around it.
412
424
  Returns None if every part is empty/missing.
413
425
  """
414
426
  parts: list[str] = []
@@ -13,20 +13,7 @@ You are an autonomous subagent. Your role is to independently complete well-defi
13
13
  - Think about the larger problem - does the task need to be done this way at all?
14
14
  - Investigate thoroughly to find truth before confirming beliefs
15
15
  - If you lack information needed to proceed, make reasonable assumptions based on context
16
-
17
- # Tool usage policy
18
- - You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
19
-
20
- You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
21
-
22
- # Tool usage instructions
23
-
24
- **Parallel Tool Execution:**
25
- - Call multiple tools in a single response when tasks are independent
26
- - Never use placeholders or guess missing parameters
27
- - Maximize parallel execution to improve efficiency
28
-
29
- {{TOOL_INSTRUCTIONS}}
16
+ - You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail
30
17
 
31
18
  # Output Requirements
32
19
  - Return a single, comprehensive final response with all results
@@ -0,0 +1,9 @@
1
+ # Tool usage policy
2
+ - For file searches, prefer the Agent tool to reduce context usage.
3
+ - For independent tasks, prefer running multiple Agent tools in parallel.
4
+ - For multiple bash commands, issue all tool calls in one message so they run in parallel.
5
+ - Batch independent tool calls in a single response to maximize parallelism.
6
+
7
+ # Tool usage instructions
8
+ {{TOOL_INSTRUCTIONS}}
9
+
@@ -32,7 +32,9 @@ CONTEXT_WINDOWS: list[tuple[str, int]] = [
32
32
  DEFAULT_CONTEXT_WINDOW = 128_000
33
33
 
34
34
  # ---- completion supervision ----------------------------------------------
35
- MAX_NUDGES = 2
35
+ # Nudges per tool round; the budget resets on every tool round (see
36
+ # AgentLoop._handle_tool), so the effective cap is MAX_NUDGES x tool rounds.
37
+ MAX_NUDGES = 1
36
38
  NUDGE_MESSAGE = (
37
39
  "Review the original user request and the Task Completion Rules in the context. "
38
40
  "Verify whether all completion criteria are satisfied. "
@@ -296,6 +298,10 @@ CONFIG_TEMPLATE = """\
296
298
  "_comment": "Optional per-model context-window overrides (tokens). Keys are model names or substrings (e.g. deepseek-v4 = 1000000); matched in file order, first match wins. Overrides the built-in CONTEXT_WINDOWS table in config.py. Remove this section to use the built-in table.",
297
299
  "deepseek-v4": 1000000
298
300
  }},
301
+ "supervision": {{
302
+ "_comment": "Completion supervision: how many times the harness nudges the model back to work when it stops with a terminal answer. The budget is PER TOOL ROUND (it resets on every tool round), so the effective cap is max_nudges x tool rounds. Default 1 suits a model that rarely stops early; raise it for a weaker model, or set 0 to disable. Each nudge costs one extra LLM round.",
303
+ "max_nudges": 1
304
+ }},
299
305
  "subagent_llm": {{
300
306
  "_comment": "Optional overrides for sub-agent (Agent tool) requests, e.g. a cheaper model. Every key is optional; unset keys inherit the main llm settings above. Set 'profile' to a name from the 'models' section to reuse a model profile (profile settings win over explicit keys below).",
301
307
  "profile": null,
@@ -570,6 +576,32 @@ def load_headless_limits(path: str | os.PathLike | None = None) -> tuple[int | N
570
576
  return _load_limits("headless", path)
571
577
 
572
578
 
579
+ def load_max_nudges(path: str | os.PathLike | None = None) -> int:
580
+ """Nudges per tool round from the config file's ``supervision`` object.
581
+
582
+ ``0`` disables supervision. A missing file/section or unreadable JSON
583
+ yields ``MAX_NUDGES``; a malformed section or a non-integer value raises
584
+ ValueError so config errors surface at session start.
585
+ """
586
+ try:
587
+ data = _read_config(path)
588
+ except ValueError:
589
+ return MAX_NUDGES
590
+ section = _object_section(data, "supervision", path)
591
+ val = section.get("max_nudges")
592
+ if val is None:
593
+ return MAX_NUDGES
594
+ if isinstance(val, bool) or not isinstance(val, int):
595
+ raise ValueError(
596
+ f"config file {_config_path(path)}: supervision.max_nudges must be an integer"
597
+ )
598
+ if val < 0:
599
+ raise ValueError(
600
+ f"config file {_config_path(path)}: supervision.max_nudges must not be negative"
601
+ )
602
+ return val
603
+
604
+
573
605
  def load_serve_limits(path: str | os.PathLike | None = None) -> tuple[int | None, float | None]:
574
606
  """Load per-run limits from the config file's ``serve`` object.
575
607
 
@@ -29,7 +29,7 @@ from ..prompts import RESERVED_AGENT_NAME, _tool_excluded, discover_agents, inde
29
29
  from ..session import config
30
30
  from ..tools import Registry, ToolContext
31
31
  from ..tools.base import PendingToolResult, resolve_path
32
- from ..tools.filesystem import cleanup_spooled_files
32
+ from ..tools.filesystem import cleanup_spooled_files, sweep_stale_spooled_files
33
33
  from ..tools.mcp import mcp_tools_from_manager
34
34
  from .hooks import HookRunner
35
35
 
@@ -159,6 +159,8 @@ class Session:
159
159
  self.calibrator = TokenCalibrator()
160
160
  self.plan_mode = PlanMode(project_dir)
161
161
  self.tool_ctx = ToolContext(self)
162
+ # Collect spool files stranded by a run that died without unwinding.
163
+ sweep_stale_spooled_files()
162
164
  self._tool_diffs: dict[str, str] = {}
163
165
  self._tool_diffs_lock = threading.Lock()
164
166
  # thread-local: sub-agents each execute tools in their own
@@ -32,6 +32,7 @@ full output remains readable via the Read tool.
32
32
 
33
33
  from __future__ import annotations
34
34
 
35
+ import atexit
35
36
  import contextlib
36
37
  import os
37
38
  import shutil # noqa: F401 (mock target for tests)
@@ -51,6 +52,14 @@ SPOOL_LINES = 50 # preview lines kept when results are spilled
51
52
  READ_SIZE_LIMIT = 400 * 1024 # whole-file reads above this are refused
52
53
  # (mirrors gptel-agent-read-file-size-threshold)
53
54
 
55
+ # Prefix every spool file carries, so a later run can recognise files a
56
+ # previous, uncleanly-exited run left behind.
57
+ SPOOL_PREFIX = "python-agent-harness-"
58
+
59
+ # A spool file is read within the run that created it, so one older than this
60
+ # cannot belong to a live session.
61
+ SPOOL_MAX_AGE_S = 24 * 60 * 60
62
+
54
63
  _spooled_files: list[str] = [] # temp files created by _spool, cleaned
55
64
  # up by cleanup_spooled_files on session close
56
65
  _spooled_files_lock = threading.Lock() # guards _spooled_files across
@@ -91,7 +100,7 @@ def _spool(text: str, label: str) -> str:
91
100
  stamp = time.strftime("%Y%m%d-%H%M%S")
92
101
  try:
93
102
  fd, temp_file = tempfile.mkstemp(
94
- prefix=f"python-agent-harness-{label}-{stamp}-",
103
+ prefix=f"{SPOOL_PREFIX}{label}-{stamp}-",
95
104
  suffix=".txt",
96
105
  dir=_spool_dir(),
97
106
  )
@@ -127,6 +136,15 @@ def _spool(text: str, label: str) -> str:
127
136
  )
128
137
 
129
138
 
139
+ def _remove_tracked(paths: list[str]) -> None:
140
+ for path in paths:
141
+ try:
142
+ if os.path.exists(path):
143
+ os.remove(path)
144
+ except OSError:
145
+ pass
146
+
147
+
130
148
  def cleanup_spooled_files() -> None:
131
149
  """Delete all tracked spooled temp files (best effort).
132
150
 
@@ -138,12 +156,63 @@ def cleanup_spooled_files() -> None:
138
156
  with _spooled_files_lock:
139
157
  paths = _spooled_files[:]
140
158
  _spooled_files.clear()
141
- for path in paths:
142
- try:
143
- if os.path.exists(path):
144
- os.remove(path)
145
- except OSError:
146
- pass
159
+ _remove_tracked(paths)
160
+
161
+
162
+ def _cleanup_at_exit() -> None:
163
+ """``atexit`` wrapper: never block interpreter shutdown.
164
+
165
+ A daemon tool thread can still hold ``_spooled_files_lock`` when the
166
+ interpreter exits (a Bash/Agent worker mid-``_spool``). ``threading.Lock``
167
+ is not reentrant and daemon threads are frozen, not joined, at shutdown, so
168
+ a plain ``cleanup_spooled_files()`` would block forever and hang the
169
+ process. Skip the tracked-file pass in that case: the age-based sweep on
170
+ the next start collects those files anyway.
171
+ """
172
+ if not _spooled_files_lock.acquire(timeout=1.0):
173
+ return
174
+ try:
175
+ paths = _spooled_files[:]
176
+ _spooled_files.clear()
177
+ finally:
178
+ _spooled_files_lock.release()
179
+ _remove_tracked(paths)
180
+
181
+
182
+ def sweep_stale_spooled_files(max_age_s: float = SPOOL_MAX_AGE_S) -> int:
183
+ """Delete spool files left behind by earlier, uncleanly-exited runs.
184
+
185
+ ``cleanup_spooled_files`` only knows the files THIS process created, so a
186
+ SIGKILL, an OOM kill or a crash strands every spool file it had written.
187
+ This sweeps the spool dir by name and age instead, which needs no
188
+ bookkeeping from the dead process.
189
+
190
+ Returns the number of files removed. Never raises: a sweep failure must
191
+ not stop a session from starting.
192
+ """
193
+ removed = 0
194
+ try:
195
+ directory = _spool_dir()
196
+ cutoff = time.time() - max_age_s
197
+ with os.scandir(directory) as entries:
198
+ for entry in entries:
199
+ if not entry.name.startswith(SPOOL_PREFIX):
200
+ continue
201
+ try:
202
+ # one stat: is_file() would stat again
203
+ st = entry.stat(follow_symlinks=False)
204
+ if not stat.S_ISREG(st.st_mode) or st.st_mtime > cutoff:
205
+ continue
206
+ os.remove(entry.path)
207
+ removed += 1
208
+ except OSError:
209
+ continue # raced with another sweep, or not ours to remove
210
+ except OSError:
211
+ return removed
212
+ return removed
213
+
214
+
215
+ atexit.register(_cleanup_at_exit)
147
216
 
148
217
 
149
218
  def _natnump(n: object) -> TypeGuard[int]:
@@ -276,8 +345,11 @@ __all__ = [
276
345
  "MAX_OUTPUT",
277
346
  "READ_SIZE_LIMIT",
278
347
  "SPOOL_LINES",
348
+ "SPOOL_MAX_AGE_S",
349
+ "SPOOL_PREFIX",
279
350
  "atomic_write_text",
280
351
  "cleanup_spooled_files",
352
+ "sweep_stale_spooled_files",
281
353
  "_fix_patch_headers",
282
354
  "_git_glob_results",
283
355
  "_git_root",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-agent-harness
3
- Version: 1.5.7.3
3
+ Version: 1.5.7.5
4
4
  Summary: A lightweight, hackable mini-OpenCode written in Python.
5
5
  Author-email: Huming Chen <chenhuming@gmail.com>
6
6
  License-Expression: MIT
@@ -164,6 +164,9 @@ All LLM settings live in `~/.config/python-agent-harness/config.json`. Environme
164
164
  "context_windows": {
165
165
  "deepseek-v4": 1000000
166
166
  },
167
+ "supervision": {
168
+ "max_nudges": 1
169
+ },
167
170
  "paths": {
168
171
  "context_path": null,
169
172
  "skill_path": null,
@@ -191,6 +194,7 @@ All LLM settings live in `~/.config/python-agent-harness/config.json`. Environme
191
194
  - **`llm`** — main LLM config. Optional keys: `temperature`, `max_tokens`, `timeout`, `reasoning_effort`, `stream`, `supports_image_input`. `run --no-stream` overrides `stream`. `supports_image_input` (default `false`) controls whether `@path` images are sent or stripped.
192
195
  - **`models`** — named LLM profiles for `/model` switching. Partial settings; unset keys inherit from `llm`. `default` restores the main config.
193
196
  - **`context_windows`** — per-model context-window overrides (tokens). Keys are model names or substrings; first match wins. Overrides `CONTEXT_WINDOWS` in `config.py`.
197
+ - **`supervision.max_nudges`** — completion-supervision budget: how many times the harness nudges the model back to work when it stops with a terminal answer. The budget is **per tool round** (it resets on every tool round), so the effective cap is `max_nudges × tool rounds`. Default `1`, which suits a model that rarely stops early; raise it for a weaker model that keeps stopping before the work is done, or set `0` to disable supervision. Each nudge costs one extra LLM round (a full history re-send), so a high value is expensive.
194
198
  - **`subagent_llm`** — LLM config for `Agent` tool. Unset values inherit from `llm`. Set `profile` to reuse a `models` entry. Precedence: profile > `subagent_llm` > `llm` > env vars.
195
199
  - **`default_agent`** — agent name to use at session start (must exist in the discovered agent set: bundled `prompts/agents/` plus `paths.agent_path`). `null` = built-in default.
196
200
  - **`paths.context_path` / `paths.skill_path`** — locations for context files and skills. Default: project-local `contexts/` and `skills/`.
@@ -48,6 +48,7 @@ python_agent_harness/prompts/subagent.md
48
48
  python_agent_harness/prompts/summary.md
49
49
  python_agent_harness/prompts/task-completion-rules.md
50
50
  python_agent_harness/prompts/title.md
51
+ python_agent_harness/prompts/tool-usage-policy.md
51
52
  python_agent_harness/prompts/agents/reviewer.md
52
53
  python_agent_harness/prompts/commands/explain.md
53
54
  python_agent_harness/session/__init__.py
@@ -285,9 +285,10 @@ class TestScenarioNudging(unittest.TestCase):
285
285
  session.tools_enabled = True
286
286
  session.client.script = ["a", "b", "c"]
287
287
  loop = AgentLoop(session, messages=[Message(role="user", content="task")])
288
+ loop.supervisor.max_nudges = 2
288
289
  result = loop.run()
289
290
  self.assertEqual(result, "c")
290
- self.assertEqual(loop.supervisor.nudge_count, config.MAX_NUDGES)
291
+ self.assertEqual(loop.supervisor.nudge_count, 2)
291
292
  self.assertFalse(loop.supervisor.can_nudge())
292
293
  self.assertEqual(
293
294
  [m.text() for m in loop.messages if m.role == "user" and m.injected],