Skip to content
PERMISSION/PROTOCOL

Tutorial

OpenAI Agents SDK Human Approval: Pause, Persist and Resume

Permission Protocol10 min readSources checked

The takeaway

Run an OpenAI Agents JavaScript SDK approval example without an API key. Test rejection, restarts and replay, and distinguish native controls from application safeguards.

In this article

In the OpenAI Agents JavaScript SDK, a tool with needsApproval: true pauses before execution. Your application resolves the pending interruption with state.approve() or state.reject(), then passes that state back to the runner. For a decision that arrives later, persist the run state and restore it in a new process.

This tutorial runs that flow with a synthetic $125 refund. The SDK runs real approval code; a deterministic model supplies the tool call, and execution only inserts a local SQLite row. No model API key, payment service or Permission Protocol integration is required.

Tested versions: @openai/agents 0.21.0, zod 4.6.7, Node 22.18.0 and Python 3.13.7. JavaScript runs the SDK. Python supplies the CLI and application ledger. The versioned lab results below were recorded October 23, 2026; the OpenAI matrix and this CLI were rechecked on Windows November 12.

1. Download and install the pinned lab

Extract the lab source archive. Save the tutorial CLI and CLI tests inside the extracted agent-approval-lab directory, beside lab.py. These files are public downloads; you do not need access to our repository.

Use Node 22.18.0 and Python 3.13.7 to match the recorded runtime. From the extracted directory:

cd agent-approval-lab
cd openai
npm ci --ignore-scripts
cd ..

The lockfile pins JavaScript dependencies. This OpenAI-only path uses Python's standard library, so it does not need the LangGraph Python packages. On macOS or Linux use python3 in place ofpython in the commands below. Keep the lab separate from your application.

2. Pause, inspect, and approve in separate processes

python openai-agents-human-approval.py start --store approved-demo
python openai-agents-human-approval.py status --store approved-demo
python openai-agents-human-approval.py approve --store approved-demo

start returns status: pending, the proposed action, and an empty mock_effects list. Inspect the order, currency and amount before approving. Each command is a separate process: the approval command restores the persisted SDK state.

{
  "operation_id": "refund-demo-001",
  "order_id": "synthetic-order-42",
  "amount_cents": 12500,
  "currency": "USD"
}

After approval, expect status: consumed and one entry in mock_effects matching that action. consumed is the application ledger's authorization state, not a payment result. The row establishes that the mock effect ran locally. It says nothing about a real refund.

Repeat the approval command, then try reject against that same store. The CLI returns the recorded state without running another action or reversing the decision. This behavior comes from lab.py and the CLI. It is separate from the native SDK retry experiment below.

3. Reject a different run

python openai-agents-human-approval.py start --store rejected-demo
python openai-agents-human-approval.py reject --store rejected-demo
python openai-agents-human-approval.py approve --store rejected-demo

The rejection resumes the SDK with a rejected tool call. The application records rejected, with zero mock effects. The later approval command leaves that decision unchanged. Start uses a new directory and refuses to overwrite an existing store.

The reviewer name and clock are fixed test fixtures. Typing approve here does not authenticate a person, prove their authority or create a human signature.

What the JavaScript SDK actually does

The official human-in-the-loop guide documents the approval flow and serialization APIs. In the pinned worker, this tool definition puts the local effect behind approval. This is an excerpt from openai/worker.mjs in the archive:

const refund = tool({
  name: 'mock_refund', description: 'Record a synthetic refund in a local test ledger only.',
  parameters: actionSchema, needsApproval: true,
  async execute(action) {
    const result = spawnSync(request.python, [path.join(root, 'lab.py')], {
      input: JSON.stringify({ mode: 'effect', directory: request.directory, action, guarded: request.guarded }),
      encoding: 'utf8', timeout: 15000,
    });
    if (result.status !== 0) throw new Error(result.stderr);
    return result.stdout.trim();
  },
});

The worker saves the pause with result.state.toString(). On resume it rebuilds the same agent and tool, restores the stored state, resolves the interruption, and runs again:

const state = await RunState.fromString(agent, fs.readFileSync(source, 'utf8'));
  const pending = state.getInterruptions();
  if (pending.length > 1) throw new Error('expected at most one pending decision');
  if (pending.length) request.approved ? state.approve(pending[0]) : state.reject(pending[0]);
  try {
    result = await runner.run(agent, state);
  } catch (error) {
    // This specific SDK refusal is an observation, not a swallowed tool failure.
    if (error instanceof UserError && error.message === 'Accepted final output cannot be resumed directly from serialized terminal state. Start a new run from persisted session history.') {
      process.stdout.write(JSON.stringify({ status: 'terminal_resume_rejected', reason: error.message }));
      process.exit(0);
    }
    throw error;
  }

