deep-agent-cli 0.2.1__py3-none-any.whl → 0.2.2__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 (130) hide show
  1. agent/__init__.py +37 -41
  2. agent/bootstrap/__init__.py +1 -0
  3. agent/{config.py → bootstrap/config.py} +24 -198
  4. agent/{factory.py → bootstrap/factory.py} +37 -16
  5. agent/{bootstrap.py → bootstrap/setup.py} +2 -1
  6. agent/cli/__init__.py +7 -3
  7. agent/cli/access_selection.py +351 -0
  8. agent/cli/app.py +367 -2041
  9. agent/cli/attachments_controller.py +176 -0
  10. agent/cli/clipboard.py +1 -0
  11. agent/cli/commands.py +9 -8
  12. agent/cli/completion.py +99 -0
  13. agent/cli/context_compaction.py +79 -0
  14. agent/cli/display.py +43 -0
  15. agent/cli/formatting.py +73 -0
  16. agent/cli/gitinfo.py +5 -3
  17. agent/cli/input_actions.py +8 -3
  18. agent/cli/interaction_flow.py +209 -0
  19. agent/cli/interactions.py +4 -3
  20. agent/cli/key_bindings.py +238 -0
  21. agent/cli/lifecycle.py +49 -20
  22. agent/cli/main.py +31 -11
  23. agent/cli/mcp_controller.py +1 -0
  24. agent/cli/mcp_ui.py +18 -16
  25. agent/cli/model_selection.py +249 -0
  26. agent/cli/pasted_content.py +1 -0
  27. agent/cli/previews.py +4 -2
  28. agent/cli/rendering.py +157 -80
  29. agent/cli/run_dispatch.py +266 -0
  30. agent/cli/run_events_controller.py +131 -0
  31. agent/cli/session_controller.py +102 -71
  32. agent/cli/session_summaries.py +88 -0
  33. agent/cli/skill_selection.py +98 -0
  34. agent/cli/skills.py +3 -1
  35. agent/cli/state.py +11 -12
  36. agent/cli/transcript_navigation.py +264 -0
  37. agent/cli/view_state.py +35 -0
  38. agent/cli/widgets.py +180 -0
  39. agent/cli/working_messages.py +0 -1
  40. agent/config.example.yaml +3 -0
  41. agent/execution/__init__.py +1 -0
  42. agent/execution/backend.py +245 -0
  43. agent/{environment.py → execution/environment.py} +6 -4
  44. agent/execution/filesystem.py +922 -0
  45. agent/execution/layout.py +489 -0
  46. agent/{sandbox_mounts.py → execution/mounts.py} +5 -11
  47. agent/{file_mutation.py → execution/mutations.py} +2 -0
  48. agent/{network.py → execution/network.py} +2 -0
  49. agent/execution/policy.py +83 -0
  50. agent/{sandbox_pool.py → execution/pool.py} +4 -2
  51. agent/execution/ports.py +12 -0
  52. agent/execution/process.py +455 -0
  53. agent/execution/types.py +22 -0
  54. agent/mcp/__init__.py +11 -2
  55. agent/mcp/adapter.py +13 -4
  56. agent/mcp/bridge.py +1 -0
  57. agent/mcp/config.py +1 -0
  58. agent/mcp/content.py +1 -0
  59. agent/mcp/contracts.py +20 -0
  60. agent/mcp/logging.py +1 -0
  61. agent/mcp/manager.py +2 -18
  62. agent/mcp/middleware.py +2 -0
  63. agent/mcp/names.py +2 -0
  64. agent/mcp/oauth.py +2 -1
  65. agent/mcp/oauth_storage.py +3 -2
  66. agent/mcp/tools.py +2 -0
  67. agent/middleware/attachments.py +4 -2
  68. agent/middleware/cancel_tools.py +2 -1
  69. agent/middleware/current_time.py +1 -0
  70. agent/middleware/pause.py +3 -2
  71. agent/middleware/payload_recovery.py +109 -0
  72. agent/middleware/recovery.py +2 -26
  73. agent/middleware/runtime_config.py +1 -0
  74. agent/middleware/steering.py +8 -2
  75. agent/middleware/tool_arg_hints.py +2 -1
  76. agent/middleware/usage.py +1 -0
  77. agent/middleware/workspace_filesystem.py +27 -1
  78. agent/middleware/write_operation.py +2 -1
  79. agent/models/__init__.py +1 -0
  80. agent/models/catalog.py +30 -0
  81. agent/{llm.py → models/client.py} +12 -10
  82. agent/{http_environment.py → models/http.py} +2 -0
  83. agent/{stream.py → models/messages.py} +35 -10
  84. agent/models/profile.py +62 -0
  85. agent/models/session_summary.py +47 -0
  86. agent/{llm_stream.py → models/stream_lifecycle.py} +2 -1
  87. agent/runtime/__init__.py +1 -0
  88. agent/{cancel.py → runtime/cancellation.py} +1 -0
  89. agent/runtime/configuration.py +68 -0
  90. agent/runtime/contracts.py +74 -0
  91. agent/{control.py → runtime/control.py} +13 -1
  92. agent/{run_events.py → runtime/events.py} +14 -73
  93. agent/runtime/graph_execution.py +75 -0
  94. agent/runtime/metrics.py +244 -0
  95. agent/{permission.py → runtime/permissions.py} +2 -1
  96. agent/{runner.py → runtime/runner.py} +192 -281
  97. agent/sessions/__init__.py +1 -0
  98. agent/{attachments.py → sessions/attachments.py} +11 -143
  99. agent/sessions/contracts.py +59 -0
  100. agent/sessions/images.py +160 -0
  101. agent/{session_runtime.py → sessions/lifecycle.py} +12 -20
  102. agent/{session_lock.py → sessions/locks.py} +2 -0
  103. agent/sessions/ports.py +36 -0
  104. agent/sessions/reader.py +42 -0
  105. agent/sessions/recovery.py +31 -0
  106. agent/sessions/snapshots.py +38 -0
  107. agent/{session.py → sessions/store.py} +36 -182
  108. agent/sessions/summary.py +91 -0
  109. agent/sessions/transcript.py +126 -0
  110. agent/subagents/configuration.py +38 -0
  111. agent/subagents/log_store.py +2 -0
  112. agent/subagents/manager.py +2 -1
  113. agent/subagents/runtime.py +5 -4
  114. agent/tools/examples.py +2 -1
  115. agent/tools/execute.py +4 -1
  116. agent/tools/grep.py +7 -3
  117. agent/tools/human_input.py +10 -16
  118. agent/tools/human_interaction.py +3 -1
  119. agent/tools/subagent_logs.py +1 -0
  120. agent/tools/web_search.py +3 -2
  121. agent/version.py +1 -0
  122. {deep_agent_cli-0.2.1.dist-info → deep_agent_cli-0.2.2.dist-info}/METADATA +9 -9
  123. deep_agent_cli-0.2.2.dist-info/RECORD +133 -0
  124. agent/performance.py +0 -118
  125. agent/sandbox.py +0 -2029
  126. deep_agent_cli-0.2.1.dist-info/RECORD +0 -89
  127. /agent/{sandbox_worker.py → execution/worker.py} +0 -0
  128. {deep_agent_cli-0.2.1.dist-info → deep_agent_cli-0.2.2.dist-info}/WHEEL +0 -0
  129. {deep_agent_cli-0.2.1.dist-info → deep_agent_cli-0.2.2.dist-info}/entry_points.txt +0 -0
  130. {deep_agent_cli-0.2.1.dist-info → deep_agent_cli-0.2.2.dist-info}/licenses/LICENSE +0 -0
