python-codex 0.5.1__py3-none-any.whl → 0.6.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.
Files changed (72) hide show
  1. pycodex/__init__.py +18 -8
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +27 -239
  4. pycodex/cli.py +19 -14
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +369 -51
  7. pycodex/events.py +28 -186
  8. pycodex/model.py +181 -88
  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 +1069 -140
  18. pycodex/protocol.py +78 -15
  19. pycodex/runtime.py +461 -203
  20. pycodex/tools/__init__.py +100 -7
  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 -29
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +2 -139
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -12
  28. pycodex/tools/exec_runtime.py +381 -0
  29. pycodex/tools/exec_tool.py +78 -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/request_user_input_tool.py +3 -23
  38. pycodex/tools/runtime_services.py +124 -408
  39. pycodex/tools/send_message_tool.py +42 -0
  40. pycodex/tools/spawn_agent_tool.py +55 -94
  41. pycodex/tools/unified_exec_manager.py +52 -34
  42. pycodex/tools/wait_agent_tool.py +46 -66
  43. pycodex/tools/wait_tool.py +24 -13
  44. pycodex/tools/web_search_tool.py +1 -0
  45. pycodex/utils/codex_config.py +105 -0
  46. pycodex/utils/compactor.py +4 -0
  47. pycodex/utils/compat.py +2 -2
  48. pycodex/utils/doctor.py +5 -4
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +33 -0
  51. pycodex/utils/session_persist.py +106 -33
  52. python_codex-0.6.0.dist-info/METADATA +352 -0
  53. python_codex-0.6.0.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +7 -6
  56. responses_server/config.py +0 -11
  57. responses_server/payload_processors.py +4 -4
  58. responses_server/request_translation.py +480 -0
  59. responses_server/server.py +31 -24
  60. responses_server/stream_events.py +124 -0
  61. responses_server/stream_router.py +33 -830
  62. responses_server/tools/custom_adapter.py +29 -29
  63. responses_server/transport.py +332 -0
  64. pycodex/tools/close_agent_tool.py +0 -60
  65. pycodex/tools/exec_runtime.js +0 -161
  66. pycodex/tools/resume_agent_tool.py +0 -54
  67. pycodex/tools/send_input_tool.py +0 -110
  68. python_codex-0.5.1.dist-info/METADATA +0 -235
  69. python_codex-0.5.1.dist-info/RECORD +0 -90
  70. {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
  71. {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
  72. {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
pycodex/runtime.py CHANGED
@@ -1,53 +1,63 @@
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,
14
+ CommandStartedEvent,
15
+ CompactStartedEvent,
13
16
  Event,
14
17
  InputQueuedEvent,
15
18
  InputRequestedEvent,
16
19
  InputResolvedEvent,
20
+ RuntimeUpdatedEvent,
17
21
  SessionClosedEvent,
18
22
  SessionStateEvent,
19
23
  StreamErrorEvent,
20
- TerminalEvent,
21
24
  ToolCompletedEvent,
22
25
  TurnCompletedEvent,
23
26
  TurnEvent,
24
27
  TurnFailedEvent,
28
+ TurnInputReadyEvent,
25
29
  TurnInterruptedEvent,
26
30
  TurnStartedEvent,
27
31
  )
28
32
  from .model import ModelControl
29
- from .protocol import TurnResult
33
+ from .protocol import AgentMessage, ToolResult, TurnResult, UserMessage
34
+ from .tools.runtime_services import close_resources
30
35
  from .utils import uuid7_string
31
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
32
39
  from .utils.session_persist import (
33
- conversation_history_to_turns,
34
40
  list_resumable_sessions,
35
41
  resolve_codex_home,
36
42
  select_resumable_session,
37
43
  )
38
44
 
45
+ if typing.TYPE_CHECKING:
46
+ from .multi_agents import AgentsManager
47
+
39
48
 
40
49
  class SubmissionInterrupted(RuntimeError):
41
50
  def __init__(self) -> "None":
42
51
  super().__init__("submission interrupted")
43
52
 
44
53
 
45
- @dataclass
46
54
  class _QueuedSubmission:
47
- submission_id: "str"
48
- turn_id: "str"
49
- texts: "typing.List[str]"
50
- 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]]" = []
51
61
 
