python-codex 0.5.2__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 (71) 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 +13 -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 +370 -226
  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 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +2 -181
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  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 +122 -450
  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 +26 -35
  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 +78 -36
  52. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/METADATA +117 -27
  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.2.dist-info/RECORD +0 -90
  69. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
  70. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
  71. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
pycodex/tools/__init__.py CHANGED
@@ -4,20 +4,30 @@ This package groups the local tool abstractions and concrete tool
4
4
  implementations that back `pycodex`.
5
5
  """
6
6
 
7
+ import typing
8
+
9
+ from ..protocol import qualified_tool_name
7
10
  from .apply_patch_tool import ApplyPatchTool
8
11
  from .base_tool import BaseTool, Registry, ToolContext, ToolRegistry
9
- from .clock_tool import ClockManager, ClockTool
10
- from .close_agent_tool import CloseAgentTool
12
+ from .clock_manager import ClockManager
13
+ from .clock_tool import ClockTool
11
14
  from .code_mode_manager import CodeModeManager
12
15
  from .exec_command_tool import ExecCommandTool
13
16
  from .exec_tool import ExecTool
17
+ from .followup_task_tool import FollowupTaskTool
18
+ from .goal_tool import CreateGoalTool, GetGoalTool, UpdateGoalTool
14
19
  from .grep_files_tool import GrepFilesTool
20
+ from .interrupt_agent_tool import InterruptAgentTool
21
+ from .list_agents_tool import ListAgentsTool
15
22
  from .list_dir_tool import ListDirTool
16
23
  from .read_file_tool import ReadFileTool
17
24
  from .request_permissions_tool import RequestPermissionsTool
18
25
  from .request_user_input_tool import RequestUserInputTool
19
- from .resume_agent_tool import ResumeAgentTool
20
- from .send_input_tool import SendInputTool
26
+ from .runtime_services import (
27
+ AgentRuntimeEnvironment,
28
+ create_agent_runtime_environment,
29
+ )
30
+ from .send_message_tool import SendMessageTool
21
31
  from .shell_command_tool import ShellCommandTool
22
32
  from .shell_tool import ShellTool
23
33
  from .spawn_agent_tool import SpawnAgentTool
@@ -29,29 +39,112 @@ from .wait_tool import WaitTool
29
39
  from .web_search_tool import WebSearchTool
30
40
  from .write_stdin_tool import WriteStdinTool
31
41
 
42
+ if typing.TYPE_CHECKING:
43
+ from ..multi_agents import AgentsManager
44
+
45
+
46
+ def get_tools(
47
+ agents_manager: "AgentsManager",
48
+ runtime_environment: "typing.Union[AgentRuntimeEnvironment, None]" = None,
49
+ toolset: "typing.Union[typing.Iterable[str], None]" = None,
50
+ ) -> "ToolRegistry":
51
+ runtime_environment = runtime_environment or create_agent_runtime_environment()
52
+ registry = Registry(runtime_environment)
53
+ code_mode_manager = CodeModeManager(registry)
54
+ unified_exec_manager = UnifiedExecManager()
55
+ clock_manager = runtime_environment.clock_manager
56
+ exec_tool = ExecTool(code_mode_manager)
57
+ wait_tool = WaitTool(code_mode_manager)
58
+ goal_tools = (
59
+ CreateGoalTool(runtime_environment.goal_manager),
60
+ GetGoalTool(runtime_environment.goal_manager),
61
+ UpdateGoalTool(runtime_environment.goal_manager),
62
+ )
63
+ request_user_input_tool = RequestUserInputTool()
64
+ agent_tools = (
65
+ SpawnAgentTool(agents_manager),
66
+ SendMessageTool(agents_manager),
67
+ FollowupTaskTool(agents_manager),
68
+ WaitAgentTool(agents_manager),
69
+ InterruptAgentTool(agents_manager),
70
+ ListAgentsTool(agents_manager),
71
+ )
72
+ apply_patch_tool = ApplyPatchTool()
73
+ exec_command_tool = ExecCommandTool(unified_exec_manager)
74
+ write_stdin_tool = WriteStdinTool(unified_exec_manager)
75
+ clock_tool = ClockTool(clock_manager)
76
+ view_image_tool = ViewImageTool()
77
+ tools = (
78
+ exec_tool,
79
+ wait_tool,
80
+ exec_command_tool,
81
+ write_stdin_tool,
82
+ clock_tool,
83
+ request_user_input_tool,
84
+ apply_patch_tool,
85
+ view_image_tool,
86
+ ) + goal_tools + agent_tools
87
+ if toolset is not None:
88
+ available_tools = {
89
+ name: tool for tool in tools
90
+ for name in (tool.name, qualified_tool_name(tool.name, tool.namespace))
91
+ }
92
+ toolset = tuple(toolset)
93
+ unknown_tools = set(toolset) - set(available_tools)
94
+ if unknown_tools:
95
+ raise ValueError(
96
+ "unknown toolset entries: {0}".format(", ".join(sorted(unknown_tools)))
97
+ )
98
+ tools = tuple(available_tools[name] for name in toolset)
99
+ if tools:
100
+ tools = (exec_tool, wait_tool) + tuple(
101
+ tool for tool in tools if tool not in (exec_tool, wait_tool)
102
+ )
103
+ for tool in tools:
104
+ registry.register(tool)
105
+ for tool in registry.tools():
106
+ if tool is exec_tool:
107
+ runtime_environment.register_resource(
108
+ tool.name, code_mode_manager,
109
+ restart=code_mode_manager.restart, close=code_mode_manager.close,
110
+ )
111
+ elif tool is exec_command_tool:
112
+ runtime_environment.register_resource(tool.name, unified_exec_manager)
113
+ elif tool is clock_tool:
114
+ runtime_environment.register_resource(
115
+ tool.name, clock_manager, observer=clock_manager.handle_agent_event,
116
+ )
117
+ return registry
118
+
119
+
32
120
  __all__ = [
33
121
  "ApplyPatchTool",
34
122
  "BaseTool",
35
123
  "ClockManager",
36
124
  "ClockTool",
37
- "CloseAgentTool",
38
125
  "CodeModeManager",
126
+ "CreateGoalTool",
39
127
  "ExecTool",
128
+ "FollowupTaskTool",
129
+ "get_tools",
130
+ "GetGoalTool",
40
131
  "ExecCommandTool",
41
132
  "GrepFilesTool",
133
+ "InterruptAgentTool",
134
+ "ListAgentsTool",
42
135
  "ListDirTool",
43
136
  "ReadFileTool",
44
137
  "Registry",
45
138
  "RequestPermissionsTool",
46
139
  "RequestUserInputTool",
47
- "ResumeAgentTool",
48
- "SendInputTool",
140
+ "SendMessageTool",
49
141
  "ShellCommandTool",
50
142
  "ShellTool",
51
143
  "SpawnAgentTool",
52
144
  "ToolContext",
53
145
  "ToolRegistry",
54
146
  "UnifiedExecManager",
147
+ "UpdateGoalTool",
55
148
  "UpdatePlanTool",
56
149
  "ViewImageTool",
57
150
  "WaitAgentTool",
@@ -1,43 +1,5 @@
1
1
  """Shared schemas for Codex-aligned collaboration tools."""
2
2
 
3
- COLLAB_INPUT_ITEMS_SCHEMA = {
4
- "type": "array",
5
- "description": (
6
- "Structured input items. Use this to pass explicit mentions (for "
7
- "example app:// connector paths)."
8
- ),
9
- "items": {
10
- "type": "object",
11
- "properties": {
12
- "type": {
13
- "type": "string",
14
- "description": "Input item type: text, image, local_image, skill, or mention.",
15
- },
16
- "text": {
17
- "type": "string",
18
- "description": "Text content when type is text.",
19
- },
20
- "image_url": {
21
- "type": "string",
22
- "description": "Image URL when type is image.",
23
- },
24
- "path": {
25
- "type": "string",
26
- "description": (
27
- "Path when type is local_image/skill, or structured mention target "
28
- "such as app://<connector-id> or plugin://<plugin-name>@<marketplace-name> "
29
- "when type is mention."
30
- ),
31
- },
32
- "name": {
33
- "type": "string",
34
- "description": "Display name when type is skill or mention.",
35
- },
36
- },
37
- "additionalProperties": False,
38
- },
39
- }
40
-
41
3
  AGENT_STATUS_SCHEMA = {
42
4
  "oneOf": [
43
5
  {
@@ -5,10 +5,8 @@ Original Codex mapping:
5
5
 
6
6
  Expected behavior:
7
7
  - Accept the same freeform patch envelope used by Codex main.
8
- - Verify the whole patch before mutating the filesystem so failed patches do not
9
- leave partial edits behind.
10
- - Apply add/delete/update/move operations inside the workspace and return the
11
- same success/error text shape Codex expects.
8
+ - Verify patch contents before writing files.
9
+ - Apply add/delete/update/move operations and return structured results for exec.
12
10
  """
