verifiers 0.3.2.dev19__py3-none-any.whl → 0.3.2.dev21__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.
@@ -87,7 +87,6 @@ __all__ = [
87
87
  "OpenAIChatCompletionsClient",
88
88
  "OpenAICompletionsClient",
89
89
  "OpenAIResponsesClient",
90
- "RendererClient",
91
90
  "extract_boxed_answer",
92
91
  "extract_hash_answer",
93
92
  "load_example_dataset",
@@ -116,7 +115,6 @@ _LAZY_IMPORTS = {
116
115
  "OpenAIChatCompletionsClient": (
117
116
  "verifiers.legacy.clients.openai_chat_completions_client:OpenAIChatCompletionsClient"
118
117
  ),
119
- "RendererClient": ("verifiers.legacy.clients.renderer_client:RendererClient"),
120
118
  "OpenAICompletionsClient": (
121
119
  "verifiers.legacy.clients.openai_completions_client:OpenAICompletionsClient"
122
120
  ),
@@ -152,8 +150,6 @@ def __getattr__(name: str):
152
150
  except KeyError:
153
151
  raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
154
152
  except ModuleNotFoundError as e:
155
- if name == "RendererClient":
156
- raise
157
153
  raise AttributeError(
158
154
  f"To use verifiers.{name}, install as `verifiers[all]`. "
159
155
  ) from e
@@ -167,7 +163,6 @@ if TYPE_CHECKING:
167
163
  )
168
164
  from .clients.openai_completions_client import OpenAICompletionsClient # noqa: F401
169
165
  from .clients.openai_responses_client import OpenAIResponsesClient # noqa: F401
170
- from .clients.renderer_client import RendererClient # noqa: F401
171
166
  from .envs.env_group import EnvGroup # noqa: F401
172
167
  from .envs.environment import Environment # noqa: F401
173
168
  from .envs.experimental.cli_agent_env import CliAgentEnv # noqa: F401
@@ -33,9 +33,12 @@ def resolve_client(client_or_config: Client | ClientConfig) -> Client:
33
33
  case "openai_responses":
34
34
  return OpenAIResponsesClient(client_or_config)
35
35
  case "renderer":
36
- from verifiers.legacy.clients.renderer_client import RendererClient
37
-
38
- return RendererClient(client_or_config)
36
+ raise ValueError(
37
+ "client_type 'renderer' was removed: the legacy "
38
+ "RendererClient depended on renderer pool APIs dropped in "
39
+ "renderers 0.1.11. Use the verifiers.v1 train client for "
40
+ "renderer-backed token generation."
41
+ )
39
42
  case "anthropic_messages":
40
43
  return AnthropicMessagesClient(client_or_config)
41
44
  case "nemorl_chat_completions":
@@ -44,14 +47,6 @@ def resolve_client(client_or_config: Client | ClientConfig) -> Client:
44
47
  raise ValueError(f"Unsupported client type: {type(client_or_config)}")
45
48
 
46
49
 
47
- def __getattr__(name: str):
48
- if name == "RendererClient":
49
- from verifiers.legacy.clients.renderer_client import RendererClient
50
-
51
- return RendererClient
52
- raise AttributeError(f"module 'verifiers.legacy.clients' has no attribute '{name}'")
53
-
54
-
55
50
  __all__ = [
56
51
  "AnthropicMessagesClient",
57
52
  "NeMoRLChatCompletionsClient",
@@ -59,6 +54,5 @@ __all__ = [
59
54
  "OpenAIChatCompletionsClient",
60
55
  "OpenAIChatCompletionsTokenClient",
61
56
  "OpenAIResponsesClient",
62
- "RendererClient",
63
57
  "Client",
64
58
  ]
@@ -1,17 +1,14 @@
1
- import json
2
1
  import os
3
- from pathlib import Path
4
2
 
5
3
  from verifiers.v1.clients import ModelContext
6
4
  from verifiers.v1.configs.harness import HarnessConfig
7
- from verifiers.v1.dialects.chat import message_to_wire
8
5
  from verifiers.v1.harness import Harness
6
+ from verifiers.v1.harnesses.minimal import PROGRAM_SOURCE
7
+ from verifiers.v1.harnesses.standalone import launch_chat_program
9
8
  from verifiers.v1.runtimes import ProgramResult, Runtime
10
9
  from verifiers.v1.task import TaskData
11
10
  from verifiers.v1.trace import Trace
12
11
 
13
- PROGRAM_SOURCE = (Path(__file__).resolve().parent / "program.py").read_text()
14
-
15
12
  # Frames the model as a coding agent and names its local tools (a pure-text chat loop gets no
16
13
  # harness-injected prompt). The edit clause is appended only when the `edit` tool is enabled.
17
14
  BASH_SYSTEM_PROMPT = (
@@ -69,12 +66,7 @@ class BashHarness(Harness[BashHarnessConfig]):
69
66
  p for p in (" ".join(fragments), system_prompt) if p
70
67
  )
71
68
  env = {**self.config.resolved_env}
72
- args = [
73
- f"--base-url={endpoint}",
74
- f"--api-key={secret}",
75
- f"--model={ctx.model}",
76
- f"--system-prompt={system_prompt}",
77
- ]
69
+ args = ["--bash"]
78
70
  if tool_interception_url:
79
71
  args.append(f"--tool-interception-url={tool_interception_url}")
80
72
  if self.config.edit:
@@ -97,31 +89,18 @@ class BashHarness(Harness[BashHarnessConfig]):
97
89
  "(the host env or the harness config's env)"
98
90
  )
99
91
  args += ["--search", f"--serper-key={serper_key}"]
100
- if mcp_urls:
101
- # The program connects to the tool servers over HTTP; hand it a standard
102
- # `mcpServers` URL config (the `mcp` client itself comes from the uv deps).
103
- args.append(
104
- "--mcp-config="
105
- + json.dumps(
106
- {
107
- "mcpServers": {
108
- name: {"url": url, "timeout": self.config.tool_timeout}
109
- for name, url in mcp_urls.items()
110
- }
111
- }
112
- )
113
- )
114
- if isinstance(prompt, str):
115
- args.append(f"--prompt={prompt}")
116
- elif prompt is not None:
117
- # Base64 images can exceed exec limits, so hand Messages off through a file.
118
- path = f".vf-initial-messages-{trace.id}.json"
119
- await runtime.write(
120
- path,
121
- json.dumps([message_to_wire(m) for m in prompt]).encode(),
122
- )
123
- args.append(f"--initial-messages-file={path}")
124
- program = await runtime.prepare_uv_script(
125
- PROGRAM_SOURCE, self.config.resolved_env, activate=False
92
+ return await launch_chat_program(
93
+ PROGRAM_SOURCE,
94
+ self.config,
95
+ ctx,
96
+ trace,
97
+ runtime,
98
+ endpoint,
99
+ secret,
100
+ mcp_urls,
101
+ system_prompt,
102
+ prompt,
103
+ extra_args=args,
104
+ env=env,
105
+ activate=False,
126
106
  )
127
- return await runtime.run_program([*program, *args], env)
@@ -1,4 +1,3 @@
1
- import json
2
1
  from pathlib import Path
3
2
  from typing import Literal
4
3
 
@@ -6,13 +5,15 @@ from pydantic import model_validator
6
5
 
7
6
  from verifiers.v1.clients import ModelContext
8
7
  from verifiers.v1.configs.harness import HarnessConfig
9
- from verifiers.v1.dialects.chat import message_to_wire
10
8
  from verifiers.v1.harness import Harness
9
+ from verifiers.v1.harnesses.standalone import inline_mcp_client, launch_chat_program
11
10
  from verifiers.v1.runtimes import ProgramResult, Runtime
12
11
  from verifiers.v1.task import TaskData
13
12
  from verifiers.v1.trace import Trace
14
13
 
15
- PROGRAM_SOURCE = (Path(__file__).resolve().parent / "program.py").read_text()
14
+ PROGRAM_SOURCE = inline_mcp_client(
15
+ (Path(__file__).resolve().parent / "program.py").read_text()
16
+ )
16
17
 
17
18
  # The helper names and persistence rules the model needs to use the local tool.
18
19
  BROWSER_SYSTEM_PROMPT = """You are a browser automation agent. Your `browser` tool executes Python code that controls a real Chromium over CDP through browser-harness; its helpers are pre-imported.
@@ -85,42 +86,23 @@ class BrowserUseHarness(Harness[BrowserUseHarnessConfig]):
85
86
  env = {**self.config.resolved_env}
86
87
  state = f".vf-browser-{trace.id}"
87
88
  args = [
88
- f"--base-url={endpoint}",
89
- f"--api-key={secret}",
90
- f"--model={ctx.model}",
91
89
  f"--browser={self.config.browser}",
92
90
  # A resumed segment reuses this trace's browser and profile.
93
91
  f"--state-dir={state}",
94
92
  ]
95
- if not replaying_browser_prompt:
96
- args.append(f"--system-prompt={system_prompt}")
97
93
  if self.config.cdp_url:
98
94
  args.append(f"--cdp-url={self.config.cdp_url}")
99
- if mcp_urls:
100
- # The program connects to the tool servers over HTTP; hand it a standard
101
- # `mcpServers` URL config (the `mcp` client itself comes from the uv deps).
102
- args.append(
103
- "--mcp-config="
104
- + json.dumps(
105
- {
106
- "mcpServers": {
107
- name: {"url": url, "timeout": self.config.tool_timeout}
108
- for name, url in mcp_urls.items()
109
- }
110
- }
111
- )
112
- )
113
- if isinstance(prompt, str):
114
- args.append(f"--prompt={prompt}")
115
- elif prompt is not None:
116
- # Base64 images can exceed exec limits, so hand Messages off through a file.
117
- path = f".vf-initial-messages-{trace.id}.json"
118
- await runtime.write(
119
- path,
120
- json.dumps([message_to_wire(m) for m in prompt]).encode(),
121
- )
122
- args.append(f"--initial-messages-file={path}")
123
- program = await runtime.prepare_uv_script(
124
- PROGRAM_SOURCE, self.config.resolved_env
95
+ return await launch_chat_program(
96
+ PROGRAM_SOURCE,
97
+ self.config,
98
+ ctx,
99
+ trace,
100
+ runtime,
101
+ endpoint,
102
+ secret,
103
+ mcp_urls,
104
+ None if replaying_browser_prompt else system_prompt,
105
+ prompt,
106
+ extra_args=args,
107
+ env=env,
125
108
  )
126
- return await runtime.run_program([*program, *args], env)
@@ -27,16 +27,15 @@ import subprocess
27
27
  import sys
28
28
  import time
29
29
  import urllib.request
30
- from contextlib import AsyncExitStack, asynccontextmanager, suppress
31
30
  from pathlib import Path
32
- from typing import Any, cast
31
+ from typing import TYPE_CHECKING, Any, cast
33
32
  from urllib.parse import urlsplit
34
33
 
35
34
  from openai import AsyncOpenAI
36
- from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter
37
35
 
38
- MCP_CALL_ATTEMPTS = 6
39
- MCP_TIMEOUT = 600.0
36
+ if TYPE_CHECKING:
37
+ # The harness bundles this module into the generated script before execution.
38
+ from verifiers.v1.mcp.client import call_mcp, connect_mcp # noqa: TC004
40
39
 
41
40
  BROWSER_TOOL_TIMEOUT = 3600
42
41
  """Matches the bash harness's command timeout."""
@@ -187,117 +186,6 @@ async def chat(
187
186
  return completion.choices[0].message
188
187
 
189
188
 
190
- @asynccontextmanager
191
- async def mcp_client(spec: dict):
192
- """One fresh MCP client, negotiating the newest protocol and falling back for old servers.
193
-
194
- It is opened and closed within the caller's task so AnyIO cancellation scopes stay correctly
195
- nested. Closing noise after a completed body cannot fail or replay an answered call.
196
- """
197
- import httpx2
198
- from mcp import Client
199
- from mcp.client.streamable_http import (
200
- create_mcp_http_client,
201
- streamable_http_client,
202
- )
203
-
204
- stack = AsyncExitStack()
205
- try:
206
- http_client = await stack.enter_async_context(
207
- create_mcp_http_client(
208
- headers=spec.get("headers") or None,
209
- timeout=httpx2.Timeout(spec.get("timeout", MCP_TIMEOUT), connect=5.0),
210
- )
211
- )
212
- transport = streamable_http_client(spec["url"], http_client=http_client)
213
- yield await stack.enter_async_context(Client(transport))
214
- finally:
215
- with suppress(Exception):
216
- await stack.aclose()
217
-
218
-
219
- async def with_retry(call):
220
- """Run one client operation, retrying transient failures with backoff. A call whose
221
- response was lost may be replayed — MCP has no idempotency key, so tools should tolerate
222
- at-least-once delivery (a tool that fails reports through its result, not an exception)."""
223
- async for attempt in AsyncRetrying(
224
- stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
225
- wait=wait_exponential_jitter(initial=0.5, max=30),
226
- reraise=True,
227
- ):
228
- with attempt:
229
- return await call()
230
-
231
-
232
- async def connect_mcp(
233
- config: dict, reserved: set[str]
234
- ) -> tuple[list[dict], dict, dict]:
235
- """Enumerate each configured MCP server's tools (a streamable-HTTP `url`); return (tool schemas,
236
- dispatch mapping `<server>_<tool>` -> (server name, raw tool name), servers mapping name -> spec).
237
- No protocol session is held; a fresh client handles each call."""
238
- tool_schemas: list[dict] = []
239
- dispatch: dict[str, tuple] = {}
240
- servers: dict[str, dict] = {}
241
- for name, spec in config.get("mcpServers", {}).items():
242
- servers[name] = spec
243
-
244
- async def list_tools(spec: dict = spec):
245
- async with mcp_client(spec) as client:
246
- return (await client.list_tools()).tools
247
-
248
- for tool in await with_retry(list_tools):
249
- # A server named "" (TOOL_PREFIX = None) advertises its tools bare.
250
- full = f"{name}_{tool.name}" if name else tool.name
251
- if full in reserved or full in dispatch:
252
- raise ValueError(
253
- f"duplicate tool name {full!r}; keep MCP tool names qualified"
254
- )
255
- tool_schemas.append(
256
- {
257
- "type": "function",
258
- "function": {
259
- "name": full,
260
- "description": tool.description or "",
261
- "parameters": tool.input_schema,
262
- },
263
- }
264
- )
265
- dispatch[full] = (name, tool.name)
266
- return tool_schemas, dispatch, servers
267
-
268
-
269
- def mcp_content_to_chat_content(blocks) -> str | list[dict]:
270
- parts = []
271
- for block in blocks:
272
- if block.type == "text":
273
- parts.append({"type": "text", "text": block.text})
274
- elif block.type == "image":
275
- url = f"data:{block.mime_type};base64,{block.data}"
276
- parts.append({"type": "image_url", "image_url": {"url": url}})
277
- else:
278
- parts.append({"type": "text", "text": str(block)})
279
- if not parts:
280
- return str(blocks)
281
- if all(part["type"] == "text" for part in parts):
282
- return "\n".join(str(part["text"]) for part in parts)
283
- return parts
284
-
285
-
286
- async def call_mcp(
287
- servers: dict, dispatch: dict, name: str, arguments: dict
288
- ) -> str | list[dict]:
289
- """Call a tool with a fresh client per attempt — see `with_retry` for replay semantics.
290
- The result is converted outside the retry so a conversion failure fails once."""
291
- server_name, raw = dispatch[name]
292
-
293
- async def call():
294
- async with mcp_client(servers[server_name]) as client:
295
- return await client.call_tool(raw, arguments)
296
-
297
- result = await with_retry(call)
298
- return mcp_content_to_chat_content(result.content)
299
-
300
-
301
189
  def parse_args() -> argparse.Namespace:
302
190
  parser = argparse.ArgumentParser()
303
191
  parser.add_argument("--base-url", required=True)
@@ -0,0 +1,9 @@
1
+ from pathlib import Path
2
+
3
+ from verifiers.v1.harnesses.standalone import inline_mcp_client
4
+
5
+ PROGRAM_SOURCE = inline_mcp_client(
6
+ (Path(__file__).resolve().parent / "program.py").read_text()
7
+ )
8
+
9
+ __all__ = ["PROGRAM_SOURCE"]
@@ -2,23 +2,42 @@
2
2
  # requires-python = ">=3.10"
3
3
  # dependencies = ["openai", "mcp==2.0.0", "httpx", "httpx2", "tenacity"]
4
4
  # ///
5
- """Secrets arrive through argv so local tool subprocesses do not inherit them."""
5
+ """Shared Null/Bash chat program; secrets use argv so tools do not inherit them."""
6
6
 
7
7
  import argparse
8
8
  import asyncio
9
9
  import json
10
10
  import subprocess
11
- from contextlib import AsyncExitStack, asynccontextmanager, suppress
12
11
  from pathlib import Path
12
+ from typing import TYPE_CHECKING
13
13
 
14
14
  import httpx
15
- from openai import AsyncOpenAI
16
- from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter
15
+ from openai import APIStatusError, AsyncOpenAI
16
+
17
+ if TYPE_CHECKING:
18
+ # The harness bundles this module into the generated script before execution.
19
+ from verifiers.v1.mcp.client import call_mcp, connect_mcp # noqa: TC004
17
20
 
18
21
  SERPER_URL = "https://google.serper.dev/search"
19
22
 
20
- MCP_CALL_ATTEMPTS = 6
21
- MCP_TIMEOUT = 600.0
23
+ CONTEXT_OVERFLOW_MARKERS = (
24
+ "context_length_exceeded",
25
+ "exceeds the context window",
26
+ "reduce the length of the messages",
27
+ "maximum context length",
28
+ "prompt is too long",
29
+ "request_too_large",
30
+ "request entity too large",
31
+ "exceeds the maximum number of tokens",
32
+ "maximum prompt length is",
33
+ )
34
+
35
+
36
+ def is_context_overflow(error: APIStatusError) -> bool:
37
+ details = f"{error} {error.body or ''}".casefold()
38
+ return error.status_code in (400, 413) and any(
39
+ marker in details for marker in CONTEXT_OVERFLOW_MARKERS
40
+ )
22
41
 
23
42
 
24
43
  BASH_TOOL = {
@@ -186,117 +205,6 @@ async def chat(
186
205
  return completion.choices[0].message
187
206
 
188
207
 
189
- @asynccontextmanager
190
- async def mcp_client(spec: dict):
191
- """One fresh MCP client, negotiating the newest protocol and falling back for old servers.
192
-
193
- It is opened and closed within the caller's task so AnyIO cancellation scopes stay correctly
194
- nested. Closing noise after a completed body cannot fail or replay an answered call.
195
- """
196
- import httpx2
197
- from mcp import Client
198
- from mcp.client.streamable_http import (
199
- create_mcp_http_client,
200
- streamable_http_client,
201
- )
202
-
203
- stack = AsyncExitStack()
204
- try:
205
- http_client = await stack.enter_async_context(
206
- create_mcp_http_client(
207
- headers=spec.get("headers") or None,
208
- timeout=httpx2.Timeout(spec.get("timeout", MCP_TIMEOUT), connect=5.0),
209
- )
210
- )
211
- transport = streamable_http_client(spec["url"], http_client=http_client)
212
- yield await stack.enter_async_context(Client(transport))
213
- finally:
214
- with suppress(Exception):
215
- await stack.aclose()
216
-
217
-
218
- async def with_retry(call):
219
- """Run one client operation, retrying transient failures with backoff. A call whose
220
- response was lost may be replayed — MCP has no idempotency key, so tools should tolerate
221
- at-least-once delivery (a tool that fails reports through its result, not an exception)."""
222
- async for attempt in AsyncRetrying(
223
- stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
224
- wait=wait_exponential_jitter(initial=0.5, max=30),
225
- reraise=True,
226
- ):
227
- with attempt:
228
- return await call()
229
-
230
-
231
- async def connect_mcp(
232
- config: dict, reserved: set[str]
233
- ) -> tuple[list[dict], dict, dict]:
234
- """Enumerate each configured MCP server's tools (a streamable-HTTP `url`); return (tool schemas,
235
- dispatch mapping `<server>_<tool>` -> (server name, raw tool name), servers mapping name -> spec).
236
- No protocol session is held; a fresh client handles each call."""
237
- tool_schemas: list[dict] = []
238
- dispatch: dict[str, tuple] = {}
239
- servers: dict[str, dict] = {}
240
- for name, spec in config.get("mcpServers", {}).items():
241
- servers[name] = spec
242
-
243
- async def list_tools(spec: dict = spec):
244
- async with mcp_client(spec) as client:
245
- return (await client.list_tools()).tools
246
-
247
- for tool in await with_retry(list_tools):
248
- # A server named "" (TOOL_PREFIX = None) advertises its tools bare.
249
- full = f"{name}_{tool.name}" if name else tool.name
250
- if full in reserved or full in dispatch:
251
- raise ValueError(
252
- f"duplicate tool name {full!r}; keep MCP tool names qualified"
253
- )
254
- tool_schemas.append(
255
- {
256
- "type": "function",
257
- "function": {
258
- "name": full,
259
- "description": tool.description or "",
260
- "parameters": tool.input_schema,
261
- },
262
- }
263
- )
264
- dispatch[full] = (name, tool.name)
265
- return tool_schemas, dispatch, servers
266
-
267
-
268
- def mcp_content_to_chat_content(blocks) -> str | list[dict]:
269
- parts = []
270
- for block in blocks:
271
- if block.type == "text":
272
- parts.append({"type": "text", "text": block.text})
273
- elif block.type == "image":
274
- url = f"data:{block.mime_type};base64,{block.data}"
275
- parts.append({"type": "image_url", "image_url": {"url": url}})
276
- else:
277
- parts.append({"type": "text", "text": str(block)})
278
- if not parts:
279
- return str(blocks)
280
- if all(part["type"] == "text" for part in parts):
281
- return "\n".join(part["text"] for part in parts)
282
- return parts
283
-
284
-
285
- async def call_mcp(
286
- servers: dict, dispatch: dict, name: str, arguments: dict
287
- ) -> str | list[dict]:
288
- """Call a tool with a fresh client per attempt — see `with_retry` for replay semantics.
289
- The result is converted outside the retry so a conversion failure fails once."""
290
- server_name, raw = dispatch[name]
291
-
292
- async def call():
293
- async with mcp_client(servers[server_name]) as client:
294
- return await client.call_tool(raw, arguments)
295
-
296
- result = await with_retry(call)
297
- return mcp_content_to_chat_content(result.content)
298
-
299
-
300
208
  async def run_tool_hook(
301
209
  client: httpx.AsyncClient,
302
210
  url: str,
@@ -326,6 +234,7 @@ def parse_args() -> argparse.Namespace:
326
234
  parser.add_argument("--initial-messages-file", default="")
327
235
  parser.add_argument("--mcp-config", default="")
328
236
  parser.add_argument("--tool-interception-url", default="")
237
+ parser.add_argument("--bash", action="store_true")
329
238
  parser.add_argument("--edit", action="store_true")
330
239
  parser.add_argument("--search", action="store_true")
331
240
  parser.add_argument("--serper-key", default="")
@@ -340,26 +249,31 @@ async def main() -> None:
340
249
  payload = path.read_bytes()
341
250
  path.unlink()
342
251
  initial = json.loads(payload)
343
- client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key)
252
+ client = AsyncOpenAI(
253
+ base_url=args.base_url,
254
+ api_key=args.api_key,
255
+ timeout=httpx.Timeout(600.0 if args.bash else None, connect=5.0),
256
+ )
344
257
  tool_client = (
345
258
  httpx.AsyncClient(timeout=httpx.Timeout(None, connect=5.0))
346
259
  if args.tool_interception_url
347
260
  else None
348
261
  )
349
262
  config = json.loads(args.mcp_config or "{}")
350
- tools = [BASH_TOOL]
351
- reserved = {"bash"}
263
+ tools = [BASH_TOOL] if args.bash else []
264
+ reserved = {"bash"} if args.bash else set()
352
265
  if args.edit:
353
266
  tools.append(EDIT_TOOL)
354
267
  reserved.add("edit")
355
268
  if args.search:
356
269
  tools.append(SEARCH_TOOL)
357
270
  reserved.add("search")
358
- mcp_tools, dispatch, servers = (
359
- await connect_mcp(config, reserved)
360
- if config.get("mcpServers")
361
- else ([], {}, {})
362
- )
271
+ if config.get("mcpServers"):
272
+ mcp_tools, dispatch, servers = await asyncio.wait_for(
273
+ connect_mcp(config, reserved), timeout=None if args.bash else 60
274
+ )
275
+ else:
276
+ mcp_tools, dispatch, servers = [], {}, {}
363
277
  tools += mcp_tools
364
278
  messages = (
365
279
  [{"role": "system", "content": args.system_prompt}]
@@ -371,7 +285,13 @@ async def main() -> None:
371
285
  elif args.prompt:
372
286
  messages.append({"role": "user", "content": args.prompt})
373
287
  while True:
374
- message = await chat(client, args.model, messages, tools)
288
+ try:
289
+ message = await chat(client, args.model, messages, tools)
290
+ except APIStatusError as error:
291
+ # Null cannot compact, so context exhaustion ends it with the transcript so far.
292
+ if args.bash or not is_context_overflow(error):
293
+ raise
294
+ return
375
295
  messages.append(message.model_dump(exclude_none=True))
376
296
  if not message.tool_calls:
377
297
  break
@@ -405,7 +325,7 @@ async def main() -> None:
405
325
  content = f"error: tool arguments must be a JSON object, got {type(tool_args).__name__}; resend as an object"
406
326
  elif name in dispatch:
407
327
  content = await call_mcp(servers, dispatch, name, tool_args)
408
- elif name == "bash":
328
+ elif name == "bash" and args.bash:
409
329
  content = await asyncio.to_thread(
410
330
  run_bash, tool_args.get("command", "")
411
331
  )