python-agent-harness 1.5.7.2__py3-none-any.whl → 1.5.7.3__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.
Files changed (33) hide show
  1. python_agent_harness/__init__.py +1 -1
  2. python_agent_harness/core/agent.py +0 -11
  3. python_agent_harness/core/context_manager.py +0 -3
  4. python_agent_harness/core/models.py +0 -1
  5. python_agent_harness/core/tool_runner.py +1 -20
  6. python_agent_harness/entry/cli.py +17 -14
  7. python_agent_harness/entry/controller.py +1 -3
  8. python_agent_harness/entry/headless.py +0 -3
  9. python_agent_harness/entry/server.py +6 -15
  10. python_agent_harness/io/attachments.py +1 -17
  11. python_agent_harness/io/diffrender.py +0 -4
  12. python_agent_harness/io/persistence.py +4 -10
  13. python_agent_harness/llm/client.py +134 -8
  14. python_agent_harness/prompts/core.py +3 -4
  15. python_agent_harness/session/commands.py +2 -5
  16. python_agent_harness/session/config.py +67 -41
  17. python_agent_harness/session/session.py +43 -17
  18. python_agent_harness/tools/agent_tool.py +1 -8
  19. python_agent_harness/tools/base.py +10 -9
  20. python_agent_harness/tools/diffapply.py +0 -2
  21. python_agent_harness/tools/edit.py +0 -1
  22. python_agent_harness/tools/glob.py +0 -3
  23. python_agent_harness/tools/planexit.py +0 -2
  24. python_agent_harness/tools/question.py +0 -2
  25. python_agent_harness/tui/commands.py +246 -21
  26. python_agent_harness/tui/input.py +1 -2
  27. python_agent_harness/tui/render.py +4 -5
  28. {python_agent_harness-1.5.7.2.dist-info → python_agent_harness-1.5.7.3.dist-info}/METADATA +2 -2
  29. {python_agent_harness-1.5.7.2.dist-info → python_agent_harness-1.5.7.3.dist-info}/RECORD +33 -33
  30. {python_agent_harness-1.5.7.2.dist-info → python_agent_harness-1.5.7.3.dist-info}/WHEEL +0 -0
  31. {python_agent_harness-1.5.7.2.dist-info → python_agent_harness-1.5.7.3.dist-info}/entry_points.txt +0 -0
  32. {python_agent_harness-1.5.7.2.dist-info → python_agent_harness-1.5.7.3.dist-info}/licenses/LICENSE +0 -0
  33. {python_agent_harness-1.5.7.2.dist-info → python_agent_harness-1.5.7.3.dist-info}/top_level.txt +0 -0
@@ -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.2"
10
+ __version__ = "1.5.7.3"
11
11
 
12
12
  __all__ = [
13
13
  "Client",
@@ -112,28 +112,17 @@ class AgentLoop:
112
112
  # round budget: an interactive TUI run still runs until the
113
113
  # model finishes or the user aborts
114
114
  self.max_rounds = max_rounds
115
- # Optional wall-clock budget for unattended runs (None = off)
116
115
  self.timeout = timeout
117
116
  self.pending: list[ToolCall] = []
118
117
  self.error: str | None = None
119
118
  self.harness_injected: bool = False
120
119
  self.supervisor = Supervisor(session)
121
- # extracted machinery (no logic changes): tool execution and
122
- # context/compaction live in tool_runner.py / context_manager.py;
123
- # the loop delegates to them and keeps the FSM state
124
120
  self._tool_runner = ToolRunner(self)
125
121
  self._context_manager = ContextManager(self)
126
- # FSM state: `state` is the current state, `info` the per-round
127
- # context read by the transition-table predicates, `history`
128
- # the states visited so far (newest last), `rounds` the number
129
- # of WAIT visits (sub-agent budget), and `result` the final
130
- # return value recorded by the terminal state's handler.
131
122
  self.state = self.WAIT
132
123
  self.info: dict[str, Any] = {}
133
124
  self.history: list[str] = []
134
125
  self.rounds = 0
135
- # Thread-local wall-clock deadline bookkeeping: sub-agent loops
136
- # run in their own threads, so a shared attribute would race
137
126
  self._local = threading.local()
138
127
  self.terminal_text: str | None = None
139
128
  self.result: str | None = None
@@ -42,9 +42,6 @@ class ContextManager:
42
42
  )
