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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. deepagents_code/_build_info.py +1 -1
  2. deepagents_code/_env_vars.py +11 -0
  3. deepagents_code/_glm_5p2_profile.py +6 -2
  4. deepagents_code/_js_cost.py +22 -0
  5. deepagents_code/_version.py +1 -1
  6. deepagents_code/agent.py +45 -2
  7. deepagents_code/app.py +110 -26
  8. deepagents_code/client/headless_resume.py +17 -0
  9. deepagents_code/client/non_interactive.py +9 -0
  10. deepagents_code/client/remote_client.py +4 -0
  11. deepagents_code/config.py +208 -145
  12. deepagents_code/config_manifest.py +13 -0
  13. deepagents_code/git_evidence.py +344 -0
  14. deepagents_code/git_trace.py +271 -0
  15. deepagents_code/hooks/models/domain.py +1 -0
  16. deepagents_code/hooks/reducer.py +25 -4
  17. deepagents_code/hooks/server_middleware.py +19 -2
  18. deepagents_code/local_context.py +15 -2
  19. deepagents_code/main.py +47 -53
  20. deepagents_code/mcp_tools.py +59 -89
  21. deepagents_code/model_config.py +16 -32
  22. deepagents_code/output_truncation.py +425 -0
  23. deepagents_code/plugins/discovery.py +40 -8
  24. deepagents_code/plugins/store.py +19 -3
  25. deepagents_code/provider_tool_search.py +202 -0
  26. deepagents_code/subagents.py +1 -1
  27. deepagents_code/tui/modals/cost_breakdown.py +1 -1
  28. deepagents_code/tui/modals/plugin_manager/state.py +2 -2
  29. deepagents_code/tui/textual_adapter.py +50 -0
  30. deepagents_code/tui/widgets/codex_auth.py +14 -6
  31. deepagents_code/tui/widgets/mcp_viewer.py +1 -1
  32. deepagents_code/tui/widgets/messages.py +31 -7
  33. deepagents_code/tui/widgets/model_selector.py +18 -15
  34. deepagents_code/turn_trace.py +135 -0
  35. deepagents_code/update_check.py +7 -16
  36. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.3.dist-info}/METADATA +14 -14
  37. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.3.dist-info}/RECORD +41 -36
  38. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.3.dist-info}/WHEEL +1 -1
  39. {deepagents_code-0.2.2.data → deepagents_code-0.2.3.data}/data/deepagents_code/default_agent_prompt.md +0 -0
  40. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.3.dist-info}/entry_points.txt +0 -0
  41. {deepagents_code-0.2.2.dist-info → deepagents_code-0.2.3.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 = "6884d39"
@@ -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.3" # 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
@@ -5576,6 +5576,8 @@ class DeepAgentsApp(App):
5576
5576
 
5577
5577
  if self._server_startup_deferred:
5578
5578
  await self._mount_deferred_start_notice()
5579
+ if not self._onboarding_session:
5580
+ await self._show_model_selector()
5579
5581
 
5580
5582
  # Fire-and-forget workers — none of these block the event loop.
5581
5583
 
@@ -6826,7 +6828,10 @@ class DeepAgentsApp(App):
6826
6828
 
6827
6829
  # Failure surfaces only in chat — keeps recovery hint adjacent to the
6828
6830
  # input. Banner is set to idle above to drop the connecting spinner.
6829
- text = f"Server failed to start: {self._server_startup_error}"
6831
+ if isinstance(event.error, MissingCredentialsError):
6832
+ text = f"Model setup required: {event.error}"
6833
+ else:
6834
+ text = f"Server failed to start: {self._server_startup_error}"
6830
6835
  if had_deferred_actions:
6831
6836
  text += (
6832
6837
  "\n\nQueued changes were not applied. "
@@ -6837,9 +6842,9 @@ class DeepAgentsApp(App):
6837
6842
  and self._server_kwargs is not None
6838
6843
  ):
6839
6844
  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`."
6845
+ "\n\nRun `/auth` to configure this "
6846
+ "provider; startup will retry automatically after you save. "
6847
+ "Or use `/model` to choose a different provider."
6843
6848
  )
6844
6849
  elif (
6845
6850
  self._server_startup_missing_provider_package is not None
@@ -11687,6 +11692,9 @@ class DeepAgentsApp(App):
11687
11692
  )
11688
11693
  return False
11689
11694
 
11695
+ if not await self._validate_auto_classifier():
11696
+ return False
11697
+
11690
11698
  if not has_auto_mode_notice():
11691
11699
  pending: asyncio.Future[bool] | None = getattr(
11692
11700
  self, "_auto_mode_confirmation_future", None
@@ -13852,6 +13860,7 @@ class DeepAgentsApp(App):
13852
13860
  if self._exiting:
13853
13861
  return
13854
13862
 
13863
+ self._last_typed_at = None
13855
13864
  value = event.value
13856
13865
  mode: InputMode = event.mode # ty: ignore[invalid-assignment] # Textual event mode is str at type level but InputMode at runtime
13857
13866
 
@@ -14475,6 +14484,7 @@ class DeepAgentsApp(App):
14475
14484
  LangSmithApiError,
14476
14485
  LangSmithImportError,
14477
14486
  LangSmithLookupTimeoutError,
14487
+ LangSmithPermissionError,
14478
14488
  LangSmithProjectNotFoundError,
14479
14489
  _assemble_langsmith_thread_url,
14480
14490
  fetch_langsmith_project_url_or_raise,
@@ -14585,6 +14595,26 @@ class DeepAgentsApp(App):
14585
14595
  ),
14586
14596
  )
14587
14597
  return
14598
+ except LangSmithPermissionError as exc:
14599
+ logger.warning(
14600
+ "LangSmith API key cannot read projects; cannot resolve thread "
14601
+ "URL for %s: %s",
14602
+ thread_id,
14603
+ exc,
14604
+ )
14605
+ from deepagents_code._env_vars import LANGSMITH_PROJECT_URL
14606
+
14607
+ await self._mount_message(UserMessage(command))
14608
+ await self._mount_message(
14609
+ AppMessage(
14610
+ "LangSmith denied the lookup of project "
14611
+ f"{project_name!r} (HTTP 403), so the thread URL cannot be "
14612
+ "resolved. The API key may lack project read access, or "
14613
+ "may not belong to this workspace. Set "
14614
+ f"`{LANGSMITH_PROJECT_URL}` to skip the lookup.",
14615
+ ),
14616
+ )
14617
+ return
14588
14618
  except LangSmithApiError as exc:
14589
14619
  logger.warning(
14590
14620
  "LangSmith API call failed while resolving thread URL for %s: %s",
@@ -15007,7 +15037,8 @@ class DeepAgentsApp(App):
15007
15037
  for group in catalog.groups:
15008
15038
  if not group.tools:
15009
15039
  continue
15010
- blocks.append(f"### {_escape_markdown(group.label)}")
15040
+ count = f" ({len(group.tools)})" if group.source == "mcp" else ""
15041
+ blocks.append(f"### {_escape_markdown(group.label)}{count}")
15011
15042
  if group.source == "mcp":
15012
15043
  has_mcp_tools = True
15013
15044
  blocks.append(
@@ -18214,8 +18245,7 @@ class DeepAgentsApp(App):
18214
18245
  msg += f"\n\n{self._format_cost_summary()}"
18215
18246
  await self._mount_message(AppMessage(msg))
18216
18247
  elif cmd == "/cost":
18217
- await self._mount_message(UserMessage(command))
18218
- await self._mount_message(AppMessage(self._format_cost_summary()))
18248
+ self.action_open_cost_breakdown()
18219
18249
  elif cmd == "/tools":
18220
18250
  await self._handle_tools_command(command)
18221
18251
  elif cmd == "/extensions":
@@ -24292,7 +24322,15 @@ class DeepAgentsApp(App):
24292
24322
  )
24293
24323
  return
24294
24324
 
24295
- # Gate the first Auto switch on the education confirmation.
24325
+ if target is ApprovalMode.AUTO and not await self._validate_auto_classifier():
24326
+ target = next_approval_mode(
24327
+ self._approval_mode,
24328
+ auto_eligible=False,
24329
+ yolo_switcher_enabled=yolo_switcher_enabled,
24330
+ )
24331
+ if target is None:
24332
+ return
24333
+
24296
24334
  if target is ApprovalMode.AUTO and not has_auto_mode_notice():
24297
24335
  self._prompt_auto_mode_confirmation()
24298
24336
  return
@@ -24321,6 +24359,9 @@ class DeepAgentsApp(App):
24321
24359
  """
24322
24360
  from deepagents_code.approval_mode import ApprovalMode
24323
24361
 
24362
+ if target is ApprovalMode.AUTO and not await self._validate_auto_classifier():
24363
+ return False
24364
+
24324
24365
  # With no usable agent/session pair there is no running graph to update.
24325
24366
  # Stage the selection locally; `execute_task_textual` persists it before
24326
24367
  # the first `astream` after connection. This is also important for an
@@ -24379,6 +24420,32 @@ class DeepAgentsApp(App):
24379
24420
  await self._auto_accept_pending_goal_rubric()
24380
24421
  return True
24381
24422
 
24423
+ async def _validate_auto_classifier(self) -> bool:
24424
+ """Return whether Auto's reviewer can be resolved."""
24425
+ spec = self._auto_classifier_review_model_spec()
24426
+ if spec is None:
24427
+ return True
24428
+ try:
24429
+ if self._remote_agent() is not None:
24430
+ await self._resolve_auxiliary_model(spec)
24431
+ else:
24432
+ from deepagents_code.config import create_model
24433
+
24434
+ await asyncio.to_thread(
24435
+ create_model, spec, bind_preserved_thinking=False
24436
+ )
24437
+ except Exception as exc:
24438
+ logger.warning(
24439
+ "Auto classifier resolution failed for %s", spec, exc_info=True
24440
+ )
24441
+ self._warn_live_approval_mode_unavailable(
24442
+ f"Auto is unavailable: {exc}. Approval mode unchanged. "
24443
+ "Use /auth to configure credentials or /auto model "
24444
+ "to choose a reviewer."
24445
+ )
24446
+ return False
24447
+ return True
24448
+
24382
24449
  def _auto_classifier_display_spec(self) -> str | None:
24383
24450
  """Return the configured classifier spec for display, or `None` to inherit.
24384
24451
 
@@ -24781,7 +24848,8 @@ class DeepAgentsApp(App):
24781
24848
 
24782
24849
  # Gate the first Auto switch on the education confirmation.
24783
24850
  if target is ApprovalMode.AUTO and not has_auto_mode_notice():
24784
- self._prompt_auto_mode_confirmation()
24851
+ if await self._validate_auto_classifier():
24852
+ self._prompt_auto_mode_confirmation()
24785
24853
  return
24786
24854
 
24787
24855
  if target is ApprovalMode.YOLO:
@@ -26331,6 +26399,7 @@ class DeepAgentsApp(App):
26331
26399
  ModelConfigError,
26332
26400
  NoAllowedModelCredentialsError,
26333
26401
  NoCredentialsConfiguredError,
26402
+ NoModelConfiguredError,
26334
26403
  )
26335
26404
 
26336
26405
  try:
@@ -26341,7 +26410,7 @@ class DeepAgentsApp(App):
26341
26410
  # actionable, and silence after closing `/auth` reads as a hang.
26342
26411
  await self._mount_message(ErrorMessage(str(exc)))
26343
26412
  return False
26344
- except NoCredentialsConfiguredError:
26413
+ except NoCredentialsConfiguredError, NoModelConfiguredError:
26345
26414
  # No usable default to fall back to — nothing to retry.
26346
26415
  return False
26347
26416
  except ModelConfigError as exc:
@@ -27173,24 +27242,31 @@ class DeepAgentsApp(App):
27173
27242
  self._open_debug_console()
27174
27243
 
27175
27244
  def action_open_cost_breakdown(self) -> None:
27176
- """Open the session cost breakdown from the footer."""
27245
+ """Open the session cost breakdown from the footer or `/cost`."""
27246
+ from deepagents_code.tui.modals.cost_breakdown import open_cost_breakdown
27247
+
27248
+ open_cost_breakdown(self, self._format_cost_modal)
27249
+
27250
+ def _format_cost_modal(self) -> str:
27251
+ """Build the modal content.
27252
+
27253
+ Returns:
27254
+ Available token details and the escaped cost explanation.
27255
+ """
27177
27256
  from deepagents_code.tui.modals.cost_breakdown import (
27178
27257
  format_cost_breakdown_table,
27179
- open_cost_breakdown,
27180
27258
  )
27181
27259
 
27182
- open_cost_breakdown(
27183
- self,
27184
- lambda: format_cost_breakdown_table(
27185
- self._session_cost_usd, self._session_cost_breakdown
27186
- ),
27260
+ table = format_cost_breakdown_table(
27261
+ self._session_cost_usd, self._session_cost_breakdown
27187
27262
  )
27263
+ summary = " \n".join(
27264
+ _escape_markdown(line) for line in self._format_cost_summary().splitlines()
27265
+ )
27266
+ return f"{table}\n\n{summary}" if table else summary
27188
27267
 
27189
27268
  def _open_debug_console(self) -> None:
27190
27269
  """Push the read-only Debug Console modal."""
27191
- from deepagents_code.tui.modals.cost_breakdown import (
27192
- format_cost_breakdown_table,
27193
- )
27194
27270
  from deepagents_code.tui.widgets.debug_console import DebugConsoleScreen
27195
27271
 
27196
27272
  def handle_result(_: None) -> None:
@@ -27207,9 +27283,7 @@ class DeepAgentsApp(App):
27207
27283
  # counts, tokens, and other in-memory fields stay current while
27208
27284
  # the modal is open. The builder is intentionally I/O-free.
27209
27285
  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
- ),
27286
+ cost_breakdown_provider=self._format_cost_modal,
27213
27287
  mcp_servers_provider=lambda: self._mcp_server_info or [],
27214
27288
  cleared_upto=self._debug_console_cleared_upto,
27215
27289
  on_clear=persist_clear,
@@ -32728,11 +32802,18 @@ class DeepAgentsApp(App):
32728
32802
 
32729
32803
  self._last_model_unchanged = None
32730
32804
  params_suffix = _format_model_params(extra_kwargs)
32805
+ classifier_suffix = (
32806
+ ". Auto-mode classifier model also switched."
32807
+ if self._auto_classifier_display_spec() is None
32808
+ else ""
32809
+ )
32731
32810
  if not persist:
32732
32811
  # Session-only switch (e.g. adopting a resumed thread's model):
32733
32812
  # announce but never touch the user's persisted recent/default.
32734
32813
  await self._mount_message(
32735
- AppMessage(f"Switched to {display}{params_suffix}"),
32814
+ AppMessage(
32815
+ f"Switched to {display}{params_suffix}{classifier_suffix}"
32816
+ ),
32736
32817
  )
32737
32818
  elif not await asyncio.to_thread(save_recent_model, resolved_spec):
32738
32819
  await self._mount_message(
@@ -32744,7 +32825,9 @@ class DeepAgentsApp(App):
32744
32825
  )
32745
32826
  else:
32746
32827
  await self._mount_message(
32747
- AppMessage(f"Switched to {display}{params_suffix}"),
32828
+ AppMessage(
32829
+ f"Switched to {display}{params_suffix}{classifier_suffix}"
32830
+ ),
32748
32831
  )
32749
32832
  if persist:
32750
32833
  # Best-effort MRU update for the `/model` Recent section.
@@ -32884,6 +32967,7 @@ class DeepAgentsApp(App):
32884
32967
  ModelConfigError,
32885
32968
  NoAllowedModelCredentialsError,
32886
32969
  NoCredentialsConfiguredError,
32970
+ NoModelConfiguredError,
32887
32971
  )
32888
32972
 
32889
32973
  try:
@@ -32894,7 +32978,7 @@ class DeepAgentsApp(App):
32894
32978
  # `/auth` look broken, so name the models that would work.
32895
32979
  await self._mount_message(ErrorMessage(str(exc)))
32896
32980
  return False
32897
- except NoCredentialsConfiguredError:
32981
+ except NoCredentialsConfiguredError, NoModelConfiguredError:
32898
32982
  return False
32899
32983
  except ModelConfigError as exc:
32900
32984
  await self._mount_message(ErrorMessage(str(exc)))
@@ -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"),