52
62
 
53
63
  @dataclass(frozen=True)
@@ -68,38 +78,96 @@ class _InputRequest:
68
78
  other: "bool" = False
69
79
  timer: "typing.Union[asyncio.TimerHandle, None]" = None
70
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
+
71
125
 
72
126
  class AgentRuntime:
73
- """Frontend-independent session input, scheduling, state and events."""
127
+ """Session input and scheduling for an Agent whose client implements ModelControl."""
74
128
 
75
- def __init__(self, agent: "Agent") -> "None":
129
+ def __init__(self, agent: "Agent", agents_manager: "AgentsManager") -> "None":
76
130
  self.agent = agent
131
+ self.agents_manager = agents_manager
77
132
  self._enqueue_queue: "deque[_QueuedSubmission]" = deque()
78
- 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
79
135
  self._queue_event = None
80
136
  self._current_submission: "typing.Union[_QueuedSubmission, None]" = None
81
137
  self.event_handler = BASE_EVENT_HANDLER
82
138
  self.agent.event_handler = self._handle_agent_event
83
139
  self.codex_home = (
84
- agent.context_manager._config.codex_home or resolve_codex_home()
140
+ agent.context_manager.config.codex_home or resolve_codex_home()
85
141
  )
86
142
  self.title = ""
87
143
  self.command_handlers = {}
88
144
  self._frontends = {}
145
+ self._interactive_frontends = set()
146
+ self._command_tasks = set()
147
+ self._active_commands = {}
89
148
  self._close_handlers = []
90
149
  self._worker = None
91
150
  self._command_lock = None
92
151
  self._input_request = None
93
- self._background_work_count = 0
94
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"
95
158
  self._recorded_rollout_path = agent.recorded_session_file_path
96
159
  environment = agent.tool_registry.runtime_environment
97
- environment.request_user_input_manager.set_handler(self._request_user_input)
98
- environment.request_permissions_manager.set_handler(self._request_permissions)
160
+ environment.bind(
161
+ self.maybe_invoke, self.receive_tool_output, self.publish_update,
162
+ self._request_user_input, self._request_permissions,
163
+ )
164
+ environment.restart()
99
165
 
100
- def attach(self, event_handler):
166
+ def attach(self, event_handler, interactive=True):
101
167
  frontend_id = uuid7_string()
102
168
  self._frontends[frontend_id] = event_handler
169
+ if interactive:
170
+ self._interactive_frontends.add(frontend_id)
103
171
  self._notify_handler(
104
172
  event_handler, SessionStateEvent("attach", self.snapshot())
105
173
  )
@@ -107,7 +175,8 @@ class AgentRuntime:
107
175
 
108
176
  def detach(self, frontend_id):
109
177
  del self._frontends[frontend_id]
110
- if not self._frontends and self._input_request is not None:
178
+ self._interactive_frontends.discard(frontend_id)
179
+ if not self._interactive_frontends and self._input_request is not None:
111
180
  self._finish_input_request(None)
112
181
 
113
182
  def register_command(self, name, handler):
@@ -118,6 +187,13 @@ class AgentRuntime:
118
187
  def add_close_handler(self, handler):
119
188
  self._close_handlers.append(handler)
120
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
+
121
197
  def commands(self):
122
198
  return (
123
199
  (
@@ -129,47 +205,97 @@ class AgentRuntime:
129
205
  "effort",
130
206
  "resume",
131
207
  "compact",
132
- "fork",
133
208
  )
134
209
  + tuple(self.command_handlers)
135
210
  + ("queue",)
136
211
  )
137
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
+
138
230
  def snapshot(self):
