python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. pycodex/__init__.py +22 -12
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +37 -251
  4. pycodex/cli.py +19 -28
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +368 -51
  7. pycodex/events.py +14 -187
  8. pycodex/model.py +197 -95
  9. pycodex/multi_agents.py +401 -0
  10. pycodex/portable/__init__.py +8 -6
  11. pycodex/portable/client.py +24 -39
  12. pycodex/portable/protocol.py +28 -0
  13. pycodex/portable/server.py +3 -3
  14. pycodex/prompts/developer_messages.json +13 -0
  15. pycodex/prompts/goals/budget_limit.md +19 -0
  16. pycodex/prompts/goals/continuation.md +56 -0
  17. pycodex/prompts/models.json +1143 -200
  18. pycodex/protocol.py +81 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +102 -10
  21. pycodex/tools/agent_tool_schemas.py +0 -38
  22. pycodex/tools/apply_patch_tool.py +17 -34
  23. pycodex/tools/base_tool.py +63 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +58 -187
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +332 -0
  29. pycodex/tools/exec_tool.py +74 -31
  30. pycodex/tools/followup_task_tool.py +44 -0
  31. pycodex/tools/goal_manager.py +205 -0
  32. pycodex/tools/goal_tool.py +126 -0
  33. pycodex/tools/interrupt_agent_tool.py +48 -0
  34. pycodex/tools/list_agents_tool.py +66 -0
  35. pycodex/tools/python_tool_schema.py +141 -0
  36. pycodex/tools/request_permissions_tool.py +1 -0
  37. pycodex/tools/runtime_services.py +122 -450
  38. pycodex/tools/send_message_tool.py +42 -0
  39. pycodex/tools/spawn_agent_tool.py +55 -94
  40. pycodex/tools/unified_exec_manager.py +26 -35
  41. pycodex/tools/wait_agent_tool.py +46 -66
  42. pycodex/tools/wait_tool.py +24 -13
  43. pycodex/tools/web_search_tool.py +1 -0
  44. pycodex/utils/codex_config.py +105 -0
  45. pycodex/utils/compactor.py +4 -0
  46. pycodex/utils/compat.py +43 -2
  47. pycodex/utils/doctor.py +5 -4
  48. pycodex/utils/dotenv.py +0 -7
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +59 -0
  51. pycodex/utils/session_persist.py +104 -48
  52. python_codex-0.6.1.dist-info/METADATA +201 -0
  53. python_codex-0.6.1.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +10 -7
  56. responses_server/config.py +6 -12
  57. responses_server/gemini_api.py +333 -0
  58. responses_server/messages_api.py +9 -1
  59. responses_server/payload_processors.py +4 -4
  60. responses_server/request_translation.py +486 -0
  61. responses_server/server.py +31 -24
  62. responses_server/stream_events.py +124 -0
  63. responses_server/stream_router.py +48 -830
  64. responses_server/tools/custom_adapter.py +29 -29
  65. responses_server/tools/web_search.py +3 -0
  66. responses_server/transport.py +388 -0
  67. pycodex/tools/close_agent_tool.py +0 -60
  68. pycodex/tools/exec_runtime.js +0 -161
  69. pycodex/tools/request_user_input_tool.py +0 -102
  70. pycodex/tools/resume_agent_tool.py +0 -54
  71. pycodex/tools/send_input_tool.py +0 -110
  72. python_codex-0.5.2.dist-info/METADATA +0 -262
  73. python_codex-0.5.2.dist-info/RECORD +0 -90
  74. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
  75. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
  76. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
pycodex/runtime.py CHANGED
@@ -1,16 +1,18 @@
1
1
  import asyncio
2
+ import json
2
3
  import typing
3
4
  from collections import deque
4
5
  from dataclasses import dataclass, field, replace
6
+ from time import monotonic
5
7
 
6
8
  from .agent import BASE_EVENT_HANDLER, Agent, TurnInterrupted
