python-codex 0.6.2__py3-none-any.whl → 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycodex/agent.py +325 -314
- pycodex/bootstrap.py +8 -0
- pycodex/config.py +4 -2
- pycodex/context.py +32 -11
- pycodex/events.py +116 -7
- pycodex/model.py +214 -99
- pycodex/multi_agents.py +11 -40
- pycodex/prompts/models.json +351 -6
- pycodex/protocol.py +1 -0
- pycodex/runtime.py +173 -127
- pycodex/tools/__init__.py +1 -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 +15 -3
- pycodex/utils/compactor.py +28 -98
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +9 -0
- pycodex/utils/http_headers.py +25 -0
- pycodex/utils/model_metadata.py +5 -4
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/METADATA +34 -8
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/RECORD +35 -34
- responses_server/app.py +6 -0
- responses_server/config.py +4 -1
- responses_server/gemini_api.py +40 -13
- responses_server/messages_api.py +12 -6
- responses_server/payload_processors.py +1 -1
- responses_server/request_translation.py +55 -13
- responses_server/stream_router.py +9 -0
- responses_server/transport.py +24 -11
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/WHEEL +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/licenses/LICENSE +0 -0
pycodex/protocol.py
CHANGED
pycodex/runtime.py
CHANGED
|
@@ -2,38 +2,33 @@ 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
|
+
BASE_EVENT_HANDLER,
|
|
11
12
|
CommandCompletedEvent,
|
|
12
13
|
CommandFailedEvent,
|
|
13
14
|
CommandStartedEvent,
|
|
14
|
-
CompactStartedEvent,
|
|
15
15
|
Event,
|
|
16
|
+
EventScope,
|
|
16
17
|
InputQueuedEvent,
|
|
17
18
|
InputRequestedEvent,
|
|
18
19
|
InputResolvedEvent,
|
|
19
|
-
|
|
20
|
+
ModelRequestInterrupted,
|
|
20
21
|
RuntimeUpdatedEvent,
|
|
21
22
|
SessionClosedEvent,
|
|
22
23
|
SessionStateEvent,
|
|
23
|
-
StreamErrorEvent,
|
|
24
|
-
ToolCompletedEvent,
|
|
25
|
-
TurnCompletedEvent,
|
|
26
24
|
TurnEvent,
|
|
27
|
-
|
|
28
|
-
TurnInputReadyEvent,
|
|
29
|
-
TurnInterruptedEvent,
|
|
30
|
-
TurnStartedEvent,
|
|
25
|
+
TurnInterrupted,
|
|
31
26
|
)
|
|
32
|
-
from .model import ModelControl
|
|
33
|
-
from .protocol import AgentMessage,
|
|
27
|
+
from .model import ModelControl, RetryCodes, matches_retry_codes
|
|
28
|
+
from .protocol import AgentMessage, ToolResult, TurnResult, UserMessage
|
|
34
29
|
from .tools.runtime_services import close_resources
|
|
35
30
|
from .utils import uuid7_string
|
|
36
|
-
from .utils.event_helpers import shorten_title
|
|
31
|
+
from .utils.event_helpers import shorten_title, visible_input_text
|
|
37
32
|
from .utils.history import conversation_history_to_turns
|
|
38
33
|
from .utils.truncation import truncate_tool_result_for_history
|
|
39
34
|
from .utils.session_persist import (
|
|
@@ -111,6 +106,12 @@ class _InputRequest:
|
|
|
111
106
|
return complete, {"answers": self.answers} if complete else None
|
|
112
107
|
|
|
113
108
|
|
|
109
|
+
def _completed_submission(kind):
|
|
110
|
+
future = asyncio.get_running_loop().create_future()
|
|
111
|
+
future.set_result(None)
|
|
112
|
+
return SubmittedInput(uuid7_string(), kind, future)
|
|
113
|
+
|
|
114
|
+
|
|
114
115
|
def _parse_input(text):
|
|
115
116
|
"""Recognize slash commands, preserving ASCII-space escapes and paths."""
|
|
116
117
|
escaped = text.startswith(" ")
|
|
@@ -122,6 +123,20 @@ def _parse_input(text):
|
|
|
122
123
|
return text, command, parts[1] if len(parts) == 2 else ""
|
|
123
124
|
|
|
124
125
|
|
|
126
|
+
def _parse_retry_argument(argument: "str") -> "typing.Tuple[typing.Optional[RetryCodes], str]":
|
|
127
|
+
if argument == "*":
|
|
128
|
+
return "*", "Retrying all model request errors indefinitely."
|
|
129
|
+
try:
|
|
130
|
+
codes = frozenset(int(part) for part in argument.split("|"))
|
|
131
|
+
except ValueError:
|
|
132
|
+
return None, "Infinite retry disabled."
|
|
133
|
+
if len(codes) == 1:
|
|
134
|
+
code = next(iter(codes))
|
|
135
|
+
return code, "Retrying error code {0} indefinitely.".format(code)
|
|
136
|
+
label = "|".join(str(code) for code in sorted(codes))
|
|
137
|
+
return codes, "Retrying error codes {0} indefinitely.".format(label)
|
|
138
|
+
|
|
139
|
+
|
|
125
140
|
class AgentRuntime:
|
|
126
141
|
"""Session input and scheduling for an Agent whose client implements ModelControl."""
|
|
127
142
|
|
|
@@ -134,7 +149,8 @@ class AgentRuntime:
|
|
|
134
149
|
self._queue_event = None
|
|
135
150
|
self._current_submission: "typing.Union[_QueuedSubmission, None]" = None
|
|
136
151
|
self.event_handler = BASE_EVENT_HANDLER
|
|
137
|
-
self.agent.event_handler = self.
|
|
152
|
+
self.agent.event_handler = self._publish_agent_event
|
|
153
|
+
self.agent.runtime_scope = self._runtime_scope
|
|
138
154
|
self.codex_home = (
|
|
139
155
|
agent.context_manager.config.codex_home or resolve_codex_home()
|
|
140
156
|
)
|
|
@@ -167,9 +183,7 @@ class AgentRuntime:
|
|
|
167
183
|
self._frontends[frontend_id] = event_handler
|
|
168
184
|
if interactive:
|
|
169
185
|
self._interactive_frontends.add(frontend_id)
|
|
170
|
-
self.
|
|
171
|
-
event_handler, SessionStateEvent("attach", self.snapshot())
|
|
172
|
-
)
|
|
186
|
+
EventScope.notify(SessionStateEvent("attach", self.snapshot()), event_handler)
|
|
173
187
|
return frontend_id
|
|
174
188
|
|
|
175
189
|
def detach(self, frontend_id):
|
|
@@ -204,6 +218,7 @@ class AgentRuntime:
|
|
|
204
218
|
"effort",
|
|
205
219
|
"resume",
|
|
206
220
|
"compact",
|
|
221
|
+
"retry",
|
|
207
222
|
)
|
|
208
223
|
+ tuple(self.command_handlers)
|
|
209
224
|
+ ("queue",)
|
|
@@ -261,7 +276,14 @@ class AgentRuntime:
|
|
|
261
276
|
"reasoning_effort": client.reasoning_effort,
|
|
262
277
|
},
|
|
263
278
|
"running": execution.running,
|
|
264
|
-
"active_turn":
|
|
279
|
+
"active_turn": None if active is None else {
|
|
280
|
+
"turn_id": active.turn_id,
|
|
281
|
+
"submission_id": self._current_submission.submission_id
|
|
282
|
+
if self._current_submission is not None else active.turn_id,
|
|
283
|
+
"messages": active.messages,
|
|
284
|
+
"assistant_text": active.assistant_text,
|
|
285
|
+
"model_errors": list(active.model_errors),
|
|
286
|
+
},
|
|
265
287
|
"queued_inputs": [
|
|
266
288
|
{
|
|
267
289
|
"submission_id": item.submission_id,
|
|
@@ -282,11 +304,18 @@ class AgentRuntime:
|
|
|
282
304
|
return await self.agent.model_client.list_models()
|
|
283
305
|
|
|
284
306
|
def publish_update(self, reason):
|
|
307
|
+
if reason != "agents":
|
|
308
|
+
self.agents_manager.notify_parents(self.agent.agent_id)
|
|
285
309
|
self._publish(RuntimeUpdatedEvent(reason))
|
|
286
310
|
|
|
287
311
|
def publish_state(self, reason):
|
|
312
|
+
try:
|
|
313
|
+
state = self.snapshot()
|
|
314
|
+
except (Exception, asyncio.CancelledError) as exc:
|
|
315
|
+
EventScope.report_observer_error("Session state notification failed: " + reason, exc)
|
|
316
|
+
return
|
|
288
317
|
self._recorded_rollout_path = self.agent.recorded_session_file_path
|
|
289
|
-
self._publish(SessionStateEvent(reason,
|
|
318
|
+
self._publish(SessionStateEvent(reason, state))
|
|
290
319
|
|
|
291
320
|
def require_idle(self, operation):
|
|
292
321
|
if self.is_busy:
|
|
@@ -369,20 +398,25 @@ class AgentRuntime:
|
|
|
369
398
|
self.publish_state("admission")
|
|
370
399
|
self._wake_worker()
|
|
371
400
|
|
|
372
|
-
async def submit_input(
|
|
401
|
+
async def submit_input(
|
|
402
|
+
self, text, sender="user", wait_for_command=True, name="user", trigger=True,
|
|
403
|
+
):
|
|
373
404
|
"""Route frontend text to a pending answer, slash command or steer input."""
|
|
405
|
+
if not isinstance(trigger, bool):
|
|
406
|
+
raise ValueError("trigger must be a boolean")
|
|
374
407
|
if not self.agent.accepts_input:
|
|
375
408
|
raise RuntimeError("agent is shutting down")
|
|
409
|
+
if not trigger:
|
|
410
|
+
text = text.strip()
|
|
411
|
+
if text:
|
|
412
|
+
self.message(UserMessage(text, name=name))
|
|
413
|
+
return _completed_submission("message" if text else "empty")
|
|
376
414
|
text, command, argument = _parse_input(text)
|
|
377
415
|
if self._input_request is not None and command is None:
|
|
378
416
|
self._answer_input(text)
|
|
379
|
-
|
|
380
|
-
future.set_result(None)
|
|
381
|
-
return SubmittedInput(uuid7_string(), "answer", future)
|
|
417
|
+
return _completed_submission("answer")
|
|
382
418
|
if not text:
|
|
383
|
-
|
|
384
|
-
future.set_result(None)
|
|
385
|
-
return SubmittedInput(uuid7_string(), "empty", future)
|
|
419
|
+
return _completed_submission("empty")
|
|
386
420
|
if command is None:
|
|
387
421
|
return self._submit_turn(text, "steer", sender, name)
|
|
388
422
|
if command == "/queue":
|
|
@@ -408,33 +442,38 @@ class AgentRuntime:
|
|
|
408
442
|
return receipt
|
|
409
443
|
|
|
410
444
|
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
|
-
|
|
445
|
+
async def execute():
|
|
446
|
+
self._active_commands[receipt.submission_id]["status"] = "running"
|
|
447
|
+
self.agents_manager.mark_used(self.agent.agent_id)
|
|
448
|
+
EventScope.emit(CommandStartedEvent(receipt.submission_id, command, sender))
|
|
449
|
+
return await self._execute_command(command[1:], argument)
|
|
450
|
+
|
|
451
|
+
with EventScope.observe(self._publish):
|
|
452
|
+
try:
|
|
453
|
+
# Retry controls must remain usable while a compact holds the lock.
|
|
454
|
+
if command == "/retry" and argument:
|
|
455
|
+
result = await execute()
|
|
456
|
+
else:
|
|
457
|
+
async with self._get_command_lock():
|
|
458
|
+
result = await execute()
|
|
459
|
+
except asyncio.CancelledError:
|
|
460
|
+
del self._active_commands[receipt.submission_id]
|
|
461
|
+
receipt.future.cancel()
|
|
462
|
+
EventScope.emit(CommandFailedEvent(
|
|
463
|
+
receipt.submission_id, command, "command caller cancelled",
|
|
464
|
+
sender, "CancelledError",
|
|
465
|
+
))
|
|
466
|
+
raise
|
|
467
|
+
except Exception as exc:
|
|
468
|
+
del self._active_commands[receipt.submission_id]
|
|
469
|
+
receipt.future.set_exception(exc)
|
|
470
|
+
EventScope.emit(CommandFailedEvent(
|
|
471
|
+
receipt.submission_id, command, str(exc), sender, type(exc).__name__,
|
|
472
|
+
))
|
|
473
|
+
else:
|
|
474
|
+
del self._active_commands[receipt.submission_id]
|
|
475
|
+
receipt.future.set_result(result)
|
|
476
|
+
EventScope.emit(CommandCompletedEvent(receipt.submission_id, command, result, sender))
|
|
438
477
|
|
|
439
478
|
async def _execute_command(self, command, argument):
|
|
440
479
|
if command in {"help", "history", "compact"} and argument:
|
|
@@ -474,6 +513,31 @@ class AgentRuntime:
|
|
|
474
513
|
effort = client.reasoning_effort
|
|
475
514
|
self.publish_state("effort")
|
|
476
515
|
return {"kind": "effort", "reasoning_effort": effort}
|
|
516
|
+
if command == "retry":
|
|
517
|
+
client = typing.cast(ModelControl, self.agent.model_client)
|
|
518
|
+
if not argument:
|
|
519
|
+
self.require_idle("retry")
|
|
520
|
+
if client.last_error is None:
|
|
521
|
+
raise ValueError("No failed model request to retry.")
|
|
522
|
+
await self.start()
|
|
523
|
+
submission_id, _future = self.trigger()
|
|
524
|
+
return {
|
|
525
|
+
"kind": "retry", "submission_id": submission_id,
|
|
526
|
+
"lines": ["Retrying the failed model request."],
|
|
527
|
+
}
|
|
528
|
+
codes, status = _parse_retry_argument(argument)
|
|
529
|
+
client.set_retry_error_code(codes)
|
|
530
|
+
lines = [status]
|
|
531
|
+
result = {"kind": "retry", "lines": lines}
|
|
532
|
+
if (
|
|
533
|
+
codes is not None and not self.is_busy
|
|
534
|
+
and client.last_error is not None
|
|
535
|
+
and matches_retry_codes(client.last_error, codes)
|
|
536
|
+
):
|
|
537
|
+
await self.start()
|
|
538
|
+
result["submission_id"], _future = self.trigger()
|
|
539
|
+
lines.append("Retrying the failed model request.")
|
|
540
|
+
return result
|
|
477
541
|
if command == "resume":
|
|
478
542
|
if not argument:
|
|
479
543
|
return {
|
|
@@ -514,7 +578,7 @@ class AgentRuntime:
|
|
|
514
578
|
if current is not None:
|
|
515
579
|
self._triggered_submission.turn_id = current.turn_id
|
|
516
580
|
self._publish(
|
|
517
|
-
InputQueuedEvent(submission_id, message, queue, sender, queue == "enqueue", busy)
|
|
581
|
+
InputQueuedEvent(submission_id, message, queue, sender, queue == "enqueue", busy),
|
|
518
582
|
)
|
|
519
583
|
return SubmittedInput(submission_id, "turn", future)
|
|
520
584
|
|
|
@@ -694,6 +758,7 @@ class AgentRuntime:
|
|
|
694
758
|
queued.futures.append(future)
|
|
695
759
|
# Publish after the input layer attaches the execution identity.
|
|
696
760
|
loop.call_soon(self._notify_queue_change)
|
|
761
|
+
loop.call_soon(self._wake_worker)
|
|
697
762
|
return queued.submission_id, future
|
|
698
763
|
|
|
699
764
|
def _notify_queue_change(self):
|
|
@@ -701,7 +766,6 @@ class AgentRuntime:
|
|
|
701
766
|
if self.agent.is_shutdown:
|
|
702
767
|
return
|
|
703
768
|
self.publish_update("queue")
|
|
704
|
-
self._wake_worker()
|
|
705
769
|
|
|
706
770
|
def message(self, text: "typing.Union[str, UserMessage, AgentMessage, ToolResult]") -> "None":
|
|
707
771
|
"""Deliver input to an open runtime's mailbox."""
|
|
@@ -832,81 +896,63 @@ class AgentRuntime:
|
|
|
832
896
|
if not future.done():
|
|
833
897
|
future.set_exception(exc)
|
|
834
898
|
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
899
|
+
@contextmanager
|
|
900
|
+
def _runtime_scope(self, turn_scope, manual=False):
|
|
901
|
+
agent_id = self.agent.agent_id
|
|
902
|
+
self.agents_manager.mark_used(agent_id)
|
|
903
|
+
self._wait_interrupted = False
|
|
904
|
+
if self._input_activity is not None and not self._steer_queue:
|
|
905
|
+
self._input_activity.clear()
|
|
906
|
+
if manual:
|
|
907
|
+
try:
|
|
908
|
+
with turn_scope:
|
|
909
|
+
self.agents_manager.notify_parents(agent_id)
|
|
910
|
+
yield
|
|
911
|
+
finally:
|
|
912
|
+
self.agents_manager.notify_parents(agent_id)
|
|
913
|
+
return
|
|
914
|
+
|
|
915
|
+
self._last_agent_status = "running"
|
|
916
|
+
self._turn_started_at = monotonic()
|
|
917
|
+
self._turn_finished_at = None
|
|
918
|
+
final_answer = None
|
|
919
|
+
try:
|
|
920
|
+
with turn_scope as turn:
|
|
921
|
+
self._active_turn = turn
|
|
922
|
+
turn.deliver_messages = self._deliver_messages
|
|
923
|
+
if not self.title:
|
|
924
|
+
prompt = visible_input_text(turn.messages)
|
|
925
|
+
if prompt:
|
|
926
|
+
self.title = shorten_title(prompt)
|
|
927
|
+
self.publish_state("auto_title")
|
|
928
|
+
self.agents_manager.notify_parents(agent_id)
|
|
929
|
+
yield
|
|
930
|
+
except (TurnInterrupted, ModelRequestInterrupted, asyncio.CancelledError):
|
|
931
|
+
self._last_agent_status = "interrupted"
|
|
932
|
+
raise
|
|
933
|
+
except Exception as exc:
|
|
934
|
+
error = "{0}: {1}".format(type(exc).__name__, exc)
|
|
935
|
+
self._last_agent_status = {"errored": error}
|
|
936
|
+
final_answer = "Agent errored: " + error
|
|
937
|
+
raise
|
|
938
|
+
else:
|
|
939
|
+
self._last_agent_status = {"completed": turn.output_text}
|
|
940
|
+
final_answer = turn.output_text or ""
|
|
941
|
+
finally:
|
|
942
|
+
self._active_turn = None
|
|
840
943
|
self._turn_finished_at = monotonic()
|
|
944
|
+
self.agents_manager.finish_turn(agent_id, final_answer)
|
|
945
|
+
self._wake_worker()
|
|
946
|
+
|
|
947
|
+
@EventScope.router
|
|
948
|
+
def _publish_agent_event(self, event: "Event") -> "None":
|
|
841
949
|
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")
|
|
950
|
+
if isinstance(event, TurnEvent) and queued is not None and event.turn_id == queued.turn_id:
|
|
951
|
+
event = replace(event, submission_id=event.submission_id or queued.submission_id)
|
|
890
952
|
if self.agent.recorded_session_file_path != self._recorded_rollout_path:
|
|
891
953
|
self.publish_state("recording")
|
|
892
954
|
self._publish(event)
|
|
893
955
|
|
|
956
|
+
@EventScope.router
|
|
894
957
|
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
|
-
)
|
|
958
|
+
EventScope.notify(event, self.event_handler, *self._frontends.values())
|
pycodex/tools/__init__.py
CHANGED
|
@@ -110,9 +110,7 @@ def get_tools(
|
|
|
110
110
|
elif tool is exec_command_tool:
|
|
111
111
|
runtime_environment.register_resource(tool.name, unified_exec_manager)
|
|
112
112
|
elif tool is set_period_tool:
|
|
113
|
-
runtime_environment.register_resource(
|
|
114
|
-
"clock", clock_manager, observer=clock_manager.handle_agent_event,
|
|
115
|
-
)
|
|
113
|
+
runtime_environment.register_resource("clock", clock_manager)
|
|
116
114
|
return registry
|
|
117
115
|
|
|
118
116
|
|
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)
|
pycodex/tools/goal_manager.py
CHANGED
|
@@ -3,14 +3,6 @@
|
|
|
3
3
|
import time
|
|
4
4
|
|
|
5
5
|
from ..context import build_goal_message
|
|
6
|
-
from ..events import (
|
|
7
|
-
CompactStartedEvent,
|
|
8
|
-
TerminalEvent,
|
|
9
|
-
TokenCountEvent,
|
|
10
|
-
TurnCompletedEvent,
|
|
11
|
-
TurnInterruptedEvent,
|
|
12
|
-
TurnStartedEvent,
|
|
13
|
-
)
|
|
14
6
|
|
|
15
7
|
|
|
16
8
|
class GoalManager:
|
|
@@ -126,30 +118,31 @@ class GoalManager:
|
|
|
126
118
|
if steer:
|
|
127
119
|
self._budget_message = build_goal_message(goal, budget_limited=True)
|
|
128
120
|
|
|
129
|
-
def
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
self.
|
|
151
|
-
|
|
152
|
-
|
|
121
|
+
def begin_turn(self):
|
|
122
|
+
self.start()
|
|
123
|
+
self._continuation_ready = False
|
|
124
|
+
self._count_tokens = self._goal is not None and self._goal["status"] == "active"
|
|
125
|
+
|
|
126
|
+
def record_usage(self, usage):
|
|
127
|
+
if self._count_tokens:
|
|
128
|
+
cached = usage.get("input_tokens_details", {}).get("cached_tokens", 0)
|
|
129
|
+
self._pending_tokens += (
|
|
130
|
+
max(0, usage.get("input_tokens", 0) - cached)
|
|
131
|
+
+ max(0, usage.get("output_tokens", 0))
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def finish_turn(self, interrupted):
|
|
135
|
+
self.account(steer=False)
|
|
136
|
+
self._count_tokens = False
|
|
137
|
+
if self._goal is not None:
|
|
138
|
+
if interrupted and self._goal["status"] == "active":
|
|
139
|
+
self._goal["status"] = "paused"
|
|
140
|
+
self._goal["updatedAt"] = int(time.time())
|
|
141
|
+
if self._goal["status"] != "active":
|
|
142
|
+
self._last_accounted_at = None
|
|
143
|
+
|
|
144
|
+
def schedule_continuation(self):
|
|
145
|
+
self._continuation_ready = self._goal is not None and self._goal["status"] == "active"
|
|
153
146
|
|
|
154
147
|
def follow_up_messages(self):
|
|
155
148
|
message, self._budget_message = self._budget_message, None
|