When an agent chooses a tool, the runtime may keep changing state: a policy can replace arguments, a retrieval step can update references, and a hook can block the call. If you only record the context after execution, you lose the most useful incident question: what did the agent see when it made the decision?
The fix is a small, immutable snapshot at a named boundary. Record the run and tool-call identity, the context that influenced the decision, the arguments emitted by the model, the final arguments that will reach the executor, and hashes that let you compare versions. Capture it after validation and policy decisions, but before the external side effect.
The snapshot does not need the entire prompt or any secret. It needs to let another engineer check whether the observed call matches the context and payload available at that point. The guide to tracing AI agent tool calls with OpenTelemetry covers the operational span tree; this article defines the boundary record that explains the decision.
If that decision must also survive a process failure, connect the record to durable execution for AI agents. The snapshot explains the call's input; the checkpoint explains where the run can continue.
Short answer
- Separate the runtime's local context from the context that reached the model.
- Capture a serialized copy after the last argument transformation and before
execute.- Keep
runId,toolCallId, context version, schema version, redacted references, and hashes.- Compare the arguments the model requested with the arguments the executor received.
- Do not treat a trace or a mutable object as proof of the original payload.
Local context is not the context the model saw
"Context" often means two different things. The runtime has dependencies, policies, IDs, and state objects that tools can read. The model sees messages, instructions, tool schemas, and results that were included in the conversation history.
The OpenAI Agents SDK context documentation makes this distinction explicit: local context is available to application code, but it is not sent to the LLM automatically. The same documentation exposes tool-call metadata such as tool_call_id, the tool name, and arguments through ToolContext. An investigation snapshot must say which surface it captured.
Use two records when the question needs precision:
| Record | Moment | Question it answers |
|---|---|---|
| Model-context snapshot | immediately before the model request | Which messages, tools, and references were available when it chose the action? |
| Tool-boundary snapshot | after validation and authorization, before execution | Which concrete call was the executor about to perform? |
The second record does not replace the first. It captures the effective payload, but it cannot prove that the model received a particular instruction. The first records the decision input, but it does not show whether a hook changed the arguments before the side effect.
This distinction matters for systems that use Agent.as_tool() or nested agents. Application state can be shared across nested runs without the parent's conversation being inherited automatically. Record parentRunId or parentToolCallId when there is a relationship, but do not infer the child's context from the parent's.
Freeze two boundaries, not one mutable object
A useful snapshot follows one rule: after creation, it does not change. Do not point at context, messages, or args objects that the loop will keep using. Make a serializable copy and remove fields that cannot or should not be persisted.
In practice, capture the tool boundary in this order:
- Receive the call emitted by the model.
- Validate its arguments against the tool schema.
- Apply authorization, limits, and deterministic normalization.
- Create the snapshot with the original and final arguments.
- Persist it or send it to an observability queue.
- Only then execute the external tool.
The beforeToolCall hook in the Cloudflare Agents documentation is a concrete example of this boundary. It runs before execute, receives messages, toolCallId, the tool name, and input, and can substitute the input. The same documentation warns that afterToolCall can still expose the model's original input after a substitution. If you need the final argument, capture it in the hook that performed the transformation, before execution.
Do not copy the entire history just to solve this problem. For most investigations, a document reference, version, hash, and count are better than a full body. The snapshot should be reproducible enough to compare decisions, but small enough that it does not become a second database of prompts and personal data.
Minimum fields for a pre-tool snapshot
Start with a stable envelope and add fields only when an investigation shows that one is missing. These fields cover the relationship between decision, context, and effect:
| Field | Why it exists |
|---|---|
runId, turnId, toolCallId |
Connect the record to the flow and exact call. |
toolName and schemaVersion |
Identify the contract that accepted the arguments. |
modelArgs |
Preserve what the model requested before transformations. |
executionArgs |
Show the payload the executor actually received. |
contextVersion and contextRefs |
Reconstruct which facts and instructions were used without copying everything. |
policyVersion and decision |
Explain why the call was allowed, blocked, or changed. |
messageHash, toolsHash, and argsHash |
Detect drift without putting sensitive content in metrics. |
capturedAt and runtimeVersion |
Place the record in time and tie it to the build that made the decision. |
The OpenAI Agents SDK tracing documentation already organizes a run into traces and spans for generations, tool calls, handoffs, and guardrails. Use its traceId for correlation when that SDK is present. Do not assume the trace contains the snapshot you need: the documentation also notes that inputs and outputs can contain sensitive data and provides a setting to disable that capture.
The goal is not a universal format. It is a contract that distinguishes modelArgs from executionArgs. Without that difference, a log can show a plausible call while a policy layer executed something else.
Node.js fixture: the snapshot does not change with the runtime
The fixture below uses only Node.js APIs. It does not call a model provider or an external tool. The test proves a local property: the snapshot keeps a redacted copy of context and preserves the difference between the original and final arguments.
Save it as context-snapshot.test.mjs and run node --test context-snapshot.test.mjs:
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { test } from "node:test";
function hash(value) {
return createHash("sha256")
.update(JSON.stringify(value))
.digest("hex")
.slice(0, 16);
}
function captureToolSnapshot({
runId,
turnId,
toolCallId,
toolName,
modelArgs,
executionArgs,
context,
}) {
const safeContext = {
taskId: context.taskId,
contextVersion: context.contextVersion,
refs: [...context.refs],
};
const snapshot = {
runId,
turnId,
toolCallId,
toolName,
modelArgs: structuredClone(modelArgs),
executionArgs: structuredClone(executionArgs),
context: safeContext,
};
return Object.freeze({
...snapshot,
hashes: {
modelArgs: hash(snapshot.modelArgs),
executionArgs: hash(snapshot.executionArgs),
context: hash(snapshot.context),
},
});
}
test("freezes the pre-tool evidence without retaining live state", () => {
const context = {
taskId: "task-7",
contextVersion: 4,
refs: ["policy:v3", "ticket:42"],
secret: "never persist this field",
};
const snapshot = captureToolSnapshot({
runId: "run-9",
turnId: 2,
toolCallId: "call-3",
toolName: "search_orders",
modelArgs: { customerId: "c-8", limit: 100 },
executionArgs: { customerId: "c-8", limit: 25 },
context,
});
context.contextVersion = 5;
context.refs.push("later-result:99");
context.secret = "changed";
assert.deepEqual(snapshot.context.refs, ["policy:v3", "ticket:42"]);
assert.equal(snapshot.context.contextVersion, 4);
assert.equal("secret" in snapshot.context, false);
assert.equal(snapshot.modelArgs.limit, 100);
assert.equal(snapshot.executionArgs.limit, 25);
assert.equal(snapshot.hashes.context.length, 16);
});
The example uses structuredClone to make the copy boundary clear. In a real runtime, define serialization explicitly: sort keys when hashes need to be stable, normalize numbers and dates, and handle values that are not JSON. The hash helps detect drift. It does not prove that the original content was correct.
Compare the model request with the authorized effect
The difference between the two payloads is information, not noise. If the model asked for limit: 100 and policy reduced it to 25, the snapshot should preserve both and record which rule made the change. If a hook changed the target, the executor should be able to point to the decision that authorized the new target.
A simple way to model that stage is to return a policy result together with the final arguments:
const decision = policy.apply({
toolName: call.name,
modelArgs: validatedArgs,
context,
});
const snapshot = captureToolSnapshot({
...identity,
toolName: call.name,
modelArgs: validatedArgs,
executionArgs: decision.args,
context,
});
await snapshotStore.append(snapshot);
if (decision.action === "deny") {
return { status: "blocked", reason: decision.reason };
}
return execute(call.name, decision.args);
The code is illustrative. snapshotStore.append needs a failure policy chosen by the product. For a low-risk read, an observable telemetry failure may not need to block execution. For a destructive action, it may be safer not to execute without a decision record. The snapshot does not replace authorization, argument validation, or idempotency.
To keep that boundary separate from payload checking, see how to validate tool calls in TypeScript for AI agents. Validation decides whether the data has an acceptable shape; the snapshot records what was decided and executed.
Redaction and retention are part of the contract
A snapshot may contain more information than an ordinary trace. Before writing it, classify every field:
- Operational identity:
runId,toolCallId, runtime version, and correlation IDs. - Context evidence: hashes, versions, and stable references to documents or state.
- Execution payload: validated and redacted arguments, including fields that change the effect.
- Default-deny data: tokens, credentials, full document bodies, private messages, and outputs that do not need retention.
The OpenAI Agents SDK documents that generation and function spans can store sensitive inputs and outputs, and that trace_include_sensitive_data controls this capture. The same reasoning applies to your store: deciding not to record is different from recording and trying to delete it later.
Keep the snapshot for as long as the investigation requires, with access control and a deletion policy. If the complete payload is needed to reproduce a bug, keep it in a separate artifact with its own retention and authorization. In the operational record, prefer a reference or hash.
I use RemoteCode as my own tool when I need continuity between Codex and Claude Code sessions without copying the entire history into each new context. It helps organize the work, but it does not turn a summary into evidence of what the agent received.
How to verify the capture in the runtime
Test the contract in four layers:
- Immutability: change messages, context, and arguments after capture. The snapshot must not change.
- Ordering: have a policy hook replace an argument and confirm that
executionArgscontains the final value. - Redaction: include a secret field in the fixture and verify that it never reaches the record.
- Correlation: run two identical tool calls in one run.
toolCallIdandturnIdmust distinguish them.
Then add an integration test around the real adapter. Emit a valid call, block another in the hook, and trigger an authorized substitution. Compare the snapshot with the arguments the executor received. Do not rely only on the model's final log, which may be produced before policy or after a result has been transformed.
If the system supports replay, use the snapshot as diagnostic input, not as permission to execute again. The guide to replaying an agent without real tools separates safe reproduction from resumption.
Common failures
Capturing after execution
A post-tool record tells you what happened after a possible effect. It helps with result and latency, but it arrives too late to explain which context authorized the operation's start.
Recording only the tool name
send_email or update_order does not identify the recipient, resource, schema version, or arguments the model produced. Relate the name, IDs, and hashes. Keep a redacted payload only when the investigation needs it.
Keeping the live object
A pointer to run state can look like a snapshot at log time and point to a different version a few milliseconds later. Clone and serialize at the boundary. If state is not serializable, keep an explicit version and verifiable references.
Treating the trace as the snapshot
Trace, audit, and replay have different responsibilities. A trace helps order operations. An AI agent audit trail connects authority and consequence. A replay cassette supplies controlled responses. The pre-tool snapshot records the decision input and effective payload. They can share IDs, but they are not interchangeable.
Method and limits
Samuel Fajreldines selected the sources, defined the problem, wrote the fixture, and edited the article. I consulted the public OpenAI Agents SDK and Cloudflare Agents documentation on December 3, 2026. I also checked current Portuguese, English, and Spanish results and recent public discussions for phrases such as "context snapshot", "beforeToolCall", and "what the model saw". Those discussions informed vocabulary and questions, not technical proof.
I ran the fixture locally with Node.js v25.5.0 using only node:test, node:assert/strict, and node:crypto. It proves copying, redaction, and argument comparison in memory. It does not test a specific SDK, multi-process concurrency, durable storage, access control, production redaction, or deterministic LLM replay.
AI assistance supported source discovery, organization, prose review, SVG preparation, and localization. It did not run a production agent, capture user data, or supply operational experience.
Conclusion
If you need to explain why an agent chose a tool, capture context at a boundary you can name and test. Take a snapshot after validation and policy, before the executor, and preserve the difference between the model's request and the authorized payload. IDs, versions, redacted references, and hashes are often more useful than copying the prompt indiscriminately.
This record complements tracing, audit, and replay. It does not authorize a call or prove that an external effect happened. Its job is simpler: stop the loop's mutable state from erasing the evidence of the decision.
Sources consulted
- OpenAI Agents SDK, "Context management", accessed December 3, 2026.
- OpenAI Agents SDK, "Tracing", accessed December 3, 2026.
- Cloudflare Agents, "Lifecycle hooks", accessed December 3, 2026.