zjcode 0.0.1__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 (163) hide show
  1. deepagents_code/__init__.py +42 -0
  2. deepagents_code/__main__.py +6 -0
  3. deepagents_code/_ask_user_types.py +90 -0
  4. deepagents_code/_cli_context.py +96 -0
  5. deepagents_code/_constants.py +41 -0
  6. deepagents_code/_debug.py +148 -0
  7. deepagents_code/_debug_buffer.py +204 -0
  8. deepagents_code/_env_vars.py +411 -0
  9. deepagents_code/_fake_models.py +66 -0
  10. deepagents_code/_git.py +521 -0
  11. deepagents_code/_paths.py +69 -0
  12. deepagents_code/_server_config.py +576 -0
  13. deepagents_code/_session_stats.py +235 -0
  14. deepagents_code/_startup_error.py +45 -0
  15. deepagents_code/_testing_models.py +305 -0
  16. deepagents_code/_textual_patches.py +420 -0
  17. deepagents_code/_tool_stream.py +694 -0
  18. deepagents_code/_version.py +46 -0
  19. deepagents_code/agent.py +1976 -0
  20. deepagents_code/app.py +19239 -0
  21. deepagents_code/app.tcss +438 -0
  22. deepagents_code/approval_mode.py +131 -0
  23. deepagents_code/ask_user.py +306 -0
  24. deepagents_code/auth_display.py +185 -0
  25. deepagents_code/auth_store.py +545 -0
  26. deepagents_code/built_in_skills/__init__.py +5 -0
  27. deepagents_code/built_in_skills/remember/SKILL.md +118 -0
  28. deepagents_code/built_in_skills/skill-creator/SKILL.md +383 -0
  29. deepagents_code/built_in_skills/skill-creator/scripts/init_skill.py +366 -0
  30. deepagents_code/built_in_skills/skill-creator/scripts/quick_validate.py +158 -0
  31. deepagents_code/client/__init__.py +1 -0
  32. deepagents_code/client/commands/__init__.py +1 -0
  33. deepagents_code/client/commands/auth.py +541 -0
  34. deepagents_code/client/commands/config.py +714 -0
  35. deepagents_code/client/commands/mcp.py +250 -0
  36. deepagents_code/client/commands/tools.py +416 -0
  37. deepagents_code/client/launch/__init__.py +1 -0
  38. deepagents_code/client/launch/server.py +978 -0
  39. deepagents_code/client/launch/server_manager.py +540 -0
  40. deepagents_code/client/non_interactive.py +1758 -0
  41. deepagents_code/client/remote_client.py +794 -0
  42. deepagents_code/clipboard.py +217 -0
  43. deepagents_code/command_registry.py +450 -0
  44. deepagents_code/config.py +4829 -0
  45. deepagents_code/config_manifest.py +1451 -0
  46. deepagents_code/configurable_model.py +577 -0
  47. deepagents_code/default_agent_prompt.md +12 -0
  48. deepagents_code/doctor.py +559 -0
  49. deepagents_code/editor.py +142 -0
  50. deepagents_code/event_bus.py +411 -0
  51. deepagents_code/extras_info.py +661 -0
  52. deepagents_code/file_ops.py +576 -0
  53. deepagents_code/formatting.py +135 -0
  54. deepagents_code/goal_rubric.py +497 -0
  55. deepagents_code/goal_tools.py +459 -0
  56. deepagents_code/hooks.py +348 -0
  57. deepagents_code/input.py +1041 -0
  58. deepagents_code/integrations/__init__.py +1 -0
  59. deepagents_code/integrations/openai_codex.py +551 -0
  60. deepagents_code/integrations/sandbox_config.py +198 -0
  61. deepagents_code/integrations/sandbox_factory.py +1124 -0
  62. deepagents_code/integrations/sandbox_provider.py +137 -0
  63. deepagents_code/integrations/sandbox_registry.py +350 -0
  64. deepagents_code/iterm_cursor_guide.py +176 -0
  65. deepagents_code/local_context.py +926 -0
  66. deepagents_code/main.py +3985 -0
  67. deepagents_code/managed_tools.py +642 -0
  68. deepagents_code/mcp_auth.py +1950 -0
  69. deepagents_code/mcp_config.py +176 -0
  70. deepagents_code/mcp_disabled.py +212 -0
  71. deepagents_code/mcp_login_service.py +281 -0
  72. deepagents_code/mcp_oauth_ui.py +199 -0
  73. deepagents_code/mcp_providers/__init__.py +23 -0
  74. deepagents_code/mcp_providers/_registry.py +39 -0
  75. deepagents_code/mcp_providers/base.py +133 -0
  76. deepagents_code/mcp_providers/github.py +102 -0
  77. deepagents_code/mcp_providers/slack.py +175 -0
  78. deepagents_code/mcp_tools.py +2427 -0
  79. deepagents_code/mcp_trust.py +207 -0
  80. deepagents_code/media_utils.py +826 -0
  81. deepagents_code/memory_guard.py +474 -0
  82. deepagents_code/model_config.py +4156 -0
  83. deepagents_code/notifications.py +247 -0
  84. deepagents_code/offload.py +402 -0
  85. deepagents_code/onboarding.py +223 -0
  86. deepagents_code/output.py +69 -0
  87. deepagents_code/paste_collapse.py +103 -0
  88. deepagents_code/project_utils.py +231 -0
  89. deepagents_code/py.typed +0 -0
  90. deepagents_code/reasoning_effort.py +641 -0
  91. deepagents_code/reliable_rubric.py +97 -0
  92. deepagents_code/resume_state.py +237 -0
  93. deepagents_code/server_graph.py +310 -0
  94. deepagents_code/session_end_summary.py +329 -0
  95. deepagents_code/sessions.py +1716 -0
  96. deepagents_code/skills/__init__.py +18 -0
  97. deepagents_code/skills/commands.py +1252 -0
  98. deepagents_code/skills/invocation.py +112 -0
  99. deepagents_code/skills/load.py +196 -0
  100. deepagents_code/skills/trust.py +547 -0
  101. deepagents_code/state_migration.py +136 -0
  102. deepagents_code/subagents.py +278 -0
  103. deepagents_code/system_prompt.md +204 -0
  104. deepagents_code/terminal_capabilities.py +115 -0
  105. deepagents_code/terminal_escape.py +287 -0
  106. deepagents_code/theme.py +891 -0
  107. deepagents_code/todo_list_prompt.md +12 -0
  108. deepagents_code/tool_catalog.py +509 -0
  109. deepagents_code/tool_display.py +367 -0
  110. deepagents_code/tools.py +516 -0
  111. deepagents_code/tui/__init__.py +1 -0
  112. deepagents_code/tui/textual_adapter.py +2553 -0
  113. deepagents_code/tui/widgets/__init__.py +9 -0
  114. deepagents_code/tui/widgets/_js_eval_display.py +139 -0
  115. deepagents_code/tui/widgets/_links.py +261 -0
  116. deepagents_code/tui/widgets/agent_selector.py +420 -0
  117. deepagents_code/tui/widgets/approval.py +602 -0
  118. deepagents_code/tui/widgets/ask_user.py +515 -0
  119. deepagents_code/tui/widgets/auth.py +1997 -0
  120. deepagents_code/tui/widgets/autocomplete.py +890 -0
  121. deepagents_code/tui/widgets/chat_input.py +3181 -0
  122. deepagents_code/tui/widgets/codex_auth.py +452 -0
  123. deepagents_code/tui/widgets/cwd_switch.py +242 -0
  124. deepagents_code/tui/widgets/debug_console.py +868 -0
  125. deepagents_code/tui/widgets/diff.py +252 -0
  126. deepagents_code/tui/widgets/effort_selector.py +189 -0
  127. deepagents_code/tui/widgets/goal_review.py +390 -0
  128. deepagents_code/tui/widgets/goal_status.py +50 -0
  129. deepagents_code/tui/widgets/history.py +194 -0
  130. deepagents_code/tui/widgets/install_confirm.py +248 -0
  131. deepagents_code/tui/widgets/launch_init.py +482 -0
  132. deepagents_code/tui/widgets/loading.py +227 -0
  133. deepagents_code/tui/widgets/mcp_login.py +539 -0
  134. deepagents_code/tui/widgets/mcp_reconnect.py +212 -0
  135. deepagents_code/tui/widgets/mcp_viewer.py +1634 -0
  136. deepagents_code/tui/widgets/message_store.py +999 -0
  137. deepagents_code/tui/widgets/messages.py +3846 -0
  138. deepagents_code/tui/widgets/model_selector.py +2343 -0
  139. deepagents_code/tui/widgets/notification_center.py +456 -0
  140. deepagents_code/tui/widgets/notification_detail.py +257 -0
  141. deepagents_code/tui/widgets/notification_settings.py +170 -0
  142. deepagents_code/tui/widgets/restart_prompt.py +158 -0
  143. deepagents_code/tui/widgets/skill_trust.py +131 -0
  144. deepagents_code/tui/widgets/startup_tip.py +91 -0
  145. deepagents_code/tui/widgets/status.py +781 -0
  146. deepagents_code/tui/widgets/subagent_panel.py +969 -0
  147. deepagents_code/tui/widgets/theme_selector.py +401 -0
  148. deepagents_code/tui/widgets/thread_selector.py +2564 -0
  149. deepagents_code/tui/widgets/tool_renderers.py +190 -0
  150. deepagents_code/tui/widgets/tool_widgets.py +304 -0
  151. deepagents_code/tui/widgets/update_available.py +311 -0
  152. deepagents_code/tui/widgets/update_confirm.py +184 -0
  153. deepagents_code/tui/widgets/update_progress.py +327 -0
  154. deepagents_code/tui/widgets/welcome.py +508 -0
  155. deepagents_code/turn_end_summary.py +522 -0
  156. deepagents_code/ui.py +858 -0
  157. deepagents_code/unicode_security.py +563 -0
  158. deepagents_code/update_check.py +3124 -0
  159. zjcode-0.0.1.data/data/deepagents_code/default_agent_prompt.md +12 -0
  160. zjcode-0.0.1.dist-info/METADATA +220 -0
  161. zjcode-0.0.1.dist-info/RECORD +163 -0
  162. zjcode-0.0.1.dist-info/WHEEL +4 -0
  163. zjcode-0.0.1.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,926 @@
