deep-agent-cli 0.2.2__py3-none-any.whl → 0.3.0__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 (90) hide show
  1. agent/bootstrap/config.py +29 -0
  2. agent/bootstrap/factory.py +63 -5
  3. agent/bootstrap/setup.py +36 -6
  4. agent/cli/access_selection.py +1 -1
  5. agent/cli/app.py +272 -126
  6. agent/cli/attachments_controller.py +1 -1
  7. agent/cli/commands.py +24 -7
  8. agent/cli/display.py +2 -2
  9. agent/cli/formatting.py +15 -0
  10. agent/cli/gitinfo.py +2 -2
  11. agent/cli/input_actions.py +6 -1
  12. agent/cli/interactions.py +1 -1
  13. agent/cli/key_bindings.py +34 -16
  14. agent/cli/mcp_ui.py +36 -8
  15. agent/cli/previews.py +48 -43
  16. agent/cli/rendering.py +87 -29
  17. agent/cli/run_dispatch.py +13 -1
  18. agent/cli/run_events_controller.py +8 -0
  19. agent/cli/session_controller.py +1 -4
  20. agent/cli/session_summaries.py +21 -11
  21. agent/cli/state.py +33 -6
  22. agent/cli/text_selection.py +92 -0
  23. agent/cli/transcript_navigation.py +44 -85
  24. agent/cli/widgets.py +189 -4
  25. agent/companion/__init__.py +3 -0
  26. agent/companion/animation.py +47 -0
  27. agent/companion/ascii_art.py +120 -0
  28. agent/companion/assets/lain_concerned.gif +0 -0
  29. agent/companion/assets/lain_curious.gif +0 -0
  30. agent/companion/assets/lain_focused.gif +0 -0
  31. agent/companion/assets/lain_idle.gif +0 -0
  32. agent/companion/assets/lain_observing.gif +0 -0
  33. agent/companion/assets/lain_relieved.gif +0 -0
  34. agent/companion/assets/manifest.json +109 -0
  35. agent/companion/chart.py +98 -0
  36. agent/companion/chat.md +7 -0
  37. agent/companion/config.py +48 -0
  38. agent/companion/controller.py +1160 -0
  39. agent/companion/diagnosis.py +105 -0
  40. agent/companion/diagnostic_io.py +36 -0
  41. agent/companion/evidence.py +36 -0
  42. agent/companion/monitor.py +122 -0
  43. agent/companion/observation.md +13 -0
  44. agent/companion/panel.py +294 -0
  45. agent/companion/persona.md +13 -0
  46. agent/companion/redaction.py +123 -0
  47. agent/companion/repository.py +246 -0
  48. agent/companion/session_inspector.py +491 -0
  49. agent/companion/theme.py +8 -0
  50. agent/companion/timeline.py +478 -0
  51. agent/companion/worker.py +334 -0
  52. agent/config.example.yaml +21 -4
  53. agent/execution/environment.py +18 -2
  54. agent/execution/pool.py +8 -0
  55. agent/execution/process.py +8 -5
  56. agent/execution/service_observation.py +25 -0
  57. agent/execution/worker.py +3 -2
  58. agent/mcp/adapter.py +1 -1
  59. agent/middleware/steering.py +9 -3
  60. agent/middleware/workspace_filesystem.py +58 -3
  61. agent/middleware/write_operation.py +2 -2
  62. agent/models/messages.py +1 -1
  63. agent/models/session_summary.py +1 -2
  64. agent/runtime/contracts.py +8 -0
  65. agent/runtime/control.py +27 -0
  66. agent/runtime/events.py +12 -7
  67. agent/runtime/metrics.py +4 -1
  68. agent/runtime/permissions.py +2 -2
  69. agent/runtime/runner.py +147 -61
  70. agent/sessions/contracts.py +1 -0
  71. agent/sessions/lifecycle.py +15 -5
  72. agent/sessions/reader.py +23 -14
  73. agent/sessions/summary.py +21 -25
  74. agent/sessions/transcript.py +89 -38
  75. agent/subagents/__init__.py +1 -1
  76. agent/subagents/configuration.py +4 -0
  77. agent/subagents/manager.py +104 -13
  78. agent/subagents/notifications.py +39 -0
  79. agent/subagents/runtime.py +60 -10
  80. agent/tools/background_tasks.py +89 -0
  81. agent/tools/execute.py +2 -2
  82. agent/tools/grep.py +1 -1
  83. agent/tools/subagent_logs.py +2 -2
  84. agent/tools/web_search.py +1 -1
  85. {deep_agent_cli-0.2.2.dist-info → deep_agent_cli-0.3.0.dist-info}/METADATA +34 -23
  86. deep_agent_cli-0.3.0.dist-info/RECORD +164 -0
  87. deep_agent_cli-0.2.2.dist-info/RECORD +0 -133
  88. {deep_agent_cli-0.2.2.dist-info → deep_agent_cli-0.3.0.dist-info}/WHEEL +0 -0
  89. {deep_agent_cli-0.2.2.dist-info → deep_agent_cli-0.3.0.dist-info}/entry_points.txt +0 -0
  90. {deep_agent_cli-0.2.2.dist-info → deep_agent_cli-0.3.0.dist-info}/licenses/LICENSE +0 -0