43
43
  loop.session.calibrator.last_raw_estimate = raw
44
44
  calibrated = loop.session.calibrator.calibrate(raw)
45
- # Prefer the client's window (config overrides -> patterns ->
46
- # default, resolved per access); fall back to the static
47
- # resolver for clients without the property (test doubles).
48
45
  client = loop.session.client
49
46
  window = getattr(client, "context_window", None)
50
47
  if window is None:
@@ -107,7 +107,6 @@ class ImagePart:
107
107
  return {"type": "image_url", "image_url": {"url": self._data_url}}
108
108
 
109
109
 
110
- # Type alias for the individual parts a Message.content list may contain.
111
110
  ContentPart = Union[TextPart, ImagePart, str, "dict[str, Any]"]
112
111
 
113
112
 
@@ -6,13 +6,6 @@ state (``messages`` / ``pending`` / ``info``) through the loop
6
6
  reference. Tool calls are always executed and delivered via the
7
7
  loop's ``_execute_tool_call`` / ``_deliver_tool_result`` methods so
8
8
  subclass or test overrides of those methods keep working.
9
-
10
- When every call in a round is readonly (``Tool.is_readonly = True``),
11
- the round is dispatched concurrently via a thread pool: readonly tools
12
- only read state, so none can depend on another's side effects, and
13
- running them in parallel reduces latency for read-heavy rounds (e.g.
14
- the model reading several files at once). Mixed rounds (any
15
- non-readonly tool) fall back to the original sequential dispatch.
16
9
  """
17
10
 
18
11
  from __future__ import annotations
@@ -53,15 +46,7 @@ def sanitize_tool_result(result: object) -> str:
53
46
 
54
47
 
55
48
  class ToolRunner:
56
- """Runs and delivers tool calls for one agent loop.
57
-
58
- Mirrors gptel's `gptel--handle-tool-use': synchronous tools
59
- (Read, Edit, Glob, ...) execute ONE AT A TIME, in call order;
60
- asynchronous tools (Bash, Agent — those whose ``run`` returns a
61
- ``PendingToolResult``) are dispatched in line and run concurrently
62
- in the background, their results awaited afterwards, again in
63
- original call order.
64
- """
49
+ """Runs and delivers tool calls for one agent loop."""
65
50
 
66
51
  def __init__(self, loop: Any) -> None:
67
52
  self.loop = loop
@@ -263,10 +248,6 @@ class ToolRunner:
263
248
  appended by the WAIT state. Results land in
264
249
  ``self.info["tool_result"]`` and are delivered by the TRET
265
250
  state in original tool-call order.
266
-
267
- Synchronous tools run ONE AT A TIME in model-emitted order
268
- (gptel-style); asynchronous tools (Bash, Agent) are dispatched
269
- in line and run concurrently in the background.
270
251
  """
271
252
  loop = self.loop
272
253
  pending = list(loop.pending)