1
+ """Middleware for injecting local context into system prompt.
2
+
3
+ Detects git state, project structure, package managers, runtimes, and
4
+ directory layout by running a bash script via the backend. Because the
5
+ script executes inside the backend (local shell or remote sandbox), the
6
+ same detection logic works regardless of where the agent runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import logging
14
+ from typing import (
15
+ TYPE_CHECKING,
16
+ Annotated,
17
+ Any,
18
+ NotRequired,
19
+ Protocol,
20
+ cast,
21
+ runtime_checkable,
22
+ )
23
+
24
+ from langchain.agents.middleware.types import (
25
+ AgentMiddleware,
26
+ AgentState,
27
+ ModelRequest,
28
+ ModelResponse,
29
+ PrivateStateAttr,
30
+ )
31
+
32
+ from deepagents_code.unicode_security import sanitize_control_chars
33
+
34
+ if TYPE_CHECKING:
35
+ from collections.abc import Awaitable, Callable
36
+
37
+ from deepagents.backends.protocol import ExecuteResponse
38
+ from deepagents.middleware.summarization import SummarizationEvent
39
+ from langgraph.runtime import Runtime
40
+
41
+ from deepagents_code.mcp_tools import MCPServerInfo
42
+
43
+
44
+ _TOOL_NAME_DISPLAY_LIMIT = 10
45
+ """Maximum number of tool names shown per MCP server in the system prompt."""
46
+
47
+ _DETECT_SCRIPT_TIMEOUT = 30
48
+ """Timeout in seconds for the environment detection script."""
49
+
50
+ _MCP_ERROR_DETAIL_LIMIT = 200
51
+ """Max characters of an MCP server error surfaced in the system prompt."""
52
+
53
+ _TRACING_PROJECT_NAME_LIMIT = 200
54
+ """Max characters of a LangSmith project name surfaced in the system prompt."""
55
+
56
+
57
+ def _sanitize_error_detail(error: str | None) -> str:
58
+ """Make an untrusted MCP error string safe to embed in the system prompt.
59
+
60
+ The error originates from exception text or MCP config-file contents, so it
61
+ is untrusted input flowing into the system prompt (prompt-injection and
62
+ log-forging risk). Strip hidden/deceptive Unicode, flatten control
63
+ characters and newlines to spaces so the value cannot break out of its
64
+ single bullet line or inject fake instruction lines, collapse runs of
65
+ whitespace, and bound the length.
66
+
67
+ Args:
68
+ error: Raw error message, or `None`.
69
+
70
+ Returns:
71
+ A single-line, length-bounded, sanitized string. Falls back to
72
+ `"unknown error"` when no usable message remains.
73
+ """
74
+ if not error:
75
+ return "unknown error"
76
+ sanitized = sanitize_control_chars(error, max_length=_MCP_ERROR_DETAIL_LIMIT)
77
+ return sanitized or "unknown error"
78
+
79
+
80
+ def _sanitize_tracing_project_name(project: str) -> str:
81
+ """Make an untrusted LangSmith project name safe for the system prompt.
82
+
83
+ Project names can originate from a workspace `.env` file or process
84
+ environment. Flatten hidden/control characters and bound the length before
85
+ embedding them in prompt bullets so a crafted value cannot inject extra
86
+ prompt lines.
87
+
88
+ Args:
89
+ project: Raw LangSmith project name.
90
+
91
+ Returns:
92
+ A single-line, length-bounded, sanitized project name. Falls back to
93
+ `"unknown project"` when no usable text remains.
94
+ """
95
+ sanitized = sanitize_control_chars(project, max_length=_TRACING_PROJECT_NAME_LIMIT)
96
+ return sanitized or "unknown project"
97
+
98
+
99
+ def _quote_tracing_project_name(project: str) -> str:
100
+ """JSON-quote a sanitized LangSmith project name for prompt insertion.
101
+
102
+ Args:
103
+ project: Sanitized LangSmith project name.
104
+
105
+ Returns:
106
+ JSON string literal for the project name.
107
+ """
108
+ return json.dumps(project, ensure_ascii=False)
109
+
110
+
111
+ def _build_mcp_context(servers: list[MCPServerInfo]) -> str:
112
+ """Format MCP server/tool inventory for the system prompt.
113
+
114
+ Args:
115
+ servers: List of connected MCP server metadata.
116
+
117
+ Returns:
118
+ Formatted markdown string, or `""` if no servers.
119
+ """
120
+ if not servers:
121
+ return ""
122
+
123
+ total_tools = sum(len(s.tools) for s in servers)
124
+ lines = [f"**MCP Servers** ({len(servers)} servers, {total_tools} tools):"]
125
+
126
+ for server in servers:
127
+ if not server.tools:
128
+ # `status`/`error` always exist on the frozen dataclass; the
129
+ # `__post_init__` invariant guarantees a non-`ok` status carries a
130
+ # non-`None` error. The error is untrusted (exception/config text),
131
+ # so it is sanitized and isolated in an `<error>` delimiter before
132
+ # reaching the prompt.
133
+ if server.status == "error":
134
+ detail = _sanitize_error_detail(server.error)
135
+ lines.append(
136
+ f"- **{server.name}** ({server.transport}): "
137
+ f"FAILED TO LOAD — <error>{detail}</error>. "
138
+ "Treat this integration as temporarily unavailable; "
139
+ "tell the user the server failed to load and suggest "
140
+ "restarting the MCP server."
141
+ )
142
+ elif server.status == "unauthenticated":
143
+ detail = _sanitize_error_detail(server.error)
144
+ lines.append(
145
+ f"- **{server.name}** ({server.transport}): "
146
+ f"NEEDS LOGIN — <error>{detail}</error>. "
147
+ "This integration requires authentication before its "
148
+ "tools are available; tell the user and suggest running "
149
+ "`/mcp` to log in."
150
+ )
151
+ elif server.status == "disabled":
152
+ lines.append(
153
+ f"- **{server.name}** ({server.transport}): (disabled by user)"
154
+ )
155
+ else:
156
+ # `ok` with no tools (genuinely empty). `awaiting_reconnect` is a
157
+ # transient UI-only status that never reaches this function (the
158
+ # middleware is always built from a fresh preload), but it would
159
+ # also render benignly here.
160
+ lines.append(
161
+ f"- **{server.name}** ({server.transport}): (no tools registered)"
162
+ )
163
+ continue
164
+
165
+ names = [t.name for t in server.tools]
166
+ if len(names) > _TOOL_NAME_DISPLAY_LIMIT:
167
+ shown = ", ".join(names[:_TOOL_NAME_DISPLAY_LIMIT])
168
+ remaining = len(names) - _TOOL_NAME_DISPLAY_LIMIT
169
+ lines.append(
170
+ f"- **{server.name}** ({server.transport}): "
171
+ f"{shown}, and {remaining} more"
172
+ )
173
+ else:
174
+ lines.append(
175
+ f"- **{server.name}** ({server.transport}): {', '.join(names)}"
176
+ )
177
+
178
+ return "\n".join(lines)
179
+
180
+
181
+ def _build_tracing_context(
182
+ agent_project: str | None,
183
+ user_project: str | None,
184
+ ) -> str:
185
+ """Format LangSmith tracing project names for the system prompt.
186
+
187
+ Surfaces both projects so the agent can look up the right traces with the
188
+ LangSmith MCP server or CLI: the project its own runs are traced to, and
189
+ the user's original project that shell commands trace to. The
190
+ shell-command line is shown only when the user's project differs from the
191
+ agent's (after sanitizing both), avoiding a redundant duplicate line.
192
+
193
+ Args:
194
+ agent_project: Project receiving the agent's own traces, or `None`
195
+ when LangSmith tracing is not enabled.
196
+ user_project: User's original `LANGSMITH_PROJECT`, used by code the
197
+ agent runs in the shell.
198
+
199
+ Returns:
200
+ Formatted markdown string, or `""` when tracing is disabled.
201
+ """
202
+ if not agent_project:
203
+ return ""
204
+
205
+ safe_agent_project = _sanitize_tracing_project_name(agent_project)
206
+ quoted_agent_project = _quote_tracing_project_name(safe_agent_project)
207
+ lines = [
208
+ "**LangSmith Tracing**:",
209
+ f"- Agent traces: project {quoted_agent_project}",
210
+ ]
211
+ if user_project:
212
+ safe_user_project = _sanitize_tracing_project_name(user_project)
213
+ if safe_user_project != safe_agent_project:
214
+ quoted_user_project = _quote_tracing_project_name(safe_user_project)
215
+ lines.append(f"- Shell-command traces: project {quoted_user_project}")
216
+ return "\n".join(lines)
217
+
218
+
219
+ @runtime_checkable
220
+ class _ExecutableBackend(Protocol):
221
+ """Any backend that supports `execute(command) -> ExecuteResponse`."""
222
+
223
+ def execute(
224
+ self, command: str, *, timeout: int | None = None
225
+ ) -> ExecuteResponse: ...
226
+
227
+
228
+ @runtime_checkable
229
+ class _AsyncExecutableBackend(Protocol):
230
+ """Any backend that provides an async `aexecute` method."""
231
+
232
+ async def aexecute(
233
+ self,
234
+ command: str,
235
+ *,
236
+ timeout: int | None = None, # noqa: ASYNC109 # Timeout is forwarded to backend, not used as asyncio timeout
237
+ ) -> ExecuteResponse: ...
238
+
239
+
240
+ logger = logging.getLogger(__name__)
241
+
242
+
243
+ # ---------------------------------------------------------------------------
244
+ # Context detection script
245
+ #
246
+ # Outputs markdown describing the current working environment. Each section
247
+ # is guarded so that missing tools or unsupported environments are silently
248
+ # skipped -- external tools like git, tree, python3, and node are checked
249
+ # with `command -v` before use.
250
+ #
251
+ # The script is built from section functions so each piece can be tested
252
+ # independently. Independent sections run as parallel background subshells;
253
+ # see build_detect_script() for the orchestration logic.
254
+ # ---------------------------------------------------------------------------
255
+
256
+
257
+ def _section_header() -> str:
258
+ """CWD line and IN_GIT flag (used by other sections).
259
+
260
+ Returns:
261
+ Bash snippet that prints the header and sets `CWD` / `IN_GIT`.
262
+ """
263
+ return r"""CWD="$(pwd)"
264
+ echo "## Local Context"
265
+ echo ""
266
+ echo "**Current Directory**: \`${CWD}\`"
267
+ echo ""
268
+
269
+ # --- Check git once ---
270
+ IN_GIT=false
271
+ if command -v git >/dev/null 2>&1 \
272
+ && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
273
+ IN_GIT=true
274
+ fi"""
275
+
276
+
277
+ def _section_project() -> str:
278
+ """Language, monorepo, git root, virtual-env detection.
279
+
280
+ Returns:
281
+ Bash snippet (requires `CWD` / `IN_GIT` from header).
282
+ """
283
+ return r"""# --- Project ---
284
+ PROJ_LANG=""
285
+ [ -f pyproject.toml ] || [ -f setup.py ] && PROJ_LANG="python"
286
+ [ -z "$PROJ_LANG" ] && [ -f package.json ] && PROJ_LANG="javascript/typescript"
287
+ [ -z "$PROJ_LANG" ] && [ -f Cargo.toml ] && PROJ_LANG="rust"
288
+ [ -z "$PROJ_LANG" ] && [ -f go.mod ] && PROJ_LANG="go"
289
+ [ -z "$PROJ_LANG" ] && { [ -f pom.xml ] || [ -f build.gradle ]; } && PROJ_LANG="java"
290
+
291
+ MONOREPO=false
292
+ { [ -f lerna.json ] || [ -f pnpm-workspace.yaml ] \
293
+ || [ -d packages ] || { [ -d libs ] && [ -d apps ]; } \
294
+ || [ -d workspaces ]; } && MONOREPO=true
295
+
296
+ ROOT=""
297
+ $IN_GIT && ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
298
+
299
+ ENVS=""
300
+ { [ -d .venv ] || [ -d venv ]; } && ENVS=".venv"
301
+ [ -d node_modules ] && ENVS="${ENVS:+${ENVS}, }node_modules"
302
+
303
+ HAS_PROJECT=false
304
+ { [ -n "$PROJ_LANG" ] || { [ -n "$ROOT" ] && [ "$ROOT" != "$CWD" ]; } \
305
+ || $MONOREPO || [ -n "$ENVS" ]; } && HAS_PROJECT=true
306
+
307
+ if $HAS_PROJECT; then
308
+ echo "**Project**:"
309
+ [ -n "$PROJ_LANG" ] && echo "- Language: ${PROJ_LANG}"
310
+ [ -n "$ROOT" ] && [ "$ROOT" != "$CWD" ] && echo "- Project root: \`${ROOT}\`"
311
+ $MONOREPO && echo "- Monorepo: yes"
312
+ [ -n "$ENVS" ] && echo "- Environments: ${ENVS}"
313
+ echo ""
314
+ fi"""
315
+
316
+
317
+ def _section_package_managers() -> str:
318
+ """Python and Node package manager detection.
319
+
320
+ Returns:
321
+ Bash snippet (standalone).
322
+ """
323
+ return r"""# --- Package managers ---
324
+ PKG=""
325
+ if [ -f uv.lock ]; then PKG="Python: uv"
326
+ elif [ -f poetry.lock ]; then PKG="Python: poetry"
327
+ elif [ -f Pipfile.lock ] || [ -f Pipfile ]; then PKG="Python: pipenv"
328
+ elif [ -f pyproject.toml ]; then
329
+ if grep -q '\[tool\.uv\]' pyproject.toml 2>/dev/null; then PKG="Python: uv"
330
+ elif grep -q '\[tool\.poetry\]' pyproject.toml 2>/dev/null; then PKG="Python: poetry"
331
+ else PKG="Python: pip"
332
+ fi
333
+ elif [ -f requirements.txt ]; then PKG="Python: pip"
334
+ fi
335
+
336
+ NODE_PKG=""
337
+ if [ -f bun.lockb ] || [ -f bun.lock ]; then NODE_PKG="Node: bun"
338
+ elif [ -f pnpm-lock.yaml ]; then NODE_PKG="Node: pnpm"
339
+ elif [ -f yarn.lock ]; then NODE_PKG="Node: yarn"
340
+ elif [ -f package-lock.json ] || [ -f package.json ]; then NODE_PKG="Node: npm"
341
+ fi
342
+ [ -n "$NODE_PKG" ] && PKG="${PKG:+${PKG}, }${NODE_PKG}"
343
+ [ -n "$PKG" ] && echo "**Package Manager**: ${PKG}" && echo ""
344
+ """
345
+
346
+
347
+ def _section_runtimes() -> str:
348
+ """Python and Node runtime version detection.
349
+
350
+ Returns:
351
+ Bash snippet (standalone).
352
+ """
353
+ return r"""# --- Runtimes ---
354
+ RT=""
355
+ if command -v python3 >/dev/null 2>&1; then
356
+ PV="$(python3 --version 2>/dev/null | awk '{print $2}')"
357
+ [ -n "$PV" ] && RT="Python ${PV}"
358
+ fi
359
+ if command -v node >/dev/null 2>&1; then
360
+ NV="$(node --version 2>/dev/null | sed 's/^v//')"
361
+ [ -n "$NV" ] && RT="${RT:+${RT}, }Node ${NV}"
362
+ fi
363
+ [ -n "$RT" ] && echo "**Detected Runtimes**: ${RT}" && echo ""
364
+ """
365
+
366
+
367
+ def _section_git() -> str:
368
+ """Git branch or detached HEAD commit, main branches, uncommitted changes.
369
+
370
+ Returns:
371
+ Bash snippet (requires `IN_GIT` from header).
372
+ """
373
+ return r"""# --- Git ---
374
+ if $IN_GIT; then
375
+ BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"
376
+ if [ "$BRANCH" = "HEAD" ]; then
377
+ COMMIT="$(git rev-parse --short HEAD 2>/dev/null)"
378
+ GT="**Git**: Detached HEAD at \`${COMMIT}\`"
379
+ else
380
+ GT="**Git**: Current branch \`${BRANCH}\`"
381
+ fi
382
+
383
+ MAINS=""
384
+ for b in $(git branch 2>/dev/null | sed 's/^[* ]*//'); do
385
+ case "$b" in
386
+ main) MAINS="${MAINS:+${MAINS}, }\`main\`" ;;
387
+ master) MAINS="${MAINS:+${MAINS}, }\`master\`" ;;
388
+ esac
389
+ done
390
+ [ -n "$MAINS" ] && GT="${GT}, ${MAINS} available"
391
+
392
+ DC=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
393
+ if [ "$DC" -gt 0 ]; then
394
+ if [ "$DC" -eq 1 ]; then GT="${GT}, 1 uncommitted change"
395
+ else GT="${GT}, ${DC} uncommitted changes"
396
+ fi
397
+ fi
398
+
399
+ echo "$GT"
400
+ echo ""
401
+ fi"""
402
+
403
+
404
+ def _section_gh_cli() -> str:
405
+ """GitHub CLI search JSON-field affordances from the installed `gh`.
406
+
407
+ Returns:
408
+ Bash snippet (standalone).
409
+ """
410
+ return r"""# --- GitHub CLI ---
411
+ if command -v gh >/dev/null 2>&1; then
412
+ _gh_json_fields() {
413
+ gh search "$1" --help 2>/dev/null \
414
+ | awk '
415
+ /^JSON FIELDS/ { in_fields = 1; next }
416
+ in_fields && /^$/ { exit }
417
+ in_fields { gsub(/^ /, ""); print }
418
+ ' \
419
+ | tr '\n' ' ' \
420
+ | sed 's/ */ /g; s/^ //; s/ $//'
421
+ }
422
+
423
+ GH_PRS_FIELDS="$(_gh_json_fields prs)"
424
+ GH_ISSUES_FIELDS="$(_gh_json_fields issues)"
425
+ if [ -n "$GH_PRS_FIELDS" ] || [ -n "$GH_ISSUES_FIELDS" ]; then
426
+ echo "**GitHub CLI**:"
427
+ [ -n "$GH_PRS_FIELDS" ] \
428
+ && echo "- \`gh search prs --json\` fields: ${GH_PRS_FIELDS}"
429
+ [ -n "$GH_ISSUES_FIELDS" ] \
430
+ && echo "- \`gh search issues --json\` fields: ${GH_ISSUES_FIELDS}"
431
+ case ",$GH_PRS_FIELDS," in
432
+ *mergedAt*) ;;
433
+ *) echo "- \`gh search prs --json\` does not expose \`mergedAt\`;"
434
+ echo " use \`gh pr view --json mergedAt\` per PR for merge timestamps." ;;
435
+ esac
436
+ echo ""
437
+ fi
438
+ fi"""
439
+
440
+
441
+ def _section_test_command() -> str:
442
+ """Test command detection (make test / pytest / npm test).
443
+
444
+ Returns:
445
+ Bash snippet (standalone).
446
+ """
447
+ return r"""# --- Test command ---
448
+ TC=""
449
+ if [ -f Makefile ] && grep -qE '^tests?:' Makefile 2>/dev/null; then TC="make test"
450
+ elif [ -f pyproject.toml ]; then
451
+ if grep -q '\[tool\.pytest' pyproject.toml 2>/dev/null \
452
+ || [ -f pytest.ini ] || [ -d tests ] || [ -d test ]; then
453
+ TC="pytest"
454
+ fi
455
+ elif [ -f package.json ] \
456
+ && grep -q '"test"' package.json 2>/dev/null; then
457
+ TC="npm test"
458
+ fi
459
+ [ -n "$TC" ] && echo "**Run Tests**: \`${TC}\`" && echo ""
460
+ """
461
+
462
+
463
+ def _section_files() -> str:
464
+ """Directory listing (filtered, capped at 20).
465
+
466
+ Returns:
467
+ Bash snippet (standalone).
468
+ """
469
+ return r"""# --- Files ---
470
+ EXCL='node_modules|__pycache__|\.pytest_cache'
471
+ EXCL="${EXCL}|\.mypy_cache|\.ruff_cache|\.tox"
472
+ EXCL="${EXCL}|\.coverage|\.eggs|dist|build"
473
+ FILES=$(
474
+ { ls -1 2>/dev/null; [ -e .deepagents ] && echo .deepagents; } |
475
+ grep -vE "^(${EXCL})$" |
476
+ sort -u
477
+ )
478
+ if [ -n "$FILES" ]; then
479
+ TOTAL=$(echo "$FILES" | wc -l | tr -d ' ')
480
+ SHOWN_FILES=$(echo "$FILES" | head -20)
481
+ SHOWN=$(echo "$SHOWN_FILES" | wc -l | tr -d ' ')
482
+ TOTAL=${TOTAL:-0}
483
+ SHOWN=${SHOWN:-0}
484
+ if [ "$SHOWN" -lt "$TOTAL" ]; then
485
+ echo "**Files** (showing ${SHOWN} of ${TOTAL}):"
486
+ else
487
+ echo "**Files** (${TOTAL}):"
488
+ fi
489
+ echo "$SHOWN_FILES" | while IFS= read -r f; do
490
+ if [ -d "$f" ]; then echo "- ${f}/"
491
+ else echo "- ${f}"
492
+ fi
493
+ done
494
+ echo ""
495
+ fi"""
496
+
497
+
498
+ def _section_tree() -> str:
499
+ """`tree -L 3` output.
500
+
501
+ Returns:
502
+ Bash snippet (standalone).
503
+ """
504
+ return r"""# --- Tree ---
505
+ if command -v tree >/dev/null 2>&1; then
506
+ TREE_EXCL='node_modules|.venv|__pycache__|.pytest_cache'
507
+ TREE_EXCL="${TREE_EXCL}|.git|.mypy_cache|.ruff_cache"
508
+ TREE_EXCL="${TREE_EXCL}|.tox|.coverage|.eggs|dist|build"
509
+ T_PREVIEW=$(tree -L 3 --noreport --dirsfirst \
510
+ -I "$TREE_EXCL" 2>/dev/null | sed -n '1,22p;23{p;q;}')
511
+ if [ -n "$T_PREVIEW" ]; then
512
+ PREVIEW_LINES=$(echo "$T_PREVIEW" | wc -l | tr -d ' ')
513
+ PREVIEW_LINES=${PREVIEW_LINES:-0}
514
+ T="$T_PREVIEW"
515
+ TREE_TRUNCATED=false
516
+ if [ "$PREVIEW_LINES" -gt 22 ]; then
517
+ T=$(echo "$T_PREVIEW" | head -22)
518
+ TREE_TRUNCATED=true
519
+ fi
520
+ echo "**Tree** (3 levels):"
521
+ echo '```text'
522
+ echo "$T"
523
+ $TREE_TRUNCATED && echo "... (more lines truncated)"
524
+ echo '```'
525
+ echo ""
526
+ fi
527
+ fi"""
528
+
529
+
530
+ def _section_makefile() -> str:
531
+ """First 20 lines of Makefile (falls back to git root in monorepos).
532
+
533
+ Returns:
534
+ Bash snippet (requires `ROOT` from `_section_project` and `CWD` from header).
535
+ """
536
+ return r"""# --- Makefile ---
537
+ MK=""
538
+ if [ -f Makefile ]; then
539
+ MK="Makefile"
540
+ elif [ -n "$ROOT" ] && [ "$ROOT" != "$CWD" ] && [ -f "${ROOT}/Makefile" ]; then
541
+ MK="${ROOT}/Makefile"
542
+ fi
543
+ if [ -n "$MK" ]; then
544
+ echo "**Makefile** (\`${MK}\`, first 20 lines):"
545
+ echo '```makefile'
546
+ head -20 "$MK"
547
+ TL=$(wc -l < "$MK" | tr -d ' ')
548
+ [ "$TL" -gt 20 ] && echo "... (truncated)"
549
+ echo '```'
550
+ fi"""
551
+
552
+
553
+ def build_detect_script() -> str:
554
+ """Concatenate all section functions into the full detection script.
555
+
556
+ Independent sections run as parallel background jobs writing to temp
557
+ files, then results are concatenated in the original display order.
558
+ The header (CWD / IN_GIT) and project section (sets ROOT) run first
559
+ because later sections depend on their variables.
560
+
561
+ Returns:
562
+ Complete bash heredoc ready for `backend.execute()`.
563
+ """
564
+ # Header + project run synchronously (set CWD, IN_GIT, ROOT for others)
565
+ serial_prefix = f"{_section_header()}\n{_section_project()}"
566
+
567
+ # These sections are independent — run them in parallel.
568
+ # Subshells inherit parent variables (IN_GIT, ROOT, CWD) via fork.
569
+ # Individual exit codes are not tracked because sections legitimately
570
+ # exit non-zero when they have nothing to report (e.g. no runtimes).
571
+ parallel_sections = [
572
+ ("02_pkgmgr", _section_package_managers()),
573
+ ("03_runtimes", _section_runtimes()),
574
+ ("04_git", _section_git()),
575
+ ("05_gh_cli", _section_gh_cli()),
576
+ ("06_testcmd", _section_test_command()),
577
+ ("07_files", _section_files()),
578
+ ("08_tree", _section_tree()),
579
+ ("09_makefile", _section_makefile()),
580
+ ]
581
+
582
+ # Build parallel wrapper: each section runs in a subshell writing to a
583
+ # temp file. Stderr is captured per-section to prevent noise leakage.
584
+ parallel_setup = "_DCT=$(mktemp -d) || exit 1\ntrap 'rm -rf \"$_DCT\"' EXIT"
585
+ parallel_block = "\n".join(
586
+ f'(\n{body}\n) > "$_DCT/{name}" 2>"$_DCT/{name}.err" &'
587
+ for name, body in parallel_sections
588
+ )
589
+ cat_line = "cat " + " ".join(f'"$_DCT/{name}"' for name, _ in parallel_sections)
590
+
591
+ body = f"{serial_prefix}\n{parallel_setup}\n{parallel_block}\nwait\n{cat_line}"
592
+ return f"bash <<'__DETECT_CONTEXT_EOF__'\n{body}\n__DETECT_CONTEXT_EOF__\n"
593
+
594
+
595
+ DETECT_CONTEXT_SCRIPT = build_detect_script()
596
+
597
+ # ---------------------------------------------------------------------------
598
+ # State schema
599
+ # ---------------------------------------------------------------------------
600
+
601
+
602
+ class LocalContextState(AgentState):
603
+ """State for local context middleware."""
604
+
605
+ _local_context: NotRequired[Annotated[str, PrivateStateAttr]]
606
+ """Private formatted local context cached for prompt injection.
607
+
608
+ The context is intentionally stored in private state rather than recomputed
609
+ before every model call: volatile sections such as git status, file lists,
610
+ and directory trees would otherwise churn the system prompt and reduce
611
+ provider prompt-cache hits across a conversation.
612
+ """
613
+
614
+ _local_context_refreshed_at_cutoff: NotRequired[Annotated[int, PrivateStateAttr]]
615
+ """Cutoff index of the summarization event we last refreshed for.
616
+
617
+ Stored in LangGraph checkpointed state (isolated per thread) and private
618
+ (not exposed to subagents via `PrivateStateAttr`). Used to avoid redundant
619
+ re-runs of the detection script for the same summarization event.
620
+ """
621
+
622
+
623
+ # ---------------------------------------------------------------------------
624
+ # Middleware
625
+ # ---------------------------------------------------------------------------
626
+
627
+
628
+ class LocalContextMiddleware(AgentMiddleware):
629
+ """Inject local context (git state, project structure, etc.) into the system prompt.
630
+
631
+ Runs a bash detection script via `backend.execute()` on first interaction
632
+ and again after each summarization event, stores the result in state, and
633
+ appends it to the system prompt on every model call.
634
+
635
+ Because the script runs inside the backend, it works for both local shells
636
+ and remote sandboxes.
637
+ """
638
+
639
+ state_schema = LocalContextState
640
+
641
+ def __init__(
642
+ self,
643
+ backend: _ExecutableBackend | _AsyncExecutableBackend,
644
+ *,
645
+ mcp_server_info: list[MCPServerInfo] | None = None,
646
+ tracing_project: str | None = None,
647
+ user_tracing_project: str | None = None,
648
+ ) -> None:
649
+ """Initialize with a backend that supports shell execution.
650
+
651
+ Args:
652
+ backend: Backend instance that provides shell command execution.
653
+ mcp_server_info: MCP server metadata to include in the system prompt.
654
+ tracing_project: LangSmith project the agent's own runs trace to, or
655
+ `None` when tracing is disabled (the tracing section is omitted).
656
+ user_tracing_project: User's original `LANGSMITH_PROJECT` used by
657
+ shell commands the agent runs.
658
+ """
659
+ self.backend = backend
660
+ self._mcp_context = _build_mcp_context(mcp_server_info or [])
661
+ self._tracing_context = _build_tracing_context(
662
+ tracing_project, user_tracing_project
663
+ )
664
+
665
+ @staticmethod
666
+ def _handle_detect_result(result: ExecuteResponse) -> str | None:
667
+ """Validate detection script output and normalize it for state storage.
668
+
669
+ Args:
670
+ result: Execution result from the backend.
671
+
672
+ Returns:
673
+ Stripped script output, or `None` on failure/empty output.
674
+ """
675
+ output = result.output.strip() if result.output else ""
676
+ if result.exit_code is None or result.exit_code != 0:
677
+ logger.warning(
678
+ "Local context detection script %s; "
679
+ "context will be omitted. Output: %.200s",
680
+ f"exited with code {result.exit_code}"
681
+ if result.exit_code is not None
682
+ else "did not report an exit code",
683
+ output or "(empty)",
684
+ )
685
+ return None
686
+ if not output:
687
+ logger.debug(
688
+ "Local context detection script succeeded but produced no output"
689
+ )
690
+ return output or None
691
+
692
+ def _run_detect_script(self) -> str | None:
693
+ """Run the environment detection script.
694
+
695
+ Returns:
696
+ Stripped script output, or `None` on failure/empty output.
697
+ """
698
+ backend = self.backend
699
+ if not isinstance(backend, _ExecutableBackend):
700
+ logger.debug(
701
+ "Skipping sync local context detection; backend %s only "
702
+ "supports async execution",
703
+ type(backend).__name__,
704
+ )
705
+ return None
706
+ try:
707
+ result = backend.execute(
708
+ DETECT_CONTEXT_SCRIPT, timeout=_DETECT_SCRIPT_TIMEOUT
709
+ )
710
+ except NotImplementedError:
711
+ # Expected for async-only backends (e.g. HarborSandbox) that
712
+ # define a stub execute() raising NotImplementedError.
713
+ logger.debug(
714
+ "Backend %s does not support sync execute; "
715
+ "context detection deferred to async path",
716
+ type(backend).__name__,
717
+ )
718
+ return None
719
+ except Exception:
720
+ logger.warning(
721
+ "Local context detection failed (backend: %s); context will "
722
+ "be omitted from system prompt",
723
+ type(backend).__name__,
724
+ exc_info=True,
725
+ )
726
+ return None
727
+
728
+ return LocalContextMiddleware._handle_detect_result(result)
729
+
730
+ # override - state parameter is intentionally narrowed from
731
+ # AgentState to LocalContextState for type safety within this middleware.
732
+ def before_agent( # ty: ignore[invalid-method-override]
733
+ self,
734
+ state: LocalContextState,
735
+ runtime: Runtime, # noqa: ARG002 # Required by interface but not used in local context
736
+ ) -> dict[str, Any] | None:
737
+ """Run context detection on first interaction and refresh after summarization.
738
+
739
+ On the first invocation, runs the detection script and stores the result.
740
+ After a summarization event (indicated by a new `_summarization_event`
741
+ in state), re-runs the script to capture any environment changes that
742
+ occurred during the session.
743
+
744
+ Args:
745
+ state: Current agent state.
746
+ runtime: Runtime context.
747
+
748
+ Returns:
749
+ State update with `_local_context` populated on success. On a
750
+ post-summarization refresh failure, returns a state update
751
+ recording the cutoff (without `_local_context`) to prevent
752
+ retry loops.
753
+
754
+ Returns `None` if context is already set and no refresh is
755
+ needed, or if initial detection fails.
756
+ """
757
+ # --- Post-summarization refresh ---
758
+ # _summarization_event is a private field from SummarizationState.
759
+ # At runtime the merged state dict contains all middleware fields;
760
+ # accessed as untyped dict value because LocalContextState does not
761
+ # (and should not) redeclare it.
762
+ raw_event = state.get("_summarization_event")
763
+ if raw_event is not None:
764
+ event: SummarizationEvent = raw_event
765
+ cutoff = event.get("cutoff_index")
766
+ refreshed_cutoff = state.get("_local_context_refreshed_at_cutoff")
767
+ if cutoff != refreshed_cutoff:
768
+ output = self._run_detect_script()
769
+ if output:
770
+ return {
771
+ "_local_context": output,
772
+ "_local_context_refreshed_at_cutoff": cutoff,
773
+ }
774
+ # Script failed — record cutoff to avoid retry loop,
775
+ # keep existing `_local_context`.
776
+ return {"_local_context_refreshed_at_cutoff": cutoff}
777
+
778
+ # --- Initial detection (first invocation) ---
779
+ if state.get("_local_context"):
780
+ return None
781
+
782
+ output = self._run_detect_script()
783
+ if output:
784
+ return {"_local_context": output}
785
+ return None
786
+
787
+ async def _arun_detect_script(self) -> str | None:
788
+ """Run the environment detection script asynchronously.
789
+
790
+ Prefers `aexecute` when the backend implements `_AsyncExecutableBackend`.
791
+ Falls back to running the sync detection script in a thread pool
792
+ for sync-only backends.
793
+
794
+ Returns:
795
+ Stripped script output, or `None` on failure/empty output.
796
+ """
797
+ backend = self.backend
798
+ if not (
799
+ isinstance(backend, _AsyncExecutableBackend)
800
+ and asyncio.iscoroutinefunction(backend.aexecute)
801
+ ):
802
+ try:
803
+ return await asyncio.to_thread(self._run_detect_script)
804
+ except Exception:
805
+ logger.warning(
806
+ "Local context detection via sync fallback failed "
807
+ "(backend: %s); context will be omitted from system prompt",
808
+ type(backend).__name__,
809
+ exc_info=True,
810
+ )
811
+ return None
812
+ try:
813
+ result = await backend.aexecute(
814
+ DETECT_CONTEXT_SCRIPT, timeout=_DETECT_SCRIPT_TIMEOUT
815
+ )
816
+ except Exception:
817
+ logger.warning(
818
+ "Local context detection failed (backend: %s); context will "
819
+ "be omitted from system prompt",
820
+ type(backend).__name__,
821
+ exc_info=True,
822
+ )
823
+ return None
824
+
825
+ return LocalContextMiddleware._handle_detect_result(result)
826
+
827
+ async def abefore_agent( # ty: ignore[invalid-method-override]
828
+ self,
829
+ state: LocalContextState,
830
+ runtime: Runtime, # noqa: ARG002 # Required by interface but not used in local context
831
+ ) -> dict[str, Any] | None:
832
+ """Async variant of `before_agent` for use in async execution contexts.
833
+
834
+ Args:
835
+ state: Current agent state.
836
+ runtime: Runtime context.
837
+
838
+ Returns:
839
+ State update with `_local_context` populated on success. On a
840
+ post-summarization refresh failure, returns a state update
841
+ recording the cutoff (without `_local_context`) to prevent
842
+ retry loops.
843
+
844
+ Returns `None` if context is already set and no refresh is
845
+ needed, or if initial detection fails.
846
+ """
847
+ raw_event = state.get("_summarization_event")
848
+ if raw_event is not None:
849
+ event: SummarizationEvent = raw_event
850
+ cutoff = event.get("cutoff_index")
851
+ refreshed_cutoff = state.get("_local_context_refreshed_at_cutoff")
852
+ if cutoff != refreshed_cutoff:
853
+ output = await self._arun_detect_script()
854
+ if output:
855
+ return {
856
+ "_local_context": output,
857
+ "_local_context_refreshed_at_cutoff": cutoff,
858
+ }
859
+ return {"_local_context_refreshed_at_cutoff": cutoff}
860
+
861
+ if state.get("_local_context"):
862
+ return None
863
+
864
+ output = await self._arun_detect_script()
865
+ if output:
866
+ return {"_local_context": output}
867
+ return None
868
+
869
+ def _get_modified_request(self, request: ModelRequest) -> ModelRequest | None:
870
+ """Append local context and MCP info to the system prompt if available.
871
+
872
+ Args:
873
+ request: The model request to potentially modify.
874
+
875
+ Returns:
876
+ Modified request with context appended, or `None`.
877
+ """
878
+ state = cast("LocalContextState", request.state)
879
+ local_context = state.get("_local_context", "")
880
+
881
+ parts = [
882
+ p for p in (local_context, self._tracing_context, self._mcp_context) if p
883
+ ]
884
+ if not parts:
885
+ return None
886
+
887
+ system_prompt = request.system_prompt or ""
888
+ new_prompt = system_prompt + "\n\n" + "\n\n".join(parts)
889
+ return request.override(system_prompt=new_prompt)
890
+
891
+ def wrap_model_call(
892
+ self,
893
+ request: ModelRequest,
894
+ handler: Callable[[ModelRequest], ModelResponse],
895
+ ) -> ModelResponse:
896
+ """Inject local context into system prompt.
897
+
898
+ Args:
899
+ request: The model request being processed.
900
+ handler: The handler function to call with the modified request.
901
+
902
+ Returns:
903
+ The model response from the handler.
904
+ """
905
+ modified_request = self._get_modified_request(request)
906
+ return handler(modified_request or request)
907
+
908
+ async def awrap_model_call(
909
+ self,
910
+ request: ModelRequest,
911
+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
912
+ ) -> ModelResponse:
913
+ """Inject local context into system prompt (async).
914
+
915
+ Args:
916
+ request: The model request being processed.
917
+ handler: The async handler function to call with the modified request.
918
+
919
+ Returns:
920
+ The model response from the handler.
921
+ """
922
+ modified_request = self._get_modified_request(request)
923
+ return await handler(modified_request or request)
924
+
925
+
926
+ __all__ = ["LocalContextMiddleware"]