231
+ execution = self.agent.execution_snapshot()
139
232
  rollout_path = self.agent.session_file_path
140
233
  recorded_path = self.agent.recorded_session_file_path
141
234
  return {
142
- "session_id": self.agent.session_id,
143
- "cwd": str(self.agent.context_manager.cwd),
235
+ **self._snapshot_fields(execution),
236
+ "session_id": execution.session_id,
144
237
  "rollout_path": str(rollout_path) if rollout_path is not None else None,
145
- "recorded_rollout_path": (
146
- str(recorded_path) if recorded_path is not None else None
147
- ),
238
+ "recorded_rollout_path": str(recorded_path) if recorded_path is not None else None,
148
239
  "model": "{0}:{1}".format(
149
240
  self.agent.model_name,
150
- getattr(self.agent.model_client, "reasoning_effort", None) or "default",
241
+ self.agent.model_client.reasoning_effort or "default",
151
242
  ),
152
- "title": self.title,
153
243
  "history": conversation_history_to_turns(self.agent.history),
154
- "busy": self.is_busy,
155
- "closed": self.agent.is_shutdown,
156
- "accepts_input": self.agent.accepts_input,
157
- "context_window": self.agent.context_manager.resolve_model_context_window(),
158
- "max_context_window": (
159
- self.agent.context_manager.resolve_model_max_context_window()
160
- ),
161
- "auto_compact_token_limit": (
162
- self.agent.context_manager.resolve_auto_compact_token_limit()
163
- ),
164
- "usage_tokens": self.agent._last_total_usage_tokens,
165
- "background_work_count": self._background_work_count,
166
- "input_request": self._input_request_event(),
167
244
  "active_turn": (
168
245
  dict(self._active_turn) if self._active_turn is not None else None
169
246
  ),
170
- "plan": self.agent.tool_registry.runtime_environment.plan_store.snapshot(),
171
247
  }
172
248
 
249
+ def state_snapshot(self):
250
+ """Current frontend state, without completed conversation history."""
251
+ agent = self.agent
252
+ execution = agent.execution_snapshot()
253
+ client = typing.cast(ModelControl, agent.model_client)
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)
259
+ return {
260
+ **self._snapshot_fields(execution),
261
+ "agent_id": agent.agent_id,
262
+ "agent_path": agent.agent_path,
263
+ "agent_session_id": execution.session_id,
264
+ "model": {
265
+ "name": agent.model_name,
266
+ "reasoning_effort": client.reasoning_effort,
267
+ },
268
+ "running": execution.running,
269
+ "active_turn": (
270
+ {
271
+ key: active[key]
272
+ for key in (
273
+ "turn_id", "submission_id", "user_texts", "assistant_text",
274
+ "model_errors",
275
+ )
276
+ } if active is not None else None
277
+ ),
278
+ "queued_inputs": [
279
+ {
280
+ "submission_id": item.submission_id,
281
+ "turn_id": item.turn_id,
282
+ "queue": name,
283
+ "prompts": list(item.texts),
284
+ }
285
+ for name, item in pending
286
+ ],
287
+ "commands": [dict(command) for command in self._active_commands.values()],
288
+ }
289
+
290
+ def background_work_snapshot(self):
291
+ return self.agent.tool_registry.runtime_environment.background_work_snapshot()
292
+
293
+ async def list_models(self):
294
+ return await self.agent.model_client.list_models()
295
+
296
+ def publish_update(self, reason):
297
+ self._publish(RuntimeUpdatedEvent(reason))
298
+
173
299
  def publish_state(self, reason):
174
300
  self._recorded_rollout_path = self.agent.recorded_session_file_path
175
301
  self._publish(SessionStateEvent(reason, self.snapshot()))
@@ -195,26 +321,28 @@ class AgentRuntime:
195
321
  self.publish_state("cwd")
196
322
 
197
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)
198
326
  self.require_idle("resume")
199
327
  resumed = self.agent.resume(path)