@@ -53,7 +53,16 @@ def make_session(
53
53
  # (so a CLI/caller model override is inherited too when the
54
54
  # subagent_llm model is unset)
55
55
  settings["model"] = model
56
- subagent_settings = config.load_subagent_llm_config(config_path, main=settings)
56
+ # One config read for both views: the fully resolved settings (to
57
+ # decide whether the sub-agent needs its own client) and the
58
+ # explicit overrides only (per-request options must stay "unset =
59
+ # inherit the main value at use time" — a value resolved here would
60
+ # pin the model active at session start, so a later /model switch
61
+ # would keep sending the previous model's reasoning_effort, which
62
+ # the new backend rejects).
63
+ subagent_overrides = config.load_subagent_overrides(config_path)
64
+ subagent_settings = dict(settings)
65
+ subagent_settings.update(subagent_overrides)
57
66
  client = Client(
58
67
  base_url=settings["base_url"],
59
68
  api_key=settings["api_key"],
@@ -128,11 +137,13 @@ def make_session(
128
137
  stream=effective_stream,
129
138
  supports_image_input=settings["supports_image_input"],
130
139
  subagent_client=subagent_client,
131
- subagent_temperature=subagent_settings["temperature"],
132
- subagent_max_tokens=subagent_settings["max_tokens"],
133
- subagent_reasoning_effort=subagent_settings["reasoning_effort"],
134
- subagent_stream=(effective_stream if stream is not None else subagent_settings["stream"]),
135
- subagent_supports_image_input=subagent_settings["supports_image_input"],
140
+ subagent_temperature=subagent_overrides.get("temperature"),
141
+ subagent_max_tokens=subagent_overrides.get("max_tokens"),
142
+ subagent_reasoning_effort=subagent_overrides.get("reasoning_effort"),
143
+ subagent_stream=(
144
+ effective_stream if stream is not None else subagent_overrides.get("stream")
145
+ ),
146
+ subagent_supports_image_input=subagent_overrides.get("supports_image_input"),
136
147
  registry=registry,
137
148
  context_path=paths.get("context_path"),
138
149
  skill_path=paths.get("skill_path"),
@@ -231,8 +242,6 @@ def cmd_headless(args: argparse.Namespace) -> int:
231
242
  if prompt is None:
232
243
  prompt = sys.stdin.read()
233
244
  runner = run_headless_jsonl if getattr(args, "json", False) else run_headless
234
- # Unattended budgets: explicit flags win over the config file's
235
- # headless section (0/negative disables the budget entirely).
236
245
  max_rounds, timeout = _resolve_budgets(args, config.load_headless_limits(args.config))
237
246
  return runner(
238
247
  session,
@@ -257,9 +266,6 @@ def cmd_serve(args: argparse.Namespace) -> int:
257
266
  try:
258
267
  from .server import run_serve
259
268
 
260
- # Per-run budgets: explicit flags win over the config file's
261
- # serve section (0/negative disables). Applied to EACH submit
262
- # — the process is resident, so every run gets a fresh budget.
263
269
  max_rounds, timeout = _resolve_budgets(args, config.load_serve_limits(args.config))
264
270
  return run_serve(
265
271
  session,
@@ -347,7 +353,6 @@ def cmd_config(args: argparse.Namespace) -> int:
347
353
  f"reasoning_effort={subagent_settings['reasoning_effort']} "
348
354
  f"stream={subagent_settings['stream']} timeout={subagent_settings['timeout']}"
349
355
  )
350
- # Show model profiles for /model command
351
356
  model_profiles = config.load_models_config(args.path)
352
357
  if model_profiles:
353
358
  print("models:")
@@ -357,7 +362,6 @@ def cmd_config(args: argparse.Namespace) -> int:
357
362
  print(f" {name}: model={model_name}, base_url={base_url}")
358
363
  else:
359
364
  print("models: (none configured — add a 'models' section to use /model)")
360
- # Show context-window overrides
361
365
  context_windows = config.load_context_windows_config(args.path)
362
366
  if context_windows:
363
367
  print("context_windows:")
@@ -365,7 +369,6 @@ def cmd_config(args: argparse.Namespace) -> int:
365
369
  print(f" {pattern}: {size}")
366
370
  else:
367
371
  print("context_windows: (none configured — built-in table in config.py applies)")
368
- # Show default agent
369
372
  default_agent = config.load_default_agent(args.path)
370
373
  print(f"default_agent: {default_agent or '(default: agent.md)'}")
371
374
  max_rounds, timeout = config.load_headless_limits(args.path)
@@ -311,7 +311,7 @@ class Controller:
311
311
  # from a previous run so a finished task's todos don't stay
312
312
  # pinned into the next task.
313
313
  self.clear_todos()
314
- # A new top-level run starts here: invalidate any worker still
314
+ # Invalidate any worker still
315
315
  # unwinding from a previous run — from this point on it is stale
316
316
  # and must never touch shared state. Bump before clearing the
317
317
  # event so there is no instant where an old worker sees "not
@@ -361,7 +361,6 @@ class Controller:
361
361
  return text, cleaned_text.strip() or "(attachment)", [], warnings
362
362
  cleaned_text, attachments, errors = parse_at_references(text, str(self.project_dir))
363
363
  if errors and not attachments and not cleaned_text.strip():
364
- # All references failed and nothing else to send
365
364
  return None, "", errors, []
366
365
  # Build the user message: multimodal if there are attachments,
367
366
  # plain text otherwise (preserving the existing text-only path).
@@ -372,7 +371,6 @@ class Controller:
372
371
  for att in attachments:
373
372
  parts.append(att.part)
374
373
  user_msg = Message(role="user", content=parts)
375
- # The display text is the user-facing text (without image data)
376
374
  display_text = (
377
375
  cleaned_text.strip()
378
376
  or f"({len(attachments)} image attachment{'s' if len(attachments) != 1 else ''})"
@@ -361,9 +361,6 @@ def run_headless(
361
361
  return 1
362
362
  answer = final_answer_text(session)
363
363
  if answer:
364
- # api_safe: the answer carries whatever the conversation carried
365
- # (a restored non-UTF-8 session), and a strict-UTF-8 stdout
366
- # raised UnicodeEncodeError here — losing the result line.
367
364
  view.out.write(api_safe(answer) + "\n")
368
365
  view.out.flush()
369
366
  return 1 if view.errors else 0
@@ -141,12 +141,9 @@ from .headless import (
141
141
 
142
142
  DEFAULT_ANSWER_TIMEOUT = 0.0 # wait forever for a host answer
143
143
 
144
- # Named features advertised on the ``ready`` line. ``protocol_version``
145
- # alone is a single integer a host can only accept or reject wholesale;
146
- # these let it discover what this build actually supports and adapt,
147
- # instead of inferring a feature's absence from events that never
148
- # arrive. Add a capability when behaviour a host can branch on is
149
- # introduced; never repurpose an existing name.
144
+ # Named features advertised on the ``ready`` line. Add a capability
145
+ # when behaviour a host can branch on is introduced; never repurpose
146
+ # an existing name.
150
147
  CAPABILITIES = (
151
148
  "submit", # run a prompt
152
149
  "answer", # deliver a mid-run answer to an ask
@@ -497,9 +494,8 @@ class AgentServer:
497
494
  self.err = err if err is not None else sys.stderr
498
495
  self.answer_timeout = answer_timeout
499
496
  # Per-run budgets (None = unlimited), applied to EVERY submit.
500
- # The process is resident, so these bound each run rather than
501
- # the process lifetime. Held here — not taken off the wire —
502
- # so a driving host cannot raise its own ceiling.
497
+ # Held here — not taken off the wire — so a driving host cannot
498
+ # raise its own ceiling.
503
499
  self.max_rounds = max_rounds
504
500
  self.timeout = timeout
505
501
  self.view: ServerView | None = None
@@ -623,18 +619,13 @@ class AgentServer:
623
619
  # Per-run budget: Controller.submit derives budget_top_level
624
620
  # from max_rounds being set, so passing it is what opts this
625
621
  # run into a finite round cap (default None = unlimited, the
626
- # interactive behavior). A tripped budget unwinds the agent
627
- # loop normally, so the run still ends with a result line
628
- # carrying errors[].code = "budget"/"timeout" and real usage.
622
+ # interactive behavior).
629
623
  handle = self.controller.submit(
630
624
  prompt,
631
625
  max_rounds=self.max_rounds,
632
626
  timeout=self.timeout,
633
627
  )
634
628
  if self._cancel_pending.is_set():
635
- # A cancel op landed before submit() — submit cleared the
636
- # session cancel event at run start, so re-apply it now
637
- # (the run must unwind; TUI parity for a Ctrl-C at turn start).
638
629
  self._cancel_pending.clear()
639
630
  self.session.cancel()
640
631
  model = self.session.model
@@ -219,11 +219,6 @@ def parse_at_references(
219
219
 
220
220
  for match in pattern.finditer(text):
221
221
  raw_path = match.group(1)
222
- # Strip trailing sentence/closing punctuation from the path
223
- # token: "@file.png." / "@file.png," / "(@file.png)" must
224
- # resolve "file.png", not "file.png." / "file.png," / "file.png)".
225
- # The stripped characters are left in the text (the replacement
226
- # below only swaps the @ + path token).
227
222
  stripped = raw_path.rstrip(".,;:!?)]}>\"'")
228
223
  if not stripped:
229
224
  continue
@@ -235,13 +230,6 @@ def parse_at_references(
235
230
  # can see what failed
236
231
  continue
237
232
  attachments.append(result)
238
- # Replace the @path token. For image attachments, the image
239
- # bytes are already in an ImagePart — leaving the file path in
240
- # the text causes some models to try reading the file with
241
- # tools, so replace it with a generic [image] placeholder.
242
- # For text attachments, keep the path (it provides context for
243
- # the inlined content). The trailing punctuation stripped
244
- # above stays in the text.
245
233
  full_match = match.group(0)
246
234
  if isinstance(result.part, ImagePart):
247
235
  replacements.append((full_match, full_match.replace("@" + stripped, "[image]", 1)))
@@ -259,8 +247,7 @@ def _has_image_signature(data: bytes, media_type: str) -> bool:
259
247
  """True when DATA's magic bytes match MEDIA_TYPE's signature.
260
248
 
261
249
  Any of the type's signatures matching at its offset is enough
262
- (e.g. GIF87a or GIF89a for image/gif). A file shorter than the
263
- signature offset+length can never match.
250
+ (e.g. GIF87a or GIF89a for image/gif).
264
251
  """
265
252
  signatures = _IMAGE_SIGNATURES.get(media_type)
266
253
  if not signatures:
@@ -290,7 +277,6 @@ def _validate_and_create(resolved: str, display_path: str) -> ParsedAttachment |
290
277
  ext = Path(resolved).suffix.lower()
291
278
  basename = os.path.basename(resolved)
292
279
 
293
- # Image files
294
280
  if ext in IMAGE_EXTENSIONS:
295
281
  size = os.path.getsize(resolved)
296
282
  if size > MAX_IMAGE_SIZE:
@@ -312,7 +298,6 @@ def _validate_and_create(resolved: str, display_path: str) -> ParsedAttachment |
312
298
  resolved, ImagePart(data=data, media_type=media_type, path=resolved)
313
299
  )
314
300
 
315
- # Text files
316
301
  if ext in TEXT_EXTENSIONS or basename in TEXT_BASENAMES or not ext:
317
302
  size = os.path.getsize(resolved)
318
303
  if size > MAX_TEXT_SIZE:
@@ -328,7 +313,6 @@ def _validate_and_create(resolved: str, display_path: str) -> ParsedAttachment |
328
313
  return AttachmentError(display_path, f"cannot read file: {e}")
329
314
  return ParsedAttachment(resolved, TextPart(text=content))
330
315
 
331
- # Unknown extension: try to read as text
332
316
  size = os.path.getsize(resolved)
333
317
  if size > MAX_TEXT_SIZE:
334
318
  return AttachmentError(
@@ -66,10 +66,6 @@ def unified_diff(
66
66
  for line in diff:
67
67
  out.append(line)
68
68
  if line[:1] in ("-", "+", " ") and not line.endswith("\n"):
69
- # a content line at EOF without a trailing newline: difflib
70
- # emits it bare, which would corrupt the joined text; mark
71
- # it like git does so the diff round-trips (the Edit tool's
72
- # diff mode parses markers and applies them)
73
69
  out.append("\n\\n")
74
70
  return "".join(out)
75
71
 
@@ -356,13 +356,9 @@ def parse_saved_body(body: str) -> list:
356
356
  messages.append(Message(role=role, content=content))
357
357
 
358
358
  for line in body.splitlines():
359
- # Check for a role header: **user**: ... or **assistant**: ...
360
359
  header = split_role_header(line)
361
360
  if header is not None:
362
361
  role, rest = header
363
- # Save the previous block (tool blocks lose their
364
- # tool_call_id/name; system blocks would duplicate the
365
- # live system prompt the client prepends per request)
366
362
  if current_role is not None and current_role not in ("tool", "system"):
367
363
  _flush(current_role, current_lines)
368
364
  current_role = role
@@ -370,7 +366,7 @@ def parse_saved_body(body: str) -> list:
370
366
  continue
371
367
  current_lines.append(unescape_role_header(line))
372
368
 
373
- # Don't forget the last block (tool/system blocks dropped, see above)
369
+ # flush the last block
374
370
  if current_role is not None and current_role not in ("tool", "system"):
375
371
  _flush(current_role, current_lines)
376
372
 
@@ -384,20 +380,18 @@ def find_session_by_title(query: str) -> str | None:
384
380
  and the derived title. Returns the most recent match, or None.
385
381
  """
386
382
  query_lower = query.lower()
387
- # Strip .md from query if present, for cleaner substring matching
388
383
  query_stem = query_lower[:-3] if query_lower.endswith(".md") else query_lower
389
- files = SessionPersistence.list_sessions() # already sorted by mtime desc
384
+ files = SessionPersistence.list_sessions()
390
385
  for f in files:
391
386
  basename = os.path.basename(f)
392
387
  basename_lower = basename.lower()
393
- # Exact basename match (with or without .md)
394
388
  if basename_lower == query_lower or basename_lower == query_lower + ".md":
395
389
  return f
396
- # Substring match against filename (minus .md)
390
+ # substring match against the filename
397
391
  name_part = basename[:-3] if basename.endswith(".md") else basename
398
392
  if query_stem in name_part.lower():
399
393
  return f
400
- # Match against derived title (dashes → spaces)
394
+ # match against the derived title
401
395
  title = title_from_filename(f)
402
396
  if title and query_stem in title.lower():
403
397
  return f
@@ -100,10 +100,14 @@ class LLMClient(Protocol):
100
100
 
101
101
  def abort(self) -> None: ...
102
102
 
103
+ def abort_probe(self) -> None: ...
104
+
103
105
  def close(self) -> None: ...
104
106
 
105
107
  def set_timeout(self, timeout: float) -> None: ...
106
108
 
109
+ def check_health(self, timeout: float = 15.0) -> tuple[bool, str]: ...
110
+
107
111
 
108
112
  # serializes appends to the shared LLM log file: concurrent sub-agents
109
113
  # (each with its own client but ONE shared log_path, see Client.clone)
@@ -230,11 +234,8 @@ def _log_llm_interaction(
230
234
  if not log_file:
231
235
  return
232
236
  try:
233
- # Build the entry in the same format as the conversation:
234
- # { "model": ..., "messages": [...all messages including response...] }
235
237
  messages = list(payload.get("messages", []))
236
238
 
237
- # Append the assistant response
238
239
  resp: dict[str, Any] = {"role": "assistant"}
239
240
  if response_msg.text():
240
241
  resp["content"] = response_msg.text()
@@ -410,13 +411,19 @@ class Client:
410
411
  )
411
412
  self._config_path = config_path
412
413
  self._http = httpx.Client(timeout=timeout, verify=_httpx_verify(self.verify))
414
+ # The throwaway httpx client owned by an in-flight ``check_health``
415
+ # probe (None when no probe runs). It is tracked so ``abort`` can
416
+ # wake a probe blocked in ``recv``: the probe cannot use
417
+ # ``self._http`` (it must not disturb a concurrent real request),
418
+ # so tearing down that pool would not touch it.
419
+ self._probe_http: httpx.Client | None = None
413
420
  # True while the in-flight request was aborted (Ctrl-C): a
414
421
  # connection error on an aborted request must NOT be retried —
415
422
  # the user asked to stop. Cleared at the start of each chat()
416
- # so a fresh turn may retry normally.
423
+ # so a fresh turn may retry normally. ``check_health`` honours it
424
+ # too: a probe cancelled before it published its client must not
425
+ # start a request nobody waits on.
417
426
  self._aborted = False
418
- # an explicit log file is inherited by clones so every request
419
- # of one session (main + all sub-agents) lands in a single log
420
427
  self.log_path = (
421
428
  log_path
422
429
  if log_path is not None
@@ -487,6 +494,7 @@ class Client:
487
494
  details.
488
495
  """
489
496
  self._aborted = True
497
+ self.abort_probe()
490
498
  old = self._http
491
499
  self._http = httpx.Client(timeout=self.timeout, verify=_httpx_verify(self.verify))
492
500
  with contextlib.suppress(Exception): # best effort
@@ -494,6 +502,25 @@ class Client:
494
502
  with contextlib.suppress(Exception): # best effort
495
503
  old.close()
496
504
 
505
+ def abort_probe(self) -> None:
506
+ """Stop the in-flight ``check_health`` probe, if any (called on cancel).
507
+
508
+ Same socket-level wake as ``abort`` (a thread parked in ``recv`` is
509
+ released by shutting its fd down), but WITHOUT rebuilding the
510
+ request pool: a probe runs on its own throwaway client that is
511
+ closed right afterwards, and building a replacement pool costs a
512
+ CA-bundle load (~70ms) that the cancelled /model listing would pay
513
+ once per profile — on the path that must be instant.
514
+ """
515
+ self._aborted = True
516
+ probe = self._probe_http
517
+ if probe is None:
518
+ return
519
+ with contextlib.suppress(Exception): # best effort
520
+ _abort_inflight_sockets(probe)
521
+ with contextlib.suppress(Exception): # best effort
522
+ probe.close()
523
+
497
524
  def _reset_http(self) -> None:
498
525
  """Replace the httpx client with a fresh instance.
499
526
 
@@ -518,6 +545,107 @@ class Client:
518
545
  self.timeout = timeout
519
546
  self._reset_http()
520
547
 
548
+ def check_health(self, timeout: float = 15.0) -> tuple[bool, str]:
549
+ """Minimal probe: send a tiny chat completion to verify the model works.
550
+
551
+ Returns ``(available, message)``. Does not retry transient
552
+ errors — this is a probe, not a request the user is waiting on —
553
+ except a 401: the key may have expired and an external refresh
554
+ process may write a new one, so the key is re-read (bounded by
555
+ *timeout*) and the probe retried once, mirroring ``chat()``'s
556
+ ``AuthExpiredError`` handling. Uses a temporary httpx client so
557
+ it never interferes with the main pool.
558
+
559
+ A chat completion request is the only reliable way to verify a
560
+ specific model is actually usable: the ``/models`` endpoint can
561
+ be stale, incomplete, or return IDs that differ from what the
562
+ completions endpoint accepts.
563
+
564
+ The call runs on a throwaway httpx client (so a probe never
565
+ disturbs a concurrent real request) which is published as
566
+ ``_probe_http`` for the duration: ``abort`` uses it to wake a
567
+ probe blocked in ``recv`` instead of leaving the caller's thread
568
+ parked until the timeout expires.
569
+ """
570
+ try:
571
+ resp = self._probe_request(timeout)
572
+ if resp is None:
573
+ return False, "aborted"
574
+ if resp.status_code == 401:
575
+ if self._refresh_api_key(
576
+ cancel_check=lambda: self._aborted,
577
+ timeout=timeout,
578
+ poll_interval=1.0,
579
+ ):
580
+ resp = self._probe_request(timeout)
581
+ if resp is None:
582
+ return False, "aborted"
583
+ elif self._aborted:
584
+ return False, "aborted"
585
+ try:
586
+ body = resp.json()
587
+ except ValueError:
588
+ body = None
589
+ # 3xx is not success: redirects aren't followed, so an SSO or
590
+ # captive-portal redirect must not read as a working model
591
+ if 200 <= resp.status_code < 300:
592
+ # some gateways report failures as 200 + {"error": ...}
593
+ err = _error_text(body) if isinstance(body, dict) else None
594
+ if err:
595
+ return False, f"HTTP {resp.status_code}: {err[:80]}"
596
+ return True, "ok"
597
+ # not AUTH_REFRESH_STATUS_CODES: it may include 502, which here
598
+ # means the backend is down, not that the key expired
599
+ if resp.status_code in (401, 403):
600
+ return False, f"auth error ({resp.status_code})"
601
+ if resp.status_code == 429:
602
+ return False, "rate limited (429)"
603
+ if isinstance(body, dict):
604
+ msg = _error_text(body) or body.get("message")
605
+ if msg:
606
+ return False, f"HTTP {resp.status_code}: {str(msg)[:80]}"
607
+ return False, f"HTTP {resp.status_code}"
608
+ except httpx.HTTPError as e:
609
+ return False, f"unreachable: {type(e).__name__}"
610
+ except (OSError, RuntimeError) as e:
611
+ # RuntimeError: abort() closed the probe client just as the
612
+ # request was about to be sent (httpx refuses a closed client).
613
+ # Still a "the probe did not answer" outcome, not a crash.
614
+ return False, f"unreachable: {type(e).__name__}"
615
+
616
+ def _probe_request(self, timeout: float) -> httpx.Response | None:
617
+ """Send one probe request on a throwaway client.
618
+
619
+ Returns the response, or None if the probe was aborted before it
620
+ could start. The client is published as ``_probe_http`` for the
621
+ duration so ``abort`` can wake it, and cleared again afterwards
622
+ (only our own slot: a concurrent probe may have replaced it).
623
+ """
624
+ with httpx.Client(timeout=timeout, verify=_httpx_verify(self.verify)) as probe:
625
+ self._probe_http = probe
626
+ # abort() may have landed before the client was published
627
+ # (then it had no socket to wake) or right after; either
628
+ # way, do not start a request the caller already stopped
629
+ # waiting for — it would block for the whole timeout.
630
+ if self._aborted:
631
+ return None
632
+ try:
633
+ return probe.post(
634
+ f"{self.base_url}/chat/completions",
635
+ headers=self._headers(stream=False),
636
+ # no token limit: reasoning models reject ``max_tokens``
637
+ # (they want ``max_completion_tokens``), and chat() sends
638
+ # none by default either
639
+ json={
640
+ "model": self.model,
641
+ "messages": [{"role": "user", "content": "hi"}],
642
+ "stream": False,
643
+ },
644
+ )
645
+ finally:
646
+ if self._probe_http is probe:
647
+ self._probe_http = None
648
+
521
649
  def _refresh_api_key(
522
650
  self,
523
651
  cancel_check: Callable[[], bool] | None = None,
@@ -579,8 +707,6 @@ class Client:
579
707
  reasoning_effort: str | None = None,
580
708
  supports_image_input: bool = False,
581
709
  ) -> dict[str, Any]:
582
- # When the target model does not accept image input, strip
583
- # ImagePart from message content to avoid API errors.
584
710
  if not supports_image_input:
585
711
  messages = [_strip_image_parts(m) for m in messages]
586
712
  msgs = [m.to_api() for m in messages]
@@ -475,8 +475,7 @@ def _is_mode_reminder_text(text: str) -> bool:
475
475
 
476
476
  Content-based: the plan.md / plan-mode.md / build-switch.md prompts
477
477
  all start with the <system-reminder> tag, and the plan-exit approval
478
- notice has a fixed format — the same checks the TUI uses, which also
479
- cover restored sessions where the ``injected`` flag is lost.
478
+ notice has a fixed format.
480
479
  """
481
480
  from ..io.text_filter import is_mode_reminder_text
482
481
 
@@ -735,8 +734,8 @@ def discover_agents(agents_dir: str | os.PathLike | None = None) -> dict[str, st
735
734
  The bundled ``prompts/agents/`` profiles are always discovered. When
736
735
  *agents_dir* is set (``paths.agent_path`` in the config file), its
737
736
  files are layered on top: a configured agent overrides a bundled one
738
- of the same name, and the rest of the bundled profiles stay
739
- available. A missing configured directory contributes nothing.
737
+ of the same name. A missing configured directory contributes
738
+ nothing.
740
739
  """
741
740
  agents = _scan_agents_dir(AGENTS_DIR)
742
741
  if agents_dir:
@@ -30,11 +30,8 @@ from ..prompts import _git_toplevel, read_prompt_file
30
30
  PROMPTS_DIR = Path(__file__).parents[1] / "prompts"
31
31
  COMMANDS_DIR = PROMPTS_DIR / "commands"
32
32
 
33
- # Custom command files take precedence over the builtin slash commands (see
34
- # ``find_command``), so a configured ``review.md`` replaces ``/review``. The
35
- # one exception is ``/exit``: it is the only way out of an interactive
36
- # session, so a command file may not shadow it. Such a file is skipped and
37
- # ``/help`` reports it instead of silently dropping it.
33
+ # ``/exit`` is the only way out of an interactive session, so a command
34
+ # file may not shadow it.
38
35
  UNOVERRIDABLE_COMMAND_NAMES = frozenset({"exit"})
39
36
 
40
37