deepagents-code 0.2.2__py3-none-any.whl → 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. deepagents_code/_build_info.py +1 -1
  2. deepagents_code/_constants.py +7 -0
  3. deepagents_code/_env_vars.py +11 -0
  4. deepagents_code/_glm_5p2_profile.py +6 -2
  5. deepagents_code/_js_cost.py +22 -0
  6. deepagents_code/_version.py +1 -1
  7. deepagents_code/agent.py +45 -2
  8. deepagents_code/app.py +143 -31
  9. deepagents_code/client/commands/mcp.py +4 -1
  10. deepagents_code/client/headless_resume.py +17 -0
  11. deepagents_code/client/non_interactive.py +9 -0
  12. deepagents_code/client/remote_client.py +4 -0
  13. deepagents_code/config.py +208 -145
  14. deepagents_code/config_manifest.py +13 -0
  15. deepagents_code/git_evidence.py +344 -0
  16. deepagents_code/git_trace.py +271 -0
  17. deepagents_code/hooks/models/domain.py +1 -0
  18. deepagents_code/hooks/reducer.py +25 -4
  19. deepagents_code/hooks/server_middleware.py +19 -2
  20. deepagents_code/local_context.py +15 -2
  21. deepagents_code/main.py +47 -53
  22. deepagents_code/mcp_auth.py +84 -3
  23. deepagents_code/mcp_tools.py +59 -89
  24. deepagents_code/model_config.py +16 -32
  25. deepagents_code/output_truncation.py +425 -0
  26. deepagents_code/plugins/discovery.py +40 -8
  27. deepagents_code/plugins/store.py +19 -3
  28. deepagents_code/provider_tool_search.py +202 -0
  29. deepagents_code/subagents.py +1 -1
  30. deepagents_code/tui/modals/cost_breakdown.py +1 -1
  31. deepagents_code/tui/modals/plugin_manager/state.py +2 -2
  32. deepagents_code/tui/textual_adapter.py +61 -5
  33. deepagents_code/tui/widgets/codex_auth.py +14 -6
  34. deepagents_code/tui/widgets/mcp_viewer.py +1 -1
  35. deepagents_code/tui/widgets/messages.py +31 -7
  36. deepagents_code/tui/widgets/model_selector.py +18 -15
  37. deepagents_code/turn_trace.py +135 -0
  38. deepagents_code/update_check.py +7 -16
  39. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.4.dist-info}/METADATA +16 -15
  40. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.4.dist-info}/RECORD +44 -39
  41. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.4.dist-info}/WHEEL +1 -1
  42. {deepagents_code-0.2.2.data → deepagents_code-0.2.4.data}/data/deepagents_code/default_agent_prompt.md +0 -0
  43. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.4.dist-info}/entry_points.txt +0 -0
  44. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.4.dist-info}/licenses/LICENSE +0 -0
@@ -1,3 +1,3 @@
1
1
  """Generated at build time. Do not edit or commit."""
2
2
 
3
- BUILD_COMMIT = "42e4f08"
3
+ BUILD_COMMIT = "88ad30d"
@@ -99,6 +99,13 @@ transcript and a thread's initial prompt. Shared here so the single producer
99
99
  LOCAL_CONTEXT_MESSAGE_SOURCE: Final[str] = "local_context"
100
100
  """Source for model-only local-context refresh messages."""
101
101
 
102
+ TASK_INTERRUPTED_MESSAGE_SOURCE: Final[str] = "task_interrupted"
103
+ """Source for the cancellation notice saved when the user interrupts a turn.
104
+
105
+ Lets readers outside the CLI tell it apart from user input without matching
106
+ `SYSTEM_MESSAGE_PREFIX` text.
107
+ """
108
+
102
109
  DEFAULT_PLUGIN_DIRNAME: Final[str] = "plugins"
103
110
  """Directory name for plugin storage under the profile root.
104
111
 
@@ -380,6 +380,14 @@ KITTY_KEYBOARD = "DEEPAGENTS_CODE_KITTY_KEYBOARD"
380
380
  LANGSMITH_PROJECT = "DEEPAGENTS_CODE_LANGSMITH_PROJECT"
381
381
  """Override LangSmith project name for agent traces."""
382
382
 
383
+ LANGSMITH_PROJECT_URL = "DEEPAGENTS_CODE_LANGSMITH_PROJECT_URL"
384
+ """LangSmith URL of the project named by `DEEPAGENTS_CODE_LANGSMITH_PROJECT`.
385
+
386
+ When set, thread links and `/trace` use this URL instead of looking the project
387
+ up, so the API key does not need project read access. It is ignored when the
388
+ active project is a different one.
389
+ """
390
+
383
391
  LANGSMITH_REDACT = "DEEPAGENTS_CODE_LANGSMITH_REDACT"
384
392
  """Toggle LangSmith secret redaction for agent traces (defaults to on)."""
385
393
 
@@ -478,6 +486,9 @@ Set to a truthy value to bring the standalone integrations screen back into the
478
486
  flow. Parsed by `is_env_truthy`: accepts `1`, `true`, `yes`, `on` as enabled.
479
487
  """
