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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. deepagents_code/_build_info.py +1 -1
  2. deepagents_code/_checkpointer_adapter.py +86 -0
  3. deepagents_code/_env_vars.py +40 -3
  4. deepagents_code/_git.py +8 -2
  5. deepagents_code/_glm_5p2_profile.py +6 -2
  6. deepagents_code/_js_cost.py +37 -0
  7. deepagents_code/_langsmith_runtime.py +91 -0
  8. deepagents_code/_run_queue_wakeup.py +156 -0
  9. deepagents_code/_textual_patches.py +5 -0
  10. deepagents_code/_trace_redaction.py +145 -0
  11. deepagents_code/_version.py +1 -1
  12. deepagents_code/agent.py +45 -2
  13. deepagents_code/app.py +888 -201
  14. deepagents_code/app.tcss +1 -1
  15. deepagents_code/auto_mode.py +180 -9
  16. deepagents_code/btw.py +176 -37
  17. deepagents_code/btw_api.py +80 -1
  18. deepagents_code/built_in_skills/deepagents-plugin-discovery/SKILL.md +3 -1
  19. deepagents_code/client/headless_resume.py +17 -0
  20. deepagents_code/client/launch/_server_bootstrap.py +5 -0
  21. deepagents_code/client/launch/server.py +55 -13
  22. deepagents_code/client/launch/server_manager.py +97 -4
  23. deepagents_code/client/non_interactive.py +48 -30
  24. deepagents_code/client/remote_client.py +48 -0
  25. deepagents_code/config.py +344 -155
  26. deepagents_code/config_manifest.py +26 -1
  27. deepagents_code/git_evidence.py +344 -0
  28. deepagents_code/git_trace.py +271 -0
  29. deepagents_code/goal_tools.py +25 -9
  30. deepagents_code/hooks/models/domain.py +7 -1
  31. deepagents_code/hooks/reducer.py +25 -4
  32. deepagents_code/hooks/server_middleware.py +19 -2
  33. deepagents_code/hooks/transcript.py +24 -5
  34. deepagents_code/integrations/sandbox_factory.py +69 -2
  35. deepagents_code/local_context.py +100 -22
  36. deepagents_code/main.py +130 -56
  37. deepagents_code/mcp_tools.py +59 -89
  38. deepagents_code/memory_guard.py +4 -0
  39. deepagents_code/model_config.py +104 -46
  40. deepagents_code/offload_api.py +84 -6
  41. deepagents_code/output_truncation.py +425 -0
  42. deepagents_code/plugins/__init__.py +4 -0
  43. deepagents_code/plugins/adapters/mcp.py +2 -4
  44. deepagents_code/plugins/adapters/skills.py +13 -9
  45. deepagents_code/plugins/commands_cli.py +127 -4
  46. deepagents_code/plugins/discovery.py +464 -142
  47. deepagents_code/plugins/models.py +55 -1
  48. deepagents_code/plugins/store.py +59 -4
  49. deepagents_code/provider_tool_search.py +202 -0
  50. deepagents_code/server_graph.py +2 -0
  51. deepagents_code/sessions.py +8 -2
  52. deepagents_code/subagents.py +1 -1
  53. deepagents_code/thread_ownership.py +59 -15
  54. deepagents_code/tui/modals/cost_breakdown.py +1 -1
  55. deepagents_code/tui/modals/plugin_manager/__init__.py +57 -0
  56. deepagents_code/tui/modals/plugin_manager/content.py +41 -0
  57. deepagents_code/tui/modals/plugin_manager/models.py +8 -1
  58. deepagents_code/tui/modals/plugin_manager/state.py +27 -4
  59. deepagents_code/tui/textual_adapter.py +50 -0
  60. deepagents_code/tui/widgets/_links.py +43 -2
  61. deepagents_code/tui/widgets/_static_update.py +35 -0
  62. deepagents_code/tui/widgets/autocomplete.py +185 -57
  63. deepagents_code/tui/widgets/chat_input.py +43 -1
  64. deepagents_code/tui/widgets/codex_auth.py +14 -6
  65. deepagents_code/tui/widgets/final_markdown/__init__.py +18 -0
  66. deepagents_code/tui/widgets/final_markdown/_layout.py +287 -0
  67. deepagents_code/tui/widgets/final_markdown/_parse.py +158 -0
  68. deepagents_code/tui/widgets/final_markdown/_rows.py +126 -0
  69. deepagents_code/tui/widgets/final_markdown/_table.py +136 -0
  70. deepagents_code/tui/widgets/final_markdown/_widget.py +329 -0
  71. deepagents_code/tui/widgets/loading.py +5 -3
  72. deepagents_code/tui/widgets/mcp_viewer.py +1 -1
  73. deepagents_code/tui/widgets/message_store.py +93 -9
  74. deepagents_code/tui/widgets/messages.py +210 -74
  75. deepagents_code/tui/widgets/model_selector.py +18 -15
  76. deepagents_code/tui/widgets/selection_action.py +131 -0
  77. deepagents_code/tui/widgets/thread_selector.py +218 -49
  78. deepagents_code/turn_trace.py +135 -0
  79. deepagents_code/ui.py +3 -0
  80. deepagents_code/update_check.py +7 -16
  81. deepagents_code/workspace_diagnostics.py +7 -2
  82. {deepagents_code-0.2.1.dist-info → deepagents_code-0.2.3.dist-info}/METADATA +32 -32
  83. {deepagents_code-0.2.1.dist-info → deepagents_code-0.2.3.dist-info}/RECORD +87 -70
  84. {deepagents_code-0.2.1.dist-info → deepagents_code-0.2.3.dist-info}/WHEEL +1 -1
  85. {deepagents_code-0.2.1.data → deepagents_code-0.2.3.data}/data/deepagents_code/default_agent_prompt.md +0 -0
  86. {deepagents_code-0.2.1.dist-info → deepagents_code-0.2.3.dist-info}/entry_points.txt +0 -0
  87. {deepagents_code-0.2.1.dist-info → deepagents_code-0.2.3.dist-info}/licenses/LICENSE +0 -0
