python-codex 0.6.3__py3-none-any.whl → 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pycodex/model.py CHANGED
@@ -2,7 +2,6 @@ import asyncio
2
2
  import json
3
3
  import os
4
4
  import re
5
- import threading
6
5
  import typing
7
6
  import urllib.parse
8
7
  import uuid
@@ -15,13 +14,16 @@ from typing import Callable
15
14
  import requests
16
15
  from urllib3.exceptions import ReadTimeoutError
17
16
 
18
- from .utils.compat import Protocol
17
+ from .utils.compat import Literal, Protocol
19
18
  from .utils.codex_config import DEFAULT_CODEX_CONFIG_PATH, read_codex_config
20
19
  from .utils.http_headers import build_http_headers
21
20
 
22
21
  from .events import (
22
+ BASE_EVENT_HANDLER,
23
23
  AssistantDeltaEvent,
24
+ EventScope,
24
25
  ModelEvent,
26
+ ModelRequestInterrupted,
25
27
  ModelRequestTimingEvent,
26
28
  StreamErrorEvent,
27
29
  TokenCountEvent,
@@ -44,7 +46,8 @@ from .utils import build_user_agent, uuid7_string
44
46
  DEFAULT_ORIGINATOR = "pycodex"
45
47
  RESPONSES_LITE_HEADER = "x-openai-internal-codex-responses-lite"
46
48
  ModelStreamEventHandler = Callable[[ModelEvent], None]
47
- NOOP_MODEL_STREAM_EVENT_HANDLER: "ModelStreamEventHandler" = lambda _event: None
49
+ RetryCodes = typing.Union[int, typing.FrozenSet[int], Literal["*"]]
50
+ NOOP_MODEL_STREAM_EVENT_HANDLER: "ModelStreamEventHandler" = BASE_EVENT_HANDLER
48
51
  DEFAULT_STREAM_MAX_RETRIES = 5
49
52
  DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000
50
53
  INITIAL_RETRY_DELAY_SECONDS = 0.2
@@ -74,15 +77,23 @@ class ModelClient(Protocol):
74
77
  ) -> "ModelClient":
75
78
  """Construct an independent client for a child Agent."""
76
79
 
80
+ def stop_retry(self) -> "None":
81
+ """Stop retrying after the issued request completes."""
82
+
77
83
  async def complete(
78
84
  self,
79
85
  prompt: "Prompt",
80
- event_handler: "ModelStreamEventHandler" = NOOP_MODEL_STREAM_EVENT_HANDLER,
81
86
  ) -> "ModelResponse":
82
- """Return the next batch of model output items for the current prompt."""
87
+ """Return the output items and any provider usage for this request."""
83
88
 
84
89
 
85
90
  class ModelControl(ModelClient, Protocol):
91
+ retry_error_code: "typing.Optional[RetryCodes]"
92
+ last_error: "typing.Optional[Exception]"
93
+
94
+ def set_retry_error_code(self, code: "typing.Optional[RetryCodes]") -> "None":
95
+ """Select error codes or '*' for infinite retries. None restores normal retries."""
96
+
86
97
  @property
87
98
  def endpoint(self) -> "str":
88
99
  """Return the active API base URL, safe for display."""
@@ -117,6 +128,9 @@ class ResponsesProviderConfig:
117
128
  model_slug: "typing.Union[str, None]" = None
118
129
  http_headers: "typing.Dict[str, str]" = field(default_factory=dict, repr=False)
119
130
  env_http_headers: "typing.Dict[str, str]" = field(default_factory=dict)
131
+ model_catalog: "typing.Dict[str, JSONDict]" = field(
132
+ default_factory=load_models_by_slug, repr=False, compare=False,
133
+ )
120
134
 
121
135
  def __post_init__(self):
122
136
  for name in ("http_headers", "env_http_headers"):
@@ -127,7 +141,7 @@ class ResponsesProviderConfig:
127
141
  ):
128
142
  raise ValueError(name + " must be a table of strings")
