python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycodex/__init__.py +22 -12
- pycodex/agent.py +89 -74
- pycodex/bootstrap.py +37 -251
- pycodex/cli.py +19 -28
- pycodex/config.py +36 -0
- pycodex/context.py +368 -51
- pycodex/events.py +14 -187
- pycodex/model.py +197 -95
- pycodex/multi_agents.py +401 -0
- pycodex/portable/__init__.py +8 -6
- pycodex/portable/client.py +24 -39
- pycodex/portable/protocol.py +28 -0
- pycodex/portable/server.py +3 -3
- pycodex/prompts/developer_messages.json +13 -0
- pycodex/prompts/goals/budget_limit.md +19 -0
- pycodex/prompts/goals/continuation.md +56 -0
- pycodex/prompts/models.json +1143 -200
- pycodex/protocol.py +81 -15
- pycodex/runtime.py +370 -226
- pycodex/tools/__init__.py +102 -10
- pycodex/tools/agent_tool_schemas.py +0 -38
- pycodex/tools/apply_patch_tool.py +17 -34
- pycodex/tools/base_tool.py +63 -35
- pycodex/tools/clock_manager.py +182 -0
- pycodex/tools/clock_tool.py +58 -187
- pycodex/tools/code_mode_manager.py +165 -246
- pycodex/tools/exec_command_tool.py +0 -18
- pycodex/tools/exec_runtime.py +332 -0
- pycodex/tools/exec_tool.py +74 -31
- pycodex/tools/followup_task_tool.py +44 -0
- pycodex/tools/goal_manager.py +205 -0
- pycodex/tools/goal_tool.py +126 -0
- pycodex/tools/interrupt_agent_tool.py +48 -0
- pycodex/tools/list_agents_tool.py +66 -0
- pycodex/tools/python_tool_schema.py +141 -0
- pycodex/tools/request_permissions_tool.py +1 -0
- pycodex/tools/runtime_services.py +122 -450
- pycodex/tools/send_message_tool.py +42 -0
- pycodex/tools/spawn_agent_tool.py +55 -94
- pycodex/tools/unified_exec_manager.py +26 -35
- pycodex/tools/wait_agent_tool.py +46 -66
- pycodex/tools/wait_tool.py +24 -13
- pycodex/tools/web_search_tool.py +1 -0
- pycodex/utils/codex_config.py +105 -0
- pycodex/utils/compactor.py +4 -0
- pycodex/utils/compat.py +43 -2
- pycodex/utils/doctor.py +5 -4
- pycodex/utils/dotenv.py +0 -7
- pycodex/utils/event_helpers.py +143 -13
- pycodex/utils/history.py +59 -0
- pycodex/utils/session_persist.py +104 -48
- python_codex-0.6.1.dist-info/METADATA +201 -0
- python_codex-0.6.1.dist-info/RECORD +106 -0
- responses_server/__init__.py +2 -0
- responses_server/app.py +10 -7
- responses_server/config.py +6 -12
- responses_server/gemini_api.py +333 -0
- responses_server/messages_api.py +9 -1
- responses_server/payload_processors.py +4 -4
- responses_server/request_translation.py +486 -0
- responses_server/server.py +31 -24
- responses_server/stream_events.py +124 -0
- responses_server/stream_router.py +48 -830
- responses_server/tools/custom_adapter.py +29 -29
- responses_server/tools/web_search.py +3 -0
- responses_server/transport.py +388 -0
- pycodex/tools/close_agent_tool.py +0 -60
- pycodex/tools/exec_runtime.js +0 -161
- pycodex/tools/request_user_input_tool.py +0 -102
- pycodex/tools/resume_agent_tool.py +0 -54
- pycodex/tools/send_input_tool.py +0 -110
- python_codex-0.5.2.dist-info/METADATA +0 -262
- python_codex-0.5.2.dist-info/RECORD +0 -90
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
pycodex/tools/__init__.py
CHANGED
|
@@ -4,20 +4,29 @@ 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 .
|
|
10
|
-
from .
|
|
12
|
+
from .clock_manager import ClockManager
|
|
13
|
+
from .clock_tool import SetPeriodTool, SleepTool
|
|
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
|
-
from .
|
|
19
|
-
|
|
20
|
-
|
|
25
|
+
from .runtime_services import (
|
|
26
|
+
AgentRuntimeEnvironment,
|
|
27
|
+
create_agent_runtime_environment,
|
|
28
|
+
)
|
|
29
|
+
from .send_message_tool import SendMessageTool
|
|
21
30
|
from .shell_command_tool import ShellCommandTool
|
|
22
31
|
from .shell_tool import ShellTool
|
|
23
32
|
from .spawn_agent_tool import SpawnAgentTool
|
|
@@ -29,29 +38,112 @@ from .wait_tool import WaitTool
|
|
|
29
38
|
from .web_search_tool import WebSearchTool
|
|
30
39
|
from .write_stdin_tool import WriteStdinTool
|
|
31
40
|
|
|
41
|
+
if typing.TYPE_CHECKING:
|
|
42
|
+
from ..multi_agents import AgentsManager
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_tools(
|
|
46
|
+
agents_manager: "AgentsManager",
|
|
47
|
+
runtime_environment: "typing.Union[AgentRuntimeEnvironment, None]" = None,
|
|
48
|
+
toolset: "typing.Union[typing.Iterable[str], None]" = None,
|
|
49
|
+
) -> "ToolRegistry":
|
|
50
|
+
runtime_environment = runtime_environment or create_agent_runtime_environment()
|
|
51
|
+
registry = Registry(runtime_environment)
|
|
52
|
+
code_mode_manager = CodeModeManager(registry)
|
|
53
|
+
unified_exec_manager = UnifiedExecManager()
|
|
54
|
+
clock_manager = runtime_environment.clock_manager
|
|
55
|
+
exec_tool = ExecTool(code_mode_manager)
|
|
56
|
+
wait_tool = WaitTool(code_mode_manager)
|
|
57
|
+
goal_tools = (
|
|
58
|
+
CreateGoalTool(runtime_environment.goal_manager),
|
|
59
|
+
GetGoalTool(runtime_environment.goal_manager),
|
|
60
|
+
UpdateGoalTool(runtime_environment.goal_manager),
|
|
61
|
+
)
|
|
62
|
+
agent_tools = (
|
|
63
|
+
SpawnAgentTool(agents_manager),
|
|
64
|
+
SendMessageTool(agents_manager),
|
|
65
|
+
FollowupTaskTool(agents_manager),
|
|
66
|
+
WaitAgentTool(agents_manager),
|
|
67
|
+
InterruptAgentTool(agents_manager),
|
|
68
|
+
ListAgentsTool(agents_manager),
|
|
69
|
+
)
|
|
70
|
+
apply_patch_tool = ApplyPatchTool()
|
|
71
|
+
exec_command_tool = ExecCommandTool(unified_exec_manager)
|
|
72
|
+
write_stdin_tool = WriteStdinTool(unified_exec_manager)
|
|
73
|
+
set_period_tool = SetPeriodTool(clock_manager)
|
|
74
|
+
sleep_tool = SleepTool(agents_manager)
|
|
75
|
+
view_image_tool = ViewImageTool()
|
|
76
|
+
tools = (
|
|
77
|
+
exec_tool,
|
|
78
|
+
wait_tool,
|
|
79
|
+
exec_command_tool,
|
|
80
|
+
write_stdin_tool,
|
|
81
|
+
set_period_tool,
|
|
82
|
+
sleep_tool,
|
|
83
|
+
apply_patch_tool,
|
|
84
|
+
view_image_tool,
|
|
85
|
+
) + goal_tools + agent_tools
|
|
86
|
+
if toolset is not None:
|
|
87
|
+
available_tools = {
|
|
88
|
+
name: tool for tool in tools
|
|
89
|
+
for name in (tool.name, qualified_tool_name(tool.name, tool.namespace))
|
|
90
|
+
}
|
|
91
|
+
toolset = tuple(toolset)
|
|
92
|
+
unknown_tools = set(toolset) - set(available_tools)
|
|
93
|
+
if unknown_tools:
|
|
94
|
+
raise ValueError(
|
|
95
|
+
"unknown toolset entries: {0}".format(", ".join(sorted(unknown_tools)))
|
|
96
|
+
)
|
|
97
|
+
tools = tuple(available_tools[name] for name in toolset)
|
|
98
|
+
if tools:
|
|
99
|
+
tools = (exec_tool, wait_tool) + tuple(
|
|
100
|
+
tool for tool in tools if tool not in (exec_tool, wait_tool)
|
|
101
|
+
)
|
|
102
|
+
for tool in tools:
|
|
103
|
+
registry.register(tool)
|
|
104
|
+
for tool in registry.tools():
|
|
105
|
+
if tool is exec_tool:
|
|
106
|
+
runtime_environment.register_resource(
|
|
107
|
+
tool.name, code_mode_manager,
|
|
108
|
+
restart=code_mode_manager.restart, close=code_mode_manager.close,
|
|
109
|
+
)
|
|
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
|
+
runtime_environment.register_resource(
|
|
114
|
+
"clock", clock_manager, observer=clock_manager.handle_agent_event,
|
|
115
|
+
)
|
|
116
|
+
return registry
|
|
117
|
+
|
|
118
|
+
|
|
32
119
|
__all__ = [
|
|
33
120
|
"ApplyPatchTool",
|
|
34
121
|
"BaseTool",
|
|
35
122
|
"ClockManager",
|
|
36
|
-
"ClockTool",
|
|
37
|
-
"CloseAgentTool",
|
|
38
123
|
"CodeModeManager",
|
|
124
|
+
"CreateGoalTool",
|
|
39
125
|
"ExecTool",
|
|
126
|
+
"FollowupTaskTool",
|
|
127
|
+
"get_tools",
|
|
128
|
+
"GetGoalTool",
|
|
40
129
|
"ExecCommandTool",
|
|
41
130
|
"GrepFilesTool",
|
|
131
|
+
"InterruptAgentTool",
|
|
132
|
+
"ListAgentsTool",
|
|
42
133
|
"ListDirTool",
|
|
43
134
|
"ReadFileTool",
|
|
44
135
|
"Registry",
|
|
45
136
|
"RequestPermissionsTool",
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"SendInputTool",
|
|
137
|
+
"SendMessageTool",
|
|
138
|
+
"SetPeriodTool",
|
|
49
139
|
"ShellCommandTool",
|
|
50
140
|
"ShellTool",
|
|
141
|
+
"SleepTool",
|
|
51
142
|
"SpawnAgentTool",
|
|
52
143
|
"ToolContext",
|
|
53
144
|
"ToolRegistry",
|
|
54
145
|
"UnifiedExecManager",
|
|
146
|
+
"UpdateGoalTool",
|
|
55
147
|
"UpdatePlanTool",
|
|
56
148
|
"ViewImageTool",
|
|
57
149
|
"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
|
|
9
|
-
|
|
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
|
-
"
|
|
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
|
-
|
|
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
|
-
|
|
103
|
+
self._apply_operations(operations, cwd)
|
|
104
|
+
return {}
|
|
104
105
|
except ApplyPatchError as exc:
|
|
105
|
-
return
|
|
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:
|
|
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
|
-
) -> "
|
|
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
|
pycodex/tools/base_tool.py
CHANGED
|
@@ -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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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(
|
|
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
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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()
|