7
- from .utils.compat import Literal
8
9
  from .events import (
9
10
  AssistantDeltaEvent,
10
11
  AutoCompactCompletedEvent,
11
12
  CommandCompletedEvent,
12
13
  CommandFailedEvent,
13
14
  CommandStartedEvent,
15
+ CompactStartedEvent,
14
16
  Event,
15
17
  InputQueuedEvent,
16
18
  InputRequestedEvent,
@@ -19,37 +21,43 @@ from .events import (
19
21
  SessionClosedEvent,
20
22
  SessionStateEvent,
21
23
  StreamErrorEvent,
22
- TerminalEvent,
23
24
  ToolCompletedEvent,
24
25
  TurnCompletedEvent,
25
26
  TurnEvent,
26
27
  TurnFailedEvent,
28
+ TurnInputReadyEvent,
27
29
  TurnInterruptedEvent,
28
30
  TurnStartedEvent,
29
31
  )
30
32
  from .model import ModelControl
31
- from .protocol import TurnResult
33
+ from .protocol import AgentMessage, ToolResult, TurnResult, UserMessage
34
+ from .tools.runtime_services import close_resources
32
35
  from .utils import uuid7_string
33
36
  from .utils.event_helpers import shorten_title
37
+ from .utils.history import conversation_history_to_turns
38
+ from .utils.truncation import truncate_tool_result_for_history
34
39
  from .utils.session_persist import (
35
- conversation_history_to_turns,
36
40
  list_resumable_sessions,
37
41
  resolve_codex_home,
38
42
  select_resumable_session,
39
43
  )
40
44
 
45
+ if typing.TYPE_CHECKING:
46
+ from .multi_agents import AgentsManager
47
+
41
48
 
42
49
  class SubmissionInterrupted(RuntimeError):
43
50
  def __init__(self) -> "None":
44
51
  super().__init__("submission interrupted")
45
52
 
46
53
 
47
- @dataclass
48
54
  class _QueuedSubmission:
49
- submission_id: "str"
50
- turn_id: "str"
51
- texts: "typing.List[str]"
52
- futures: "typing.List[asyncio.Future[TurnResult]]"
55
+ def __init__(self, texts: "typing.List[str]", name: "str" = "user") -> "None":
56
+ self.submission_id = uuid7_string()
57
+ self.turn_id = self.submission_id
58
+ self.texts = texts
59
+ self.name = name
60
+ self.futures: "typing.List[asyncio.Future[TurnResult]]" = []
53
61
 
54
62
 
55
63
  @dataclass(frozen=True)
@@ -70,20 +78,66 @@ class _InputRequest:
70
78
  other: "bool" = False
71
79
  timer: "typing.Union[asyncio.TimerHandle, None]" = None
72
80
 
81
+ def event(self):
82
+ payload = (
83
+ {"question": self.payload["questions"][self.question_index]}
84
+ if self.kind == "questions" else {"permissions": self.payload}
85
+ )
86
+ return InputRequestedEvent(self.request_id, self.kind, self.other, **payload)
87
+
88
+ def answer(self, text):
89
+ """Advance question progress and return (resolved, answer)."""
90
+ if not text:
91
+ return True, None
92
+ if self.kind == "permissions":
93
+ answer = text.lower()
94
+ granted = answer in {"t", "turn", "y", "yes", "s", "session"}
95
+ return True, {
96
+ "permissions": self.payload.get("permissions", {}) if granted else {},
97
+ "scope": "session" if answer in {"s", "session"} else "turn",
98
+ }
99
+ question = self.payload["questions"][self.question_index]
100
+ options = question["options"]
101
+ if not self.other and text.isdigit():
102
+ choice = int(text)
103
+ if choice == 0:
104
+ self.other = True
105
+ return False, None
106
+ if 1 <= choice <= len(options):
107
+ text = options[choice - 1]["label"]
108
+ self.answers[question["id"]] = {"answers": [text]}
109
+ self.question_index += 1
110
+ self.other = False
111
+ complete = self.question_index == len(self.payload["questions"])
112
+ return complete, {"answers": self.answers} if complete else None
113
+
114
+
115
+ def _parse_input(text):
116
+ """Recognize slash commands, preserving ASCII-space escapes and paths."""
117
+ escaped = text.startswith(" ")
118
+ text = text.strip()
119
+ parts = text.split(None, 1)
120
+ command = parts[0] if parts else ""
121
+ if escaped or not command.startswith("/") or "/" in command[1:] or len(command) < 2:
122
+ command = None
123
+ return text, command, parts[1] if len(parts) == 2 else ""
124
+
73
125
 
74
126
  class AgentRuntime:
75
- """Frontend-independent session input, scheduling, state and events."""
127
+ """Session input and scheduling for an Agent whose client implements ModelControl."""
76
128
 
77
- def __init__(self, agent: "Agent") -> "None":
129
+ def __init__(self, agent: "Agent", agents_manager: "AgentsManager") -> "None":
78
130
  self.agent = agent
131
+ self.agents_manager = agents_manager
79
132
  self._enqueue_queue: "deque[_QueuedSubmission]" = deque()
80
- self._steer_queue: "deque[_QueuedSubmission]" = deque()
133
+ self._steer_queue: "deque[typing.Union[UserMessage, AgentMessage, ToolResult]]" = deque()
134
+ self._triggered_submission: "typing.Union[_QueuedSubmission, None]" = None
81
135
  self._queue_event = None
82
136
  self._current_submission: "typing.Union[_QueuedSubmission, None]" = None
83
137
  self.event_handler = BASE_EVENT_HANDLER
84
138
  self.agent.event_handler = self._handle_agent_event
85
139
  self.codex_home = (
86
- agent.context_manager._config.codex_home or resolve_codex_home()
140
+ agent.context_manager.config.codex_home or resolve_codex_home()
87
141
  )
88
142
  self.title = ""
89
143
  self.command_handlers = {}
@@ -95,18 +149,19 @@ class AgentRuntime:
95
149
  self._worker = None
96
150
  self._command_lock = None
97
151
  self._input_request = None
98
- self._background_work_count = 0
99
152
  self._active_turn = None
153
+ self._turn_started_at = None
154
+ self._turn_finished_at = None
155
+ self._input_activity: "typing.Union[asyncio.Event, None]" = None
156
+ self._wait_interrupted = False
157
+ self._last_agent_status: "typing.Union[str, dict]" = "pending_init"
100
158
  self._recorded_rollout_path = agent.recorded_session_file_path
101
159
  environment = agent.tool_registry.runtime_environment
102
- environment.request_user_input_manager.set_handler(self._request_user_input)
103
- environment.request_permissions_manager.set_handler(self._request_permissions)
104
- environment.plan_store.set_listener(lambda _plan: self._publish_update("plan"))
105
- environment.subagent_manager.set_state_listener(
106
- lambda: self._publish_update("agents")
160
+ environment.bind(
161
+ self.maybe_invoke, self.receive_tool_output, self.publish_update,
162
+ self._request_user_input, self._request_permissions,
107
163
  )
108
- for tool in self.agent.tool_registry.tools():
109
- tool.set_state_listener(lambda: self._publish_update("background_work"))
164
+ environment.restart()
110
165
 
111
166
  def attach(self, event_handler, interactive=True):
112
167
  frontend_id = uuid7_string()
@@ -132,6 +187,13 @@ class AgentRuntime:
132
187
  def add_close_handler(self, handler):
133
188
  self._close_handlers.append(handler)
134
189
 
190
+ def receive_tool_output(self, result: "ToolResult"):
191
+ if not self.accepts_input:
192
+ return
193
+ self.message(truncate_tool_result_for_history(result))
194
+ if not self.is_busy and self.accepts_input:
195
+ self.trigger()
196
+
135
197
  def commands(self):
136
198
  return (
137
199
  (
@@ -143,64 +205,67 @@ class AgentRuntime:
143
205
  "effort",
144
206
  "resume",
145
207
  "compact",
146
- "fork",
147
208
  )
148
209
  + tuple(self.command_handlers)
149
210
  + ("queue",)
150
211
  )
151
212
 
213
+ def _snapshot_fields(self, execution):
214
+ agent = self.agent
215
+ return {
216
+ "title": self.title,
217
+ "cwd": str(agent.context_manager.cwd),
218
+ "busy": self.is_busy,
219
+ "closed": agent.is_shutdown,
220
+ "accepts_input": agent.accepts_input,
221
+ "context_window": agent.context_manager.resolve_model_context_window(),
222
+ "max_context_window": agent.context_manager.resolve_model_max_context_window(),
223
+ "auto_compact_token_limit": agent.context_manager.resolve_auto_compact_token_limit(),
224
+ "usage_tokens": execution.usage_tokens,
225
+ "background_work_count": agent.tool_registry.runtime_environment.background_work_count(False),
226
+ "input_request": self._input_request_event(),
227
+ "plan": agent.tool_registry.runtime_environment.plan_store.snapshot(),
228
+ }
229
+
152
230
  def snapshot(self):
231
+ execution = self.agent.execution_snapshot()
153
232
  rollout_path = self.agent.session_file_path
154
233
  recorded_path = self.agent.recorded_session_file_path
155
234
  return {
156
- "session_id": self.agent.session_id,
157
- "cwd": str(self.agent.context_manager.cwd),
235
+ **self._snapshot_fields(execution),
236
+ "session_id": execution.session_id,
158
237
  "rollout_path": str(rollout_path) if rollout_path is not None else None,
159
- "recorded_rollout_path": (
160
- str(recorded_path) if recorded_path is not None else None
161
- ),
238
+ "recorded_rollout_path": str(recorded_path) if recorded_path is not None else None,
162
239
  "model": "{0}:{1}".format(
163
240
  self.agent.model_name,
164
- getattr(self.agent.model_client, "reasoning_effort", None) or "default",
241
+ self.agent.model_client.reasoning_effort or "default",
165
242
  ),
166
- "title": self.title,
167
243
  "history": conversation_history_to_turns(self.agent.history),
168
- "busy": self.is_busy,
169
- "closed": self.agent.is_shutdown,
170
- "accepts_input": self.agent.accepts_input,
171
- "context_window": self.agent.context_manager.resolve_model_context_window(),
172
- "max_context_window": (
173
- self.agent.context_manager.resolve_model_max_context_window()
174
- ),
175
- "auto_compact_token_limit": (
176
- self.agent.context_manager.resolve_auto_compact_token_limit()
177
- ),
178
- "usage_tokens": self.agent._last_total_usage_tokens,
179
- "background_work_count": self._background_work_count,
180
- "input_request": self._input_request_event(),
181
244
  "active_turn": (
182
245
  dict(self._active_turn) if self._active_turn is not None else None
183
246
  ),
184
- "plan": self.agent.tool_registry.runtime_environment.plan_store.snapshot(),
185
247
  }
186
248
 
187
249
  def state_snapshot(self):
188
250
  """Current frontend state, without completed conversation history."""
189
251
  agent = self.agent
252
+ execution = agent.execution_snapshot()
190
253
  client = typing.cast(ModelControl, agent.model_client)
191
254
  active = self._active_turn
255
+ pending = []
256
+ if self._triggered_submission is not None:
257
+ pending.append(("steer", self._triggered_submission))
258
+ pending.extend(("enqueue", item) for item in self._enqueue_queue)
192
259
  return {
193
- "agent_session_id": agent.session_id,
194
- "title": self.title,
195
- "cwd": str(agent.context_manager.cwd),
260
+ **self._snapshot_fields(execution),
261
+ "agent_id": agent.agent_id,
262
+ "agent_path": agent.agent_path,
263
+ "agent_session_id": execution.session_id,
196
264
  "model": {
197
265
  "name": agent.model_name,
198
266
  "reasoning_effort": client.reasoning_effort,
199
267
  },
200
- "busy": self.is_busy,
201
- "running": agent.is_running,
202
- "closed": agent.is_shutdown,
203
- "accepts_input": self.accepts_input,
268
+ "running": execution.running,
204
269
  "active_turn": (
205
270
  {
206
271
  key: active[key]
@@ -217,35 +282,18 @@ class AgentRuntime:
217
282
  "queue": name,
218
283
  "prompts": list(item.texts),
219
284
  }
220
- for name, queue in (
221
- ("steer", self._steer_queue), ("enqueue", self._enqueue_queue)
222
- )
223
- for item in queue
285
+ for name, item in pending
224
286
  ],
225
- "input_request": self._input_request_event(),
226
- "plan": agent.tool_registry.runtime_environment.plan_store.snapshot(),
227
287
  "commands": [dict(command) for command in self._active_commands.values()],
228
- "background_work_count": sum(
229
- tool.background_work_count(False)
230
- for tool in agent.tool_registry.tools()
231
- ),
232
- "context_window": agent.context_manager.resolve_model_context_window(),
233
- "max_context_window": agent.context_manager.resolve_model_max_context_window(),
234
- "auto_compact_token_limit": agent.context_manager.resolve_auto_compact_token_limit(),
235
- "usage_tokens": agent._last_total_usage_tokens,
236
288
  }
237
289
 
238
290
  def background_work_snapshot(self):
239
- return [
240
- dict(item, tool=tool.name)
241
- for tool in self.agent.tool_registry.tools()
242
- for item in tool.background_work_snapshot()
243
- ]
291
+ return self.agent.tool_registry.runtime_environment.background_work_snapshot()
244
292
 
245
293
  async def list_models(self):
246
294
  return await self.agent.model_client.list_models()
247
295
 
248
- def _publish_update(self, reason):
296
+ def publish_update(self, reason):
249
297
  self._publish(RuntimeUpdatedEvent(reason))
250
298
 
251
299
  def publish_state(self, reason):
@@ -273,26 +321,28 @@ class AgentRuntime:
273
321
  self.publish_state("cwd")
274
322
 
275
323
  def resume(self, path=None, title=""):
324
+ """Reopen an idle registered agent, optionally restoring its rollout."""
325
+ self.agents_manager.get_runtime(self.agent.agent_id)
276
326
  self.require_idle("resume")
277
327
  resumed = self.agent.resume(path)
328
+ self.agent.tool_registry.runtime_environment.restart()
278
329
  if resumed is not None:
279
330
  self.title = title or str(resumed["title"])
331
+ if self._worker is not None and not self._worker.done():
332
+ self.agent.tool_registry.runtime_environment.start()
280
333
  self.publish_state("history" if path is not None else "admission")
281
334
  return resumed
282
335
 
283
- def fork(self):
284
- self.require_idle("fork")
285
- self.agent.fork()
286
- self.publish_state("identity")
287
-
288
336
  async def start(self, config_path=None):
289
337
  if config_path is not None:
290
338
  self.codex_home = resolve_codex_home(config_path)
339
+ if not self.accepts_input:
340
+ raise RuntimeError("resume the agent before restarting its runtime")
291
341
  if self._worker is None or self._worker.done():
292
342
  if self.agent.is_shutdown:
293
343
  raise RuntimeError("resume the agent before restarting its runtime")
294
- self.agent.accepts_input = True
295
344
  self._worker = asyncio.create_task(self._run_forever())
345
+ self.agent.tool_registry.runtime_environment.start()
296
346
  return self
297
347
 
298
348
  def _get_command_lock(self):
@@ -305,31 +355,38 @@ class AgentRuntime:
305
355
  self._queue_event.set()
306
356
 
307
357
  async def close(self):
358
+ """Stop admission across the subtree and wait for issued work and cleanup."""
308
359
  if self._worker is None:
309
360
  self._worker = asyncio.create_task(self._run_forever())
310
361
  if self.accepts_input:
311
- self.agent.accepts_input = False
312
- self.publish_state("admission")
313
- if self._input_request is not None:
314
- self._finish_input_request(None)
315
- self._wake_worker()
362
+ self.agents_manager.request_close(self.agent.agent_id)
316
363
  await asyncio.shield(self._worker)
317
364
 
318
- async def submit_input(self, text, sender="user", wait_for_command=True):
365
+ def request_close(self):
366
+ """Manager-only local signal, after it captures this node's children."""
367
+ if not self.accepts_input:
368
+ return
369
+ self.agent.accepts_input = False
370
+ self.stop_asap()
371
+ pending = list(self._enqueue_queue)
372
+ if self._triggered_submission is not None:
373
+ pending.append(self._triggered_submission)
374
+ self._enqueue_queue.clear()
375
+ self._steer_queue.clear()
376
+ self._triggered_submission = None
377
+ for queued in pending:
378
+ self._finish_submission_exception(queued, SubmissionInterrupted())
379
+ if self._input_request is not None:
380
+ self._finish_input_request(None)
381
+ self.publish_state("admission")
382
+ self._wake_worker()
383
+
384
+ async def submit_input(self, text, sender="user", wait_for_command=True, name="user"):
385
+ """Route frontend text to a pending answer, slash command or steer input."""
319
386
  if not self.agent.accepts_input:
320
387
  raise RuntimeError("agent is shutting down")
321
- input_starts_with_space = text.startswith(" ")
322
- text = text.strip()
323
- command = text.split(None, 1)[0] if text else ""
324
- # Codex treats another slash in the name as a path and a leading
325
- # ASCII space as an escape, even for a registered command.
326
- is_command = (
327
- command.startswith("/")
328
- and not input_starts_with_space
329
- and "/" not in command[1:]
330
- and len(command) > 1
331
- )
332
- if self._input_request is not None and not is_command:
388
+ text, command, argument = _parse_input(text)
389
+ if self._input_request is not None and command is None:
333
390
  self._answer_input(text)
334
391
  future = asyncio.get_running_loop().create_future()
335
392
  future.set_result(None)
@@ -338,14 +395,12 @@ class AgentRuntime:
338
395
  future = asyncio.get_running_loop().create_future()
339
396
  future.set_result(None)
340
397
  return SubmittedInput(uuid7_string(), "empty", future)
341
- parts = text.split(None, 1)
342
- argument = parts[1] if len(parts) == 2 else ""
343
- if not is_command:
344
- return await self._submit_message(text, "steer", sender, False)
398
+ if command is None:
399
+ return self._submit_turn(text, "steer", sender, name)
345
400
  if command == "/queue":
346
401
  if not argument.strip():
347
402
  raise ValueError("Usage: /queue <message>")
348
- return await self._submit_message(argument.strip(), "enqueue", sender, True)
403
+ return self._submit_turn(argument.strip(), "enqueue", sender, name)
349
404
  submission_id = uuid7_string()
350
405
  future = asyncio.get_running_loop().create_future()
351
406
  future.add_done_callback(self._observe_completion)
@@ -354,7 +409,7 @@ class AgentRuntime:
354
409
  "submission_id": submission_id, "command": command,
355
410
  "sender": sender, "status": "queued",
356
411
  }
357
- self._publish_update("commands")
412
+ self.publish_update("commands")
358
413
  operation = self._run_command(receipt, command, argument.strip(), sender)
359
414
  if wait_for_command:
360
415
  await operation
@@ -394,7 +449,7 @@ class AgentRuntime:
394
449
  )
