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
@@ -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):
@@ -0,0 +1,332 @@
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.request
10
+ from contextlib import contextmanager
11
+
12
+ from .config import CompatServerConfig
13
+ from .messages_api import MessagesAPIAdapterError, build_messages_request
14
+ from .messages_api import iter_chat_chunks as iter_chat_chunks_from_messages
15
+ from .messages_api import saw_message_stop as messages_saw_message_stop
16
+
17
+
18
+ class OutcommingChatError(RuntimeError):
19
+ def __init__(
20
+ self,
21
+ message: "str",
22
+ error_type: "typing.Union[str, None]" = None,
23
+ ) -> "None":
24
+ super().__init__(message)
25
+ self.error_type = error_type
26
+
27
+
28
+ class OutcommingTransport:
29
+ def __init__(self, config: "CompatServerConfig") -> "None":
30
+ self.config = config
31
+
32
+ def list_models(self) -> "typing.Dict[str, object]":
33
+ request = urllib.request.Request(
34
+ self.config.outcomming_models_url(),
35
+ headers=self._build_headers(accept="application/json"),
36
+ method="GET",
37
+ )
38
+ return self._request_json(request)
39
+
40
+ def open_stream(self, outcomming_request: "typing.Dict[str, object]"):
41
+ outcomming_api = self.config.normalized_outcomming_api()
42
+ if outcomming_api == "messages":
43
+ return self._open_outcomming_messages_stream(outcomming_request)
44
+ if outcomming_api != "chat_completions":
45
+ raise OutcommingChatError(
46
+ f"unsupported outcomming API: {self.config.outcomming_api!r}"
47
+ )
48
+ return self._open_outcomming_chat_stream(outcomming_request)
49
+
50
+ def _open_outcomming_chat_stream(
51
+ self,
52
+ outcomming_request: "typing.Dict[str, object]",
53
+ ):
54
+ request = urllib.request.Request(
55
+ self.config.outcomming_chat_completions_url(),
56
+ data=json.dumps(outcomming_request).encode("utf-8"),
57
+ headers=self._build_headers(accept="text/event-stream"),
58
+ method="POST",
59
+ )
60
+ with self._request_diagnostics(request) as progress:
61
+ yield from self._read_outcomming_chat_stream(request, progress)
62
+
63
+ def _read_outcomming_chat_stream(self, request, progress):
64
+ try:
65
+ with urllib.request.urlopen(
66
+ request,
67
+ context=ssl.create_default_context(),
68
+ timeout=self.config.timeout_seconds,
69
+ ) as response:
70
+ progress["headers_at"] = time.monotonic()
71
+ progress["status"] = response.status
72
+ progress["phase"] = "waiting_first_chunk"
73
+ try:
74
+ saw_done = False
75
+ for _event_name, data in self._iter_sse_events(response):
76
+ if not data:
77
+ continue
78
+ if data == "[DONE]":
79
+ saw_done = True
80
+ break
81
+ payload = json.loads(data)
82
+ self._received_chunk(progress)
83
+ if isinstance(payload, dict) and payload.get("error") is not None:
84
+ raise OutcommingChatError(
85
+ "outcomming chat stream returned an error: "
86
+ + json.dumps(payload["error"], ensure_ascii=False)[:500]
87
+ )
88
+ yield payload
89
+ if not saw_done:
90
+ raise OutcommingChatError(
91
+ "outcomming chat stream ended before [DONE]"
92
+ )
93
+ except (
94
+ ConnectionError,
95
+ EOFError,
96
+ OSError,
97
+ http.client.HTTPException,
98
+ json.JSONDecodeError,
99
+ ) as exc:
100
+ raise OutcommingChatError(
101
+ "outcomming chat stream failed while reading response body: "
102
+ f"{exc}"
103
+ ) from exc
104
+ except urllib.error.HTTPError as exc:
105
+ progress["headers_at"] = time.monotonic()
106
+ progress["status"] = exc.code
107
+ progress["phase"] = "reading_error_body"
108
+ body = exc.read().decode("utf-8", errors="replace")
109
+ raise OutcommingChatError(
110
+ f"outcomming chat request failed with status {exc.code}: {body[:500]}"
111
+ ) from exc
112
+ except TimeoutError as exc:
113
+ raise OutcommingChatError(
114
+ "outcomming chat request timed out after "
115
+ f"{self.config.timeout_seconds:g}s"
116
+ ) from exc
117
+ except urllib.error.URLError as exc:
118
+ raise OutcommingChatError(
119
+ f"outcomming chat request failed: {exc.reason}"
120
+ ) from exc
121
+ except (OSError, EOFError, http.client.HTTPException) as exc:
122
+ raise OutcommingChatError(
123
+ "outcomming chat request failed while opening response: "
124
+ f"{type(exc).__name__}: {exc}"
125
+ ) from exc
126
+
127
+ def _open_outcomming_messages_stream(
128
+ self,
129
+ outcomming_request: "typing.Dict[str, object]",
130
+ ):
131
+ try:
132
+ messages_request = build_messages_request(outcomming_request)
133
+ except MessagesAPIAdapterError as exc:
134
+ raise OutcommingChatError(str(exc)) from exc
135
+
136
+ request = urllib.request.Request(
137
+ self.config.outcomming_messages_url(),
138
+ data=json.dumps(messages_request).encode("utf-8"),
139
+ headers=self._build_headers(accept="text/event-stream"),
140
+ method="POST",
141
+ )
142
+ with self._request_diagnostics(request) as progress:
143
+ yield from self._read_outcomming_messages_stream(request, progress)
144
+
145
+ def _read_outcomming_messages_stream(self, request, progress):
146
+ try:
147
+ with urllib.request.urlopen(
148
+ request,
149
+ context=ssl.create_default_context(),
150
+ timeout=self.config.timeout_seconds,
151
+ ) as response:
152
+ progress["headers_at"] = time.monotonic()
153
+ progress["status"] = response.status
154
+ progress["phase"] = "waiting_first_chunk"
155
+ try:
156
+ stream_state: "typing.Dict[str, object]" = {}
157
+ for event_name, data in self._iter_sse_events(response):
158
+ if not data:
159
+ continue
160
+ payload = json.loads(data)
161
+ if not isinstance(payload, dict):
162
+ continue
163
+ self._received_chunk(progress)
164
+ for chunk in iter_chat_chunks_from_messages(
165
+ event_name,
166
+ payload,
167
+ stream_state,
168
+ ):
169
+ yield chunk
170
+ if not messages_saw_message_stop(stream_state):
171
+ raise OutcommingChatError(
172
+ "outcomming messages stream ended before `message_stop`"
173
+ )
174
+ except (
175
+ ConnectionError,
176
+ EOFError,
177
+ OSError,
178
+ http.client.HTTPException,
179
+ json.JSONDecodeError,
180
+ MessagesAPIAdapterError,
181
+ ) as exc:
182
+ raise OutcommingChatError(
183
+ "outcomming messages stream failed while reading response body: "
184
+ f"{exc}"
185
+ ) from exc
186
+ except urllib.error.HTTPError as exc:
187
+ progress["headers_at"] = time.monotonic()
188
+ progress["status"] = exc.code
189
+ progress["phase"] = "reading_error_body"
190
+ body = exc.read().decode("utf-8", errors="replace")
191
+ raise OutcommingChatError(
192
+ f"outcomming messages request failed with status {exc.code}: {body[:500]}"
193
+ ) from exc
194
+ except TimeoutError as exc:
195
+ raise OutcommingChatError(
196
+ "outcomming messages request timed out after "
197
+ f"{self.config.timeout_seconds:g}s"
198
+ ) from exc
199
+ except urllib.error.URLError as exc:
200
+ raise OutcommingChatError(
201
+ f"outcomming messages request failed: {exc.reason}"
202
+ ) from exc
203
+ except (OSError, EOFError, http.client.HTTPException) as exc:
204
+ raise OutcommingChatError(
205
+ "outcomming messages request failed while opening response: "
206
+ f"{type(exc).__name__}: {exc}"
207
+ ) from exc
208
+
209
+ @contextmanager
210
+ def _request_diagnostics(self, request):
211
+ started = time.monotonic()
212
+ progress = {
213
+ "phase": "waiting_response_headers",
214
+ "headers_at": None,
215
+ "first_chunk_at": None,
216
+ "last_chunk_at": None,
217
+ "chunks": 0,
218
+ "status": None,
219
+ }
220
+ try:
221
+ yield progress
222
+ except OutcommingChatError as exc:
223
+ now = time.monotonic()
224
+ cause = exc.__cause__ or exc
225
+ if isinstance(cause, urllib.error.URLError) and isinstance(
226
+ cause.reason, BaseException
227
+ ):
228
+ cause = cause.reason
229
+
230
+ def timing(received_at):
231
+ if received_at is None:
232
+ return "not_received"
233
+ return f"{received_at - started:.2f}s"
234
+
235
+ idle = (
236
+ f"{now - progress['last_chunk_at']:.2f}s"
237
+ if progress["last_chunk_at"] is not None
238
+ else "not_started"
239
+ )
240
+ details = (
241
+ f"phase={progress['phase']}, elapsed={now - started:.2f}s, "
242
+ f"timeout={self.config.timeout_seconds:g}s\n"
243
+ f"headers={timing(progress['headers_at'])}, "
244
+ f"first_chunk={timing(progress['first_chunk_at'])}, "
245
+ f"chunks={progress['chunks']}, idle={idle}\n"
246
+ f"status={progress['status']}, "
247
+ f"request_bytes={len(request.data or b'')}, "
248
+ f"exception={type(cause).__name__}"
249
+ )
250
+ exc.args = (f"{exc}\n{details}",)
251
+ raise
252
+
253
+ def _received_chunk(self, progress):
254
+ now = time.monotonic()
255
+ if progress["chunks"] == 0:
256
+ progress["first_chunk_at"] = now
257
+ progress["last_chunk_at"] = now
258
+ progress["chunks"] += 1
259
+ progress["phase"] = "reading_stream"
260
+
261
+ def _request_json(
262
+ self, request: "urllib.request.Request"
263
+ ) -> "typing.Dict[str, object]":
264
+ with self._request_diagnostics(request) as progress:
265
+ return self._read_json_response(request, progress)
266
+
267
+ def _read_json_response(self, request, progress):
268
+ try:
269
+ with urllib.request.urlopen(
270
+ request,
271
+ context=ssl.create_default_context(),
272
+ timeout=self.config.timeout_seconds,
273
+ ) as response:
274
+ progress["headers_at"] = time.monotonic()
275
+ progress["status"] = response.status
276
+ progress["phase"] = "reading_response_body"
277
+ return json.loads(response.read().decode("utf-8"))
278
+ except urllib.error.HTTPError as exc:
279
+ progress["headers_at"] = time.monotonic()
280
+ progress["status"] = exc.code
281
+ progress["phase"] = "reading_error_body"
282
+ body = exc.read().decode("utf-8", errors="replace")
283
+ raise OutcommingChatError(
284
+ f"outcomming request failed with status {exc.code}: {body[:500]}"
285
+ ) from exc
286
+ except TimeoutError as exc:
287
+ raise OutcommingChatError(
288
+ "outcomming request timed out after "
289
+ f"{self.config.timeout_seconds:g}s"
290
+ ) from exc
291
+ except urllib.error.URLError as exc:
292
+ raise OutcommingChatError(
293
+ f"outcomming request failed: {exc.reason}"
294
+ ) from exc
295
+ except (OSError, EOFError, http.client.HTTPException) as exc:
296
+ raise OutcommingChatError(
297
+ f"outcomming request failed: {type(exc).__name__}: {exc}"
298
+ ) from exc
299
+
300
+ def _build_headers(self, accept: "str") -> "typing.Dict[str, str]":
301
+ headers = {
302
+ "Accept": accept,
303
+ "Content-Type": "application/json",
304
+ }
305
+ api_key = self.config.outcomming_api_key()
306
+ if api_key is not None:
307
+ headers["Authorization"] = f"Bearer {api_key}"
308
+ return headers
309
+
310
+ def _iter_sse_events(self, response):
311
+ event_name: "typing.Union[str, None]" = None
312
+ data_lines: "typing.List[str]" = []
313
+
314
+ for raw_line in response:
315
+ line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
316
+ if line == "":
317
+ if data_lines:
318
+ yield event_name or "message", "\n".join(data_lines)
319
+ event_name = None
320
+ data_lines = []
321
+ continue
322
+
323
+ if line.startswith(":"):
324
+ continue
325
+ if line.startswith("event:"):
326
+ event_name = line.split(":", 1)[1].lstrip()
327
+ continue
328
+ if line.startswith("data:"):
329
+ data_lines.append(line.split(":", 1)[1].lstrip())
330
+
331
+ if data_lines:
332
+ 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)
@@ -1,161 +0,0 @@
1
- const readline = require('readline');
2
- const { stdin, stdout } = require('process');
3
-
4
- const pending = new Map();
5
- let storedValues = {};
6
- let toolMap = {};
7
- let initialized = false;
8
-
9
- function send(message) {
10
- stdout.write(JSON.stringify(message) + '\n');
11
- }
12
-
13
- function stringifyValue(value) {
14
- if (typeof value === 'string') {
15
- return value;
16
- }
17
- if (value === undefined) {
18
- return 'undefined';
19
- }
20
- try {
21
- return JSON.stringify(value);
22
- } catch (_error) {
23
- return String(value);
24
- }
25
- }
26
-
27
- function text(value) {
28
- send({ type: 'output_text', text: stringifyValue(value) });
29
- }
30
-
31
- function notify(value) {
32
- text(value);
33
- }
34
-
35
- function image(value) {
36
- if (typeof value === 'string') {
37
- send({ type: 'output_image', image_url: value, detail: null });
38
- return;
39
- }
40
- if (value && typeof value === 'object' && typeof value.image_url === 'string') {
41
- send({
42
- type: 'output_image',
43
- image_url: value.image_url,
44
- detail: value.detail === undefined ? null : value.detail,
45
- });
46
- return;
47
- }
48
- throw new Error('image(...) expects an image URL string or { image_url, detail? }');
49
- }
50
-
51
- function store(key, value) {
52
- storedValues[key] = value;
53
- }
54
-
55
- function load(key) {
56
- return storedValues[key];
57
- }
58
-
59
- function exit() {
60
- const error = new Error('__CODEX_EXIT__');
61
- error.__codexExit = true;
62
- throw error;
63
- }
64
-
65
- async function yield_control() {
66
- send({ type: 'yield' });
67
- }
68
-
69
- function createToolCaller(toolName) {
70
- return function callTool(argumentsValue = {}) {
71
- const id = `${toolName}_${Math.random().toString(16).slice(2)}`;
72
- send({
73
- type: 'tool_call',
74
- id,
75
- tool_name: toolName,
76
- arguments: argumentsValue,
77
- });
78
- return new Promise((resolve, reject) => {
79
- pending.set(id, { resolve, reject });
80
- });
81
- };
82
- }
83
-
84
- function initialize(message) {
85
- storedValues = message.stored_values || {};
86
- toolMap = {};
87
- for (const tool of message.tools || []) {
88
- toolMap[tool.js_name] = createToolCaller(tool.tool_name);
89
- }
90
- const allTools = Object.freeze(
91
- (message.tools || []).map((tool) => ({
92
- name: tool.js_name,
93
- description: tool.description,
94
- }))
95
- );
96
-
97
- const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
98
- const fn = new AsyncFunction(
99
- 'tools',
100
- 'text',
101
- 'image',
102
- 'store',
103
- 'load',
104
- 'exit',
105
- 'notify',
106
- 'ALL_TOOLS',
107
- 'yield_control',
108
- 'console',
109
- message.source
110
- );
111
-
112
- (async () => {
113
- try {
114
- await fn(
115
- toolMap,
116
- text,
117
- image,
118
- store,
119
- load,
120
- exit,
121
- notify,
122
- allTools,
123
- yield_control,
124
- undefined
125
- );
126
- send({ type: 'result', stored_values: storedValues, error_text: null });
127
- } catch (error) {
128
- if (error && error.__codexExit) {
129
- send({ type: 'result', stored_values: storedValues, error_text: null });
130
- return;
131
- }
132
- const errorText = error && error.stack ? error.stack : String(error);
133
- send({ type: 'result', stored_values: storedValues, error_text: errorText });
134
- }
135
- })();
136
- }
137
-
138
- const rl = readline.createInterface({ input: stdin, crlfDelay: Infinity });
139
- rl.on('line', (line) => {
140
- if (!line.trim()) {
141
- return;
142
- }
143
- const message = JSON.parse(line);
144
- if (message.type === 'init' && !initialized) {
145
- initialized = true;
146
- initialize(message);
147
- return;
148
- }
149
- if (message.type === 'tool_result') {
150
- const entry = pending.get(message.id);
151
- if (!entry) {
152
- return;
153
- }
154
- pending.delete(message.id);
155
- if (message.ok) {
156
- entry.resolve(message.result);
157
- } else {
158
- entry.reject(new Error(message.error || 'nested tool failed'));
159
- }
160
- }
161
- });
@@ -1,54 +0,0 @@
1
- """`resume_agent` tool for the Python Codex prototype.
2
-
3
- Original Codex mapping:
4
- - Corresponds to the original Codex `resume_agent` collaboration tool.
5
-
6
- Expected behavior:
7
- - Restart a previously closed local sub-agent runtime.
8
- - Return the agent's current status payload.
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
- RESUME_AGENT_OUTPUT_SCHEMA = {
17
- "type": "object",
18
- "properties": {
19
- "status": AGENT_STATUS_SCHEMA,
20
- },
21
- "required": ["status"],
22
- "additionalProperties": False,
23
- }
24
-
25
-
26
- class ResumeAgentTool(BaseTool):
27
- name = "resume_agent"
28
- description = (
29
- "Resume a previously closed agent by id so it can receive send_input "
30
- "and wait_agent calls."
31
- )
32
- input_schema = {
33
- "type": "object",
34
- "properties": {
35
- "id": {
36
- "type": "string",
37
- "description": "Agent id to resume.",
38
- }
39
- },
40
- "required": ["id"],
41
- "additionalProperties": False,
42
- }
43
- output_schema = RESUME_AGENT_OUTPUT_SCHEMA
44
- supports_parallel = False
45
-
46
- def __init__(self, subagent_manager: "SubAgentManager") -> "None":
47
- self._subagent_manager = subagent_manager
48
-
49
- async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
50
- del context
51
- agent_id = str(args.get("id", "")).strip()
52
- if not agent_id:
53
- return "Error: `id` is required."
54
- return await self._subagent_manager.resume_agent(agent_id)