-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault_runtime.py
More file actions
1826 lines (1684 loc) · 76 KB
/
default_runtime.py
File metadata and controls
1826 lines (1684 loc) · 76 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
"""Default runtime implementation - orchestrates agent execution."""
from __future__ import annotations
import importlib
import inspect
import logging
import time
from typing import TYPE_CHECKING, Any
from uuid import uuid4
if TYPE_CHECKING:
from openagents.config.schema import AgentDefinition, AppConfig
from pydantic import BaseModel, Field
from openagents.errors.exceptions import (
BudgetExhausted,
ConfigError,
MaxStepsExceeded,
ModelRetryError,
OpenAgentsError,
OutputValidationError,
PatternError,
PermanentToolError,
)
from openagents.interfaces.agent_router import HandoffSignal
from openagents.interfaces.context import ContextAssemblerPlugin, ContextAssemblyResult
from openagents.interfaces.events import (
CONTEXT_COMPACT_FAILED,
CONTEXT_COMPACT_SUCCEEDED,
CONTEXT_CREATED,
MEMORY_COMPACT_FAILED,
MEMORY_COMPACT_SUCCEEDED,
MEMORY_INJECT_FAILED,
MEMORY_INJECTED,
MEMORY_WRITEBACK_FAILED,
MEMORY_WRITEBACK_SUCCEEDED,
RUN_COMPLETED,
RUN_FAILED,
RUN_REQUESTED,
RUN_VALIDATED,
SESSION_ACQUIRED,
EventBusPlugin,
)
from openagents.interfaces.pattern import PatternPlugin
from openagents.interfaces.runtime import (
RUN_STOP_COMPLETED,
RUN_STOP_FAILED,
RUN_STOP_TIMEOUT,
ErrorDetails,
RunRequest,
RunResult,
RuntimePlugin,
RunUsage,
StopReason,
)
from openagents.interfaces.session import SessionArtifact, SessionCheckpoint
from openagents.interfaces.tool import (
ToolExecutionRequest,
ToolExecutionResult,
ToolExecutionSpec,
ToolExecutor,
ToolExecutorPlugin,
)
from openagents.interfaces.typed_config import TypedConfigPluginMixin
logger = logging.getLogger("openagents")
# State-dict key used by the durable-run machinery to stash usage /
# artifacts / step counter across checkpoints. Private to this module.
_DURABLE_STATE_KEY = "__durable__"
def _supports_parameter(fn: Any, name: str) -> bool:
params = inspect.signature(fn).parameters.values()
return any(param.name == name or param.kind is inspect.Parameter.VAR_KEYWORD for param in params)
async def _maybe_await(value: Any) -> Any:
if inspect.isawaitable(value):
return await value
return value
def _import_symbol(path: str) -> Any:
if "." not in path:
raise ValueError(f"Invalid impl path: '{path}'")
module_name, attr_name = path.rsplit(".", 1)
module = importlib.import_module(module_name)
return getattr(module, attr_name)
def _instantiate(factory: Any, config: dict[str, Any]) -> Any:
if not callable(factory):
return factory
try:
return factory(config=config)
except TypeError as exc:
raise TypeError(f"Could not instantiate runtime dependency from {factory!r}: {exc}") from exc
class _DefaultToolExecutor(ToolExecutorPlugin):
async def execute(self, request: ToolExecutionRequest) -> ToolExecutionResult:
try:
data = await request.tool.invoke(request.params or {}, request.context)
return ToolExecutionResult(
tool_id=request.tool_id,
success=True,
data=data,
)
except Exception as exc:
return ToolExecutionResult(
tool_id=request.tool_id,
success=False,
error=str(exc),
exception=exc,
)
async def execute_stream(self, request: ToolExecutionRequest):
async for chunk in request.tool.invoke_stream(request.params or {}, request.context):
yield chunk
class _DefaultContextAssembler(ContextAssemblerPlugin):
async def assemble(
self,
*,
request: Any,
session_state: dict[str, Any],
session_manager: Any,
) -> ContextAssemblyResult:
transcript: list[dict[str, Any]] = []
load_messages = getattr(session_manager, "load_messages", None)
if callable(load_messages):
transcript = await load_messages(request.session_id)
session_artifacts = []
list_artifacts = getattr(session_manager, "list_artifacts", None)
if callable(list_artifacts):
session_artifacts = await list_artifacts(request.session_id)
return ContextAssemblyResult(
transcript=transcript,
session_artifacts=session_artifacts,
)
async def finalize(
self,
*,
request: Any,
session_state: dict[str, Any],
session_manager: Any,
result: Any,
) -> Any:
return result
class _BoundTool:
def __init__(
self,
*,
tool_id: str,
tool: Any,
executor: ToolExecutor,
):
self._tool_id = tool_id
self._tool = tool
self._executor = executor
def execution_spec(self) -> ToolExecutionSpec:
get_spec = getattr(self._tool, "execution_spec", None)
if callable(get_spec):
return get_spec()
return ToolExecutionSpec()
@property
def durable_idempotent(self) -> bool:
return bool(getattr(self._tool, "durable_idempotent", True))
async def invoke(self, params: dict[str, Any], context: Any) -> ToolExecutionResult:
"""Bound invocation: call_id + approval gate + before/after hooks + executor.
Owns the per-call lifecycle: assigns ``call_id`` and stashes it in
``ctx.scratch['__current_call_id__']``; evaluates
``tool.requires_approval()`` and consults
``ctx.run_request.context_hints['approvals']``; runs
``before_invoke`` and ``after_invoke`` hooks around the executor.
Returns the executor's :class:`ToolExecutionResult` on success so
metadata (retry counts, timeouts, policy decisions) flows to events.
Raises on failure so the pattern fallback path still works.
"""
budget = getattr(getattr(context, "run_request", None), "budget", None)
usage = getattr(context, "usage", None)
if budget is not None and budget.max_tool_calls is not None and usage is not None:
if usage.tool_calls >= budget.max_tool_calls:
raise MaxStepsExceeded(f"Tool call limit ({budget.max_tool_calls}) exceeded").with_context(
agent_id=getattr(context, "agent_id", None),
session_id=getattr(context, "session_id", None),
run_id=getattr(getattr(context, "run_request", None), "run_id", None),
tool_id=self._tool_id,
)
call_id = uuid4().hex
scratch = getattr(context, "scratch", None)
if isinstance(scratch, dict):
scratch["__current_call_id__"] = call_id
# One-shot durable idempotency warning: emitted the first time a
# tool declaring durable_idempotent=False is invoked inside a
# durable run. Dedup key = (run_id, tool_id). Advisory only — we
# do not block the call.
run_request = getattr(context, "run_request", None)
if (
run_request is not None
and getattr(run_request, "durable", False)
and not self.durable_idempotent
and isinstance(scratch, dict)
):
warned: set[str] = scratch.setdefault("__idempotency_warned__", set())
if self._tool_id not in warned:
warned.add(self._tool_id)
event_bus = getattr(context, "event_bus", None)
if event_bus is not None and callable(getattr(event_bus, "emit", None)):
try:
await event_bus.emit(
"run.durable_idempotency_warning",
run_id=getattr(run_request, "run_id", ""),
tool_id=self._tool_id,
hint=(
f"Tool '{self._tool_id}' declares durable_idempotent=False; "
"on resume it may re-execute and repeat side effects."
),
)
except Exception: # noqa: BLE001
pass
if self._requires_approval(params, context):
event_bus = getattr(context, "event_bus", None)
if event_bus is not None and callable(getattr(event_bus, "emit", None)):
try:
await event_bus.emit(
"tool.approval_needed",
tool_id=self._tool_id,
call_id=call_id,
params=params or {},
)
except Exception:
pass
approvals = self._approvals_dict(context)
decision = approvals.get(call_id) if approvals else None
if decision is None and approvals:
decision = approvals.get("*")
if decision is None:
raise PermanentToolError(
f"Tool '{self._tool_id}' requires approval; no decision found for call_id '{call_id}'",
tool_name=self._tool_id,
hint=f"Inject context_hints['approvals']['{call_id}'] = 'allow' and re-run",
)
if decision == "deny":
raise PermanentToolError(
f"Tool '{self._tool_id}' denied by approval policy",
tool_name=self._tool_id,
)
before = getattr(self._tool, "before_invoke", None)
if callable(before):
await before(params or {}, context)
cancel_event = scratch.get("__cancel_event__") if isinstance(scratch, dict) else None
request = ToolExecutionRequest(
tool_id=self._tool_id,
tool=self._tool,
params=params or {},
context=context,
execution_spec=self.execution_spec(),
metadata={"bound_tool": True, "call_id": call_id},
cancel_event=cancel_event,
)
exception: BaseException | None = None
result: ToolExecutionResult | None = None
try:
result = await self._executor.execute(request)
if result.success:
if usage is not None:
usage.tool_calls += 1
return result
exception = (
result.exception
if result.exception is not None
else RuntimeError(result.error or f"Tool '{self._tool_id}' failed")
)
raise exception
except BaseException as exc:
if exception is None:
exception = exc
raise
finally:
after = getattr(self._tool, "after_invoke", None)
if callable(after):
try:
await after(
params or {},
context,
result.data if (result is not None and result.success) else None,
exception,
)
except Exception:
# after_invoke must not mask the original exception path.
pass
def _requires_approval(self, params: dict[str, Any], context: Any) -> bool:
check = getattr(self._tool, "requires_approval", None)
if not callable(check):
return False
try:
return bool(check(params or {}, context))
except Exception:
return False
def _approvals_dict(self, context: Any) -> dict[str, str] | None:
run_request = getattr(context, "run_request", None)
if run_request is None:
return None
hints = getattr(run_request, "context_hints", None)
if not isinstance(hints, dict):
return None
approvals = hints.get("approvals")
return approvals if isinstance(approvals, dict) else None
async def invoke_stream(self, params: dict[str, Any], context: Any):
request = ToolExecutionRequest(
tool_id=self._tool_id,
tool=self._tool,
params=params or {},
context=context,
execution_spec=self.execution_spec(),
metadata={"bound_tool": True},
)
async for chunk in self._executor.execute_stream(request):
yield chunk
async def invoke_batch(self, items, context):
"""Dispatch a batch through the executor (executor.execute_batch or sequential fallback).
Preserves the input ``item_id`` on each ``BatchResult`` and input order.
"""
from openagents.interfaces.tool import BatchResult
if not items:
return []
scratch = getattr(context, "scratch", None)
cancel_event = scratch.get("__cancel_event__") if isinstance(scratch, dict) else None
spec = self.execution_spec()
requests = [
ToolExecutionRequest(
tool_id=self._tool_id,
tool=self._tool,
params=it.params or {},
context=context,
execution_spec=spec,
metadata={"bound_tool": True, "batch_item_id": it.item_id},
cancel_event=cancel_event,
)
for it in items
]
batch_method = getattr(self._executor, "execute_batch", None)
if callable(batch_method):
results = await batch_method(requests)
else:
results = [await self._executor.execute(r) for r in requests]
out: list[BatchResult] = []
for item, res in zip(items, results):
if res.success:
out.append(BatchResult(item_id=item.item_id, success=True, data=res.data))
else:
out.append(
BatchResult(
item_id=item.item_id,
success=False,
error=res.error,
exception=res.exception,
)
)
return out
async def invoke_background(self, params, context):
"""Submit a long-running job via the wrapped tool.
Background jobs bypass the executor cancel/timeout race — their lifecycle
is owned by the tool implementation. ``before_invoke`` / ``after_invoke``
still run so hook-based instrumentation works.
"""
before = getattr(self._tool, "before_invoke", None)
if callable(before):
await before(params or {}, context)
handle = None
exception: BaseException | None = None
try:
handle = await self._tool.invoke_background(params or {}, context)
event_bus = getattr(context, "event_bus", None)
if event_bus is not None and callable(getattr(event_bus, "emit", None)):
try:
scratch = getattr(context, "scratch", None)
call_id = scratch.get("__current_call_id__") if isinstance(scratch, dict) else None
await event_bus.emit(
"tool.background.submitted",
tool_id=self._tool_id,
call_id=call_id or handle.job_id,
job_id=handle.job_id,
)
except Exception:
pass
return handle
except BaseException as exc:
exception = exc
raise
finally:
after = getattr(self._tool, "after_invoke", None)
if callable(after):
try:
await after(params or {}, context, handle, exception)
except Exception:
pass
async def poll_job(self, handle, context):
return await self._tool.poll_job(handle, context)
async def cancel_job(self, handle, context):
return await self._tool.cancel_job(handle, context)
async def fallback(self, error: Exception, params: dict[str, Any], context: Any) -> Any:
fallback = getattr(self._tool, "fallback", None)
if callable(fallback):
return await fallback(error, params, context)
raise error
def describe(self) -> dict[str, Any]:
describe = getattr(self._tool, "describe", None)
if callable(describe):
return describe()
return {"name": self._tool_id, "description": "", "parameters": {"type": "object"}}
def schema(self) -> dict[str, Any]:
schema = getattr(self._tool, "schema", None)
if callable(schema):
return schema()
return {"type": "object", "properties": {}, "required": []}
def __getattr__(self, name: str) -> Any:
return getattr(self._tool, name)
class DefaultRuntime(TypedConfigPluginMixin, RuntimePlugin):
"""Default runtime implementation.
What:
Owns the per-run orchestration: acquires the session lock,
runs ``context_assembler.assemble``, rebinds tools through the
``tool_executor`` (which owns policy evaluation internally),
then drives ``pattern.setup`` / ``memory.inject`` /
``pattern.execute`` / ``memory.writeback``, finally persists
the transcript and artifacts. Emits the full set of lifecycle
events declared in
:data:`openagents.interfaces.event_taxonomy.EVENT_SCHEMAS`.
Usage:
``{"runtime": {"type": "default"}}``. Optional
per-dependency overrides under ``config.tool_executor`` and
``config.context_assembler``.
Depends on:
- ``EventBusPlugin`` (top-level ``events``) for emit
- ``SessionManagerPlugin`` (top-level ``session``) for state
and transcript persistence
- the agent's ``memory`` / ``pattern`` / optional executor
plugins
"""
class McpRuntimeConfig(BaseModel):
"""Runtime-wide knobs for the shared MCP session pool (Phase 2/3).
All fields are optional; defaults preserve today's behaviour
(no cross-run pool, no eviction).
"""
max_pooled_sessions: int | None = None
max_idle_seconds: float | None = None
preflight_cache_success_ttl: float | None = None
class Config(BaseModel):
tool_executor: dict[str, Any] | None = None
context_assembler: dict[str, Any] | None = None
mcp: "DefaultRuntime.McpRuntimeConfig" = Field(default_factory=lambda: DefaultRuntime.McpRuntimeConfig())
def __init__(
self,
config: dict[str, Any] | None = None,
):
super().__init__(
config=config or {},
)
self._init_typed_config()
self._event_bus: EventBusPlugin | None = None
self._session_manager: Any | None = None
self._diagnostics: Any | None = None
self._llm_clients: dict[str, Any | None] = {}
self._tool_executor: ToolExecutor | None = None
self._context_assembler: ContextAssemblerPlugin | None = None
self._agent_router: Any | None = None
from ._mcp_coordinator import _McpSessionCoordinator
mcp_cfg = self.cfg.mcp
self._mcp_coordinator = _McpSessionCoordinator(
max_pooled_sessions=mcp_cfg.max_pooled_sessions,
max_idle_seconds=mcp_cfg.max_idle_seconds,
)
@property
def event_bus(self) -> EventBusPlugin:
if self._event_bus is None:
raise RuntimeError("EventBus not initialized. Call load_runtime_components() first.")
return self._event_bus
@property
def session_manager(self) -> Any:
if self._session_manager is None:
raise RuntimeError("SessionManager not initialized. Call load_runtime_components() first.")
return self._session_manager
async def run(
self,
*,
request: RunRequest,
app_config: "AppConfig",
agents_by_id: dict[str, "AgentDefinition"],
agent_plugins: Any = None,
) -> RunResult:
"""Execute an agent run."""
from openagents.plugins.loader import load_agent_plugins
agent = agents_by_id.get(request.agent_id)
if agent is None:
from openagents.errors.suggestions import near_match
available = sorted(agents_by_id.keys())
guess = near_match(request.agent_id, available)
extra = f" Did you mean '{guess}'?" if guess else ""
raise ValueError(f"Unknown agent id: '{request.agent_id}'.{extra} Available: {available}")
if agent_plugins is None:
plugins = load_agent_plugins(agent)
else:
plugins = agent_plugins
await self._event_bus.emit(
RUN_REQUESTED,
agent_id=request.agent_id,
session_id=request.session_id,
input_text=request.input_text,
run_id=request.run_id,
)
await self._event_bus.emit(
"session.run.started",
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
input_text=request.input_text,
)
llm_client = self._get_llm_client(agent)
await self._event_bus.emit(
RUN_VALIDATED,
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
)
usage = RunUsage()
artifacts = []
tool_executor = self._resolve_tool_executor(agent_plugins)
context_assembler = self._resolve_context_assembler(agent_plugins)
started_at = time.perf_counter()
# Diagnostics wiring: record metrics from pattern.call_llm and
# maintain a tool-call chain that capture_error_snapshot can read.
diag = self._diagnostics
diag_tool_chain: list[dict[str, Any]] = []
diag_llm_handler = None
diag_llm_fail_handler = None
diag_tool_called_handler = None
if diag is not None:
from openagents.interfaces.diagnostics import LLMCallMetrics as _LLMCallMetrics
def _diag_llm_handler(event):
metrics = (event.payload or {}).get("_metrics")
if isinstance(metrics, _LLMCallMetrics):
diag.record_llm_call(request.run_id, metrics)
def _diag_tool_called_handler(event):
payload = event.payload or {}
entry = {
"tool_id": payload.get("tool_id"),
"params": payload.get("params"),
}
call_id = payload.get("call_id")
if call_id is not None:
entry["call_id"] = call_id
diag_tool_chain.append(entry)
diag_llm_handler = _diag_llm_handler
diag_llm_fail_handler = _diag_llm_handler
diag_tool_called_handler = _diag_tool_called_handler
self._event_bus.subscribe("llm.succeeded", diag_llm_handler)
self._event_bus.subscribe("llm.failed", diag_llm_fail_handler)
self._event_bus.subscribe("tool.called", diag_tool_called_handler)
resumed_from_checkpoint: SessionCheckpoint | None = None
try:
async with self._session_manager.session(request.session_id) as session_state:
await self._event_bus.emit(
SESSION_ACQUIRED,
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
)
session_state.pop("_runtime_last_output", None)
# --- Explicit resume entry point ---
# When request.resume_from_checkpoint is set, we skip the
# normal context_assembler.assemble() path and build the
# assembly from the loaded checkpoint's state instead.
if request.resume_from_checkpoint:
checkpoint = await self._session_manager.load_checkpoint(
request.session_id, request.resume_from_checkpoint
)
if checkpoint is None:
available = await self._list_checkpoint_ids(request.session_id)
hint = (
f"No checkpoint '{request.resume_from_checkpoint}' for session "
f"'{request.session_id}'. Available: {available}"
if available
else f"No checkpoints exist for session '{request.session_id}'."
)
raise ConfigError(
f"Unknown resume_from_checkpoint '{request.resume_from_checkpoint}'",
hint=hint,
)
resumed_from_checkpoint = checkpoint
ckpt_state = dict(checkpoint.state or {})
transcript_full = list(ckpt_state.get("_session_transcript", []))
if checkpoint.transcript_length and checkpoint.transcript_length <= len(transcript_full):
transcript_full = transcript_full[: checkpoint.transcript_length]
ckpt_artifacts_raw = list(ckpt_state.get("_session_artifacts", []))
if checkpoint.artifact_count and checkpoint.artifact_count <= len(ckpt_artifacts_raw):
ckpt_artifacts_raw = ckpt_artifacts_raw[: checkpoint.artifact_count]
ckpt_artifacts = [
SessionArtifact.from_dict(item) if isinstance(item, dict) else item
for item in ckpt_artifacts_raw
]
assembly = ContextAssemblyResult(
transcript=transcript_full,
session_artifacts=ckpt_artifacts,
metadata={"resumed_from_checkpoint": request.resume_from_checkpoint},
)
# Merge the checkpoint's saved state (minus private keys) into session_state
# so subsequent pattern.execute() sees the same scratch data it had.
for key, value in ckpt_state.items():
if key.startswith("_session_"):
continue
session_state[key] = value
# Rehydrate usage / artifacts from the durable blob (if any).
durable_blob = ckpt_state.get(_DURABLE_STATE_KEY) or {}
blob_usage = durable_blob.get("usage")
if isinstance(blob_usage, dict):
try:
restored = RunUsage.model_validate(blob_usage)
usage.llm_calls = restored.llm_calls
usage.tool_calls = restored.tool_calls
usage.input_tokens = restored.input_tokens
usage.output_tokens = restored.output_tokens
usage.total_tokens = restored.total_tokens
usage.input_tokens_cached = restored.input_tokens_cached
usage.input_tokens_cache_creation = restored.input_tokens_cache_creation
usage.cost_usd = restored.cost_usd
usage.cost_breakdown = dict(restored.cost_breakdown)
except Exception: # noqa: BLE001
logger.exception("failed to rehydrate usage from resume checkpoint")
from openagents.interfaces.runtime import RunArtifact as _RunArtifact
blob_artifacts = durable_blob.get("artifacts")
if isinstance(blob_artifacts, list):
for item in blob_artifacts:
try:
if isinstance(item, dict):
artifacts.append(_RunArtifact.model_validate(item))
except Exception: # noqa: BLE001
logger.exception("failed to rehydrate artifact on resume")
await self._event_bus.emit(
"context.assemble.completed",
transcript_size=len(assembly.transcript),
artifact_count=len(assembly.session_artifacts),
duration_ms=0,
)
else:
await self._run_context_compact(
agent=agent,
context_assembler=context_assembler,
request=request,
session_state=session_state,
)
await self._event_bus.emit("context.assemble.started")
assemble_started_at = time.perf_counter()
assembly = await context_assembler.assemble(
request=request,
session_state=session_state,
session_manager=self._session_manager,
)
assemble_duration_ms = int((time.perf_counter() - assemble_started_at) * 1000)
await self._event_bus.emit(
"context.assemble.completed",
transcript_size=len(assembly.transcript),
artifact_count=len(assembly.session_artifacts),
duration_ms=assemble_duration_ms,
)
self._apply_runtime_budget(pattern=plugins.pattern, agent=agent)
bound_tools = self._bind_tools(plugins.tools, tool_executor)
mcp_pool = await self._mcp_coordinator.get_or_create(request.session_id)
await self._run_tool_preflight(
tools=plugins.tools,
request=request,
mcp_pool=mcp_pool,
)
await self._mcp_coordinator.warmup_eager(mcp_pool, plugins.tools.values())
await self._setup_pattern(
pattern=plugins.pattern,
request=request,
state=session_state,
tools=bound_tools,
llm_client=llm_client,
llm_options=agent.llm,
transcript=assembly.transcript,
session_artifacts=assembly.session_artifacts,
assembly_metadata=assembly.metadata,
tool_executor=tool_executor,
usage=usage,
artifacts=artifacts,
)
# Seed a per-run cancel event so tools can race against external
# cancellation. External callers set the event to request cancel.
import asyncio as _asyncio
pattern_ctx = getattr(plugins.pattern, "context", None)
if pattern_ctx is not None and isinstance(getattr(pattern_ctx, "scratch", None), dict):
pattern_ctx.scratch.setdefault("__cancel_event__", _asyncio.Event())
pattern_ctx.scratch["__mcp_session_pool__"] = mcp_pool
if diag is not None:
# Expose the tool-call chain on the pattern's RunContext so
# DiagnosticsPlugin.capture_error_snapshot can read it if
# an exception fires before we return.
pattern_ctx.scratch["_diag_tool_chain"] = diag_tool_chain
await self._event_bus.emit(
CONTEXT_CREATED,
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
)
self._enforce_duration_budget(request=request, started_at=started_at)
# Skip memory.inject on explicit resume — the checkpoint's
# transcript already contains the injected memory from the
# original run, and re-injecting is not idempotent for
# memory plugins with side effects.
if resumed_from_checkpoint is None:
await self._run_memory_inject(agent=agent, memory=plugins.memory, pattern=plugins.pattern)
self._enforce_duration_budget(request=request, started_at=started_at)
# --- Durable step-checkpoint subscription (opt-in) ---
checkpoint_handler = None
if request.durable:
checkpoint_handler = self._build_step_checkpoint_handler(
run_id=request.run_id,
session_id=request.session_id,
session_state=session_state,
pattern=plugins.pattern,
usage=usage,
artifacts=artifacts,
)
self._event_bus.subscribe("tool.succeeded", checkpoint_handler)
self._event_bus.subscribe("llm.succeeded", checkpoint_handler)
output_type = request.output_type
max_retries = (
request.budget.max_validation_retries
if request.budget is not None and request.budget.max_validation_retries is not None
else 3
)
max_resume = (
request.budget.max_resume_attempts
if request.budget is not None and request.budget.max_resume_attempts is not None
else 3
)
resume_attempt = 0
attempts = 0
validation_exhausted: OutputValidationError | None = None
result: Any = None
try:
# Durable outer loop: catches OpenAgentsError with
# exc.retryable=True and resumes from the most recent
# checkpoint. Any exc.retryable=False error propagates.
while True:
try:
raw = await plugins.pattern.execute()
self._enforce_duration_budget(request=request, started_at=started_at)
validation_exhausted = None
finalize_fn = getattr(plugins.pattern, "finalize", None)
if finalize_fn is None:
# Duck-typed pattern without finalize hook: skip validation.
result = raw
finalize_enabled = False
else:
finalize_enabled = True
while finalize_enabled:
try:
result = await finalize_fn(raw, output_type)
break
except ModelRetryError as retry_exc:
attempts += 1
if max_retries is not None and attempts > max_retries:
validation_exhausted = OutputValidationError(
str(retry_exc),
output_type=output_type,
attempts=attempts,
last_validation_error=retry_exc.validation_error,
).with_context(
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
)
break
pattern_ctx = getattr(plugins.pattern, "context", None)
if pattern_ctx is not None:
pattern_ctx.scratch["last_validation_error"] = {
"attempt": attempts,
"message": str(retry_exc),
"expected_schema": (
output_type.model_json_schema() if output_type is not None else {}
),
}
await self._event_bus.emit(
"validation.retry",
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
attempt=attempts,
error=str(retry_exc),
)
raw = await plugins.pattern.execute()
self._enforce_duration_budget(request=request, started_at=started_at)
break # durable outer loop success
except OpenAgentsError as exc:
if not request.durable or not exc.retryable:
raise
durable_blob = session_state.get(_DURABLE_STATE_KEY) or {}
checkpoint_id = durable_blob.get("checkpoint_id")
if checkpoint_id is None:
# No checkpoint written yet — nothing to resume to.
raise
if resume_attempt >= max_resume:
await self._event_bus.emit(
"run.resume_exhausted",
run_id=request.run_id,
attempt_index=resume_attempt + 1,
error_type=type(exc).__name__,
error_code=getattr(exc, "code", "error.unknown"),
limit=max_resume,
)
raise
resume_attempt += 1
await self._event_bus.emit(
"run.resume_attempted",
run_id=request.run_id,
checkpoint_id=checkpoint_id,
error_type=type(exc).__name__,
error_code=getattr(exc, "code", "error.unknown"),
attempt_index=resume_attempt,
)
ckpt = await self._session_manager.load_checkpoint(request.session_id, checkpoint_id)
if ckpt is None:
raise
self._rehydrate_pattern_from_checkpoint(
pattern=plugins.pattern,
checkpoint=ckpt,
usage=usage,
artifacts=artifacts,
)
await self._event_bus.emit(
"run.resume_succeeded",
run_id=request.run_id,
checkpoint_id=checkpoint_id,
attempt_index=resume_attempt,
)
finally:
if checkpoint_handler is not None:
self._event_bus.unsubscribe("tool.succeeded", checkpoint_handler)
self._event_bus.unsubscribe("llm.succeeded", checkpoint_handler)
if validation_exhausted is not None:
await self._append_transcript(
request=request,
final_output=str(validation_exhausted),
stop_reason=RUN_STOP_FAILED,
is_error=True,
)
await self._persist_artifacts(request.session_id, artifacts)
_ve_details = ErrorDetails.from_exception(validation_exhausted)
await self._event_bus.emit(
RUN_FAILED,
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
error=str(validation_exhausted),
error_details=_ve_details.model_dump(),
)
await self._event_bus.emit(
"session.run.completed",
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
stop_reason=RUN_STOP_FAILED,
duration_ms=int((time.perf_counter() - started_at) * 1000),
)
return RunResult(
run_id=request.run_id,
final_output=None,
stop_reason=RUN_STOP_FAILED,
usage=usage,
artifacts=list(artifacts),
error_details=_ve_details,
metadata={
"agent_id": request.agent_id,
"session_id": request.session_id,
},
)
self._enforce_duration_budget(request=request, started_at=started_at)
await self._run_memory_writeback(agent=agent, memory=plugins.memory, pattern=plugins.pattern)
self._enforce_duration_budget(request=request, started_at=started_at)
await self._run_memory_compact(agent=agent, memory=plugins.memory, pattern=plugins.pattern)
self._enforce_duration_budget(request=request, started_at=started_at)
session_state["_runtime_last_output"] = result
await self._append_transcript(
request=request,
final_output=result,
stop_reason=RUN_STOP_COMPLETED,
)
await self._persist_artifacts(request.session_id, artifacts)
run_result = RunResult(
run_id=request.run_id,
final_output=result,
stop_reason=RUN_STOP_COMPLETED,
usage=usage,
artifacts=list(artifacts),
metadata={
"agent_id": request.agent_id,
"session_id": request.session_id,
},
)
finalized_result = await context_assembler.finalize(
request=request,
session_state=session_state,
session_manager=self._session_manager,
result=run_result,
)
if finalized_result is not None:
run_result = finalized_result
await self._event_bus.emit(
RUN_COMPLETED,
agent_id=request.agent_id,
session_id=request.session_id,
run_id=request.run_id,
result=result,
)
await self._event_bus.emit(
"session.run.completed",