395
450
 
396
451
  async def _execute_command(self, command, argument):
397
- if command in {"help", "history", "compact", "fork"} and argument:
452
+ if command in {"help", "history", "compact"} and argument:
398
453
  raise ValueError("Usage: /{0}".format(command))
399
454
  if command == "help":
400
455
  return {"kind": "help", "commands": self.commands()}
@@ -453,20 +508,25 @@ class AgentRuntime:
453
508
  "retained_item_count": result.retained_item_count,
454
509
  "pruned_tool_results": result.pruned_tool_results,
455
510
  }
456
- if command == "fork":
457
- self.fork()
458
- return {"kind": "forked", "session_id": self.agent.session_id}
459
511
  handler = self.command_handlers.get(command)
460
512
  if handler is None:
461
513
  raise ValueError("Unknown command: /{0}".format(command))
462
514
  return await handler(argument)
463
515
 
464
- async def _submit_message(self, text, queue, sender, explicit_queue):
516
+ def _submit_turn(self, text, queue, sender, name):
465
517
  busy = self.is_busy
466
- submission_id, future = await self.enqueue_user_turn(text, queue)
467
- future.add_done_callback(self._observe_completion)
518
+ if queue == "enqueue":
519
+ submission_id, future = self.enqueue(text, name=name)
520
+ else:
521
+ current = self._current_submission if self.agent.is_running else None
522
+ self.stop_asap()
523
+ self.message(UserMessage(text, name=name))
524
+ submission_id, future = self.trigger()
525
+ self._triggered_submission.texts.append(text)
526
+ if current is not None:
527
+ self._triggered_submission.turn_id = current.turn_id
468
528
  self._publish(
469
- InputQueuedEvent(submission_id, text, queue, sender, explicit_queue, busy)
529
+ InputQueuedEvent(submission_id, text, queue, sender, queue == "enqueue", busy)
470
530
  )