agent/__init__.py CHANGED
@@ -1,42 +1,38 @@
1
- from agent.config import BindMount, ModelProfile, SandboxConfig
2
- from agent.control import RunController
3
- from agent.factory import AgentSpec, PreparedAgent, build_agent, create_agent
4
- from agent.permission import PermissionMode
5
- from agent.runner import (
6
- AgentRunner,
7
- InterruptKind,
8
- InterruptState,
9
- RunEvent,
10
- RunResult,
11
- UnknownInterruptError,
12
- )
13
- from agent.sandbox import ExecutionMode, SandboxUnavailableError
14
- from agent.attachments import ImageAttachment, ImageAttachmentRef
15
- from agent.session import SessionInfo, SessionStore, StopReason
16
- from agent.stream import StreamDeltaCallback
1
+ """Public application API with lazy adapter loading."""
2
+ from importlib import import_module
17
3
 
18
- __all__ = [
19
- "AgentRunner",
20
- "InterruptKind",
21
- "InterruptState",
22
- "UnknownInterruptError",
23
- "AgentSpec",
24
- "BindMount",
25
- "ExecutionMode",
26
- "ModelProfile",
27
- "PermissionMode",
28
- "PreparedAgent",
29
- "RunController",
30
- "RunResult",
31
- "RunEvent",
32
- "SandboxConfig",
33
- "SandboxUnavailableError",
34
- "SessionInfo",
35
- "SessionStore",
36
- "StopReason",
37
- "ImageAttachment",
38
- "ImageAttachmentRef",
39
- "StreamDeltaCallback",
40
- "create_agent",
41
- "build_agent",
42
- ]
4
+ _EXPORTS = {
5
+ 'ModelProfile': ('agent.models.profile', 'ModelProfile'),
6
+ 'BindMount': ('agent.execution.policy', 'BindMount'),
7
+ 'SandboxConfig': ('agent.execution.policy', 'SandboxConfig'),
8
+ 'RunController': ('agent.runtime.control', 'RunController'),
9
+ 'AgentSpec': ('agent.bootstrap.factory', 'AgentSpec'),
10
+ 'PreparedAgent': ('agent.bootstrap.factory', 'PreparedAgent'),
11
+ 'build_agent': ('agent.bootstrap.factory', 'build_agent'),
12
+ 'create_agent': ('agent.bootstrap.factory', 'create_agent'),
13
+ 'PermissionMode': ('agent.runtime.permissions', 'PermissionMode'),
14
+ 'AgentRunner': ('agent.runtime.runner', 'AgentRunner'),
15
+ 'InterruptKind': ('agent.runtime.contracts', 'InterruptKind'),
16
+ 'InterruptState': ('agent.runtime.contracts', 'InterruptState'),
17
+ 'RunEvent': ('agent.runtime.contracts', 'RunEvent'),
18
+ 'RunResult': ('agent.runtime.contracts', 'RunResult'),
19
+ 'UnknownInterruptError': ('agent.runtime.contracts', 'UnknownInterruptError'),
20
+ 'ExecutionMode': ('agent.execution.types', 'ExecutionMode'),
21
+ 'SandboxUnavailableError': ('agent.execution.types', 'SandboxUnavailableError'),
22
+ 'ImageAttachment': ('agent.sessions.images', 'ImageAttachment'),
23
+ 'ImageAttachmentRef': ('agent.sessions.images', 'ImageAttachmentRef'),
24
+ 'SessionStore': ('agent.sessions.store', 'SessionStore'),
25
+ 'SessionInfo': ('agent.sessions.contracts', 'SessionInfo'),
26
+ 'StopReason': ('agent.sessions.contracts', 'StopReason'),
27
+ 'StreamDeltaCallback': ('agent.models.messages', 'StreamDeltaCallback'),
28
+ }
29
+ __all__ = list(_EXPORTS)
30
+
31
+
32
+ def __getattr__(name: str):
33
+ if name not in _EXPORTS:
34
+ raise AttributeError(name)
35
+ module, symbol = _EXPORTS[name]
36
+ value = getattr(import_module(module), symbol)
37
+ globals()[name] = value
38
+ return value
@@ -0,0 +1 @@
1
+ """Bootstrap bounded context."""
@@ -4,117 +4,34 @@ from dataclasses import dataclass, field, replace
4
4
  import os
