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
pycodex/context.py
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
+
import json
|
|
1
2
|
import typing
|
|
3
|
+
from copy import deepcopy
|
|
2
4
|
from dataclasses import dataclass, replace
|
|
3
5
|
from datetime import datetime
|
|
4
6
|
from pathlib import Path
|
|
7
|
+
from uuid import UUID, uuid5
|
|
5
8
|
from xml.sax.saxutils import escape
|
|
6
9
|
|
|
7
10
|
import yaml
|
|
8
11
|
|
|
9
|
-
|
|
10
|
-
import tomllib
|
|
11
|
-
except ModuleNotFoundError: # pragma: no cover - Python 3.10 path
|
|
12
|
-
import tomli as tomllib
|
|
13
|
-
|
|
12
|
+
from .utils.codex_config import read_codex_config
|
|
14
13
|
from .utils.model_metadata import model_metadata
|
|
15
|
-
from .protocol import
|
|
14
|
+
from .protocol import (
|
|
15
|
+
ContextMessage, ConversationItem, JSONDict, Prompt, ToolCall, ToolResult, ToolSpec, UserMessage,
|
|
16
|
+
)
|
|
16
17
|
from .utils.get_env import (
|
|
17
18
|
get_sandbox_tag,
|
|
18
19
|
get_shell_name,
|
|
@@ -81,22 +82,46 @@ class ContextConfig:
|
|
|
81
82
|
network_access: "str" = "enabled"
|
|
82
83
|
extra_contextual_user_messages: "typing.Tuple[str, ...]" = ()
|
|
83
84
|
cwd: "typing.Union[str, Path, None]" = None
|
|
85
|
+
multi_agent_max_concurrency: "int" = 16
|
|
86
|
+
multi_agent_root_instructions: "typing.Union[str, None]" = None
|
|
87
|
+
multi_agent_subagent_instructions: "typing.Union[str, None]" = None
|
|
88
|
+
multi_agent_hint: "typing.Union[str, None]" = None
|
|
89
|
+
code_mode_only: "typing.Union[bool, None]" = None
|
|
90
|
+
|
|
91
|
+
def __post_init__(self):
|
|
92
|
+
if self.code_mode_only is not None and not isinstance(self.code_mode_only, bool):
|
|
93
|
+
raise ValueError("code_mode_only must be a boolean")
|
|
94
|
+
if (
|
|
95
|
+
type(self.multi_agent_max_concurrency) is not int
|
|
96
|
+
or self.multi_agent_max_concurrency < 1
|
|
97
|
+
):
|
|
98
|
+
raise ValueError("multi-agent max concurrency must be a positive integer")
|
|
99
|
+
for text in (
|
|
100
|
+
self.multi_agent_root_instructions,
|
|
101
|
+
self.multi_agent_subagent_instructions,
|
|
102
|
+
self.multi_agent_hint,
|
|
103
|
+
):
|
|
104
|
+
if text is not None and not isinstance(text, str):
|
|
105
|
+
raise ValueError("multi-agent instruction overrides must be strings")
|
|
84
106
|
|
|
85
107
|
@classmethod
|
|
86
108
|
def from_codex_config(
|
|
87
109
|
cls,
|
|
88
110
|
config_path: "typing.Union[str, Path]",
|
|
89
111
|
profile: "typing.Union[str, None]" = None,
|
|
112
|
+
use_default_profile: "bool" = True,
|
|
90
113
|
) -> "ContextConfig":
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if profile is not None:
|
|
95
|
-
overrides = data.get("profiles", {}).get(profile)
|
|
96
|
-
if overrides is None:
|
|
97
|
-
raise ValueError(f"unknown Codex profile: {profile}")
|
|
98
|
-
selected.update(overrides)
|
|
114
|
+
return cls.from_mapping(
|
|
115
|
+
read_codex_config(config_path, profile, use_default_profile), config_path,
|
|
116
|
+
)
|
|
99
117
|
|
|
118
|
+
@classmethod
|
|
119
|
+
def from_mapping(
|
|
120
|
+
cls,
|
|
121
|
+
selected: "typing.Mapping[str, typing.Any]",
|
|
122
|
+
config_path: "typing.Union[str, Path]",
|
|
123
|
+
) -> "ContextConfig":
|
|
124
|
+
path = Path(config_path)
|
|
100
125
|
model_instructions_file = selected.get("model_instructions_file")
|
|
101
126
|
resolved_file = None
|
|
102
127
|
if model_instructions_file:
|
|
@@ -107,6 +132,17 @@ class ContextConfig:
|
|
|
107
132
|
|
|
108
133
|
codex_home = path.parent.resolve()
|
|
109
134
|
codex_home_instructions = _read_first_instruction_file(codex_home)
|
|
135
|
+
multi_agent = selected.get("features", {}).get("multi_agent_v2", {})
|
|
136
|
+
if isinstance(multi_agent, bool):
|
|
137
|
+
multi_agent = {}
|
|
138
|
+
if not isinstance(multi_agent, dict):
|
|
139
|
+
raise ValueError("features.multi_agent_v2 must be a boolean or table")
|
|
140
|
+
max_children = selected.get("agents", {}).get("max_concurrent_threads_per_session")
|
|
141
|
+
if max_children is not None and type(max_children) is not int:
|
|
142
|
+
raise ValueError("agents.max_concurrent_threads_per_session must be an integer")
|
|
143
|
+
max_concurrency = multi_agent.get("max_concurrent_threads_per_session")
|
|
144
|
+
if max_concurrency is None:
|
|
145
|
+
max_concurrency = 16 if max_children is None else max_children + 1
|
|
110
146
|
|
|
111
147
|
return cls(
|
|
112
148
|
base_instructions=_normalize_text(selected.get("base_instructions")),
|
|
@@ -126,6 +162,11 @@ class ContextConfig:
|
|
|
126
162
|
personality=_normalize_text(selected.get("personality")),
|
|
127
163
|
approval_policy=_normalize_text(selected.get("approval_policy")),
|
|
128
164
|
sandbox_mode=_normalize_text(selected.get("sandbox_mode")),
|
|
165
|
+
multi_agent_max_concurrency=max_concurrency,
|
|
166
|
+
multi_agent_root_instructions=multi_agent.get("root_agent_usage_hint_text"),
|
|
167
|
+
multi_agent_subagent_instructions=multi_agent.get("subagent_usage_hint_text"),
|
|
168
|
+
multi_agent_hint=multi_agent.get("multi_agent_mode_hint_text"),
|
|
169
|
+
code_mode_only=selected.get("code_mode_only"),
|
|
129
170
|
)
|
|
130
171
|
|
|
131
172
|
|
|
@@ -140,16 +181,27 @@ class SkillDescriptor:
|
|
|
140
181
|
root: "Path"
|
|
141
182
|
|
|
142
183
|
|
|
184
|
+
@dataclass(frozen=True)
|
|
185
|
+
class ForkContext:
|
|
186
|
+
"""Fixed context blocks anchored to positions in a copied history."""
|
|
187
|
+
|
|
188
|
+
history: "typing.Tuple[ConversationItem, ...]"
|
|
189
|
+
messages: "typing.Tuple[typing.Tuple[int, typing.Tuple[ContextMessage, ...]], ...]"
|
|
190
|
+
base_instructions: "str"
|
|
191
|
+
multi_agent: "typing.Tuple[typing.Union[ContextMessage, None], typing.Union[ContextMessage, None]]"
|
|
192
|
+
|
|
193
|
+
|
|
143
194
|
class ContextManager:
|
|
144
195
|
def __init__(self, config: "ContextConfig") -> "None":
|
|
145
196
|
self.cwd = Path(config.cwd or Path.cwd()).resolve()
|
|
197
|
+
self.agent_path: "typing.Union[str, None]" = None
|
|
146
198
|
self._shell = get_shell_name()
|
|
147
199
|
self._current_date = datetime.now().date().isoformat()
|
|
148
200
|
self._timezone_name = get_timezone_name()
|
|
149
201
|
self._base_instructions_override = _normalize_text(
|
|
150
202
|
config.base_instructions_override
|
|
151
203
|
)
|
|
152
|
-
self.
|
|
204
|
+
self.config = config
|
|
153
205
|
self._include_permissions_instructions = config.include_permissions_instructions
|
|
154
206
|
self._include_skills_instructions = config.include_skills_instructions
|
|
155
207
|
self._network_access = config.network_access
|
|
@@ -164,8 +216,15 @@ class ContextManager:
|
|
|
164
216
|
self._default_base_instructions = DEFAULT_BASE_INSTRUCTIONS_PATH.read_text(
|
|
165
217
|
encoding="utf-8"
|
|
166
218
|
)
|
|
219
|
+
self._developer_defaults = json.loads(
|
|
220
|
+
(Path(__file__).resolve().parent / "prompts" / "developer_messages.json")
|
|
221
|
+
.read_text(encoding="utf-8")
|
|
222
|
+
)
|
|
167
223
|
self._workspace_metadata_turn_id: "typing.Union[str, None]" = None
|
|
168
224
|
self._workspace_metadata_cache: "typing.Union[JSONDict, None]" = None
|
|
225
|
+
self._fork_context: "typing.Union[ForkContext, None]" = None
|
|
226
|
+
self._last_context: "typing.Union[ForkContext, None]" = None
|
|
227
|
+
self._fork_local_context: "typing.Tuple[ContextMessage, ...]" = ()
|
|
169
228
|
|
|
170
229
|
def get_turn_metadata(self, turn_id: "str") -> "JSONDict":
|
|
171
230
|
metadata: "JSONDict" = {"turn_id": turn_id}
|
|
@@ -177,7 +236,7 @@ class ContextManager:
|
|
|
177
236
|
and self._workspace_metadata_cache is not None
|
|
178
237
|
):
|
|
179
238
|
metadata.update(self._workspace_metadata_cache)
|
|
180
|
-
metadata["sandbox"] = get_sandbox_tag(self.
|
|
239
|
+
metadata["sandbox"] = get_sandbox_tag(self.config.sandbox_mode)
|
|
181
240
|
return metadata
|
|
182
241
|
|
|
183
242
|
def build_prompt(
|
|
@@ -186,32 +245,141 @@ class ContextManager:
|
|
|
186
245
|
tools: "typing.List[ToolSpec]",
|
|
187
246
|
parallel_tool_calls: "bool",
|
|
188
247
|
turn_id: "typing.Union[str, None]" = None,
|
|
248
|
+
reasoning_effort: "typing.Union[str, None]" = None,
|
|
249
|
+
capture_context: "bool" = True,
|
|
250
|
+
session_id: "typing.Union[str, None]" = None,
|
|
189
251
|
) -> "Prompt":
|
|
190
|
-
input_items: "typing.List[ConversationItem]" = []
|
|
191
252
|
turn_metadata = self.get_turn_metadata(turn_id) if turn_id is not None else None
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
253
|
+
multi_agent = self._build_multi_agent_context(tools, reasoning_effort)
|
|
254
|
+
if self._fork_context is None:
|
|
255
|
+
messages = ((0, self._build_initial_context(multi_agent)),)
|
|
256
|
+
else:
|
|
257
|
+
messages = self._fork_context_messages(history)
|
|
258
|
+
if capture_context:
|
|
259
|
+
current_context = self._build_initial_context(multi_agent)
|
|
260
|
+
updates = tuple(
|
|
261
|
+
item for item in current_context
|
|
262
|
+
if item not in self._fork_local_context
|
|
263
|
+
or (
|
|
264
|
+
item is multi_agent[1]
|
|
265
|
+
and multi_agent != self._fork_context.multi_agent
|
|
266
|
+
)
|
|
267
|
+
)
|
|
268
|
+
if updates:
|
|
269
|
+
# Keep inherited blocks intact when the child's cwd, model,
|
|
270
|
+
# effort or instructions change after the fork.
|
|
271
|
+
messages += ((len(history), updates),)
|
|
272
|
+
self._fork_context = ForkContext(
|
|
273
|
+
tuple(history), messages, self.resolve_base_instructions(),
|
|
274
|
+
multi_agent,
|
|
275
|
+
)
|
|
276
|
+
self._fork_local_context = current_context
|
|
277
|
+
input_items: "typing.List[ConversationItem]" = []
|
|
278
|
+
position = 0
|
|
279
|
+
for offset, block in messages:
|
|
280
|
+
input_items.extend(history[position:offset])
|
|
281
|
+
input_items.extend(block)
|
|
282
|
+
position = offset
|
|
283
|
+
input_items.extend(history[position:])
|
|
284
|
+
if self._fork_context is not None:
|
|
285
|
+
input_items = _normalize_fork_calls(input_items)
|
|
286
|
+
base_instructions = self.resolve_base_instructions()
|
|
287
|
+
if capture_context:
|
|
288
|
+
self._last_context = ForkContext(
|
|
289
|
+
tuple(history), messages, base_instructions, multi_agent,
|
|
290
|
+
)
|
|
199
291
|
return Prompt(
|
|
200
292
|
input=input_items,
|
|
201
293
|
tools=tools,
|
|
202
294
|
parallel_tool_calls=parallel_tool_calls,
|
|
203
|
-
base_instructions=
|
|
295
|
+
base_instructions=base_instructions,
|
|
204
296
|
turn_id=turn_id,
|
|
205
297
|
turn_metadata=turn_metadata,
|
|
298
|
+
session_id=session_id,
|
|
206
299
|
)
|
|
207
300
|
|
|
301
|
+
def _build_initial_context(self, multi_agent):
|
|
302
|
+
messages = []
|
|
303
|
+
developer_message = self._build_developer_message()
|
|
304
|
+
if developer_message is not None:
|
|
305
|
+
messages.append(developer_message)
|
|
306
|
+
messages.extend(message for message in multi_agent if message is not None)
|
|
307
|
+
messages.extend(self._build_contextual_user_messages())
|
|
308
|
+
return tuple(messages)
|
|
309
|
+
|
|
310
|
+
def snapshot_for_fork(self, history, tools, reasoning_effort) -> "ForkContext":
|
|
311
|
+
if self._last_context is None:
|
|
312
|
+
self.build_prompt(history, tools, False, reasoning_effort=reasoning_effort)
|
|
313
|
+
context = self._last_context
|
|
314
|
+
# Calls emitted since the last sample extend its history without changing
|
|
315
|
+
# the fixed prefix. Copy items and blocks together to keep child ownership.
|
|
316
|
+
return deepcopy(ForkContext(
|
|
317
|
+
tuple(history), context.messages, context.base_instructions,
|
|
318
|
+
context.multi_agent,
|
|
319
|
+
))
|
|
320
|
+
|
|
321
|
+
def inherit_fork_context(self, context: "ForkContext", tools, reasoning_effort):
|
|
322
|
+
handoff = [ContextMessage(
|
|
323
|
+
role="developer",
|
|
324
|
+
text=(
|
|
325
|
+
"You are now a newly spawned child agent. The preceding conversation "
|
|
326
|
+
"is inherited parent context. Follow your own role, identity, and "
|
|
327
|
+
"task below; earlier identities, tasks, and action-specific approvals "
|
|
328
|
+
"belong to your ancestors. Inherited tool calls are historical "
|
|
329
|
+
"records; live tool sessions and process handles are not inherited. "
|
|
330
|
+
"Report your result to your parent."
|
|
331
|
+
),
|
|
332
|
+
)]
|
|
333
|
+
multi_agent = self._build_multi_agent_context(tools, reasoning_effort)
|
|
334
|
+
role, mode = multi_agent
|
|
335
|
+
if role is not None:
|
|
336
|
+
handoff.append(role)
|
|
337
|
+
# Upstream reasserts the mode when either its text or the role changes.
|
|
338
|
+
if mode is not None and multi_agent != context.multi_agent:
|
|
339
|
+
handoff.append(mode)
|
|
340
|
+
self._fork_context = replace(
|
|
341
|
+
context,
|
|
342
|
+
messages=context.messages + ((len(context.history), tuple(handoff)),),
|
|
343
|
+
multi_agent=multi_agent,
|
|
344
|
+
)
|
|
345
|
+
self._base_instructions_override = context.base_instructions
|
|
346
|
+
self.config = replace(
|
|
347
|
+
self.config, base_instructions_override=context.base_instructions,
|
|
348
|
+
)
|
|
349
|
+
self._fork_local_context = self._build_initial_context(multi_agent)
|
|
350
|
+
self._last_context = None
|
|
351
|
+
|
|
352
|
+
def reset_history_context(self) -> "None":
|
|
353
|
+
"""Discard inherited context only when active history is replaced."""
|
|
354
|
+
self._fork_context = None
|
|
355
|
+
self._last_context = None
|
|
356
|
+
self._fork_local_context = ()
|
|
357
|
+
|
|
358
|
+
def _fork_context_messages(self, history):
|
|
359
|
+
context = self._fork_context
|
|
360
|
+
messages = []
|
|
361
|
+
original_position = 0
|
|
362
|
+
position = 0
|
|
363
|
+
for offset, block in context.messages:
|
|
364
|
+
while original_position < offset:
|
|
365
|
+
if (
|
|
366
|
+
position < len(history)
|
|
367
|
+
and history[position] is context.history[original_position]
|
|
368
|
+
):
|
|
369
|
+
position += 1
|
|
370
|
+
original_position += 1
|
|
371
|
+
messages.append((position, block))
|
|
372
|
+
# Compaction retries may prune inherited call/result pairs. Anchor blocks
|
|
373
|
+
# to the surviving items, without replaying removed history from a snapshot.
|
|
374
|
+
return tuple(messages)
|
|
375
|
+
|
|
208
376
|
def resolve_base_instructions(self) -> "str":
|
|
209
377
|
if self._base_instructions_override is not None:
|
|
210
378
|
return self._base_instructions_override
|
|
211
|
-
if self.
|
|
212
|
-
return self.
|
|
213
|
-
if self.
|
|
214
|
-
return self.
|
|
379
|
+
if self.config.base_instructions is not None:
|
|
380
|
+
return self.config.base_instructions
|
|
381
|
+
if self.config.model_instructions_file is not None:
|
|
382
|
+
return self.config.model_instructions_file.read_text(
|
|
215
383
|
encoding="utf-8",
|
|
216
384
|
errors="replace",
|
|
217
385
|
).strip()
|
|
@@ -220,9 +388,15 @@ class ContextManager:
|
|
|
220
388
|
return resolved
|
|
221
389
|
return self._default_base_instructions
|
|
222
390
|
|
|
391
|
+
def resolve_code_mode_only(self) -> "bool":
|
|
392
|
+
if self.config.code_mode_only is not None:
|
|
393
|
+
return self.config.code_mode_only
|
|
394
|
+
metadata = model_metadata(self.config.model)
|
|
395
|
+
return metadata is not None and metadata.get("tool_mode") == "code_mode_only"
|
|
396
|
+
|
|
223
397
|
def resolve_model_max_context_window(self) -> "typing.Union[int, None]":
|
|
224
|
-
metadata = model_metadata(self.
|
|
225
|
-
context_window = self.
|
|
398
|
+
metadata = model_metadata(self.config.model)
|
|
399
|
+
context_window = self.config.model_context_window
|
|
226
400
|
if context_window is None and metadata is not None:
|
|
227
401
|
context_window = _normalize_int(metadata.get("context_window"))
|
|
228
402
|
return context_window
|
|
@@ -231,7 +405,7 @@ class ContextManager:
|
|
|
231
405
|
context_window = self.resolve_model_max_context_window()
|
|
232
406
|
if context_window is None:
|
|
233
407
|
return None
|
|
234
|
-
metadata = model_metadata(self.
|
|
408
|
+
metadata = model_metadata(self.config.model)
|
|
235
409
|
effective_percent = None
|
|
236
410
|
if metadata is not None:
|
|
237
411
|
effective_percent = _normalize_int(
|
|
@@ -242,7 +416,7 @@ class ContextManager:
|
|
|
242
416
|
return context_window * max(effective_percent, 0) // 100
|
|
243
417
|
|
|
244
418
|
def set_model(self, model: "str") -> "None":
|
|
245
|
-
self.
|
|
419
|
+
self.config = replace(self.config, model=model)
|
|
246
420
|
|
|
247
421
|
def set_cwd(self, cwd: "typing.Union[str, Path]") -> "None":
|
|
248
422
|
path = Path(cwd).expanduser()
|
|
@@ -250,15 +424,15 @@ class ContextManager:
|
|
|
250
424
|
if not path.is_dir():
|
|
251
425
|
raise NotADirectoryError(str(path))
|
|
252
426
|
self.cwd = path
|
|
253
|
-
self.
|
|
427
|
+
self.config = replace(self.config, cwd=path)
|
|
254
428
|
self._workspace_metadata_turn_id = None
|
|
255
429
|
self._workspace_metadata_cache = None
|
|
256
430
|
|
|
257
431
|
def resolve_auto_compact_token_limit(self) -> "typing.Union[int, None]":
|
|
258
|
-
if self.
|
|
259
|
-
return self.
|
|
432
|
+
if self.config.model_auto_compact_token_limit is not None:
|
|
433
|
+
return self.config.model_auto_compact_token_limit
|
|
260
434
|
|
|
261
|
-
model_slug = self.
|
|
435
|
+
model_slug = self.config.model
|
|
262
436
|
if model_slug is None:
|
|
263
437
|
return None
|
|
264
438
|
metadata = model_metadata(model_slug)
|
|
@@ -267,7 +441,7 @@ class ContextManager:
|
|
|
267
441
|
return _normalize_int(metadata.get("auto_compact_token_limit"))
|
|
268
442
|
|
|
269
443
|
def _resolve_model_instructions(self) -> "typing.Union[str, None]":
|
|
270
|
-
model_slug = self.
|
|
444
|
+
model_slug = self.config.model
|
|
271
445
|
if model_slug is None:
|
|
272
446
|
return None
|
|
273
447
|
metadata = model_metadata(model_slug)
|
|
@@ -281,7 +455,7 @@ class ContextManager:
|
|
|
281
455
|
if isinstance(template, str):
|
|
282
456
|
personality_message = _resolve_personality_message(
|
|
283
457
|
variables,
|
|
284
|
-
self.
|
|
458
|
+
self.config.personality,
|
|
285
459
|
)
|
|
286
460
|
return template.replace(PERSONALITY_PLACEHOLDER, personality_message)
|
|
287
461
|
|
|
@@ -292,8 +466,8 @@ class ContextManager:
|
|
|
292
466
|
|
|
293
467
|
def _build_developer_message(self) -> "typing.Union[ContextMessage, None]":
|
|
294
468
|
sections: "typing.List[str]" = []
|
|
295
|
-
if self.
|
|
296
|
-
sections.append(self.
|
|
469
|
+
if self.config.developer_instructions is not None:
|
|
470
|
+
sections.append(self.config.developer_instructions)
|
|
297
471
|
if self._include_skills_instructions:
|
|
298
472
|
skills = self._build_skills_instructions()
|
|
299
473
|
if skills is not None:
|
|
@@ -302,6 +476,13 @@ class ContextManager:
|
|
|
302
476
|
permissions = self._build_permissions_instructions()
|
|
303
477
|
if permissions is not None:
|
|
304
478
|
sections.append(permissions)
|
|
479
|
+
default_instructions = self._model_message("collaboration_modes", "default")
|
|
480
|
+
if default_instructions:
|
|
481
|
+
sections.append(
|
|
482
|
+
"<collaboration_mode>{0}</collaboration_mode>".format(
|
|
483
|
+
default_instructions
|
|
484
|
+
)
|
|
485
|
+
)
|
|
305
486
|
if not sections:
|
|
306
487
|
return None
|
|
307
488
|
return ContextMessage(
|
|
@@ -309,9 +490,93 @@ class ContextManager:
|
|
|
309
490
|
content_items=tuple(_input_text_item(section) for section in sections),
|
|
310
491
|
)
|
|
311
492
|
|
|
493
|
+
def _model_message(self, *keys):
|
|
494
|
+
metadata = model_metadata(self.config.model)
|
|
495
|
+
value = metadata.get("model_messages") if metadata is not None else None
|
|
496
|
+
for key in keys:
|
|
497
|
+
if value is None:
|
|
498
|
+
return None
|
|
499
|
+
value = value.get(key)
|
|
500
|
+
return value
|
|
501
|
+
|
|
502
|
+
def _build_multi_agent_messages(self, tools, reasoning_effort):
|
|
503
|
+
return [
|
|
504
|
+
message for message in self._build_multi_agent_context(tools, reasoning_effort)
|
|
505
|
+
if message is not None
|
|
506
|
+
]
|
|
507
|
+
|
|
508
|
+
def _build_multi_agent_context(self, tools, reasoning_effort):
|
|
509
|
+
if self.agent_path is None:
|
|
510
|
+
return None, None
|
|
511
|
+
defaults = self._developer_defaults["multi_agent"]
|
|
512
|
+
root = self.agent_path == "/root"
|
|
513
|
+
role = "root" if root else "subagent"
|
|
514
|
+
configured = (
|
|
515
|
+
self.config.multi_agent_root_instructions
|
|
516
|
+
if root else self.config.multi_agent_subagent_instructions
|
|
517
|
+
)
|
|
518
|
+
if configured is not None:
|
|
519
|
+
role_text = configured
|
|
520
|
+
else:
|
|
521
|
+
base = self._model_message("multi_agent", "role", role)
|
|
522
|
+
marked = base is not None
|
|
523
|
+
if base is None:
|
|
524
|
+
base = defaults[role]
|
|
525
|
+
role_text = ""
|
|
526
|
+
if base:
|
|
527
|
+
exec_guidance = (
|
|
528
|
+
defaults["exec"] + "\n\n"
|
|
529
|
+
if any(
|
|
530
|
+
tool.name == "exec" and tool.namespace in (None, "functions")
|
|
531
|
+
for tool in tools
|
|
532
|
+
) and any(tool.namespace == "collaboration" for tool in tools)
|
|
533
|
+
else ""
|
|
534
|
+
)
|
|
535
|
+
wait_guidance = (
|
|
536
|
+
defaults["wait"] + "\n\n"
|
|
537
|
+
if any(tool.name == "wait_agent" for tool in tools) else ""
|
|
538
|
+
)
|
|
539
|
+
role_text = (
|
|
540
|
+
"{base}\n{shared}\n{exec}{wait}"
|
|
541
|
+
"There are {limit} available concurrency slots, meaning that "
|
|
542
|
+
"up to {limit} agents can be active at once, including you."
|
|
543
|
+
).format(
|
|
544
|
+
base=base, shared=defaults["shared"],
|
|
545
|
+
exec=exec_guidance, wait=wait_guidance,
|
|
546
|
+
limit=self.config.multi_agent_max_concurrency,
|
|
547
|
+
)
|
|
548
|
+
spawn = next(
|
|
549
|
+
(tool for tool in tools if tool.name == "spawn_agent"), None,
|
|
550
|
+
)
|
|
551
|
+
if spawn is not None and "model" in spawn.input_schema["properties"]:
|
|
552
|
+
role_text += "\n\n" + defaults["model_overrides"]
|
|
553
|
+
if marked:
|
|
554
|
+
role_text = "<multi_agent_role>{0}</multi_agent_role>".format(
|
|
555
|
+
role_text
|
|
556
|
+
)
|
|
557
|
+
role_message = (
|
|
558
|
+
ContextMessage(role="developer", text=role_text) if role_text else None
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
hint = self.config.multi_agent_hint
|
|
562
|
+
if hint is None:
|
|
563
|
+
hint = self._model_message("multi_agent", "mode", "hint_text")
|
|
564
|
+
if hint is None:
|
|
565
|
+
mode = "proactive" if reasoning_effort == "ultra" else "explicit"
|
|
566
|
+
hint = self._model_message("multi_agent", "mode", mode)
|
|
567
|
+
if hint is None:
|
|
568
|
+
hint = defaults[mode]
|
|
569
|
+
mode_message = (
|
|
570
|
+
ContextMessage(
|
|
571
|
+
role="developer",
|
|
572
|
+
text="<multi_agent_mode>{0}</multi_agent_mode>".format(hint),
|
|
573
|
+
) if hint else None
|
|
574
|
+
)
|
|
575
|
+
return role_message, mode_message
|
|
576
|
+
|
|
312
577
|
def _build_permissions_instructions(self) -> "typing.Union[str, None]":
|
|
313
|
-
sandbox_mode = self.
|
|
314
|
-
approval_policy = self.
|
|
578
|
+
sandbox_mode = self.config.sandbox_mode or "danger-full-access"
|
|
579
|
+
approval_policy = self.config.approval_policy or "never"
|
|
315
580
|
sandbox_prompt_name = sandbox_mode.replace("-", "_")
|
|
316
581
|
sandbox_prompt_path = (
|
|
317
582
|
PERMISSIONS_SANDBOX_PROMPTS_PATH / f"{sandbox_prompt_name}.md"
|
|
@@ -363,7 +628,7 @@ class ContextManager:
|
|
|
363
628
|
skill.path_to_skill_md.relative_to(skill.root).as_posix(),
|
|
364
629
|
)
|
|
365
630
|
lines.append(f"- {skill.name}: {skill.description} (file: {path_str})")
|
|
366
|
-
metadata = model_metadata(self.
|
|
631
|
+
metadata = model_metadata(self.config.model)
|
|
367
632
|
if metadata is None or metadata.get("include_skills_usage_instructions", True):
|
|
368
633
|
lines.append("### How to use skills")
|
|
369
634
|
lines.extend(SKILLS_GUIDANCE.splitlines())
|
|
@@ -371,7 +636,7 @@ class ContextManager:
|
|
|
371
636
|
return f"{SKILLS_OPEN_TAG}\n{body}\n{SKILLS_CLOSE_TAG}"
|
|
372
637
|
|
|
373
638
|
def _discover_skills(self) -> "typing.List[SkillDescriptor]":
|
|
374
|
-
codex_home = self.
|
|
639
|
+
codex_home = self.config.codex_home
|
|
375
640
|
if codex_home is None:
|
|
376
641
|
return []
|
|
377
642
|
|
|
@@ -421,10 +686,10 @@ class ContextManager:
|
|
|
421
686
|
|
|
422
687
|
def _merged_user_instructions(self) -> "typing.Union[str, None]":
|
|
423
688
|
parts: "typing.List[str]" = []
|
|
424
|
-
if self.
|
|
425
|
-
parts.append(self.
|
|
426
|
-
if self.
|
|
427
|
-
parts.append(self.
|
|
689
|
+
if self.config.user_instructions is not None:
|
|
690
|
+
parts.append(self.config.user_instructions)
|
|
691
|
+
if self.config.codex_home_instructions is not None:
|
|
692
|
+
parts.append(self.config.codex_home_instructions)
|
|
428
693
|
|
|
429
694
|
project_doc = self._read_project_docs()
|
|
430
695
|
if project_doc is not None:
|
|
@@ -437,7 +702,7 @@ class ContextManager:
|
|
|
437
702
|
|
|
438
703
|
def _read_project_docs(self) -> "typing.Union[str, None]":
|
|
439
704
|
docs: "typing.List[str]" = []
|
|
440
|
-
remaining = self.
|
|
705
|
+
remaining = self.config.project_doc_max_bytes
|
|
441
706
|
for path in self._discover_project_doc_paths():
|
|
442
707
|
text = path.read_text(encoding="utf-8", errors="replace")
|
|
443
708
|
if not text.strip():
|
|
@@ -498,7 +763,7 @@ class ContextManager:
|
|
|
498
763
|
f" <current_date>{self._current_date}</current_date>",
|
|
499
764
|
f" <timezone>{self._timezone_name}</timezone>",
|
|
500
765
|
]
|
|
501
|
-
sandbox_mode = self.
|
|
766
|
+
sandbox_mode = self.config.sandbox_mode or "danger-full-access"
|
|
502
767
|
if sandbox_mode == "danger-full-access":
|
|
503
768
|
permissions = (
|
|
504
769
|
'<permission_profile type="disabled"><file_system type="unrestricted" />'
|
|
@@ -534,6 +799,44 @@ class ContextManager:
|
|
|
534
799
|
return "\n".join(lines)
|
|
535
800
|
|
|
536
801
|
|
|
802
|
+
def _normalize_fork_calls(items):
|
|
803
|
+
call_ids = {
|
|
804
|
+
(item.tool_type, item.call_id)
|
|
805
|
+
for item in items if isinstance(item, ToolCall)
|
|
806
|
+
}
|
|
807
|
+
result_ids = {
|
|
808
|
+
(item.tool_type, item.call_id)
|
|
809
|
+
for item in items if isinstance(item, ToolResult)
|
|
810
|
+
}
|
|
811
|
+
normalized = []
|
|
812
|
+
for item in items:
|
|
813
|
+
if (
|
|
814
|
+
isinstance(item, ToolResult)
|
|
815
|
+
and (item.tool_type, item.call_id) not in call_ids
|
|
816
|
+
):
|
|
817
|
+
continue
|
|
818
|
+
normalized.append(item)
|
|
819
|
+
if (
|
|
820
|
+
isinstance(item, ToolCall)
|
|
821
|
+
and (item.tool_type, item.call_id) not in result_ids
|
|
822
|
+
):
|
|
823
|
+
prefix = "ctco" if item.tool_type == "custom" else "fco"
|
|
824
|
+
output_id = None
|
|
825
|
+
if item.id:
|
|
826
|
+
output_id = "{0}_{1}".format(
|
|
827
|
+
prefix,
|
|
828
|
+
uuid5(
|
|
829
|
+
UUID("90d38d3e-6a5b-4d52-bfe2-2f1e634bfac4"),
|
|
830
|
+
prefix + ":" + item.id,
|
|
831
|
+
),
|
|
832
|
+
)
|
|
833
|
+
normalized.append(ToolResult(
|
|
834
|
+
call_id=item.call_id, name=None, output="aborted",
|
|
835
|
+
tool_type=item.tool_type, id=output_id,
|
|
836
|
+
))
|
|
837
|
+
return normalized
|
|
838
|
+
|
|
839
|
+
|
|
537
840
|
def _input_text_item(text: "str") -> "JSONDict":
|
|
538
841
|
return {"type": "input_text", "text": text}
|
|
539
842
|
|
|
@@ -643,3 +946,18 @@ def _parse_skill_descriptor(
|
|
|
643
946
|
scope_rank=scope_rank,
|
|
644
947
|
root=root.resolve(),
|
|
645
948
|
)
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
def build_goal_message(goal, budget_limited=False):
|
|
952
|
+
template_name = "budget_limit.md" if budget_limited else "continuation.md"
|
|
953
|
+
template = (
|
|
954
|
+
Path(__file__).resolve().parent / "prompts" / "goals" / template_name
|
|
955
|
+
).read_text(encoding="utf-8").rstrip("\n")
|
|
956
|
+
budget = goal.get("tokenBudget")
|
|
957
|
+
return UserMessage(template.format(
|
|
958
|
+
objective=escape(goal["objective"]),
|
|
959
|
+
tokens_used=goal["tokensUsed"],
|
|
960
|
+
time_used_seconds=goal["timeUsedSeconds"],
|
|
961
|
+
token_budget="none" if budget is None else budget,
|
|
962
|
+
remaining_tokens="unbounded" if budget is None else max(0, budget - goal["tokensUsed"]),
|
|
963
|
+
))
|