python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycodex/__init__.py +22 -12
- pycodex/agent.py +89 -74
- pycodex/bootstrap.py +37 -251
- pycodex/cli.py +19 -28
- pycodex/config.py +36 -0
- pycodex/context.py +368 -51
- pycodex/events.py +14 -187
- pycodex/model.py +197 -95
- pycodex/multi_agents.py +401 -0
- pycodex/portable/__init__.py +8 -6
- pycodex/portable/client.py +24 -39
- pycodex/portable/protocol.py +28 -0
- pycodex/portable/server.py +3 -3
- pycodex/prompts/developer_messages.json +13 -0
- pycodex/prompts/goals/budget_limit.md +19 -0
- pycodex/prompts/goals/continuation.md +56 -0
- pycodex/prompts/models.json +1143 -200
- pycodex/protocol.py +81 -15
- pycodex/runtime.py +370 -226
- pycodex/tools/__init__.py +102 -10
- pycodex/tools/agent_tool_schemas.py +0 -38
- pycodex/tools/apply_patch_tool.py +17 -34
- pycodex/tools/base_tool.py +63 -35
- pycodex/tools/clock_manager.py +182 -0
- pycodex/tools/clock_tool.py +58 -187
- pycodex/tools/code_mode_manager.py +165 -246
- pycodex/tools/exec_command_tool.py +0 -18
- pycodex/tools/exec_runtime.py +332 -0
- pycodex/tools/exec_tool.py +74 -31
- pycodex/tools/followup_task_tool.py +44 -0
- pycodex/tools/goal_manager.py +205 -0
- pycodex/tools/goal_tool.py +126 -0
- pycodex/tools/interrupt_agent_tool.py +48 -0
- pycodex/tools/list_agents_tool.py +66 -0
- pycodex/tools/python_tool_schema.py +141 -0
- pycodex/tools/request_permissions_tool.py +1 -0
- pycodex/tools/runtime_services.py +122 -450
- pycodex/tools/send_message_tool.py +42 -0
- pycodex/tools/spawn_agent_tool.py +55 -94
- pycodex/tools/unified_exec_manager.py +26 -35
- pycodex/tools/wait_agent_tool.py +46 -66
- pycodex/tools/wait_tool.py +24 -13
- pycodex/tools/web_search_tool.py +1 -0
- pycodex/utils/codex_config.py +105 -0
- pycodex/utils/compactor.py +4 -0
- pycodex/utils/compat.py +43 -2
- pycodex/utils/doctor.py +5 -4
- pycodex/utils/dotenv.py +0 -7
- pycodex/utils/event_helpers.py +143 -13
- pycodex/utils/history.py +59 -0
- pycodex/utils/session_persist.py +104 -48
- python_codex-0.6.1.dist-info/METADATA +201 -0
- python_codex-0.6.1.dist-info/RECORD +106 -0
- responses_server/__init__.py +2 -0
- responses_server/app.py +10 -7
- responses_server/config.py +6 -12
- responses_server/gemini_api.py +333 -0
- responses_server/messages_api.py +9 -1
- responses_server/payload_processors.py +4 -4
- responses_server/request_translation.py +486 -0
- responses_server/server.py +31 -24
- responses_server/stream_events.py +124 -0
- responses_server/stream_router.py +48 -830
- responses_server/tools/custom_adapter.py +29 -29
- responses_server/tools/web_search.py +3 -0
- responses_server/transport.py +388 -0
- pycodex/tools/close_agent_tool.py +0 -60
- pycodex/tools/exec_runtime.js +0 -161
- pycodex/tools/request_user_input_tool.py +0 -102
- pycodex/tools/resume_agent_tool.py +0 -54
- pycodex/tools/send_input_tool.py +0 -110
- python_codex-0.5.2.dist-info/METADATA +0 -262
- python_codex-0.5.2.dist-info/RECORD +0 -90
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
pycodex/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,140 @@ 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
|
+
input_items = _normalize_tool_calls(input_items, self._fork_context is not None)
|
|
285
|
+
base_instructions = self.resolve_base_instructions()
|
|
286
|
+
if capture_context:
|
|
287
|
+
self._last_context = ForkContext(
|
|
288
|
+
tuple(history), messages, base_instructions, multi_agent,
|
|
289
|
+
)
|
|
199
290
|
return Prompt(
|
|
200
291
|
input=input_items,
|
|
201
292
|
tools=tools,
|
|
202
293
|
parallel_tool_calls=parallel_tool_calls,
|
|
203
|
-
base_instructions=
|
|
294
|
+
base_instructions=base_instructions,
|
|
204
295
|
turn_id=turn_id,
|
|
205
296
|
turn_metadata=turn_metadata,
|
|
297
|
+
session_id=session_id,
|
|
206
298
|
)
|
|
207
299
|
|
|
300
|
+
def _build_initial_context(self, multi_agent):
|
|
301
|
+
messages = []
|
|
302
|
+
developer_message = self._build_developer_message()
|
|
303
|
+
if developer_message is not None:
|
|
304
|
+
messages.append(developer_message)
|
|
305
|
+
messages.extend(message for message in multi_agent if message is not None)
|
|
306
|
+
messages.extend(self._build_contextual_user_messages())
|
|
307
|
+
return tuple(messages)
|
|
308
|
+
|
|
309
|
+
def snapshot_for_fork(self, history, tools, reasoning_effort) -> "ForkContext":
|
|
310
|
+
if self._last_context is None:
|
|
311
|
+
self.build_prompt(history, tools, False, reasoning_effort=reasoning_effort)
|
|
312
|
+
context = self._last_context
|
|
313
|
+
# Calls emitted since the last sample extend its history without changing
|
|
314
|
+
# the fixed prefix. Copy items and blocks together to keep child ownership.
|
|
315
|
+
return deepcopy(ForkContext(
|
|
316
|
+
tuple(history), context.messages, context.base_instructions,
|
|
317
|
+
context.multi_agent,
|
|
318
|
+
))
|
|
319
|
+
|
|
320
|
+
def inherit_fork_context(self, context: "ForkContext", tools, reasoning_effort):
|
|
321
|
+
handoff = [ContextMessage(
|
|
322
|
+
role="developer",
|
|
323
|
+
text=(
|
|
324
|
+
"You are now a newly spawned child agent. The preceding conversation "
|
|
325
|
+
"is inherited parent context. Follow your own role, identity, and "
|
|
326
|
+
"task below; earlier identities, tasks, and action-specific approvals "
|
|
327
|
+
"belong to your ancestors. Inherited tool calls are historical "
|
|
328
|
+
"records; live tool sessions and process handles are not inherited. "
|
|
329
|
+
"Report your result to your parent."
|
|
330
|
+
),
|
|
331
|
+
)]
|
|
332
|
+
multi_agent = self._build_multi_agent_context(tools, reasoning_effort)
|
|
333
|
+
role, mode = multi_agent
|
|
334
|
+
if role is not None:
|
|
335
|
+
handoff.append(role)
|
|
336
|
+
# Upstream reasserts the mode when either its text or the role changes.
|
|
337
|
+
if mode is not None and multi_agent != context.multi_agent:
|
|
338
|
+
handoff.append(mode)
|
|
339
|
+
self._fork_context = replace(
|
|
340
|
+
context,
|
|
341
|
+
messages=context.messages + ((len(context.history), tuple(handoff)),),
|
|
342
|
+
multi_agent=multi_agent,
|
|
343
|
+
)
|
|
344
|
+
self._base_instructions_override = context.base_instructions
|
|
345
|
+
self.config = replace(
|
|
346
|
+
self.config, base_instructions_override=context.base_instructions,
|
|
347
|
+
)
|
|
348
|
+
self._fork_local_context = self._build_initial_context(multi_agent)
|
|
349
|
+
self._last_context = None
|
|
350
|
+
|
|
351
|
+
def reset_history_context(self) -> "None":
|
|
352
|
+
"""Discard inherited context only when active history is replaced."""
|
|
353
|
+
self._fork_context = None
|
|
354
|
+
self._last_context = None
|
|
355
|
+
self._fork_local_context = ()
|
|
356
|
+
|
|
357
|
+
def _fork_context_messages(self, history):
|
|
358
|
+
context = self._fork_context
|
|
359
|
+
messages = []
|
|
360
|
+
original_position = 0
|
|
361
|
+
position = 0
|
|
362
|
+
for offset, block in context.messages:
|
|
363
|
+
while original_position < offset:
|
|
364
|
+
if (
|
|
365
|
+
position < len(history)
|
|
366
|
+
and history[position] is context.history[original_position]
|
|
367
|
+
):
|
|
368
|
+
position += 1
|
|
369
|
+
original_position += 1
|
|
370
|
+
messages.append((position, block))
|
|
371
|
+
# Compaction retries may prune inherited call/result pairs. Anchor blocks
|
|
372
|
+
# to the surviving items, without replaying removed history from a snapshot.
|
|
373
|
+
return tuple(messages)
|
|
374
|
+
|
|
208
375
|
def resolve_base_instructions(self) -> "str":
|
|
209
376
|
if self._base_instructions_override is not None:
|
|
210
377
|
return self._base_instructions_override
|
|
211
|
-
if self.
|
|
212
|
-
return self.
|
|
213
|
-
if self.
|
|
214
|
-
return self.
|
|
378
|
+
if self.config.base_instructions is not None:
|
|
379
|
+
return self.config.base_instructions
|
|
380
|
+
if self.config.model_instructions_file is not None:
|
|
381
|
+
return self.config.model_instructions_file.read_text(
|
|
215
382
|
encoding="utf-8",
|
|
216
383
|
errors="replace",
|
|
217
384
|
).strip()
|
|
@@ -220,9 +387,15 @@ class ContextManager:
|
|
|
220
387
|
return resolved
|
|
221
388
|
return self._default_base_instructions
|
|
222
389
|
|
|
390
|
+
def resolve_code_mode_only(self) -> "bool":
|
|
391
|
+
if self.config.code_mode_only is not None:
|
|
392
|
+
return self.config.code_mode_only
|
|
393
|
+
metadata = model_metadata(self.config.model)
|
|
394
|
+
return metadata is not None and metadata.get("tool_mode") == "code_mode_only"
|
|
395
|
+
|
|
223
396
|
def resolve_model_max_context_window(self) -> "typing.Union[int, None]":
|
|
224
|
-
metadata = model_metadata(self.
|
|
225
|
-
context_window = self.
|
|
397
|
+
metadata = model_metadata(self.config.model)
|
|
398
|
+
context_window = self.config.model_context_window
|
|
226
399
|
if context_window is None and metadata is not None:
|
|
227
400
|
context_window = _normalize_int(metadata.get("context_window"))
|
|
228
401
|
return context_window
|
|
@@ -231,7 +404,7 @@ class ContextManager:
|
|
|
231
404
|
context_window = self.resolve_model_max_context_window()
|
|
232
405
|
if context_window is None:
|
|
233
406
|
return None
|
|
234
|
-
metadata = model_metadata(self.
|
|
407
|
+
metadata = model_metadata(self.config.model)
|
|
235
408
|
effective_percent = None
|
|
236
409
|
if metadata is not None:
|
|
237
410
|
effective_percent = _normalize_int(
|
|
@@ -242,7 +415,7 @@ class ContextManager:
|
|
|
242
415
|
return context_window * max(effective_percent, 0) // 100
|
|
243
416
|
|
|
244
417
|
def set_model(self, model: "str") -> "None":
|
|
245
|
-
self.
|
|
418
|
+
self.config = replace(self.config, model=model)
|
|
246
419
|
|
|
247
420
|
def set_cwd(self, cwd: "typing.Union[str, Path]") -> "None":
|
|
248
421
|
path = Path(cwd).expanduser()
|
|
@@ -250,15 +423,15 @@ class ContextManager:
|
|
|
250
423
|
if not path.is_dir():
|
|
251
424
|
raise NotADirectoryError(str(path))
|
|
252
425
|
self.cwd = path
|
|
253
|
-
self.
|
|
426
|
+
self.config = replace(self.config, cwd=path)
|
|
254
427
|
self._workspace_metadata_turn_id = None
|
|
255
428
|
self._workspace_metadata_cache = None
|
|
256
429
|
|
|
257
430
|
def resolve_auto_compact_token_limit(self) -> "typing.Union[int, None]":
|
|
258
|
-
if self.
|
|
259
|
-
return self.
|
|
431
|
+
if self.config.model_auto_compact_token_limit is not None:
|
|
432
|
+
return self.config.model_auto_compact_token_limit
|
|
260
433
|
|
|
261
|
-
model_slug = self.
|
|
434
|
+
model_slug = self.config.model
|
|
262
435
|
if model_slug is None:
|
|
263
436
|
return None
|
|
264
437
|
metadata = model_metadata(model_slug)
|
|
@@ -267,7 +440,7 @@ class ContextManager:
|
|
|
267
440
|
return _normalize_int(metadata.get("auto_compact_token_limit"))
|
|
268
441
|
|
|
269
442
|
def _resolve_model_instructions(self) -> "typing.Union[str, None]":
|
|
270
|
-
model_slug = self.
|
|
443
|
+
model_slug = self.config.model
|
|
271
444
|
if model_slug is None:
|
|
272
445
|
return None
|
|
273
446
|
metadata = model_metadata(model_slug)
|
|
@@ -281,7 +454,7 @@ class ContextManager:
|
|
|
281
454
|
if isinstance(template, str):
|
|
282
455
|
personality_message = _resolve_personality_message(
|
|
283
456
|
variables,
|
|
284
|
-
self.
|
|
457
|
+
self.config.personality,
|
|
285
458
|
)
|
|
286
459
|
return template.replace(PERSONALITY_PLACEHOLDER, personality_message)
|
|
287
460
|
|
|
@@ -292,8 +465,8 @@ class ContextManager:
|
|
|
292
465
|
|
|
293
466
|
def _build_developer_message(self) -> "typing.Union[ContextMessage, None]":
|
|
294
467
|
sections: "typing.List[str]" = []
|
|
295
|
-
if self.
|
|
296
|
-
sections.append(self.
|
|
468
|
+
if self.config.developer_instructions is not None:
|
|
469
|
+
sections.append(self.config.developer_instructions)
|
|
297
470
|
if self._include_skills_instructions:
|
|
298
471
|
skills = self._build_skills_instructions()
|
|
299
472
|
if skills is not None:
|
|
@@ -302,6 +475,13 @@ class ContextManager:
|
|
|
302
475
|
permissions = self._build_permissions_instructions()
|
|
303
476
|
if permissions is not None:
|
|
304
477
|
sections.append(permissions)
|
|
478
|
+
default_instructions = self._model_message("collaboration_modes", "default")
|
|
479
|
+
if default_instructions:
|
|
480
|
+
sections.append(
|
|
481
|
+
"<collaboration_mode>{0}</collaboration_mode>".format(
|
|
482
|
+
default_instructions
|
|
483
|
+
)
|
|
484
|
+
)
|
|
305
485
|
if not sections:
|
|
306
486
|
return None
|
|
307
487
|
return ContextMessage(
|
|
@@ -309,9 +489,93 @@ class ContextManager:
|
|
|
309
489
|
content_items=tuple(_input_text_item(section) for section in sections),
|
|
310
490
|
)
|
|
311
491
|
|
|
492
|
+
def _model_message(self, *keys):
|
|
493
|
+
metadata = model_metadata(self.config.model)
|
|
494
|
+
value = metadata.get("model_messages") if metadata is not None else None
|
|
495
|
+
for key in keys:
|
|
496
|
+
if value is None:
|
|
497
|
+
return None
|
|
498
|
+
value = value.get(key)
|
|
499
|
+
return value
|
|
500
|
+
|
|
501
|
+
def _build_multi_agent_messages(self, tools, reasoning_effort):
|
|
502
|
+
return [
|
|
503
|
+
message for message in self._build_multi_agent_context(tools, reasoning_effort)
|
|
504
|
+
if message is not None
|
|
505
|
+
]
|
|
506
|
+
|
|
507
|
+
def _build_multi_agent_context(self, tools, reasoning_effort):
|
|
508
|
+
if self.agent_path is None:
|
|
509
|
+
return None, None
|
|
510
|
+
defaults = self._developer_defaults["multi_agent"]
|
|
511
|
+
root = self.agent_path == "/root"
|
|
512
|
+
role = "root" if root else "subagent"
|
|
513
|
+
configured = (
|
|
514
|
+
self.config.multi_agent_root_instructions
|
|
515
|
+
if root else self.config.multi_agent_subagent_instructions
|
|
516
|
+
)
|
|
517
|
+
if configured is not None:
|
|
518
|
+
role_text = configured
|
|
519
|
+
else:
|
|
520
|
+
base = self._model_message("multi_agent", "role", role)
|
|
521
|
+
marked = base is not None
|
|
522
|
+
if base is None:
|
|
523
|
+
base = defaults[role]
|
|
524
|
+
role_text = ""
|
|
525
|
+
if base:
|
|
526
|
+
exec_guidance = (
|
|
527
|
+
defaults["exec"] + "\n\n"
|
|
528
|
+
if any(
|
|
529
|
+
tool.name == "exec" and tool.namespace in (None, "functions")
|
|
530
|
+
for tool in tools
|
|
531
|
+
) and any(tool.namespace == "collaboration" for tool in tools)
|
|
532
|
+
else ""
|
|
533
|
+
)
|
|
534
|
+
wait_guidance = (
|
|
535
|
+
defaults["wait"] + "\n\n"
|
|
536
|
+
if any(tool.name == "wait_agent" for tool in tools) else ""
|
|
537
|
+
)
|
|
538
|
+
role_text = (
|
|
539
|
+
"{base}\n{shared}\n{exec}{wait}"
|
|
540
|
+
"There are {limit} available concurrency slots, meaning that "
|
|
541
|
+
"up to {limit} agents can be active at once, including you."
|
|
542
|
+
).format(
|
|
543
|
+
base=base, shared=defaults["shared"],
|
|
544
|
+
exec=exec_guidance, wait=wait_guidance,
|
|
545
|
+
limit=self.config.multi_agent_max_concurrency,
|
|
546
|
+
)
|
|
547
|
+
spawn = next(
|
|
548
|
+
(tool for tool in tools if tool.name == "spawn_agent"), None,
|
|
549
|
+
)
|
|
550
|
+
if spawn is not None and "model" in spawn.input_schema["properties"]:
|
|
551
|
+
role_text += "\n\n" + defaults["model_overrides"]
|
|
552
|
+
if marked:
|
|
553
|
+
role_text = "<multi_agent_role>{0}</multi_agent_role>".format(
|
|
554
|
+
role_text
|
|
555
|
+
)
|
|
556
|
+
role_message = (
|
|
557
|
+
ContextMessage(role="developer", text=role_text) if role_text else None
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
hint = self.config.multi_agent_hint
|
|
561
|
+
if hint is None:
|
|
562
|
+
hint = self._model_message("multi_agent", "mode", "hint_text")
|
|
563
|
+
if hint is None:
|
|
564
|
+
mode = "proactive" if reasoning_effort == "ultra" else "explicit"
|
|
565
|
+
hint = self._model_message("multi_agent", "mode", mode)
|
|
566
|
+
if hint is None:
|
|
567
|
+
hint = defaults[mode]
|
|
568
|
+
mode_message = (
|
|
569
|
+
ContextMessage(
|
|
570
|
+
role="developer",
|
|
571
|
+
text="<multi_agent_mode>{0}</multi_agent_mode>".format(hint),
|
|
572
|
+
) if hint else None
|
|
573
|
+
)
|
|
574
|
+
return role_message, mode_message
|
|
575
|
+
|
|
312
576
|
def _build_permissions_instructions(self) -> "typing.Union[str, None]":
|
|
313
|
-
sandbox_mode = self.
|
|
314
|
-
approval_policy = self.
|
|
577
|
+
sandbox_mode = self.config.sandbox_mode or "danger-full-access"
|
|
578
|
+
approval_policy = self.config.approval_policy or "never"
|
|
315
579
|
sandbox_prompt_name = sandbox_mode.replace("-", "_")
|
|
316
580
|
sandbox_prompt_path = (
|
|
317
581
|
PERMISSIONS_SANDBOX_PROMPTS_PATH / f"{sandbox_prompt_name}.md"
|
|
@@ -363,7 +627,7 @@ class ContextManager:
|
|
|
363
627
|
skill.path_to_skill_md.relative_to(skill.root).as_posix(),
|
|
364
628
|
)
|
|
365
629
|
lines.append(f"- {skill.name}: {skill.description} (file: {path_str})")
|
|
366
|
-
metadata = model_metadata(self.
|
|
630
|
+
metadata = model_metadata(self.config.model)
|
|
367
631
|
if metadata is None or metadata.get("include_skills_usage_instructions", True):
|
|
368
632
|
lines.append("### How to use skills")
|
|
369
633
|
lines.extend(SKILLS_GUIDANCE.splitlines())
|
|
@@ -371,7 +635,7 @@ class ContextManager:
|
|
|
371
635
|
return f"{SKILLS_OPEN_TAG}\n{body}\n{SKILLS_CLOSE_TAG}"
|
|
372
636
|
|
|
373
637
|
def _discover_skills(self) -> "typing.List[SkillDescriptor]":
|
|
374
|
-
codex_home = self.
|
|
638
|
+
codex_home = self.config.codex_home
|
|
375
639
|
if codex_home is None:
|
|
376
640
|
return []
|
|
377
641
|
|
|
@@ -421,10 +685,10 @@ class ContextManager:
|
|
|
421
685
|
|
|
422
686
|
def _merged_user_instructions(self) -> "typing.Union[str, None]":
|
|
423
687
|
parts: "typing.List[str]" = []
|
|
424
|
-
if self.
|
|
425
|
-
parts.append(self.
|
|
426
|
-
if self.
|
|
427
|
-
parts.append(self.
|
|
688
|
+
if self.config.user_instructions is not None:
|
|
689
|
+
parts.append(self.config.user_instructions)
|
|
690
|
+
if self.config.codex_home_instructions is not None:
|
|
691
|
+
parts.append(self.config.codex_home_instructions)
|
|
428
692
|
|
|
429
693
|
project_doc = self._read_project_docs()
|
|
430
694
|
if project_doc is not None:
|
|
@@ -437,7 +701,7 @@ class ContextManager:
|
|
|
437
701
|
|
|
438
702
|
def _read_project_docs(self) -> "typing.Union[str, None]":
|
|
439
703
|
docs: "typing.List[str]" = []
|
|
440
|
-
remaining = self.
|
|
704
|
+
remaining = self.config.project_doc_max_bytes
|
|
441
705
|
for path in self._discover_project_doc_paths():
|
|
442
706
|
text = path.read_text(encoding="utf-8", errors="replace")
|
|
443
707
|
if not text.strip():
|
|
@@ -498,7 +762,7 @@ class ContextManager:
|
|
|
498
762
|
f" <current_date>{self._current_date}</current_date>",
|
|
499
763
|
f" <timezone>{self._timezone_name}</timezone>",
|
|
500
764
|
]
|
|
501
|
-
sandbox_mode = self.
|
|
765
|
+
sandbox_mode = self.config.sandbox_mode or "danger-full-access"
|
|
502
766
|
if sandbox_mode == "danger-full-access":
|
|
503
767
|
permissions = (
|
|
504
768
|
'<permission_profile type="disabled"><file_system type="unrestricted" />'
|
|
@@ -534,6 +798,44 @@ class ContextManager:
|
|
|
534
798
|
return "\n".join(lines)
|
|
535
799
|
|
|
536
800
|
|
|
801
|
+
def _normalize_tool_calls(items, complete_calls):
|
|
802
|
+
call_ids = {
|
|
803
|
+
(item.tool_type, item.call_id)
|
|
804
|
+
for item in items if isinstance(item, ToolCall)
|
|
805
|
+
}
|
|
806
|
+
result_ids = {
|
|
807
|
+
(item.tool_type, item.call_id)
|
|
808
|
+
for item in items if isinstance(item, ToolResult)
|
|
809
|
+
}
|
|
810
|
+
normalized = []
|
|
811
|
+
for item in items:
|
|
812
|
+
if (
|
|
813
|
+
isinstance(item, ToolResult)
|
|
814
|
+
and (item.tool_type, item.call_id) not in call_ids
|
|
815
|
+
):
|
|
816
|
+
continue
|
|
817
|
+
normalized.append(item)
|
|
818
|
+
if (
|
|
819
|
+
complete_calls and isinstance(item, ToolCall)
|
|
820
|
+
and (item.tool_type, item.call_id) not in result_ids
|
|
821
|
+
):
|
|
822
|
+
prefix = "ctco" if item.tool_type == "custom" else "fco"
|
|
823
|
+
output_id = None
|
|
824
|
+
if item.id:
|
|
825
|
+
output_id = "{0}_{1}".format(
|
|
826
|
+
prefix,
|
|
827
|
+
uuid5(
|
|
828
|
+
UUID("90d38d3e-6a5b-4d52-bfe2-2f1e634bfac4"),
|
|
829
|
+
prefix + ":" + item.id,
|
|
830
|
+
),
|
|
831
|
+
)
|
|
832
|
+
normalized.append(ToolResult(
|
|
833
|
+
call_id=item.call_id, name=None, output="aborted",
|
|
834
|
+
tool_type=item.tool_type, id=output_id,
|
|
835
|
+
))
|
|
836
|
+
return normalized
|
|
837
|
+
|
|
838
|
+
|
|
537
839
|
def _input_text_item(text: "str") -> "JSONDict":
|
|
538
840
|
return {"type": "input_text", "text": text}
|
|
539
841
|
|
|
@@ -643,3 +945,18 @@ def _parse_skill_descriptor(
|
|
|
643
945
|
scope_rank=scope_rank,
|
|
644
946
|
root=root.resolve(),
|
|
645
947
|
)
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def build_goal_message(goal, budget_limited=False):
|
|
951
|
+
template_name = "budget_limit.md" if budget_limited else "continuation.md"
|
|
952
|
+
template = (
|
|
953
|
+
Path(__file__).resolve().parent / "prompts" / "goals" / template_name
|
|
954
|
+
).read_text(encoding="utf-8").rstrip("\n")
|
|
955
|
+
budget = goal.get("tokenBudget")
|
|
956
|
+
return UserMessage(template.format(
|
|
957
|
+
objective=escape(goal["objective"]),
|
|
958
|
+
tokens_used=goal["tokensUsed"],
|
|
959
|
+
time_used_seconds=goal["timeUsedSeconds"],
|
|
960
|
+
token_budget="none" if budget is None else budget,
|
|
961
|
+
remaining_tokens="unbounded" if budget is None else max(0, budget - goal["tokensUsed"]),
|
|
962
|
+
))
|