129
143
  if self.model_slug is not None and (
130
- not isinstance(self.model_slug, str) or self.model_slug not in load_models_by_slug()
144
+ not isinstance(self.model_slug, str) or self.model_slug not in self.model_catalog
131
145
  ):
132
146
  raise ValueError("model_slug must name an entry in models.json")
133
147
  if self.compat_api not in ("none", "chat_completions", "messages", "gemini"):
@@ -155,6 +169,7 @@ class ResponsesProviderConfig:
155
169
  @classmethod
156
170
  def from_mapping(
157
171
  cls, selected: "typing.Mapping[str, typing.Any]",
172
+ model_catalog: "typing.Union[typing.Dict[str, JSONDict], None]" = None,
158
173
  ) -> "ResponsesProviderConfig":
159
174
  provider_name = selected.get("model_provider", "openai")
160
175
  provider = selected.get("model_providers", {}).get(provider_name)
@@ -201,6 +216,7 @@ class ResponsesProviderConfig:
201
216
  raise ValueError("fallback_models must be an array of non-empty model IDs")
202
217
  return cls(
203
218
  model=selected["model"],
219
+ model_catalog=load_models_by_slug() if model_catalog is None else model_catalog,
204
220
  model_slug=selected.get("model_slug"),
205
221
  provider_name=provider_name,
206
222
  base_url=provider["base_url"],
@@ -246,7 +262,7 @@ class ResponsesProviderConfig:
246
262
  return max(int(self.stream_idle_timeout_ms), 1) / 1000.0
247
263
 
248
264
  def metadata(self) -> "typing.Union[JSONDict, None]":
249
- return model_metadata(self.model_slug or self.model)
265
+ return model_metadata(self.model_slug or self.model, self.model_catalog)
250
266
 
251
267
  def use_responses_lite(self) -> "bool":
252
268
  if self.responses_lite_override is not None:
@@ -376,12 +392,37 @@ def _filter_audio_inputs(items, metadata):
376
392
 
377
393
 
378
394
  class ResponsesApiError(RuntimeError):
379
- pass
395
+ def __init__(
396
+ self,
397
+ message: "str",
398
+ http_status: "typing.Union[int, None]" = None,
399
+ error_code: "typing.Union[str, int, None]" = None,
400
+ ) -> "None":
401
+ super().__init__(message)
402
+ self.http_status = http_status
403
+ self.error_code = error_code
404
+
405
+ def matches_code(self, code: "int") -> "bool":
406
+ return self.http_status == code or str(self.error_code) == str(code)
407
+
408
+
409
+ def matches_retry_codes(error: "Exception", codes: "RetryCodes") -> "bool":
410
+ if codes == "*":
411
+ return True
412
+ selected = (codes,) if isinstance(codes, int) else codes
413
+ return isinstance(error, ResponsesApiError) and any(
414
+ error.matches_code(code) for code in selected
415
+ )
380
416
 
381
417
 
382
418
  class ContextLengthExceeded(ResponsesApiError):
383
- def __init__(self, message: "str") -> "None":
384
- super().__init__(message)
419
+ def __init__(
420
+ self,
421
+ message: "str",
422
+ http_status: "typing.Union[int, None]" = None,
423
+ error_code: "typing.Union[str, int, None]" = None,
424
+ ) -> "None":
425
+ super().__init__(message, http_status, error_code)
385
426
  self.usage: "typing.Union[typing.Dict[str, int], None]" = None
386
427
  self.token_limit: "typing.Union[int, None]" = None
387
428
  requested = re.search(r"requested\s+([0-9,]+)\s+tokens", message, re.IGNORECASE)
@@ -422,8 +463,10 @@ class ResponsesRetryableError(ResponsesApiError):
422
463
  self,
423
464
  message: "str",
424
465
  retry_delay_seconds: "typing.Union[float, None]" = None,
466
+ http_status: "typing.Union[int, None]" = None,
467
+ error_code: "typing.Union[str, int, None]" = None,
425
468
  ) -> "None":