@@ -1,3 +1,3 @@
1
1
  """Generated at build time. Do not edit or commit."""
2
2
 
3
- BUILD_COMMIT = "8f48aab"
3
+ BUILD_COMMIT = "6884d39"
@@ -0,0 +1,86 @@
1
+ """Forward delta-channel history reads through langgraph-api's saver adapter.
2
+
3
+ The LangGraph dev server wraps a custom checkpointer in
4
+ `langgraph_api._checkpointer._adapter._CustomCheckpointerAdapter`. The adapter
5
+ forwards unknown attributes to the inner saver through `__getattr__`, but
6
+ `BaseCheckpointSaver` already defines `aget_delta_channel_history`, so the
7
+ forwarding never fires. The adapter then runs the base ancestor walk: one
8
+ `aget_tuple` and one full checkpoint decode per ancestor. The SQLite saver
9
+ overrides the method with two indexed queries, and long threads pay the
10
+ difference on every state read and every run start.
11
+
12
+ This module is a best-effort patch over a private langgraph-api class. It only
13
+ patches when the adapter still inherits the base method, and it falls back to
14
+ the base walk when the inner saver has no override of its own. Remove it when
15
+ the adapter forwards these methods itself.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ from typing import TYPE_CHECKING
22
+
23
+ from langgraph.checkpoint.base import BaseCheckpointSaver
24
+
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Mapping, Sequence
27
+
28
+ from langchain_core.runnables import RunnableConfig
29
+ from langgraph.checkpoint.base import DeltaChannelHistory
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ _BASE_ASYNC = BaseCheckpointSaver.aget_delta_channel_history
34
+ _BASE_SYNC = BaseCheckpointSaver.get_delta_channel_history
35
+
36
+
37
+ def _overriding_inner(
38
+ adapter: BaseCheckpointSaver, name: str
39
+ ) -> BaseCheckpointSaver | None:
40
+ """Return the adapter's inner saver if it overrides the base method `name`."""
41
+ inner = adapter.__dict__.get("_inner")
42
+ if not isinstance(inner, BaseCheckpointSaver):
43
+ return None
44
+ if getattr(type(inner), name) is getattr(BaseCheckpointSaver, name):
45
+ return None
46
+ return inner
47
+
48
+
49
+ async def _aget_delta_channel_history(
50
+ self: BaseCheckpointSaver, *, config: RunnableConfig, channels: Sequence[str]
51
+ ) -> Mapping[str, DeltaChannelHistory]:
52
+ inner = _overriding_inner(self, "aget_delta_channel_history")
53
+ if inner is None:
54
+ return await _BASE_ASYNC(self, config=config, channels=channels)
55
+ return await inner.aget_delta_channel_history(config=config, channels=channels)
56
+
57
+
58
+ def _get_delta_channel_history(
59
+ self: BaseCheckpointSaver, *, config: RunnableConfig, channels: Sequence[str]
60
+ ) -> Mapping[str, DeltaChannelHistory]:
61
+ inner = _overriding_inner(self, "get_delta_channel_history")
62
+ if inner is None:
63
+ return _BASE_SYNC(self, config=config, channels=channels)
64
+ return inner.get_delta_channel_history(config=config, channels=channels)
65
+
66
+
67
+ def install_delta_history_forwarding() -> None:
68
+ """Make langgraph-api's checkpointer adapter use the inner saver's fast path.
69
+
70
+ Call this in the server process before the adapter serves requests. It is
71
+ idempotent and a no-op when the adapter is missing or already overrides
72
+ the methods.
73
+ """
74
+ try:
75
+ # The adapter has no public seam; this patch exists to reach it.
76
+ from langgraph_api._checkpointer._adapter import ( # noqa: PLC2701
77
+ _CustomCheckpointerAdapter,
78
+ )
79
+ except ImportError:
80
+ logger.warning("langgraph-api checkpointer adapter not found; skipping patch")
81
+ return
82
+ adapter = _CustomCheckpointerAdapter
83
+ if adapter.aget_delta_channel_history is _BASE_ASYNC:
84
+ adapter.aget_delta_channel_history = _aget_delta_channel_history
85
+ if adapter.get_delta_channel_history is _BASE_SYNC:
86
+ adapter.get_delta_channel_history = _get_delta_channel_history
@@ -77,6 +77,15 @@ Values outside 1-900 seconds are ignored in favor of the next config source.
77
77
  Also settable via `[mcp].tool_timeout` in config.toml.
