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.
- pycodex/__init__.py +18 -8
- pycodex/agent.py +89 -74
- pycodex/bootstrap.py +27 -239
- pycodex/cli.py +19 -14
- pycodex/config.py +36 -0
- pycodex/context.py +369 -51
- pycodex/events.py +13 -186
- pycodex/model.py +181 -88
- 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 +1069 -140
- pycodex/protocol.py +78 -15
- pycodex/runtime.py +370 -226
- pycodex/tools/__init__.py +100 -7
- 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 +2 -181
- pycodex/tools/code_mode_manager.py +165 -246
- pycodex/tools/exec_command_tool.py +0 -18
- pycodex/tools/exec_runtime.py +381 -0
- pycodex/tools/exec_tool.py +78 -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/request_user_input_tool.py +3 -23
- 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 +2 -2
- pycodex/utils/doctor.py +5 -4
- pycodex/utils/event_helpers.py +143 -13
- pycodex/utils/history.py +33 -0
- pycodex/utils/session_persist.py +78 -36
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/METADATA +117 -27
- python_codex-0.6.0.dist-info/RECORD +106 -0
- responses_server/__init__.py +2 -0
- responses_server/app.py +7 -6
- responses_server/config.py +0 -11
- responses_server/payload_processors.py +4 -4
- responses_server/request_translation.py +480 -0
- responses_server/server.py +31 -24
- responses_server/stream_events.py +124 -0
- responses_server/stream_router.py +33 -830
- responses_server/tools/custom_adapter.py +29 -29
- responses_server/transport.py +332 -0
- pycodex/tools/close_agent_tool.py +0 -60
- pycodex/tools/exec_runtime.js +0 -161
- pycodex/tools/resume_agent_tool.py +0 -54
- pycodex/tools/send_input_tool.py +0 -110
- python_codex-0.5.2.dist-info/RECORD +0 -90
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""In-process Python cells with expression display and asyncio task ownership."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import asyncio
|
|
5
|
+
import base64
|
|
6
|
+
import builtins
|
|
7
|
+
from copy import deepcopy
|
|
8
|
+
import inspect
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import tokenize
|
|
13
|
+
import traceback
|
|
14
|
+
from types import SimpleNamespace
|
|
15
|
+
import wave
|
|
16
|
+
|
|
17
|
+
from .python_tool_schema import python_tool_signature
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CellTaskFactory:
|
|
21
|
+
"""Track descendants of cell tasks without owning the host's tool tasks.
|
|
22
|
+
|
|
23
|
+
One factory serves the active cells on an event loop. The previous factory
|
|
24
|
+
is restored after the last cell has cleaned up; no process-global state or
|
|
25
|
+
changes to the asyncio module are needed.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, loop, previous):
|
|
29
|
+
self._loop = loop
|
|
30
|
+
self._previous = previous
|
|
31
|
+
self._owners = {}
|
|
32
|
+
self._users = 0
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def acquire(cls, loop):
|
|
36
|
+
factory = loop.get_task_factory()
|
|
37
|
+
if not isinstance(factory, cls):
|
|
38
|
+
factory = cls(loop, factory)
|
|
39
|
+
loop.set_task_factory(factory)
|
|
40
|
+
factory._users += 1
|
|
41
|
+
return factory
|
|
42
|
+
|
|
43
|
+
def release(self):
|
|
44
|
+
self._users -= 1
|
|
45
|
+
if self._users == 0 and self._loop.get_task_factory() is self:
|
|
46
|
+
self._loop.set_task_factory(self._previous)
|
|
47
|
+
|
|
48
|
+
def __call__(self, loop, coroutine, **kwargs):
|
|
49
|
+
owner = self._owners.get(asyncio.current_task(loop=loop))
|
|
50
|
+
return self.create_task(coroutine, owner, **kwargs)
|
|
51
|
+
|
|
52
|
+
def create_task(self, coroutine, owner=None, **kwargs):
|
|
53
|
+
if self._previous is None:
|
|
54
|
+
task = asyncio.Task(coroutine, loop=self._loop, **kwargs)
|
|
55
|
+
else:
|
|
56
|
+
task = self._previous(self._loop, coroutine, **kwargs)
|
|
57
|
+
if owner is not None:
|
|
58
|
+
self._owners[task] = owner
|
|
59
|
+
owner._tasks.add(task)
|
|
60
|
+
task.add_done_callback(self._forget)
|
|
61
|
+
return task
|
|
62
|
+
|
|
63
|
+
def _forget(self, task):
|
|
64
|
+
self._owners.pop(task, None)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ExecExit(BaseException):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class TextWriter:
|
|
72
|
+
def __init__(self, emit):
|
|
73
|
+
self._emit = emit
|
|
74
|
+
self._buffer = ""
|
|
75
|
+
|
|
76
|
+
def write(self, value):
|
|
77
|
+
self._buffer += value
|
|
78
|
+
while "\n" in self._buffer:
|
|
79
|
+
line, self._buffer = self._buffer.split("\n", 1)
|
|
80
|
+
self._emit(line)
|
|
81
|
+
return len(value)
|
|
82
|
+
|
|
83
|
+
def flush(self):
|
|
84
|
+
if self._buffer:
|
|
85
|
+
self._emit(self._buffer)
|
|
86
|
+
self._buffer = ""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class ExecRuntime:
|
|
90
|
+
def __init__(self, source, tools, stored_values, cwd, emit, invoke_tool):
|
|
91
|
+
self._loop = asyncio.get_running_loop()
|
|
92
|
+
self._source = source
|
|
93
|
+
self._values = stored_values
|
|
94
|
+
self._tool_specs = tools
|
|
95
|
+
self._cwd = cwd
|
|
96
|
+
self._emit = emit
|
|
97
|
+
self._invoke_tool = invoke_tool
|
|
98
|
+
self._writer = TextWriter(self.text)
|
|
99
|
+
self._next_request_id = 0
|
|
100
|
+
self._tasks = set()
|
|
101
|
+
self._tool_tasks = []
|
|
102
|
+
self._timers = set()
|
|
103
|
+
self._factory = None
|
|
104
|
+
self._main_task = None
|
|
105
|
+
self._background_error = None
|
|
106
|
+
self._exited = False
|
|
107
|
+
self._stop_requested = False
|
|
108
|
+
self._closing = False
|
|
109
|
+
|
|
110
|
+
def send(self, message):
|
|
111
|
+
self._emit(message)
|
|
112
|
+
|
|
113
|
+
def request_stop(self):
|
|
114
|
+
if not self._stop_requested:
|
|
115
|
+
self._stop_requested = True
|
|
116
|
+
if self._main_task is not None and not self._main_task.done():
|
|
117
|
+
self._main_task.cancel()
|
|
118
|
+
|
|
119
|
+
def print(self, *values, **kwargs):
|
|
120
|
+
if kwargs.get("file") is None:
|
|
121
|
+
kwargs["file"] = self._writer
|
|
122
|
+
builtins.print(*values, **kwargs)
|
|
123
|
+
|
|
124
|
+
def content(self, item):
|
|
125
|
+
self.send({"type": "content", "item": item})
|
|
126
|
+
|
|
127
|
+
def text(self, value):
|
|
128
|
+
text = value if isinstance(value, str) else json.dumps(
|
|
129
|
+
value, ensure_ascii=False, allow_nan=False,
|
|
130
|
+
)
|
|
131
|
+
self.content({"type": "input_text", "text": text})
|
|
132
|
+
|
|
133
|
+
def notify(self, value):
|
|
134
|
+
text = value if isinstance(value, str) else json.dumps(
|
|
135
|
+
value, ensure_ascii=False, allow_nan=False,
|
|
136
|
+
)
|
|
137
|
+
self.send({"type": "notify", "text": text})
|
|
138
|
+
|
|
139
|
+
def image(self, value, detail=...):
|
|
140
|
+
url, item = self._media_url(value, "image")
|
|
141
|
+
if detail is ...:
|
|
142
|
+
detail = item.get("detail", item.get("_meta", {}).get("codex/imageDetail"))
|
|
143
|
+
if detail not in (None, "auto", "low", "high", "original"):
|
|
144
|
+
raise ValueError("unsupported image detail")
|
|
145
|
+
output = {"type": "input_image", "image_url": url}
|
|
146
|
+
if detail is not None:
|
|
147
|
+
output["detail"] = detail
|
|
148
|
+
self.content(output)
|
|
149
|
+
|
|
150
|
+
def audio(self, value):
|
|
151
|
+
url, _item = self._media_url(value, "audio")
|
|
152
|
+
mime_type, encoded = url[5:].split(";base64,", 1)
|
|
153
|
+
if mime_type in ("audio/wav", "audio/x-wav"):
|
|
154
|
+
with wave.open(io.BytesIO(base64.b64decode(encoded)), "rb") as clip:
|
|
155
|
+
if clip.getnframes() / clip.getframerate() < 0.025:
|
|
156
|
+
self.text(
|
|
157
|
+
"Audio output omitted because the clip is shorter than "
|
|
158
|
+
"25 ms; use a longer clip."
|
|
159
|
+
)
|
|
160
|
+
return
|
|
161
|
+
self.content({"type": "input_audio", "audio_url": url})
|
|
162
|
+
|
|
163
|
+
def generated_image(self, result):
|
|
164
|
+
self.image(result["image_url"])
|
|
165
|
+
if "output_hint" in result:
|
|
166
|
+
if not isinstance(result["output_hint"], str):
|
|
167
|
+
raise TypeError("output_hint must be a string")
|
|
168
|
+
self.text(result["output_hint"])
|
|
169
|
+
|
|
170
|
+
def _media_url(self, value, kind):
|
|
171
|
+
item = {}
|
|
172
|
+
if isinstance(value, str):
|
|
173
|
+
url = value
|
|
174
|
+
elif isinstance(value, dict):
|
|
175
|
+
item = value
|
|
176
|
+
if value.get("type") == kind:
|
|
177
|
+
url = "data:{0};base64,{1}".format(value["mimeType"], value["data"])
|
|
178
|
+
else:
|
|
179
|
+
url = value[kind + "_url"]
|
|
180
|
+
else:
|
|
181
|
+
raise TypeError(kind + " expects a data URL or an individual media object")
|
|
182
|
+
if not isinstance(url, str) or not url.startswith("data:" + kind + "/"):
|
|
183
|
+
raise ValueError(kind + " expects a base64 data URL")
|
|
184
|
+
_header, encoded = url.split(";base64,", 1)
|
|
185
|
+
if not encoded:
|
|
186
|
+
raise ValueError(kind + " data must not be empty")
|
|
187
|
+
base64.b64decode(encoded, validate=True)
|
|
188
|
+
return url, item
|
|
189
|
+
|
|
190
|
+
def store(self, key, value):
|
|
191
|
+
if not isinstance(key, str):
|
|
192
|
+
raise TypeError("store key must be a string")
|
|
193
|
+
self._values[key] = json.loads(json.dumps(value, allow_nan=False))
|
|
194
|
+
|
|
195
|
+
def load(self, key):
|
|
196
|
+
if not isinstance(key, str):
|
|
197
|
+
raise TypeError("load key must be a string")
|
|
198
|
+
return deepcopy(self._values.get(key))
|
|
199
|
+
|
|
200
|
+
def exit(self):
|
|
201
|
+
raise ExecExit()
|
|
202
|
+
|
|
203
|
+
async def yield_control(self):
|
|
204
|
+
self.send({"type": "yield"})
|
|
205
|
+
await asyncio.sleep(0)
|
|
206
|
+
|
|
207
|
+
def set_timeout(self, callback, delay_ms=0):
|
|
208
|
+
if self._stop_requested or self._closing:
|
|
209
|
+
raise RuntimeError("exec cell is stopping")
|
|
210
|
+
if not callable(callback):
|
|
211
|
+
raise TypeError("set_timeout expects a callable")
|
|
212
|
+
if (
|
|
213
|
+
isinstance(delay_ms, bool) or not isinstance(delay_ms, (int, float))
|
|
214
|
+
or not math.isfinite(delay_ms) or delay_ms < 0
|
|
215
|
+
):
|
|
216
|
+
raise ValueError("delay_ms must be a finite non-negative number")
|
|
217
|
+
|
|
218
|
+
async def invoke():
|
|
219
|
+
try:
|
|
220
|
+
result = callback()
|
|
221
|
+
if inspect.isawaitable(result):
|
|
222
|
+
await result
|
|
223
|
+
except asyncio.CancelledError:
|
|
224
|
+
raise
|
|
225
|
+
except BaseException as error:
|
|
226
|
+
# Catch control-flow exceptions before they reach asyncio.Task.
|
|
227
|
+
if isinstance(error, ExecExit):
|
|
228
|
+
self._exited = True
|
|
229
|
+
else:
|
|
230
|
+
self._background_error = "".join(traceback.format_exception(
|
|
231
|
+
type(error), error, error.__traceback__,
|
|
232
|
+
))
|
|
233
|
+
self._main_task.cancel()
|
|
234
|
+
|
|
235
|
+
def fire():
|
|
236
|
+
self._timers.discard(handle)
|
|
237
|
+
self._factory.create_task(invoke(), self)
|
|
238
|
+
|
|
239
|
+
handle = self._loop.call_later(delay_ms / 1000.0, fire)
|
|
240
|
+
self._timers.add(handle)
|
|
241
|
+
return handle
|
|
242
|
+
|
|
243
|
+
def clear_timeout(self, handle=None):
|
|
244
|
+
if handle is not None:
|
|
245
|
+
handle.cancel()
|
|
246
|
+
self._timers.discard(handle)
|
|
247
|
+
|
|
248
|
+
def _tool_caller(self, spec):
|
|
249
|
+
signature = python_tool_signature(spec)
|
|
250
|
+
|
|
251
|
+
def call(*args, **kwargs):
|
|
252
|
+
arguments = dict(signature.bind(*args, **kwargs).arguments)
|
|
253
|
+
if spec["tool_type"] == "custom":
|
|
254
|
+
arguments = arguments["input"]
|
|
255
|
+
if not isinstance(arguments, str):
|
|
256
|
+
raise TypeError(spec["name"] + " expects one source string")
|
|
257
|
+
return self._call_tool(spec, arguments)
|
|
258
|
+
call.__name__ = spec["name"]
|
|
259
|
+
call.__signature__ = signature
|
|
260
|
+
return call
|
|
261
|
+
|
|
262
|
+
async def _call_tool(self, spec, arguments):
|
|
263
|
+
if self._stop_requested or self._closing:
|
|
264
|
+
raise RuntimeError("exec cell is stopping")
|
|
265
|
+
self._next_request_id += 1
|
|
266
|
+
request_id = str(self._next_request_id)
|
|
267
|
+
task = self._factory.create_task(self._invoke_tool(
|
|
268
|
+
spec, request_id, deepcopy(arguments),
|
|
269
|
+
))
|
|
270
|
+
self._tool_tasks.append(task)
|
|
271
|
+
# Once issued, host tool calls finish even if the cell is cancelled.
|
|
272
|
+
return deepcopy(await asyncio.shield(task))
|
|
273
|
+
|
|
274
|
+
def _compile_source(self):
|
|
275
|
+
source = self._source.replace("\r\n", "\n").replace("\r", "\n")
|
|
276
|
+
string_lines = set()
|
|
277
|
+
for token in tokenize.generate_tokens(io.StringIO(source).readline):
|
|
278
|
+
if tokenize.tok_name[token.type] in ("STRING", "FSTRING_MIDDLE", "TSTRING_MIDDLE"):
|
|
279
|
+
string_lines.update(range(token.start[0], token.end[0]))
|
|
280
|
+
# Indent code into an async body without changing multiline string contents.
|
|
281
|
+
source = "async def __exec_cell__():\n" + "\n".join(
|
|
282
|
+
line if index in string_lines else " " + line
|
|
283
|
+
for index, line in enumerate(source.split("\n"))
|
|
284
|
+
) + "\n pass\n"
|
|
285
|
+
tree = ast.parse(source, filename="<exec>")
|
|
286
|
+
body = tree.body[0].body
|
|
287
|
+
# The trailing pass keeps comment-only cells valid.
|
|
288
|
+
if len(body) > 1 and isinstance(body[-2], ast.Expr):
|
|
289
|
+
expression = body[-2]
|
|
290
|
+
body[-2] = ast.copy_location(ast.Return(value=expression.value), expression)
|
|
291
|
+
for statement in body:
|
|
292
|
+
ast.increment_lineno(statement, -1)
|
|
293
|
+
return compile(tree, "<exec>", "exec")
|
|
294
|
+
|
|
295
|
+
async def run(self):
|
|
296
|
+
if self._stop_requested:
|
|
297
|
+
return None
|
|
298
|
+
tool_namespaces = {
|
|
299
|
+
"tools": SimpleNamespace(), "collaboration": SimpleNamespace(),
|
|
300
|
+
}
|
|
301
|
+
for spec in self._tool_specs:
|
|
302
|
+
setattr(
|
|
303
|
+
tool_namespaces[spec["namespace"]], spec["name"], self._tool_caller(spec),
|
|
304
|
+
)
|
|
305
|
+
namespace = {
|
|
306
|
+
"__name__": "__codex_exec__",
|
|
307
|
+
"__builtins__": dict(vars(builtins), print=self.print),
|
|
308
|
+
"cwd": self._cwd,
|
|
309
|
+
"asyncio": asyncio,
|
|
310
|
+
"text": self.text, "image": self.image, "audio": self.audio,
|
|
311
|
+
"generated_image": self.generated_image,
|
|
312
|
+
"store": self.store, "load": self.load, "notify": self.notify,
|
|
313
|
+
"set_timeout": self.set_timeout, "clear_timeout": self.clear_timeout,
|
|
314
|
+
"exit": self.exit, "yield_control": self.yield_control,
|
|
315
|
+
"ALL_TOOLS": tuple(
|
|
316
|
+
{
|
|
317
|
+
"name": spec["namespace"] + "." + spec["name"],
|
|
318
|
+
"description": spec["description"],
|
|
319
|
+
}
|
|
320
|
+
for spec in self._tool_specs
|
|
321
|
+
),
|
|
322
|
+
}
|
|
323
|
+
namespace.update(tool_namespaces)
|
|
324
|
+
error_text = None
|
|
325
|
+
self._factory = CellTaskFactory.acquire(self._loop)
|
|
326
|
+
try:
|
|
327
|
+
self._main_task = self._factory.create_task(
|
|
328
|
+
self._execute(namespace), self,
|
|
329
|
+
)
|
|
330
|
+
try:
|
|
331
|
+
error_text = await self._main_task
|
|
332
|
+
except asyncio.CancelledError:
|
|
333
|
+
if not self._stop_requested and not self._exited:
|
|
334
|
+
error_text = self._background_error or "exec cell was cancelled"
|
|
335
|
+
finally:
|
|
336
|
+
self._closing = True
|
|
337
|
+
try:
|
|
338
|
+
for handle in self._timers:
|
|
339
|
+
handle.cancel()
|
|
340
|
+
self._timers.clear()
|
|
341
|
+
# A cancelled task's finally block can create another task.
|
|
342
|
+
while True:
|
|
343
|
+
pending = [task for task in self._tasks if not task.done()]
|
|
344
|
+
if not pending:
|
|
345
|
+
break
|
|
346
|
+
for task in pending:
|
|
347
|
+
task.cancel()
|
|
348
|
+
outcomes = await asyncio.gather(*pending, return_exceptions=True)
|
|
349
|
+
for outcome in outcomes:
|
|
350
|
+
if (
|
|
351
|
+
isinstance(outcome, BaseException)
|
|
352
|
+
and not isinstance(outcome, (asyncio.CancelledError, ExecExit))
|
|
353
|
+
and error_text is None
|
|
354
|
+
):
|
|
355
|
+
error_text = "".join(traceback.format_exception(
|
|
356
|
+
type(outcome), outcome, outcome.__traceback__,
|
|
357
|
+
))
|
|
358
|
+
await asyncio.gather(*self._tool_tasks, return_exceptions=True)
|
|
359
|
+
self._writer.flush()
|
|
360
|
+
finally:
|
|
361
|
+
self._tasks.clear()
|
|
362
|
+
self._tool_tasks.clear()
|
|
363
|
+
self._factory.release()
|
|
364
|
+
return error_text or self._background_error
|
|
365
|
+
|
|
366
|
+
async def _execute(self, namespace):
|
|
367
|
+
try:
|
|
368
|
+
exec(self._compile_source(), namespace)
|
|
369
|
+
result = await namespace.pop("__exec_cell__")()
|
|
370
|
+
if result is not None:
|
|
371
|
+
output = repr(result)
|
|
372
|
+
self._writer.flush()
|
|
373
|
+
self.text(output)
|
|
374
|
+
except ExecExit:
|
|
375
|
+
return None
|
|
376
|
+
except asyncio.CancelledError:
|
|
377
|
+
raise
|
|
378
|
+
except BaseException:
|
|
379
|
+
# User code (including sys.exit()) must report through its cell.
|
|
380
|
+
return traceback.format_exc()
|
|
381
|
+
return None
|
pycodex/tools/exec_tool.py
CHANGED
|
@@ -1,15 +1,6 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Python implementation of the CodeModeOnly `exec` entrypoint."""
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
- Corresponds to the original Codex code-mode `exec` tool.
|
|
5
|
-
|
|
6
|
-
Expected behavior:
|
|
7
|
-
- Accept raw JavaScript source text as a freeform/custom tool payload.
|
|
8
|
-
- Run the script inside a background exec cell with helper functions and nested
|
|
9
|
-
tool access.
|
|
10
|
-
- Return either a completed result or a running `cell_id` status that can be
|
|
11
|
-
resumed via `wait`.
|
|
12
|
-
"""
|
|
3
|
+
from dataclasses import replace
|
|
13
4
|
|
|
14
5
|
from ..protocol import JSONValue
|
|
15
6
|
from .base_tool import BaseTool, ToolContext
|
|
@@ -19,7 +10,7 @@ EXEC_FREEFORM_GRAMMAR = r"""start: pragma_source | plain_source
|
|
|
19
10
|
pragma_source: PRAGMA_LINE NEWLINE SOURCE
|
|
20
11
|
plain_source: SOURCE
|
|
21
12
|
|
|
22
|
-
PRAGMA_LINE: /[ \t]
|
|
13
|
+
PRAGMA_LINE: /[ \t]*# @exec:[^\r\n]*/
|
|
23
14
|
NEWLINE: /\r?\n/
|
|
24
15
|
SOURCE: /[\s\S]+/
|
|
25
16
|
"""
|
|
@@ -27,25 +18,73 @@ SOURCE: /[\s\S]+/
|
|
|
27
18
|
|
|
28
19
|
class ExecTool(BaseTool):
|
|
29
20
|
name = "exec"
|
|
21
|
+
exec_only = False
|
|
30
22
|
description = (
|
|
31
|
-
"Run
|
|
32
|
-
"-
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"-
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
23
|
+
"Run Python code to orchestrate and compose tool calls.\n"
|
|
24
|
+
"- Submit raw Python source with top-level `await`; the runner executes "
|
|
25
|
+
"it in the host process with a fresh namespace for each cell. "
|
|
26
|
+
"Imports and helper definitions are allowed. "
|
|
27
|
+
"Do not wrap the source in a main function, JSON, or Markdown.\n"
|
|
28
|
+
"- The final top-level expression is displayed with `repr()` unless its "
|
|
29
|
+
"value is None. Assignment-only cells do not display a value. "
|
|
30
|
+
"`print()` and `text()` remain available for explicit output.\n"
|
|
31
|
+
"- To run a shell command, submit Python such as "
|
|
32
|
+
'`await tools.exec_command(cmd="git status --short")`.\n'
|
|
33
|
+
"- Call ordinary nested tools through `tools.<name>(...)` and agent "
|
|
34
|
+
"tools through `collaboration.<name>(...)` inside this Python source. "
|
|
35
|
+
"Collaboration tools also remain available as direct tool calls. "
|
|
36
|
+
"Both namespaces are listed below. Follow the Python signatures: use "
|
|
37
|
+
"positional or keyword arguments, and `**arguments` to unpack a dict. "
|
|
38
|
+
"Freeform tools accept one string, either "
|
|
39
|
+
"positionally or with `input=...`.\n"
|
|
40
|
+
"- Tool calls are asynchronous: use `await tools.exec_command(cmd=\"pwd\")`. "
|
|
41
|
+
"Use `await asyncio.gather(...)` for independent calls, or "
|
|
42
|
+
"`await asyncio.gather(..., return_exceptions=True)` to inspect every "
|
|
43
|
+
"success and failure. Keep dependent operations sequential.\n"
|
|
44
|
+
"- `asyncio` and the Python standard library are available. Tasks created "
|
|
45
|
+
"through asyncio from cell tasks, and timers created with `set_timeout`, "
|
|
46
|
+
"are cleaned up when the script finishes. Already issued host tool calls "
|
|
47
|
+
"finish before the cell is closed.\n"
|
|
48
|
+
"- Execution and stopping are cooperative. Use async operations and run "
|
|
49
|
+
"blocking work through tools.exec_command. Synchronous code blocks the host; "
|
|
50
|
+
"a non-yielding loop cannot be stopped independently. Imported modules and "
|
|
51
|
+
"process state are shared.\n"
|
|
52
|
+
"- `cwd` is the cell's workspace Path; use `cwd / \"file\"` for direct file "
|
|
53
|
+
"access. Nested tools use that workspace. The host's working directory "
|
|
54
|
+
"and sys.stdout are not changed. Plain `print()` writes to this cell; "
|
|
55
|
+
"output from imported modules is not captured.\n"
|
|
56
|
+
"- Optional first line: "
|
|
57
|
+
'`# @exec: {"yield_time_ms": 30000, "max_output_tokens": 1000}`. '
|
|
58
|
+
"The defaults are 30000 ms and 10000 tokens. A running script returns a "
|
|
59
|
+
"cell_id; use wait for subsequent output.\n"
|
|
60
|
+
"\n"
|
|
61
|
+
"Global helpers:\n"
|
|
62
|
+
"- `text(value)`: append text; non-string values use JSON encoding. "
|
|
63
|
+
"Use `text()` or `print()` for explicit output.\n"
|
|
64
|
+
"- `image(value, detail=...)`: append a base64 data-URL image, an object "
|
|
65
|
+
"with image_url/detail, or an individual MCP image block. An explicit "
|
|
66
|
+
"detail overrides the object's detail or codex/imageDetail metadata.\n"
|
|
67
|
+
"- `audio(value)`: append a base64 data-URL audio item, an object with "
|
|
68
|
+
"audio_url, or an individual MCP audio block.\n"
|
|
69
|
+
"- `generated_image(result)`: append the generated image_url and optional "
|
|
70
|
+
"output_hint. The URL must be a base64 data URL.\n"
|
|
71
|
+
"- `store(key, value)` / `load(key)`: save and retrieve JSON-serializable "
|
|
72
|
+
"values across exec cells in this session; a missing key returns None.\n"
|
|
73
|
+
"- `notify(value)`: immediately submit an additional output for this exec "
|
|
74
|
+
"call through the attached Runtime.\n"
|
|
75
|
+
"- `set_timeout(callback, delay_ms=0)` / `clear_timeout(handle)`: schedule "
|
|
76
|
+
"or cancel a callback; timers alone do not keep the script alive. Use "
|
|
77
|
+
"`await asyncio.sleep(seconds)` to wait.\n"
|
|
78
|
+
"- `await yield_control()`: return accumulated output to the model while "
|
|
79
|
+
"the script continues running.\n"
|
|
80
|
+
"- `exit()`: finish the current script successfully.\n"
|
|
81
|
+
"- `ALL_TOOLS`: the available nested tools as qualified name/description records.\n"
|
|
82
|
+
"\n"
|
|
83
|
+
"Example:\n"
|
|
84
|
+
"```python\n"
|
|
85
|
+
"result = await tools.exec_command(cmd=\"pwd\")\n"
|
|
86
|
+
"result\n"
|
|
87
|
+
"```"
|
|
49
88
|
)
|
|
50
89
|
tool_type = "custom"
|
|
51
90
|
format = {
|
|
@@ -58,5 +97,13 @@ class ExecTool(BaseTool):
|
|
|
58
97
|
def __init__(self, manager: "CodeModeManager") -> "None":
|
|
59
98
|
self._manager = manager
|
|
60
99
|
|
|
100
|
+
def spec(self):
|
|
101
|
+
return replace(
|
|
102
|
+
super().spec(),
|
|
103
|
+
description=self.description + self._manager.describe_tools(),
|
|
104
|
+
)
|
|
105
|
+
|
|
61
106
|
async def run(self, context: "ToolContext", args: "JSONValue") -> "JSONValue":
|
|
62
|
-
|
|
107
|
+
if not isinstance(args, str):
|
|
108
|
+
raise ValueError("exec expects Python source text")
|
|
109
|
+
return await self._manager.exec(args, context)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Deliver a MultiAgentV2 task, starting an idle recipient when necessary."""
|
|
2
|
+
|
|
3
|
+
from .base_tool import BaseTool
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FollowupTaskTool(BaseTool):
|
|
7
|
+
name = "followup_task"
|
|
8
|
+
namespace = "collaboration"
|
|
9
|
+
namespace_description = "Tools for spawning and managing sub-agents."
|
|
10
|
+
exec_only = False
|
|
11
|
+
description = (
|
|
12
|
+
"Send a follow-up task to an existing non-root target agent and trigger "
|
|
13
|
+
"a turn if it is idle. If the target is already running, deliver the task "
|
|
14
|
+
"promptly at message boundaries while sampling, or after the pending "
|
|
15
|
+
"tool call completes."
|
|
16
|
+
)
|
|
17
|
+
input_schema = {
|
|
18
|
+
"type": "object",
|
|
19
|
+
"properties": {
|
|
20
|
+
"target": {
|
|
21
|
+
"type": "string",
|
|
22
|
+
"description": "Agent id or canonical task name to send a follow-up task to (from spawn_agent).",
|
|
23
|
+
},
|
|
24
|
+
"message": {
|
|
25
|
+
"type": "string",
|
|
26
|
+
"encrypted": True,
|
|
27
|
+
"description": "Message text to send to the target agent.",
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
"required": ["target", "message"],
|
|
31
|
+
"additionalProperties": False,
|
|
32
|
+
}
|
|
33
|
+
supports_parallel = False
|
|
34
|
+
|
|
35
|
+
def __init__(self, agents_manager):
|
|
36
|
+
self._agents_manager = agents_manager
|
|
37
|
+
|
|
38
|
+
async def run(self, context, args):
|
|
39
|
+
if set(args) != {"target", "message"}:
|
|
40
|
+
raise ValueError("expected target and message")
|
|
41
|
+
return await self._agents_manager.send_message(
|
|
42
|
+
context.agent_id, args["target"], args["message"], trigger_turn=True,
|
|
43
|
+
encrypted=context.encrypted_messages,
|
|
44
|
+
)
|