The complete worker is in the download. Its custom model returns a fixed tool call, then a final response after the tool result. Network calls and tracing are disabled in the worker. This isolates control flow; it does not test a live model's behavior or ability to choose the correct action.

Read the complete Python CLI that invokes the JavaScript worker
"""Run from the extracted agent-approval-lab directory. Synthetic local actions only."""
import argparse
from contextlib import closing
import json
from pathlib import Path
import sqlite3
import sys


def status(store):
    if not (store / "ledger.sqlite").is_file():
        raise ValueError("No run exists here. Run start with a new --store path first.")
    with closing(sqlite3.connect((store / "ledger.sqlite").as_uri() + "?mode=ro", uri=True)) as db:
        row = db.execute("SELECT action, status FROM request WHERE id=1").fetchone()
        if row is None:
            raise ValueError("Incomplete store. Inspect it; do not reuse it for a new action.")
        actions = [json.loads(item[0]) for item in db.execute("SELECT action FROM effects ORDER BY id")]
    return {"status": row[1], "action": json.loads(row[0]), "mock_effects": actions}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=["start", "approve", "reject", "status"])
    parser.add_argument("--store", required=True, type=Path)
    args = parser.parse_args()
    # The public script reuses the pinned lab, including its actual JavaScript SDK worker.
    if not (Path.cwd() / "lab.py").is_file():
        raise ValueError("Run this script from the extracted agent-approval-lab directory.")
    sys.path.insert(0, str(Path.cwd()))
    from lab import ACTION, NOW, PRINCIPAL, create, decide, dispatch, worker
    store = args.store.resolve()
    if args.command == "start":
        # Never overwrite a pending decision, completed run, or unrelated existing directory.
        store.mkdir(parents=True, exist_ok=False)
        create("openai", store, guarded=True)
    elif args.command != "status":
        current = status(store)
        if current["status"] == "pending":
            approved = args.command == "approve"
            decision = decide(store, PRINCIPAL, approved, NOW)
            if decision["status"] == "approved":
                dispatch("openai", store, ACTION, NOW)
            elif decision["status"] == "rejected":
                worker("openai", store, "resume", approved=False, guarded=True)
        # A prior decision is never reversed or automatically retried. A crash between
        # decision, consumption and SDK completion requires operator reconciliation.
    print(json.dumps(status(store), indent=2))


if __name__ == "__main__":
    try:
        main()
    except (ValueError, OSError, RuntimeError, sqlite3.Error) as error:
        print(str(error), file=sys.stderr)
        sys.exit(2)

Keep ownership of the approval state

RunState.fromString() restores data; it does not authenticate the snapshot or reviewer. The official guide recommends application-controlled storage. Keep the authoritative snapshot on the server, and validate the caller's access to the specific request before accepting a decision.

For this local lab, the files and SQLite ledger are trusted inputs controlled by the operator. For a web application, send the reviewer a request identifier and the permitted display fields. Look up the authoritative action on the server. Do not accept a browser-supplied run snapshot as proof of approval.

The lab binds the decision to an action fingerprint, checks a synthetic reviewer and expiry, then transactionally consumes approval before SDK execution. Its mock backend deduplicates an operation ID. Those are example application safeguards. They are not extra guarantees supplied by the SDK.

A completed-state retry and an old snapshot replay are different

In the native OpenAI experiment, resuming the latest serialized terminal state raised a specific UserError and added no effect. The worker reports this as terminal_resume_rejected. Reusing the retained paused snapshot after the successful run produced a second mock effect.

Two processes resuming that same retained pause also produced two effects when application claim and backend idempotency were absent. These are specific lab observations, not a claim that every SDK retry duplicates work. A stored snapshot is not a durable record that an approval remains unused.

The CLI does not offer historical replay. It uses the application ledger and leaves prior decisions unchanged. If a process crashes after consumption but before the effect, the ledger can say consumed while mock_effects is empty. Inspect and reconcile that state; do not reset the approval automatically. This example does not guarantee exactly-once execution.

The eight-scenario lab results