78
78
  """
79
79
 
80
+ ASK_ABOUT_SELECTION = "DEEPAGENTS_CODE_ASK_ABOUT_SELECTION"
81
+ """Show "Ask about this" when conversation text is selected.
82
+
83
+ Enabled by default; set to a falsy value (`0`, `false`, `no`, `off`) to hide
84
+ it. Parsed by `classify_env_bool` (an unrecognized or empty value falls through
85
+ to the config value rather than forcing the default). Also settable via
86
+ `[ui].ask_about_selection` in config.toml. `/reload` applies a change.
87
+ """
88
+
80
89
  AUTO_UPDATE = "DEEPAGENTS_CODE_AUTO_UPDATE"
81
90
  """Toggle automatic app updates. Enabled by default; set to a falsy value
82
91
  ('0', 'false', 'no', 'off', or empty) to opt out."""
@@ -277,13 +286,20 @@ EXPERIMENTAL = "DEEPAGENTS_CODE_EXPERIMENTAL"
277
286
  Off by default; parsed by `is_env_truthy` (see there for the accepted truthy
278
287
  values). Marks experimental runs in UI/trace metadata. Behavior behind this
279
288
  flag may change or be removed without notice.
289
+
290
+ Set only through the launching shell or global `~/.deepagents/.env`; a project
291
+ `.env` cannot set it.
280
292
  """
281
293
 
282
294
  EXTENSIONS = "DEEPAGENTS_CODE_EXTENSIONS"
283
295
  """Enable loading installed-plugin and trusted-project Python extensions."""
284
296
 
285
297
  EXTENSIONS_TRUST = "DEEPAGENTS_CODE_EXTENSIONS_TRUST"
286
- """Default project extension trust policy: `ask`, `always`, or `never`."""
298
+ """Default project extension trust policy: `ask`, `always`, or `never`.
299
+
300
+ Set only through the launching shell or global `~/.deepagents/.env`; a project
301
+ `.env` cannot set it.
302
+ """
287
303
 
288
304
  EXTERNAL_EVENT_SOCKET = "DEEPAGENTS_CODE_EXTERNAL_EVENT_SOCKET"
