Skip to content

Commit 6bc55f7

Browse files
feat: edit detached native sampling requests (#5518)
* fix: report captured context limits and model defaults * feat: edit detached native sampling requests * Expose typed reasons for owned model output failures * Report prepared-request mid-turn compaction failures * Handle the expected parser disconnect in the reason fixture * Report the compactor's context window on terminal overflow * Borrow the sampling prompt when no request editor is active * Preserve received response history on current v1 * Fill overflow usage from the model that sampled the request * Import the types and assertions used by context metadata tests * fix: preserve trace context on repaired history base * Validate prepared requests against the selected tool roster * Fix CI assumptions about child snapshots and temporary directories * Preserve defined trace flags and manual action budgets * Sequence trace regression tool replies before final model output * Preserve explicit provider overrides in request editor preflight * Keep request editor forwarding optional for run_sync overrides * feat: expose passive request metadata and response links (#5519) Observe passive request metadata on repaired history Co-authored-by: markstuart-oai <[email protected]> * Keep integrity reason tests within the native enum contract * Let the turn report fatal prepared-request compaction once * Validate native trace prefix widths and fresh-root controls * Validate sampled manual tools and retain request callback tracing * Align manual continuation trace and observation arguments * Fix worker deadline fixtures and Windows storage type checks * Preserve existing submit overrides on ordinary agent runs * Verify the winning reply when manual responses race * Check complete trace handles and both MCP callback parents * Observe child turns before testing unconfirmed cancellation * Respect supported platforms in SQLite trace fixtures * Distinguish caller exports from disabled child work * Preserve native child callback tracing ownership * Distinguish child trace exports and surface callback failures * Keep remote trace ancestry separate from private SDK policy * Preserve owned child tracing policy across native admission * Avoid callback scheduling assumptions in trace policy test * Separate session setup from concurrent trace policy admissions * Account for split trace processor batches in loop-loss test * fix: preserve completed answers when request editing skips compaction --------- Co-authored-by: markstuart-oai <[email protected]>
1 parent a1b704a commit 6bc55f7

19 files changed

Lines changed: 2919 additions & 12 deletions
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
"""Edit a detached sampling copy after a real tool result, without live credentials.
2+
3+
ScriptedResponses supplies an explicitly HTTP loopback provider with a synthetic
4+
key. Use NativeProvider(supports_websockets=False) for the same transport choice
5+
with your own provider.
6+
7+
Select a standard Responses (non-Lite) model, such as gpt-5.5.
8+
This profile supports direct roots with eager ordinary function/MCP tools and
9+
no Environment, children or code mode. Edits leave canonical history, original
10+
handlers, validators and approval policies authoritative. Active editor state
11+
cannot be exported. Operations requiring automatic compaction are rejected
12+
before compaction dispatch. For structured output, use NativeOutput or
13+
PromptedOutput(max_retries=0): separate output correction requests cannot carry
14+
this callback.
15+
"""
16+
17+
import asyncio
18+
from typing import Any, Literal
19+
20+
from agents import (
21+
Agent,
22+
PreparedRequest,
23+
ReplaceArguments,
24+
ToolContext,
25+
ToolOutput,
26+
Turn,
27+
function_tool,
28+
)
29+
from agents.testing import ScriptedResponses, text, tool_call
30+
31+
32+
def prepare(
33+
turn: Turn[Any],
34+
request: PreparedRequest,
35+
*,
36+
preparation_index: int,
37+
recovery_attempt: int,
38+
) -> PreparedRequest | None:
39+
# Recovery can advance preparation_index without a tool result. Inspect
40+
# the native input and retain call IDs instead of treating the index as proof.
41+
if not any(
42+
item.get("type") == "function_call_output" and item.get("call_id") == "lookup"
43+
for item in request["input"]
44+
):
45+
return None
46+
request["instructions"] = "Explain the lookup result in one sentence."
47+
request["input"].append(
48+
{
49+
"type": "message",
50+
"role": "user",
51+
"content": [{"type": "input_text", "text": "SAMPLING_ONLY_NOTE"}],
52+
}
53+
)
54+
request["tools"][0]["description"] = "Sampled record description."
55+
request["tools"][0]["parameters"]["properties"]["key"] = {
56+
"type": "string",
57+
"enum": ["allowed", "sampled-only"],
58+
}
59+
return request
60+
61+
62+
async def run_example() -> str:
63+
effects = []
64+
65+
def correct(context: ToolContext[None]) -> ReplaceArguments:
66+
assert context.call_id == "lookup"
67+
assert context.original_arguments == {"key": "allowed", "label": "original"}
68+
return ReplaceArguments({"key": "allowed", "label": "corrected"})
69+
70+
def shape(context: ToolContext[None], output: ToolOutput) -> ToolOutput:
71+
assert context.call_id == "lookup"
72+
assert context.effective_arguments["label"] == "corrected"
73+
return ToolOutput.text("SHAPED_RESULT")
74+
75+
@function_tool(before=correct, after=shape)
76+
async def lookup(key: Literal["allowed"], label: str) -> str:
77+
"""Read a record after original validation and the captured before policy."""
78+
effects.append(label)
79+
return f"Raw record {key}"
80+
81+
async with ScriptedResponses(
82+
[tool_call("lookup", {"key": "allowed", "label": "original"}, call_id="lookup")],
83+
[text("The record is allowed.")],
84+
) as peer:
85+
result = await Agent(
86+
model="gpt-5.5",
87+
instructions="Call lookup, then explain its result.",
88+
tools=[lookup],
89+
provider=peer.provider,
90+
).run("Look up the record.", prepare_request=prepare)
91+
assert effects == ["corrected"]
92+
assert peer.tool_output("lookup") == "SHAPED_RESULT"
93+
assert len(peer.requests) == 2
94+
assert "SAMPLING_ONLY_NOTE" in str(peer.requests[1]["input"])
95+
assert "Sampled record description." in str(peer.requests[1]["tools"])
96+
wire_request: Any = peer.requests[1]
97+
assert any(
98+
part.get("text") == "Explain the lookup result in one sentence."
99+
for item in wire_request["input"]
100+
if isinstance(item, dict) and item.get("role") == "developer"
101+
for part in item.get("content", [])
102+
if isinstance(part, dict)
103+
)
104+
return result.final_output
105+
106+
107+
if __name__ == "__main__":
108+
print(asyncio.run(run_example()))

‎packages/codex/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)