deep-agent-cli 0.2.0__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 (131) hide show
  1. agent/__init__.py +37 -41
  2. agent/bootstrap/__init__.py +1 -0
  3. agent/{config.py → bootstrap/config.py} +34 -166
  4. agent/{factory.py → bootstrap/factory.py} +130 -19
  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 +376 -2042
  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 +21 -3
  28. agent/cli/rendering.py +191 -94
  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 +35 -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 +41 -24
  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 +34 -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} +12 -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} +31 -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} +211 -286
  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} +20 -23
  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 -167
  108. agent/sessions/summary.py +91 -0
  109. agent/sessions/transcript.py +126 -0
  110. agent/subagents/__init__.py +1 -0
  111. agent/subagents/configuration.py +38 -0
  112. agent/subagents/log_store.py +92 -0
  113. agent/subagents/manager.py +51 -0
  114. agent/subagents/runtime.py +213 -0
  115. agent/tools/examples.py +2 -1
  116. agent/tools/execute.py +4 -1
  117. agent/tools/grep.py +7 -3
  118. agent/tools/human_input.py +10 -16
  119. agent/tools/human_interaction.py +3 -1
  120. agent/tools/subagent_logs.py +21 -0
  121. agent/tools/web_search.py +3 -2
  122. agent/version.py +1 -0
  123. {deep_agent_cli-0.2.0.dist-info → deep_agent_cli-0.2.2.dist-info}/METADATA +17 -14
  124. deep_agent_cli-0.2.2.dist-info/RECORD +133 -0
  125. {deep_agent_cli-0.2.0.dist-info → deep_agent_cli-0.2.2.dist-info}/WHEEL +1 -1
  126. agent/performance.py +0 -118
  127. agent/sandbox.py +0 -2029
  128. deep_agent_cli-0.2.0.dist-info/RECORD +0 -83
  129. /agent/{sandbox_worker.py → execution/worker.py} +0 -0
  130. {deep_agent_cli-0.2.0.dist-info → deep_agent_cli-0.2.2.dist-info}/entry_points.txt +0 -0
  131. {deep_agent_cli-0.2.0.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,44 +43,11 @@ 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
46
  @dataclass(frozen=True)
164
47
  class Settings:
165
48
  llm_profiles: tuple[ModelProfile, ...] = field(default_factory=_default_profiles)
166
49
  llm_default: str = "default"
50
+ subagents: SubAgentConfig = field(default_factory=SubAgentConfig)
167
51
  sandbox: SandboxConfig = field(default_factory=SandboxConfig)
168
52
  state_path: Path | None = None
169
53
  config_dir: Path | None = None
@@ -175,10 +59,23 @@ class Settings:
175
59
  tavily_api_key: str | None = field(default=None, repr=False)
176
60
  trust_env: bool = False
177
61
  request_timeout: float = DEFAULT_REQUEST_TIMEOUT
62
+ compaction_threshold: float = 0.85
178
63
 
179
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")
180
69
  if not isinstance(self.trust_env, bool):
181
70
  raise ValueError("trust_env must be a boolean")
71
+ profile = self.active_profile
72
+ if self.subagents.model is not None:
73
+ profile = next((p for p in self.llm_profiles if p.id == self.subagents.model), None)
74
+ if profile is None:
75
+ raise ValueError(f"Unknown subagents.model: {self.subagents.model}")
76
+ effort = self.subagents.reasoning_effort
77
+ if effort != "default" and effort not in profile.reasoning_efforts:
78
+ raise ValueError(f"Unsupported subagents.reasoning_effort for {profile.id}: {effort}")
182
79
  object.__setattr__(self, "sandbox", replace(self.sandbox, trust_env=self.trust_env))
183
80
  object.__setattr__(
184
81
  self, "request_timeout",
@@ -201,20 +98,12 @@ class Settings:
201
98
  def active_profile(self) -> ModelProfile:
202
99
  return self.get_profile(self.llm_default)
203
100
 
101
+ @property
102
+ def model_catalog(self) -> ModelCatalog:
103
+ return ModelCatalog(self.llm_profiles, self.llm_default)
104
+
204
105
  def get_profile(self, id_or_prefix: str) -> ModelProfile:
205
- key = id_or_prefix.strip()
206
- if not key:
207
- raise KeyError("model id is empty")
208
- exact = next((item for item in self.llm_profiles if item.id == key), None)
209
- if exact is not None:
210
- return exact
211
- matches = [item for item in self.llm_profiles if item.id.startswith(key)]
212
- if len(matches) == 1:
213
- return matches[0]
214
- if not matches:
215
- raise KeyError(f"Unknown model: {id_or_prefix}")
216
- ids = ", ".join(item.id for item in matches)
217
- raise KeyError(f"Ambiguous model prefix {id_or_prefix!r}: {ids}")
106
+ return self.model_catalog.get_profile(id_or_prefix)
218
107
 
219
108
  def list_profiles(self) -> tuple[ModelProfile, ...]:
220
109
  return self.llm_profiles
@@ -299,6 +188,7 @@ class Settings:
299
188
  result = cls(
300
189
  trust_env=trust_env,
301
190
  hidden_tools=tuple(dict.fromkeys(name.strip() for name in hidden_tools)),
191
+ subagents=SubAgentConfig.from_mapping(_section(raw, "subagents")),
302
192
  llm_profiles=profiles,
303
193
  llm_default=default_id,
304
194
  sandbox=_sandbox_from_mapping(sandbox_raw, base_dir=root),
@@ -306,6 +196,7 @@ class Settings:
306
196
  config_dir=_optional_path(paths.get("config_dir"), base_dir=root),
307
197
  source_path=source_path.resolve() if source_path is not None else None,
308
198
  agent_instructions=instructions,
199
+ compaction_threshold=agent.get("compaction_threshold", 0.85),
309
200
  ui_timezone=timezone_name,
310
201
  ui_display_limits=display_limits,
311
202
  tavily_api_key=os.environ.get("TAVILY_API_KEY") or _optional_secret(
@@ -735,29 +626,6 @@ def _sandbox_from_mapping(data: Mapping[str, Any], *, base_dir: Path) -> Sandbox
735
626
  )
736
627
 
737
628
 
738
- def _model_max_retries(value: Any, *, field_name: str) -> int:
739
- if value is None:
740
- return 5
741
- if type(value) is not int or value < 0:
742
- raise ValueError(f"{field_name} must be a non-negative integer")
743
- return value
744
-
745
-
746
- def _model_stream_chunk_timeout(value: Any, *, field_name: str) -> float:
747
- """Seconds without a parsed stream chunk before the current model request retries.
748
-
749
- ``0`` disables the idle timeout. ``None`` keeps the 120 second default.
750
- """
751
- if value is None:
752
- return DEFAULT_STREAM_CHUNK_TIMEOUT
753
- if isinstance(value, bool) or not isinstance(value, (int, float)):
754
- raise ValueError(f"{field_name} must be a non-negative number of seconds")
755
- number = float(value)
756
- if not (number >= 0 and number < float("inf")):
757
- raise ValueError(f"{field_name} must be a non-negative number of seconds")
758
- return number
759
-
760
-
761
629
  def _model_request_timeout(value: Any, *, field_name: str) -> float:
762
630
  """Shared HTTP wait for the first response bytes. ``None`` keeps 60 seconds."""
763
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
@@ -12,9 +10,11 @@ from deepagents import (
12
10
  register_harness_profile,
13
11
  )
14
12
  from deepagents.backends.protocol import BackendProtocol, SandboxBackendProtocol
13
+ from deepagents.middleware.subagents import CompiledSubAgent
15
14
  from deepagents.middleware.summarization import (
15
+ SummarizationMiddleware,
16
16
  SummarizationToolMiddleware,
17
- create_summarization_tool_middleware,
17
+ compute_summarization_defaults,
18
18
  )
19
19
  from deepagents._models import get_model_identifier, get_model_provider
20
20
  from langchain.agents.middleware import AgentMiddleware
@@ -22,12 +22,15 @@ from langchain_core.language_models import BaseChatModel
22
22
  from langchain_core.tools import BaseTool
23
23
  from langgraph.checkpoint.memory import InMemorySaver
24
24
 
25
- from agent.config import SandboxConfig, Settings
26
- from agent.control import RunController
27
- from agent.environment import EnvironmentContextMiddleware
28
- from agent.llm import 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
29
30
  from agent.middleware.cancel_tools import ToolCancelMiddleware
31
+ from agent.middleware.current_time import CurrentTimeMiddleware
30
32
  from agent.middleware.attachments import AttachmentMaterializationMiddleware
33
+ from agent.middleware.payload_recovery import PayloadRecoveryMiddleware
31
34
  from agent.middleware.pause import PauseGateMiddleware
32
35
  from agent.middleware.usage import UsageIdentityMiddleware
33
36
  from agent.middleware.recovery import RecoveryContextMiddleware
@@ -35,19 +38,25 @@ from agent.middleware.steering import SteeringMiddleware
35
38
  from agent.middleware.tool_arg_hints import ToolArgHintMiddleware
36
39
  from agent.middleware.write_operation import WriteOperationMiddleware
37
40
  from agent.middleware.workspace_filesystem import WorkspaceFilesystemMiddleware
38
- from agent.permission import (
39
- 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,
40
45
  permission_mode_from_interrupt_on,
41
46
  )
42
- from agent.sandbox import (
43
- BackendSelection, ExecutionMode, SKILLS_ROOT, WorkspaceCompositeBackend, sandbox_pool_of, select_backend,
44
- )
45
- 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
46
51
  from agent.tools.execute import build_execute_tool
47
52
  from agent.tools.human_input import build_human_input_tools
48
53
  from agent.middleware.runtime_config import RuntimeConfigGateMiddleware
49
54
  from agent.tools.web_search import build_web_search_tool
50
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
+
51
60
  DEFAULT_FS_TOOLS = ["ls", "read_file", "write_file", "edit_file", "delete"]
52
61
 
53
62
  DEFAULT_SYSTEM_PROMPT = (
@@ -113,6 +122,8 @@ class AgentSpec:
113
122
  web_search_api_key: str | None = field(default=None, repr=False)
114
123
  hidden_tools: tuple[str, ...] = ()
115
124
  trust_env: bool = False
125
+ role: str = "main"
126
+ settings: Settings | None = field(default=None, repr=False)
116
127
 
117
128
 
118
129
  @dataclass
@@ -136,6 +147,8 @@ class PreparedAgent:
136
147
  sandbox_pool: SandboxPool | None = None
137
148
  skill_sources: tuple[str, ...] = ()
138
149
  model_tool_names: tuple[str, ...] = ()
150
+ subagent_manager: Any = None
151
+ owns_model_clients: bool = False
139
152
 
140
153
 
141
154
  def compose_system_prompt(spec: AgentSpec, model: BaseChatModel, workspace: Path) -> str:
@@ -159,6 +172,7 @@ def build_agent(
159
172
  interrupt_on_override: dict[str, Any] | None = None,
160
173
  backend_selection: BackendSelection | None = None,
161
174
  mcp: Any | None = None,
175
+ settings: Settings | None = None,
162
176
  ) -> PreparedAgent:
163
177
  sandbox_cfg = replace(spec.sandbox or SandboxConfig(), trust_env=spec.trust_env)
164
178
  selected: BackendSelection | None = None
@@ -169,14 +183,15 @@ def build_agent(
169
183
  security_warning = selected.warning
170
184
  else:
171
185
  fs_backend = spec.backend
172
- execution_mode = ExecutionMode.CUSTOM
173
- security_warning = ""
186
+ selected = backend_selection if backend_selection is not None and backend_selection.backend is fs_backend else None
187
+ execution_mode = selected.mode if selected is not None else ExecutionMode.CUSTOM
188
+ security_warning = selected.warning if selected is not None else ""
174
189
  if permission is PermissionMode.ALLOW and execution_mode is not ExecutionMode.SANDBOXED:
175
190
  raise ValueError(allow_mode_unavailable_reason(execution_mode))
176
191
  sandbox_pool = sandbox_pool_of(fs_backend)
177
192
  _disable_general_purpose_task(model)
178
193
  prompt = compose_system_prompt(spec, model, sandbox_cfg.workspace)
179
- tools = [*build_human_input_tools(), *spec.tools]
194
+ tools = [*build_human_input_tools(), *spec.tools] if spec.role == "main" else []
180
195
  if spec.web_search_api_key:
181
196
  tools.append(build_web_search_tool(spec.web_search_api_key, trust_env=spec.trust_env))
182
197
  hitl = dict(interrupt_on_override) if interrupt_on_override is not None else (interrupt_on_for_mode(permission) or {})
@@ -192,11 +207,24 @@ def build_agent(
192
207
  )
193
208
  tools = [tool for tool in tools if tool.name not in spec.hidden_tools]
194
209
  saver = checkpointer if checkpointer is not None else InMemorySaver()
195
- 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)
196
224
  mcp_revision: int | None = None
197
225
  mcp_tools: list[Any] = []
198
226
  include_mcp = False
199
- if mcp is not None:
227
+ if mcp is not None and spec.role == "main":
200
228
  from agent.mcp.middleware import MCPMiddleware, MCP_HOST_PROMPT
201
229
  from agent.mcp.names import host_interrupt_on
202
230
 
@@ -206,9 +234,80 @@ def build_agent(
206
234
  if permission is PermissionMode.ASK:
207
235
  hitl.update(host_interrupt_on(tool.name for tool in mcp_tools))
208
236
  prompt = f"{prompt}\n\n{MCP_HOST_PROMPT}"
237
+ subagents: list[CompiledSubAgent] = []
238
+ manager = None
239
+ if spec.role == "main" and cfg.subagents.enabled:
240
+ from agent.subagents.manager import SubAgentManager
241
+ from agent.subagents.log_store import SubAgentLogStore
242
+ from agent.subagents.runtime import SubAgentRuntime
243
+ from agent.tools.subagent_logs import build_subagent_log_tool
244
+ # Rebuilds occur at a safe boundary; keep lifetime accounting on the
245
+ # parent controller, which survives model changes and session switches.
246
+ manager = getattr(run_controller, "subagent_manager", None)
247
+ if manager is None:
248
+ manager = SubAgentManager(run_controller, cfg.subagents.max_concurrent)
249
+ run_controller.subagent_manager = manager
250
+ manager.max_concurrent = cfg.subagents.max_concurrent
251
+ root = (cfg.config_dir or Path.home() / ".deep-agent") / "subagents"
252
+ store = SubAgentLogStore(root, tuple(p.api_key for p in cfg.llm_profiles) + (spec.web_search_api_key or "",))
253
+ tools.append(build_subagent_log_tool(store))
254
+
255
+ def prepare_child(controller: RunController) -> PreparedAgent:
256
+ if execution_mode is not ExecutionMode.SANDBOXED:
257
+ raise ValueError("Subagents require a verified SANDBOXED backend for allow permission")
258
+ effort = cfg.subagents.reasoning_effort
259
+ effort = None if effort in (None, "default") else effort
260
+ if cfg.subagents.model is not None or isinstance(model, ProtocolChatOpenAI):
261
+ profile = cfg.get_profile(cfg.subagents.model or getattr(model, "_deep_agent_model_id", cfg.llm_default))
262
+ # Each task owns a fresh client. Never inherit the parent's
263
+ # configured effort, including when it uses the same profile.
264
+ child_model = build_chat_model(
265
+ profile, streaming=True, trust_env=cfg.trust_env, timeout=cfg.request_timeout,
266
+ reasoning_effort=effort,
267
+ )
268
+ else:
269
+ # Injected custom models (including scripted test doubles) have
270
+ # no general profile-based reconstruction contract. Keep the
271
+ # supplied object instead of silently selecting cfg.llm_default.
272
+ if effort is not None:
273
+ raise ValueError("A custom BaseChatModel requires subagents.model to override reasoning_effort")
274
+ child_model = model
275
+ child_spec = replace(
276
+ spec, role="subagent", tools=(), backend=fs_backend,
277
+ skills=tuple(skill_sources or ()),
278
+ hidden_tools=tuple(set(spec.hidden_tools) | {"task", "request_human_input", "read_subagent_log"}),
279
+ )
280
+ try:
281
+ child = build_agent(child_spec, child_model, PermissionMode.ALLOW, None,
282
+ controller, lambda: False, backend_selection=selected, settings=cfg)
283
+ except BaseException:
284
+ if child_model is not model:
285
+ from agent.models.stream_lifecycle import close_model_http_clients
286
+ close_model_http_clients(child_model)
287
+ raise
288
+ child.owns_model_clients = child_model is not model
289
+ return child
290
+
291
+ runtime = SubAgentRuntime(manager, store, prepare_child,
292
+ cfg.subagents.model or str(get_model_identifier(model) or type(model).__name__))
293
+ subagents.append({
294
+ "name": "general-purpose",
295
+ "description": (
296
+ "Only delegate when the problem can be decomposed into independent "
297
+ "subproblems that do not interfere with one another. "
298
+ "Complete an isolated coding or research task. "
299
+ "Only the final result is returned. "
300
+ "No MCP, user interaction, or recursive delegation. "
301
+ "Maximum concurrent tasks is configured by the host."
302
+ ),
303
+ "runnable": runtime,
304
+ "mode": "isolated",
305
+ })
306
+ tools = [tool for tool in tools if tool.name not in spec.hidden_tools]
209
307
  try:
210
308
  graph = create_deep_agent(
211
309
  model=model,
310
+ subagents=subagents,
212
311
  tools=tools,
213
312
  system_prompt=prompt,
214
313
  middleware=[
@@ -216,13 +315,16 @@ def build_agent(
216
315
  PauseGateMiddleware(lambda: run_controller.pause_requested or should_pause()),
217
316
  RecoveryContextMiddleware(),
218
317
  EnvironmentContextMiddleware(),
318
+ CurrentTimeMiddleware(cfg.ui_timezone),
219
319
  UsageIdentityMiddleware(),
220
320
  SteeringMiddleware(run_controller),
221
321
  ToolCancelMiddleware(run_controller),
222
322
  ToolArgHintMiddleware(),
223
323
  WriteOperationMiddleware(fs_backend),
224
324
  AttachmentMaterializationMiddleware(),
325
+ PayloadRecoveryMiddleware(),
225
326
  WorkspaceFilesystemMiddleware(backend=fs_backend, tools=filesystem_tools),
327
+ summarization,
226
328
  compact_middleware,
227
329
  *([MCPMiddleware(mcp, mcp_tools)] if include_mcp else []),
228
330
  *([HiddenToolsMiddleware(spec.hidden_tools)] if spec.hidden_tools else []),
@@ -254,6 +356,7 @@ def build_agent(
254
356
  backend_selection=selected,
255
357
  sandbox_pool=sandbox_pool,
256
358
  skill_sources=tuple(skill_sources or ()),
359
+ subagent_manager=manager,
257
360
  )
258
361
 
259
362
  if mcp is not None and mcp_revision is not None:
@@ -279,9 +382,14 @@ def create_agent(
279
382
  sandbox_config: SandboxConfig | None = None,
280
383
  run_controller: RunController | None = None,
281
384
  mcp: Any | None = None,
385
+ role: str = "main",
386
+ backend_selection: BackendSelection | None = None,
282
387
  ) -> PreparedAgent:
283
388
  cfg = settings or Settings()
389
+ if role not in {"main", "subagent"}:
390
+ raise ValueError("Unknown agent role")
284
391
  spec = AgentSpec(
392
+ role=role, settings=cfg,
285
393
  trust_env=cfg.trust_env,
286
394
  instructions=instructions if instructions is not None else cfg.agent_instructions,
287
395
  tools=tuple(extra_tools or ()),
@@ -291,6 +399,8 @@ def create_agent(
291
399
  sandbox=sandbox_config or cfg.sandbox,
292
400
  web_search_api_key=os.environ.get("TAVILY_API_KEY") or cfg.tavily_api_key,
293
401
  )
402
+ if role == "subagent":
403
+ interrupt_on = {}
294
404
  permission = permission_mode_from_interrupt_on(interrupt_on) if interrupt_on is not None else PermissionMode.ASK
295
405
  effective_interrupt_on = interrupt_on
296
406
  if interrupt_on:
@@ -303,7 +413,8 @@ def create_agent(
303
413
  spec, model or _default_model(cfg), permission, checkpointer,
304
414
  run_controller or RunController(), should_pause or (lambda: False),
305
415
  interrupt_on_override=effective_interrupt_on,
306
- mcp=mcp,
416
+ mcp=mcp if role == "main" else None,
417
+ backend_selection=backend_selection,
307
418
  )
308
419
 
309
420
 
@@ -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)