13
11
 
14
12
  import typing
@@ -18,7 +16,7 @@ from pathlib import Path
18
16
  from loguru import logger
19
17
 
20
18
  from ..protocol import JSONValue
21
- from .base_tool import BaseTool, ToolContext
19
+ from .base_tool import BaseTool, StructuredToolOutput, ToolContext
22
20
 
23
21
  APPLY_PATCH_LARK_GRAMMAR = """start: begin_patch hunk+ end_patch
24
22
  begin_patch: \"*** Begin Patch\" LF
@@ -81,7 +79,7 @@ class _UpdateFileOp:
81
79
  class ApplyPatchTool(BaseTool):
82
80
  name = "apply_patch"
83
81
  description = (
84
- "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, "
82
+ "The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, "
85
83
  "so do not wrap the patch in JSON."
86
84
  )
87
85
  tool_type = "custom"
@@ -92,27 +90,33 @@ class ApplyPatchTool(BaseTool):
92
90
  }
93
91
  supports_parallel = False
94
92
 
95
- async def run(self, context: "ToolContext", args: "JSONValue") -> "JSONValue":
93
+ async def run(self, context: "ToolContext", args: "JSONValue") -> "typing.Union[JSONValue, StructuredToolOutput]":
96
94
  cwd = context.cwd
97
- patch_text = str(args)
95
+ if not isinstance(args, str):
96
+ raise ValueError("apply_patch expects patch text as a string")
97
+ patch_text = args
98
98
  logger.debug(
99
99
  "apply_patch workspace={} bytes={}", cwd, len(patch_text)
100
100
  )
101
101
  try:
102
102
  operations = self._parse_patch(patch_text)
103
- return self._format_result(self._apply_operations(operations, cwd), exit_code=0)
103
+ self._apply_operations(operations, cwd)
104
+ return {}
104
105
  except ApplyPatchError as exc:
105
- return self._format_result(str(exc), exit_code=1)
106
+ return StructuredToolOutput(str(exc), success=False)
106
107
 
107
108
  def _parse_patch(
108
109
  self, patch_text: "str"
109
110
  ) -> "typing.List[typing.Union[typing.Union[_AddFileOp, _DeleteFileOp], _UpdateFileOp]]":
110
- lines = patch_text.splitlines()
111
+ lines = patch_text.strip().splitlines()
111
112
  if not lines:
112
113
  raise ApplyPatchError("patch rejected: empty patch")
114
+ lines[0] = lines[0].strip()
115
+ lines[-1] = lines[-1].strip()
113
116
  if lines[0] != "*** Begin Patch":
114
117
  raise ApplyPatchError(
115
- "apply_patch verification failed: missing '*** Begin Patch' header"
118
+ "apply_patch verification failed: invalid patch: "
119
+ "The first line of the patch must be '*** Begin Patch'"
116
120
  )
117
121
 
118
122
  operations: "typing.List[typing.Union[typing.Union[_AddFileOp, _DeleteFileOp], _UpdateFileOp]]" = ([])
@@ -235,22 +239,19 @@ class ApplyPatchTool(BaseTool):
235
239
  self,
236
240
  operations: "typing.List[typing.Union[typing.Union[_AddFileOp, _DeleteFileOp], _UpdateFileOp]]",
237
241
  cwd: "Path",
238
- ) -> "str":
242
+ ) -> "None":
239
243
  preview: "typing.Dict[Path, typing.Union[str, None]]" = {}
240
- summaries: "typing.Dict[Path, str]" = {}
241
244
 
242
245
  for operation in operations:
243
246
  if isinstance(operation, _AddFileOp):
244
247
  path = self._resolve_workspace_path(operation.path, cwd)
245
248
  preview[path] = operation.content
246
- summaries[path] = "A"
247
249
  continue
248
250
 
249
251
  if isinstance(operation, _DeleteFileOp):
250
252
  path = self._resolve_workspace_path(operation.path, cwd)
251
253
  self._read_preview_file(path, preview, cwd)
252
254
  preview[path] = None
253
- summaries[path] = "D"
254
255
  continue
255
256
 
256
257
  path = self._resolve_workspace_path(operation.path, cwd)
@@ -260,12 +261,9 @@ class ApplyPatchTool(BaseTool):
260
261
  if operation.move_to is not None:
261
262
  destination = self._resolve_workspace_path(operation.move_to, cwd)
262
263
  preview[path] = None
263
- summaries.pop(path, None)
264
264
  preview[destination] = updated
265
- summaries[destination] = "M"
266
265
 
267
266
  self._write_preview(preview)
268
- return self._format_success(summaries, cwd)
269
267
 
270
268
  def _read_preview_file(
271
269
  self, path: "Path", preview: "typing.Dict[Path, typing.Union[str, None]]",
@@ -348,21 +346,6 @@ class ApplyPatchTool(BaseTool):
348
346
  path.parent.mkdir(parents=True, exist_ok=True)
349
347
  path.write_text(content, encoding="utf-8")
350
348
 
351
- def _format_success(self, summaries: "typing.Dict[Path, str]", cwd: "Path") -> "str":
352
- buckets = {"A": [], "M": [], "D": []}
353
- for path, status in summaries.items():
354
- buckets[status].append(self._display_path(path, cwd))
355
- lines = ["Success:"]
356
- for status in ("A", "M", "D"):
357
- for rel_path in sorted(buckets[status]):
358
- lines.append(f"{status} {rel_path}")
359
- return " ".join(lines) + "\n"
360
-
361
- def _format_result(self, output: "str", exit_code: "int") -> "str":
362
- return (
363
- f"Exit code: {exit_code}\n" "Wall time: 0 seconds\n" "Output:\n" f"{output}"
364
- )
365
-
366
349
  def _resolve_workspace_path(self, path_text: "str", cwd: "Path") -> "Path":
367
350
  path = Path(path_text).expanduser()
368
351
  resolved = path if path.is_absolute() else cwd / path
@@ -15,10 +15,9 @@ import json
15
15
  import traceback
16
16
  import typing
17
17
  from abc import ABC, abstractmethod
18
- from dataclasses import dataclass
18
+ from dataclasses import dataclass, replace
19
19
  from pathlib import Path
20
20
 
21
- from ..events import Event
22
21
  from ..protocol import (
23
22
  ConversationItem,
24
23
  JSONDict,
@@ -27,12 +26,11 @@ from ..protocol import (
27
26
  ToolResult,
28
27
  ToolSpec,
29
28
  UserMessage,
29
+ qualified_tool_name,
30
30
  )
31
31
  from ..utils import get_debug_dir
32
32
  from .runtime_services import AgentRuntimeEnvironment
33
-
34
- if typing.TYPE_CHECKING:
35
- from ..agent import Agent
33
+ from .python_tool_schema import python_tool_identifier
36
34
 
37
35
 
38
36
  @dataclass(
@@ -42,6 +40,10 @@ class ToolContext:
42
40
  turn_id: "str"
43
41
  history: "typing.Tuple[ConversationItem, ...]"
44
42
  cwd: "Path"
43
+ agent_id: "typing.Union[str, None]" = None
44
+ encrypted_messages: "bool" = True
45
+ call_id: "typing.Union[str, None]" = None
46
+ session_id: "typing.Union[str, None]" = None
45
47
 
46
48
  def resolve_path(self, path=None) -> "Path":
47
49
  return (self.cwd / Path("." if path is None else path).expanduser()).resolve()
@@ -62,6 +64,9 @@ class StructuredToolOutput:
62
64
  class BaseTool(ABC):
63
65
  name: "str"
64
66
  description: "str"
67
+ namespace: "typing.Union[str, None]" = None
68
+ namespace_description: "str" = ""
69
+ exec_only: "bool" = True
65
70
  input_schema: "typing.Union[JSONDict, None]" = None
66
71
  tool_type: "str" = "function"
67
72
  format: "typing.Union[JSONDict, None]" = None
@@ -79,6 +84,8 @@ class BaseTool(ABC):
79
84
  options=self.options,
80
85
  output_schema=self.output_schema,
81
86
  supports_parallel=self.supports_parallel,
87
+ namespace=self.namespace,
88
+ namespace_description=self.namespace_description,
82
89
  )
83
90
 
84
91
  def serialize(self) -> "JSONDict":
@@ -95,24 +102,6 @@ class BaseTool(ABC):
95
102
  ) -> "typing.Tuple[UserMessage, ...]":
96
103
  return ()
97
104
 
98
- def bind_agent(self, agent: "Agent") -> "None":
99
- pass
100
-
101
- def handle_agent_event(self, event: "Event") -> "None":
102
- pass
103
-
104
- def shutdown(self) -> "None":
105
- pass
106
-
107
- def background_work_count(self, after_reply: "bool") -> "int":
108
- return 0
109
-
110
- def background_work_snapshot(self) -> "typing.List[JSONDict]":
111
- return []
112
-
113
- def set_state_listener(self, listener) -> "None":
114
- pass
115
-
116
105
 
117
106
  class ToolRegistry:
118
107
  def __init__(
@@ -122,10 +111,44 @@ class ToolRegistry:
122
111
  self.runtime_environment = runtime_environment or AgentRuntimeEnvironment()
123
112
 
124
113
  def register(self, tool: "BaseTool") -> "None":
125
- self._tools[tool.name] = tool
126
-
127
- def model_visible_specs(self) -> "typing.List[ToolSpec]":
128
- return [tool.spec() for tool in self._tools.values()]
114
+ if "." in tool.name:
115
+ raise ValueError("tool names must not contain '.'")
116
+ self._tools[qualified_tool_name(tool.name, tool.namespace)] = tool
117
+
118
+ def model_visible_specs(self, code_mode_only: "bool" = False) -> "typing.List[ToolSpec]":
119
+ if not code_mode_only:
120
+ return [
121
+ tool.spec() for name, tool in self._tools.items()
122
+ if name not in ("exec", "wait")
123
+ ]
124
+ direct_tools = {
125
+ name: tool for name, tool in self._tools.items() if not tool.exec_only
126
+ }
127
+ if len(direct_tools) != len(self._tools):
128
+ if not {"exec", "wait"}.issubset(direct_tools):
129
+ raise ValueError("CodeModeOnly requires registered exec and wait tools")
130
+ return [tool.spec() for tool in direct_tools.values()]
131
+
132
+ def exec_tools(self) -> "typing.List[JSONDict]":
133
+ enabled = []
134
+ identifiers = set()
135
+ for tool_name, tool in self._tools.items():
136
+ if not tool.exec_only and tool.namespace != "collaboration":
137
+ continue
138
+ if tool.tool_type not in {"function", "custom"}:
139
+ continue
140
+ namespace, name = python_tool_identifier(tool.name, tool.namespace)
141
+ identifier = namespace + "." + name
142
+ if identifier in identifiers:
143
+ raise ValueError("duplicate exec tool identifier: " + identifier)
144
+ identifiers.add(identifier)
145
+ enabled.append({
146
+ "tool_name": tool_name, "namespace": namespace, "name": name,
147
+ "description": tool.description, "tool_type": tool.tool_type,
148
+ "parameters": tool.input_schema, "output_schema": tool.output_schema,
149
+ "format": tool.format,
150
+ })
151
+ return sorted(enabled, key=lambda item: (item["namespace"], item["name"]))
129
152
 
130
153
  def supports_parallel(self, tool_name: "str") -> "bool":
131
154
  tool = self._tools.get(tool_name)
@@ -134,6 +157,7 @@ class ToolRegistry:
134
157
  async def execute(self, call: "ToolCall", context: "ToolContext") -> "ToolResult":
135
158
  tool = self._tools.get(call.name)
136
159
  if tool is None:
160
+ self.runtime_environment.tool_completed()
137
161
  return ToolResult(
138
162
  call_id=call.call_id,
139
163
  name=call.name,
@@ -143,21 +167,23 @@ class ToolRegistry:
143
167
  )
144
168
 
145
169
  try:
146
- output = await tool.run(context, call.arguments)
170
+ output = await tool.run(
171
+ replace(context, call_id=call.call_id),
172
+ call.arguments,
173
+ )
174
+ metadata = {}
147
175
  if isinstance(output, StructuredToolOutput):
148
- return ToolResult(
149
- call_id=call.call_id,
150
- name=call.name,
151
- output=output.output,
152
- content_items=output.content_items,
153
- success=output.success,
154
- tool_type=call.tool_type,
176
+ metadata = dict(
177
+ content_items=output.content_items, success=output.success,
178
+ is_error=output.success is False,
155
179
  )
180
+ output = output.output
156
181
  return ToolResult(
157
182
  call_id=call.call_id,
158
183
  name=call.name,
159
184
  output=output,
160
185
  tool_type=call.tool_type,
186
+ **metadata,
161
187
  )
162
188
  except asyncio.CancelledError:
163
189
  raise
@@ -186,6 +212,8 @@ class ToolRegistry:
186
212
  is_error=True,
187
213
  tool_type=call.tool_type,
188
214
  )
215
+ finally:
216
+ self.runtime_environment.tool_completed()
189
217
 
190
218
  def follow_up_messages(
191
219
  self, results: "typing.Iterable[ToolResult]"
@@ -0,0 +1,182 @@
1
+ """Session-scoped periodic clock and its restorable configuration."""
2
+
3
+ import asyncio
4
+ import math
5
+ import typing
6
+ from datetime import datetime, timedelta
7
+
8
+ from ..events import CompactCompletedEvent, CompactStartedEvent, TurnCompletedEvent, TurnStartedEvent
9
+ from ..protocol import JSONDict
10
+
11
+
12
+ def _current_time() -> "str":
13
+ return datetime.now().astimezone().isoformat(timespec="seconds")
14
+
15
+
16
+ class ClockManager:
17
+ def __init__(self, seconds_per_minute: "float" = 60.0) -> "None":
18
+ self._seconds_per_minute = seconds_per_minute
19
+ self._period_m: "typing.Union[float, None]" = None
20
+ self._timer_task: "typing.Union[asyncio.Task, None]" = None
21
+ self._generation = 0
22
+ self._next_fire_at = None
23
+ self._state_listener = None
24
+ self._notify_hook: "typing.Union[typing.Callable[[typing.Dict[str, object]], typing.Awaitable[typing.Any]], None]" = (None)
25
+
26
+ def bind(self, invoke, output, state_changed):
27
+ self._notify_hook = invoke
28
+ self._state_listener = state_changed
29
+
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
+ def background_work_count(self, after_reply):
37
+ return int(self.enabled if after_reply else self.armed)
38
+
39
+ def set_state_listener(self, listener):
40
+ self._state_listener = listener
41
+
42
+ def _state_changed(self):
43
+ if self._state_listener is not None:
44
+ self._state_listener()
45
+
46
+ def background_work_snapshot(self):
47
+ return [dict(
48
+ self.snapshot(),
49
+ kind="clock",
50
+ next_fire_at=self._next_fire_at,
51
+ status=(
52
+ "armed" if self._next_fire_at is not None
53
+ else "paused" if self.enabled else "disabled"
54
+ ),
55
+ )]
56
+
57
+ @staticmethod
58
+ def _parse_period(value):
59
+ if value is None:
60
+ return None
61
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
62
+ raise ValueError("period_m must be a positive finite number or null")
63
+ period_m = float(value)
64
+ if not math.isfinite(period_m) or period_m <= 0:
65
+ raise ValueError("period_m must be a positive finite number or null")
66
+ return period_m
67
+
68
+ def set_period(self, value: "object") -> "JSONDict":
69
+ period_m = self._parse_period(value)
70
+ self._cancel_pending()
71
+ self._period_m = period_m
72
+ self._state_changed()
73
+ return self.snapshot()
74
+
75
+ def dump_state(self):
76
+ return {"period_m": self._period_m}
77
+
78
+ def validate_state(self, state):
79
+ self._parse_period(state["period_m"])
80
+
81
+ def restore_state(self, state):
82
+ period_m = self._parse_period(state["period_m"])
83
+ self._cancel_pending()
84
+ self._period_m = period_m
85
+
86
+ def snapshot(self) -> "JSONDict":
87
+ return {
88
+ "enabled": self.enabled,
89
+ "period_m": self._period_m,
90
+ }
91
+
92
+ @property
93
+ def enabled(self) -> "bool":
94
+ return self._period_m is not None
95
+
96
+ @property
97
+ def armed(self) -> "bool":
98
+ return self._next_fire_at is not None
99
+
100
+ def turn_started(self) -> "None":
101
+ self._cancel_pending()
102
+ self._state_changed()
103
+
104
+ def arm_after_reply(self) -> "None":
105
+ self._cancel_pending()
106
+ period_m = self._period_m
107
+ if period_m is None or self._notify_hook is None:
108
+ self._state_changed()
109
+ return
110
+ generation = self._generation
111
+ self._next_fire_at = (
112
+ datetime.now().astimezone()
113
+ + timedelta(seconds=period_m * self._seconds_per_minute)
114
+ ).isoformat()
115
+ self._timer_task = asyncio.create_task(
116
+ self._wait_and_notify(generation, period_m)
117
+ )
118
+ self._timer_task.add_done_callback(
119
+ lambda task: None if task.cancelled() else task.exception()
120
+ )
121
+ self._state_changed()
122
+
123
+ def cancel(self) -> "None":
124
+ self.set_period(None)
125
+
126
+ def shutdown(self) -> "None":
127
+ self._cancel_pending()
128
+ self._notify_hook = None
129
+ self._state_changed()
130
+
131
+ def _cancel_pending(self) -> "None":
132
+ self._generation += 1
133
+ task = self._timer_task
134
+ self._timer_task = None
135
+ self._next_fire_at = None
136
+ if task is not None and not task.done():
137
+ task.cancel()
138
+
139
+ async def _wait_and_notify(self, generation: "int", period_m: "float") -> "None":
140
+ from ..runtime import SubmissionInterrupted
141
+
142
+ try:
143
+ await asyncio.sleep(period_m * self._seconds_per_minute)
144
+ except asyncio.CancelledError:
145
+ return
146
+ if generation != self._generation or period_m != self._period_m:
147
+ return
148
+
149
+ self._timer_task = None
150
+ self._next_fire_at = None
151
+ self._state_changed()
152
+ callback = self._notify_hook
153
+ if callback is None:
154
+ return
155
+ try:
156
+ started = await callback(
157
+ {
158
+ "type": "clock_tick",
159
+ "period_m": period_m,
160
+ "current_time": _current_time(),
161
+ }
162
+ )
163
+ except SubmissionInterrupted:
164
+ # The next successful reply will arm the clock after a steer.
165
+ return
166
+ except asyncio.CancelledError:
167
+ raise
168
+ except Exception as exc:
169
+ asyncio.get_running_loop().call_exception_handler(
170
+ {
171
+ "message": "Clock notification failed",
172
+ "exception": exc,
173
+ }
174
+ )
175
+ return
176
+
177
+ if (
178
+ not started
179
+ and generation == self._generation
180
+ and period_m == self._period_m
181
+ ):
182
+ self.arm_after_reply()