471
531
  return SubmittedInput(submission_id, "turn", future)
472
532
 
@@ -513,58 +573,15 @@ class AgentRuntime:
513
573
  self._publish(InputResolvedEvent(request.request_id))
514
574
 
515
575
  def _input_request_event(self):
516
- request = self._input_request
517
- if request is None:
518
- return None
519
- if request.kind == "questions":
520
- return InputRequestedEvent(
521
- request.request_id,
522
- request.kind,
523
- request.other,
524
- question=request.payload["questions"][request.question_index],
525
- )
526
- return InputRequestedEvent(
527
- request.request_id,
528
- request.kind,
529
- request.other,
530
- permissions=request.payload,
531
- )
576
+ return self._input_request.event() if self._input_request is not None else None
532
577
 
533
578
  def _publish_input_request(self):
534
579
  self._publish(self._input_request_event())
535
580
 
536
581
  def _answer_input(self, text):
537
- request = self._input_request
538
- if not text:
539
- self._finish_input_request(None)
540
- return
541
- if request.kind == "permissions":
542
- answer = text.lower()
543
- granted = answer in {"t", "turn", "y", "yes", "s", "session"}
544
- self._finish_input_request(
545
- {
546
- "permissions": (
547
- request.payload.get("permissions", {}) if granted else {}
548
- ),
549
- "scope": "session" if answer in {"s", "session"} else "turn",
550
- }
551
- )
552
- return
553
- question = request.payload["questions"][request.question_index]
554
- options = question["options"]
555
- if not request.other and text.isdigit():
556
- choice = int(text)
557
- if choice == 0:
558
- request.other = True
559
- self._publish_input_request()
560
- return
561
- if 1 <= choice <= len(options):
562
- text = options[choice - 1]["label"]
563
- request.answers[question["id"]] = {"answers": [text]}
564
- request.question_index += 1
565
- request.other = False
566
- if request.question_index == len(request.payload["questions"]):
567
- self._finish_input_request({"answers": request.answers})
582
+ complete, answer = self._input_request.answer(text)
583
+ if complete:
584
+ self._finish_input_request(answer)
568
585
  else:
569
586
  self._publish_input_request()
570
587
 
@@ -589,64 +606,164 @@ class AgentRuntime:
589
606
  return (
590
607
  self.agent.is_running
591
608
  or self._current_submission is not None
592
- or bool(self._steer_queue or self._enqueue_queue)
609
+ or self._triggered_submission is not None
610
+ or bool(self._enqueue_queue)
593
611
  or (not self.accepts_input and not self.agent.is_shutdown)
594
612
  )
595
613
 
614
+ @property
615
+ def turn_elapsed_seconds(self) -> "float":
616
+ if self._turn_started_at is None:
617
+ return 0.0
618
+ end = monotonic() if self._turn_finished_at is None else self._turn_finished_at
619
+ return end - self._turn_started_at
620
+
621
+ @property
622
+ def agent_status(self):
623
+ if self.agent.is_shutdown:
624
+ return "shutdown"
625
+ if self._last_agent_status == "interrupted":
626
+ return "interrupted"
627
+ if self.is_busy:
628
+ return "running"
629
+ status = self._last_agent_status
630
+ return dict(status) if isinstance(status, dict) else status
631
+
632
+ def can_close_for_capacity(self):
633
+ """Only reclaim a finished runtime with no accepted or background work."""
634
+ return (
635
+ self.accepts_input
636
+ and not self.is_busy
637
+ and self._last_agent_status != "pending_init"
638
+ and not self._active_commands
639
+ and self._input_request is None
640
+ and not self._steer_queue
641
+ and not self.agent.tool_registry.runtime_environment.background_work_count(True)
642
+ )
643
+
596
644
  async def submit_user_turn(self, text: "str") -> "TurnResult":
