python-codex 0.6.3__py3-none-any.whl → 0.7.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.
- pycodex/agent.py +325 -321
- pycodex/config.py +19 -2
- pycodex/context.py +24 -9
- pycodex/events.py +127 -7
- pycodex/model.py +269 -95
- pycodex/multi_agents.py +13 -42
- pycodex/prompts/models.json +8 -8
- pycodex/protocol.py +4 -2
- pycodex/runtime.py +227 -131
- pycodex/tools/__init__.py +3 -3
- pycodex/tools/clock_manager.py +0 -7
- pycodex/tools/exec_command_tool.py +16 -5
- pycodex/tools/exec_runtime.py +5 -1
- pycodex/tools/goal_manager.py +25 -32
- pycodex/tools/runtime_services.py +21 -11
- pycodex/tools/unified_exec_manager.py +46 -3
- pycodex/utils/compactor.py +28 -101
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +47 -0
- pycodex/utils/history.py +22 -7
- pycodex/utils/model_metadata.py +5 -4
- pycodex/utils/session_persist.py +6 -2
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/METADATA +40 -13
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/RECORD +30 -30
- responses_server/app.py +4 -0
- responses_server/gemini_api.py +26 -7
- responses_server/transport.py +12 -5
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/WHEEL +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/licenses/LICENSE +0 -0
pycodex/runtime.py
CHANGED
|
@@ -2,38 +2,41 @@ import asyncio
|
|
|
2
2
|
import json
|
|
3
3
|
import typing
|
|
4
4
|
from collections import deque
|
|
5
|
+
from contextlib import contextmanager
|
|
5
6
|
from dataclasses import dataclass, field, replace
|
|
6
7
|
from time import monotonic
|
|
7
8
|
|
|
8
|
-
from .agent import
|
|
9
|
+
from .agent import Agent
|
|
9
10
|
from .events import (
|
|
10
11
|
AssistantDeltaEvent,
|
|
12
|
+
AutoCompactCompletedEvent,
|
|
13
|
+
BASE_EVENT_HANDLER,
|
|
11
14
|
CommandCompletedEvent,
|
|
12
15
|
CommandFailedEvent,
|
|
13
16
|
CommandStartedEvent,
|
|
14
|
-
|
|
17
|
+
CompactCompletedEvent,
|
|
15
18
|
Event,
|
|
19
|
+
EventScope,
|
|
16
20
|
InputQueuedEvent,
|
|
17
21
|
InputRequestedEvent,
|
|
18
22
|
InputResolvedEvent,
|
|
19
23
|
MessagesAddedEvent,
|
|
24
|
+
ModelCalledEvent,
|
|
25
|
+
ModelRequestInterrupted,
|
|
26
|
+
ReasoningEvent,
|
|
20
27
|
RuntimeUpdatedEvent,
|
|
21
28
|
SessionClosedEvent,
|
|
22
29
|
SessionStateEvent,
|
|
23
30
|
StreamErrorEvent,
|
|
24
|
-
|
|
25
|
-
TurnCompletedEvent,
|
|
31
|
+
ToolStartedEvent,
|
|
26
32
|
TurnEvent,
|
|
27
|
-
|
|
28
|
-
TurnInputReadyEvent,
|
|
29
|
-
TurnInterruptedEvent,
|
|
30
|
-
TurnStartedEvent,
|
|
33
|
+
TurnInterrupted,
|
|
31
34
|
)
|
|
32
|
-
from .model import ModelControl
|
|
33
|
-
from .protocol import AgentMessage,
|
|
35
|
+
from .model import ModelControl, RetryCodes, matches_retry_codes
|
|
36
|
+
from .protocol import AgentMessage, ToolResult, TurnResult, UserMessage
|
|
34
37
|
from .tools.runtime_services import close_resources
|
|
35
38
|
from .utils import uuid7_string
|
|
36
|
-
from .utils.event_helpers import shorten_title
|
|
39
|
+
from .utils.event_helpers import last_reasoning_text, shorten_title, visible_input_text
|
|
37
40
|
from .utils.history import conversation_history_to_turns
|
|
38
41
|
from .utils.truncation import truncate_tool_result_for_history
|
|
39
42
|
from .utils.session_persist import (
|
|
@@ -46,6 +49,12 @@ if typing.TYPE_CHECKING:
|
|
|
46
49
|
from .multi_agents import AgentsManager
|
|
47
50
|
|
|
48
51
|
|
|
52
|
+
_INVOKE_VISIBLE_TAGS = {
|
|
53
|
+
"clock_tick": "Wake-up",
|
|
54
|
+
"exec_command_completed": "Task done",
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
49
58
|
class SubmissionInterrupted(RuntimeError):
|
|
50
59
|
def __init__(self) -> "None":
|
|
51
60
|
super().__init__("submission interrupted")
|
|
@@ -111,6 +120,12 @@ class _InputRequest:
|
|
|
111
120
|
return complete, {"answers": self.answers} if complete else None
|
|
112
121
|
|
|
113
122
|
|
|
123
|
+
def _completed_submission(kind):
|
|
124
|
+
future = asyncio.get_running_loop().create_future()
|
|
125
|
+
future.set_result(None)
|
|
126
|
+
return SubmittedInput(uuid7_string(), kind, future)
|
|
127
|
+
|
|
128
|
+
|
|
114
129
|
def _parse_input(text):
|
|
115
130
|
"""Recognize slash commands, preserving ASCII-space escapes and paths."""
|
|
116
131
|
escaped = text.startswith(" ")
|
|
@@ -122,6 +137,20 @@ def _parse_input(text):
|
|
|
122
137
|
return text, command, parts[1] if len(parts) == 2 else ""
|
|
123
138
|
|
|
124
139
|
|
|
140
|
+
def _parse_retry_argument(argument: "str") -> "typing.Tuple[typing.Optional[RetryCodes], str]":
|
|
141
|
+
if argument == "*":
|
|
142
|
+
return "*", "Retrying all model request errors indefinitely."
|
|
143
|
+
try:
|
|
144
|
+
codes = frozenset(int(part) for part in argument.split("|"))
|
|
145
|
+
except ValueError:
|
|
146
|
+
return None, "Infinite retry disabled."
|
|
147
|
+
if len(codes) == 1:
|
|
148
|
+
code = next(iter(codes))
|
|
149
|
+
return code, "Retrying error code {0} indefinitely.".format(code)
|
|
150
|
+
label = "|".join(str(code) for code in sorted(codes))
|
|
151
|
+
return codes, "Retrying error codes {0} indefinitely.".format(label)
|
|
152
|
+
|
|
153
|
+
|
|
125
154
|
class AgentRuntime:
|
|
126
155
|
"""Session input and scheduling for an Agent whose client implements ModelControl."""
|
|
127
156
|
|
|
@@ -134,7 +163,8 @@ class AgentRuntime:
|
|
|
134
163
|
self._queue_event = None
|
|
135
164
|
self._current_submission: "typing.Union[_QueuedSubmission, None]" = None
|
|
136
165
|
self.event_handler = BASE_EVENT_HANDLER
|
|
137
|
-
self.agent.event_handler = self.
|
|
166
|
+
self.agent.event_handler = self._publish_agent_event
|
|
167
|
+
self.agent.runtime_scope = self._runtime_scope
|
|
138
168
|
self.codex_home = (
|
|
139
169
|
agent.context_manager.config.codex_home or resolve_codex_home()
|
|
140
170
|
)
|
|
@@ -167,9 +197,7 @@ class AgentRuntime:
|
|
|
167
197
|
self._frontends[frontend_id] = event_handler
|
|
168
198
|
if interactive:
|
|
169
199
|
self._interactive_frontends.add(frontend_id)
|
|
170
|
-
self.
|
|
171
|
-
event_handler, SessionStateEvent("attach", self.snapshot())
|
|
172
|
-
)
|
|
200
|
+
EventScope.notify(SessionStateEvent("attach", self.snapshot()), event_handler)
|
|
173
201
|
return frontend_id
|
|
174
202
|
|
|
175
203
|
def detach(self, frontend_id):
|
|
@@ -204,6 +232,7 @@ class AgentRuntime:
|
|
|
204
232
|
"effort",
|
|
205
233
|
"resume",
|
|
206
234
|
"compact",
|
|
235
|
+
"retry",
|
|
207
236
|
)
|
|
208
237
|
+ tuple(self.command_handlers)
|
|
209
238
|
+ ("queue",)
|
|
@@ -241,12 +270,27 @@ class AgentRuntime:
|
|
|
241
270
|
"history": conversation_history_to_turns(self.agent.history),
|
|
242
271
|
}
|
|
243
272
|
|
|
273
|
+
def active_turn_snapshot(self):
|
|
274
|
+
active = self._active_turn
|
|
275
|
+
if active is None:
|
|
276
|
+
return None
|
|
277
|
+
return {
|
|
278
|
+
"turn_id": active.turn_id,
|
|
279
|
+
"submission_id": self._current_submission.submission_id
|
|
280
|
+
if self._current_submission is not None else active.turn_id,
|
|
281
|
+
"messages": active.messages,
|
|
282
|
+
"assistant_text": active.assistant_text,
|
|
283
|
+
"reasoning": self._stream_reasoning,
|
|
284
|
+
"model_errors": list(active.model_errors),
|
|
285
|
+
}
|
|
286
|
+
|
|
244
287
|
def state_snapshot(self):
|
|
245
288
|
"""Current frontend state, without completed conversation history."""
|
|
246
289
|
agent = self.agent
|
|
247
290
|
execution = agent.execution_snapshot()
|
|
248
291
|
client = typing.cast(ModelControl, agent.model_client)
|
|
249
|
-
|
|
292
|
+
status = self._last_agent_status
|
|
293
|
+
failed = status == "interrupted" or isinstance(status, dict) and "errored" in status
|
|
250
294
|
pending = []
|
|
251
295
|
if self._triggered_submission is not None:
|
|
252
296
|
pending.append(("steer", self._triggered_submission))
|
|
@@ -261,7 +305,8 @@ class AgentRuntime:
|
|
|
261
305
|
"reasoning_effort": client.reasoning_effort,
|
|
262
306
|
},
|
|
263
307
|
"running": execution.running,
|
|
264
|
-
"
|
|
308
|
+
"last_reasoning": last_reasoning_text(agent.history) if self._active_turn is None and not failed else "",
|
|
309
|
+
"active_turn": self.active_turn_snapshot(),
|
|
265
310
|
"queued_inputs": [
|
|
266
311
|
{
|
|
267
312
|
"submission_id": item.submission_id,
|
|
@@ -282,11 +327,18 @@ class AgentRuntime:
|
|
|
282
327
|
return await self.agent.model_client.list_models()
|
|
283
328
|
|
|
284
329
|
def publish_update(self, reason):
|
|
330
|
+
if reason != "agents":
|
|
331
|
+
self.agents_manager.notify_parents(self.agent.agent_id)
|
|
285
332
|
self._publish(RuntimeUpdatedEvent(reason))
|
|
286
333
|
|
|
287
334
|
def publish_state(self, reason):
|
|
335
|
+
try:
|
|
336
|
+
state = self.snapshot()
|
|
337
|
+
except (Exception, asyncio.CancelledError) as exc:
|
|
338
|
+
EventScope.report_observer_error("Session state notification failed: " + reason, exc)
|
|
339
|
+
return
|
|
288
340
|
self._recorded_rollout_path = self.agent.recorded_session_file_path
|
|
289
|
-
self._publish(SessionStateEvent(reason,
|
|
341
|
+
self._publish(SessionStateEvent(reason, state))
|
|
290
342
|
|
|
291
343
|
def require_idle(self, operation):
|
|
292
344
|
if self.is_busy:
|
|
@@ -342,20 +394,29 @@ class AgentRuntime:
|
|
|
342
394
|
if self._queue_event is not None:
|
|
343
395
|
self._queue_event.set()
|
|
344
396
|
|
|
345
|
-
async def close(self):
|
|
346
|
-
"""Stop admission across the subtree and wait for issued work and cleanup.
|
|
397
|
+
async def close(self, finish_turn=False):
|
|
398
|
+
"""Stop admission across the subtree and wait for issued work and cleanup.
|
|
399
|
+
|
|
400
|
+
With ``finish_turn`` active turns run to their natural end instead of
|
|
401
|
+
receiving a cooperative stop; only waits are woken early.
|
|
402
|
+
"""
|
|
347
403
|
if self._worker is None:
|
|
348
404
|
self._worker = asyncio.create_task(self._run_forever())
|
|
349
405
|
if self.accepts_input:
|
|
350
|
-
self.agents_manager.request_close(self.agent.agent_id)
|
|
406
|
+
self.agents_manager.request_close(self.agent.agent_id, finish_turn)
|
|
351
407
|
await asyncio.shield(self._worker)
|
|
352
408
|
|
|
353
|
-
def request_close(self):
|
|
409
|
+
def request_close(self, finish_turn=False):
|
|
354
410
|
"""Manager-only local signal, after it captures this node's children."""
|
|
355
411
|
if not self.accepts_input:
|
|
356
412
|
return
|
|
357
413
|
self.agent.accepts_input = False
|
|
358
|
-
|
|
414
|
+
if not finish_turn:
|
|
415
|
+
self.stop_asap()
|
|
416
|
+
elif self.agent.is_running:
|
|
417
|
+
self._wait_interrupted = True
|
|
418
|
+
if self._input_activity is not None:
|
|
419
|
+
self._input_activity.set()
|
|
359
420
|
pending = list(self._enqueue_queue)
|
|
360
421
|
if self._triggered_submission is not None:
|
|
361
422
|
pending.append(self._triggered_submission)
|
|
@@ -369,20 +430,25 @@ class AgentRuntime:
|
|
|
369
430
|
self.publish_state("admission")
|
|
370
431
|
self._wake_worker()
|
|
371
432
|
|
|
372
|
-
async def submit_input(
|
|
433
|
+
async def submit_input(
|
|
434
|
+
self, text, sender="user", wait_for_command=True, name="user", trigger=True,
|
|
435
|
+
):
|
|
373
436
|
"""Route frontend text to a pending answer, slash command or steer input."""
|
|
437
|
+
if not isinstance(trigger, bool):
|
|
438
|
+
raise ValueError("trigger must be a boolean")
|
|
374
439
|
if not self.agent.accepts_input:
|
|
375
440
|
raise RuntimeError("agent is shutting down")
|
|
441
|
+
if not trigger:
|
|
442
|
+
text = text.strip()
|
|
443
|
+
if text:
|
|
444
|
+
self.message(UserMessage(text, name=name))
|
|
445
|
+
return _completed_submission("message" if text else "empty")
|
|
376
446
|
text, command, argument = _parse_input(text)
|
|
377
447
|
if self._input_request is not None and command is None:
|
|
378
448
|
self._answer_input(text)
|
|
379
|
-
|
|
380
|
-
future.set_result(None)
|
|
381
|
-
return SubmittedInput(uuid7_string(), "answer", future)
|
|
449
|
+
return _completed_submission("answer")
|
|
382
450
|
if not text:
|
|
383
|
-
|
|
384
|
-
future.set_result(None)
|
|
385
|
-
return SubmittedInput(uuid7_string(), "empty", future)
|
|
451
|
+
return _completed_submission("empty")
|
|
386
452
|
if command is None:
|
|
387
453
|
return self._submit_turn(text, "steer", sender, name)
|
|
388
454
|
if command == "/queue":
|
|
@@ -408,33 +474,38 @@ class AgentRuntime:
|
|
|
408
474
|
return receipt
|
|
409
475
|
|
|
410
476
|
async def _run_command(self, receipt, command, argument, sender):
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
477
|
+
async def execute():
|
|
478
|
+
self._active_commands[receipt.submission_id]["status"] = "running"
|
|
479
|
+
self.agents_manager.mark_used(self.agent.agent_id)
|
|
480
|
+
EventScope.emit(CommandStartedEvent(receipt.submission_id, command, sender))
|
|
481
|
+
return await self._execute_command(command[1:], argument)
|
|
482
|
+
|
|
483
|
+
with EventScope.observe(self._publish):
|
|
484
|
+
try:
|
|
485
|
+
# Retry controls must remain usable while a compact holds the lock.
|
|
486
|
+
if command == "/retry" and argument:
|
|
487
|
+
result = await execute()
|
|
488
|
+
else:
|
|
489
|
+
async with self._get_command_lock():
|
|
490
|
+
result = await execute()
|
|
491
|
+
except asyncio.CancelledError:
|
|
492
|
+
del self._active_commands[receipt.submission_id]
|
|
493
|
+
receipt.future.cancel()
|
|
494
|
+
EventScope.emit(CommandFailedEvent(
|
|
495
|
+
receipt.submission_id, command, "command caller cancelled",
|
|
496
|
+
sender, "CancelledError",
|
|
497
|
+
))
|
|
498
|
+
raise
|
|
499
|
+
except Exception as exc:
|
|
500
|
+
del self._active_commands[receipt.submission_id]
|
|
501
|
+
receipt.future.set_exception(exc)
|
|
502
|
+
EventScope.emit(CommandFailedEvent(
|
|
503
|
+
receipt.submission_id, command, str(exc), sender, type(exc).__name__,
|
|
504
|
+
))
|
|
505
|
+
else:
|
|
506
|
+
del self._active_commands[receipt.submission_id]
|
|
507
|
+
receipt.future.set_result(result)
|
|
508
|
+
EventScope.emit(CommandCompletedEvent(receipt.submission_id, command, result, sender))
|
|
438
509
|
|
|
439
510
|
async def _execute_command(self, command, argument):
|
|
440
511
|
if command in {"help", "history", "compact"} and argument:
|
|
@@ -474,6 +545,31 @@ class AgentRuntime:
|
|
|
474
545
|
effort = client.reasoning_effort
|
|
475
546
|
self.publish_state("effort")
|
|
476
547
|
return {"kind": "effort", "reasoning_effort": effort}
|
|
548
|
+
if command == "retry":
|
|
549
|
+
client = typing.cast(ModelControl, self.agent.model_client)
|
|
550
|
+
if not argument:
|
|
551
|
+
self.require_idle("retry")
|
|
552
|
+
if client.last_error is None:
|
|
553
|
+
raise ValueError("No failed model request to retry.")
|
|
554
|
+
await self.start()
|
|
555
|
+
submission_id, _future = self.trigger()
|
|
556
|
+
return {
|
|
557
|
+
"kind": "retry", "submission_id": submission_id,
|
|
558
|
+
"lines": ["Retrying the failed model request."],
|
|
559
|
+
}
|
|
560
|
+
codes, status = _parse_retry_argument(argument)
|
|
561
|
+
client.set_retry_error_code(codes)
|
|
562
|
+
lines = [status]
|
|
563
|
+
result = {"kind": "retry", "lines": lines}
|
|
564
|
+
if (
|
|
565
|
+
codes is not None and not self.is_busy
|
|
566
|
+
and client.last_error is not None
|
|
567
|
+
and matches_retry_codes(client.last_error, codes)
|
|
568
|
+
):
|
|
569
|
+
await self.start()
|
|
570
|
+
result["submission_id"], _future = self.trigger()
|
|
571
|
+
lines.append("Retrying the failed model request.")
|
|
572
|
+
return result
|
|
477
573
|
if command == "resume":
|
|
478
574
|
if not argument:
|
|
479
575
|
return {
|
|
@@ -514,7 +610,7 @@ class AgentRuntime:
|
|
|
514
610
|
if current is not None:
|
|
515
611
|
self._triggered_submission.turn_id = current.turn_id
|
|
516
612
|
self._publish(
|
|
517
|
-
InputQueuedEvent(submission_id, message, queue, sender, queue == "enqueue", busy)
|
|
613
|
+
InputQueuedEvent(submission_id, message, queue, sender, queue == "enqueue", busy),
|
|
518
614
|
)
|
|
519
615
|
return SubmittedInput(submission_id, "turn", future)
|
|
520
616
|
|
|
@@ -648,7 +744,7 @@ class AgentRuntime:
|
|
|
648
744
|
f"</{tag}>"
|
|
649
745
|
)
|
|
650
746
|
await self.start()
|
|
651
|
-
self.message(text)
|
|
747
|
+
self.message(UserMessage(text, visible=_INVOKE_VISIBLE_TAGS.get(tag, tag)))
|
|
652
748
|
_submission_id, future = self.trigger()
|
|
653
749
|
await future
|
|
654
750
|
return True
|
|
@@ -694,6 +790,7 @@ class AgentRuntime:
|
|
|
694
790
|
queued.futures.append(future)
|
|
695
791
|
# Publish after the input layer attaches the execution identity.
|
|
696
792
|
loop.call_soon(self._notify_queue_change)
|
|
793
|
+
loop.call_soon(self._wake_worker)
|
|
697
794
|
return queued.submission_id, future
|
|
698
795
|
|
|
699
796
|
def _notify_queue_change(self):
|
|
@@ -701,7 +798,6 @@ class AgentRuntime:
|
|
|
701
798
|
if self.agent.is_shutdown:
|
|
702
799
|
return
|
|
703
800
|
self.publish_update("queue")
|
|
704
|
-
self._wake_worker()
|
|
705
801
|
|
|
706
802
|
def message(self, text: "typing.Union[str, UserMessage, AgentMessage, ToolResult]") -> "None":
|
|
707
803
|
"""Deliver input to an open runtime's mailbox."""
|
|
@@ -748,6 +844,9 @@ class AgentRuntime:
|
|
|
748
844
|
await waiter
|
|
749
845
|
except asyncio.CancelledError:
|
|
750
846
|
pass
|
|
847
|
+
if not self.accepts_input:
|
|
848
|
+
# A graceful close cannot wait for input that will never arrive.
|
|
849
|
+
self.stop_asap()
|
|
751
850
|
if self._wait_interrupted:
|
|
752
851
|
return {"message": "Wait interrupted by new input.", "timed_out": False}
|
|
753
852
|
if self._steer_queue:
|
|
@@ -832,81 +931,78 @@ class AgentRuntime:
|
|
|
832
931
|
if not future.done():
|
|
833
932
|
future.set_exception(exc)
|
|
834
933
|
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
934
|
+
@contextmanager
|
|
935
|
+
def _runtime_scope(self, turn_scope, manual=False):
|
|
936
|
+
agent_id = self.agent.agent_id
|
|
937
|
+
self.agents_manager.mark_used(agent_id)
|
|
938
|
+
self._wait_interrupted = False
|
|
939
|
+
if self._input_activity is not None and not self._steer_queue:
|
|
940
|
+
self._input_activity.clear()
|
|
941
|
+
if manual:
|
|
942
|
+
try:
|
|
943
|
+
with turn_scope:
|
|
944
|
+
self.agents_manager.notify_parents(agent_id)
|
|
945
|
+
yield
|
|
946
|
+
finally:
|
|
947
|
+
self.agents_manager.notify_parents(agent_id)
|
|
948
|
+
return
|
|
949
|
+
|
|
950
|
+
self._last_agent_status = "running"
|
|
951
|
+
self._stream_reasoning = ""
|
|
952
|
+
self._turn_started_at = monotonic()
|
|
953
|
+
self._turn_finished_at = None
|
|
954
|
+
final_answer = None
|
|
955
|
+
try:
|
|
956
|
+
with turn_scope as turn:
|
|
957
|
+
self._active_turn = turn
|
|
958
|
+
turn.deliver_messages = self._deliver_messages
|
|
959
|
+
if not self.title:
|
|
960
|
+
prompt = "\n".join(
|
|
961
|
+
message.text
|
|
962
|
+
for message in turn.messages
|
|
963
|
+
if isinstance(message, (UserMessage, AgentMessage))
|
|
964
|
+
and message.visible is True
|
|
965
|
+
).strip()
|
|
966
|
+
if prompt:
|
|
967
|
+
self.title = shorten_title(prompt)
|
|
968
|
+
self.publish_state("auto_title")
|
|
969
|
+
self.agents_manager.notify_parents(agent_id)
|
|
970
|
+
yield
|
|
971
|
+
except (TurnInterrupted, ModelRequestInterrupted, asyncio.CancelledError):
|
|
972
|
+
self._last_agent_status = "interrupted"
|
|
973
|
+
raise
|
|
974
|
+
except Exception as exc:
|
|
975
|
+
error = "{0}: {1}".format(type(exc).__name__, exc)
|
|
976
|
+
self._last_agent_status = {"errored": error}
|
|
977
|
+
final_answer = "Agent errored: " + error
|
|
978
|
+
raise
|
|
979
|
+
else:
|
|
980
|
+
self._last_agent_status = {"completed": turn.output_text}
|
|
981
|
+
final_answer = turn.output_text or ""
|
|
982
|
+
finally:
|
|
983
|
+
self._active_turn = None
|
|
840
984
|
self._turn_finished_at = monotonic()
|
|
985
|
+
self.agents_manager.finish_turn(agent_id, final_answer)
|
|
986
|
+
self._wake_worker()
|
|
987
|
+
|
|
988
|
+
@EventScope.router
|
|
989
|
+
def _publish_agent_event(self, event: "Event") -> "None":
|
|
990
|
+
if isinstance(event, ReasoningEvent):
|
|
991
|
+
self._stream_reasoning = event.text
|
|
992
|
+
elif isinstance(event, AssistantDeltaEvent) and event.delta:
|
|
993
|
+
self._stream_reasoning = ""
|
|
994
|
+
elif isinstance(event, (
|
|
995
|
+
MessagesAddedEvent, StreamErrorEvent, ModelCalledEvent, ToolStartedEvent,
|
|
996
|
+
AutoCompactCompletedEvent, CompactCompletedEvent,
|
|
997
|
+
)):
|
|
998
|
+
self._stream_reasoning = last_reasoning_text(self.agent.history)
|
|
841
999
|
queued = self._current_submission
|
|
842
|
-
if queued is not None and event.turn_id == queued.turn_id:
|
|
843
|
-
event = replace(
|
|
844
|
-
event, submission_id=event.submission_id or queued.submission_id
|
|
845
|
-
)
|
|
846
|
-
if isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
|
|
847
|
-
self._wait_interrupted = False
|
|
848
|
-
if self._input_activity is not None and not self._steer_queue:
|
|
849
|
-
self._input_activity.clear()
|
|
850
|
-
elif isinstance(event, TurnInputReadyEvent):
|
|
851
|
-
self._deliver_messages()
|
|
852
|
-
elif isinstance(event, TurnCompletedEvent):
|
|
853
|
-
self._last_agent_status = {"completed": event.output_text}
|
|
854
|
-
elif isinstance(event, TurnFailedEvent):
|
|
855
|
-
self._last_agent_status = {
|
|
856
|
-
"errored": "{0}: {1}".format(event.error_type, event.error),
|
|
857
|
-
}
|
|
858
|
-
elif isinstance(event, TurnInterruptedEvent):
|
|
859
|
-
self._last_agent_status = "interrupted"
|
|
860
|
-
if isinstance(event, TurnStartedEvent):
|
|
861
|
-
self._last_agent_status = "running"
|
|
862
|
-
self._active_turn = {
|
|
863
|
-
"turn_id": event.turn_id,
|
|
864
|
-
"submission_id": event.submission_id or event.turn_id,
|
|
865
|
-
"messages": event.messages,
|
|
866
|
-
"assistant_text": "",
|
|
867
|
-
"model_errors": [],
|
|
868
|
-
}
|
|
869
|
-
elif self._active_turn is not None:
|
|
870
|
-
if isinstance(event, AssistantDeltaEvent):
|
|
871
|
-
self._active_turn["assistant_text"] += event.delta
|
|
872
|
-
elif isinstance(event, MessagesAddedEvent) and any(
|
|
873
|
-
isinstance(message, AssistantMessage) for message in event.messages
|
|
874
|
-
):
|
|
875
|
-
self._active_turn["assistant_text"] = ""
|
|
876
|
-
elif isinstance(event, StreamErrorEvent):
|
|
877
|
-
self._active_turn["assistant_text"] = ""
|
|
878
|
-
self._active_turn["model_errors"].append(event.detail())
|
|
879
|
-
elif isinstance(event, ToolCompletedEvent):
|
|
880
|
-
self._active_turn["assistant_text"] = ""
|
|
881
|
-
elif isinstance(
|
|
882
|
-
event, (TurnCompletedEvent, TurnFailedEvent, TurnInterruptedEvent)
|
|
883
|
-
):
|
|
884
|
-
self._active_turn = None
|
|
885
|
-
if isinstance(event, TurnStartedEvent) and not self.title:
|
|
886
|
-
prompt = event.visualize()
|
|
887
|
-
if prompt:
|
|
888
|
-
self.title = shorten_title(prompt)
|
|
889
|
-
self.publish_state("auto_title")
|
|
1000
|
+
if isinstance(event, TurnEvent) and queued is not None and event.turn_id == queued.turn_id:
|
|
1001
|
+
event = replace(event, submission_id=event.submission_id or queued.submission_id)
|
|
890
1002
|
if self.agent.recorded_session_file_path != self._recorded_rollout_path:
|
|
891
1003
|
self.publish_state("recording")
|
|
892
1004
|
self._publish(event)
|
|
893
1005
|
|
|
1006
|
+
@EventScope.router
|
|
894
1007
|
def _publish(self, event: "Event"):
|
|
895
|
-
self.
|
|
896
|
-
lambda event: self.agents_manager.handle_event(self.agent.agent_id, event),
|
|
897
|
-
event,
|
|
898
|
-
)
|
|
899
|
-
for handler in (self.event_handler,) + tuple(self._frontends.values()):
|
|
900
|
-
self._notify_handler(handler, event)
|
|
901
|
-
|
|
902
|
-
@staticmethod
|
|
903
|
-
def _notify_handler(handler, event):
|
|
904
|
-
try:
|
|
905
|
-
handler(event)
|
|
906
|
-
except (Exception, asyncio.CancelledError) as exc:
|
|
907
|
-
asyncio.get_running_loop().call_exception_handler(
|
|
908
|
-
{
|
|
909
|
-
"message": "Submission event observer failed: " + event.kind,
|
|
910
|
-
"exception": exc,
|
|
911
|
-
}
|
|
912
|
-
)
|
|
1008
|
+
EventScope.notify(event, self.event_handler, *self._frontends.values())
|
pycodex/tools/__init__.py
CHANGED
|
@@ -108,11 +108,11 @@ def get_tools(
|
|
|
108
108
|
restart=code_mode_manager.restart, close=code_mode_manager.close,
|
|
109
109
|
)
|
|
110
110
|
elif tool is exec_command_tool:
|
|
111
|
-
runtime_environment.register_resource(tool.name, unified_exec_manager)
|
|
112
|
-
elif tool is set_period_tool:
|
|
113
111
|
runtime_environment.register_resource(
|
|
114
|
-
|
|
112
|
+
tool.name, unified_exec_manager, close=unified_exec_manager.close,
|
|
115
113
|
)
|
|
114
|
+
elif tool is set_period_tool:
|
|
115
|
+
runtime_environment.register_resource("clock", clock_manager)
|
|
116
116
|
return registry
|
|
117
117
|
|
|
118
118
|
|
pycodex/tools/clock_manager.py
CHANGED
|
@@ -5,7 +5,6 @@ import math
|
|
|
5
5
|
import typing
|
|
6
6
|
from datetime import datetime, timedelta
|
|
7
7
|
|
|
8
|
-
from ..events import CompactCompletedEvent, CompactStartedEvent, TurnCompletedEvent, TurnStartedEvent
|
|
9
8
|
from ..protocol import JSONDict
|
|
10
9
|
|
|
11
10
|
|
|
@@ -27,12 +26,6 @@ class ClockManager:
|
|
|
27
26
|
self._notify_hook = invoke
|
|
28
27
|
self._state_listener = state_changed
|
|
29
28
|
|
|
30
|
-
def handle_agent_event(self, event):
|
|
31
|
-
if isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
|
|
32
|
-
self.turn_started()
|
|
33
|
-
elif isinstance(event, (TurnCompletedEvent, CompactCompletedEvent)):
|
|
34
|
-
self.arm_after_reply()
|
|
35
|
-
|
|
36
29
|
def background_work_count(self, after_reply):
|
|
37
30
|
return int(self.enabled if after_reply else self.armed)
|
|
38
31
|
|
|
@@ -18,6 +18,7 @@ from .unified_exec_manager import (
|
|
|
18
18
|
DEFAULT_EXEC_YIELD_TIME_MS,
|
|
19
19
|
DEFAULT_LOGIN,
|
|
20
20
|
DEFAULT_TTY,
|
|
21
|
+
DEFAULT_WAKE_ME_UP_WHEN_DONE,
|
|
21
22
|
UNIFIED_EXEC_OUTPUT_SCHEMA,
|
|
22
23
|
UnifiedExecManager,
|
|
23
24
|
)
|
|
@@ -28,11 +29,7 @@ MAX_EXEC_YIELD_TIME_MS = 30_000
|
|
|
28
29
|
|
|
29
30
|
class ExecCommandTool(BaseTool):
|
|
30
31
|
name = "exec_command"
|
|
31
|
-
description =
|
|
32
|
-
"Runs a command in a PTY, returning output or a session ID for ongoing interaction. "
|
|
33
|
-
"For long tasks, you can reply first; when the task finishes, you will be "
|
|
34
|
-
"invoked to continue."
|
|
35
|
-
)
|
|
32
|
+
description = "Runs a command in a PTY, returning output or a session ID for ongoing interaction."
|
|
36
33
|
input_schema = {
|
|
37
34
|
"type": "object",
|
|
38
35
|
"properties": {
|
|
@@ -64,6 +61,14 @@ class ExecCommandTool(BaseTool):
|
|
|
64
61
|
"type": "boolean",
|
|
65
62
|
"description": "True runs the shell with -l/-i semantics; false disables them. Defaults to true.",
|
|
66
63
|
},
|
|
64
|
+
"wake_me_up_when_done": {
|
|
65
|
+
"type": "boolean",
|
|
66
|
+
"default": False,
|
|
67
|
+
"description": (
|
|
68
|
+
"True wakes the idle agent when a background session finishes; "
|
|
69
|
+
"false or omitted does not."
|
|
70
|
+
),
|
|
71
|
+
},
|
|
67
72
|
},
|
|
68
73
|
"required": ["cmd"],
|
|
69
74
|
"additionalProperties": False,
|
|
@@ -78,6 +83,11 @@ class ExecCommandTool(BaseTool):
|
|
|
78
83
|
cmd = str(args.get("cmd", "")).strip()
|
|
79
84
|
if not cmd:
|
|
80
85
|
return "Error: `cmd` is required."
|
|
86
|
+
wake_me_up_when_done = args.get(
|
|
87
|
+
"wake_me_up_when_done", DEFAULT_WAKE_ME_UP_WHEN_DONE
|
|
88
|
+
)
|
|
89
|
+
if not isinstance(wake_me_up_when_done, bool):
|
|
90
|
+
raise ValueError("wake_me_up_when_done must be a boolean")
|
|
81
91
|
|
|
82
92
|
return await self._manager.exec_command(
|
|
83
93
|
cmd=cmd,
|
|
@@ -93,6 +103,7 @@ class ExecCommandTool(BaseTool):
|
|
|
93
103
|
MAX_EXEC_YIELD_TIME_MS,
|
|
94
104
|
),
|
|
95
105
|
max_output_tokens=self._optional_int(args, "max_output_tokens"),
|
|
106
|
+
wake_me_up_when_done=wake_me_up_when_done,
|
|
96
107
|
)
|
|
97
108
|
|
|
98
109
|
def _optional_string(
|
pycodex/tools/exec_runtime.py
CHANGED
|
@@ -7,11 +7,12 @@ from copy import deepcopy
|
|
|
7
7
|
import inspect
|
|
8
8
|
import io
|
|
9
9
|
import json
|
|
10
|
+
import sys
|
|
10
11
|
import traceback
|
|
11
12
|
from types import SimpleNamespace
|
|
12
13
|
import wave
|
|
13
14
|
|
|
14
|
-
from ..utils.compat import compile_async_cell
|
|
15
|
+
from ..utils.compat import compile_async_cell, copy_context
|
|
15
16
|
from .python_tool_schema import python_tool_signature
|
|
16
17
|
|
|
17
18
|
_BLOCKED_MODULES = frozenset(("ctypes", "_ctypes", "cffi"))
|
|
@@ -65,6 +66,9 @@ class CellTaskFactory:
|
|
|
65
66
|
task = asyncio.Task(coroutine, loop=self._loop, **kwargs)
|
|
66
67
|
else:
|
|
67
68
|
task = self._previous(self._loop, coroutine, **kwargs)
|
|
69
|
+
if sys.version_info < (3, 7):
|
|
70
|
+
# Direct cell tasks bypass the backport's loop.create_task hook.
|
|
71
|
+
task.context = copy_context()
|
|
68
72
|
if owner is not None:
|
|
69
73
|
self._owners[task] = owner
|
|
70
74
|
owner._tasks.add(task)
|