diff --git a/src/freehand/runtime/agent.py b/src/freehand/runtime/agent.py index ec5587c..34db2bb 100755 --- a/src/freehand/runtime/agent.py +++ b/src/freehand/runtime/agent.py @@ -1161,7 +1161,8 @@ def _send_request(self, token: str | None, kind: str) -> dict[str, Any]: return self._send_once(token, kind) except _providers.HTTPStatusError as exc: err = ModelError(exc.status, exc.body) - if exc.status < 500 or err.code in NON_RETRYABLE_CODES or attempt == limit: + # Some servers (Apple's `fm serve`) report an overflow as a 5xx; resending cannot make it fit. + if exc.status < 500 or err.code in NON_RETRYABLE_CODES or _compaction.overflow(err) or attempt == limit: raise wait = exc.retry_after if exc.retry_after is not None else retry_delay(attempt) if not self._backoff(wait, f"HTTP {exc.status}", attempt, exc.status, error_detail(exc.body), @@ -1289,7 +1290,7 @@ def call_model(self) -> dict[str, Any]: except StreamFailure as exc: self._check_cancel() last = ModelError(429 if exc.code == USAGE_LIMIT_CODE else 200, exc.body) - if (exc.code in NON_RETRYABLE_CODES or image_input_error(exc.body) + if (exc.code in NON_RETRYABLE_CODES or image_input_error(exc.body) or _compaction.overflow(last) or (self.edited_pending and last.rejects_transcript_edit())): raise last from None retry_after = exc.retry_after @@ -1764,7 +1765,8 @@ def run_turn(self, interactive: bool = False) -> tuple[str, str]: return "stopped_usage_limit", ("Usage limit reached on your ChatGPT plan (or on Freehand's share " f"of it). Manage usage: {_auth.USAGE_URL}") if exc.code == "context_length_exceeded" or re.search( - r"context (length|window)|maximum context|prompt is too long|input token count.*exceeds", + r"context (length|window)|maximum context|prompt is too long|input token count.*exceeds|" + r"exceeded the model's context size", exc.body, re.I): window = f" of {int(self.cfg['context_window']):,}" if self.cfg.get("context_window") else "" return "context_full", (f"the context no longer fits the model's window{window} tokens " diff --git a/src/freehand/runtime/compaction.py b/src/freehand/runtime/compaction.py index 0bdf2a9..b43310e 100644 --- a/src/freehand/runtime/compaction.py +++ b/src/freehand/runtime/compaction.py @@ -257,4 +257,5 @@ def overflow(exc: Any) -> bool: or bool(re.search(r"context[_ ](?:length|window).*(?:exceed|limit)|exceeds.*context (?:window|length)|" r"maximum context|prompt (?:is )?too long|input token count.*exceeds|" r"maximum prompt length|exceeded model token limit|context window exceeds|" - r"reduce the length of the messages|exceeds the available context size", body, re.I))) + r"reduce the length of the messages|exceeds the available context size|" + r"exceeded the model's context size", body, re.I))) diff --git a/tests/test_context_window.py b/tests/test_context_window.py index 4492634..412320f 100644 --- a/tests/test_context_window.py +++ b/tests/test_context_window.py @@ -4,6 +4,8 @@ import json from http.server import BaseHTTPRequestHandler +import pytest + from fakes import FakeAuth, FakeResponses, call, developer_texts, say, load_runtime, make_session, send_json, transcript from freehand import session, ui from test_runtime import serve @@ -70,6 +72,46 @@ def do_POST(self): assert status == "context_full" and "272,000" in summary +FM_OVERFLOW = {"error": {"message": "The session's transcript exceeded the model's context size.", + "type": "server_error", "code": "500"}} + + +@pytest.mark.parametrize("stream", [True, False]) +def test_apple_fm_overflow_is_context_full_and_not_retried(tmp_path, stream): + # `fm serve` reports overflow as a server error: in-stream after HTTP 200, or HTTP 500 without streaming. + # Each retry would resend the whole conversation against Apple's daily PCC quota. + posts = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + posts.append(json.loads(self.rfile.read(int(self.headers["Content-Length"])))) + if not stream: + return send_json(self, 500, FM_OVERFLOW) + data = (b'data: {"choices":[{"index":0,"delta":{"role":"assistant"}}]}\n\n' + b"event: error\ndata: " + json.dumps(FM_OVERFLOW).encode() + b"\n\n") + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + server, url = serve(Handler) + try: + h = make_session(tmp_path, url, provider="openai-chat", model="pcc", auth="none", stream=stream, + context_window=32768) + agent = load_runtime(h).Agent(h) + agent.start() + status, summary = agent.submit("hello") + finally: + server.shutdown() + server.server_close() + assert status == "context_full" and "32,768" in summary + assert len(posts) == 1 + + def test_status_bar_shows_used_over_window(tmp_path): h = make_session(tmp_path, "http://127.0.0.1:1", context_window=500000, model="gpt-6.1-sol") agent = load_runtime(h).Agent(h)