5
5
  import re
6
6
  from pathlib import Path
7
- from typing import Any, Literal, Mapping
7
+ from typing import Any, Mapping
8
8
  from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
9
-
10
9
  import yaml
11
10
 
12
- SAFE_INHERITED_ENV = (
13
- "LANG",
14
- "TERM",
15
- "COLORTERM",
16
- "NO_COLOR",
17
- "TZ",
11
+ from agent.execution.policy import BindMount, SandboxMode, parse_sandbox_mode, SandboxConfig
12
+ from agent.subagents.configuration import SubAgentConfig
13
+ from agent.cli.display import UiDisplayLimits, DEFAULT_UI_TIMEZONE
14
+ from agent.execution.policy import default_skills_dir
15
+ from agent.models.profile import DEFAULT_REQUEST_TIMEOUT
16
+ from agent.models.catalog import ModelCatalog
17
+ from agent.models.profile import (
18
+ InputKind,
19
+ ModelProfile,
20
+ _model_max_retries,
21
+ _model_stream_chunk_timeout,
18
22
  )
19
23
 
24
+
20
25
  _DEFAULT_CONFIG_NAME = "config.yaml"
21
- DEFAULT_UI_TIMEZONE = "Asia/Shanghai"
22
- DEFAULT_STREAM_CHUNK_TIMEOUT = 120.0
23
- DEFAULT_REQUEST_TIMEOUT = 60.0
24
26
 
25
27
 
26
28
  class ConfigError(ValueError):
27
29
  """A user configuration error safe to display without a traceback."""
28
30
 
29
31
 
30
- def default_skills_dir() -> Path:
31
- return Path.home() / ".deep-agent" / "skills"
32
-
33
-
34
- @dataclass(frozen=True)
35
- class BindMount:
36
- """An explicit host-to-sandbox mount.
37
-
38
- ``modes`` is ``None`` when the mount applies in both filesystem modes.
39
- That is the historical behavior for entries that omit the field.
40
- """
41
-
42
- source: Path
43
- destination: str
44
- optional: bool = False
45
- dev_bind: bool = False
46
- modes: tuple["SandboxMode", ...] | None = None
47
-
48
-
49
- @dataclass(frozen=True)
50
- class ModelProfile:
51
- """Named OpenAI-compatible chat model profile."""
52
-
53
- id: str
54
- model: str
55
- api_key: str = "sk-local"
56
- base_url: str = "http://localhost:8000/v1"
57
- input: tuple["InputKind", ...] = ("text",)
58
- api: Literal["responses", "chat_completions"] = "responses"
59
- # 0 = unknown, so the UI can hide the context meter instead of guessing.
60
- context_window: int = 0
61
- source: str = ""
62
- reasoning_efforts: tuple[str, ...] = ()
63
- max_retries: int = 5
64
- stream_chunk_timeout: float = DEFAULT_STREAM_CHUNK_TIMEOUT
65
-
66
- def __post_init__(self) -> None:
67
- object.__setattr__(self, "max_retries", _model_max_retries(self.max_retries, field_name="max_retries"))
68
- object.__setattr__(
69
- self, "stream_chunk_timeout",
70
- _model_stream_chunk_timeout(self.stream_chunk_timeout, field_name="stream_chunk_timeout"),
71
- )
72
-
73
- def supports_input(self, kind: "InputKind") -> bool:
74
- return kind in self.input
75
-
76
-
77
- InputKind = Literal["text", "image"]
78
32
  _INPUT_KINDS = frozenset({"text", "image"})
79
33
 
80
34
 
81
- SandboxMode = Literal["restricted", "full-access"]
82
- _SANDBOX_MODES = frozenset({"restricted", "full-access"})
83
-
84
-
85
- def parse_sandbox_mode(value: str) -> SandboxMode | None:
86
- key = value.strip().lower()
87
- if key == "restricted":
88
- return "restricted"
89
- if key == "full-access":
90
- return "full-access"
91
- return None
92
-
93
-
94
- @dataclass(frozen=True)
95
- class SandboxConfig:
96
- """Bubblewrap policy. ``restricted`` is the default filesystem boundary."""
97
-
98
- workspace: Path = field(default_factory=Path.cwd)
99
- bwrap_path: str = "bwrap"
100
- mode: SandboxMode = "restricted"
101
- timeout_seconds: int | None = None
102
- max_output_bytes: int = 100_000
103
- env_allowlist: tuple[str, ...] = ()
104
- env_set: dict[str, str] = field(default_factory=dict)
105
- extra_read_only_mounts: tuple[BindMount, ...] = ()
106
- extra_read_write_mounts: tuple[BindMount, ...] = ()
107
- protected_config_dir: Path | None = None
108
- protected_files: tuple[Path, ...] = ()
109
- trust_env: bool = False
110
-
111
- def __post_init__(self) -> None:
112
- if self.mode not in _SANDBOX_MODES:
113
- raise ValueError(
114
- f"sandbox.mode must be restricted or full-access, got {self.mode!r}"
115
- )
116
-
117
-
118
35
  def _default_profiles() -> tuple[ModelProfile, ...]:
119
36
  return (
120
37
  ModelProfile(
@@ -126,72 +43,6 @@ def _default_profiles() -> tuple[ModelProfile, ...]:
126
43
  )
127
44
 
128
45
 
129
- @dataclass(frozen=True)
130
- class UiDisplayLimits:
131
- """Content folding limits, loaded from the main configuration's ui section."""
132
-
133
- head_lines: int = 4
134
- tail_lines: int = 4
135
- explore_preview_items: int = 5
136
- explore_failure_items: int = 3
137
- create_preview_items: int = 5
138
- editor_max_lines: int = 10
139
- completion_menu_lines: int = 8
140
-
141
- def __post_init__(self) -> None:
142
- for name in self.__dataclass_fields__:
143
- value = getattr(self, name)
144
- if isinstance(value, bool) or not isinstance(value, int) or value < 1:
145
- raise ValueError(f"ui.{name} must be a positive integer")
146
-
147
- @classmethod
148
- def from_mapping(cls, ui: Mapping[str, Any]) -> "UiDisplayLimits":
149
- removed = (
150
- "thinking_tail_lines", "execute_tail_lines", "tool_tail_lines", "expanded_tool_lines",
151
- "edit_preview_changed_lines", "write_preview_lines", "failure_preview_lines",
152
- "command_failure_tail_lines",
153
- )
154
- obsolete = [name for name in removed if name in ui]
155
- if obsolete:
156
- raise ValueError(f"Removed ui settings: {', '.join(obsolete)}; use ui.head_lines and ui.tail_lines")
157
- return cls(**{name: ui[name] for name in cls.__dataclass_fields__ if name in ui})
158
-
159
-
160
- DEFAULT_UI_DISPLAY_LIMITS = UiDisplayLimits()
161
-
162
-
163
- @dataclass(frozen=True)
164
- class SubAgentConfig:
165
- enabled: bool = True
166
- max_concurrent: int = 2
167
- model: str | None = None
168
- reasoning_effort: str | None = "default"
169
- permission: str = "allow"
170
-
171
- @classmethod
172
- def from_mapping(cls, values: Mapping[str, Any]) -> "SubAgentConfig":
173
- unknown = set(values) - cls.__dataclass_fields__.keys()
174
- if unknown:
175
- raise ValueError(f"Unknown subagents settings: {', '.join(sorted(unknown))}")
176
- return cls(**values)
177
-
178
- def __post_init__(self) -> None:
179
- if not isinstance(self.enabled, bool):
180
- raise ValueError("subagents.enabled must be a boolean")
181
- if type(self.max_concurrent) is not int or self.max_concurrent < 1:
182
- raise ValueError("subagents.max_concurrent must be a positive integer")
183
- if self.permission != "allow":
184
- raise ValueError("subagents.permission must be allow")
185
- for name in ("model", "reasoning_effort"):
186
- value = getattr(self, name)
187
- if value is not None and (not isinstance(value, str) or not value.strip()):
188
- raise ValueError(f"subagents.{name} must be a non-empty string or null")
189
- if self.reasoning_effort is None:
190
- object.__setattr__(self, "reasoning_effort", "default")
191
- if self.reasoning_effort == "auto":
192
- raise ValueError("subagents.reasoning_effort auto is not supported yet")
193
-
194
-
195
46
  @dataclass(frozen=True)
196
47
  class Settings:
197
48
  llm_profiles: tuple[ModelProfile, ...] = field(default_factory=_default_profiles)
@@ -208,8 +59,13 @@ class Settings:
208
59
  tavily_api_key: str | None = field(default=None, repr=False)
209
60
  trust_env: bool = False
210
61
  request_timeout: float = DEFAULT_REQUEST_TIMEOUT
62
+ compaction_threshold: float = 0.85
211
63
 
212
64
  def __post_init__(self) -> None:
65
+ if (isinstance(self.compaction_threshold, bool)
66
+ or not isinstance(self.compaction_threshold, (int, float))
67
+ or not 0 < self.compaction_threshold <= 1):
68
+ raise ValueError("agent.compaction_threshold must be a number greater than 0 and at most 1")
213
69
  if not isinstance(self.trust_env, bool):
214
70
  raise ValueError("trust_env must be a boolean")
215
71
  profile = self.active_profile
@@ -242,20 +98,12 @@ class Settings:
242
98
  def active_profile(self) -> ModelProfile:
243
99
  return self.get_profile(self.llm_default)
244
100
 
101
+ @property
102
+ def model_catalog(self) -> ModelCatalog:
103
+ return ModelCatalog(self.llm_profiles, self.llm_default)
104
+
245
105
  def get_profile(self, id_or_prefix: str) -> ModelProfile:
246
- key = id_or_prefix.strip()
247
- if not key:
248
- raise KeyError("model id is empty")
249
- exact = next((item for item in self.llm_profiles if item.id == key), None)
250
- if exact is not None:
251
- return exact
252
- matches = [item for item in self.llm_profiles if item.id.startswith(key)]
253
- if len(matches) == 1:
254
- return matches[0]
255
- if not matches:
256
- raise KeyError(f"Unknown model: {id_or_prefix}")
257
- ids = ", ".join(item.id for item in matches)
258
- raise KeyError(f"Ambiguous model prefix {id_or_prefix!r}: {ids}")
106
+ return self.model_catalog.get_profile(id_or_prefix)
259
107
 
260
108
  def list_profiles(self) -> tuple[ModelProfile, ...]:
261
109
  return self.llm_profiles
@@ -348,6 +196,7 @@ class Settings:
348
196
  config_dir=_optional_path(paths.get("config_dir"), base_dir=root),
349
197
  source_path=source_path.resolve() if source_path is not None else None,
350
198
  agent_instructions=instructions,
199
+ compaction_threshold=agent.get("compaction_threshold", 0.85),
351
200
  ui_timezone=timezone_name,
352
201
  ui_display_limits=display_limits,
353
202
  tavily_api_key=os.environ.get("TAVILY_API_KEY") or _optional_secret(
@@ -777,29 +626,6 @@ def _sandbox_from_mapping(data: Mapping[str, Any], *, base_dir: Path) -> Sandbox
777
626
  )
778
627
 
779
628
 
780
- def _model_max_retries(value: Any, *, field_name: str) -> int:
781
- if value is None:
782
- return 5
783
- if type(value) is not int or value < 0:
784
- raise ValueError(f"{field_name} must be a non-negative integer")
785
- return value
786
-
787
-
788
- def _model_stream_chunk_timeout(value: Any, *, field_name: str) -> float:
789
- """Seconds without a parsed stream chunk before the current model request retries.
790
-
791
- ``0`` disables the idle timeout. ``None`` keeps the 120 second default.
792
- """
793
- if value is None:
794
- return DEFAULT_STREAM_CHUNK_TIMEOUT
795
- if isinstance(value, bool) or not isinstance(value, (int, float)):
796
- raise ValueError(f"{field_name} must be a non-negative number of seconds")
797
- number = float(value)
798
- if not (number >= 0 and number < float("inf")):
799
- raise ValueError(f"{field_name} must be a non-negative number of seconds")
800
- return number
801
-
802
-
803
629
  def _model_request_timeout(value: Any, *, field_name: str) -> float:
804
630
  """Shared HTTP wait for the first response bytes. ``None`` keeps 60 seconds."""
805
631
  if value is None:
@@ -1,5 +1,3 @@
1
- # Assembly entry: create_deep_agent() only. Do not fork Deep Agents core.
2
- # Middleware augments the Deep Agents defaults; create_deep_agent remains the only assembly entry.
3
1
  from dataclasses import dataclass, field, replace
4
2
  import os
5
3
  from pathlib import Path
@@ -14,8 +12,9 @@ from deepagents import (
14
12
  from deepagents.backends.protocol import BackendProtocol, SandboxBackendProtocol
15
13
  from deepagents.middleware.subagents import CompiledSubAgent
16
14
  from deepagents.middleware.summarization import (
15
+ SummarizationMiddleware,
17
16
  SummarizationToolMiddleware,
18
- create_summarization_tool_middleware,
17
+ compute_summarization_defaults,
19
18
  )
20
19
  from deepagents._models import get_model_identifier, get_model_provider
21
20
  from langchain.agents.middleware import AgentMiddleware
@@ -23,13 +22,15 @@ from langchain_core.language_models import BaseChatModel
23
22
  from langchain_core.tools import BaseTool
24
23
  from langgraph.checkpoint.memory import InMemorySaver
25
24
 
26
- from agent.config import SandboxConfig, Settings
27
- from agent.control import RunController
28
- from agent.environment import EnvironmentContextMiddleware
29
- from agent.llm import ProtocolChatOpenAI, build_chat_model
25
+ from agent.bootstrap.config import Settings
26
+ from agent.execution.policy import SandboxConfig
27
+ from agent.runtime.control import RunController
28
+ from agent.execution.environment import EnvironmentContextMiddleware
29
+ from agent.models.client import ProtocolChatOpenAI, build_chat_model
30
30
  from agent.middleware.cancel_tools import ToolCancelMiddleware
31
31
  from agent.middleware.current_time import CurrentTimeMiddleware
32
32
  from agent.middleware.attachments import AttachmentMaterializationMiddleware
33
+ from agent.middleware.payload_recovery import PayloadRecoveryMiddleware
33
34
  from agent.middleware.pause import PauseGateMiddleware
34
35
  from agent.middleware.usage import UsageIdentityMiddleware
35
36
  from agent.middleware.recovery import RecoveryContextMiddleware
@@ -37,19 +38,25 @@ from agent.middleware.steering import SteeringMiddleware
37
38
  from agent.middleware.tool_arg_hints import ToolArgHintMiddleware
38
39
  from agent.middleware.write_operation import WriteOperationMiddleware
39
40
  from agent.middleware.workspace_filesystem import WorkspaceFilesystemMiddleware
40
- from agent.permission import (
41
- PermissionMode, allow_mode_unavailable_reason, interrupt_on_for_mode,
41
+ from agent.runtime.permissions import (
42
+ PermissionMode,
43
+ allow_mode_unavailable_reason,
44
+ interrupt_on_for_mode,
42
45
  permission_mode_from_interrupt_on,
43
46
  )
44
- from agent.sandbox import (
45
- BackendSelection, ExecutionMode, SKILLS_ROOT, WorkspaceCompositeBackend, sandbox_pool_of, select_backend,
46
- )
47
- from agent.sandbox_pool import SandboxPool
47
+ from agent.execution.backend import BackendSelection, sandbox_pool_of, select_backend
48
+ from agent.execution.filesystem import WorkspaceCompositeBackend
49
+ from agent.execution.types import ExecutionMode, SKILLS_ROOT
50
+ from agent.execution.pool import SandboxPool
48
51
  from agent.tools.execute import build_execute_tool
49
52
  from agent.tools.human_input import build_human_input_tools
50
53
  from agent.middleware.runtime_config import RuntimeConfigGateMiddleware
51
54
  from agent.tools.web_search import build_web_search_tool
52
55
 
56
+ # Assembly entry: create_deep_agent() only. Do not fork Deep Agents core.
57
+ # Middleware augments the Deep Agents defaults; create_deep_agent remains the only assembly entry.
58
+
59
+
53
60
  DEFAULT_FS_TOOLS = ["ls", "read_file", "write_file", "edit_file", "delete"]
54
61
 
55
62
  DEFAULT_SYSTEM_PROMPT = (
@@ -200,7 +207,20 @@ def build_agent(
200
207
  )
201
208
  tools = [tool for tool in tools if tool.name not in spec.hidden_tools]
202
209
  saver = checkpointer if checkpointer is not None else InMemorySaver()
203
- compact_middleware = create_summarization_tool_middleware(model, fs_backend)
210
+ cfg = settings or spec.settings or Settings()
211
+ summary_defaults = compute_summarization_defaults(model)
212
+ trigger = summary_defaults["trigger"]
213
+ keep = summary_defaults["keep"]
214
+ if trigger[0] == "fraction":
215
+ trigger = ("fraction", min(trigger[1], cfg.compaction_threshold))
216
+ if keep[0] == "fraction" and keep[1] >= trigger[1]:
217
+ keep = ("fraction", trigger[1] / 2)
218
+ summarization = SummarizationMiddleware(
219
+ model=model, backend=fs_backend, trigger=trigger,
220
+ keep=keep, trim_tokens_to_summarize=None,
221
+ truncate_args_settings=summary_defaults["truncate_args_settings"],
222
+ )
223
+ compact_middleware = SummarizationToolMiddleware(summarization)
204
224
  mcp_revision: int | None = None
205
225
  mcp_tools: list[Any] = []
206
226
  include_mcp = False
@@ -216,7 +236,6 @@ def build_agent(
216
236
  prompt = f"{prompt}\n\n{MCP_HOST_PROMPT}"
217
237
  subagents: list[CompiledSubAgent] = []
218
238
  manager = None
219
- cfg = settings or spec.settings or Settings()
220
239
  if spec.role == "main" and cfg.subagents.enabled:
221
240
  from agent.subagents.manager import SubAgentManager
222
241
  from agent.subagents.log_store import SubAgentLogStore
@@ -263,7 +282,7 @@ def build_agent(
263
282
  controller, lambda: False, backend_selection=selected, settings=cfg)
264
283
  except BaseException:
265
284
  if child_model is not model:
266
- from agent.llm_stream import close_model_http_clients
285
+ from agent.models.stream_lifecycle import close_model_http_clients
267
286
  close_model_http_clients(child_model)
268
287
  raise
269
288
  child.owns_model_clients = child_model is not model
@@ -303,7 +322,9 @@ def build_agent(
303
322
  ToolArgHintMiddleware(),
304
323
  WriteOperationMiddleware(fs_backend),
305
324
  AttachmentMaterializationMiddleware(),
325
+ PayloadRecoveryMiddleware(),
306
326
  WorkspaceFilesystemMiddleware(backend=fs_backend, tools=filesystem_tools),
327
+ summarization,
307
328
  compact_middleware,
308
329
  *([MCPMiddleware(mcp, mcp_tools)] if include_mcp else []),
309
330
  *([HiddenToolsMiddleware(spec.hidden_tools)] if spec.hidden_tools else []),
@@ -1,4 +1,5 @@
1
1
  """Initialize the CLI's user-owned configuration on first launch."""
2
+
2
3
  from __future__ import annotations
3
4
 
4
5
  import os
@@ -6,7 +7,7 @@ from importlib.resources import files
6
7
  from pathlib import Path
7
8
  import tempfile
8
9
 
9
- from agent.config import default_skills_dir, require_outside_workspace
10
+ from agent.bootstrap.config import default_skills_dir, require_outside_workspace
10
11
 
11
12
 
12
13
  def initialize_user_files(*, workspace: Path | None = None) -> Path | None:
agent/cli/__init__.py CHANGED
@@ -1,5 +1,9 @@
1
- """Terminal presentation layer for the Deep Agent CLI."""
2
-
3
- from agent.cli.app import CliApplication
1
+ """Terminal presentation adapter."""
4
2
 
5
3
  __all__ = ["CliApplication"]
4
+
5
+ def __getattr__(name: str):
6
+ if name == "CliApplication":
7
+ from agent.cli.app import CliApplication
8
+ return CliApplication
9
+ raise AttributeError(name)