289
305
  """Enable the local Unix-socket external event listener.
@@ -296,7 +312,11 @@ EXTERNAL_EVENT_SOCKET_PATH = "DEEPAGENTS_CODE_EXTERNAL_EVENT_SOCKET_PATH"
296
312
  """Override the default Unix-socket path for the external event listener."""
297
313
 
298
314
  EXTRA_SKILLS_DIRS = "DEEPAGENTS_CODE_EXTRA_SKILLS_DIRS"
299
- """Paths added to the skill containment allowlist, split with `os.pathsep`."""
315
+ """Paths added to the skill containment allowlist, split with `os.pathsep`.
316
+
317
+ Set only through the launching shell or global `~/.deepagents/.env`; a project
318
+ `.env` cannot set it.
319
+ """
300
320
 
301
321
  GOAL_AUTO_ACCEPT_CRITERIA = "DEEPAGENTS_CODE_GOAL_AUTO_ACCEPT_CRITERIA"
302
322
  """Apply generated goal criteria automatically in Auto mode.
@@ -360,6 +380,14 @@ KITTY_KEYBOARD = "DEEPAGENTS_CODE_KITTY_KEYBOARD"
360
380
  LANGSMITH_PROJECT = "DEEPAGENTS_CODE_LANGSMITH_PROJECT"
361
381
  """Override LangSmith project name for agent traces."""
362
382
 
383
+ LANGSMITH_PROJECT_URL = "DEEPAGENTS_CODE_LANGSMITH_PROJECT_URL"
384
+ """LangSmith URL of the project named by `DEEPAGENTS_CODE_LANGSMITH_PROJECT`.
385
+
386
+ When set, thread links and `/trace` use this URL instead of looking the project
387
+ up, so the API key does not need project read access. It is ignored when the
388
+ active project is a different one.
389
+ """
390
+
363
391
  LANGSMITH_REDACT = "DEEPAGENTS_CODE_LANGSMITH_REDACT"
364
392
  """Toggle LangSmith secret redaction for agent traces (defaults to on)."""
365
393
 
@@ -458,6 +486,9 @@ Set to a truthy value to bring the standalone integrations screen back into the
458
486
  flow. Parsed by `is_env_truthy`: accepts `1`, `true`, `yes`, `on` as enabled.
459
487
  """
460
488
 
489
+ PROVIDER_TOOL_SEARCH = "DEEPAGENTS_CODE_PROVIDER_TOOL_SEARCH"
490
+ """Toggle native MCP tool discovery on verified endpoints (defaults to on)."""
491
+
461
492
  OPENAI_PROMPT_CACHE_KEY = "DEEPAGENTS_CODE_OPENAI_PROMPT_CACHE_KEY"
462
493
  """Toggle injecting a per-thread OpenAI `prompt_cache_key` (defaults to on).
463
494
 
@@ -485,6 +516,8 @@ PLUGIN_CACHE_DIR = "DEEPAGENTS_CODE_PLUGIN_CACHE_DIR"
485
516
  """Override the plugin install/marketplace cache root.
486
517
 
487
518
  When unset, plugins are stored under `DEFAULT_CONFIG_DIR / "plugins"`.
519
+ Set only through the launching shell or global `~/.deepagents/.env`; a project
520
+ `.env` cannot set it.
488
521
  """
489
522
 
490
523
  PRICES_AUTO_UPDATE = "DEEPAGENTS_CODE_PRICES_AUTO_UPDATE"
@@ -564,7 +597,11 @@ SERVER_ENV_PREFIX = "DEEPAGENTS_CODE_SERVER_"
564
597
  """Environment variable prefix used to pass CLI config to the server subprocess."""
565
598
 
566
599
  SHELL_ALLOW_LIST = "DEEPAGENTS_CODE_SHELL_ALLOW_LIST"
567
- """Comma-separated shell commands to allow (or 'recommended'/'all')."""
600
+ """Comma-separated shell commands to allow (or 'recommended'/'all').
601
+
602
+ Set only through the launching shell or global `~/.deepagents/.env`; a project
603
+ `.env` cannot set it.
604
+ """
568
605
 
569
606
  SHOW_HEADER = "DEEPAGENTS_CODE_SHOW_HEADER"
570
607
  """Show Textual's native header bar at the top of the TUI when enabled."""