480
488
 
489
+ PROVIDER_TOOL_SEARCH = "DEEPAGENTS_CODE_PROVIDER_TOOL_SEARCH"
490
+ """Toggle native MCP tool discovery on verified endpoints (defaults to on)."""
491
+
481
492
  OPENAI_PROMPT_CACHE_KEY = "DEEPAGENTS_CODE_OPENAI_PROMPT_CACHE_KEY"
482
493
  """Toggle injecting a per-thread OpenAI `prompt_cache_key` (defaults to on).
483
494
 
@@ -26,6 +26,8 @@ from langchain.agents.middleware.types import (
26
26
  )
27
27
  from langchain_core.messages import AIMessage
28
28
 
29
+ from deepagents_code.output_truncation import MAX_OUTPUT_TOKENS, output_truncation
30
+
29
31
  if TYPE_CHECKING:
30
32
  from collections.abc import Awaitable, Callable
31
33
 
@@ -168,8 +170,10 @@ class _GlmTerminalStallRecovery(AgentMiddleware):
168
170
  message = response.result[0]
169
171
  if not isinstance(message, AIMessage) or message.tool_calls:
170
172
  return False
171
- metadata = message.response_metadata
172
- return isinstance(metadata, dict) and metadata.get("finish_reason") == "length"
173
+ # Fireworks reports the output cap as Chat Completions `finish_reason
174
+ # "length"`, which the shared classifier maps to `max_output_tokens`.
175
+ truncation = output_truncation(message)
176
+ return truncation is not None and truncation.reason == MAX_OUTPUT_TOKENS
173
177
 
174
178
  @staticmethod
175
179
  def _recovery_request(request: ModelRequest) -> ModelRequest:
@@ -33,6 +33,7 @@ from deepagents_code.thread_ownership import OWNER_KEY
33
33
  if TYPE_CHECKING:
34
34
  from collections.abc import Awaitable, Callable
35
35
 
36
+ from langchain.agents.middleware.types import ModelRequest
36
37
  from langchain_core.messages import ToolMessage
37
38
  from langchain_core.runnables import RunnableConfig
38
39
  from langgraph.prebuilt.tool_node import ToolCallRequest, ToolRuntime
@@ -57,6 +58,27 @@ def _digest(value: str) -> str:
57
58
  class CostAwareCodeInterpreterMiddleware(CodeInterpreterMiddleware):
58
59
  """Transport cost receipts without caching JavaScript or forwarding state."""
59
60
 
61
+ @override
62
+ def _prepare_for_call(self, request: ModelRequest) -> str:
63
+ """Return a compact reference while retaining all PTC bindings."""
64
+ from langchain_core.tools import BaseTool
65
+ from langchain_quickjs.middleware import render_ptc_prompt
66
+
67
+ tools = [tool for tool in request.tools if isinstance(tool, BaseTool)]
68
+ prompt = super()._prepare_for_call(request.override(tools=list(tools)))
69
+ slot = self._slot_id(request.state)
70
+ cached = self._ptc_prompt_by_slot.get(slot)
71
+ if cached is None:
72
+ return prompt
73
+ exposed, reference = cached
74
+ visible = [
75
+ tool for tool in exposed if not (tool.extras or {}).get("defer_loading")
76
+ ]
77
+ if len(visible) == len(exposed):
78
+ return prompt
79
+ replacement = render_ptc_prompt(visible, tool_name=self._tool_name)
80
+ return prompt.removesuffix(reference) + replacement
81
+
60
82
  @override
61
83
  def wrap_tool_call(
62
84
  self,
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Keep the `x-release-please-version` annotation — release-please uses it to
4
4
  # bump `__version__` in sync with `pyproject.toml` on every release PR.
5
- __version__ = "0.2.2" # x-release-please-version
5
+ __version__ = "0.2.4" # x-release-please-version
6
6
 
7
7
  DOCS_URL = "https://docs.langchain.com/oss/python/deepagents/code"
8
8
  """URL for `deepagents-code` documentation."""
deepagents_code/agent.py CHANGED
@@ -137,6 +137,11 @@ from deepagents_code.offload_middleware import (
137
137
  _create_cli_compaction_middleware,
138
138
  attach_offload_operation,
139
139
  )
140
+ from deepagents_code.output_truncation import (
141
+ EmptyTruncatedReplyMiddleware,
142
+ ModelOutputTruncatedError,
143
+ SubagentTruncatedReplyMiddleware,
144
+ )
140
145
  from deepagents_code.plugins.adapters.skills_middleware import PluginSkillsMiddleware
141
146
  from deepagents_code.project_utils import ProjectContext, get_server_project_context
142
147
  from deepagents_code.reliable_rubric import ReliableRubricMiddleware
@@ -162,6 +167,8 @@ def _format_task_error(error: Exception, request: ToolCallRequest) -> str | None
162
167
  subagent_type = request.tool_call.get("args", {}).get("subagent_type")
163
168
  subagent_name = subagent_type if isinstance(subagent_type, str) else "unknown"
164
169
  logger.debug("Subagent %r failed", subagent_name, exc_info=error)
170
+ if isinstance(error, ModelOutputTruncatedError):
171
+ return f"Subagent {subagent_name!r} failed: {error}"
165
172
  return f"Subagent {subagent_name!r} failed. You may retry this task."
166
173
 
167
174
 
@@ -2772,6 +2779,17 @@ def create_cli_agent(
2772
2779
  ):
2773
2780
  extension_registry = None
2774
2781
  mcp_tools = tuple(mcp_tools or ())
2782
+ from deepagents_code.config_manifest import get_option
2783
+ from deepagents_code.configuration.resolver import get_config_resolver
2784
+ from deepagents_code.provider_tool_search import MCPProviderToolSearchMiddleware
2785
+
2786
+ search_option = get_option("models.provider_tool_search")
2787
+ provider_tool_search = bool(
2788
+ search_option
2789
+ and get_config_resolver()
2790
+ .resolve_options((search_option,))[search_option.key]
2791
+ .value
2792
+ )
2775
2793
  skill_tools = tuple(
2776
2794
  item
2777
2795
  for item in mcp_tools
@@ -2805,6 +2823,17 @@ def create_cli_agent(
2805
2823
  else (project_context.user_cwd if project_context is not None else None)
2806
2824
  )
2807
2825
 
2826
+ from deepagents_code.git_trace import GitTraceMiddleware
2827
+
2828
+ trace_cwd = (
2829
+ get_default_working_dir(sandbox_type)
2830
+ if sandbox is not None and sandbox_type is not None
2831
+ else str(effective_cwd)
2832
+ if effective_cwd is not None
2833
+ else ""
2834
+ )
2835
+ git_trace = GitTraceMiddleware(lambda: backend, trace_cwd)
2836
+
2808
2837
  # Setup agent directory for persistent memory (if enabled)
2809
2838
  if enable_memory or enable_skills:
2810
2839
  agent_dir = ensure_agent_dir(assistant_id)
@@ -2864,7 +2893,7 @@ def create_cli_agent(
2864
2893
  ) -> list[AgentMiddleware[Any, Any]]:
2865
2894
  from deepagents_code.cost_tracking import CostTrackingMiddleware
2866
2895
 
2867
- middleware: list[AgentMiddleware[Any, Any]] = []
2896
+ middleware: list[AgentMiddleware[Any, Any]] = [git_trace]
2868
2897
  if resolved_interrupt_on is not None:
2869
2898
  middleware.append(AsyncApprovalHITLMiddleware(resolved_interrupt_on))
2870
2899
  if not has_explicit_model:
@@ -2878,7 +2907,9 @@ def create_cli_agent(
2878
2907
  # Checkpoint nested spend before HITL can pause the subgraph, then hand
2879
2908
  # the completed delta back through owner-scoped state for the parent
2880
2909
  # graph to add to its durable total.
2881
- middleware.append(CostTrackingMiddleware(nested=True))
2910
+ middleware.extend(
2911
+ [CostTrackingMiddleware(nested=True), SubagentTruncatedReplyMiddleware()]
2912
+ )
2882
2913
  # Interactive turns may legitimately be tool-free, so terminal-stall
2883
2914
  # recovery is installed only on headless stacks. The middleware itself
2884
2915
  # activates only for the measured Fireworks GLM-5.2 endpoint.
@@ -2930,6 +2961,8 @@ def create_cli_agent(
2930
2961
  tools=skill_tools,
2931
2962
  ),
2932
2963
  )
2964
+ if provider_tool_search and mcp_tools:
2965
+ middleware.append(MCPProviderToolSearchMiddleware(mcp_tools))
2933
2966
  return middleware
2934
2967
 
2935
2968
  from deepagents_code._cli_context import INHERIT_CLASSIFIER_MODEL
@@ -3041,11 +3074,18 @@ def create_cli_agent(
3041
3074
 
3042
3075
  # Build middleware stack based on enabled features
3043
3076
  agent_middleware: list[AgentMiddleware[Any, Any]] = [
3077
+ git_trace,
3044
3078
  ConfigurableModelMiddleware(
3045
3079
  cli_max_retries=cli_max_retries,
3046
3080
  environ=environment,
3047
3081
  model_result=model_result,
3048
3082
  ),
3083
+ # Wrap every other model-call middleware. Inside model selection, the
3084
+ # guard sees the resolved model for its error message. Outside GLM
3085
+ # stall recovery, recovery still gets its one retry first. Outside
3086
+ # `CodeModelRetryMiddleware`, the error is never retried. Outside
3087
+ # `BtwOperation`, the side-question capture runs as before.
3088
+ EmptyTruncatedReplyMiddleware(),
3049
3089
  ]
3050
3090
  if not interactive:
3051
3091
  agent_middleware.append(_GlmTerminalStallRecovery())
@@ -3183,6 +3223,9 @@ def create_cli_agent(
3183
3223
  # Note: Shell middleware not used in sandbox mode
3184
3224
  # File operations and execute tool are provided by the sandbox backend
3185
3225
 
3226
+ if provider_tool_search and mcp_tools:
3227
+ agent_middleware.append(MCPProviderToolSearchMiddleware(mcp_tools))
3228
+
3186
3229
  if enable_interpreter:
3187
3230
  if sandbox is not None:
3188
3231
  msg = (
deepagents_code/app.py CHANGED
@@ -1080,10 +1080,10 @@ def _format_mcp_server_changes(
1080
1080
  ):
1081
1081
  if stuck:
1082
1082
  return (
1083
- "MCP server changes: no changes detected "
1083
+ "MCP server changes: no metadata changes detected "
1084
1084
  f"(still needs attention: {', '.join(stuck)}; use /mcp)."
1085
1085
  )
1086
- return "MCP server changes: no changes detected."
1086
+ return "MCP server changes: no metadata changes detected."
1087
1087
 
1088
1088
  lines = ["MCP server changes:"]
1089
1089
  if loaded:
@@ -2642,8 +2642,32 @@ def _build_model_switch_error_body(exc: BaseException) -> str | Content:
2642
2642
  ") or see the provider reference: ",
2643
2643
  (exc.docs_url, TStyle(underline=True, link=exc.docs_url)),
2644
2644
  )
2645
- from deepagents_code.client.remote_client import format_agent_exception
2645
+ from langgraph_sdk.errors import ConflictError
2646
2646
 
2647
+ from deepagents_code.client.remote_client import (
2648
+ format_agent_exception,
2649
+ workspace_conflict_diagnostics,
2650
+ )
2651
+
2652
+ if isinstance(exc, ConflictError):
2653
+ diagnostics = workspace_conflict_diagnostics(exc)
2654
+ if diagnostics is not None and diagnostics.category in {
2655
+ "policy_drift",
2656
+ "config_drift",
2657
+ }:
2658
+ text = (
2659
+ "Model switch blocked: this conversation's workspace settings "
2660
+ "changed. The model was not changed.\n\n"
2661
+ "Restore the original settings and relaunch to continue this "
2662
+ "conversation, or use /clear to start a new conversation with "
2663
+ "the current settings. The existing conversation is preserved."
2664
+ )
2665
+ else:
2666
+ text = (
2667
+ "Model switch blocked by a workspace conflict. "
2668
+ f"The model was not changed.\n\n{format_agent_exception(exc)}"
2669
+ )
2670
+ return _build_agent_error_body(text, exc)
2647
2671
  return f"Failed to switch model: {format_agent_exception(exc)}"
2648
2672
 
2649
2673
 
@@ -5576,6 +5600,8 @@ class DeepAgentsApp(App):
5576
5600
 
5577
5601
  if self._server_startup_deferred:
5578
5602
  await self._mount_deferred_start_notice()
5603
+ if not self._onboarding_session:
5604
+ await self._show_model_selector()
5579
5605
 
5580
5606
  # Fire-and-forget workers — none of these block the event loop.
5581
5607
 
@@ -6826,7 +6852,10 @@ class DeepAgentsApp(App):
6826
6852
 
6827
6853
  # Failure surfaces only in chat — keeps recovery hint adjacent to the
6828
6854
  # input. Banner is set to idle above to drop the connecting spinner.
6829
- text = f"Server failed to start: {self._server_startup_error}"
6855
+ if isinstance(event.error, MissingCredentialsError):
6856
+ text = f"Model setup required: {event.error}"
6857
+ else:
6858
+ text = f"Server failed to start: {self._server_startup_error}"
6830
6859
  if had_deferred_actions:
6831
6860
  text += (
6832
6861
  "\n\nQueued changes were not applied. "
@@ -6837,9 +6866,9 @@ class DeepAgentsApp(App):
6837
6866
  and self._server_kwargs is not None
6838
6867
  ):
6839
6868
  text += (
6840
- "\n\nHint: run `/auth` to add a key for this provider, then "
6841
- "`/model <provider>:<model>` to retry startup. Or pick a "
6842
- "different provider directly with `/model`."
6869
+ "\n\nRun `/auth` to configure this "
6870
+ "provider; startup will retry automatically after you save. "
6871
+ "Or use `/model` to choose a different provider."
6843
6872
  )
6844
6873
  elif (
6845
6874
  self._server_startup_missing_provider_package is not None
@@ -11687,6 +11716,9 @@ class DeepAgentsApp(App):
11687
11716
  )
11688
11717
  return False
11689
11718
 
11719
+ if not await self._validate_auto_classifier():
11720
+ return False
11721
+
11690
11722
  if not has_auto_mode_notice():
11691
11723
  pending: asyncio.Future[bool] | None = getattr(
11692
11724
  self, "_auto_mode_confirmation_future", None
@@ -13852,6 +13884,7 @@ class DeepAgentsApp(App):
13852
13884
  if self._exiting:
13853
13885
  return
13854
13886
 
13887
+ self._last_typed_at = None
13855
13888
  value = event.value
13856
13889
  mode: InputMode = event.mode # ty: ignore[invalid-assignment] # Textual event mode is str at type level but InputMode at runtime
13857
13890
 
@@ -14475,6 +14508,7 @@ class DeepAgentsApp(App):
14475
14508
  LangSmithApiError,
14476
14509
  LangSmithImportError,
14477
14510
  LangSmithLookupTimeoutError,
14511
+ LangSmithPermissionError,
14478
14512
  LangSmithProjectNotFoundError,
14479
14513
  _assemble_langsmith_thread_url,
14480
14514
  fetch_langsmith_project_url_or_raise,
@@ -14585,6 +14619,26 @@ class DeepAgentsApp(App):
14585
14619
  ),
14586
14620
  )
14587
14621
  return
14622
+ except LangSmithPermissionError as exc:
14623
+ logger.warning(
14624
+ "LangSmith API key cannot read projects; cannot resolve thread "
14625
+ "URL for %s: %s",
14626
+ thread_id,
14627
+ exc,
14628
+ )
14629
+ from deepagents_code._env_vars import LANGSMITH_PROJECT_URL
14630
+
14631
+ await self._mount_message(UserMessage(command))
14632
+ await self._mount_message(
14633
+ AppMessage(
14634
+ "LangSmith denied the lookup of project "
14635
+ f"{project_name!r} (HTTP 403), so the thread URL cannot be "
14636
+ "resolved. The API key may lack project read access, or "
14637
+ "may not belong to this workspace. Set "
14638
+ f"`{LANGSMITH_PROJECT_URL}` to skip the lookup.",
14639
+ ),
14640
+ )
14641
+ return
14588
14642
  except LangSmithApiError as exc:
14589
14643
  logger.warning(
14590
14644
  "LangSmith API call failed while resolving thread URL for %s: %s",
@@ -15007,7 +15061,8 @@ class DeepAgentsApp(App):
15007
15061
  for group in catalog.groups:
15008
15062
  if not group.tools:
15009
15063
  continue
15010
- blocks.append(f"### {_escape_markdown(group.label)}")
15064
+ count = f" ({len(group.tools)})" if group.source == "mcp" else ""
15065
+ blocks.append(f"### {_escape_markdown(group.label)}{count}")
15011
15066
  if group.source == "mcp":
15012
15067
  has_mcp_tools = True
15013
15068
  blocks.append(
@@ -18214,8 +18269,7 @@ class DeepAgentsApp(App):
18214
18269
  msg += f"\n\n{self._format_cost_summary()}"
18215
18270
  await self._mount_message(AppMessage(msg))
18216
18271
  elif cmd == "/cost":
18217
- await self._mount_message(UserMessage(command))
18218
- await self._mount_message(AppMessage(self._format_cost_summary()))
18272
+ self.action_open_cost_breakdown()
18219
18273
  elif cmd == "/tools":
18220
18274
  await self._handle_tools_command(command)
18221
18275
  elif cmd == "/extensions":
@@ -18813,7 +18867,7 @@ class DeepAgentsApp(App):
18813
18867
  if restart_result.restarted:
18814
18868
  server_fresh = True
18815
18869
  self._session_plugin_ids = discovered_plugin_ids
18816
- report += "\nAgent server restarted for plugin MCP."
18870
+ report += "\nAgent server restarted."
18817
18871
  if restart_result.mcp_status == "disabled":
18818
18872
  # `--no-mcp`: there is nothing to refresh, so an
18819
18873
  # empty diff is the truth rather than an unknown.
@@ -18826,6 +18880,10 @@ class DeepAgentsApp(App):
18826
18880
  "no servers were loaded."
18827
18881
  )
18828
18882
  else:
18883
+ if restart_result.mcp_status == "fresh":
18884
+ report += (
18885
+ "\nMCP configuration re-read (including .mcp.json)."
18886
+ )
18829
18887
  report += "\n" + _format_mcp_server_changes(
18830
18888
  old_mcp_server_info,
18831
18889
  restart_result.mcp_server_info,
@@ -24292,7 +24350,15 @@ class DeepAgentsApp(App):
24292
24350
  )
24293
24351
  return
24294
24352
 
24295
- # Gate the first Auto switch on the education confirmation.
24353
+ if target is ApprovalMode.AUTO and not await self._validate_auto_classifier():
24354
+ target = next_approval_mode(
24355
+ self._approval_mode,
24356
+ auto_eligible=False,
24357
+ yolo_switcher_enabled=yolo_switcher_enabled,
24358
+ )
24359
+ if target is None:
24360
+ return
24361
+
24296
24362
  if target is ApprovalMode.AUTO and not has_auto_mode_notice():
24297
24363
  self._prompt_auto_mode_confirmation()
24298
24364
  return
@@ -24321,6 +24387,9 @@ class DeepAgentsApp(App):
24321
24387
  """