328
+ self.agent.tool_registry.runtime_environment.restart()
200
329
  if resumed is not None:
201
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()
202
333
  self.publish_state("history" if path is not None else "admission")
203
334
  return resumed
204
335
 
205
- def fork(self):
206
- self.require_idle("fork")
207
- self.agent.fork()
208
- self.publish_state("identity")
209
-
210
336
  async def start(self, config_path=None):
211
337
  if config_path is not None:
212
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")
213
341
  if self._worker is None or self._worker.done():
214
342
  if self.agent.is_shutdown:
215
343
  raise RuntimeError("resume the agent before restarting its runtime")
216
- self.agent.accepts_input = True
217
344
  self._worker = asyncio.create_task(self._run_forever())
345
+ self.agent.tool_registry.runtime_environment.start()
218
346
  return self
219
347
 
220
348
  def _get_command_lock(self):
@@ -227,31 +355,38 @@ class AgentRuntime:
227
355
  self._queue_event.set()
228
356
 
229
357
  async def close(self):
358
+ """Stop admission across the subtree and wait for issued work and cleanup."""
230
359
  if self._worker is None:
231
360
  self._worker = asyncio.create_task(self._run_forever())
232
361
  if self.accepts_input:
233
- self.agent.accepts_input = False
234
- self.publish_state("admission")
235
- if self._input_request is not None:
236
- self._finish_input_request(None)
237
- self._wake_worker()
362
+ self.agents_manager.request_close(self.agent.agent_id)
238
363
  await asyncio.shield(self._worker)
239
364
 