This table reads the published v1 JSON directly. Five native cases and eight application cases were exercised for OpenAI. Three native cases were not tested. A passing experiment confirms its stated observation; it does not certify a production control.

October 23, 2026: native SDK observations and example application safeguards
ScenarioNative OpenAI SDKExample application
ApprovalObserved

Native approval resumed and executed once.

Observed

Stored exact-action approval was consumed and the SDK recorded one mock effect.

RejectionObserved

Native rejection resumed without a mock effect.

Observed

Rejection persisted; dispatch was denied before SDK resume.

Changed actionNot tested

Native post-approval argument mutation is not exercised in v1; application test changes the dispatch candidate after the stored approval.

Observed

After approval of 12500 cents, dispatch of 25000 cents was denied before SDK resume.

Expired approvalNot tested

No native expiry policy configured; tested at the application dispatch boundary only.

Observed

An approval made before expiry was denied at dispatch at the exact expiry boundary.

Duplicate resume or replayObserved

SDK rejected serialized terminal-state resume; explicit replay of the retained paused snapshot/checkpoint produced a second effect.

Observed

Second application dispatch was denied by the durable consumed status.

Process restartObserved

A fresh OS process restored the persisted pause and executed once.

Observed

Decision process exited; a fresh dispatch process loaded the ledger and persisted SDK state, then executed once.

Concurrent approvalsObserved

Two processes resumed the same retained paused snapshot/checkpoint and recorded two mock effects. No application claim or idempotency was installed.

Observed

Two released processes competed to approve and dispatch one request; one resumed the SDK, the other was denied as already decided.

Wrong approverNot tested

No native identity provider configured; application test uses a simulated authenticated principal, not a login system.

Observed

Simulated wrong principal could not approve; later dispatch was denied.

The application rejection case stops before SDK resume. The tutorial CLI additionally exercises native rejection through the worker, then verifies that a later CLI approval cannot reverse the recorded decision.

python openai-agents-human-approval-tests.py
python run_lab.py --framework openai

The CLI has four tests covering restarts, approval/rejection, repeated or opposite decisions, missing/existing stores, and an uncertain consumed state. The matrix also exercises changed parameters, expired approvals, concurrency and a wrong synthetic reviewer at the application boundary. Download the original CSV observations for comparison. Fresh matrix results are written to results/latest.json and results/latest.csv.

Decisions to make before connecting a real tool

  • Identity and authority: authenticate the reviewer and authorize their decision for this action. A supplied name or request ID is insufficient.
  • Changed action: a different amount, recipient or artifact needs a new review. Bind the parameters displayed to the parameters dispatched.
  • Expiry: check the deadline again at dispatch. The lab's fixed clock is a fixture, not a production time source.
  • Retry and crash handling: coordinate competing claims, use backend idempotency where supported, and define how an operator reconciles an uncertain outcome.
  • Evidence: retain the decision separately from the execution outcome. These local rows are unsigned application records, not independently issued receipts.

Use the approval design checklist and free worksheet to apply those decisions to one workflow. The authorization foundation explains the boundary between delegated access and approval of a specific action.

This is an educational example, not a Permission Protocol integration or security certification. If native SDK controls cover your requirements, use them. If you still have a concrete approval or evidence gap, bring that workflow to a conversation with us.

Troubleshooting and limits

  • Cannot find lab.py: run from the extracted lab directory, with both tutorial files saved beside it.
  • Cannot find @openai/agents: run npm ci --ignore-scripts inside that directory's openai folder.
  • The store already exists: inspect it with status or choose a new path. Never overwrite a pending approval just to restart the walkthrough.
  • The SDK refuses a terminal resume: keep completed and pending states distinct. Do not fall back to an old pending snapshot to suppress the error.
  • Consumed approval, no effect: investigate the interruption between claim and execution. The CLI intentionally does not attempt recovery.

Official documentation was checked November 12, 2026. It is a rolling reference; the observations here apply to the pinned versions. Live models, hosted MCP approvals, streaming, nested agent tools, distributed failover and native post-approval argument mutation were outside this test.

Building in a workflow editor? The n8n tool-review walkthrough covers native Chat approval and provides an acceptance worksheet. It is documentation-based; we have not executed that workflow.

For another framework, see the LangGraph approval tutorial. For review design across frameworks, start with the human-approval guide.

Put it into practice

Plan your approval boundary

Use the free checklist and worksheet to define the action, reviewer, expiry, retry rules and evidence for one real workflow.

Keep reading