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.
Files changed (76) hide show
  1. pycodex/__init__.py +22 -12
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +37 -251
  4. pycodex/cli.py +19 -28
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +368 -51
  7. pycodex/events.py +14 -187
  8. pycodex/model.py +197 -95
  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 +1143 -200
  18. pycodex/protocol.py +81 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +102 -10
  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 +58 -187
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +332 -0
  29. pycodex/tools/exec_tool.py +74 -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/runtime_services.py +122 -450
  38. pycodex/tools/send_message_tool.py +42 -0
  39. pycodex/tools/spawn_agent_tool.py +55 -94
  40. pycodex/tools/unified_exec_manager.py +26 -35
  41. pycodex/tools/wait_agent_tool.py +46 -66
  42. pycodex/tools/wait_tool.py +24 -13
  43. pycodex/tools/web_search_tool.py +1 -0
  44. pycodex/utils/codex_config.py +105 -0
  45. pycodex/utils/compactor.py +4 -0
  46. pycodex/utils/compat.py +43 -2
  47. pycodex/utils/doctor.py +5 -4
  48. pycodex/utils/dotenv.py +0 -7
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +59 -0
  51. pycodex/utils/session_persist.py +104 -48
  52. python_codex-0.6.1.dist-info/METADATA +201 -0
  53. python_codex-0.6.1.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +10 -7
  56. responses_server/config.py +6 -12
  57. responses_server/gemini_api.py +333 -0
  58. responses_server/messages_api.py +9 -1
  59. responses_server/payload_processors.py +4 -4
  60. responses_server/request_translation.py +486 -0
  61. responses_server/server.py +31 -24
  62. responses_server/stream_events.py +124 -0
  63. responses_server/stream_router.py +48 -830
  64. responses_server/tools/custom_adapter.py +29 -29
  65. responses_server/tools/web_search.py +3 -0
  66. responses_server/transport.py +388 -0
  67. pycodex/tools/close_agent_tool.py +0 -60
  68. pycodex/tools/exec_runtime.js +0 -161
  69. pycodex/tools/request_user_input_tool.py +0 -102
  70. pycodex/tools/resume_agent_tool.py +0 -54
  71. pycodex/tools/send_input_tool.py +0 -110
  72. python_codex-0.5.2.dist-info/METADATA +0 -262
  73. python_codex-0.5.2.dist-info/RECORD +0 -90
  74. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
  75. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
  76. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
@@ -1,6 +1,5 @@
1
1
  import json
2
2
  import typing
3
- from copy import deepcopy
4
3
 
5
4
 
6
5
  class CustomToolAdapterError(ValueError):
