Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): size context compaction to the model's real window

Haozhe Wuef2a1e0e9fbc
diff --git a/agent/.env.example b/agent/.env.example
index 581c4b630..30d18bfce 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -323,7 +323,16 @@ TUSHARE_TOKEN=your-tushare-token
# SWARM_STREAM_RETRY_MAX_DELAY_S=30.0
# SUBAGENT_TIMEOUT=300
# SUBAGENT_MAX_ITER=25
-# TOKEN_THRESHOLD=40000
+# Context compaction follows the model's real context window
+# (agent/src/providers/context_windows.json; unknown models 128000, and a
+# provider's context-length error teaches the real limit mid-run).
+# Override the window only if the catalog is wrong for your model:
+# VIBE_TRADING_CONTEXT_WINDOW=272000
+# Cost ceiling on how large a run's prompt may grow before it is compacted,
+# whatever the window (real tokens):
+# VIBE_TRADING_CONTEXT_MAX_TOKENS=200000
+# TOKEN_THRESHOLD is deprecated and ignored (it counted chars/4 of the messages
+# without tool schemas); remove it from your .env.
# Hard timeout (seconds) for read-only tool execution; write tools only warn.
# Default 1800; set 0 to disable.
# VIBE_TRADING_TOOL_TIMEOUT_SECONDS=1800
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 77245a820..0aac8b47d 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -5899,7 +5899,7 @@ _PROVIDER_CHOICES: list[dict[str, str | None]] = [
"key_env": None,
"base_env": "OPENAI_CODEX_BASE_URL",
"base_url": "https://chatgpt.com/backend-api/codex/responses",
- "model": "openai-codex/gpt-5.4",
+ "model": "openai-codex/gpt-6-sol",
"key_prefix": None,
"key_placeholder": None,
},
diff --git a/agent/cli/onboard.py b/agent/cli/onboard.py
index 017dbfb40..ec23bb405 100644
--- a/agent/cli/onboard.py
+++ b/agent/cli/onboard.py
@@ -66,9 +66,9 @@ PROVIDERS: Final[tuple[Provider, ...]] = (
"https://api.anthropic.com", None,
("claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5")),
Provider("openai-codex", "OpenAI Codex", "ChatGPT OAuth for Codex",
- "openai-codex/gpt-5.4", None, "OPENAI_CODEX_BASE_URL",
+ "openai-codex/gpt-6-sol", None, "OPENAI_CODEX_BASE_URL",
"https://chatgpt.com/backend-api/codex/responses", None,
- ("openai-codex/gpt-5.4", "openai-codex/gpt-5.4-mini")),
+ ("openai-codex/gpt-6-sol", "openai-codex/gpt-6-astra", "openai-codex/gpt-6-luna")),
Provider("deepseek", "DeepSeek",
"cheapest tier — good for batch backtest research",
"deepseek-v4-pro", "DEEPSEEK_API_KEY", "DEEPSEEK_BASE_URL",
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index c328b5449..1faa05995 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -426,6 +426,7 @@ class ContextBuilder:
tool_calls: list,
content: Optional[str] = None,
reasoning_content: Optional[str] = None,
+ provider_items: Optional[list] = None,
) -> Dict[str, Any]:
"""Format an assistant tool_calls message, preserving thinking text.
@@ -436,6 +437,9 @@ class ContextBuilder:
reasoning_content: Provider-specific reasoning field (Kimi K2.5,
DeepSeek reasoner, Qwen thinking). Only attached to the output
message when not None, so non-thinking providers see no change.
+ provider_items: Opaque items the provider must receive back verbatim
+ with this turn (Codex encrypted reasoning). Attached only when
+ non-empty; only the adapter that produced them reads them.
Returns:
OpenAI-format assistant message.
@@ -468,4 +472,6 @@ class ContextBuilder:
}
if reasoning_content is not None:
message["reasoning_content"] = reasoning_content
+ if provider_items:
+ message["provider_items"] = list(provider_items)
return message
diff --git a/agent/src/agent/context_budget.py b/agent/src/agent/context_budget.py
new file mode 100644
index 000000000..16cb5de1f
--- /dev/null
+++ b/agent/src/agent/context_budget.py
@@ -0,0 +1,203 @@
+"""Size context compaction from the model's real window and real token usage.
+
+Compaction used to trigger at a fixed 40K *estimated* tokens (``chars / 4`` of
+the messages, tool schemas excluded), with layer 1 clearing every tool result
+but the last three once the estimate passed 20K. The system prompt alone
+estimates at ~12.5K, so a cross-sectional question (a dozen companies' filings)
+lost its evidence from the third iteration on, re-fetched it, got byte-identical
+results and ended in ``no_progress``. gpt-6-sol has a 272K window and
+deepseek-v4-pro 1M; the old budget used a few percent of either.
+
+The budget here is the model's window (env override > limit learned from a
+context-length error > ``context_windows.json`` > default), capped for cost,
+minus the prompt's static part (system prompt + tool schemas). Layers 1-3 fire
+at fixed fractions of what remains for the conversation.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+logger = logging.getLogger(__name__)
+
+_CATALOG_PATH = Path(__file__).resolve().parents[1] / "providers" / "context_windows.json"
+
+#: Share of the window a prompt may use; the rest is left for the reply,
+#: reasoning tokens and the error of estimating growth between calls.
+USABLE_FRACTION = 0.8
+#: Layer 1 (clear old tool results, oldest first, only back down to this line)
+#: and layer 2 (fold long text) start at these shares of the conversation
+#: budget; layer 3 (summary) at all of it. Calibrated so the largest healthy
+#: run measured on 2026-09-29 (154K real input, ~48K of it static) loses
+#: nothing: with the 200K cost cap, layer 1 starts at ~170K.
+MICRO_FRACTION = 0.8
+COLLAPSE_FRACTION = 0.9
+#: Floor for the conversation budget when the static prompt nearly fills the
+#: window, so a tiny window still compacts instead of computing a negative.
+MIN_CONVERSATION_TOKENS = 8_000
+
+_LIMIT_RE = re.compile(
+ r"(?:maximum context length|context length|context window|token limit|maximum of)"
+ r"\D{0,40}?(\d[\d,]{3,})",
+ re.IGNORECASE,
+)
+_warned_token_threshold = False
+
+
+@lru_cache(maxsize=1)
+def _catalog() -> dict[str, Any]:
+ return json.loads(_CATALOG_PATH.read_text(encoding="utf-8"))
+
+
+def estimate_tokens(value: Any) -> int:
+ """Rough token count (~4 chars/token) of any JSON-serialisable value."""
+ return len(json.dumps(value, default=str, ensure_ascii=False)) // 4
+
+
+def resolve_window(
+ provider: str,
+ model: str,
+ *,
+ env_window: Optional[int] = None,
+ learned_window: Optional[int] = None,
+) -> tuple[int, str]:
+ """Return the model's context window and where the number came from.
+
+ Args:
+ provider: Canonical provider name (``openai-codex``, ``deepseek`` ...).
+ model: Model name as configured.
+ env_window: ``VIBE_TRADING_CONTEXT_WINDOW``, when set.
+ learned_window: Limit read from a context-length error in this run.
+
+ Returns:
+ ``(window_tokens, source)``.
+ """
+ _warn_deprecated_token_threshold()
+ if env_window:
+ return int(env_window), "env:VIBE_TRADING_CONTEXT_WINDOW"
+ if learned_window:
+ return int(learned_window), "learned:context_length_error"
+ catalog = _catalog()
+ provider = (provider or "").strip().lower()
+ model = (model or "").strip()
+ for entry in catalog["models"]:
+ if entry.get("provider") and entry["provider"] != provider:
+ continue
+ if re.search(entry["pattern"], model, re.IGNORECASE):
+ return int(entry["window"]), f"catalog:{entry['pattern']}"
+ return int(catalog["default_window"]), "default"
+
+
+def _warn_deprecated_token_threshold() -> None:
+ global _warned_token_threshold
+ if _warned_token_threshold or "TOKEN_THRESHOLD" not in os.environ:
+ return
+ _warned_token_threshold = True
+ logger.warning(
+ "TOKEN_THRESHOLD is deprecated and ignored: it measured chars/4 of the "
+ "messages without tool schemas. Compaction now follows the model's real "
+ "context window; set VIBE_TRADING_CONTEXT_WINDOW to override it."
+ )
+
+
+def is_context_overflow(error_text: str) -> bool:
+ """Whether a provider error says the prompt exceeded the context window."""
+ lowered = (error_text or "").lower()
+ return any(pattern in lowered for pattern in _catalog()["overflow_error_patterns"])
+
+
+def parse_context_limit(error_text: str) -> Optional[int]:
+ """Read the context limit a provider states in its overflow error, if any."""
+ match = _LIMIT_RE.search(error_text or "")
+ if not match:
+ return None
+ value = int(match.group(1).replace(",", ""))
+ return value if value >= 1_000 else None
+
+
+@dataclass(frozen=True)
+class CompactionBudget:
+ """Real-token thresholds for the three compaction layers.
+
+ Attributes:
+ window: Model context window in tokens.
+ source: Where ``window`` came from.
+ max_tokens: Cost ceiling on the prompt size, whatever the window.
+ static_tokens: Tokens of the part compaction cannot shrink (system
+ prompt + tool schemas).
+ """
+
+ window: int
+ source: str
+ max_tokens: int
+ static_tokens: int
+
+ @property
+ def total(self) -> int:
+ """Largest prompt, in real tokens, the loop lets a run grow to."""
+ return min(int(self.window * USABLE_FRACTION), self.max_tokens)
+
+ @property
+ def conversation(self) -> int:
+ """Tokens left for the conversation after the static prompt."""
+ return max(self.total - self.static_tokens, MIN_CONVERSATION_TOKENS)
+
+ @property
+ def micro_at(self) -> int:
+ return self.static_tokens + int(self.conversation * MICRO_FRACTION)
+
+ @property
+ def collapse_at(self) -> int:
+ return self.static_tokens + int(self.conversation * COLLAPSE_FRACTION)
+
+ @property
+ def compact_at(self) -> int:
+ return self.static_tokens + self.conversation
+
+
+class ContextMeter:
+ """Current prompt size in real tokens.
+
+ The provider reports what the last request cost; messages appended or
+ compacted since then are counted by estimate. Before any usage arrives the
+ whole prompt is estimated, tool schemas included.
+ """
+
+ def __init__(self, estimator: Callable[[Any], int] = estimate_tokens) -> None:
+ self._estimate = estimator
+ self._anchor: Optional[tuple[int, int]] = None
+ self.static_tokens: Optional[int] = None
+
+ def observe(self, input_tokens: Optional[int], messages: list) -> None:
+ """Anchor on the real input size of the request just answered.
+
+ Args:
+ input_tokens: Provider-reported prompt tokens of that request.
+ messages: Exactly the messages that request sent.
+ """
+ if not isinstance(input_tokens, int) or isinstance(input_tokens, bool) or input_tokens <= 0:
+ return
+ self._anchor = (input_tokens, self._estimate(messages))
+ if self.static_tokens is None:
+ # The first request is the static prompt plus the opening turn(s).
+ self.static_tokens = max(0, input_tokens - self._estimate(messages[1:]))
+
+ def tokens(self, messages: list, tool_schema_tokens: int) -> int:
+ """Real-token size the next request would have."""
+ if self._anchor is None:
+ return self._estimate(messages) + tool_schema_tokens
+ anchor_input, anchor_estimate = self._anchor
+ return max(0, anchor_input + self._estimate(messages) - anchor_estimate)
+
+ def static(self, messages: list, tool_schema_tokens: int) -> int:
+ """Static prompt size: measured once usage arrives, else estimated."""
+ if self.static_tokens is not None:
+ return self.static_tokens
+ return self._estimate(messages[:1]) + tool_schema_tokens
diff --git a/agent/src/agent/grounding/ledger.py b/agent/src/agent/grounding/ledger.py
index d4e8a09c8..a947d1c25 100644
--- a/agent/src/agent/grounding/ledger.py
+++ b/agent/src/agent/grounding/ledger.py
@@ -253,6 +253,11 @@ class GroundingLedger(
self._record_tool_failure(tool_name, call_id, result)
if tool_name == _RESOLVER_TOOL:
self._finish_failed_resolution(arguments, call_id)
+ elif tool_name == "get_market_data" and payload is not None and payload.get("_unresolved"):
+ # A fetch where no symbol returned data is a failed call, but
+ # each symbol is still recorded as unavailable, as it was
+ # when this envelope counted as a success.
+ self._ingest_market_data(arguments, payload, call_id)
self.persist()
return
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 78fb38020..7da096491 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -33,7 +33,15 @@ from src.agent.grounding import GroundingLedger
from src.agent.grounding.release import MAX_GROUNDING_REVISIONS
from src.agent.memory import WorkspaceMemory
from src.agent.progress import HeartbeatTimer, ProgressEvent, _set_emitter
-from src.agent.tool_progress import RECOVERY_MESSAGE, ToolProgress
+from src.agent.context_budget import (
+ MIN_CONVERSATION_TOKENS,
+ CompactionBudget,
+ ContextMeter,
+ is_context_overflow,
+ parse_context_limit,
+ resolve_window,
+)
+from src.agent.tool_progress import ToolProgress
from src.agent.tools import ToolRegistry
from src.agent.trace import TraceWriter
from src.core.state import RunStateStore
@@ -88,6 +96,14 @@ MAX_CONSECUTIVE_EMPTY_RESPONSE_SKIPS = 1
MAX_READONLY_REPLAY_RECOVERIES = 6
+#: Test hook only: set it (monkeypatch) to run the three compaction layers on
+#: the pre-2026-09-29 estimated-token thresholds. A real attribute on purpose:
+#: while it was resolved lazily by the module ``__getattr__``, monkeypatch read
+#: the lazy 40000 before patching and wrote it back as a real attribute on
+#: undo, silently switching every later test in the process to the old path.
+TOKEN_THRESHOLD: Optional[int] = None
+
+
def _override(name: str):
"""Return a monkeypatched module-level override if present."""
mod = sys.modules.get(__name__)
@@ -515,11 +531,22 @@ def _replay_context_result(result: str) -> str:
return json.dumps(replay_payload, ensure_ascii=False)
-def _microcompact(messages: list) -> list:
- """Layer 1: silently prune old tool results, keeping the most recent N intact.
+def _microcompact(
+ messages: list,
+ *,
+ target_tokens: Optional[int] = None,
+ measure: Optional[Callable[[list], int]] = None,
+) -> list:
+ """Layer 1: prune old tool results, keeping the most recent N intact.
Args:
messages: Message list (mutated in place).
+ target_tokens: Stop clearing, oldest first, once ``measure(messages)``
+ is at or below this. ``None`` clears every result but the last
+ ``KEEP_RECENT`` — clearing everything a cross-sectional question
+ still needs is what made it re-fetch its evidence until
+ ``no_progress``, so the loop passes a target.
+ measure: Prompt-size function for ``target_tokens``.
Returns:
Names of tools whose every result just became unreadable (legacy
@@ -531,6 +558,8 @@ def _microcompact(messages: list) -> list:
return []
newly_cleared = []
for msg in tool_msgs[:-KEEP_RECENT]:
+ if target_tokens is not None and measure is not None and measure(messages) <= target_tokens:
+ break
content = msg.get("content", "")
# Skip a result already cleared: the marker is itself >100 chars, so
# re-clearing it would rewrite the recorded original size with the
@@ -855,6 +884,17 @@ Rules:
{focus_section}"""
+def _failure_code(result: str) -> str:
+ """The ``error_code`` (else error text) of a refused call, for the stop message."""
+ try:
+ payload = json.loads(result)
+ except (TypeError, ValueError):
+ return ""
+ if not isinstance(payload, dict):
+ return ""
+ return str(payload.get("error_code") or payload.get("reason") or payload.get("error") or "")[:120]
+
+
def _is_tool_success(result: str) -> bool:
"""Return True if the tool result does not look like an error response."""
try:
@@ -1166,6 +1206,10 @@ class AgentLoop:
self._readonly_replay_protected: set[tuple[str, str]] = set()
self._readonly_replay_recoveries = 0
self._tool_progress = ToolProgress()
+ self._context_meter = ContextMeter()
+ self._learned_context_window: int | None = None
+ self._compacted_to_tokens: int | None = None
+ self._tool_schema_tokens = 0
def cancel(self) -> None:
"""Cancel the current loop.
@@ -1287,6 +1331,13 @@ class AgentLoop:
self._readonly_replay_protected = set()
self._readonly_replay_recoveries = 0
self._tool_progress = ToolProgress()
+ self._context_meter = ContextMeter()
+ self._learned_context_window: int | None = None
+ self._compacted_to_tokens: int | None = None
+ # Sent with every request and never compacted, so they count against
+ # the window exactly like the system prompt.
+ definitions = getattr(self.registry, "get_definitions", None)
+ self._tool_schema_tokens = estimate_tokens(definitions()) if callable(definitions) else 0
run_started_wall = _time.time()
state_store = RunStateStore()
@@ -1397,28 +1448,23 @@ class AgentLoop:
notif_text = "\n".join(f"[bg:{n['task_id']}] {n['status']}: {n['result']}" for n in notifs)
messages.append({"role": "user", "content": f"<background-results>\n{notif_text}\n</background-results>\n\n<system>Continue processing with the background results above.</system>"})
- # Estimate transcript size once; each compaction layer below
- # escalates only when its own token threshold is crossed.
- tokens = estimate_tokens(messages)
-
- # Layer 1: microcompact — prune old tool results only under
- # memory pressure, so short, low-pressure runs keep their full
- # tool history available for the model to reference instead of
- # having every result past the most recent few cleared.
- if tokens > int(_token_threshold() * 0.5):
- self._microcompact_and_unblock(messages, trace, iteration)
- tokens = estimate_tokens(messages)
-
- # Layer 2: context collapse (fold long text, zero API cost)
- if tokens > int(_token_threshold() * 0.7):
- _context_collapse(messages)
+ if _override("TOKEN_THRESHOLD") is not None:
+ # Test hook: a monkeypatched module-level TOKEN_THRESHOLD
+ # keeps the old estimate-based layers so compaction tests
+ # can force each layer with a tiny number.
tokens = estimate_tokens(messages)
-
- # Layer 3: auto_compact (token threshold exceeded)
- _tok_threshold = _token_threshold()
- if tokens > _tok_threshold:
- logger.info(f"Auto compact triggered: {tokens} tokens > {_tok_threshold}")
- self._auto_compact(messages, run_dir, trace, iteration=current_iter)
+ if tokens > int(_token_threshold() * 0.5):
+ self._microcompact_and_unblock(messages, trace, iteration)
+ tokens = estimate_tokens(messages)
+ if tokens > int(_token_threshold() * 0.7):
+ _context_collapse(messages)
+ tokens = estimate_tokens(messages)
+ _tok_threshold = _token_threshold()
+ if tokens > _tok_threshold:
+ logger.info(f"Auto compact triggered: {tokens} tokens > {_tok_threshold}")
+ self._auto_compact(messages, run_dir, trace, iteration=current_iter)
+ else:
+ self._compact_to_budget(messages, run_dir, trace, iteration, current_iter)
logger.info(f"ReAct iteration {iteration}/{self.max_iterations}")
@@ -1585,14 +1631,23 @@ class AgentLoop:
# provider's Retry-After header (bounded by the configured
# cap) when present. A successful retry does not reset the
# streak — only a clean first-attempt success does.
- if not exc.retryable:
+ context_overflow = is_context_overflow(str(exc))
+ if not exc.retryable and not context_overflow:
raise
- stream_failure_streak += 1
- retry_delay_s = (
- min(exc.retry_after_s, _stream_retry_max_delay_s())
- if exc.retry_after_s is not None
- else _stream_retry_backoff_s(stream_failure_streak)
- )
+ if context_overflow:
+ # Deterministic, so no backoff: shrink to the limit the
+ # provider reported and send once more.
+ self._recover_context_overflow(
+ exc, messages, run_dir, trace, iteration, current_iter
+ )
+ retry_delay_s = 0.0
+ else:
+ stream_failure_streak += 1
+ retry_delay_s = (
+ min(exc.retry_after_s, _stream_retry_max_delay_s())
+ if exc.retry_after_s is not None
+ else _stream_retry_backoff_s(stream_failure_streak)
+ )
logger.warning(
"Provider stream failed (iter %s), retrying once in %.2fs: %s",
current_iter,
@@ -1603,7 +1658,7 @@ class AgentLoop:
"stream_reset",
{
"iter": current_iter,
- "reason": "provider_stream_retry",
+ "reason": "context_overflow" if context_overflow else "provider_stream_retry",
"provider": exc.provider,
"model": exc.model,
"retry_delay_s": retry_delay_s,
@@ -1644,6 +1699,11 @@ class AgentLoop:
self._last_activity_wall = _time.time()
usage = getattr(response, "usage_metadata", None)
+ # `messages` is still exactly what this request sent.
+ self._context_meter.observe(
+ usage.get("input_tokens") if isinstance(usage, dict) else None,
+ messages,
+ )
if getattr(response, "response_model", None):
last_response_model = response.response_model
usage_delta = _record_llm_usage(
@@ -2157,6 +2217,7 @@ class AgentLoop:
response.tool_calls,
content=response.content,
reasoning_content=response.reasoning_content or thinking_text or None,
+ provider_items=getattr(response, "provider_items", None),
)
_attach_tool_call_thought_signatures(assistant_message, response.tool_calls)
messages.append(assistant_message)
@@ -2170,8 +2231,8 @@ class AgentLoop:
not self._cancel_event.is_set()
and self._tool_progress.finish_iteration()
):
- no_progress_reason = "no_progress: " + RECOVERY_MESSAGE
- final_content = RECOVERY_MESSAGE
+ final_content = self._tool_progress.recovery_message()
+ no_progress_reason = "no_progress: " + final_content
trace.write(
{
"type": "no_progress",
@@ -2441,10 +2502,36 @@ class AgentLoop:
for tc in tool_calls:
# Layer 4: compact tool — mark then defer execution
if tc.name == "compact":
- compact_requested = True
- focus_topic = tc.arguments.get("focus_topic", "")
- messages.append(context.format_tool_result(tc.id, "compact", '{"status":"ok","message":"Compressing..."}'))
- trace.write({"type": "compact_requested", "iter": iteration})
+ self._tool_progress.note("compact", "compact")
+ self._emit(
+ "tool_call",
+ {"tool": "compact", "arguments": {}, "iter": iteration, "call_id": tc.id},
+ )
+ budget = None if _override("TOKEN_THRESHOLD") is not None else self._context_budget(messages)
+ tokens = self._prompt_tokens(messages) if budget is not None else 0
+ if budget is not None and tokens <= budget.micro_at:
+ # Summarising a prompt this small only destroys evidence the
+ # model will then fetch again: decline, and say why.
+ declined = json.dumps({
+ "status": "ok",
+ "skipped": True,
+ "message": (
+ f"Compaction not needed: the prompt is {tokens} tokens, "
+ f"under the {budget.micro_at}-token threshold. Earlier "
+ "tool results are still in context; keep using them."
+ ),
+ })
+ messages.append(context.format_tool_result(tc.id, "compact", declined))
+ trace.write({"type": "compact_declined", "iter": iteration, "prompt_tokens": tokens})
+ else:
+ compact_requested = True
+ focus_topic = tc.arguments.get("focus_topic", "")
+ messages.append(context.format_tool_result(tc.id, "compact", '{"status":"ok","message":"Compressing..."}'))
+ trace.write({"type": "compact_requested", "iter": iteration})
+ self._emit(
+ "tool_result",
+ {"tool": "compact", "status": "ok", "elapsed_ms": 0, "call_id": tc.id},
+ )
continue
tool_def = self.registry.get(tc.name)
@@ -2533,6 +2620,7 @@ class AgentLoop:
"recovery_limit": MAX_READONLY_REPLAY_RECOVERIES,
})
react_trace.append({"type": "tool_result_replayed", "tool": tc.name})
+ self._tool_progress.note("replayed", tc.name)
self._emit(
"tool_result",
{
@@ -2568,6 +2656,7 @@ class AgentLoop:
skip_msg = json.dumps({"skipped": True, "reason": reason})
messages.append(context.format_tool_result(tc.id, tc.name, skip_msg))
trace.write({"type": "tool_skipped", "iter": iteration, "tool": tc.name})
+ self._tool_progress.note("skipped", tc.name)
react_trace.append({"type": "tool_skipped", "tool": tc.name})
continue
@@ -2591,6 +2680,7 @@ class AgentLoop:
"call_id": tc.id,
})
react_trace.append({"type": "tool_result_cached", "tool": tc.name})
+ self._tool_progress.note("cached", tc.name)
self._emit(
"tool_result",
{
@@ -2676,6 +2766,7 @@ class AgentLoop:
react_trace: Compact returned trace.
iteration: Current iteration.
"""
+ self._tool_progress.note("blocked", tc.name, _failure_code(result))
args = _normalize_tool_run_dir(tc.arguments, self.memory.run_dir)
redacted_args = redact_payload(args)
event_args = {key: str(value)[:200] for key, value in redacted_args.items()}
@@ -3126,7 +3217,126 @@ class AgentLoop:
"file write is a failure."
)
- def _microcompact_and_unblock(self, messages: list, trace: TraceWriter, iteration: int) -> list[str]:
+ def _context_budget(self, messages: list) -> CompactionBudget:
+ """Compaction thresholds for the active model's real context window."""
+ cfg = get_env_config()
+ provider = (cfg.llm.langchain_provider or "").strip().lower().replace("_", "-")
+ model = getattr(self.llm, "model_name", "") or cfg.llm.langchain_model_name
+ window, source = resolve_window(
+ provider,
+ str(model or ""),
+ env_window=cfg.agent_tuning.vibe_trading_context_window,
+ learned_window=self._learned_context_window,
+ )
+ return CompactionBudget(
+ window=window,
+ source=source,
+ max_tokens=cfg.agent_tuning.vibe_trading_context_max_tokens,
+ static_tokens=self._context_meter.static(messages, self._tool_schema_tokens),
+ )
+
+ def _prompt_tokens(self, messages: list) -> int:
+ """Real-token size the next request would have."""
+ return self._context_meter.tokens(messages, self._tool_schema_tokens)
+
+ def _compact_to_budget(
+ self,
+ messages: list,
+ run_dir: Path,
+ trace: TraceWriter,
+ iteration: int,
+ current_iter: int,
+ *,
+ force: bool = False,
+ ) -> None:
+ """Run the compaction layers the prompt has actually grown into.
+
+ Args:
+ messages: Message list, mutated in place.
+ run_dir: Active run directory.
+ trace: Run trace.
+ iteration: Loop-local iteration (the microcompact event's key).
+ current_iter: Session-wide iteration number.
+ force: Summarise even under budget (the provider said it overflowed).
+ """
+ budget = self._context_budget(messages)
+ tokens = self._prompt_tokens(messages)
+ if tokens > budget.micro_at:
+ # Oldest results first and only until the prompt fits again:
+ # clearing all but the last few is what sent a 12-company
+ # comparison back to re-fetch its own evidence.
+ self._microcompact_and_unblock(
+ messages,
+ trace,
+ iteration,
+ target_tokens=budget.micro_at,
+ measure=self._prompt_tokens,
+ )
+ tokens = self._prompt_tokens(messages)
+ if tokens > budget.collapse_at:
+ _context_collapse(messages)
+ tokens = self._prompt_tokens(messages)
+ # A summary keeps the static prompt plus a ~20K-token tail, so on a
+ # window that small the prompt stays over the line after compacting;
+ # without this every later iteration paid for another summary call.
+ regrown = (
+ self._compacted_to_tokens is None
+ or tokens > self._compacted_to_tokens + MIN_CONVERSATION_TOKENS
+ )
+ if force or (tokens > budget.compact_at and regrown):
+ logger.info(
+ "Auto compact triggered: %s real tokens > %s (window %s from %s)",
+ tokens, budget.compact_at, budget.window, budget.source,
+ )
+ self._auto_compact(messages, run_dir, trace, iteration=current_iter)
+ self._compacted_to_tokens = self._prompt_tokens(messages)
+
+ def _recover_context_overflow(
+ self,
+ exc: Exception,
+ messages: list,
+ run_dir: Path,
+ trace: TraceWriter,
+ iteration: int,
+ current_iter: int,
+ ) -> None:
+ """Learn the real window from a context-length error and compact to it.
+
+ A model missing from ``context_windows.json`` runs on the default
+ window; if that is larger than the real one the provider says so, and
+ the run shrinks to the limit instead of failing.
+
+ Args:
+ exc: The provider error that reported the overflow.
+ messages: Message list, mutated in place.
+ run_dir: Active run directory.
+ trace: Run trace.
+ iteration: Loop-local iteration.
+ current_iter: Session-wide iteration number.
+ """
+ sent = self._prompt_tokens(messages)
+ stated = parse_context_limit(str(exc))
+ # The provider's own number when it gives one; otherwise the prompt
+ # that did not fit, with a margin for our estimate of it.
+ self._learned_context_window = stated or int(sent * 0.9)
+ trace.write({
+ "type": "context_overflow",
+ "iter": current_iter,
+ "prompt_tokens": sent,
+ "stated_limit": stated,
+ "learned_window": self._learned_context_window,
+ })
+ self._compact_to_budget(messages, run_dir, trace, iteration, current_iter, force=True)
+
+ def _microcompact_and_unblock(
+ self,
+ messages: list,
+ trace: TraceWriter,
+ iteration: int,
+ *,
+ target_tokens: Optional[int] = None,
+ measure: Optional[Callable[[list], int]] = None,
+ ) -> list[str]:
"""Run layer-1 microcompact and re-open lost readonly call identities.
A readable result for another argument variant, or a synthetic skip,
@@ -3140,12 +3350,14 @@ class AgentLoop:
whenever the ledger is re-opened, because this layer used to
act silently and left no evidence for diagnosis.
iteration: Current ReAct iteration, recorded on the trace event.
+ target_tokens: Clear oldest-first only until the prompt fits.
+ measure: Prompt-size function for ``target_tokens``.
Returns:
The tool names re-opened, for callers and tests to assert on.
"""
readable_before = self._readable_success_keys(messages)
- _microcompact(messages)
+ _microcompact(messages, target_tokens=target_tokens, measure=measure)
unreadable_tools = self._unblock_lost_readonly_results(messages, readable_before)
if unreadable_tools:
trace.write({
@@ -3389,7 +3601,11 @@ class AgentLoop:
# Fold every head chunk so no message falls between the summary prompt
# and the preserved tail. The first fresh chunk gets the full
# structured handoff; subsequent chunks incrementally update it.
- chunks = _summary_chunks(head)
+ # Encrypted provider items are opaque to the summariser and only
+ # cost tokens there; the messages they belong to are being folded.
+ chunks = _summary_chunks(
+ [{k: v for k, v in m.items() if k != "provider_items"} for m in head]
+ )
logger.info("Auto compact: folding %d summary chunks", len(chunks))
summary = self._previous_summary or ""
degraded_compact = False
@@ -3524,7 +3740,6 @@ class AgentLoop:
_LEGACY_LAZY = {
- "TOKEN_THRESHOLD": _token_threshold,
"MICROCOMPACT_THRESHOLD": lambda: int(_token_threshold() * 0.5),
"COLLAPSE_THRESHOLD": lambda: int(_token_threshold() * 0.7),
"HEARTBEAT_INTERVAL_S": _heartbeat_interval_s,
diff --git a/agent/src/agent/tool_progress.py b/agent/src/agent/tool_progress.py
index 4553fc1b6..db74663a2 100644
--- a/agent/src/agent/tool_progress.py
+++ b/agent/src/agent/tool_progress.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
+from collections import Counter
NO_PROGRESS_LIMIT = 8
#: Identical failures tolerated before an exact repeat is refused. Blocking
@@ -15,11 +16,40 @@ NO_PROGRESS_LIMIT = 8
#: rejected path ~35 times, so a threshold of 2 still kills it well inside
#: NO_PROGRESS_LIMIT.
FAILURE_BLOCK_THRESHOLD = 2
+#: What the user can do next, whatever stalled: #1363's case was an artifact
+#: the agent could not find, where only the exact path helps.
+_NEXT_STEP = (
+ "Retry the request, rerun the missing research step with a narrower scope "
+ "(fewer symbols, another data source), or give the exact file path if you "
+ "meant an existing artifact."
+)
RECOVERY_MESSAGE = (
- "I stopped because repeated tool attempts did not produce new information. "
- "I cannot reliably answer from the previous summary alone. Please provide "
- "the artifact path or confirm that you want to rerun the missing research step."
+ "I stopped because repeated tool attempts did not produce new information, "
+ "so I cannot reliably answer. " + _NEXT_STEP
)
+#: How each kind of unproductive tool call is described in the stop message.
+_NOTE_TEXT = {
+ "error": "failed",
+ "repeat": "returned results it had already returned",
+ "blocked": "was refused before running",
+ "skipped": "was skipped as a repeat of a call that already succeeded",
+ "cached": "was served from cache",
+ "replayed": "was restored after context compaction",
+ "compact": "was asked to compact the context",
+}
+
+
+def _failure_detail(result: str) -> str:
+ """Short reason from a failed tool envelope, for the stop message."""
+ try:
+ payload = json.loads(result)
+ except (TypeError, ValueError):
+ return str(result or "")[:120]
+ if not isinstance(payload, dict):
+ return ""
+ return str(
+ payload.get("error_code") or payload.get("error") or payload.get("message") or ""
+ )[:120]
class ToolProgress:
@@ -32,6 +62,18 @@ class ToolProgress:
self._context_restored = False
self._context_restore_grace_used = False
self.stalled_iterations = 0
+ self._notes: list[tuple[str, str, str]] = []
+ self._stall_notes: list[tuple[str, str, str]] = []
+
+ def note(self, kind: str, tool: str, detail: str = "") -> None:
+ """Record why a call in this iteration produced nothing new.
+
+ Args:
+ kind: One of the ``_NOTE_TEXT`` keys.
+ tool: Tool name.
+ detail: Error code or message, when there is one.
+ """
+ self._notes.append((kind, tool, detail))
def record(
self,
@@ -46,6 +88,7 @@ class ToolProgress:
if not success:
if key is not None:
self.failed[key] = self.failed.get(key, 0) + 1
+ self.note("error", name, _failure_detail(result))
return
if not is_readonly:
self.failed.clear()
@@ -64,6 +107,8 @@ class ToolProgress:
if observation not in self._observations:
self._observations.add(observation)
self._new_observation = True
+ else:
+ self.note("repeat", name)
def mark_context_restored(self) -> None:
"""Grant one run-scoped grace iteration after compaction restores evidence.
@@ -96,6 +141,7 @@ class ToolProgress:
"""Return whether the run exhausted its consecutive no-progress budget."""
if self._new_observation:
self.stalled_iterations = 0
+ self._stall_notes.clear()
elif self._context_restored:
# One grace iteration: preserve, but do not erase, prior stall
# history. This lets the next model turn see the restored evidence
@@ -103,6 +149,36 @@ class ToolProgress:
pass
else:
self.stalled_iterations += 1
+ self._stall_notes.extend(self._notes)
+ self._notes = []
self._new_observation = False
self._context_restored = False
return self.stalled_iterations >= NO_PROGRESS_LIMIT
+
+ def recovery_message(self) -> str:
+ """Say what the stalled iterations kept doing, not just that they stalled.
+
+ The fixed message this replaces described one scenario (an answer lost
+ to compaction) for every stop, so a user whose data source was down or
+ whose request was refused by the identity check read about "the
+ previous summary" and could not tell what to change.
+
+ Returns:
+ The stop message shown to the user.
+ """
+ if not self._stall_notes:
+ return RECOVERY_MESSAGE
+ counts = Counter(self._stall_notes)
+ parts = []
+ for (kind, tool, detail), count in counts.most_common(5):
+ text = f"{tool} {_NOTE_TEXT.get(kind, kind)}"
+ if detail:
+ text += f" ({detail})"
+ parts.append(f"{text} x{count}")
+ return (
+ f"I stopped because {self.stalled_iterations} tool rounds in a row "
+ "produced no new information: "
+ + "; ".join(parts)
+ + ". I cannot reliably answer from this. "
+ + _NEXT_STEP
+ )
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index 932fbf454..efb001e8b 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -424,7 +424,19 @@ class AgentTuningConfig(_EnvBase):
``src/tools/web_search_tool.py``, ``api_server.py``.
"""
+ # Deprecated: counted chars/4 of messages without tool schemas, so no value
+ # tuned against it means anything under real-token accounting. Read only to
+ # warn (src/agent/context_budget.py); compaction ignores it.
token_threshold: int = Field(alias="TOKEN_THRESHOLD", default=40000)
+ vibe_trading_context_window: int | None = Field(
+ alias="VIBE_TRADING_CONTEXT_WINDOW", default=None, gt=0,
+ )
+ # Cost ceiling on the prompt the loop lets a run grow to before compacting,
+ # whatever the model's window. The largest healthy research run measured
+ # on 2026-09-29 sent 154K real input tokens.
+ vibe_trading_context_max_tokens: int = Field(
+ alias="VIBE_TRADING_CONTEXT_MAX_TOKENS", default=200_000, gt=0,
+ )
vt_heartbeat_interval_s: float = Field(alias="VT_HEARTBEAT_INTERVAL_S", default=3.0)
vt_reasoning_delta_min_interval_s: float = Field(
alias="VT_REASONING_DELTA_MIN_INTERVAL_S", default=1.0,
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index 0e79d2d6e..a60c21eae 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -491,5 +491,27 @@ def fetch_market_data(
def fetch_market_data_json(**kwargs: Any) -> str:
- """Fetch market data and return strict JSON."""
- return json.dumps(fetch_market_data(**kwargs), ensure_ascii=False, indent=2, allow_nan=False)
+ """Fetch market data and return strict JSON.
+
+ When no requested symbol returned data the envelope says so with
+ ``status: error``: a bare ``{"_unresolved": [...]}`` classified as a
+ successful call, so the agent loop neither refused an identical retry nor
+ told the model to change the request. ``_unresolved`` and ``_provenance``
+ stay, so grounding still records each symbol as unavailable. The dict API
+ (``fetch_market_data``) is unchanged for in-process callers.
+ """
+ payload = fetch_market_data(**kwargs)
+ unresolved = payload.get("_unresolved") or []
+ if unresolved and not any(not str(key).startswith("_") for key in payload):
+ payload = {
+ "status": "error",
+ "error_code": "no_market_data",
+ "error": (
+ f"No data returned for any requested symbol: {', '.join(map(str, unresolved))} "
+ f"({kwargs.get('start_date')}..{kwargs.get('end_date')}, "
+ f"source={kwargs.get('source', 'auto')}). Check the symbol suffix and the date "
+ "range or try another source; the identical request returns the same result."
+ ),
+ **payload,
+ }
+ return json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False)
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.py
index b0942d769..243ef7fc2 100644
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@ -128,6 +128,9 @@ class LLMResponse:
response_model: Model identifier reported by the provider response,
when available. This is authoritative runtime metadata and must
not be inferred from the model's natural-language self-report.
+ provider_items: Opaque output items the provider needs back verbatim
+ on the next request of the same turn chain (the Codex backend's
+ encrypted reasoning items). Never shown, never summarised.
"""
content: Optional[str] = None
@@ -137,6 +140,7 @@ class LLMResponse:
usage_metadata: Optional[Dict[str, int]] = None
content_filter_triggered: bool = False
response_model: Optional[str] = None
+ provider_items: List[Dict[str, Any]] = field(default_factory=list)
@property
def has_tool_calls(self) -> bool:
@@ -682,6 +686,7 @@ class ChatLLM:
usage_metadata=usage,
content_filter_triggered=content_filter_triggered,
response_model=response_model,
+ provider_items=list(additional_kwargs.get("provider_items") or []),
)
diff --git a/agent/src/providers/context_windows.json b/agent/src/providers/context_windows.json
new file mode 100644
index 000000000..ef1e2e9c3
--- /dev/null
+++ b/agent/src/providers/context_windows.json
@@ -0,0 +1,28 @@
+{
+ "_comment": "Model context windows used to size context compaction. Every entry names its source; add a model only with one. Unknown models use default_window, and a provider's own context-length error teaches the loop the real limit at runtime. VIBE_TRADING_CONTEXT_WINDOW overrides everything.",
+ "default_window": 128000,
+ "models": [
+ {
+ "provider": "openai-codex",
+ "pattern": "^(openai[-_]codex/)?(gpt-6-(astra|sol|luna)|gpt-5\\.6-(sol|terra|luna)|gpt-5\\.5)$",
+ "window": 272000,
+ "source": "Codex backend model metadata: context_window=272000 for every listed model (Codex CLI models cache fetched 2026-09-29T03:26Z)"
+ },
+ {
+ "pattern": "^(deepseek/)?deepseek-(v4-pro|flash)$",
+ "window": 1000000,
+ "source": "https://api-docs.deepseek.com/quick_start/pricing — deepseek-v4-pro and deepseek-flash: context length 1M (read 2026-09-29)"
+ }
+ ],
+ "overflow_error_patterns": [
+ "context_length_exceeded",
+ "maximum context length",
+ "context window",
+ "prompt is too long",
+ "input is too long",
+ "too many tokens",
+ "exceeds the context",
+ "exceeded model token limit",
+ "reduce the length of the messages"
+ ]
+}
diff --git a/agent/src/providers/llm_providers.json b/agent/src/providers/llm_providers.json
index ed8bc4d5a..f73a5d7a7 100644
--- a/agent/src/providers/llm_providers.json
+++ b/agent/src/providers/llm_providers.json
@@ -31,7 +31,7 @@
"label": "OpenAI Codex (ChatGPT OAuth)",
"api_key_env": null,
"base_url_env": "OPENAI_CODEX_BASE_URL",
- "default_model": "openai-codex/gpt-5.4",
+ "default_model": "openai-codex/gpt-6-sol",
"default_base_url": "https://chatgpt.com/backend-api/codex/responses",
"api_key_required": false,
"auth_type": "oauth",
diff --git a/agent/src/providers/openai_codex.py b/agent/src/providers/openai_codex.py
index 7903290e4..aef1e60c9 100644
--- a/agent/src/providers/openai_codex.py
+++ b/agent/src/providers/openai_codex.py
@@ -13,6 +13,7 @@ import base64
import hashlib
import json
import os
+import re
import threading
import time
from contextlib import contextmanager
@@ -23,6 +24,7 @@ from urllib.parse import urlparse
from src.config.accessor import get_env_config
from src.config.paths import get_runtime_root
+from src.providers.session_context import current_llm_session_id
try: # pragma: no cover - platform-specific imports are exercised via mocks.
import fcntl
@@ -235,10 +237,17 @@ class CodexAIMessage:
reasoning = self.additional_kwargs.get("reasoning_content", "") + other.additional_kwargs.get(
"reasoning_content", ""
)
+ additional_kwargs: dict[str, Any] = {"reasoning_content": reasoning} if reasoning else {}
+ provider_items = [
+ *self.additional_kwargs.get("provider_items", []),
+ *other.additional_kwargs.get("provider_items", []),
+ ]
+ if provider_items:
+ additional_kwargs["provider_items"] = provider_items
return CodexAIMessage(
content=(self.content or "") + (other.content or ""),
tool_calls=[*self.tool_calls, *other.tool_calls],
- additional_kwargs={"reasoning_content": reasoning} if reasoning else {},
+ additional_kwargs=additional_kwargs,
response_metadata=response_metadata,
usage_metadata=other.usage_metadata or self.usage_metadata,
)
@@ -414,9 +423,16 @@ def _strip_model_prefix(model: str) -> str:
return model
-def _prompt_cache_key(messages: list[dict[str, Any]]) -> str:
- raw = json.dumps(messages, ensure_ascii=True, sort_keys=True)
- return hashlib.sha256(raw.encode("utf-8")).hexdigest()
+def _prompt_cache_key(instructions: str) -> str:
+ """Cache-routing key shared by every request of one conversation.
+
+ The key hashed the whole message list, so it changed on every request and
+ never routed two turns of a run to the same cache. Codex CLI keys on its
+ conversation id; the bound LLM session id is ours, and the system prompt
+ stands in when no session is bound.
+ """
+ basis = current_llm_session_id() or instructions
+ return hashlib.sha256(basis.encode("utf-8")).hexdigest()
def _convert_user_message(content: Any) -> dict[str, Any]:
@@ -447,17 +463,56 @@ def _split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:
return "call_0", None
-def _convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:
+def _convert_messages(
+ messages: list[dict[str, Any]],
+ *,
+ replay_reasoning: bool = True,
+) -> tuple[str, list[dict[str, Any]]]:
+ """Convert loop messages into Responses ``instructions`` + ``input`` items.
+
+ Args:
+ messages: OpenAI-format loop messages.
+ replay_reasoning: Send each turn's encrypted reasoning items back, as
+ Codex CLI does. With ``store: false`` the backend keeps nothing
+ between requests, so without them a reasoning model starts every
+ turn blind to why it made the calls it is now reading results of.
+
+ Returns:
+ ``(instructions, input_items)``.
+ """
system_prompt = ""
+ instructions_taken = False
input_items: list[dict[str, Any]] = []
for idx, msg in enumerate(messages):
role = msg.get("role")
content = msg.get("content")
if role == "system":
- system_prompt = content if isinstance(content, str) else ""
+ text = content if isinstance(content, str) else ""
+ if not instructions_taken:
+ system_prompt = text
+ instructions_taken = True
+ elif text:
+ # A system message appended mid-run (the empty-response retry,
+ # the tool-markup retry, the pending-write directive) used to
+ # overwrite `instructions`, so every later request ran without
+ # the 49K-character system prompt. Codex CLI sends added
+ # instructions as developer messages.
+ input_items.append(
+ {
+ "type": "message",
+ "role": "developer",
+ "content": [{"type": "input_text", "text": text}],
+ }
+ )
elif role == "user":
input_items.append(_convert_user_message(content))
elif role == "assistant":
+ if replay_reasoning:
+ input_items.extend(
+ dict(item)
+ for item in msg.get("provider_items") or []
+ if isinstance(item, dict) and item.get("type") == "reasoning"
+ )
if isinstance(content, str) and content:
input_items.append(
{
@@ -471,15 +526,17 @@ def _convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[st
for tool_call in msg.get("tool_calls", []) or []:
fn = tool_call.get("function") or {}
call_id, item_id = _split_tool_call_id(tool_call.get("id"))
- input_items.append(
- {
- "type": "function_call",
- "id": item_id or f"fc_{idx}",
- "call_id": call_id or f"call_{idx}",
- "name": fn.get("name"),
- "arguments": fn.get("arguments") or "{}",
- }
- )
+ function_call = {
+ "type": "function_call",
+ "call_id": call_id or f"call_{idx}",
+ "name": fn.get("name"),
+ "arguments": fn.get("arguments") or "{}",
+ }
+ # Only an id the backend issued; a made-up one gave every call
+ # of a parallel batch the same "fc_0".
+ if item_id:
+ function_call["id"] = item_id
+ input_items.append(function_call)
elif role == "tool":
call_id, _ = _split_tool_call_id(msg.get("tool_call_id"))
output = content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
@@ -558,6 +615,15 @@ def _events_from_lines(lines: Iterable[str]) -> Iterable[dict[str, Any]]:
yield event
+#: Models whose backend refused a replayed reasoning item (process lifetime).
+_REASONING_REPLAY_REJECTED: set[str] = set()
+_REASONING_REJECTION_RE = re.compile(r"reasoning|encrypted_content|rs_[A-Za-z0-9]", re.IGNORECASE)
+
+
+def _has_reasoning_items(body: dict[str, Any]) -> bool:
+ return any(item.get("type") == "reasoning" for item in body.get("input") or [])
+
+
def _message_chunks_from_events(events: Iterable[dict[str, Any]]) -> Iterable[CodexAIMessage]:
tool_buffers: dict[str, dict[str, Any]] = {}
for event in events:
@@ -566,7 +632,7 @@ def _message_chunks_from_events(events: Iterable[dict[str, Any]]) -> Iterable[Co
item = event.get("item") or {}
if item.get("type") == "function_call" and item.get("call_id"):
tool_buffers[item["call_id"]] = {
- "id": item.get("id") or "fc_0",
+ "id": item.get("id"),
"name": item.get("name") or "",
"arguments": item.get("arguments") or "",
}
@@ -584,12 +650,23 @@ def _message_chunks_from_events(events: Iterable[dict[str, Any]]) -> Iterable[Co
tool_buffers[call_id]["arguments"] = event.get("arguments") or ""
elif event_type == "response.output_item.done":
item = event.get("item") or {}
- if item.get("type") == "function_call" and item.get("call_id"):
+ if item.get("type") == "reasoning" and item.get("encrypted_content"):
+ # Kept verbatim (minus plaintext content) for the next request.
+ kept = {
+ "type": "reasoning",
+ "summary": item.get("summary") or [],
+ "encrypted_content": item["encrypted_content"],
+ }
+ if item.get("id"):
+ kept["id"] = item["id"]
+ yield CodexAIMessage(additional_kwargs={"provider_items": [kept]})
+ elif item.get("type") == "function_call" and item.get("call_id"):
call_id = item["call_id"]
buf = tool_buffers.get(call_id) or {}
args_raw = buf.get("arguments") or item.get("arguments") or "{}"
+ item_id = buf.get("id") or item.get("id")
tool = CodexToolCall(
- id=f"{call_id}|{buf.get('id') or item.get('id') or 'fc_0'}",
+ id=f"{call_id}|{item_id}" if item_id else call_id,
name=buf.get("name") or item.get("name") or "",
arguments=_decode_tool_args(args_raw),
)
@@ -651,8 +728,16 @@ class OpenAICodexLLM:
codex_url=self.codex_url,
)
- def _body(self, messages: list[dict[str, Any]], *, stream: bool) -> dict[str, Any]:
- system_prompt, input_items = _convert_messages(messages)
+ def _body(
+ self,
+ messages: list[dict[str, Any]],
+ *,
+ stream: bool,
+ replay_reasoning: bool = True,
+ ) -> dict[str, Any]:
+ system_prompt, input_items = _convert_messages(
+ messages, replay_reasoning=replay_reasoning
+ )
body: dict[str, Any] = {
"model": _strip_model_prefix(self.model),
"store": False,
@@ -661,7 +746,7 @@ class OpenAICodexLLM:
"input": input_items,
"text": {"verbosity": "medium"},
"include": ["reasoning.encrypted_content"],
- "prompt_cache_key": _prompt_cache_key(messages),
+ "prompt_cache_key": _prompt_cache_key(system_prompt),
"tool_choice": "auto",
"parallel_tool_calls": True,
}
@@ -688,10 +773,12 @@ class OpenAICodexLLM:
self, messages: list[dict[str, Any]], config: Optional[dict[str, Any]] = None
) -> Iterable[CodexAIMessage]:
timeout = (config or {}).get("timeout") or self.timeout
- body = self._body(messages, stream=True)
+ replay = _strip_model_prefix(self.model) not in _REASONING_REPLAY_REJECTED
+ body = self._body(messages, stream=True, replay_reasoning=replay)
headers = self._headers()
+ refreshed = False
with httpx.Client(timeout=timeout, follow_redirects=True, trust_env=True) as client:
- for attempt in range(2):
+ while True:
with client.stream(
"POST",
self.codex_url,
@@ -704,7 +791,8 @@ class OpenAICodexLLM:
raw = response.read().decode("utf-8", "ignore")
status_code = response.status_code
- if status_code == 401 and attempt == 0:
+ if status_code == 401 and not refreshed:
+ refreshed = True
authorization = headers.get("Authorization", "")
rejected_access = authorization[7:] if authorization.startswith("Bearer ") else None
headers = self._headers(
@@ -713,6 +801,20 @@ class OpenAICodexLLM:
)
continue
+ if (
+ status_code == 400
+ and replay
+ and _has_reasoning_items(body)
+ and _REASONING_REJECTION_RE.search(raw)
+ ):
+ # Replay mirrors Codex CLI but was not verified live against
+ # every model: if the backend refuses a replayed reasoning
+ # item, stop sending them for this model and resend once.
+ _REASONING_REPLAY_REJECTED.add(_strip_model_prefix(self.model))
+ replay = False
+ body = self._body(messages, stream=True, replay_reasoning=False)
+ continue
+
# Preserve the typed status so deterministic 4xx failures are
# not retried again by the provider-level retry wrapper.
raise CodexStreamError(status_code, raw)
diff --git a/agent/src/session/service.py b/agent/src/session/service.py
index e80bc0fc1..30461bda9 100644
--- a/agent/src/session/service.py
+++ b/agent/src/session/service.py
@@ -404,11 +404,11 @@ class SessionService:
content=self._format_result_message(attempt),
linked_attempt_id=attempt.attempt_id,
metadata=reply_metadata,
- tool_trail=(
- result.get("tool_trail", [])
- if attempt.status == AttemptStatus.COMPLETED
- else []
- ),
+ # Every terminal attempt keeps its steps. A failed run saved an
+ # empty trail, so after a reload the history said "0 steps"
+ # for a run that made eight rounds of tool calls — hiding the
+ # one thing a failure report needs.
+ tool_trail=result.get("tool_trail", []),
)
self.store.append_message(reply)
# The append-only transcript is the user-visible source of truth.
diff --git a/agent/tests/test_cli_init.py b/agent/tests/test_cli_init.py
index 95de0ee4c..95f7bbdbc 100644
--- a/agent/tests/test_cli_init.py
+++ b/agent/tests/test_cli_init.py
@@ -129,7 +129,7 @@ class TestCliInit:
"ask",
side_effect=[
"https://chatgpt.com/backend-api/codex/responses",
- "openai-codex/gpt-5.4",
+ "openai-codex/gpt-6-sol",
"",
],
):
@@ -139,5 +139,5 @@ class TestCliInit:
content = env_path.read_text(encoding="utf-8")
assert "LANGCHAIN_PROVIDER=openai-codex" in content
assert "OPENAI_CODEX_BASE_URL=https://chatgpt.com/backend-api/codex/responses" in content
- assert "LANGCHAIN_MODEL_NAME=openai-codex/gpt-5.4" in content
+ assert "LANGCHAIN_MODEL_NAME=openai-codex/gpt-6-sol" in content
assert "OPENAI_API_KEY=" not in content
diff --git a/agent/tests/test_context_budget.py b/agent/tests/test_context_budget.py
new file mode 100644
index 000000000..297fc4e4a
--- /dev/null
+++ b/agent/tests/test_context_budget.py
@@ -0,0 +1,372 @@
+"""Compaction follows the model's real window, not a fixed estimated 40K.
+
+Reproduced on 2026-09-29 (v0.1.15 + deepseek-v4-pro, "A股和港股通的游戏公司,
+找出最值得投资的三家"): layer 1 fired from iteration 3 because the system prompt
+alone estimates at ~12.5K of the 20K trigger, kept only the last three tool
+results, and the run re-fetched the same seven filings 4-5 times each until
+``no_progress`` at iteration 16. Same code with the threshold raised: re-fetches
+54 -> 0 over 8 runs. These tests pin both sides: a healthy run of that size
+loses nothing, and a small window still compacts before it overflows.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+import src.agent.context_budget as cb
+from src.agent.context_budget import (
+ CompactionBudget,
+ ContextMeter,
+ estimate_tokens,
+ is_context_overflow,
+ parse_context_limit,
+ resolve_window,
+)
+from src.agent.loop import AgentLoop
+from src.agent.tools import BaseTool, ToolRegistry
+from src.agent.trace import TraceWriter
+from src.config.accessor import reset_env_config
+from src.providers.chat import ProviderStreamError
+
+#: Real input tokens of the first request of a research run on 2026-09-29
+#: (deepseek-v4-pro llm_usage.json: 47,661) — system prompt plus 107 tool schemas.
+STATIC_TOKENS = 48_000
+#: The largest healthy run measured that day sent 154K real input tokens.
+LARGEST_HEALTHY_PROMPT = 154_000
+
+
+# --------------------------------------------------------------------------
+# Window resolution
+# --------------------------------------------------------------------------
+
+
+def test_window_comes_from_the_catalog_for_the_reported_models() -> None:
+ assert resolve_window("openai-codex", "openai-codex/gpt-6-sol")[0] == 272_000
+ assert resolve_window("openai-codex", "gpt-6-sol")[0] == 272_000
+ assert resolve_window("deepseek", "deepseek-v4-pro")[0] == 1_000_000
+ assert resolve_window("openrouter", "deepseek/deepseek-v4-pro")[0] == 1_000_000
+
+
+def test_provider_scoped_entries_do_not_leak_to_other_providers() -> None:
+ # The 272K is what the Codex backend publishes; another provider serving a
+ # model of the same name is not covered by that source.
+ assert resolve_window("openai", "gpt-6-sol") == (128_000, "default")
+
+
+def test_resolution_order_env_then_learned_then_catalog() -> None:
+ assert resolve_window("deepseek", "deepseek-v4-pro", env_window=64_000, learned_window=32_000) == (
+ 64_000, "env:VIBE_TRADING_CONTEXT_WINDOW")
+ assert resolve_window("deepseek", "deepseek-v4-pro", learned_window=32_000) == (
+ 32_000, "learned:context_length_error")
+ assert resolve_window("someone", "unknown-model") == (128_000, "default")
+
+
+def test_every_catalog_entry_names_its_source() -> None:
+ catalog = json.loads((Path(cb.__file__).resolve().parents[1] / "providers" / "context_windows.json").read_text())
+ for entry in catalog["models"]:
+ assert entry["source"].strip(), entry
+ assert entry["window"] >= 1_000
+ re.compile(entry["pattern"])
+
+
+def test_deprecated_token_threshold_is_ignored_with_a_warning(monkeypatch, caplog) -> None:
+ monkeypatch.setenv("TOKEN_THRESHOLD", "40000")
+ monkeypatch.setattr(cb, "_warned_token_threshold", False)
+ with caplog.at_level(logging.WARNING, logger=cb.logger.name):
+ window = resolve_window("deepseek", "deepseek-v4-pro")
+ resolve_window("deepseek", "deepseek-v4-pro")
+ assert window[0] == 1_000_000
+ assert sum("TOKEN_THRESHOLD is deprecated" in r.message for r in caplog.records) == 1
+
+
+# --------------------------------------------------------------------------
+# Thresholds: both sides
+# --------------------------------------------------------------------------
+
+
[email protected]("provider,model", [
+ ("openai-codex", "openai-codex/gpt-6-sol"),
+ ("deepseek", "deepseek-v4-pro"),
+])
+def test_a_healthy_run_of_the_largest_measured_size_is_never_compacted(provider, model) -> None:
+ window, source = resolve_window(provider, model)
+ budget = CompactionBudget(window=window, source=source, max_tokens=200_000, static_tokens=STATIC_TOKENS)
+ assert budget.micro_at > LARGEST_HEALTHY_PROMPT
+ assert budget.compact_at > LARGEST_HEALTHY_PROMPT
+
+
[email protected]("window", [128_000, 200_000, 272_000, 1_000_000])
+def test_every_layer_fires_before_the_window_is_full(window) -> None:
+ budget = CompactionBudget(window=window, source="t", max_tokens=200_000, static_tokens=STATIC_TOKENS)
+ assert budget.micro_at < budget.collapse_at < budget.compact_at <= window * cb.USABLE_FRACTION
+
+
+def test_cost_cap_bounds_a_huge_window() -> None:
+ budget = CompactionBudget(window=1_000_000, source="t", max_tokens=200_000, static_tokens=STATIC_TOKENS)
+ assert budget.compact_at == 200_000
+
+
+def test_a_window_smaller_than_the_static_prompt_still_has_a_floor() -> None:
+ budget = CompactionBudget(window=32_000, source="t", max_tokens=200_000, static_tokens=STATIC_TOKENS)
+ assert budget.conversation == cb.MIN_CONVERSATION_TOKENS
+
+
+# --------------------------------------------------------------------------
+# Measuring the prompt
+# --------------------------------------------------------------------------
+
+
+def test_meter_anchors_on_reported_tokens_and_tracks_growth_and_shrinkage() -> None:
+ messages = [{"role": "system", "content": "s" * 400}, {"role": "user", "content": "u" * 400}]
+ meter = ContextMeter()
+ assert meter.tokens(messages, 1_000) == estimate_tokens(messages) + 1_000
+ meter.observe(50_000, messages)
+ assert meter.static_tokens == 50_000 - estimate_tokens(messages[1:])
+ grown = messages + [{"role": "tool", "content": "x" * 4_000}]
+ assert meter.tokens(grown, 1_000) == 50_000 + estimate_tokens(grown) - estimate_tokens(messages)
+ assert meter.tokens(messages[:1], 1_000) < 50_000
+
+
+def test_meter_ignores_missing_or_bogus_usage() -> None:
+ meter = ContextMeter()
+ for value in (None, 0, -5, True, "900"):
+ meter.observe(value, [{"role": "system", "content": "s"}])
+ assert meter.static_tokens is None
+
+
+def test_overflow_errors_are_recognised_and_their_limit_read() -> None:
+ deepseek = ("Error code: 400 - This model's maximum context length is 131072 tokens. "
+ "However, you requested 140000 tokens.")
+ assert is_context_overflow(deepseek)
+ assert parse_context_limit(deepseek) == 131_072
+ assert is_context_overflow('{"error": {"code": "context_length_exceeded"}}')
+ assert is_context_overflow("prompt is too long: 210000 tokens > 200000 maximum")
+ assert not is_context_overflow("The usage limit has been reached")
+ assert not is_context_overflow("Insufficient Balance")
+
+
+# --------------------------------------------------------------------------
+# The loop, end to end with an offline model
+# --------------------------------------------------------------------------
+
+
+class FilingTool(BaseTool):
+ """Readonly stand-in for get_financial_statements (~6K tokens per filing)."""
+
+ name = "fetch_filing"
+ description = "Fetch one company's annual indicators (offline test double)."
+ parameters = {"type": "object", "properties": {"filing": {"type": "string"}}, "required": ["filing"]}
+ is_readonly = True
+
+ def __init__(self, payload_chars: int) -> None:
+ self.payload_chars = payload_chars
+ self.calls: list[str] = []
+
+ def execute(self, **kwargs: object) -> str:
+ self.calls.append(str(kwargs["filing"]))
+ return json.dumps({"ok": True, "filing": kwargs["filing"], "rows": "7" * self.payload_chars})
+
+
+class ComparisonLLM:
+ """Fetches each filing once, then answers; reports realistic usage.
+
+ It keeps its own progress, the way a model carries on from a compaction
+ summary. A model that re-fetches whatever it can no longer see is the
+ failure under test; faking that here would test the fake.
+ """
+
+ def __init__(self, model: str, codes: list[str], *, overflow_above: int | None = None) -> None:
+ self.model_name = model
+ self.reasoning = "r" * REASONING_CHARS
+ self.codes = codes
+ self.overflow_above = overflow_above
+ self.sent_tokens: list[int] = []
+ self.overflows = 0
+ self.fetched = 0
+
+ def _input_tokens(self, messages: list[dict]) -> int:
+ return STATIC_TOKENS + estimate_tokens(messages[1:])
+
+ def stream_chat(self, messages: list[dict], **kwargs: object) -> SimpleNamespace:
+ tokens = self._input_tokens(messages)
+ if self.overflow_above is not None and tokens > self.overflow_above:
+ self.overflows += 1
+ original = RuntimeError(
+ f"Error code: 400 - This model's maximum context length is {self.overflow_above} "
+ f"tokens. However, you requested {tokens} tokens."
+ )
+ original.status_code = 400
+ raise ProviderStreamError(provider="deepseek", model=self.model_name, original=original)
+ self.sent_tokens.append(tokens)
+ usage = {"input_tokens": tokens, "output_tokens": 20, "total_tokens": tokens + 20}
+ if self.fetched < len(self.codes):
+ code = self.codes[self.fetched]
+ call = SimpleNamespace(id=f"call-{self.fetched}", name="fetch_filing", arguments={"filing": code})
+ self.fetched += 1
+ return SimpleNamespace(content="", reasoning_content=self.reasoning, has_tool_calls=True,
+ tool_calls=[call], usage_metadata=usage, provider_items=[])
+ return SimpleNamespace(content="The comparison is complete.", reasoning_content=None,
+ has_tool_calls=False, tool_calls=[], usage_metadata=usage, provider_items=[])
+
+ def chat(self, messages: list[dict], **kwargs: object) -> SimpleNamespace:
+ return SimpleNamespace(content="## Summary\nFetched filings for the comparison.")
+
+
+#: Filing ids, not tickers: a symbol-shaped argument sends the call through the
+#: grounding identity gate, which is not what these tests exercise.
+CODES = [f"filing-{i:02d}" for i in range(1, 21)]
+#: Tool results reach the model cut to 10,000 chars (config/limits.py), so what
+#: made real runs grow was the reasoning text replayed each turn as well. With
+#: both, 20 filings reach ~158K real tokens: past the 154K healthy maximum.
+REASONING_CHARS = 12_000
+
+
+def _run(tmp_path: Path, monkeypatch, *, provider: str, model: str, payload_chars: int = 24_000,
+ env_window: int | None = None, overflow_above: int | None = None):
+ monkeypatch.setenv("LANGCHAIN_PROVIDER", provider)
+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", model)
+ if env_window:
+ monkeypatch.setenv("VIBE_TRADING_CONTEXT_WINDOW", str(env_window))
+ reset_env_config()
+ tool = FilingTool(payload_chars)
+ registry = ToolRegistry()
+ registry.register(tool)
+ llm = ComparisonLLM(model, CODES, overflow_above=overflow_above)
+ loop = AgentLoop(registry=registry, llm=llm, max_iterations=30)
+ run_dir = tmp_path / "run"
+ run_dir.mkdir()
+ loop.memory.run_dir = str(run_dir)
+ result = loop.run("Compare these twelve game companies' annual indicators.")
+ return result, tool, llm, loop, TraceWriter.read(run_dir)
+
+
+def _cleared_codes(loop_messages_trace: list[dict]) -> list[str]:
+ return [code for event in loop_messages_trace if event.get("type") == "microcompact_cleared"
+ for code in event.get("tools", [])]
+
+
[email protected]("provider,model", [
+ ("openai-codex", "openai-codex/gpt-6-sol"),
+ ("deepseek", "deepseek-v4-pro"),
+])
+def test_twelve_company_comparison_keeps_every_filing(tmp_path, monkeypatch, provider, model) -> None:
+ # A .env still carrying the deprecated setting (the maintainer's did) must
+ # not bring the old threshold back.
+ monkeypatch.setenv("TOKEN_THRESHOLD", "40000")
+ result, tool, llm, _, trace = _run(tmp_path, monkeypatch, provider=provider, model=model)
+
+ assert result["status"] == "success", result.get("reason")
+ assert max(llm.sent_tokens) >= LARGEST_HEALTHY_PROMPT # as large as the real one
+ assert tool.calls == CODES # each filing fetched exactly once
+ assert not [e for e in trace if e.get("type") in ("microcompact_cleared", "compact")]
+
+
+def test_the_old_fixed_threshold_evicts_the_same_run(tmp_path, monkeypatch) -> None:
+ """Mutation side: the pre-fix 40K estimate clears filings mid-comparison."""
+ import src.agent.loop as loop_mod
+
+ monkeypatch.setattr(loop_mod, "TOKEN_THRESHOLD", 40_000, raising=False)
+ _, _, _, _, trace = _run(tmp_path, monkeypatch, provider="openai-codex", model="openai-codex/gpt-6-sol")
+ assert [e for e in trace if e.get("type") == "microcompact_cleared"]
+
+
+def test_a_small_window_compacts_before_it_overflows(tmp_path, monkeypatch) -> None:
+ result, tool, llm, _, trace = _run(
+ tmp_path, monkeypatch, provider="someone", model="small-model", env_window=100_000
+ )
+ assert result["status"] == "success", result.get("reason")
+ assert max(llm.sent_tokens) <= 100_000 * cb.USABLE_FRACTION + 6_500 # one filing of growth
+ cleared = [e for e in trace if e.get("type") in ("microcompact_cleared", "compact")]
+ assert cleared
+
+
+def test_a_context_length_error_teaches_the_window_and_the_run_recovers(tmp_path, monkeypatch) -> None:
+ """Unknown model on the 128K default whose real window is 90K."""
+ result, tool, llm, loop, trace = _run(
+ tmp_path, monkeypatch, provider="someone", model="unknown-model", overflow_above=90_000
+ )
+ overflow = [e for e in trace if e.get("type") == "context_overflow"]
+
+ assert result["status"] == "success", result.get("reason")
+ assert overflow and overflow[0]["stated_limit"] == 90_000
+ assert loop._learned_context_window == 90_000
+ assert llm.overflows == 1 # recovered once, never overflowed again
+ assert max(llm.sent_tokens) <= 90_000
+ # A summary keeps static prompt + ~20K tail, so on a 90K window the prompt
+ # stays near the line after compacting; each further summary must wait
+ # for 8K of regrowth instead of firing every iteration (13 before).
+ assert len([e for e in trace if e.get("type") == "compact"]) <= 8
+
+
+class CompactingLLM(ComparisonLLM):
+ """Asks for `compact` after two filings, as gpt/deepseek sometimes do."""
+
+ def stream_chat(self, messages: list[dict], **kwargs: object) -> SimpleNamespace:
+ if self.fetched >= 2 and not getattr(self, "asked", False):
+ self.asked = True
+ tokens = self._input_tokens(messages)
+ self.sent_tokens.append(tokens)
+ call = SimpleNamespace(id="call-compact", name="compact", arguments={"focus_topic": "games"})
+ return SimpleNamespace(content="", reasoning_content=None, has_tool_calls=True, tool_calls=[call],
+ usage_metadata={"input_tokens": tokens, "output_tokens": 5, "total_tokens": tokens},
+ provider_items=[])
+ return super().stream_chat(messages, **kwargs)
+
+
+def test_a_model_asking_to_compact_a_small_prompt_is_declined(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "openai-codex")
+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "openai-codex/gpt-6-sol")
+ reset_env_config()
+ tool = FilingTool(4_000)
+ registry = ToolRegistry()
+ registry.register(tool)
+ events: list[tuple[str, dict]] = []
+ loop = AgentLoop(registry=registry, llm=CompactingLLM("openai-codex/gpt-6-sol", CODES[:4]),
+ max_iterations=30, event_callback=lambda n, d: events.append((n, d)))
+ run_dir = tmp_path / "run"
+ run_dir.mkdir()
+ loop.memory.run_dir = str(run_dir)
+ loop.run("Compare four companies.")
+ trace = TraceWriter.read(run_dir)
+
+ assert [e for e in trace if e.get("type") == "compact_declined"]
+ assert not [e for e in trace if e.get("type") in ("compact", "compact_requested")]
+ # The step is visible: a compact call used to emit no tool_call event at all.
+ assert ("tool_call", "compact") in [(n, d.get("tool")) for n, d in events]
+
+
+def test_layer_one_clears_oldest_results_only_until_the_prompt_fits() -> None:
+ from src.agent.loop import KEEP_RECENT, _is_cleared, _microcompact
+
+ messages = [{"role": "system", "content": "s"}]
+ for i in range(10):
+ messages.append({"role": "tool", "name": f"t{i}", "tool_call_id": f"c{i}", "content": "x" * 4_000})
+ full = estimate_tokens(messages)
+ target = full - 2_500 # needs ~2.5 results' worth cleared
+
+ _microcompact(messages, target_tokens=target, measure=estimate_tokens)
+
+ cleared = [m["name"] for m in messages[1:] if _is_cleared(m["content"])]
+ assert cleared == ["t0", "t1", "t2"] # oldest first, and no further
+ assert estimate_tokens(messages) <= target
+ # Legacy call (no target) still clears all but the last KEEP_RECENT.
+ _microcompact(messages)
+ assert sum(_is_cleared(m["content"]) for m in messages[1:]) == 10 - KEEP_RECENT
+
+
+def test_a_window_too_small_for_the_summary_tail_does_not_resummarise_every_turn(tmp_path, monkeypatch) -> None:
+ """80K window: static ~48K + the ~20K tail a summary keeps is over the 64K
+ line, so without the regrowth rule every iteration paid for a summary."""
+ result, tool, llm, _, trace = _run(
+ tmp_path, monkeypatch, provider="someone", model="small-model", env_window=80_000
+ )
+ compacts = [e for e in trace if e.get("type") == "compact"]
+ assert result["status"] == "success", result.get("reason")
+ assert compacts
+ assert len(compacts) <= len(CODES) // 2
diff --git a/agent/tests/test_get_market_data_unresolved.py b/agent/tests/test_get_market_data_unresolved.py
index 25c5aa970..0bf7fefd5 100644
--- a/agent/tests/test_get_market_data_unresolved.py
+++ b/agent/tests/test_get_market_data_unresolved.py
@@ -94,3 +94,52 @@ def test_swallowed_loader_exception_is_logged(monkeypatch, caplog):
with caplog.at_level(logging.ERROR, logger=mcp_server.logger.name):
_call(["AAA.US", "BBB.US"])
assert any("market-data loader" in r.message for r in caplog.records)
+
+
+def test_nothing_resolved_is_an_error_envelope(monkeypatch):
+ """A fetch where no symbol returned data must not read as success.
+
+ ``{"_unresolved": [...]}`` alone classified as a successful call, so the
+ loop neither refused the identical retry nor told the model to change the
+ request; repeats only counted as "no new information".
+ """
+ from src.agent.loop import _is_tool_success
+
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _BoomLoader)
+ raw = _gmd(codes=["AAA.US", "BBB.US"], start_date="2026-05-01", end_date="2026-05-02", source="yfinance")
+ out = json.loads(raw)
+
+ assert out["status"] == "error"
+ assert out["error_code"] == "no_market_data"
+ assert "AAA.US" in out["error"] and "BBB.US" in out["error"]
+ assert sorted(out["_unresolved"]) == ["AAA.US", "BBB.US"]
+ assert _is_tool_success(raw) is False
+
+
+def test_partial_and_full_results_stay_successful(monkeypatch, good_only):
+ from src.agent.loop import _is_tool_success
+
+ partial = _gmd(codes=["GOOD.US", "BOGUS.US"], start_date="2026-05-01", end_date="2026-05-02", source="yfinance")
+ full = _gmd(codes=["GOOD.US"], start_date="2026-05-01", end_date="2026-05-02", source="yfinance")
+
+ assert "status" not in json.loads(partial) and _is_tool_success(partial)
+ assert "status" not in json.loads(full) and _is_tool_success(full)
+
+
+def test_grounding_still_records_each_unavailable_symbol(tmp_path):
+ """The failed envelope keeps per-symbol unavailable evidence."""
+ from src.agent.grounding.ledger import GroundingLedger
+
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="price of AAA.US")
+ raw = json.dumps({"status": "error", "error_code": "no_market_data", "error": "x",
+ "_unresolved": ["AAA.US"]})
+ ledger.ingest_tool_result(
+ tool_name="get_market_data",
+ arguments={"codes": ["AAA.US"], "start_date": "2026-05-01", "end_date": "2026-05-02"},
+ result=raw,
+ call_id="call-1",
+ success=False,
+ )
+ unavailable = [r for r in ledger._evidence if r.field == "availability"]
+ assert [(r.symbol, r.status) for r in unavailable] == [("AAA.US", "unavailable")]
+ assert ledger._tool_failures[-1]["error_code"] == "no_market_data"
diff --git a/agent/tests/test_llm_provider_defaults.py b/agent/tests/test_llm_provider_defaults.py
index 3496246a3..86c3b8392 100644
--- a/agent/tests/test_llm_provider_defaults.py
+++ b/agent/tests/test_llm_provider_defaults.py
@@ -17,7 +17,7 @@ EXPECTED_PROVIDER_DEFAULTS = {
"openrouter": "deepseek/deepseek-v4-pro",
"openai": "gpt-5.5",
"anthropic": "claude-sonnet-4-6",
- "openai-codex": "openai-codex/gpt-5.4",
+ "openai-codex": "openai-codex/gpt-6-sol",
"deepseek": "deepseek-v4-pro",
"siliconflow-cn": "deepseek-ai/DeepSeek-V3.1-Terminus",
"siliconflow-global": "deepseek-ai/DeepSeek-V3.1-Terminus",
@@ -73,10 +73,10 @@ def test_interactive_onboard_openai_defaults_to_available_model() -> None:
def test_interactive_onboard_codex_defaults_to_supported_model() -> None:
provider = next(provider for provider in ONBOARD_PROVIDERS if provider.key == "openai-codex")
- assert provider.default_model == "openai-codex/gpt-5.4"
+ assert provider.default_model == "openai-codex/gpt-6-sol"
assert provider.key_env is None
assert provider.base_env == "OPENAI_CODEX_BASE_URL"
- assert provider.suggested_models[0] == "openai-codex/gpt-5.4"
+ assert provider.suggested_models[0] == "openai-codex/gpt-6-sol"
def test_legacy_cli_provider_choices_match_registry_defaults() -> None:
@@ -98,7 +98,7 @@ def test_interactive_onboard_suggests_current_primary_models() -> None:
assert onboard_defaults["openrouter"] == "deepseek/deepseek-v4-pro"
assert onboard_defaults["openai"] == "gpt-5.5"
assert onboard_defaults["anthropic"] == "claude-sonnet-4-6"
- assert onboard_defaults["openai-codex"] == "openai-codex/gpt-5.4"
+ assert onboard_defaults["openai-codex"] == "openai-codex/gpt-6-sol"
assert onboard_defaults["deepseek"] == "deepseek-v4-pro"
assert onboard_defaults["siliconflow-cn"] == "deepseek-ai/DeepSeek-V3.1-Terminus"
assert onboard_defaults["siliconflow-global"] == "deepseek-ai/DeepSeek-V3.1-Terminus"
@@ -192,3 +192,26 @@ def test_direct_deepseek_suggests_current_flash_name():
provider = next(p for p in ONBOARD_PROVIDERS if p.key == "deepseek")
assert "deepseek-flash" in provider.suggested_models
assert "deepseek-v4-flash" not in provider.suggested_models
+
+
+def test_codex_models_offered_are_ones_the_codex_backend_publishes() -> None:
+ """Every Codex model we default to or suggest is in the published list.
+
+ ``openai-codex/gpt-5.4`` was the default and the Codex backend answers it
+ with 400 "not supported when using Codex with a ChatGPT account"; its
+ ``-mini`` sibling was suggested beside it. ``context_windows.json`` holds
+ the models the Codex backend lists (with their source), so a default
+ outside that pattern is a model nobody verified.
+ """
+ import json
+ import re
+ from pathlib import Path
+
+ catalog = json.loads(
+ (Path(__file__).resolve().parents[1] / "src" / "providers" / "context_windows.json").read_text()
+ )
+ patterns = [e["pattern"] for e in catalog["models"] if e.get("provider") == "openai-codex"]
+ onboard = next(provider for provider in ONBOARD_PROVIDERS if provider.key == "openai-codex")
+ offered = {EXPECTED_PROVIDER_DEFAULTS["openai-codex"], onboard.default_model, *onboard.suggested_models}
+ for model in offered:
+ assert any(re.search(pattern, model) for pattern in patterns), model
diff --git a/agent/tests/test_openai_codex.py b/agent/tests/test_openai_codex.py
index 9c6fbbe69..d4007e518 100644
--- a/agent/tests/test_openai_codex.py
+++ b/agent/tests/test_openai_codex.py
@@ -29,7 +29,7 @@ from src.providers.openai_codex import (
)
-DEFAULT_CODEX_MODEL = "openai-codex/gpt-5.4"
+DEFAULT_CODEX_MODEL = "openai-codex/gpt-6-sol"
def _jwt(payload: dict[str, object]) -> str:
@@ -92,8 +92,8 @@ def test_codex_body_strips_provider_prefix_and_converts_tools() -> None:
stream=True,
)
- assert _strip_model_prefix(DEFAULT_CODEX_MODEL) == "gpt-5.4"
- assert body["model"] == "gpt-5.4"
+ assert _strip_model_prefix(DEFAULT_CODEX_MODEL) == "gpt-6-sol"
+ assert body["model"] == "gpt-6-sol"
assert body["instructions"] == "You are careful."
assert body["tools"][0]["name"] == "bash"
assert body["input"][0]["content"][0]["text"] == "Say hi."
diff --git a/agent/tests/test_openai_codex_replay.py b/agent/tests/test_openai_codex_replay.py
new file mode 100644
index 000000000..3cb856c24
--- /dev/null
+++ b/agent/tests/test_openai_codex_replay.py
@@ -0,0 +1,273 @@
+"""Codex adapter: what the model sees on the next request of a run.
+
+Event shapes follow Codex CLI's own test helpers (openai/codex
+``codex-rs/core/tests/common/responses.rs``: ``ev_reasoning_item`` — a
+``response.output_item.done`` whose item is ``{type: reasoning, id, summary,
+encrypted_content}`` — and ``ev_function_call``, whose item carries
+``call_id``/``name``/``arguments`` and no ``id``). Codex CLI replays reasoning
+items as API input (``context_manager/history.rs`` ``is_api_message``) and sends
+added instructions as ``developer`` messages (``context/base_instructions.rs``).
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+
+import pytest
+
+import src.providers.openai_codex as codex_mod
+from src.agent.context import ContextBuilder
+from src.providers.chat import ChatLLM
+from src.providers.openai_codex import (
+ CodexToolCall,
+ OpenAICodexLLM,
+ _convert_messages,
+ _events_from_lines,
+ _message_chunks_from_events,
+ _prompt_cache_key,
+)
+from src.providers.session_context import bind_llm_session_id, reset_llm_session_id
+
+SYSTEM_PROMPT = "You are the research agent. " * 2000 # ~54K chars, like the real one
+
+
+def ev_reasoning_item(item_id: str, summary: list[str], raw: str) -> dict:
+ return {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "reasoning",
+ "id": item_id,
+ "summary": [{"type": "summary_text", "text": text} for text in summary],
+ "encrypted_content": base64.b64encode(("b" * 550 + raw).encode()).decode(),
+ },
+ }
+
+
+def ev_function_call(call_id: str, name: str, arguments: str) -> dict:
+ return {
+ "type": "response.output_item.done",
+ "item": {"type": "function_call", "call_id": call_id, "name": name, "arguments": arguments},
+ }
+
+
+def ev_completed() -> dict:
+ return {
+ "type": "response.completed",
+ "response": {"id": "resp_1", "status": "completed",
+ "usage": {"input_tokens": 90_000, "output_tokens": 40, "total_tokens": 90_040}},
+ }
+
+
+def _sse(*events: dict) -> list[str]:
+ lines: list[str] = []
+ for event in events:
+ lines += [f"data: {json.dumps(event)}", ""]
+ return lines
+
+
+def _accumulate(lines: list[str]):
+ total = None
+ for chunk in _message_chunks_from_events(_events_from_lines(lines)):
+ total = chunk if total is None else total + chunk
+ return total
+
+
+def _turn_one():
+ return _accumulate(_sse(
+ ev_reasoning_item("rs_1", ["Plan: fetch both"], "need 002555 and 002624 filings"),
+ ev_function_call("call_a", "get_financial_statements", '{"code": "002555.SZ"}'),
+ ev_function_call("call_b", "get_financial_statements", '{"code": "002624.SZ"}'),
+ ev_completed(),
+ ))
+
+
+def _history_after_turn_one() -> list[dict]:
+ """Loop messages after turn one ran, built by the loop's own helpers."""
+ response = ChatLLM._parse_response(_turn_one())
+ assistant = ContextBuilder.format_assistant_tool_calls(
+ response.tool_calls,
+ content=response.content,
+ reasoning_content=response.reasoning_content,
+ provider_items=response.provider_items,
+ )
+ return [
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": "Compare A-share game companies."},
+ assistant,
+ {"role": "tool", "tool_call_id": response.tool_calls[0].id, "content": '{"ok": true}'},
+ {"role": "tool", "tool_call_id": response.tool_calls[1].id, "content": '{"ok": true}'},
+ ]
+
+
+def test_reasoning_items_travel_back_ahead_of_their_calls() -> None:
+ _, items = _convert_messages(_history_after_turn_one())
+ kinds = [item.get("type") or item.get("role") for item in items]
+
+ assert kinds == ["user", "reasoning", "function_call", "function_call",
+ "function_call_output", "function_call_output"]
+ reasoning = items[1]
+ assert reasoning["id"] == "rs_1"
+ assert reasoning["encrypted_content"]
+ assert reasoning["summary"] == [{"type": "summary_text", "text": "Plan: fetch both"}]
+ assert "content" not in reasoning # plaintext never goes back
+
+
+def test_replay_can_be_switched_off() -> None:
+ _, items = _convert_messages(_history_after_turn_one(), replay_reasoning=False)
+ assert all(item.get("type") != "reasoning" for item in items)
+
+
+def test_calls_without_backend_ids_are_not_given_made_up_ones() -> None:
+ """Two parallel calls used to both be sent back as id "fc_0"."""
+ _, items = _convert_messages(_history_after_turn_one())
+ calls = [item for item in items if item.get("type") == "function_call"]
+
+ assert [call["call_id"] for call in calls] == ["call_a", "call_b"]
+ assert all("id" not in call for call in calls)
+ outputs = [item["call_id"] for item in items if item.get("type") == "function_call_output"]
+ assert outputs == ["call_a", "call_b"]
+
+
+def test_backend_issued_call_ids_are_kept() -> None:
+ lines = _sse(
+ {"type": "response.output_item.added",
+ "item": {"type": "function_call", "call_id": "call_1", "id": "fc_real", "name": "bash", "arguments": ""}},
+ {"type": "response.output_item.done",
+ "item": {"type": "function_call", "call_id": "call_1", "id": "fc_real", "name": "bash",
+ "arguments": '{"command": "pwd"}'}},
+ )
+ message = _accumulate(lines)
+ assert message.tool_calls == [{"id": "call_1|fc_real", "name": "bash", "args": {"command": "pwd"}}]
+ _, items = _convert_messages([
+ {"role": "system", "content": "s"},
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "call_1|fc_real", "type": "function",
+ "function": {"name": "bash", "arguments": '{"command": "pwd"}'}}]},
+ ])
+ assert items[0]["id"] == "fc_real" and items[0]["call_id"] == "call_1"
+
+
+def test_a_mid_run_system_message_does_not_replace_the_system_prompt() -> None:
+ """The loop appends system messages mid-run; each one used to become
+ ``instructions`` and every later request lost the whole system prompt."""
+ messages = _history_after_turn_one() + [
+ {"role": "system", "content": "[SYSTEM] Your previous response was empty."},
+ {"role": "system", "content": "[SYSTEM] Write the pending file now."},
+ ]
+ instructions, items = _convert_messages(messages)
+
+ assert instructions == SYSTEM_PROMPT
+ developer = [item for item in items if item.get("role") == "developer"]
+ assert [item["content"][0]["text"] for item in developer] == [
+ "[SYSTEM] Your previous response was empty.",
+ "[SYSTEM] Write the pending file now.",
+ ]
+
+
+def test_prompt_cache_key_is_stable_for_a_session_and_differs_between_sessions() -> None:
+ token = bind_llm_session_id("session-a")
+ try:
+ first = _prompt_cache_key(SYSTEM_PROMPT)
+ second = _prompt_cache_key(SYSTEM_PROMPT)
+ finally:
+ reset_llm_session_id(token)
+ token = bind_llm_session_id("session-b")
+ try:
+ other = _prompt_cache_key(SYSTEM_PROMPT)
+ finally:
+ reset_llm_session_id(token)
+
+ assert first == second
+ assert first != other
+ # Unbound: stable per system prompt, never per message list.
+ assert _prompt_cache_key(SYSTEM_PROMPT) == _prompt_cache_key(SYSTEM_PROMPT)
+
+
+def test_body_uses_the_session_key_across_turns() -> None:
+ adapter = OpenAICodexLLM(model="openai-codex/gpt-6-sol")
+ history = _history_after_turn_one()
+ token = bind_llm_session_id("session-a")
+ try:
+ early = adapter._body(history[:2], stream=True)["prompt_cache_key"]
+ late = adapter._body(history, stream=True)["prompt_cache_key"]
+ finally:
+ reset_llm_session_id(token)
+ assert early == late
+
+
+class _Response:
+ def __init__(self, status_code: int, body: bytes = b"", lines: list[str] | None = None) -> None:
+ self.status_code = status_code
+ self._body = body
+ self._lines = lines or []
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ return None
+
+ def read(self) -> bytes:
+ return self._body
+
+ def iter_lines(self):
+ return iter(self._lines)
+
+
+def fresh_replay_state(monkeypatch):
+ monkeypatch.setattr(codex_mod, "_REASONING_REPLAY_REJECTED", set())
+
+
+def _client_returning(responses: list[_Response], sent: list[dict]):
+ class _Client:
+ def __init__(self, **kwargs: object) -> None:
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ return None
+
+ def stream(self, method: str, url: str, **kwargs: object) -> _Response:
+ sent.append(kwargs["json"])
+ return responses.pop(0)
+
+ return _Client
+
+
+def test_a_refused_reasoning_replay_is_resent_without_it(monkeypatch, fresh_replay_state) -> None:
+ sent: list[dict] = []
+ ok = _Response(200, lines=_sse({"type": "response.output_text.delta", "delta": "done"}, ev_completed()))
+ refused = _Response(400, b'{"error": {"message": "Invalid reasoning item rs_1: encrypted_content could not be verified"}}')
+ monkeypatch.setattr(codex_mod.httpx, "Client", _client_returning([refused, ok], sent))
+ adapter = OpenAICodexLLM(model="openai-codex/gpt-6-sol")
+ adapter._headers = lambda **kwargs: {}
+
+ text = "".join(chunk.content for chunk in adapter.stream(_history_after_turn_one()))
+
+ assert text == "done"
+ assert [any(i.get("type") == "reasoning" for i in body["input"]) for body in sent] == [True, False]
+ assert "gpt-6-sol" in codex_mod._REASONING_REPLAY_REJECTED
+
+
+def test_an_unrelated_400_is_not_retried(monkeypatch, fresh_replay_state) -> None:
+ sent: list[dict] = []
+ refused = _Response(400, b'{"detail": "The model is not supported when using Codex with a ChatGPT account."}')
+ monkeypatch.setattr(codex_mod.httpx, "Client", _client_returning([refused], sent))
+ adapter = OpenAICodexLLM(model="openai-codex/gpt-6-sol")
+ adapter._headers = lambda **kwargs: {}
+
+ with pytest.raises(codex_mod.CodexStreamError):
+ list(adapter.stream(_history_after_turn_one()))
+ assert len(sent) == 1
+ assert codex_mod._REASONING_REPLAY_REJECTED == set()
+
+
+def test_tool_call_ids_round_trip_through_the_parser() -> None:
+ message = _turn_one()
+ assert [call["id"] for call in message.tool_calls] == ["call_a", "call_b"]
+ assert CodexToolCall(id="call_a", name="x", arguments={}).as_langchain_tool_call()["id"] == "call_a"
+ assert [item["id"] for item in message.additional_kwargs["provider_items"]] == ["rs_1"]
diff --git a/agent/tests/test_session_tool_trail.py b/agent/tests/test_session_tool_trail.py
index 6d2cb6f76..fe43cacde 100644
--- a/agent/tests/test_session_tool_trail.py
+++ b/agent/tests/test_session_tool_trail.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
from pathlib import Path
+import pytest
from fastapi.testclient import TestClient
import api_server
@@ -94,6 +95,42 @@ def test_completed_attempt_tool_trail_round_trips_through_history_endpoint(
]
+ ("run_status", "attempt_status"),
+ [("failed", "failed"), ("cancelled", "cancelled")],
+)
+def test_unfinished_attempt_keeps_its_tool_trail(
+ tmp_path: Path, monkeypatch, run_status: str, attempt_status: str
+) -> None:
+ """A failed run's steps survive a reload; they used to be saved as ``[]``.
+
+ The history then read "failed · 0 steps" for a run that stopped on
+ ``no_progress`` after eight rounds of tool calls.
+ """
+ service = _service(tmp_path, monkeypatch)
+ session = Session(session_id="abcdef012346", title="failed trail")
+ service.store.create_session(session)
+ attempt = Attempt(attempt_id="attempt00002", session_id=session.session_id, prompt="Compare games")
+ service.store.create_attempt(attempt)
+ trail = [
+ {"tool": "get_financial_statements", "status": "ok", "arguments": {"code": "002555.SZ"},
+ "call_id": "call-1", "timestamp": 1_785_342_400_000},
+ {"tool": "get_financial_statements", "status": "error", "arguments": {"code": "09999.HK"},
+ "call_id": "call-2", "timestamp": 1_785_342_401_000},
+ ]
+
+ async def _run_with_agent(*args, **kwargs):
+ del args, kwargs
+ return {"status": run_status, "reason": "no_progress: stopped", "tool_trail": trail}
+
+ monkeypatch.setattr(service, "_run_with_agent", _run_with_agent)
+ asyncio.run(service._run_attempt(session, attempt))
+
+ stored = service.store.get_messages(session.session_id)[0]
+ assert stored.metadata["status"] == attempt_status
+ assert stored.tool_trail == trail
+
+
def test_run_with_agent_consolidates_tool_events_by_call_id(
tmp_path: Path,
monkeypatch,
diff --git a/agent/tests/test_tool_progress.py b/agent/tests/test_tool_progress.py
index 688c912ec..cd75dccd9 100644
--- a/agent/tests/test_tool_progress.py
+++ b/agent/tests/test_tool_progress.py
@@ -120,3 +120,41 @@ def test_no_progress_limit_remains_bounded() -> None:
assert progress.finish_iteration() is False
assert progress.finish_iteration() is True
assert progress.stalled_iterations == NO_PROGRESS_LIMIT
+
+
+def test_stop_message_names_what_kept_happening() -> None:
+ """The fixed text described one scenario (an answer lost to compaction)
+ for every stop; the stop now says which tool did what, how often."""
+ from src.agent.tool_progress import NO_PROGRESS_LIMIT, RECOVERY_MESSAGE, ToolProgress
+
+ progress = ToolProgress()
+ key = ("get_financial_statements", '{"code": "002555.SZ"}')
+ progress.record("get_financial_statements", key, '{"ok": true, "v": 1}', success=True)
+ assert progress.finish_iteration() is False # first result is new
+ for i in range(NO_PROGRESS_LIMIT):
+ progress.record("get_financial_statements", key, '{"ok": true, "v": 1}', success=True)
+ if i == 0:
+ progress.note("blocked", "get_financial_statements", "identity_mismatch")
+ stopped = progress.finish_iteration()
+ assert stopped
+ message = progress.recovery_message()
+ assert message != RECOVERY_MESSAGE
+ assert f"{NO_PROGRESS_LIMIT} tool rounds in a row" in message
+ assert f"get_financial_statements returned results it had already returned x{NO_PROGRESS_LIMIT}" in message
+ assert "get_financial_statements was refused before running (identity_mismatch) x1" in message
+ assert "rerun" in message and "path" in message
+
+
+def test_progress_forgets_the_notes_of_an_earlier_stall() -> None:
+ from src.agent.tool_progress import ToolProgress
+
+ progress = ToolProgress()
+ progress.record("a", ("a", "{}"), '{"status": "error", "error_code": "timeout"}', success=False)
+ progress.finish_iteration()
+ progress.record("b", ("b", "{}"), '{"ok": true}', success=True) # new -> progress
+ progress.finish_iteration()
+ progress.record("c", ("c", "{}"), '{"status": "error", "error": "boom"}', success=False)
+ progress.finish_iteration()
+ message = progress.recovery_message()
+ assert "c failed (boom) x1" in message
+ assert "timeout" not in message