Repository navigation
Expand file tree
/
Copy pathserver_graph.py
More file actions
1124 lines (973 loc) · 43.1 KB
/
Copy pathserver_graph.py
File metadata and controls
1124 lines (973 loc) · 43.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Server-side graph entry point for `langgraph dev`.
This module is referenced by the generated `langgraph.json` and exposes a graph
factory that the LangGraph server can load and serve.
The graph is created by `make_graph()`, which reads configuration from
`ServerConfig.from_env()` — the same dataclass the CLI uses to *write* the
configuration via `ServerConfig.to_env()`. This shared schema ensures the two
sides stay in sync.
"""
from __future__ import annotations
import asyncio
import atexit
import logging
import sys
from collections import OrderedDict
from pathlib import Path
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, NamedTuple
# Imported at runtime rather than under TYPE_CHECKING: the LangGraph server
# classifies `make_graph` by resolving its annotations with
# `typing.get_type_hints` at graph-load time. A name that only type checkers
# can see fails to resolve, and the server then refuses to load the graph.
from langgraph_sdk.runtime import ServerRuntime as LangGraphServerRuntime # noqa: TC002
from deepagents_code._cli_context import CLIContextSchema
from deepagents_code._server_config import ServerConfig
from deepagents_code._startup_error import (
STARTUP_ERROR_MARKER as _STARTUP_ERROR_MARKER,
emit_startup_failure,
)
from deepagents_code.configuration.interpreter import InterpreterConfig
from deepagents_code.configuration.resolver import get_config_resolver
from deepagents_code.model_metadata import ModelMetadata
from deepagents_code.project_utils import ProjectContext, get_server_project_context
from deepagents_code.workspace import (
PROJECT_POLICY_DRIFT_REASON,
SERVER_CONFIG_DRIFT_REASON,
WorkspaceConflictError,
canonical_fingerprint,
drifted_project_fields,
get_snapshot_for_binding,
resolve_workspace,
)
from deepagents_code.workspace_diagnostics import (
WorkspaceDiagnostics,
diff_snapshots,
snapshot_for_payload,
)
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Mapping
from contextlib import AbstractContextManager
from deepagents.backends.composite import CompositeBackend
from deepagents.backends.protocol import SandboxBackendProtocol
EnvironmentContext = Callable[
[Mapping[str, str] | None], AbstractContextManager[None]
]
from deepagents_code.config import CredentialsSnapshot
from deepagents_code.extensions.registry import ExtensionRegistry
from deepagents_code.mcp_tools import MCPServerInfo
from deepagents_code.offload_middleware import OffloadOperation
from deepagents_code.workspace import WorkspaceBinding
logger = logging.getLogger(__name__)
_sandbox_cm: Any = None
_sandbox_backend: Any = None
_mcp_session_manager: Any = None
_server_tracing_settings: tuple[dict[str, str | None], bool] | None = None
_server_tracing_initialized = False
def _close_sandbox(context: AbstractContextManager[Any]) -> None:
context.__exit__(None, None, None)
async def _open_sandbox(
create: Callable[[], AbstractContextManager[Any]],
) -> tuple[AbstractContextManager[Any], Any]:
def _enter() -> tuple[AbstractContextManager[Any], Any]:
context = create()
return context, context.__enter__() # noqa: PLC2801
task = asyncio.create_task(asyncio.to_thread(_enter))
try:
return await asyncio.shield(task)
except asyncio.CancelledError:
try:
context, _ = await asyncio.shield(task)
except BaseException: # Preserve the caller's cancellation
logger.debug(
"Sandbox startup did not complete after cancellation", exc_info=True
)
else:
await asyncio.to_thread(_close_sandbox, context)
raise
def _validate_server_tracing(
environ: Mapping[str, str], *, redact: bool
) -> tuple[dict[str, str | None], bool]:
"""Check tracing compatibility without reserving or configuring the process.
Returns:
Compatible tracing settings.
"""
from deepagents_code.config import _tracing_environment_values
settings = (_tracing_environment_values(environ), redact)
if _server_tracing_settings is not None and settings != _server_tracing_settings:
reason = (
"its LangSmith tracing settings differ from this server's; "
"start a separate server for this workspace"
)
conflict = WorkspaceConflictError.from_reason(reason)
raise conflict
return settings
def _configure_server_tracing(environ: Mapping[str, str], *, redact: bool) -> None:
"""Pin tracing for the server lifetime before any runtime can execute.
LangSmith uses process-wide env caches and a default client. Replacing
them, even under a build lock, reroutes cached and concurrently executing
runtimes. Only workspaces with matching tracing settings can share this
process. Keep the reservation across failed builds and cache eviction.
Called on the server loop with no suspension between claim and setup.
"""
from deepagents_code.config import (
configure_langsmith_secret_redaction,
reconcile_tracing_environment,
)
global _server_tracing_settings, _server_tracing_initialized # noqa: PLW0603 # process-lifetime policy
_server_tracing_settings = _validate_server_tracing(environ, redact=redact)
if not _server_tracing_initialized:
reconcile_tracing_environment(environ)
# Keep redaction on the server task: its fail-closed disable must
# reach this task's LangSmith ContextVar, not a worker's copied context.
configure_langsmith_secret_redaction()
_server_tracing_initialized = True
def _print_startup_error(message: str) -> None:
"""Print a startup error for both humans and the parent app process.
Args:
message: Concise startup failure to surface in the parent process.
"""
print(message, file=sys.stderr) # noqa: T201 # stderr fallback for logs
print( # noqa: T201 # machine-readable marker consumed by server.py
f"{_STARTUP_ERROR_MARKER}{message}",
file=sys.stderr,
)
def _get_mcp_session_manager() -> Any: # noqa: ANN401
"""Return the process-wide MCP session manager singleton.
Sessions are bound to the langgraph dev server's event loop. Cleanup
therefore belongs to that loop's normal shutdown path, not `atexit` —
an atexit handler runs after the loop is already closed and cannot
await `AsyncExitStack.aclose()` safely. Subprocess handles held by
stdio transports are released when the Python process exits.
"""
global _mcp_session_manager # noqa: PLW0603
if _mcp_session_manager is None:
from deepagents_code.mcp_tools import MCPSessionManager
_mcp_session_manager = MCPSessionManager()
return _mcp_session_manager
async def _build_tools(
config: ServerConfig,
project_context: ProjectContext | None,
*,
tavily_api_key: str | None,
) -> tuple[list[Any], list[Any] | None, list[Any], list[Any]]:
"""Assemble the tool list based on server config.
Loads built-in tools (conditionally including web search when Tavily is
available) and MCP tools when enabled.
MCP discovery is awaited on the server's event loop: LangGraph invokes this
async factory on its running loop, so discovery must use `await` rather than
`asyncio.run` (which raises inside a running loop). `stateless=True` ensures
discovery only uses throwaway sessions, while the shared runtime session
manager binds real sessions lazily inside the server loop on first tool
invocation. MCP adapter imports are warmed in a worker thread inside
`_load_tools_from_config` (only when active servers exist) because first
import can perform blocking package-resource scans.
Args:
config: Deserialized server configuration.
project_context: Resolved project context for MCP discovery.
tavily_api_key: Workspace Tavily key, or `None` when the workspace
configures none. An empty string still binds the tool, which then
reports the key as unconfigured.
Returns:
Tuple of `(tools, mcp_server_info, mcp_tools, read_only_builtins)`. The
last element is the exact built-in tool objects that are safe to expose
to criteria drafting and rubric grading; read-only-ness is known here,
at construction, so no consumer has to re-derive it.
Raises:
FileNotFoundError: If the MCP config file is not found.
RuntimeError: If MCP tool loading fails.
"""
from deepagents_code.tools import (
create_web_search_tool,
fetch_url,
get_current_thread_id,
)
tools: list[Any] = [fetch_url, get_current_thread_id]
read_only_builtins: list[Any] = [fetch_url]
if tavily_api_key is not None:
search_tool = create_web_search_tool(tavily_api_key)
tools.append(search_tool)
read_only_builtins.append(search_tool)
mcp_server_info: list[Any] | None = None
mcp_tools: list[Any] = []
if not config.no_mcp:
from deepagents_code.mcp_tools import resolve_and_load_mcp_tools
from deepagents_code.plugins.adapters.mcp import discover_plugin_mcp_configs
project_dir = (
project_context.project_root or project_context.user_cwd
if project_context is not None
else None
)
# Offload plugin discovery: it does blocking disk IO (`os.mkdir` for
# per-plugin data dirs, plus state/manifest reads) that `blockbuster`
# rejects on the server event loop.
plugin_mcp_configs = await asyncio.to_thread(
discover_plugin_mcp_configs, project_dir=project_dir
)
try:
mcp_tools, _, mcp_server_info = await resolve_and_load_mcp_tools(
explicit_config_path=config.mcp_config_path,
no_mcp=config.no_mcp,
trust_project_mcp=config.trust_project_mcp,
project_context=project_context,
additional_configs=plugin_mcp_configs,
stateless=True,
session_manager=_get_mcp_session_manager(),
)
except FileNotFoundError:
logger.exception("MCP config file not found: %s", config.mcp_config_path)
raise
except RuntimeError:
logger.exception(
"Failed to load MCP tools (config: %s)", config.mcp_config_path
)
raise
tools.extend(mcp_tools)
if mcp_tools:
logger.info("Loaded %d MCP tool(s)", len(mcp_tools))
return tools, mcp_server_info, mcp_tools, read_only_builtins
def _criteria_context_tools(
tools: list[Any],
mcp_tools: list[Any],
read_only_builtins: list[Any],
) -> list[Any]:
"""Select read-only external tools for criteria drafting and rubric grading.
Args:
tools: Main agent tools in execution order.
mcp_tools: Exact tool objects returned by MCP discovery.
read_only_builtins: Built-in tool objects `_build_tools` created and
marked read-only.
Returns:
External context tools available to criteria generation and grading.
MCP tools are included only when their protocol annotations explicitly
declare them read-only.
"""
allowed_ids = {id(tool) for tool in read_only_builtins}
allowed_ids.update(
id(tool) for tool in mcp_tools if _mcp_tool_is_explicitly_read_only(tool)
)
return [tool for tool in tools if id(tool) in allowed_ids]
def _mcp_tool_is_explicitly_read_only(tool: Any) -> bool: # noqa: ANN401
"""Return whether a wrapped MCP tool is unambiguously read-only.
MCP `ToolAnnotations.readOnlyHint` is serialized by the installed adapter
into the LangChain tool's metadata as the camel-case `readOnlyHint` key.
Require the literal boolean `True` and reject a contradictory destructive
hint so absent, malformed, or ambiguous annotations fail closed.
Returns:
`True` only for an explicitly and consistently read-only MCP tool.
"""
from deepagents_code.auto_mode import mcp_tool_is_coherently_read_only
return mcp_tool_is_coherently_read_only(tool)
class ServerRuntime(NamedTuple):
"""The one-per-process result with named slots to prevent transposition."""
agent: Any
"""Compiled LangGraph agent graph served as `agent`."""
backend: CompositeBackend
"""Composite backend the agent and its operations were built with."""
offload: OffloadOperation
"""Server-owned thread offload operation bound to `backend`."""
mcp_server_info: list[MCPServerInfo] | None = None
"""Workspace-scoped MCP metadata for the interactive client."""
model_metadata: ModelMetadata | None = None
"""Resolved startup model properties for the interactive client."""
model_environment: Mapping[str, str] | None = None
"""Immutable workspace environment shared by metadata resolution and inference."""
async def _make_graphs(
*,
config_override: ServerConfig | None = None,
project_context_override: ProjectContext | None = None,
sandbox_backend_override: SandboxBackendProtocol | None = None,
) -> ServerRuntime:
"""Create the agent graph and the backend carrying its shared resources.
Reads `DEEPAGENTS_CODE_SERVER_*` env vars via `ServerConfig.from_env()`
(the inverse of `ServerConfig.to_env()` used by the app process), resolves a
model, assembles tools, and compiles the agent graph.
Returns:
The agent graph, its configured composite backend, and the server-owned
offload operation bound to that backend.
"""
config = config_override or ServerConfig.from_env()
workspace_path = (
project_context_override.user_cwd
if project_context_override is not None
else Path(config.cwd)
if config.cwd is not None
else None
)
# Offload the workspace environment snapshot off the event loop. Dotenv
# discovery walks parent directories (`Path.resolve()`, `is_file()`) and
# reads up to three files, and `snapshot_from_environment` adds
# `find_project_root()` -> `Path.cwd()` — all of which `blockbuster`
# rejects when invoked directly from the server loop (see issue #5043),
# for the same reason as the offload in `_make_graphs_in_environment`.
def _resolve_workspace_environment() -> tuple[
Mapping[str, str], CredentialsSnapshot, EnvironmentContext, bool
]:
from deepagents_code.config import (
Credentials,
_ensure_bootstrap,
_preview_dotenv_environ,
is_langsmith_redaction_enabled,
use_environment,
)
# Finish the one-time global credential publication before pinning
# tracing. A later lazy import of `agent` must not overwrite the pin.
_ensure_bootstrap()
environ = MappingProxyType(_preview_dotenv_environ(start_path=workspace_path))
with use_environment(environ):
redact = is_langsmith_redaction_enabled()
return (
environ,
Credentials.snapshot_from_environment(
start_path=workspace_path,
environ=environ,
),
use_environment,
redact,
)
(
workspace_env,
workspace_credentials,
use_environment,
redact,
) = await asyncio.to_thread(_resolve_workspace_environment)
with use_environment(workspace_env):
_configure_server_tracing(workspace_env, redact=redact)
return await _make_graphs_in_environment(
config=config,
project_context_override=project_context_override,
workspace_env=workspace_env,
workspace_credentials=workspace_credentials,
sandbox_backend_override=sandbox_backend_override,
)
async def _make_graphs_in_environment(
*,
config: ServerConfig,
project_context_override: ProjectContext | None,
workspace_env: Mapping[str, str],
workspace_credentials: CredentialsSnapshot,
sandbox_backend_override: SandboxBackendProtocol | None = None,
) -> ServerRuntime:
"""Build one runtime while its immutable workspace environment is active.
Returns:
Agent graph and its workspace-bound resources.
"""
# Offload cwd/path resolution and the lazy settings bootstrap off the event
# loop. On Windows, `Path.resolve()` / `Path.cwd()` call `os.getcwd()`, which
# `blockbuster` rejects when invoked directly from the server loop (see
# issue #5043). Importing `deepagents_code.agent` / first `settings` access
# can also trigger `find_project_root()` -> `Path.cwd()`.
def _resolve_project_context_and_settings() -> tuple[
ProjectContext | None,
Any,
Any,
Any,
Any,
Any,
]:
project_context = project_context_override or get_server_project_context()
from deepagents_code.agent import create_cli_agent, load_async_subagents
from deepagents_code.config import (
create_model,
is_memory_auto_save_enabled,
resolve_auto_classifier_model_for_provider,
)
return (
project_context,
create_cli_agent,
load_async_subagents,
create_model,
is_memory_auto_save_enabled,
resolve_auto_classifier_model_for_provider,
)
(
project_context,
create_cli_agent,
load_async_subagents,
create_model,
is_memory_auto_save_enabled,
resolve_auto_classifier_model_for_provider,
) = await asyncio.to_thread(_resolve_project_context_and_settings)
# Offload to a worker thread: `create_model` does blocking disk IO for some
# providers (e.g. the `openai_codex` token store currently acquires a file
# lock via `langchain-openai` that calls `os.mkdir`), which `blockbuster`
# rejects on the server event loop.
result = await asyncio.to_thread(
create_model,
config.model,
extra_kwargs=config.model_params,
profile_overrides=config.profile_overrides,
cli_max_retries=config.cli_max_retries,
)
result.apply_to_runtime_state()
tools, mcp_server_info, mcp_tools, read_only_builtins = await _build_tools(
config,
project_context,
tavily_api_key=workspace_credentials.tavily_api_key,
)
read_only_context_tools = _criteria_context_tools(
tools, mcp_tools, read_only_builtins
)
# Create sandbox backend if a sandbox provider is configured.
# The context manager is created here in the factory, but its reference is
# stored in a module-level global (and cleaned up via atexit) so the sandbox
# lives for the entire server process lifetime. `make_graph` caches the built
# graph, so this runs once per process despite LangGraph's per-run factory
# invocation.
global _sandbox_cm, _sandbox_backend # noqa: PLW0603
sandbox_backend = sandbox_backend_override
if (sandbox_type := config.sandbox_type) and sandbox_backend is None:
from deepagents_code.integrations.sandbox_factory import create_sandbox
try:
context, backend = await _open_sandbox(
lambda: create_sandbox(
sandbox_type,
sandbox_id=config.sandbox_id,
snapshot_name=config.sandbox_snapshot_name,
setup_script_path=config.sandbox_setup,
)
)
_sandbox_cm = context
_sandbox_backend = backend
sandbox_backend = backend
atexit.register(_close_sandbox, context)
except ImportError:
logger.exception(
"Sandbox provider '%s' is not installed", config.sandbox_type
)
_print_startup_error(
f"Sandbox provider '{config.sandbox_type}' is not installed"
)
sys.exit(1)
except NotImplementedError:
logger.exception("Sandbox type '%s' is not supported", config.sandbox_type)
_print_startup_error(
f"Sandbox type '{config.sandbox_type}' is not supported"
)
sys.exit(1)
except ValueError as exc:
logger.exception(
"Invalid sandbox configuration for '%s'", config.sandbox_type
)
_print_startup_error(f"Invalid sandbox configuration: {exc}")
sys.exit(1)
except Exception as exc:
logger.exception("Sandbox creation failed for '%s'", config.sandbox_type)
_print_startup_error(
f"Sandbox creation failed for '{config.sandbox_type}': {exc}"
)
sys.exit(1)
extension_registry: ExtensionRegistry | None = None
def _create_cli_graphs_sync() -> ServerRuntime:
async_subagents = load_async_subagents() or None
auto_mode_enabled = config.interactive and sandbox_backend is None
interpreter_config = (
InterpreterConfig.from_resolver(
get_config_resolver(),
ptc=config.interpreter_ptc,
ptc_acknowledge_unsafe=config.interpreter_ptc_acknowledge_unsafe,
)
if config.enable_interpreter
else None
)
agent, composite_backend = create_cli_agent(
model=result.model,
assistant_id=config.assistant_id,
tools=tools,
mcp_tools=mcp_tools,
sandbox=sandbox_backend,
sandbox_type=config.sandbox_type,
system_prompt=config.system_prompt,
interactive=config.interactive,
auto_approve=config.auto_approve,
auto_mode_enabled=auto_mode_enabled,
interrupt_shell_only=config.interrupt_shell_only,
shell_allow_list=config.shell_allow_list,
fs_tools=config.allow_fs_tools,
enable_ask_user=config.enable_ask_user,
enable_memory=config.enable_memory,
memory_auto_save=is_memory_auto_save_enabled(),
enable_skills=config.enable_skills,
enable_shell=config.enable_shell,
enable_interpreter=config.enable_interpreter,
interpreter_config=interpreter_config,
rubric_model=config.rubric_model,
rubric_max_iterations=config.rubric_max_iterations,
auto_classifier_model=resolve_auto_classifier_model_for_provider(
result.provider,
config.auto_classifier_model,
),
recursion_limit=config.recursion_limit,
mcp_server_info=mcp_server_info,
cwd=project_context.user_cwd if project_context is not None else config.cwd,
project_context=project_context,
async_subagents=async_subagents,
goal_criteria_tools=read_only_context_tools,
rubric_grader_tools=read_only_context_tools,
model_retries=result.model_retries,
cli_max_retries=result.cli_max_retries,
summarization_model=config.summarization_model,
extension_registry=extension_registry,
environ=workspace_env,
credentials_snapshot=workspace_credentials,
model_result=result,
profile_overrides=config.profile_overrides,
)
from deepagents_code.offload_middleware import offload_operation_from
offload = offload_operation_from(composite_backend)
if offload is None:
msg = (
"Agent backend did not publish its offload operation; "
"/offload has no server implementation."
)
raise RuntimeError(msg)
return ServerRuntime(
agent=agent,
backend=composite_backend,
offload=offload,
mcp_server_info=mcp_server_info,
model_metadata=ModelMetadata(
result.model_name,
result.provider,
result.context_limit,
result.unsupported_modalities,
),
model_environment=workspace_env,
)
from deepagents_code._env_vars import EXPERIMENTAL, is_env_truthy
if is_env_truthy(EXPERIMENTAL, environ=workspace_env):
from deepagents_code.extensions import ExtensionMode, load_extensions
from deepagents_code.extensions.runtime import bind_server_extensions
extension_result = await load_extensions(
cwd=(
project_context.user_cwd
if project_context is not None
else Path(config.cwd)
if config.cwd is not None
else None
),
mode=(
ExtensionMode.INTERACTIVE
if config.interactive
else ExtensionMode.HEADLESS
),
project_root=(
project_context.project_root or project_context.user_cwd
if project_context is not None
else None
),
project_trust_granted=config.trust_project_extensions,
cli_paths=tuple(Path(path) for path in config.extension_paths),
)
for message in extension_result.errors:
logger.warning("Extension not loaded: %s", message)
if extension_result.active:
extension_registry = extension_result.registry
bind_server_extensions(extension_result)
try:
return await asyncio.to_thread(_create_cli_graphs_sync)
except BaseException:
if extension_registry is not None:
from deepagents_code.extensions.runtime import shutdown_server_extensions
await shutdown_server_extensions()
raise
def _build_runtime_factory(
builder: Callable[[], Awaitable[ServerRuntime]] | None = None,
) -> Callable[[], Awaitable[ServerRuntime]]:
"""Build the cached factory for all server-owned runtime resources.
The cache is load-bearing, not an optimization: MCP discovery, sandbox
creation, and `atexit` registration each must happen exactly once. Building
per request would re-discover MCP servers, leak sandbox sessions, and stack
duplicate `atexit` handlers. Two consumers now share this cache -- the
interactive graph and the offload HTTP route -- so both must resolve the
*same* agent, backend, and compaction policy for a server-side archive to be
readable by the agent.
The cache and its lock live in this closure rather than in module-level
globals, so importing this module introduces no shared mutable state; the
single process-wide instance is created explicitly at the bottom of the
module.
Args:
builder: Optional alternate builder used by unit tests.
Returns:
Async runtime factory shared by the graph and custom operation API.
"""
runtime: ServerRuntime | None = None
lock = asyncio.Lock()
async def get_runtime() -> ServerRuntime:
"""Return the cached interactive graph and operation resources."""
nonlocal runtime
if runtime is None:
async with lock:
if runtime is None:
try:
from deepagents_code.configuration.service import (
require_healthy_managed_config,
)
await asyncio.to_thread(
require_healthy_managed_config,
refresh=True,
)
runtime = await (builder or _make_graphs)()
except Exception as exc: # noqa: BLE001 # startup barrier
emit_startup_failure(exc)
sys.exit(1)
return runtime
return get_runtime
def _build_graph_factory(
builder: Callable[[], Awaitable[ServerRuntime]] | None = None,
) -> Callable[[], Awaitable[Any]]:
"""Build a cached graph factory, for tests.
`langgraph.json` references the module-level `make_graph`, which delegates to
`get_server_runtime`; nothing in production calls this. It survives so unit
tests can inject a builder.
Args:
builder: Optional alternate runtime builder used by unit tests.
Returns:
Async graph factory for the interactive `agent` graph.
"""
get_runtime = _build_runtime_factory(builder)
async def make_graph() -> Any: # noqa: ANN401
"""Create or return the cached agent graph for `langgraph dev`.
Returns:
Compiled LangGraph agent graph.
"""
return (await get_runtime()).agent
return make_graph
_get_runtime = _build_runtime_factory()
_MAX_WORKSPACE_RUNTIMES = 32
_workspace_runtimes: OrderedDict[str, ServerRuntime] = OrderedDict()
_workspace_runtime_lock = asyncio.Lock()
_sandbox_workspace_id: str | None = None
def _runtime_cache_key(
binding: WorkspaceBinding, *, current_config_fingerprint: str | None = None
) -> str:
"""Key the runtime cache on full runtime identity, not just the binding.
The binding's `resource_key` mixes workspace identity with the policy
fingerprint; the runtime cache must *also* change when the full runtime
identity (model, model params, prompt, runtime-only fields) changes, so a
model switch rebuilds the runtime while the durable binding — and its
checkpoints/history — are preserved.
Args:
binding: The durable binding (workspace identity).
current_config_fingerprint: The runtime fingerprint of the *current*
resolved config, when the caller has resolved one. Falls back to
the binding's recorded fingerprint otherwise.
Returns:
The cache key for this binding's current runtime identity.
"""
from deepagents_code.workspace import canonical_fingerprint
return canonical_fingerprint(
{
"runtime_fingerprint": (
current_config_fingerprint
or binding.runtime_fingerprint
or binding.config_fingerprint
),
"workspace_id": binding.workspace_id,
}
)
def _cached_workspace_runtime(
binding: WorkspaceBinding, *, current_config_fingerprint: str | None = None
) -> ServerRuntime | None:
"""Return and refresh a cached runtime for one workspace binding."""
key = _runtime_cache_key(
binding, current_config_fingerprint=current_config_fingerprint
)
cached = _workspace_runtimes.get(key)
if cached is None:
return None
_workspace_runtimes.move_to_end(key)
return cached
def _claim_sandbox_workspace(
sandbox_type: str | None,
binding: WorkspaceBinding,
) -> None:
"""Reserve the process-wide sandbox for the first requesting workspace."""
global _sandbox_workspace_id # noqa: PLW0603 # process-lifetime ownership
_validate_sandbox_workspace(sandbox_type, binding)
if sandbox_type:
_sandbox_workspace_id = binding.workspace_id
def _validate_sandbox_workspace(
sandbox_type: str | None, binding: WorkspaceBinding
) -> None:
"""Check sandbox ownership without reserving the process-wide sandbox."""
if not sandbox_type or _sandbox_workspace_id in {None, binding.workspace_id}:
return
reason = (
"a runtime for another workspace already exists and the configured "
"sandbox is process-wide"
)
# Built into a local first: `raise X.from_reason(...)` reads as a
# `from_reason` raise to ruff's DOC501.
conflict = WorkspaceConflictError.from_reason(
reason,
diagnostics=WorkspaceDiagnostics(
category="policy_drift",
reason=reason,
snapshot_status="unavailable",
),
)
raise conflict
def _remember_workspace_runtime(
binding: WorkspaceBinding,
runtime: ServerRuntime,
*,
current_config_fingerprint: str | None = None,
) -> None:
"""Cache one workspace runtime and enforce the bounded LRU size."""
_workspace_runtimes[
_runtime_cache_key(
binding, current_config_fingerprint=current_config_fingerprint
)
] = runtime
if len(_workspace_runtimes) > _MAX_WORKSPACE_RUNTIMES:
_workspace_runtimes.popitem(last=False)
async def _default_workspace_binding(config: ServerConfig) -> WorkspaceBinding | None:
"""Resolve the launch workspace represented by the server configuration.
Returns:
The canonical launch binding, or `None` without a configured workspace.
"""
if config.cwd is None:
return None
def _bind() -> WorkspaceBinding:
# First pass resolves identity only (cwd plus project root); its
# fingerprints are digests of an empty policy and are discarded.
identity = resolve_workspace(config.cwd)
# The shared policy resolver honors the explicit launch root while
# keeping the durable identity consistent with workspace validation.
resolved = config.resolve_workspace(identity.cwd, identity.project_root)
return resolve_workspace(
identity.cwd,
resolved.to_workspace_payload(),
config_fingerprint=resolved.workspace_fingerprint(),
)
return await asyncio.to_thread(_bind)
async def _resolve_bound_workspace_config(
binding: WorkspaceBinding,
) -> ServerConfig:
"""Resolve current workspace policy and reject drift from its binding.
Refusals name the fields that drifted. This runs on every request, and it
reads the extension trust store each time, so a transient read failure
reports as a policy change; without the field names that refusal is not
diagnosable. Only allowlisted, non-path policy values reach the attached
diagnostics: paths, model parameters, and prompts are never reported.
Returns:
The current server configuration resolved for the workspace.
"""
config = await asyncio.to_thread(ServerConfig.from_env)
def _resolve_current() -> ServerConfig:
resolved = config.resolve_workspace(binding.cwd, binding.project_root)
return resolved.preserve_bound_extension_trust(binding.workspace_config())
current_config = await asyncio.to_thread(_resolve_current)
bound_policy = binding.workspace_config()
snapshot = await get_snapshot_for_binding(binding)
snapshot_status = "current" if snapshot is not None else "unavailable"
# Fail closed on a disappeared extension-trust grant. A grant recorded at
# bind time that the trust store no longer reports is either a genuine
# revocation or a transient store-read failure (which fails closed to
# `False`). `preserve_bound_extension_trust` only *adds* privilege, so
# without this guard a vanished grant would be silently dropped — the policy
# payload still matches (it omits nothing) but the runtime fingerprint
# changes and the rebuild would run without the grant. Refuse instead.
if (
bound_policy.get("trust_project_extensions") is True
and current_config.trust_project_extensions is not True
):
reason = (
"the project's extension trust recorded at binding is no longer "
"present; re-bind the thread to re-evaluate trust"
)
conflict = WorkspaceConflictError.from_reason(
reason,
diagnostics=WorkspaceDiagnostics(
category="policy_drift",
reason=reason,
snapshot_status=snapshot_status,
),
)
logger.warning(
"Workspace %s extension trust changed since binding", binding.cwd
)
raise conflict
current_snapshot = snapshot_for_payload(current_config.to_workspace_payload())
drifted = drifted_project_fields(
bound_policy, current_config.to_project_workspace_policy()
)
if drifted:
fields = ", ".join(drifted)
changes = diff_snapshots(snapshot, current_snapshot, changed_names=drifted)
conflict = WorkspaceConflictError.from_reason(
f"{PROJECT_POLICY_DRIFT_REASON} ({fields})",
diagnostics=WorkspaceDiagnostics(
category="policy_drift",
reason=PROJECT_POLICY_DRIFT_REASON,
changes=changes,
snapshot_status=snapshot_status,
),
)
logger.warning(
"Workspace %s project policy drifted since binding: %s",
binding.cwd,
conflict.diagnostics.log_summary()
if conflict.diagnostics is not None
else fields,
)
raise conflict
# Durable access-policy compatibility: only trust/tool/sandbox/approval
# policy (and workspace identity) invalidate a binding. Cosmetic model
# settings and runtime-only fields are excluded from the policy payload, so
# a model switch no longer refuses the thread — it rebuilds the runtime via
# the runtime-fingerprint cache key instead.
current_policy = current_config.to_workspace_payload()
if binding.policy_fingerprint:
policy_changed = binding.policy_fingerprint != canonical_fingerprint(
{
"cwd": binding.cwd,
"policy": current_policy,
"project_root": binding.project_root,
}
)
else:
# Pre-v4 row: no policy fingerprint recorded. Fall back to the strict
# full-fingerprint comparison (fail closed on any change).
policy_changed = (
current_config.workspace_fingerprint() != binding.config_fingerprint
)
if policy_changed:
payload_drift = sorted(
key
for key in bound_policy
if bound_policy.get(key) != current_policy.get(key)
)
changes = diff_snapshots(
snapshot, current_snapshot, changed_names=payload_drift
)
conflict = WorkspaceConflictError.from_reason(
SERVER_CONFIG_DRIFT_REASON,
diagnostics=WorkspaceDiagnostics(
category="config_drift",
reason=SERVER_CONFIG_DRIFT_REASON,
changes=changes,
snapshot_status=snapshot_status,
),
)
logger.warning(
"Workspace %s access policy changed since binding: %s",
binding.cwd,
conflict.diagnostics.log_summary()
if conflict.diagnostics is not None
else SERVER_CONFIG_DRIFT_REASON,
)
raise conflict
if current_config.runtime_fingerprint() != (
binding.runtime_fingerprint or binding.config_fingerprint
):
# Runtime identity (model/params/prompt/runtime fields) changed without
# any policy drift. Not a refusal: log it and let the cache key rebuild.