597
- _submission_id, future = await self.enqueue_user_turn(text, queue="enqueue")
645
+ """Enqueue one independent turn and wait for its receipt."""
646
+ _submission_id, future = self.enqueue(text)
598
647
  return await future
599
648
 
600
- async def enqueue_user_turn(
601
- self,
602
- text: "str",
603
- queue: 'Literal["enqueue", "steer"]' = "enqueue",
604
- ) -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
605
- if queue not in {"enqueue", "steer"}:
606
- raise ValueError(f"unknown submission queue: {queue}")
607
- if not self.agent.accepts_input:
608
- raise RuntimeError("agent is shutting down")
609
- if queue == "steer":
610
- self.agent.stop_asap()
611
- future: "asyncio.Future[TurnResult]" = (
612
- asyncio.get_running_loop().create_future()
649
+ async def maybe_invoke(self, event: "typing.Dict[str, object]") -> "bool":
650
+ """Submit a tool notification only while this runtime is idle and open."""
651
+ if self.is_busy or not self.accepts_input:
652
+ return False
653
+ tag = event["type"]
654
+ if not isinstance(tag, str) or not tag.isidentifier():
655
+ raise ValueError("invoke event type must be an identifier")
656
+ payload = {key: value for key, value in event.items() if key != "type"}
657
+ text = (
658
+ f"<{tag}>\n"
659
+ f"{json.dumps(payload, ensure_ascii=False, separators=(',', ':'))}\n"
660
+ f"</{tag}>"
613
661
  )
614
- if queue == "steer" and self._steer_queue:
615
- queued = self._steer_queue[-1]
616
- queued.texts.append(text)
617
- queued.futures.append(future)
618
- self._publish_update("queue")
619
- return queued.submission_id, future
662
+ await self.start()
663
+ self.message(text)
664
+ _submission_id, future = self.trigger()
665
+ self._triggered_submission.texts.append(text)
666
+ await future
667
+ return True
668
+
669
+ def stop_asap(self) -> "None":
670
+ """Request a cooperative stop; issued model and tool operations finish."""
671
+ if self.agent.is_shutdown:
672
+ raise RuntimeError("agent is shutdown")
673
+ if self.agent.is_running:
674
+ self.agent.stop_asap()
675
+ self._wait_interrupted = True
676
+ if self._input_activity is not None:
677
+ self._input_activity.set()
678
+
679
+ def interrupt(self) -> "None":
680
+ """Request a stop and publish interrupted status immediately."""
681
+ self.stop_asap()
682
+ self._last_agent_status = "interrupted"
683
+ self.publish_update("interrupt")
684
+
685
+ def enqueue(self, text: "str", name: "str" = "user") -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
686
+ """Schedule an independent user turn without affecting active execution."""
687
+ if not self.accepts_input:
688
+ raise RuntimeError("agent is shutting down")
689
+ queued = _QueuedSubmission([text], name=name)
690
+ self._enqueue_queue.append(queued)
691
+ return self._submission_receipt(queued)
620
692
 
621
- submission_id = uuid7_string()
622
- current = self._current_submission if self.agent.is_running else None
623
- queued = _QueuedSubmission(
624
- submission_id=submission_id,
625
- turn_id=(
626
- current.turn_id
627
- if queue == "steer" and current is not None
628
- else submission_id
629
- ),
630
- texts=[text],
631
- futures=[future],
632
- )
633
- target = self._steer_queue if queue == "steer" else self._enqueue_queue
634
- target.append(queued)
635
- self._publish_update("queue")
636
- asyncio.get_running_loop().call_soon(self._wake_worker)
637
- return submission_id, future
693
+ def trigger(self) -> "typing.Union[typing.Tuple[str, asyncio.Future[TurnResult]], None]":
694
+ """Start or restart execution; repeated pending triggers share one run."""
695
+ if not self.accepts_input:
696
+ raise RuntimeError("agent is shutting down")
697
+ if self._active_turn is not None and not self.agent.execution_snapshot().stop_requested:
698
+ return None
699
+ if self._triggered_submission is None:
700
+ self._triggered_submission = _QueuedSubmission([])
701
+ return self._submission_receipt(self._triggered_submission)
702
+
703
+ def _submission_receipt(self, queued):
704
+ loop = asyncio.get_running_loop()
705
+ future = loop.create_future()
706
+ future.add_done_callback(self._observe_completion)
707
+ queued.futures.append(future)
708
+ # Publish after the input layer attaches display text and turn identity.
709
+ loop.call_soon(self._notify_queue_change)
710
+ return queued.submission_id, future
711
+
712
+ def _notify_queue_change(self):
713
+ # The worker can drain and unregister before this notification runs.
714
+ if self.agent.is_shutdown:
715
+ return
716
+ self.publish_update("queue")
717
+ self._wake_worker()
718
+
719
+ def message(self, text: "typing.Union[str, AgentMessage, ToolResult]") -> "None":
720
+ """Deliver input to an open runtime's mailbox."""
721
+ if not self.accepts_input:
722
+ raise RuntimeError("agent is shutting down")
723
+ self._steer_queue.append(UserMessage(text) if isinstance(text, str) else text)
724
+ if self._active_turn is not None:
725
+ self.agent.request_follow_up()
726
+ if self._input_activity is not None:
727
+ self._input_activity.set()
728
+
729
+ def _deliver_messages(self):
730
+ if not self._steer_queue or self.agent.execution_snapshot().stop_requested:
731
+ return
732
+ self.agent.receive_messages(tuple(self._steer_queue))
733
+ self._steer_queue.clear()
734
+ if self._input_activity is not None and not self._wait_interrupted:
735
+ self._input_activity.clear()
736
+
737
+ async def wait_for_activity(self, timeout_ms):
738
+ if self._input_activity is None:
739
+ self._input_activity = asyncio.Event()
740
+ if not self._steer_queue and not self._wait_interrupted:
741
+ waiter = asyncio.create_task(self._input_activity.wait())
742
+ try:
743
+ await asyncio.wait({waiter}, timeout=timeout_ms / 1000.0)
744
+ finally:
745
+ if not waiter.done():
746
+ waiter.cancel()
747
+ try:
748
+ await waiter
749
+ except asyncio.CancelledError:
750
+ pass
751
+ if self._wait_interrupted:
752
+ return {"message": "Wait interrupted by new input.", "timed_out": False}
753
+ if self._steer_queue:
754
+ return {"message": "Wait completed.", "timed_out": False}
755
+ return {"message": "Wait timed out.", "timed_out": True}
638
756
 
639
757
  async def _run_forever(self) -> "None":
640
758
  self._queue_event = asyncio.Event()
641
759
  while True:
642
- queued = await self._next_submission()
643
- if queued is None:
760
+ pending = await self._next_submission()
761
+ if pending is None:
644
762
  break
763
+ queued, texts = pending
645
764
  self._current_submission = queued
646
765
  try:
647
- result = await self.agent.run_turn(
648
- list(queued.texts), turn_id=queued.turn_id
649
- )
766
+ result = await self.agent.run_turn(texts, turn_id=queued.turn_id, name=queued.name)
650
767
  except TurnInterrupted:
651
768
  self._finish_submission_exception(queued, SubmissionInterrupted())
652
769
  except Exception as exc:
@@ -655,43 +772,45 @@ class AgentRuntime:
655
772
  self._finish_submission_result(queued, result)
656
773
  finally:
657
774
  self._current_submission = None
658
- self._publish_update("idle")
775
+ self.publish_update("idle")
659
776
  try:
660
777
  if self._command_tasks:
661
778
  await asyncio.gather(*tuple(self._command_tasks))
662
779
  async with self._get_command_lock():
663
- await self._close_resources()
780
+ await close_resources([
781
+ lambda: self.agents_manager.shutdown_children(self.agent.agent_id),
782
+ self.agent.tool_registry.runtime_environment.close,
783
+ ] + self._close_handlers)
664
784
  finally:
665
- self.agent.shutdown()
666
- self._publish(SessionClosedEvent())
667
-
668
- async def _close_resources(self):
669
- errors = []
670
- environment = self.agent.tool_registry.runtime_environment
671
- for handler in [environment.subagent_manager.shutdown] + self._close_handlers:
672
785
  try:
673
- await handler()
674
- except Exception as exc:
675
- errors.append(exc)
676
- if errors:
677
- for error in errors[1:]:
678
- asyncio.get_running_loop().call_exception_handler(
679
- {
680
- "message": "Session close handler failed",
681
- "exception": error,
682
- }
683
- )
684
- raise errors[0]
786
+ self.agent.shutdown()
787
+ finally:
788
+ self._publish(SessionClosedEvent())
789
+ self.agents_manager.unregister_runtime(self.agent.agent_id)
685
790
 
686
- async def _next_submission(self) -> "typing.Union[_QueuedSubmission, None]":
791
+ async def _next_submission(self) -> "typing.Union[typing.Tuple[_QueuedSubmission, typing.List[str]], None]":
687
792
  while True:
688
793
  await self.agent.wait_until_idle()
689
- if self._steer_queue:
690
- return self._steer_queue.popleft()
691
- if self._enqueue_queue:
692
- return self._enqueue_queue.popleft()
693
794
  if not self.accepts_input:
694
795
  return None
796
+ if self._triggered_submission is not None:
797
+ queued, self._triggered_submission = self._triggered_submission, None
798
+ return queued, []
799
+ if self._enqueue_queue:
800
+ queued = self._enqueue_queue.popleft()
801
+ return queued, list(queued.texts)
802
+ if not self._steer_queue:
803
+ continuation = self.agent.tool_registry.runtime_environment.take_continuation()
804
+ if continuation is not None:
805
+ # Let reply consumers close or submit input before autonomous work.
806
+ await asyncio.sleep(0)
807
+ if (
808
+ not self.accepts_input or self._triggered_submission is not None
809
+ or self._enqueue_queue or self._steer_queue
810
+ ):
811
+ continue
812
+ self.message(continuation)
813
+ return _QueuedSubmission([]), []
695
814
  self._queue_event.clear()
696
815
  await self._queue_event.wait()
697
816
 
@@ -714,12 +833,35 @@ class AgentRuntime:
714
833
  future.set_exception(exc)
715
834
 
716
835
  def _handle_agent_event(self, event: "TurnEvent") -> "None":
836
+ if isinstance(event, TurnStartedEvent):
837
+ self._turn_started_at = monotonic()
838
+ self._turn_finished_at = None
839
+ elif isinstance(event, (TurnCompletedEvent, TurnFailedEvent, TurnInterruptedEvent)):
840
+ self._turn_finished_at = monotonic()
717
841
  queued = self._current_submission
718
842
  if queued is not None and event.turn_id == queued.turn_id:
719
843
  event = replace(
720
844
  event, submission_id=event.submission_id or queued.submission_id
721
845
  )
846
+ if isinstance(event, TurnStartedEvent):
847
+ # Triggered input is delivered through steer, not run_turn's texts.
848
+ event = replace(event, user_texts=tuple(queued.texts))
849
+ if isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
850
+ self._wait_interrupted = False
851
+ if self._input_activity is not None and not self._steer_queue:
852
+ self._input_activity.clear()
853
+ elif isinstance(event, TurnInputReadyEvent):
854
+ self._deliver_messages()
855
+ elif isinstance(event, TurnCompletedEvent):
856
+ self._last_agent_status = {"completed": event.output_text}
857
+ elif isinstance(event, TurnFailedEvent):
858
+ self._last_agent_status = {
859
+ "errored": "{0}: {1}".format(event.error_type, event.error),
860
+ }
861
+ elif isinstance(event, TurnInterruptedEvent):
862
+ self._last_agent_status = "interrupted"
722
863
  if isinstance(event, TurnStartedEvent):
864
+ self._last_agent_status = "running"
723
865
  self._active_turn = {
724
866
  "turn_id": event.turn_id,
725
867
  "submission_id": event.submission_id or event.turn_id,
@@ -750,13 +892,15 @@ class AgentRuntime:
750
892
  if prompt:
751
893
  self.title = shorten_title(prompt)
752
894
  self.publish_state("auto_title")
753
- if isinstance(event, TerminalEvent) and event.background_work_count is not None:
754
- self._background_work_count = event.background_work_count
755
895
  if self.agent.recorded_session_file_path != self._recorded_rollout_path:
756
896
  self.publish_state("recording")
757
897
  self._publish(event)
758
898
 
759
899
  def _publish(self, event: "Event"):
900
+ self._notify_handler(
901
+ lambda event: self.agents_manager.handle_event(self.agent.agent_id, event),
902
+ event,
903
+ )
760
904
  for handler in (self.event_handler,) + tuple(self._frontends.values()):
761
905
  self._notify_handler(handler, event)
762
906