240
- async def submit_input(self, text, sender="user"):
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."""
241
386
  if not self.agent.accepts_input:
242
387
  raise RuntimeError("agent is shutting down")
243
- input_starts_with_space = text.startswith(" ")
244
- text = text.strip()
245
- command = text.split(None, 1)[0] if text else ""
246
- # Codex treats another slash in the name as a path and a leading
247
- # ASCII space as an escape, even for a registered command.
248
- is_command = (
249
- command.startswith("/")
250
- and not input_starts_with_space
251
- and "/" not in command[1:]
252
- and len(command) > 1
253
- )
254
- 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:
255
390
  self._answer_input(text)
256
391
  future = asyncio.get_running_loop().create_future()
257
392
  future.set_result(None)
@@ -260,32 +395,61 @@ class AgentRuntime:
260
395
  future = asyncio.get_running_loop().create_future()
261
396
  future.set_result(None)
262
397
  return SubmittedInput(uuid7_string(), "empty", future)
263
- parts = text.split(None, 1)
264
- argument = parts[1] if len(parts) == 2 else ""
265
- if not is_command:
266
- return await self._submit_message(text, "steer", sender, False)
398
+ if command is None:
399
+ return self._submit_turn(text, "steer", sender, name)
267
400
  if command == "/queue":
268
401
  if not argument.strip():
269
402
  raise ValueError("Usage: /queue <message>")
270
- return await self._submit_message(argument.strip(), "enqueue", sender, True)
403
+ return self._submit_turn(argument.strip(), "enqueue", sender, name)
271
404
  submission_id = uuid7_string()
272
405
  future = asyncio.get_running_loop().create_future()
406
+ future.add_done_callback(self._observe_completion)
407
+ receipt = SubmittedInput(submission_id, "command", future)
408
+ self._active_commands[submission_id] = {
409
+ "submission_id": submission_id, "command": command,
410
+ "sender": sender, "status": "queued",
411
+ }
412
+ self.publish_update("commands")
413
+ operation = self._run_command(receipt, command, argument.strip(), sender)
414
+ if wait_for_command:
415
+ await operation
416
+ else:
417
+ task = asyncio.create_task(operation)
418
+ self._command_tasks.add(task)
419
+ task.add_done_callback(self._command_tasks.discard)
420
+ return receipt
421
+
422
+ async def _run_command(self, receipt, command, argument, sender):
273
423
  try:
274
424
  async with self._get_command_lock():
275
- if not self.agent.accepts_input:
276
- raise RuntimeError("agent is shutting down")
277
- result = await self._execute_command(command[1:], argument.strip())
425
+ self._active_commands[receipt.submission_id]["status"] = "running"
426
+ self._publish(
427
+ CommandStartedEvent(receipt.submission_id, command, sender)
428
+ )
429
+ result = await self._execute_command(command[1:], argument)
430
+ except asyncio.CancelledError:
431
+ del self._active_commands[receipt.submission_id]
432
+ receipt.future.cancel()
433
+ self._publish(CommandFailedEvent(
434
+ receipt.submission_id, command, "command caller cancelled",
435
+ sender, "CancelledError",
436
+ ))
437
+ raise
278
438
  except Exception as exc:
279
- future.set_exception(exc)
280
- self._publish(CommandFailedEvent(submission_id, command, str(exc), sender))
439
+ del self._active_commands[receipt.submission_id]
440
+ receipt.future.set_exception(exc)
441
+ self._publish(CommandFailedEvent(
442
+ receipt.submission_id, command, str(exc), sender, type(exc).__name__,
443
+ ))
281
444
  else:
282
- future.set_result(result)
283
- self._publish(CommandCompletedEvent(submission_id, command, result, sender))
284
- future.add_done_callback(self._observe_completion)
285
- return SubmittedInput(submission_id, "command", future)
445
+ del self._active_commands[receipt.submission_id]
446
+ receipt.future.set_result(result)
447
+ self._publish(
448
+ CommandCompletedEvent(receipt.submission_id, command, result, sender)
449
+ )
286
450
 
287
451
  async def _execute_command(self, command, argument):
288
- if command in {"help", "history", "compact", "fork"} and argument:
452
+ if command in {"help", "history", "compact"} and argument:
289
453
  raise ValueError("Usage: /{0}".format(command))
290
454
  if command == "help":
291
455
  return {"kind": "help", "commands": self.commands()}
@@ -309,7 +473,7 @@ class AgentRuntime:
309
473
  return {
310
474
  "kind": "models",
311
475
  "model": self.agent.model_name,
312
- "models": await self.agent.model_client.list_models(),
476
+ "models": await self.list_models(),
313
477
  }
314
478
  if command == "effort":
315
479
  client = typing.cast(ModelControl, self.agent.model_client)
@@ -344,20 +508,25 @@ class AgentRuntime:
344
508
  "retained_item_count": result.retained_item_count,
345
509
  "pruned_tool_results": result.pruned_tool_results,
346
510
  }
347
- if command == "fork":
348
- self.fork()
349
- return {"kind": "forked", "session_id": self.agent.session_id}
350
511
  handler = self.command_handlers.get(command)
351
512
  if handler is None:
352
513
  raise ValueError("Unknown command: /{0}".format(command))
353
514
  return await handler(argument)
354
515
 
355
- async def _submit_message(self, text, queue, sender, explicit_queue):
516
+ def _submit_turn(self, text, queue, sender, name):
356
517
  busy = self.is_busy
357
- submission_id, future = await self.enqueue_user_turn(text, queue)
358
- 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
359
528
  self._publish(
360
- InputQueuedEvent(submission_id, text, queue, sender, explicit_queue, busy)
529
+ InputQueuedEvent(submission_id, text, queue, sender, queue == "enqueue", busy)
361
530
  )
362
531
  return SubmittedInput(submission_id, "turn", future)
363
532
 
@@ -373,7 +542,7 @@ class AgentRuntime:
373
542
  return await self._request_input("permissions", payload)
374
543
 
375
544
  async def _request_input(self, kind, payload):
376
- if not self._frontends or not self.agent.accepts_input:
545
+ if not self._interactive_frontends or not self.agent.accepts_input:
377
546
  return None
378
547
  if self._input_request is not None:
379
548
  raise RuntimeError("a user input request is already pending")
@@ -404,58 +573,15 @@ class AgentRuntime:
404
573
  self._publish(InputResolvedEvent(request.request_id))
405
574
 
406
575
  def _input_request_event(self):
407
- request = self._input_request
408
- if request is None:
409
- return None
410
- if request.kind == "questions":
411
- return InputRequestedEvent(
412
- request.request_id,
413
- request.kind,
414
- request.other,
415
- question=request.payload["questions"][request.question_index],
416
- )
417
- return InputRequestedEvent(
418
- request.request_id,
419
- request.kind,
420
- request.other,
421
- permissions=request.payload,
422
- )
576
+ return self._input_request.event() if self._input_request is not None else None
423
577
 
424
578
  def _publish_input_request(self):
425
579
  self._publish(self._input_request_event())
426
580
 
427
581
  def _answer_input(self, text):
428
- request = self._input_request
429
- if not text:
430
- self._finish_input_request(None)
431
- return
432
- if request.kind == "permissions":
433
- answer = text.lower()
434
- granted = answer in {"t", "turn", "y", "yes", "s", "session"}
435
- self._finish_input_request(
436
- {
437
- "permissions": (
438
- request.payload.get("permissions", {}) if granted else {}
439
- ),
440
- "scope": "session" if answer in {"s", "session"} else "turn",
441
- }
442
- )
443
- return
444
- question = request.payload["questions"][request.question_index]
445
- options = question["options"]
446
- if not request.other and text.isdigit():
447
- choice = int(text)
448
- if choice == 0:
449
- request.other = True
450
- self._publish_input_request()
451
- return
452
- if 1 <= choice <= len(options):
453
- text = options[choice - 1]["label"]
454
- request.answers[question["id"]] = {"answers": [text]}
455
- request.question_index += 1
456
- request.other = False
457
- if request.question_index == len(request.payload["questions"]):
458
- self._finish_input_request({"answers": request.answers})
582
+ complete, answer = self._input_request.answer(text)
583
+ if complete:
584
+ self._finish_input_request(answer)
459
585
  else:
460
586
  self._publish_input_request()
461
587
 
@@ -480,62 +606,164 @@ class AgentRuntime:
480
606
  return (
481
607
  self.agent.is_running
482
608
  or self._current_submission is not None
483
- or bool(self._steer_queue or self._enqueue_queue)
609
+ or self._triggered_submission is not None
610
+ or bool(self._enqueue_queue)
484
611
  or (not self.accepts_input and not self.agent.is_shutdown)
485
612
  )
486
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
+
487
644
  async def submit_user_turn(self, text: "str") -> "TurnResult":
488
- _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)
489
647
  return await future
490
648
 
491
- async def enqueue_user_turn(
492
- self,
493
- text: "str",
494
- queue: 'Literal["enqueue", "steer"]' = "enqueue",
495
- ) -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
496
- if queue not in {"enqueue", "steer"}:
497
- raise ValueError(f"unknown submission queue: {queue}")
498
- if not self.agent.accepts_input:
499
- raise RuntimeError("agent is shutting down")
500
- if queue == "steer":
501
- self.agent.stop_asap()
502
- future: "asyncio.Future[TurnResult]" = (
503
- 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}>"
504
661
  )
505
- if queue == "steer" and self._steer_queue:
506
- queued = self._steer_queue[-1]
507
- queued.texts.append(text)
508
- queued.futures.append(future)
509
- 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)
510
692
 
511
- submission_id = uuid7_string()
512
- current = self._current_submission if self.agent.is_running else None
513
- queued = _QueuedSubmission(
514
- submission_id=submission_id,
515
- turn_id=(
516
- current.turn_id
517
- if queue == "steer" and current is not None
518
- else submission_id
519
- ),
520
- texts=[text],
521
- futures=[future],
522
- )
523
- target = self._steer_queue if queue == "steer" else self._enqueue_queue
524
- target.append(queued)
525
- asyncio.get_running_loop().call_soon(self._wake_worker)
526
- 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}
527
756
 
528
757
  async def _run_forever(self) -> "None":
529
758
  self._queue_event = asyncio.Event()
530
759
  while True:
531
- queued = await self._next_submission()
532
- if queued is None:
760
+ pending = await self._next_submission()
761
+ if pending is None:
533
762
  break
763
+ queued, texts = pending
534
764
  self._current_submission = queued
535
765
  try:
536
- result = await self.agent.run_turn(
537
- list(queued.texts), turn_id=queued.turn_id
538
- )
766
+ result = await self.agent.run_turn(texts, turn_id=queued.turn_id, name=queued.name)
539
767
  except TurnInterrupted:
540
768
  self._finish_submission_exception(queued, SubmissionInterrupted())
541
769
  except Exception as exc:
@@ -544,40 +772,45 @@ class AgentRuntime:
544
772
  self._finish_submission_result(queued, result)
545
773
  finally:
546
774
  self._current_submission = None
775
+ self.publish_update("idle")
547
776
  try:
777
+ if self._command_tasks:
778
+ await asyncio.gather(*tuple(self._command_tasks))
548
779
  async with self._get_command_lock():
549
- 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)
550
784
  finally:
551
- self.agent.shutdown()
552
- self._publish(SessionClosedEvent())
553
-
554
- async def _close_resources(self):
555
- errors = []
556
- environment = self.agent.tool_registry.runtime_environment
557
- for handler in [environment.subagent_manager.shutdown] + self._close_handlers:
558
785
  try:
559
- await handler()
560
- except Exception as exc:
561
- errors.append(exc)
562
- if errors:
563
- for error in errors[1:]:
564
- asyncio.get_running_loop().call_exception_handler(
565
- {
566
- "message": "Session close handler failed",
567
- "exception": error,
568
- }
569
- )
570
- raise errors[0]
786
+ self.agent.shutdown()
787
+ finally:
788
+ self._publish(SessionClosedEvent())
789
+ self.agents_manager.unregister_runtime(self.agent.agent_id)
571
790
 
572
- async def _next_submission(self) -> "typing.Union[_QueuedSubmission, None]":
791
+ async def _next_submission(self) -> "typing.Union[typing.Tuple[_QueuedSubmission, typing.List[str]], None]":
573
792
  while True:
574
793
  await self.agent.wait_until_idle()
575
- if self._steer_queue:
576
- return self._steer_queue.popleft()
577
- if self._enqueue_queue:
578
- return self._enqueue_queue.popleft()
579
794
  if not self.accepts_input:
580
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([]), []
581
814
  self._queue_event.clear()
582
815
  await self._queue_event.wait()
583
816
 
@@ -600,12 +833,35 @@ class AgentRuntime:
600
833
  future.set_exception(exc)
601
834
 
602
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()
603
841
  queued = self._current_submission
604
842
  if queued is not None and event.turn_id == queued.turn_id:
605
843
  event = replace(
606
844
  event, submission_id=event.submission_id or queued.submission_id
607
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"
608
863
  if isinstance(event, TurnStartedEvent):
864
+ self._last_agent_status = "running"
609
865
  self._active_turn = {
610
866
  "turn_id": event.turn_id,
611
867
  "submission_id": event.submission_id or event.turn_id,
@@ -636,13 +892,15 @@ class AgentRuntime:
636
892
  if prompt:
637
893
  self.title = shorten_title(prompt)
638
894
  self.publish_state("auto_title")
639
- if isinstance(event, TerminalEvent) and event.background_work_count is not None:
640
- self._background_work_count = event.background_work_count
641
895
  if self.agent.recorded_session_file_path != self._recorded_rollout_path:
642
896
  self.publish_state("recording")
643
897
  self._publish(event)
644
898
 
645
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
+ )
646
904
  for handler in (self.event_handler,) + tuple(self._frontends.values()):
647
905
  self._notify_handler(handler, event)
648
906