24322
24388
  from deepagents_code.approval_mode import ApprovalMode
24323
24389
 
24390
+ if target is ApprovalMode.AUTO and not await self._validate_auto_classifier():
24391
+ return False
24392
+
24324
24393
  # With no usable agent/session pair there is no running graph to update.
24325
24394
  # Stage the selection locally; `execute_task_textual` persists it before
24326
24395
  # the first `astream` after connection. This is also important for an
@@ -24379,6 +24448,32 @@ class DeepAgentsApp(App):
24379
24448
  await self._auto_accept_pending_goal_rubric()
24380
24449
  return True
24381
24450
 
24451
+ async def _validate_auto_classifier(self) -> bool:
24452
+ """Return whether Auto's reviewer can be resolved."""
24453
+ spec = self._auto_classifier_review_model_spec()
24454
+ if spec is None:
24455
+ return True
24456
+ try:
24457
+ if self._remote_agent() is not None:
24458
+ await self._resolve_auxiliary_model(spec)
24459
+ else:
24460
+ from deepagents_code.config import create_model
24461
+
24462
+ await asyncio.to_thread(
24463
+ create_model, spec, bind_preserved_thinking=False
24464
+ )
24465
+ except Exception as exc:
24466
+ logger.warning(
24467
+ "Auto classifier resolution failed for %s", spec, exc_info=True
24468
+ )
24469
+ self._warn_live_approval_mode_unavailable(
24470
+ f"Auto is unavailable: {exc}. Approval mode unchanged. "
24471
+ "Use /auth to configure credentials or /auto model "
24472
+ "to choose a reviewer."
24473
+ )
24474
+ return False
24475
+ return True
24476
+
24382
24477
  def _auto_classifier_display_spec(self) -> str | None:
24383
24478
  """Return the configured classifier spec for display, or `None` to inherit.
24384
24479
 
@@ -24781,7 +24876,8 @@ class DeepAgentsApp(App):
24781
24876
 
24782
24877
  # Gate the first Auto switch on the education confirmation.
24783
24878
  if target is ApprovalMode.AUTO and not has_auto_mode_notice():
24784
- self._prompt_auto_mode_confirmation()
24879
+ if await self._validate_auto_classifier():
24880
+ self._prompt_auto_mode_confirmation()
24785
24881
  return
24786
24882
 
24787
24883
  if target is ApprovalMode.YOLO:
@@ -26331,6 +26427,7 @@ class DeepAgentsApp(App):
26331
26427
  ModelConfigError,
26332
26428
  NoAllowedModelCredentialsError,
26333
26429
  NoCredentialsConfiguredError,
26430
+ NoModelConfiguredError,
26334
26431
  )
26335
26432
 
26336
26433
  try:
@@ -26341,7 +26438,7 @@ class DeepAgentsApp(App):
26341
26438
  # actionable, and silence after closing `/auth` reads as a hang.
26342
26439
  await self._mount_message(ErrorMessage(str(exc)))
26343
26440
  return False
26344
- except NoCredentialsConfiguredError:
26441
+ except NoCredentialsConfiguredError, NoModelConfiguredError:
26345
26442
  # No usable default to fall back to — nothing to retry.
26346
26443
  return False
26347
26444
  except ModelConfigError as exc:
@@ -27173,24 +27270,31 @@ class DeepAgentsApp(App):
27173
27270
  self._open_debug_console()
27174
27271
 
27175
27272
  def action_open_cost_breakdown(self) -> None:
27176
- """Open the session cost breakdown from the footer."""
27273
+ """Open the session cost breakdown from the footer or `/cost`."""
27274
+ from deepagents_code.tui.modals.cost_breakdown import open_cost_breakdown
27275
+
27276
+ open_cost_breakdown(self, self._format_cost_modal)
27277
+
27278
+ def _format_cost_modal(self) -> str:
27279
+ """Build the modal content.
27280
+
27281
+ Returns:
27282
+ Available token details and the escaped cost explanation.
27283
+ """
27177
27284
  from deepagents_code.tui.modals.cost_breakdown import (
27178
27285
  format_cost_breakdown_table,
27179
- open_cost_breakdown,
27180
27286
  )
27181
27287
 
27182
- open_cost_breakdown(
27183
- self,
27184
- lambda: format_cost_breakdown_table(
27185
- self._session_cost_usd, self._session_cost_breakdown
27186
- ),
27288
+ table = format_cost_breakdown_table(
27289
+ self._session_cost_usd, self._session_cost_breakdown
27290
+ )
27291
+ summary = " \n".join(
27292
+ _escape_markdown(line) for line in self._format_cost_summary().splitlines()
27187
27293
  )
27294
+ return f"{table}\n\n{summary}" if table else summary
27188
27295
 
27189
27296
  def _open_debug_console(self) -> None:
27190
27297
  """Push the read-only Debug Console modal."""
27191
- from deepagents_code.tui.modals.cost_breakdown import (
27192
- format_cost_breakdown_table,
27193
- )
27194
27298
  from deepagents_code.tui.widgets.debug_console import DebugConsoleScreen
27195
27299
 
27196
27300
  def handle_result(_: None) -> None:
@@ -27207,9 +27311,7 @@ class DeepAgentsApp(App):
27207
27311
  # counts, tokens, and other in-memory fields stay current while
27208
27312
  # the modal is open. The builder is intentionally I/O-free.
27209
27313
  snapshot_provider=self._build_debug_snapshot,
27210
- cost_breakdown_provider=lambda: format_cost_breakdown_table(
27211
- self._session_cost_usd, self._session_cost_breakdown
27212
- ),
27314
+ cost_breakdown_provider=self._format_cost_modal,
27213
27315
  mcp_servers_provider=lambda: self._mcp_server_info or [],
27214
27316
  cleared_upto=self._debug_console_cleared_upto,
27215
27317
  on_clear=persist_clear,
@@ -29346,7 +29448,7 @@ class DeepAgentsApp(App):
29346
29448
  # exception — its `args`/repr may include an `OAuthToken` from
29347
29449
  # the MCP SDK. `format_login_failure` unwraps `ExceptionGroup`
29348
29450
  # roots and degrades to a class-name chain for unknown types.
29349
- summary = format_login_failure(login_error)
29451
+ summary = format_login_failure(login_error, include_login_hint=True)
29350
29452
  logger.warning("MCP login for %r failed: %s", server_name, summary)
29351
29453
  screen.finish(success=False, message=f"Login failed: {summary}")
29352
29454
  await asyncio.wait_for(outcome_future, timeout=5.0)
@@ -32728,11 +32830,18 @@ class DeepAgentsApp(App):
32728
32830
 
32729
32831
  self._last_model_unchanged = None
32730
32832
  params_suffix = _format_model_params(extra_kwargs)
32833
+ classifier_suffix = (
32834
+ ". Auto-mode classifier model also switched."
32835
+ if self._auto_classifier_display_spec() is None
32836
+ else ""
32837
+ )
32731
32838
  if not persist:
32732
32839
  # Session-only switch (e.g. adopting a resumed thread's model):
32733
32840
  # announce but never touch the user's persisted recent/default.
32734
32841
  await self._mount_message(
32735
- AppMessage(f"Switched to {display}{params_suffix}"),
32842
+ AppMessage(
32843
+ f"Switched to {display}{params_suffix}{classifier_suffix}"
32844
+ ),
32736
32845
  )
32737
32846
  elif not await asyncio.to_thread(save_recent_model, resolved_spec):
32738
32847
  await self._mount_message(
@@ -32744,7 +32853,9 @@ class DeepAgentsApp(App):
32744
32853
  )
32745
32854
  else:
32746
32855
  await self._mount_message(
32747
- AppMessage(f"Switched to {display}{params_suffix}"),
32856
+ AppMessage(
32857
+ f"Switched to {display}{params_suffix}{classifier_suffix}"
32858
+ ),
32748
32859
  )
32749
32860
  if persist:
32750
32861
  # Best-effort MRU update for the `/model` Recent section.
@@ -32884,6 +32995,7 @@ class DeepAgentsApp(App):
32884
32995
  ModelConfigError,
32885
32996
  NoAllowedModelCredentialsError,
32886
32997
  NoCredentialsConfiguredError,
32998
+ NoModelConfiguredError,
32887
32999
  )
32888
33000
 
32889
33001
  try:
@@ -32894,7 +33006,7 @@ class DeepAgentsApp(App):
32894
33006
  # `/auth` look broken, so name the models that would work.
32895
33007
  await self._mount_message(ErrorMessage(str(exc)))
32896
33008
  return False
32897
- except NoCredentialsConfiguredError:
33009
+ except NoCredentialsConfiguredError, NoModelConfiguredError:
32898
33010
  return False
32899
33011
  except ModelConfigError as exc:
32900
33012
  await self._mount_message(ErrorMessage(str(exc)))
@@ -268,6 +268,7 @@ async def run_mcp_login(*, server: str, config_path: str | None) -> int:
268
268
  return 1
269
269
 
270
270
  import httpx
271
+ from mcp.shared.exceptions import MCPError
271
272
  from pydantic import ValidationError
272
273
 
273
274
  from deepagents_code.mcp_auth import format_login_failure, token_store_dir
@@ -297,9 +298,11 @@ async def run_mcp_login(*, server: str, config_path: str | None) -> int:
297
298
  ValidationError,
298
299
  KeyError,
299
300
  OSError,
301
+ MCPError,
302
+ ExceptionGroup,
300
303
  ) as exc:
301
304
  print( # noqa: T201
302
- f"Login failed: {format_login_failure(exc)}",
305
+ f"Login failed: {format_login_failure(exc, include_login_hint=True)}",
303
306
  file=sys.stderr,
304
307
  )
305
308
  return 1
@@ -111,6 +111,23 @@ def cwd_conflict(target: ResumeTarget, current_cwd: str) -> str | None:
111
111
  return None
112
112
 
113
113
 
114
+ async def resume_launch_model(thread_id: str) -> str:
115
+ """Return the thread's model, or its saved-preference fallback."""
116
+ from deepagents_code.config import _get_default_model_spec
117
+ from deepagents_code.sessions import get_checkpointer
118
+
119
+ async with get_checkpointer() as checkpointer:
120
+ checkpoint = await checkpointer.aget_tuple(
121
+ {"configurable": {"thread_id": thread_id}}
122
+ )
123
+ selection = (
124
+ persisted_model(checkpoint.checkpoint["channel_values"])
125
+ if checkpoint is not None
126
+ else None
127
+ )
128
+ return selection[0] if selection else _get_default_model_spec()
129
+
130
+
114
131
  def persisted_model(
115
132
  values: Mapping[str, object],
116
133
  ) -> tuple[str, dict[str, Any] | None] | None:
@@ -2944,6 +2944,15 @@ async def run_non_interactive(
2944
2944
  except ResumeError as exc:
2945
2945
  _print_resume_error(console, exc)
2946
2946
  return 1
2947
+ if resume is not None and resume.adopt_model and model_name is None:
2948
+ from deepagents_code.client.headless_resume import resume_launch_model
2949
+ from deepagents_code.model_config import ModelConfigError
2950
+
2951
+ try:
2952
+ model_name = await resume_launch_model(thread_id)
2953
+ except ModelConfigError as exc:
2954
+ _print_resume_error(console, exc)
2955
+ return 1
2947
2956
  if quiet:
2948
2957
  # Printed despite `-q`: scripts parse it to resume the thread later.
2949
2958
  console.print(
@@ -1577,9 +1577,13 @@ def _convert_ai_message(data: dict[str, Any]) -> Any: # noqa: ANN401
1577
1577
  tool_calls = data.get("tool_calls", [])
1578
1578
  usage_metadata = data.get("usage_metadata")
1579
1579
  response_metadata = data.get("response_metadata", {})
1580
+ additional_kwargs = data.get("additional_kwargs")
1580
1581
 
1581
1582
  kwargs: dict[str, Any] = {
1582
1583
  "content": content,
1584
+ "additional_kwargs": (
1585
+ additional_kwargs if isinstance(additional_kwargs, dict) else {}
1586
+ ),
1583
1587
  "id": data.get("id"),
1584
1588
  "response_metadata": response_metadata,
1585
1589
  "chunk_position": data.get("chunk_position"),