agent/bootstrap/config.py CHANGED
@@ -8,6 +8,8 @@ from typing import Any, Mapping
8
8
  from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
9
9
  import yaml
10
10
 
11
+ from agent.companion import STATES
12
+ from agent.companion.config import CompanionConfig
11
13
  from agent.execution.policy import BindMount, SandboxMode, parse_sandbox_mode, SandboxConfig
12
14
  from agent.subagents.configuration import SubAgentConfig
13
15
  from agent.cli.display import UiDisplayLimits, DEFAULT_UI_TIMEZONE
@@ -60,6 +62,7 @@ class Settings:
60
62
  trust_env: bool = False
61
63
  request_timeout: float = DEFAULT_REQUEST_TIMEOUT
62
64
  compaction_threshold: float = 0.85
65
+ companion: CompanionConfig = field(default_factory=CompanionConfig)
63
66
 
64
67
  def __post_init__(self) -> None:
65
68
  if (isinstance(self.compaction_threshold, bool)
@@ -199,6 +202,7 @@ class Settings:
199
202
  compaction_threshold=agent.get("compaction_threshold", 0.85),
200
203
  ui_timezone=timezone_name,
201
204
  ui_display_limits=display_limits,
205
+ companion=_companion_from_mapping(_section(raw, "companion"), base_dir=root),
202
206
  tavily_api_key=os.environ.get("TAVILY_API_KEY") or _optional_secret(
203
207
  web_search.get("tavily_api_key"), field_name="web_search.tavily_api_key"
204
208
  ),
@@ -283,6 +287,31 @@ def _optional_path(value: Any, *, base_dir: Path) -> Path | None:
283
287
  return path.resolve()
284
288
 
285
289
 
290
+ def _companion_from_mapping(data: Mapping[str, Any], *, base_dir: Path) -> CompanionConfig:
291
+ def path(value: Any, name: str) -> Path | None:
292
+ if value is not None and (not isinstance(value, str) or not value.strip()):
293
+ raise ValueError(f"companion.{name} must be a non-empty path or null")
294
+ return _optional_path(value, base_dir=base_dir)
295
+
296
+ gifs = {}
297
+ for state, value in _section(data, "gifs").items():
298
+ if state not in STATES:
299
+ raise ValueError(f"unknown companion.gifs state: {state}")
300
+ configured = path(value, f"gifs.{state}")
301
+ if configured is not None:
302
+ gifs[state] = configured
303
+ defaults = CompanionConfig()
304
+ return CompanionConfig(
305
+ persona_prompt=path(data.get("persona_prompt"), "persona_prompt") or defaults.persona_prompt,
306
+ observation_prompt=path(data.get("observation_prompt"), "observation_prompt") or defaults.observation_prompt,
307
+ chat_prompt=path(data.get("chat_prompt"), "chat_prompt") or defaults.chat_prompt,
308
+ gifs=gifs,
309
+ rpc_timeout_seconds=data.get("rpc_timeout_seconds", defaults.rpc_timeout_seconds),
310
+ question_timeout_seconds=data.get("question_timeout_seconds", defaults.question_timeout_seconds),
311
+ source_read_lines=data.get("source_read_lines", defaults.source_read_lines),
312
+ )
313
+
314
+
286
315
  def _required_path(value: Any, *, base_dir: Path, default: Path) -> Path:
287
316
  if value is None or value == "":
288
317
  return default.expanduser().resolve()
@@ -10,7 +10,8 @@ from deepagents import (
10
10
  register_harness_profile,
11
11
  )
12
12
  from deepagents.backends.protocol import BackendProtocol, SandboxBackendProtocol
13
- from deepagents.middleware.subagents import CompiledSubAgent
13
+ from deepagents.middleware.subagents import CompiledSubAgent, SubAgentMiddleware
14
+ from deepagents.middleware.skills import SKILLS_SYSTEM_PROMPT, SkillsMiddleware
14
15
  from deepagents.middleware.summarization import (
15
16
  SummarizationMiddleware,
16
17
  SummarizationToolMiddleware,
@@ -19,6 +20,7 @@ from deepagents.middleware.summarization import (
19
20
  from deepagents._models import get_model_identifier, get_model_provider
20
21
  from langchain.agents.middleware import AgentMiddleware
21
22
  from langchain_core.language_models import BaseChatModel
23
+ from langchain_core.messages import AIMessage, AnyMessage
22
24
  from langchain_core.tools import BaseTool
23
25
  from langgraph.checkpoint.memory import InMemorySaver
24
26
 
@@ -57,7 +59,7 @@ from agent.tools.web_search import build_web_search_tool
57
59
  # Middleware augments the Deep Agents defaults; create_deep_agent remains the only assembly entry.
58
60
 
59
61
 
60
- DEFAULT_FS_TOOLS = ["ls", "read_file", "write_file", "edit_file", "delete"]
62
+ DEFAULT_FS_TOOLS = ["ls", "read", "write", "edit", "delete"]
61
63
 
62
64
  DEFAULT_SYSTEM_PROMPT = (
63
65
  "你是运行在 Deep Agent CLI 中、使用 {model_name} 的编程智能体。"
@@ -92,6 +94,47 @@ DEFAULT_SYSTEM_PROMPT = (
92
94
  )
93
95
 
94
96
 
97
+ class StartTaskMiddleware(SubAgentMiddleware):
98
+ @property
99
+ def name(self) -> str:
100
+ return "SubAgentMiddleware"
101
+
102
+ def __init__(self, **kwargs: Any) -> None:
103
+ super().__init__(**kwargs)
104
+ self.tools[0].name = "start_task"
105
+
106
+ @SubAgentMiddleware.private_state_keys.setter
107
+ def private_state_keys(self, value: frozenset[str]) -> None:
108
+ # create_deep_agent rebuilds the native tool after collecting state keys.
109
+ SubAgentMiddleware.private_state_keys.fset(self, value)
110
+ self.tools[0].name = "start_task"
111
+
112
+
113
+ class WorkspaceSummarizationMiddleware(SummarizationMiddleware):
114
+ def _truncate_args(
115
+ self, messages: list[AnyMessage], total_tokens: int,
116
+ ) -> tuple[list[AnyMessage], bool]:
117
+ """Keep upstream argument truncation for the renamed write and edit tools."""
118
+ if not self._should_truncate_args(messages, total_tokens):
119
+ return messages, False
120
+ cutoff = self._determine_truncate_cutoff_index(messages)
121
+ if cutoff >= len(messages):
122
+ return messages, False
123
+ updated = list(messages)
124
+ modified = False
125
+ for index, message in enumerate(messages[:cutoff]):
126
+ if not isinstance(message, AIMessage):
127
+ continue
128
+ calls = [
129
+ self._truncate_tool_call(call) if call["name"] in {"write", "edit"} else call
130
+ for call in message.tool_calls
131
+ ]
132
+ if calls != message.tool_calls:
133
+ updated[index] = message.model_copy(update={"tool_calls": calls})
134
+ modified = True
135
+ return (updated, True) if modified else (messages, False)
136
+
137
+
95
138
  class HiddenToolsMiddleware(AgentMiddleware):
96
139
  """Filter middleware-provided tools too, without changing approval rules."""
97
140
 
@@ -215,7 +258,7 @@ def build_agent(
215
258
  trigger = ("fraction", min(trigger[1], cfg.compaction_threshold))
216
259
  if keep[0] == "fraction" and keep[1] >= trigger[1]:
217
260
  keep = ("fraction", trigger[1] / 2)
218
- summarization = SummarizationMiddleware(
261
+ summarization = WorkspaceSummarizationMiddleware(
219
262
  model=model, backend=fs_backend, trigger=trigger,
220
263
  keep=keep, trim_tokens_to_summarize=None,
221
264
  truncate_args_settings=summary_defaults["truncate_args_settings"],
@@ -240,6 +283,8 @@ def build_agent(
240
283
  from agent.subagents.manager import SubAgentManager
241
284
  from agent.subagents.log_store import SubAgentLogStore
242
285
  from agent.subagents.runtime import SubAgentRuntime
286
+ from agent.subagents.notifications import BACKGROUND_TOOLS
287
+ from agent.tools.background_tasks import build_background_task_tools
243
288
  from agent.tools.subagent_logs import build_subagent_log_tool
244
289
  # Rebuilds occur at a safe boundary; keep lifetime accounting on the
245
290
  # parent controller, which survives model changes and session switches.
@@ -275,7 +320,8 @@ def build_agent(
275
320
  child_spec = replace(
276
321
  spec, role="subagent", tools=(), backend=fs_backend,
277
322
  skills=tuple(skill_sources or ()),
278
- hidden_tools=tuple(set(spec.hidden_tools) | {"task", "request_human_input", "read_subagent_log"}),
323
+ hidden_tools=tuple(set(spec.hidden_tools) | BACKGROUND_TOOLS
324
+ | {"start_task", "request_human_input", "read_task_log"}),
279
325
  )
280
326
  try:
281
327
  child = build_agent(child_spec, child_model, PermissionMode.ALLOW, None,
@@ -289,7 +335,14 @@ def build_agent(
289
335
  return child
290
336
 
291
337
  runtime = SubAgentRuntime(manager, store, prepare_child,
292
- cfg.subagents.model or str(get_model_identifier(model) or type(model).__name__))
338
+ cfg.subagents.model or str(get_model_identifier(model) or type(model).__name__),
339
+ cfg.subagents.reasoning_effort or "default")
340
+ if cfg.subagents.background:
341
+ tools.extend(build_background_task_tools(
342
+ runtime, manager,
343
+ unavailable="" if execution_mode is ExecutionMode.SANDBOXED
344
+ else "Subagents require a verified SANDBOXED backend for allow permission",
345
+ ))
293
346
  subagents.append({
294
347
  "name": "general-purpose",
295
348
  "description": (
@@ -324,6 +377,11 @@ def build_agent(
324
377
  AttachmentMaterializationMiddleware(),
325
378
  PayloadRecoveryMiddleware(),
326
379
  WorkspaceFilesystemMiddleware(backend=fs_backend, tools=filesystem_tools),
380
+ *([StartTaskMiddleware(backend=fs_backend, subagents=subagents)] if subagents else []),
381
+ *([SkillsMiddleware(
382
+ backend=fs_backend, sources=skill_sources,
383
+ system_prompt=SKILLS_SYSTEM_PROMPT.replace("read_file", "read"),
384
+ )] if skill_sources else []),
327
385
  summarization,
328
386
  compact_middleware,
329
387
  *([MCPMiddleware(mcp, mcp_tools)] if include_mcp else []),
agent/bootstrap/setup.py CHANGED
@@ -3,11 +3,12 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
- from importlib.resources import files
6
+ from importlib.resources import abc, files
7
7
  from pathlib import Path
8
8
  import tempfile
9
9
 
10
10
  from agent.bootstrap.config import default_skills_dir, require_outside_workspace
11
+ from agent.companion import STATES
11
12
 
12
13
 
13
14
  def initialize_user_files(*, workspace: Path | None = None) -> Path | None:
@@ -24,22 +25,51 @@ def initialize_user_files(*, workspace: Path | None = None) -> Path | None:
24
25
  skills.mkdir(mode=0o700, exist_ok=True)
25
26
  if os.environ.get("DEEP_AGENT_CONFIG"):
26
27
  return None
28
+ # Creating config.yaml and filling missing companion prompts/GIFs are
29
+ # independent: an older config must still receive newly required assets.
30
+ initialize_companion_files(root)
27
31
  if config.exists() or config.is_symlink():
28
32
  if not config.is_file():
29
33
  raise ValueError(f"configuration path must be a file: {config}")
30
34
  return None
31
35
  template = files("agent").joinpath("config.example.yaml")
32
- with tempfile.NamedTemporaryFile(mode="wb", dir=root, prefix=".config-", delete=False) as temporary:
36
+ return config if _write_default(config, template) else None
37
+
38
+
39
+ def initialize_companion_files(config_dir: Path) -> None:
40
+ source = files("agent.companion")
41
+ companion_dir = config_dir / "companion"
42
+ prompts = companion_dir / "prompts"
43
+ gifs = companion_dir / "gifs"
44
+ for directory in (companion_dir, prompts, gifs):
45
+ if directory.is_symlink():
46
+ raise ValueError(f"Companion directory must not be a symlink: {directory}")
47
+ directory.mkdir(mode=0o700, exist_ok=True)
48
+ for name in ("persona.md", "observation.md", "chat.md"):
49
+ _write_default(prompts / name, source.joinpath(name))
50
+ for state in STATES:
51
+ name = f"lain_{state}.gif"
52
+ _write_default(gifs / name, source.joinpath("assets", name))
53
+
54
+
55
+ def _write_default(destination: Path, source: abc.Traversable) -> bool:
56
+ if destination.exists() or destination.is_symlink():
57
+ if not destination.is_file():
58
+ raise ValueError(f"configuration asset must be a file: {destination}")
59
+ return False
60
+ with tempfile.NamedTemporaryFile(mode="wb", dir=destination.parent, prefix=".config-", delete=False) as temporary:
33
61
  temp_path = Path(temporary.name)
34
62
  try:
35
63
  os.chmod(temp_path, 0o600)
36
- temporary.write(template.read_bytes())
64
+ temporary.write(source.read_bytes())
37
65
  temporary.flush()
38
66
  os.fsync(temporary.fileno())
39
67
  try:
40
- os.link(temp_path, config)
68
+ os.link(temp_path, destination)
41
69
  except FileExistsError:
42
- return None
70
+ if not destination.is_file():
71
+ raise ValueError(f"configuration asset must be a file: {destination}") from None
72
+ return False
43
73
  finally:
44
74
  temp_path.unlink(missing_ok=True)
45
- return config
75
+ return True
@@ -158,7 +158,7 @@ class AccessSelection:
158
158
  self.state.add_system("Sandbox mount policy is not available for this backend.", error=True)
159
159
  return
160
160
  skills = getattr(backend, "skills_dir", None)
161
- self.state.add_system(render_launch_manifest(
161
+ self.state.add_command_panel("/sandbox mounts", render_launch_manifest(
162
162
  config, skills_dir=skills, pending_mode=self.runner.pending_sandbox_mode(),
163
163
  ))
164
164
  self.invalidate()