426
- super().__init__(message)
469
+ super().__init__(message, http_status, error_code)
427
470
  self.retry_delay_seconds = retry_delay_seconds
428
471
 
429
472
 
@@ -474,6 +517,21 @@ class ResponsesModelClient:
474
517
  self._user_agent = user_agent or build_user_agent(originator)
475
518
  self._openai_subagent = openai_subagent
476
519
  self._model_cooldowns: "typing.Dict[str, float]" = {}
520
+ self.retry_error_code: "typing.Optional[RetryCodes]" = None
521
+ self.last_error: "typing.Optional[Exception]" = None
522
+ self._retry_wakeup: "typing.Union[asyncio.Event, None]" = None
523
+ self._retry_stopped = False
524
+
525
+ def set_retry_error_code(self, code: "typing.Optional[RetryCodes]") -> "None":
526
+ if code != self.retry_error_code:
527
+ self.retry_error_code = code
528
+ if self._retry_wakeup is not None:
529
+ self._retry_wakeup.set()
530
+
531
+ def stop_retry(self) -> "None":
532
+ if self._retry_wakeup is not None:
533
+ self._retry_stopped = True
534
+ self._retry_wakeup.set()
477
535
 
478
536
  @property
479
537
  def model(self) -> "str":
@@ -567,10 +625,13 @@ class ResponsesModelClient:
567
625
  async def complete(
568
626
  self,
569
627
  prompt: "Prompt",
570
- event_handler: "ModelStreamEventHandler" = NOOP_MODEL_STREAM_EVENT_HANDLER,
628
+ event_handler: "typing.Optional[ModelStreamEventHandler]" = None,
571
629
  ) -> "ModelResponse":
572
630
  retries = 0
573
631
  max_retries = self._config.effective_stream_max_retries()
632
+ self.last_error = None
633
+ self._retry_stopped = False
634
+ self._retry_wakeup = asyncio.Event()
574
635
  models = tuple(dict.fromkeys((self.model,) + self._config.fallback_models))
575
636
  now = monotonic()
576
637
  self._model_cooldowns = {
@@ -591,74 +652,103 @@ class ResponsesModelClient:
591
652
  if first_model == self.model
592
653
  else self.with_overrides(model=first_model)
593
654
  )
594
- loop = asyncio.get_running_loop()
595
- active = True
596
- callback_lock = threading.Lock()
597
-
598
- def deliver(event):
599
- if active:
600
- event_handler(event)
601
-
602
- def receive(event):
603
- with callback_lock:
604
- if active:
605
- loop.call_soon_threadsafe(deliver, event)
606
-
607
- try:
608
- while True:
609
- try:
610
- response = await asyncio.to_thread(request_client._complete_sync, prompt, receive)
611
- self._model_cooldowns.pop(request_client.model, None)
612
- return response
613
- except (ResponsesRetryableError, ResponsesModelUnavailableError) as exc:
614
- if (
615
- isinstance(exc, ResponsesModelUnavailableError)
616
- or (isinstance(exc, ResponsesFirstDataTimeout) and len(models) > 1)
617
- or retries >= max_retries
618
- ):
619
- cooldown = self._config.fallback_cooldown_seconds
620
- if len(models) > 1 and cooldown > 0:
621
- self._model_cooldowns[request_client.model] = (
622
- monotonic() + cooldown
623
- )
624
- fallback_model = next(fallback_models, None)
625
- if fallback_model is None:
655
+ with EventScope.worker_events(event_handler) as worker_context:
656
+ try:
657
+ while True:
658
+ if self._retry_stopped:
659
+ raise ModelRequestInterrupted()
660
+ was_infinite = self.retry_error_code is not None
661
+ try:
662
+ response = await asyncio.to_thread(
663
+ worker_context.run, request_client._complete_sync, prompt,
664
+ )
665
+ except (asyncio.CancelledError, ModelRequestInterrupted):
666
+ raise
667
+ except Exception as exc:
668
+ self.last_error = exc
669
+ if self._retry_stopped:
670
+ raise ModelRequestInterrupted() from exc
671
+ infinite = self.retry_error_code is not None
672
+ if was_infinite and not infinite:
673
+ raise
674
+ if infinite:
675
+ if not matches_retry_codes(exc, self.retry_error_code):
676
+ raise
677
+ elif not isinstance(exc, (ResponsesRetryableError, ResponsesModelUnavailableError)):
626
678
  raise