@@ -153,38 +152,36 @@ def build_output_item(
153
152
  name = str(function.get("name", "")).strip()
154
153
  if not name:
155
154
  raise CustomToolAdapterError("outcomming custom tool call is missing `name`")
155
+ try:
156
+ input_text = extract_input_text(function.get("arguments"))
157
+ except CustomToolAdapterError as exc:
158
+ raise CustomToolAdapterError(
159
+ f"outcomming custom tool call arguments for {name!r}: {exc}"
160
+ ) from exc
156
161
  return {
157
162
  "type": "custom_tool_call",
158
163
  "call_id": str(tool_call.get("id", "")).strip() or f"call_{index}",
159
164
  "name": name,
160
- "input": extract_input_text(function.get("arguments")),
165
+ "input": input_text,
161
166
  }
162
167
 
163
168
 
164
169
  def extract_input_text(raw_arguments: "object") -> "str":
165
- if isinstance(raw_arguments, dict):
166
- parsed = deepcopy(raw_arguments)
167
- else:
168
- parsed = None
169
-
170
- raw_text = raw_arguments if isinstance(raw_arguments, str) else None
171
- if parsed is None and raw_text is not None:
170
+ parsed = raw_arguments
171
+ if isinstance(raw_arguments, str):
172
172
  try:
173
- parsed = json.loads(raw_text or "{}")
174
- except json.JSONDecodeError:
175
- return raw_text
176
-
177
- if isinstance(parsed, dict) and "input" in parsed:
178
- value = parsed.get("input")
179
- if isinstance(value, str):
180
- return value
181
- return json.dumps(value, ensure_ascii=False)
182
-
183
- if raw_text is not None:
184
- return raw_text
185
- if parsed is not None:
186
- return json.dumps(parsed, ensure_ascii=False)
187
- return str(raw_arguments or "")
173
+ parsed = json.loads(raw_arguments)
174
+ except json.JSONDecodeError as exc:
175
+ raise CustomToolAdapterError(
176
+ "expected JSON arguments containing an `input` string: " + str(exc)
177
+ ) from exc
178
+ if not isinstance(parsed, dict) or set(parsed) != {"input"}:
179
+ raise CustomToolAdapterError(
180
+ "expected a JSON object containing only the `input` string field"
181
+ )
182
+ if not isinstance(parsed["input"], str):
183
+ raise CustomToolAdapterError("`input` must be a string")
184
+ return parsed["input"]
188
185
 
189
186
 
190
187
  def _build_description(raw_tool: "typing.Dict[str, object]") -> "str":
@@ -193,11 +190,14 @@ def _build_description(raw_tool: "typing.Dict[str, object]") -> "str":
193
190
  return APPLY_PATCH_CHAT_DESCRIPTION
194
191
 
195
192
  description = str(raw_tool.get("description", "") or "").strip()
196
- parts = [description] if description else []
197
- parts.append(
198
- "Chat-completions compatibility: provide the raw tool payload in the "
199
- "`input` string field."
200
- )
193
+ parts = [
194
+ 'Call this function with JSON arguments {"input": "<raw tool input>"}. '
195
+ "The `input` field is required and must be a string. "
196
+ "The raw-input instructions below describe the contents of that string; "
197
+ "the function call arguments must still be valid JSON."
198
+ ]
199
+ if description:
200
+ parts.append(description)
201
201
 
202
202
  raw_format = raw_tool.get("format")
203
203
  if isinstance(raw_format, dict):
@@ -131,6 +131,7 @@ def build_followup_request(
131
131
  outcomming_request: "typing.Dict[str, object]",
132
132
  mock_search_calls: "typing.List[typing.Dict[str, object]]",
133
133
  reasoning_text: "typing.Union[str, None]" = None,
134
+ provider_data=None,
134
135
  ) -> "typing.Dict[str, object]":
135
136
  followup_request = deepcopy(outcomming_request)
136
137
  messages = followup_request.get("messages") or []
@@ -159,6 +160,8 @@ def build_followup_request(
159
160
  }
160
161
  if reasoning_text:
161
162
  assistant_message["reasoning"] = reasoning_text
163
+ if provider_data:
164
+ assistant_message["provider_data"] = deepcopy(provider_data)
162
165
  messages.append(assistant_message)
163
166
 
164
167
  for tool_call in mock_search_calls:
@@ -0,0 +1,388 @@
1
+ """Downstream HTTP transport, provider boundary adapters and SSE diagnostics."""
2
+
3
+ import http.client
4
+ import json
5
+ import ssl
6
+ import time
7
+ import typing
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from contextlib import contextmanager
12
+
13
+ from .config import CompatServerConfig
14
+ from .gemini_api import GeminiAPIAdapterError, build_gemini_request
15
+ from .gemini_api import continuation_chunk as gemini_continuation_chunk
16
+ from .gemini_api import iter_chat_chunks as iter_chat_chunks_from_gemini
17
+ from .messages_api import MessagesAPIAdapterError, build_messages_request
18
+ from .messages_api import iter_chat_chunks as iter_chat_chunks_from_messages
19
+ from .messages_api import saw_message_stop as messages_saw_message_stop
20
+
21
+
22
+ class OutcommingChatError(RuntimeError):
23
+ def __init__(
24
+ self,
25
+ message: "str",
26
+ error_type: "typing.Union[str, None]" = None,
27
+ ) -> "None":
28
+ super().__init__(message)
29
+ self.error_type = error_type
30
+
31
+
32
+ class OutcommingTransport:
33
+ def __init__(self, config: "CompatServerConfig") -> "None":
34
+ self.config = config
35
+
36
+ def list_models(self) -> "typing.Dict[str, object]":
37
+ if self.config.normalized_outcomming_api() == "gemini":
38
+ return self._list_gemini_models()
39
+ request = urllib.request.Request(
40
+ self.config.outcomming_models_url(),
41
+ headers=self._build_headers(accept="application/json"),
42
+ method="GET",
43
+ )
44
+ return self._request_json(request)
45
+
46
+ def _list_gemini_models(self):
47
+ url = self.config.outcomming_models_url()
48
+ models = []
49
+ while True:
50
+ request = urllib.request.Request(
51
+ url, headers=self._build_headers(accept="application/json"), method="GET",
52
+ )
53
+ payload = self._request_json(request)
54
+ for model in payload.get("models", []):
55
+ name = model["name"]
56
+ if not name.startswith("models/"):
57
+ raise OutcommingChatError("invalid Gemini model resource name")
58
+ models.append({"id": name[len("models/"):], "object": "model"})
59
+ page_token = payload.get("nextPageToken")
60
+ if not page_token:
61
+ return {"object": "list", "data": models}
62
+ url = self.config.outcomming_models_url() + "?" + urllib.parse.urlencode({"pageToken": page_token})
63
+
64
+ def open_stream(self, outcomming_request: "typing.Dict[str, object]"):
65
+ outcomming_api = self.config.normalized_outcomming_api()
66
+ if outcomming_api == "messages":
67
+ return self._open_outcomming_messages_stream(outcomming_request)
68
+ if outcomming_api == "gemini":
69
+ return self._open_outcomming_gemini_stream(outcomming_request)
70
+ if outcomming_api != "chat_completions":
71
+ raise OutcommingChatError(
72
+ f"unsupported outcomming API: {self.config.outcomming_api!r}"
73
+ )
74
+ return self._open_outcomming_chat_stream(outcomming_request)
75
+
76
+ def _open_outcomming_chat_stream(
77
+ self,
78
+ outcomming_request: "typing.Dict[str, object]",
79
+ ):
80
+ request = urllib.request.Request(
81
+ self.config.outcomming_chat_completions_url(),
82
+ data=json.dumps(outcomming_request).encode("utf-8"),
83
+ headers=self._build_headers(accept="text/event-stream"),
84
+ method="POST",
85
+ )
86
+ with self._request_diagnostics(request) as progress:
87
+ yield from self._read_outcomming_chat_stream(request, progress)
88
+
89
+ def _read_outcomming_chat_stream(self, request, progress):
90
+ try:
91
+ with urllib.request.urlopen(
92
+ request,
93
+ context=ssl.create_default_context(),
94
+ timeout=self.config.timeout_seconds,
95
+ ) as response:
96
+ progress["headers_at"] = time.monotonic()
97
+ progress["status"] = response.status
98
+ progress["phase"] = "waiting_first_chunk"
99
+ try:
100
+ saw_done = False
101
+ for _event_name, data in self._iter_sse_events(response):
102
+ if not data:
103
+ yield {}
104
+ continue
105
+ if data == "[DONE]":
106
+ saw_done = True
107
+ break
108
+ payload = json.loads(data)
109
+ self._received_chunk(progress)
110
+ if isinstance(payload, dict) and payload.get("error") is not None:
111
+ raise OutcommingChatError(
112
+ "outcomming chat stream returned an error: "
113
+ + json.dumps(payload["error"], ensure_ascii=False)[:500]
114
+ )
115
+ yield payload
116
+ if not saw_done:
117
+ raise OutcommingChatError(
118
+ "outcomming chat stream ended before [DONE]"
119
+ )
120
+ except (
121
+ ConnectionError,
122
+ EOFError,
123
+ OSError,
124
+ http.client.HTTPException,
125
+ json.JSONDecodeError,
126
+ ) as exc:
127
+ raise OutcommingChatError(
128
+ "outcomming chat stream failed while reading response body: "
129
+ f"{exc}"
130
+ ) from exc
131
+ except urllib.error.HTTPError as exc:
132
+ progress["headers_at"] = time.monotonic()
133
+ progress["status"] = exc.code
134
+ progress["phase"] = "reading_error_body"
135
+ body = exc.read().decode("utf-8", errors="replace")
136
+ raise OutcommingChatError(
137
+ f"outcomming chat request failed with status {exc.code}: {body[:500]}"
138
+ ) from exc
139
+ except TimeoutError as exc:
140
+ raise OutcommingChatError(
141
+ "outcomming chat request timed out after "
142
+ f"{self.config.timeout_seconds:g}s"
143
+ ) from exc
144
+ except urllib.error.URLError as exc:
145
+ raise OutcommingChatError(
146
+ f"outcomming chat request failed: {exc.reason}"
147
+ ) from exc
148
+ except (OSError, EOFError, http.client.HTTPException) as exc:
149
+ raise OutcommingChatError(
150
+ "outcomming chat request failed while opening response: "
151
+ f"{type(exc).__name__}: {exc}"
152
+ ) from exc
153
+
154
+ def _open_outcomming_messages_stream(
155
+ self,
156
+ outcomming_request: "typing.Dict[str, object]",
157
+ ):
158
+ try:
159
+ messages_request = build_messages_request(outcomming_request)
160
+ except MessagesAPIAdapterError as exc:
161
+ raise OutcommingChatError(str(exc)) from exc
162
+
163
+ request = urllib.request.Request(
164
+ self.config.outcomming_messages_url(),
165
+ data=json.dumps(messages_request).encode("utf-8"),
166
+ headers=self._build_headers(accept="text/event-stream"),
167
+ method="POST",
168
+ )
169
+ with self._request_diagnostics(request) as progress:
170
+ yield from self._read_outcomming_native_stream(request, progress, "messages")
171
+
172
+ def _open_outcomming_gemini_stream(self, outcomming_request):
173
+ try:
174
+ payload = build_gemini_request(outcomming_request)
175
+ url = self.config.outcomming_gemini_url(outcomming_request["model"])
176
+ except ValueError as exc:
177
+ raise OutcommingChatError(str(exc)) from exc
178
+ request = urllib.request.Request(
179
+ url, data=json.dumps(payload).encode("utf-8"),
180
+ headers=self._build_headers(accept="text/event-stream"), method="POST",
181
+ )
182
+ with self._request_diagnostics(request) as progress:
183
+ yield from self._read_outcomming_native_stream(request, progress, "gemini")
184
+
185
+ def _read_outcomming_native_stream(self, request, progress, api):
186
+ try:
187
+ with urllib.request.urlopen(
188
+ request,
189
+ context=ssl.create_default_context(),
190
+ timeout=self.config.timeout_seconds,
191
+ ) as response:
192
+ progress["headers_at"] = time.monotonic()
193
+ progress["status"] = response.status
194
+ progress["phase"] = "waiting_first_chunk"
195
+ try:
196
+ stream_state: "typing.Dict[str, object]" = {}
197
+ for event_name, data in self._iter_sse_events(response):
198
+ if not data:
199
+ yield {}
200
+ continue
201
+ payload = json.loads(data)
202
+ self._received_chunk(progress)
203
+ if api == "gemini":
204
+ chunks = list(iter_chat_chunks_from_gemini(payload, stream_state))
205
+ elif isinstance(payload, dict):
206
+ chunks = iter_chat_chunks_from_messages(event_name, payload, stream_state)
207
+ else:
208
+ chunks = []
209
+ yield from chunks or [{}]
210
+ finished = (
211
+ stream_state.get("finished") if api == "gemini"
212
+ else messages_saw_message_stop(stream_state)
213
+ )
214
+ if not finished:
215
+ terminal = "finishReason" if api == "gemini" else "message_stop"
216
+ raise OutcommingChatError(
217
+ f"outcomming {api} stream ended before `{terminal}`"
218
+ )
219
+ if api == "gemini":
220
+ yield gemini_continuation_chunk(stream_state)
221
+ except MessagesAPIAdapterError as exc:
222
+ raise OutcommingChatError(
223
+ "outcomming messages stream failed while reading response body: "
224
+ + str(exc), error_type=exc.error_type,
225
+ ) from exc
226
+ except (
227
+ ConnectionError,
228
+ EOFError,
229
+ OSError,
230
+ http.client.HTTPException,
231
+ json.JSONDecodeError,
232
+ GeminiAPIAdapterError,
233
+ ) as exc:
234
+ raise OutcommingChatError(
235
+ f"outcomming {api} stream failed while reading response body: "
236
+ f"{exc}"
237
+ ) from exc
238
+ except urllib.error.HTTPError as exc:
239
+ progress["headers_at"] = time.monotonic()
240
+ progress["status"] = exc.code
241
+ progress["phase"] = "reading_error_body"
242
+ body = exc.read().decode("utf-8", errors="replace")
243
+ raise OutcommingChatError(
244
+ f"outcomming {api} request failed with status {exc.code}: {body[:500]}"
245
+ ) from exc
246
+ except TimeoutError as exc:
247
+ raise OutcommingChatError(
248
+ f"outcomming {api} request timed out after "
249
+ f"{self.config.timeout_seconds:g}s"
250
+ ) from exc
251
+ except urllib.error.URLError as exc:
252
+ raise OutcommingChatError(
253
+ f"outcomming {api} request failed: {exc.reason}"
254
+ ) from exc
255
+ except (OSError, EOFError, http.client.HTTPException) as exc:
256
+ raise OutcommingChatError(
257
+ f"outcomming {api} request failed while opening response: "
258
+ f"{type(exc).__name__}: {exc}"
259
+ ) from exc
260
+
261
+ @contextmanager
262
+ def _request_diagnostics(self, request):
263
+ started = time.monotonic()
264
+ progress = {
265
+ "phase": "waiting_response_headers",
266
+ "headers_at": None,
267
+ "first_chunk_at": None,
268
+ "last_chunk_at": None,
269
+ "chunks": 0,
270
+ "status": None,
271
+ }
272
+ try:
273
+ yield progress
274
+ except OutcommingChatError as exc:
275
+ now = time.monotonic()
276
+ cause = exc.__cause__ or exc
277
+ if isinstance(cause, urllib.error.URLError) and isinstance(
278
+ cause.reason, BaseException
279
+ ):
280
+ cause = cause.reason
281
+
282
+ def timing(received_at):
283
+ if received_at is None:
284
+ return "not_received"
285
+ return f"{received_at - started:.2f}s"
286
+
287
+ idle = (
288
+ f"{now - progress['last_chunk_at']:.2f}s"
289
+ if progress["last_chunk_at"] is not None
290
+ else "not_started"
291
+ )
292
+ details = (
293
+ f"phase={progress['phase']}, elapsed={now - started:.2f}s, "
294
+ f"timeout={self.config.timeout_seconds:g}s\n"
295
+ f"headers={timing(progress['headers_at'])}, "
296
+ f"first_chunk={timing(progress['first_chunk_at'])}, "
297
+ f"chunks={progress['chunks']}, idle={idle}\n"
298
+ f"status={progress['status']}, "
299
+ f"request_bytes={len(request.data or b'')}, "
300
+ f"exception={type(cause).__name__}"
301
+ )
302
+ exc.args = (f"{exc}\n{details}",)
303
+ raise
304
+
305
+ def _received_chunk(self, progress):
306
+ now = time.monotonic()
307
+ if progress["chunks"] == 0:
308
+ progress["first_chunk_at"] = now
309
+ progress["last_chunk_at"] = now
310
+ progress["chunks"] += 1
311
+ progress["phase"] = "reading_stream"
312
+
313
+ def _request_json(
314
+ self, request: "urllib.request.Request"
315
+ ) -> "typing.Dict[str, object]":
316
+ with self._request_diagnostics(request) as progress:
317
+ return self._read_json_response(request, progress)
318
+
319
+ def _read_json_response(self, request, progress):
320
+ try:
321
+ with urllib.request.urlopen(
322
+ request,
323
+ context=ssl.create_default_context(),
324
+ timeout=self.config.timeout_seconds,
325
+ ) as response:
326
+ progress["headers_at"] = time.monotonic()
327
+ progress["status"] = response.status
328
+ progress["phase"] = "reading_response_body"
329
+ return json.loads(response.read().decode("utf-8"))
330
+ except urllib.error.HTTPError as exc:
331
+ progress["headers_at"] = time.monotonic()
332
+ progress["status"] = exc.code
333
+ progress["phase"] = "reading_error_body"
334
+ body = exc.read().decode("utf-8", errors="replace")
335
+ raise OutcommingChatError(
336
+ f"outcomming request failed with status {exc.code}: {body[:500]}"
337
+ ) from exc
338
+ except TimeoutError as exc:
339
+ raise OutcommingChatError(
340
+ "outcomming request timed out after "
341
+ f"{self.config.timeout_seconds:g}s"
342
+ ) from exc
343
+ except urllib.error.URLError as exc:
344
+ raise OutcommingChatError(
345
+ f"outcomming request failed: {exc.reason}"
346
+ ) from exc
347
+ except (OSError, EOFError, http.client.HTTPException) as exc:
348
+ raise OutcommingChatError(
349
+ f"outcomming request failed: {type(exc).__name__}: {exc}"
350
+ ) from exc
351
+
352
+ def _build_headers(self, accept: "str") -> "typing.Dict[str, str]":
353
+ headers = {
354
+ "Accept": accept,
355
+ "Content-Type": "application/json",
356
+ }
357
+ api_key = self.config.outcomming_api_key()
358
+ if api_key is not None:
359
+ if self.config.normalized_outcomming_api() == "gemini":
360
+ headers["x-goog-api-key"] = api_key
361
+ else:
362
+ headers["Authorization"] = f"Bearer {api_key}"
363
+ return headers
364
+
365
+ def _iter_sse_events(self, response):
366
+ event_name: "typing.Union[str, None]" = None
367
+ data_lines: "typing.List[str]" = []
368
+
369
+ for raw_line in response:
370
+ line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
371
+ if line == "":
372
+ if data_lines:
373
+ yield event_name or "message", "\n".join(data_lines)
374
+ event_name = None
375
+ data_lines = []
376
+ continue
377
+
378
+ if line.startswith(":"):
379
+ yield None, ""
380
+ continue
381
+ if line.startswith("event:"):
382
+ event_name = line.split(":", 1)[1].lstrip()
383
+ continue
384
+ if line.startswith("data:"):
385
+ data_lines.append(line.split(":", 1)[1].lstrip())
386
+
387
+ if data_lines:
388
+ yield event_name or "message", "\n".join(data_lines)
@@ -1,60 +0,0 @@
1
- """`close_agent` tool for the Python Codex prototype.
2
-
3
- Original Codex mapping:
4
- - Corresponds to the original Codex `close_agent` collaboration tool.
5
-
6
- Expected behavior:
7
- - Shut down a spawned agent when it is no longer needed.
8
- - Return the agent status observed before shutdown was requested.
9
- """
10
-
11
- from ..protocol import JSONDict, JSONValue
12
- from .agent_tool_schemas import AGENT_STATUS_SCHEMA
13
- from .base_tool import BaseTool, ToolContext
14
- from .runtime_services import SubAgentManager
15
-
16
- CLOSE_AGENT_OUTPUT_SCHEMA = {
17
- "type": "object",
18
- "properties": {
19
- "previous_status": {
20
- "description": "The agent status observed before shutdown was requested.",
21
- "allOf": [AGENT_STATUS_SCHEMA],
22
- },
23
- },
24
- "required": ["previous_status"],
25
- "additionalProperties": False,
26
- }
27
-
28
-
29
- class CloseAgentTool(BaseTool):
30
- name = "close_agent"
31
- description = (
32
- "Close an agent and any open descendants when they are no longer "
33
- "needed, and return the target agent's previous status before shutdown "
34
- "was requested. Completed agents remain open and count toward the "
35
- "concurrency limit until closed. Don't keep agents open for too long "
36
- "if they are not needed anymore."
37
- )
38
- input_schema = {
39
- "type": "object",
40
- "properties": {
41
- "id": {
42
- "type": "string",
43
- "description": "Agent id to close (from spawn_agent).",
44
- }
45
- },
46
- "required": ["id"],
47
- "additionalProperties": False,
48
- }
49
- output_schema = CLOSE_AGENT_OUTPUT_SCHEMA
50
- supports_parallel = False
51
-
52
- def __init__(self, subagent_manager: "SubAgentManager") -> "None":
53
- self._subagent_manager = subagent_manager
54
-
55
- async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
56
- del context
57
- agent_id = str(args.get("id", "")).strip()
58
- if not agent_id:
59
- return "Error: `id` is required."
60
- return await self._subagent_manager.close_agent(agent_id)