deepagents_code/_git.py CHANGED
@@ -17,6 +17,9 @@ _GIT_DIR_POINTER_PREFIX = "gitdir: "
17
17
  _GIT_HEAD_REF_PREFIX = "ref: "
18
18
  """Prefix used by `HEAD` when it points at a named ref instead of a commit."""
19
19
 
20
+ _REFTABLE_HEAD_PLACEHOLDER = "refs/heads/.invalid"
21
+ """Ref a reftable repository writes to `HEAD`; the real refs live in `reftable/`."""
22
+
20
23
  _GIT_REF_PREFIXES = ("refs/heads/", "refs/remotes/", "refs/tags/", "refs/")
21
24
  """Known git ref prefixes stripped when formatting a branch-like display name."""
22
25
 
@@ -411,7 +414,8 @@ def read_git_branch_from_filesystem(path: str | Path) -> str | None:
411
414
  Returns:
412
415
  The abbreviated branch name, `HEAD` for detached HEAD, an empty string
413
416
  when `path` is not inside a git repository, or `None` when metadata
414
- exists but cannot be parsed confidently.
417
+ exists but cannot be parsed confidently (including reftable
418
+ repositories, whose `HEAD` file only holds a placeholder).
415
419
  """
416
420
  git_dir = find_git_dir(path)
417
421
  if git_dir is None:
@@ -431,7 +435,9 @@ def read_git_branch_from_filesystem(path: str | Path) -> str | None:
431
435
  return ""
432
436
  if head.startswith(_GIT_HEAD_REF_PREFIX):
433
437
  ref = head.removeprefix(_GIT_HEAD_REF_PREFIX).strip()
434
- return _abbreviate_git_ref(ref) if ref else None
438
+ if not ref or ref == _REFTABLE_HEAD_PLACEHOLDER:
439
+ return None
440
+ return _abbreviate_git_ref(ref)
435
441
  return "HEAD"
436
442
 
437
443
 
@@ -26,6 +26,8 @@ from langchain.agents.middleware.types import (
26
26
  )
27
27
  from langchain_core.messages import AIMessage
28
28
 
29
+ from deepagents_code.output_truncation import MAX_OUTPUT_TOKENS, output_truncation
30
+
29
31
  if TYPE_CHECKING:
30
32
  from collections.abc import Awaitable, Callable
31
33
 
@@ -168,8 +170,10 @@ class _GlmTerminalStallRecovery(AgentMiddleware):
168
170
  message = response.result[0]
169
171
  if not isinstance(message, AIMessage) or message.tool_calls:
170
172
  return False
171
- metadata = message.response_metadata
172
- return isinstance(metadata, dict) and metadata.get("finish_reason") == "length"
173
+ # Fireworks reports the output cap as Chat Completions `finish_reason
174
+ # "length"`, which the shared classifier maps to `max_output_tokens`.
175
+ truncation = output_truncation(message)
176
+ return truncation is not None and truncation.reason == MAX_OUTPUT_TOKENS
173
177
 
174
178
  @staticmethod
175
179
  def _recovery_request(request: ModelRequest) -> ModelRequest:
@@ -7,6 +7,7 @@ import dataclasses
7
7
  import hashlib
8
8
  import itertools
9
9
  import json
10
+ import logging
10
11
  import math
11
12
  from collections.abc import Mapping
12
13
  from typing import TYPE_CHECKING, override
@@ -19,6 +20,7 @@ from langgraph.checkpoint.base import (
19
20
  empty_checkpoint,
20
21
  )
21
22
  from langgraph.config import get_config
23
+ from langgraph.errors import GraphBubbleUp, NodeCancelledError
22
24
  from langgraph.types import Command
23
25
 
24
26
  from deepagents_code.cost_tracking import (
@@ -31,12 +33,15 @@ from deepagents_code.thread_ownership import OWNER_KEY
31
33
  if TYPE_CHECKING:
32
34
  from collections.abc import Awaitable, Callable
33
35
 
36
+ from langchain.agents.middleware.types import ModelRequest
34
37
  from langchain_core.messages import ToolMessage
35
38
  from langchain_core.runnables import RunnableConfig
36
39
  from langgraph.prebuilt.tool_node import ToolCallRequest, ToolRuntime
37
40
 
38
41
  from deepagents_code.cost_tracking import CostBreakdown
39
42
 
43
+ logger = logging.getLogger(__name__)
44
+
40
45
  _ACCOUNTING_KEY = "__deepagents_js_cost_owner"
41
46
  _RESPONSE_FORMAT_KEY = "__deepagents_subagent_response_format"
42
47
 
@@ -53,6 +58,27 @@ def _digest(value: str) -> str:
53
58
  class CostAwareCodeInterpreterMiddleware(CodeInterpreterMiddleware):
54
59
  """Transport cost receipts without caching JavaScript or forwarding state."""
55
60
 
61
+ @override
62
+ def _prepare_for_call(self, request: ModelRequest) -> str:
63
+ """Return a compact reference while retaining all PTC bindings."""
64
+ from langchain_core.tools import BaseTool
65
+ from langchain_quickjs.middleware import render_ptc_prompt
66
+
67
+ tools = [tool for tool in request.tools if isinstance(tool, BaseTool)]
68
+ prompt = super()._prepare_for_call(request.override(tools=list(tools)))
69
+ slot = self._slot_id(request.state)
70
+ cached = self._ptc_prompt_by_slot.get(slot)
71
+ if cached is None:
72
+ return prompt
73
+ exposed, reference = cached
74
+ visible = [
75
+ tool for tool in exposed if not (tool.extras or {}).get("defer_loading")
76
+ ]
77
+ if len(visible) == len(exposed):
78
+ return prompt
79
+ replacement = render_ptc_prompt(visible, tool_name=self._tool_name)
80
+ return prompt.removesuffix(reference) + replacement
81
+
56
82
  @override
57
83
  def wrap_tool_call(
58
84
  self,
@@ -172,6 +198,17 @@ def _cost_task(
172
198
  config=config,
173
199
  tool_call_id=runtime.tool_call_id,
174
200
  )
201
+ except asyncio.CancelledError, GraphBubbleUp, NodeCancelledError:
202
+ raise
203
+ except Exception as exc:
204
+ logger.debug("Subagent %r failed", subagent_type, exc_info=exc)
205
+ return {
206
+ "error": (
207
+ f"Subagent {subagent_type!r} failed: "
208
+ f"{type(exc).__name__}: {str(exc)[:300]}. You may retry this task."
209
+ ),
210
+ "failed": True,
211
+ }
175
212
  finally:
176
213
  if invocation is not None:
177
214
  active.discard(invocation)
@@ -0,0 +1,91 @@
1
+ """Run untraced `@traceable` bookkeeping inline on the server loop.
2
+
3
+ LangChain wraps every middleware `awrap_tool_call` and `awrap_model_call` hook
4
+ in `langsmith.traceable`. Its async wrapper sends two calls to a worker thread
5
+ per hook: one to set up the run and one to end it. It does this even when
6
+ tracing is off and both calls only build an empty container. About 20 traced
7
+ hooks run per tool round trip, so each round trip pays for about 40 thread
8
+ hops that do no work.
9
+
10
+ `install_untraced_inline_override` installs a LangSmith runtime override. The
11
+ override runs those two calls inline when they cannot trace, and gives every
12
+ other call to LangSmith's default thread hop.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import functools
18
+ import logging
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ if TYPE_CHECKING:
22
+ import contextvars
23
+ from collections.abc import Awaitable, Callable
24
+
25
+ DefaultAioToThread = Callable[..., Awaitable[Any]]
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ def _target(func: Callable[..., Any]) -> Callable[..., Any]:
31
+ """Return the function a `functools.partial` wraps, else `func` itself.
32
+
33
+ Returns:
34
+ The underlying callable.
35
+ """
36
+ return func.func if isinstance(func, functools.partial) else func
37
+
38
+
39
+ def _runs_inline(
40
+ ctx: contextvars.Context,
41
+ func: Callable[..., Any],
42
+ args: tuple[Any, ...],
43
+ ) -> bool:
44
+ """Whether a `traceable` bookkeeping call cannot trace, so it is cheap.
45
+
46
+ Only run setup and run end qualify. Any other call (for example an async
47
+ `Client` API method) can do network I/O, so it keeps the thread hop.
48
+
49
+ Returns:
50
+ `True` when the call is safe to run on the event loop.
51
+ """
52
+ from langsmith import run_helpers
53
+ from langsmith.utils import tracing_is_enabled
54
+
55
+ target = _target(func)
56
+ if target is getattr(run_helpers, "_setup_run", None):
57
+ return not ctx.run(tracing_is_enabled)
58
+ if target is getattr(run_helpers, "_handle_container_end", None):
59
+ container = args[0] if args else None
60
+ return isinstance(container, dict) and container.get("new_run") is None
61
+ return False
62
+
63
+
64
+ async def _untraced_inline_aio_to_thread(
65
+ default: DefaultAioToThread,
66
+ ctx: contextvars.Context,
67
+ func: Callable[..., Any],
68
+ /,
69
+ *args: Any, # forwards arbitrary LangSmith call arguments
70
+ **kwargs: Any, # forwards arbitrary LangSmith call arguments
71
+ ) -> Any: # noqa: ANN401 # returns whatever `func` returns
72
+ """Run untraced bookkeeping inline; hop to a thread for everything else.
73
+
74
+ Returns:
75
+ The result of `func`.
76
+ """
77
+ if _runs_inline(ctx, func, args):
78
+ return ctx.run(func, *args, **kwargs)
79
+ return await default(ctx, func, *args, **kwargs)
80
+
81
+
82
+ def install_untraced_inline_override() -> None:
83
+ """Install the override for this process.
84
+
85
+ The override is process-global. Call it only in the server process, which
86
+ owns its event loop and pins one tracing configuration for its lifetime.
87
+ """
88
+ import langsmith
89
+
90
+ langsmith.set_runtime_overrides(aio_to_thread=_untraced_inline_aio_to_thread)
91
+ logger.debug("Installed inline LangSmith runtime override for untraced runs")
@@ -0,0 +1,156 @@
1
+ """Wake the in-memory run queue when a run is created.
2
+
3
+ The server runs on `langgraph_runtime_inmem`. Its background scheduler polls
4
+ for pending runs: `Runs.next(wait=True)` sleeps 0.5 s, then claims only runs
5
+ created before that sleep began. Every user turn and every interrupt resume is
6
+ a new run, so each one waits 0.5-1.0 s before a worker starts it.
7
+
8
+ This patch makes `Runs.put` set an event and makes a waiting `Runs.next` wait
9
+ on that event instead of the fixed sleep. The stock `Runs.next` still claims
10
+ the runs, so queue order and per-thread locking do not change. The 0.5 s
11
+ timeout stays as a fallback, so a missed wakeup costs at most the stock delay.
12
+
13
+ `Runs.next` and `Runs.put` are private APIs. If their shape is not what this
14
+ module expects, the patch logs at debug level and does nothing. Remove this
15
+ module when `langgraph_runtime_inmem` wakes the scheduler on put.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import contextlib
22
+ import functools
23
+ import inspect
24
+ import logging
25
+ from typing import TYPE_CHECKING
26
+
27
+ if TYPE_CHECKING:
28
+ from collections.abc import AsyncIterator, Awaitable, Callable
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ _POLL_INTERVAL = 0.5
33
+ """Fallback wait in seconds; matches the stock `Runs.next` sleep."""
34
+
35
+ _PATCHED_MARKER = "_dcode_run_queue_wakeup"
36
+ """Attribute set on each wrapper so a second install is a no-op."""
37
+
38
+
39
+ class _Wakeup:
40
+ """Edge-triggered signal from `Runs.put` to a waiting `Runs.next`.
41
+
42
+ The event binds to the scheduler loop on the first wait. A put before
43
+ that first wait is not lost: the scheduler then waits the fallback
44
+ interval, as stock does.
45
+ """
46
+
47
+ def __init__(self) -> None:
48
+ self._event: asyncio.Event | None = None
49
+ self._loop: asyncio.AbstractEventLoop | None = None
50
+
51
+ async def wait(self) -> None:
52
+ """Wait until a run is put, or until the fallback interval passes."""
53
+ if self._event is None:
54
+ self._event = asyncio.Event()
55
+ self._loop = asyncio.get_running_loop()
56
+ with contextlib.suppress(TimeoutError):
57
+ async with asyncio.timeout(_POLL_INTERVAL):
58
+ await self._event.wait()
59
+ self._event.clear()
60
+
61
+ def notify(self) -> None:
62
+ """Wake the scheduler; safe from any thread and after loop close."""
63
+ event, loop = self._event, self._loop
64
+ if event is None or loop is None:
65
+ return
66
+ # The loop can close during shutdown; the wakeup is then moot.
67
+ with contextlib.suppress(RuntimeError):
68
+ loop.call_soon_threadsafe(event.set)
69
+
70
+
71
+ _WAKEUP = _Wakeup()
72
+
73
+
74
+ def _wrap_next(
75
+ original: Callable[[bool, int], AsyncIterator[object]],
76
+ ) -> Callable[[bool, int], AsyncIterator[object]]:
77
+ """Replace the fixed poll sleep with a wait on `_WAKEUP`.
78
+
79
+ Returns:
80
+ A drop-in replacement for the upstream `Runs.next`.
81
+ """
82
+
83
+ @functools.wraps(original)
84
+ async def next_runs(wait: bool, limit: int = 1) -> AsyncIterator[object]:
85
+ if wait:
86
+ await _WAKEUP.wait()
87
+ # `wait=False` skips the sleep and claims runs created before now,
88
+ # which includes the run that woke us.
89
+ async for item in original(False, limit):
90
+ yield item
91
+
92
+ setattr(next_runs, _PATCHED_MARKER, True)
93
+ return next_runs
94
+
95
+
96
+ def _wrap_put(
97
+ original: Callable[..., Awaitable[object]],
98
+ ) -> Callable[..., Awaitable[object]]:
99
+ """Notify `_WAKEUP` after each run insert.
100
+
101
+ Returns:
102
+ A drop-in replacement for the upstream `Runs.put`.
103
+ """
104
+
105
+ @functools.wraps(original)
106
+ async def put(*args: object, **kwargs: object) -> object:
107
+ result = await original(*args, **kwargs)
108
+ _WAKEUP.notify()
109
+ return result
110
+
111
+ setattr(put, _PATCHED_MARKER, True)
112
+ return put
113
+
114
+
115
+ def _has_expected_shape(runs: type) -> bool:
116
+ """Check that `Runs.next` and `Runs.put` look like the pinned version.
117
+
118
+ Returns:
119
+ `True` when both are static methods with the expected signatures.
120
+ """
121
+ next_attr = runs.__dict__.get("next")
122
+ put_attr = runs.__dict__.get("put")
123
+ if not isinstance(next_attr, staticmethod) or not isinstance(
124
+ put_attr, staticmethod
125
+ ):
126
+ return False
127
+ next_fn, put_fn = next_attr.__func__, put_attr.__func__
128
+ params = list(inspect.signature(next_fn).parameters)
129
+ return (
130
+ inspect.isasyncgenfunction(next_fn)
131
+ and params[:2] == ["wait", "limit"]
132
+ and inspect.iscoroutinefunction(put_fn)
133
+ )
134
+
135
+
136
+ def install_run_queue_wakeup() -> bool:
137
+ """Patch the in-memory run queue to start new runs without the poll delay.
138
+
139
+ Returns:
140
+ `True` when the patch is active after the call, else `False`.
141
+ """
142
+ try:
143
+ from langgraph_runtime_inmem.ops import Runs
144
+ except ImportError:
145
+ logger.debug("Run queue wakeup skipped: in-memory runtime not installed")
146
+ return False
147
+ if getattr(Runs.next, _PATCHED_MARKER, False):
148
+ return True
149
+ if not _has_expected_shape(Runs):
150
+ logger.debug("Run queue wakeup skipped: Runs.next/put changed upstream")
151
+ return False
152
+ wrappers = {"next": _wrap_next, "put": _wrap_put}
153
+ for name, wrap in wrappers.items():
154
+ setattr(Runs, name, staticmethod(wrap(getattr(Runs, name))))
155
+ logger.debug("Run queue wakeup installed")
156
+ return True
@@ -293,6 +293,11 @@ else:
293
293
 
294
294
 
295
295
  def _rendered_text(widget: Widget) -> str | None:
296
+ # A widget that renders a custom visual (such as `FinalMarkdown`) can
297
+ # publish the text its selection offsets index into.
298
+ selectable = getattr(widget, "selectable_text", None)
299
+ if isinstance(selectable, str):
300
+ return selectable
296
301
  visual = widget._render() # match Textual's get_selection path
297
302
  if isinstance(visual, (Content, Text)):
298
303
  return str(visual)