627
- event_handler(
679
+ elif (
680
+ isinstance(exc, ResponsesModelUnavailableError)
681
+ or (isinstance(exc, ResponsesFirstDataTimeout) and len(models) > 1)
682
+ or retries >= max_retries
683
+ ):
684
+ cooldown = self._config.fallback_cooldown_seconds
685
+ if len(models) > 1 and cooldown > 0:
686
+ self._model_cooldowns[request_client.model] = (
687
+ monotonic() + cooldown
688
+ )
689
+ fallback_model = next(fallback_models, None)
690
+ if fallback_model is None:
691
+ raise
692
+ EventScope.emit(
693
+ StreamErrorEvent(
694
+ f"Falling back: {request_client.model} -> {fallback_model}",
695
+ 0,
696
+ max_retries,
697
+ 0.0,
698
+ str(exc),
699
+ )
700
+ )
701
+ request_client = self.with_overrides(model=fallback_model)
702
+ retries = 0
703
+ continue
704
+ retries += 1
705
+ delay_seconds = (
706
+ exc.retry_delay_seconds
707
+ if isinstance(exc, ResponsesRetryableError) else None
708
+ )
709
+ if delay_seconds is None:
710
+ delay_seconds = self._retry_delay_seconds(retries)
711
+ self._retry_wakeup.clear()
712
+ EventScope.emit(
628
713
  StreamErrorEvent(
629
- f"Falling back: {request_client.model} -> {fallback_model}",
630
- 0,
631
- max_retries,
632
- 0.0,
714
+ f"Reconnecting... {retries}/∞"
715
+ if infinite else f"Reconnecting... {retries}/{max_retries}",
716
+ retries,
717
+ 0 if infinite else max_retries,
718
+ delay_seconds,
633
719
  str(exc),
634
720
  )
635
721
  )
636
- request_client = self.with_overrides(model=fallback_model)
637
- retries = 0
638
- continue
639
- retries += 1
640
- delay_seconds = exc.retry_delay_seconds
641
- if delay_seconds is None:
642
- delay_seconds = self._retry_delay_seconds(retries)
643
- event_handler(
644
- StreamErrorEvent(
645
- f"Reconnecting... {retries}/{max_retries}",
646
- retries,
647
- max_retries,
648
- delay_seconds,
649
- str(exc),
650
- )
651
- )
652
- if delay_seconds > 0:
653
- await asyncio.sleep(delay_seconds)
654
- finally:
655
- with callback_lock:
656
- active = False
722
+ if delay_seconds > 0:
723
+ waiter = asyncio.ensure_future(self._retry_wakeup.wait())
724
+ try:
725
+ await asyncio.wait({waiter}, timeout=delay_seconds)
726
+ finally:
727
+ if not waiter.done():
728
+ waiter.cancel()
729
+ try:
730
+ await waiter
731
+ except asyncio.CancelledError:
732
+ pass
733
+ if self._retry_stopped:
734
+ raise ModelRequestInterrupted() from exc
735
+ if infinite and self.retry_error_code is None:
736
+ raise
737
+ if (
738
+ self.retry_error_code is not None
739
+ and not matches_retry_codes(exc, self.retry_error_code)
740
+ ):
741
+ raise
742
+ else:
743
+ self._model_cooldowns.pop(request_client.model, None)
744
+ self.last_error = None
745
+ return response
746
+ finally:
747
+ self._retry_wakeup = None
657
748
 
658
749
  def _complete_sync(
659
750
  self,
660
751
  prompt: "Prompt",
661
- event_handler: "ModelStreamEventHandler",
662
752
  ) -> "ModelResponse":
663
753
  payload = self._build_payload(prompt)
664
754
  session_id = payload["prompt_cache_key"]
@@ -707,7 +797,7 @@ class ResponsesModelClient:
707
797
  f"{error_body[:500]}"
708
798
  )
709
799
  if _is_context_length_error_message(error_body):
710
- raise ContextLengthExceeded(message)
800
+ raise ContextLengthExceeded(message, http_status=response.status_code)
711
801
  if response.status_code >= 500 or response.status_code in (408, 429):
712
802
  raise ResponsesRetryableError(
713
803
  message,
@@ -715,10 +805,11 @@ class ResponsesModelClient:
715
805
  "rate_limit_exceeded" if response.status_code == 429 else "",
716
806
  error_body,
717
807
  ),
808
+ http_status=response.status_code,
718
809
  )
719
810
  if response.status_code in (403, 404):
720
- raise ResponsesModelUnavailableError(message)
721
- raise ResponsesApiError(message)
811
+ raise ResponsesModelUnavailableError(message, http_status=response.status_code)
812
+ raise ResponsesApiError(message, http_status=response.status_code)
722
813
  if first_timeout is not None:
723
814
  remaining = first_timeout - (monotonic() - diagnostics.started_at)
724
815
  if remaining <= 0:
@@ -735,7 +826,6 @@ class ResponsesModelClient:
735
826
  tracked_lines = self._track_stream_lines(lines, diagnostics)
736
827
  result = self._parse_stream(
737
828
  tracked_lines,
738
- event_handler,
739
829
  diagnostics=diagnostics,
740
830
  session_id=session_id,
741
831
  )
@@ -761,7 +851,7 @@ class ResponsesModelClient:
761
851
  exc.first_data_seconds = diagnostics.first_data_seconds
762
852
  raise
763
853
  finally:
764
- event_handler(ModelRequestTimingEvent(
854
+ EventScope.emit(ModelRequestTimingEvent(
765
855
  self.model, monotonic() - diagnostics.started_at,
766
856
  diagnostics.first_data_seconds, "completed" if completed else "failed",
767
857
  ))
@@ -1001,12 +1091,10 @@ class ResponsesModelClient:
1001
1091
  def _parse_stream(
1002
1092
  self,
1003
1093
  response,
1004
- event_handler: "ModelStreamEventHandler",
1005
1094
  diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
1006
1095
  session_id: "typing.Union[str, None]" = None,
1007
1096
  ) -> "ModelResponse":
1008
1097
  items: "typing.List[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem]]" = ([])
1009
- saw_completed = False
1010
1098
  last_event_type = ""
1011
1099
 
1012
1100
  for event_name, data in self._iter_sse_events(response, diagnostics):
@@ -1024,7 +1112,7 @@ class ResponsesModelClient:
1024
1112
  diagnostics.last_event_type = last_event_type
1025
1113
 
1026
1114
  if event_type == "response.output_text.delta":
1027
- event_handler(AssistantDeltaEvent(str(payload.get("delta", ""))))
1115
+ EventScope.emit(AssistantDeltaEvent(str(payload.get("delta", ""))))
1028
1116
  continue
1029
1117
 
1030
1118
  if event_type == "response.output_item.done":
@@ -1040,7 +1128,7 @@ class ResponsesModelClient:
1040
1128
  else:
1041
1129
  action_payload = {}
1042
1130
  queries = action_payload.get("queries")
1043
- event_handler(
1131
+ EventScope.emit(
1044
1132
  ToolCalledEvent(
1045
1133
  call_id=str(item_payload.get("id", "web_search")),
1046
1134
  tool_name="web_search",
@@ -1076,7 +1164,7 @@ class ResponsesModelClient:
1076
1164
  parsed = self._parse_output_item(item_payload)
1077
1165
  if parsed is not None:
1078
1166
  if isinstance(parsed, ToolCall):
1079
- event_handler(ToolCalledEvent(parsed.call_id, parsed.name))
1167
+ EventScope.emit(ToolCalledEvent(parsed.call_id, parsed.name))
1080
1168
  items.append(parsed)
1081
1169
  if diagnostics is not None:
1082
1170
  diagnostics.output_items_received += 1
@@ -1091,9 +1179,8 @@ class ResponsesModelClient:
1091
1179
  usage = dict(response_usage)
1092
1180
  elif isinstance(payload.get("usage"), dict):
1093
1181
  usage = dict(payload["usage"])
1094
- event_handler(TokenCountEvent(usage))
1095
- saw_completed = True
1096
- break
1182
+ EventScope.emit(TokenCountEvent(usage))
1183
+ return ModelResponse(items=items, usage=usage)
1097
1184
 
1098
1185
  if event_type == "response.incomplete":
1099
1186
  partial_items = tuple(items)
@@ -1112,12 +1199,9 @@ class ResponsesModelClient:
1112
1199
  if event_type == "response.failed":
1113
1200
  self._raise_response_failed_error(payload, session_id)
1114
1201
 
1115
- if not saw_completed:
1116
- raise ResponsesRetryableError(
1117
- self._format_incomplete_stream_error(last_event_type, len(items), session_id)
1118
- )
1119
-
1120
- return ModelResponse(items=items)
1202
+ raise ResponsesRetryableError(
1203
+ self._format_incomplete_stream_error(last_event_type, len(items), session_id)
1204
+ )
1121
1205
 
1122
1206
  @staticmethod
1123
1207
  def _parse_output_item(
@@ -1364,25 +1448,31 @@ class ResponsesModelClient:
1364
1448
  )
1365
1449
 
1366
1450
  message = str(error.get("message") or "responses stream failed")
1367
- code = str(error.get("code") or error.get("type") or "").strip()
1451
+ error_code = error.get("code")
1452
+ if error_code is None:
1453
+ error_code = error.get("type")
1454
+ http_status = error.get("http_status")
1455
+ code = str(error_code or "").strip()
1368
1456
  formatted = self._format_response_failed_error(message, code, session_id)
1369
1457
  if code == "context_length_exceeded" or _is_context_length_error_message(
1370
1458
  message
1371
1459
  ):
1372
- raise ContextLengthExceeded(formatted)
1460
+ raise ContextLengthExceeded(formatted, http_status=http_status, error_code=error_code)
1373
1461
  if code in {"model_not_found", "model_not_available", "permission_denied"}:
1374
- raise ResponsesModelUnavailableError(formatted)
1462
+ raise ResponsesModelUnavailableError(formatted, http_status=http_status, error_code=error_code)
1375
1463
  if code in {
1376
1464
  "insufficient_quota",
1377
1465
  "invalid_prompt",
1378
1466
  "model_output_invalid",
1379
1467
  "usage_not_included",
1380
1468
  }:
1381
- raise ResponsesApiError(formatted)
1469
+ raise ResponsesApiError(formatted, http_status=http_status, error_code=error_code)
1382
1470
 
1383
1471
  raise ResponsesRetryableError(
1384
1472
  formatted,
1385
1473
  retry_delay_seconds=self._try_parse_retry_after_seconds(code, message),
1474
+ http_status=http_status,
1475
+ error_code=error_code,
1386
1476
  )
1387
1477
 
1388
1478
  def _format_incomplete_stream_error(
pycodex/multi_agents.py CHANGED
@@ -9,17 +9,6 @@ from typing import TYPE_CHECKING
9
9
 
10
10
  from .agent import Agent
11
11
  from .context import ContextConfig
12
- from .events import (
13
- CommandStartedEvent,
14
- CompactStartedEvent,
15
- Event,
16
- RuntimeUpdatedEvent,
17
- SessionClosedEvent,
18
- TurnCompletedEvent,
19
- TurnFailedEvent,
20
- TurnInterruptedEvent,
21
- TurnStartedEvent,
22
- )
23
12
  from .protocol import AgentMessage, ConversationItem
24
13
  from .tools import get_tools
25
14
  from .tools.runtime_services import create_agent_runtime_environment
@@ -111,7 +100,10 @@ class AgentsManager:
111
100
  agent.context_manager.agent_path = agent.agent_path
112
101
  return runtime
113
102
 
114
- def _notify_parents(self, agent_id):
103
+ def mark_used(self, agent_id):
104
+ self._runtimes.move_to_end(agent_id)
105
+
106
+ def notify_parents(self, agent_id):
115
107
  parent_agent_id = self.get_parent_agent_id(agent_id)
116
108
  while parent_agent_id is not None:
117
109
  parent = self._runtimes[parent_agent_id]
@@ -184,7 +176,7 @@ class AgentsManager:
184
176
  runtime.agent.tool_registry.runtime_environment.set_state_listener(None)
185
177
  del self._runtimes[agent_id]
186
178
  self._runtimes[parent_agent_id].publish_update("agents")
187
- self._notify_parents(parent_agent_id)
179
+ self.notify_parents(parent_agent_id)
188
180
 
189
181
  async def _make_spawn_room(self, caller_agent_id):
190
182
  caller = self._runtimes[caller_agent_id]
@@ -285,7 +277,7 @@ class AgentsManager:
285
277
  ),
286
278
  runtime.agent.model_client.reasoning_effort,
287
279
  )
288
- self._notify_parents(runtime.agent.agent_id)
280
+ self.notify_parents(runtime.agent.agent_id)
289
281
  await runtime.start()
290
282
  await self.send_message(
291
283
  caller_agent_id, runtime.agent.agent_id, message, trigger_turn=True,
@@ -313,7 +305,7 @@ class AgentsManager:
313
305
  recipient.message(item)
314
306
  if trigger_turn:
315
307
  recipient.trigger()
316
- self._runtimes.move_to_end(recipient_agent_id)
308
+ self.mark_used(recipient_agent_id)
317
309
  return ""
318
310
 
319
311
  async def interrupt_agent(self, caller_agent_id, target):
@@ -369,33 +361,12 @@ class AgentsManager:
369
361
  )
370
362
  raise errors[0]
371
363
 
372
- def handle_event(self, agent_id, event: "Event") -> "None":
373
- self._runtimes[agent_id]
374
- if isinstance(event, (TurnStartedEvent, CompactStartedEvent, CommandStartedEvent)):
375
- self._runtimes.move_to_end(agent_id)
376
- text = None
377
- if isinstance(event, TurnCompletedEvent):
378
- text = event.output_text or ""
379
- elif isinstance(event, TurnFailedEvent):
380
- text = "Agent errored: {0}: {1}".format(event.error_type, event.error)
381
- elif isinstance(event, RuntimeUpdatedEvent):
382
- if event.reason == "agents":
383
- return
384
- elif not isinstance(
385
- event,
386
- (
387
- TurnStartedEvent,
388
- TurnInterruptedEvent,
389
- CompactStartedEvent,
390
- SessionClosedEvent,
391
- ),
392
- ):
393
- return
364
+ def finish_turn(self, agent_id, final_answer):
394
365
  parent_agent_id = self.get_parent_agent_id(agent_id)
395
- if parent_agent_id is not None and text is not None:
366
+ if parent_agent_id is not None and final_answer is not None:
396
367
  parent = self._runtimes[parent_agent_id]
397
368
  if parent.accepts_input:
398
369
  parent.message(
399
- self._message(agent_id, parent_agent_id, text, "FINAL_ANSWER"),
370
+ self._message(agent_id, parent_agent_id, final_answer, "FINAL_ANSWER"),
400
371
  )
401
- self._notify_parents(agent_id)
372
+ self.notify_parents(agent_id)