agent_signal
← All templates
OpenAI Agents SDK · 0.21.0 · JavaScript ✓ Tested

Tested on OpenAI Agents SDK (@openai/agents 0.21.0, pinned in package.json) · last tested Oct 28

Approval + resume in a fresh process (TypeScript SDK)

@openai/agents 0.21.0: needsApproval pauses the run, RunState goes to disk, a new Node process restores, approves and resumes. The tool runs exactly once.

What it shows

  • Approval pause: issue_refund is a tool({ needsApproval: true }) whose side effect is one line appended to out/ledger.jsonl. run() stops with result.interruptions.length === 1 and the ledger still empty.
  • Fresh-process resume: result.state.toString() is written to out/state.json ($schemaVersion "1.23"). A new Node process calls RunState.fromString(makeAgent(), json), state.getInterruptions(), state.approve(item), then run(agent, state). The script asserts ledger lines === 1 and exits 1 otherwise.
  • 0.20.0 snapshot: A schema-1.22 snapshot written by @openai/agents 0.20.0 restores and resumes under 0.21.0, runs the tool once and re-serializes as 1.23.
Mocked vs real. MOCKED: the LLM only. fake_model.mjs implements the SDK Model interface (getResponse) and emits the issue_refund call until it sees a function_call_result, then a final message. Streaming is not mocked. REAL: the run loop, approval interruption, RunState serialize/restore, resume and tool execution are unmodified SDK code; tracing is disabled. Not tested: real models, streaming, sessions/Conversations storage, MCP tools, realtime.

Code

agent.mjssrc
import { Agent, tool, Usage, setTracingDisabled } from '@openai/agents';
import { z } from 'zod';
import fs from 'node:fs';
import { makeFakeModel } from './fake_model.mjs';

setTracingDisabled(true);
export const LEDGER = process.env.LEDGER_FILE ?? new URL('./out/ledger.jsonl', import.meta.url).pathname;

// The side effect we must never double-execute: one line per real refund.
export const issueRefund = tool({
  name: 'issue_refund',
  description: 'Refund a customer order. Irreversible.',
  parameters: z.object({ orderId: z.string(), amountCents: z.number().int() }),
  needsApproval: true,
  async execute({ orderId, amountCents }) {
    fs.appendFileSync(LEDGER, JSON.stringify({ orderId, amountCents, pid: process.pid }) + '\n');
    return `refunded ${orderId} (${amountCents} cents)`;
  },
});

// Restore needs the same agent name + tool definitions as the run that paused.
export function makeAgent() {
  return new Agent({ name: 'RefundDesk', instructions: 'Refund when asked.',
    model: makeFakeModel(Usage), tools: [issueRefund] });
}

export function ledgerCount() {
  return fs.existsSync(LEDGER) ? fs.readFileSync(LEDGER, 'utf8').split('\n').filter(Boolean).length : 0;
}
fake_model.mjssrc
// Scripted fake model: no API key, no network. Implements the SDK's Model interface
// (getResponse / getStreamedResponse). Stateless on purpose: it decides from the request
// input, so it behaves the same in a fresh process after RunState restore.
export function makeFakeModel(Usage, { nested = true } = {}) {
  return {
    async getResponse(request) {
      const items = Array.isArray(request.input) ? request.input : [];
      const toolResult = items.find((i) => i.type === 'function_call_result');
      const usage = new Usage({
        requests: 1, inputTokens: 12, outputTokens: 4, totalTokens: 16,
        // 0.21.0 allows nested numeric breakdowns; 0.20.0 only flat numbers.
        inputTokensDetails: nested ? { cached_tokens: 2, breakdown: { text: 10 } } : { cached_tokens: 2 },
        outputTokensDetails: { reasoning_tokens: 1 },
      });
      if (!toolResult) {
        return { usage, responseId: 'fake_resp_1', output: [{
          type: 'function_call', callId: 'call_refund_1', name: 'issue_refund',
          arguments: JSON.stringify({ orderId: 'A-1001', amountCents: 4900 }), status: 'completed',
        }] };
      }
      const out = typeof toolResult.output === 'string' ? toolResult.output : JSON.stringify(toolResult.output);
      return { usage, responseId: 'fake_resp_2', output: [{
        type: 'message', role: 'assistant', status: 'completed',
        content: [{ type: 'output_text', text: `Done. Tool said: ${out}` }],
      }] };
    },
    async *getStreamedResponse() { throw new Error('streaming not mocked'); },
  };
}
01_pause.mjssrc
// Process 1: run until the approval interruption, write RunState JSON to disk, exit.
import fs from 'node:fs';
import { run } from '@openai/agents';
import { makeAgent, ledgerCount, LEDGER } from './agent.mjs';

fs.mkdirSync(new URL('./out/', import.meta.url), { recursive: true });
fs.rmSync(LEDGER, { force: true });
const STATE = new URL('./out/state.json', import.meta.url);

const result = await run(makeAgent(), 'Refund order A-1001, $49.');
const pending = result.interruptions ?? [];
console.log(`[pause pid=${process.pid}] interruptions: ${pending.length}`,
  pending.map((i) => `${i.rawItem.name}(${i.rawItem.arguments})`).join(', '));
if (pending.length !== 1) { console.error('FAIL: expected exactly 1 interruption'); process.exit(1); }
if (ledgerCount() !== 0) { console.error('FAIL: tool ran before approval'); process.exit(1); }

const json = result.state.toString();
fs.writeFileSync(STATE, json);
console.log(`[pause] RunState written: out/state.json (${json.length} bytes, $schemaVersion=${JSON.parse(json).$schemaVersion})`);
console.log('[pause] ledger lines before approval: 0  -> exiting process');
02_resume.mjssrc
// Process 2 (fresh): restore RunState from disk, approve, resume, assert tool ran exactly once.
import fs from 'node:fs';
import { run, RunState } from '@openai/agents';
import { makeAgent, ledgerCount } from './agent.mjs';

const json = fs.readFileSync(new URL('./out/state.json', import.meta.url), 'utf8');
const agent = makeAgent();
const state = await RunState.fromString(agent, json);
const pending = state.getInterruptions();
console.log(`[resume pid=${process.pid}] restored state, pending approvals: ${pending.length}`);
for (const item of pending) { console.log(`[resume] approving ${item.rawItem.name}`); state.approve(item); }

const result = await run(agent, state);
console.log(`[resume] final output: ${result.finalOutput}`);
const n = ledgerCount();
console.log(`[resume] ledger lines: ${n}`);

// Usage after restore: 0.21.0 detail values are number | nested object -> narrow before math.
const u = result.state.usage;
const det = u.inputTokensDetails?.[0] ?? u.inputTokensDetails;
const cached = typeof det?.cached_tokens === 'number' ? det.cached_tokens : 0;
console.log(`[resume] usage: requests=${u.requests} total=${u.totalTokens} cached(narrowed)=${cached} breakdown=${JSON.stringify(det?.breakdown)}`);

if (n !== 1) { console.error(`FAIL: tool executed ${n} times, expected exactly 1`); process.exit(1); }
if ((result.interruptions ?? []).length) { console.error('FAIL: still interrupted'); process.exit(1); }
console.log('[resume] PASS: tool executed exactly once');
legacy-0.20.0/write_snapshot.mjssrc
// Runs under @openai/agents 0.20.0 (its own node_modules): pause and write a schema-1.22 snapshot.
import fs from 'node:fs';
import { Agent, run, tool, Usage, setTracingDisabled } from '@openai/agents';
import { z } from 'zod';
import { makeFakeModel } from '../fake_model.mjs';
setTracingDisabled(true);
const agent = new Agent({ name: 'RefundDesk', instructions: 'Refund when asked.',
  model: makeFakeModel(Usage, { nested: false }), // 0.20.0 details are flat Record<string, number>
  tools: [tool({ name: 'issue_refund', description: 'Refund a customer order. Irreversible.',
    parameters: z.object({ orderId: z.string(), amountCents: z.number().int() }), needsApproval: true,
    async execute() { throw new Error('must not run under 0.20.0'); } })] });
const r = await run(agent, 'Refund order A-1001, $49.');
const json = r.state.toString();
const out = new URL('../out/state-0.20.0.json', import.meta.url);
fs.mkdirSync(new URL('../out/', import.meta.url), { recursive: true });
fs.writeFileSync(out, json);
const ver = JSON.parse(fs.readFileSync(new URL('./node_modules/@openai/agents/package.json', import.meta.url))).version;
console.log(`[legacy] @openai/agents ${ver} wrote out/state-0.20.0.json, $schemaVersion=${JSON.parse(json).$schemaVersion}, interruptions=${r.interruptions.length}`);
03_restore_legacy.mjssrc
// Under 0.21.0: restore the snapshot written by 0.20.0, approve, resume, assert exactly once.
import fs from 'node:fs';
import { run, RunState } from '@openai/agents';
import { makeAgent, ledgerCount, LEDGER } from './agent.mjs';

fs.rmSync(LEDGER, { force: true });
const json = fs.readFileSync(new URL('./out/state-0.20.0.json', import.meta.url), 'utf8');
console.log(`[legacy-restore] snapshot $schemaVersion=${JSON.parse(json).$schemaVersion}`);
const agent = makeAgent();
const state = await RunState.fromString(agent, json);
for (const item of state.getInterruptions()) state.approve(item);
const result = await run(agent, state);
const n = ledgerCount();
console.log(`[legacy-restore] final output: ${result.finalOutput}`);
console.log(`[legacy-restore] re-serialized as $schemaVersion=${JSON.parse(result.state.toString()).$schemaVersion}, ledger lines: ${n}`);
if (n !== 1) { console.error(`FAIL: tool executed ${n} times`); process.exit(1); }
console.log('[legacy-restore] PASS: 0.20.0 snapshot readable by 0.21.0, tool executed exactly once');
run_demo.mjssrc
// npm test: every step is a separate Node process. Nonzero exit on any failure.
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
const here = new URL('.', import.meta.url).pathname;
const v = JSON.parse(fs.readFileSync(new URL('./node_modules/@openai/agents/package.json', import.meta.url))).version;
console.log(`node ${process.version} | @openai/agents ${v}`);
const steps = [['01_pause.mjs'], ['02_resume.mjs']];
if (fs.existsSync(here + 'legacy-0.20.0/node_modules/@openai/agents')) {
  steps.push(['legacy-0.20.0/write_snapshot.mjs'], ['03_restore_legacy.mjs']);
} else console.log('SKIP legacy check: run `npm --prefix legacy-0.20.0 install` first');
for (const [f] of steps) {
  const r = spawnSync(process.execPath, [here + f], { stdio: 'inherit', env: { ...process.env, OPENAI_API_KEY: '' } });
  if (r.status !== 0) { console.error(`STEP FAILED: ${f} (exit ${r.status})`); process.exit(1); }
}
console.log('ALL PASS');
package.jsonsrc
{
  "name": "openai-agents-js-approval-resume",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT",
  "description": "OpenAI Agents SDK (TypeScript) 0.21.0: tool approval -> pause -> RunState to disk -> fresh process restore -> approve -> resume -> tool runs exactly once. Fake model, no API key.",
  "engines": {
    "node": ">=22"
  },
  "scripts": {
    "test": "node run_demo.mjs"
  },
  "dependencies": {
    "@openai/agents": "0.21.0",
    "zod": "4.6.7"
  }
}
run_output.txtsrc
# captured 2026-10-28 09:15 MDT on Linux 6.12.94+ (zod 4.6.7, engines node >=22)
$ npm --prefix legacy-0.20.0 ci && npm test
node v22.23.4 | @openai/agents 0.21.0
[pause pid=903112] interruptions: 1 issue_refund({"orderId":"A-1001","amountCents":4900})
[pause] RunState written: out/state.json (4175 bytes, $schemaVersion=1.23)
[pause] ledger lines before approval: 0  -> exiting process
[resume pid=903120] restored state, pending approvals: 1
[resume] approving issue_refund
[resume] final output: Done. Tool said: {"type":"text","text":"refunded A-1001 (4900 cents)"}
[resume] ledger lines: 1
[resume] usage: requests=2 total=32 cached(narrowed)=2 breakdown={"text":10}
[resume] PASS: tool executed exactly once
[legacy] @openai/agents 0.20.0 wrote out/state-0.20.0.json, $schemaVersion=1.22, interruptions=1
[legacy-restore] snapshot $schemaVersion=1.22
[legacy-restore] final output: Done. Tool said: {"type":"text","text":"refunded A-1001 (4900 cents)"}
[legacy-restore] re-serialized as $schemaVersion=1.23, ledger lines: 1
[legacy-restore] PASS: 0.20.0 snapshot readable by 0.21.0, tool executed exactly once
ALL PASS

$ npm test   # without legacy-0.20.0 installed
node v22.23.4 | @openai/agents 0.21.0
SKIP legacy check: run `npm --prefix legacy-0.20.0 install` first
[pause pid=903350] interruptions: 1 issue_refund({"orderId":"A-1001","amountCents":4900})
[pause] RunState written: out/state.json (4175 bytes, $schemaVersion=1.23)
[pause] ledger lines before approval: 0  -> exiting process
[resume pid=903364] restored state, pending approvals: 1
[resume] approving issue_refund
[resume] final output: Done. Tool said: {"type":"text","text":"refunded A-1001 (4900 cents)"}
[resume] ledger lines: 1
[resume] usage: requests=2 total=32 cached(narrowed)=2 breakdown={"text":10}
[resume] PASS: tool executed exactly once
ALL PASS
LAST_TESTED.mdsrc
# Last tested

- **Date:** 2026-10-28 (America/Edmonton), zod bump re-test on Node v22.23.4. Previous: 2026-10-21.
- **SDK:** @openai/agents 0.21.0 (agents-core / agents-openai 0.21.0, openai 7.40.0, zod 4.6.7 since 2026-10-28; was 4.1.12). Legacy check: @openai/agents 0.20.0 (agents-core 0.20.0), zod 4.6.7.
- **Node:** `engines` is now `node >=22` (openai@7.40.0 declares `node >=22.0.0`). Supported/tested: v22.23.4 (npm 10.9.9). The 2026-10-21 runs and Tester's 2026-10-28 re-test also passed on v20.19.2, but Node 20 is outside `engines` (npm warns EBADENGINE) and is not supported. Official nodejs.org tarballs, sha256 verified.
- **OS:** Debian GNU/Linux 13 (trixie), Linux 6.12.94+ x86_64
- **Command:** `npm ci` + `npm --prefix legacy-0.20.0 ci` (legacy step is skipped without it), then `npm test` (= `node run_demo.mjs`, 4 separate Node processes per run)

## 2026-10-28 zod bump (GHSA-mrhx-c7xc-m3w5)
- zod pinned 4.1.12 -> 4.6.7 (>= 4.6.6) in `package.json` and `legacy-0.20.0/package.json`; lockfiles regenerated. `npm ls zod`: every copy is 4.6.7. `npm audit`: 0 vulnerabilities (root and legacy-0.20.0).
- Node v22.23.4: 3 runs, 3 pass, 0 fail (with legacy installed, ALL PASS each run; output identical except PIDs). Captured in `run_output.txt`.
- Without `legacy-0.20.0/node_modules`: prints `SKIP legacy check` and ends ALL PASS (covers only the 0.21.0 pause/resume).
- Replay gotcha re-checked: second resume of the same snapshot -> ledger 2, `02_resume.mjs` exits 1.
- Before the bump, Tester's 2026-10-28 re-test (zod 4.1.12) was 3/3 on v20.19.2 and 3/3 on v22.23.4.

## Pass counts (2026-10-21, zod 4.1.12)
| Node | Runs | Pass | Fail |
|---|---|---|---|
| v20.19.2 | 3 | 3 | 0 |
| v22.23.4 | 3 | 3 | 0 |

Each run: pause (1 interruption, ledger 0) -> fresh-process resume (ledger exactly 1) -> 0.20.0 snapshot (schema 1.22) -> restored under 0.21.0 (ledger exactly 1, re-saved as 1.23). Output identical across runs except PIDs.

## Verified against source / release notes
- GitHub release `@openai/agents-openai@0.21.0` (989513a): "saved run state (schema 1.23, with backward reads of earlier snapshots); usage detail values now require narrowing to numbers before arithmetic."
- Installed `agents-core/dist/runState.mjs`: `CURRENT_SCHEMA_VERSION = '1.23'`, `SUPPORTED_SCHEMA_VERSIONS` 1.0 to 1.23. In 0.20.0: `'1.22'`.
- `types/protocol.d.ts`: 0.21.0 `TokenDetails = { [key]: number | TokenDetails }`; 0.20.0 details are `ZodRecord<string, number>`.
- npm publish time of 0.21.0: 2026-10-20T22:14Z (16:14 MDT).

## Notes / what broke
- Nothing in the SDK broke. Green on the first full run.
- Usage narrowing: hit it by design (the fake model returns a nested `breakdown`). The value comes back nested after restore; code narrows with `typeof`. Plain JS doesn't fail without the check; TS would at compile time.
- Negative check (manual, not in `npm test`): resuming the same paused snapshot twice executes the tool twice. See the README gotcha.
- Minor: reading `finalOutput` on a paused run logs a warning; removed from the demo.
LICENSEsrc
MIT License

Copyright (c) 2026 Agent Signal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Upgrade gotchas

  • Exactly-once is your job, not the SDK's. Restoring the same paused state.json twice and approving twice ran the tool twice (verified: ledger = 2). Delete or mark the snapshot consumed after resume, or make the tool idempotent (e.g. key on callId/order id).
  • Usage detail narrowing (0.21.0): inputTokensDetails / outputTokensDetails values are now number | TokenDetails (nested), was Record<string, number> in 0.20.0. Check typeof v === 'number' before arithmetic.
  • Schema 1.23: 0.21.0 writes 1.23 and still reads 1.0 to 1.22. 0.20.0 only knows up to 1.22, so do not roll back the SDK once 0.21.0 has written snapshots.
  • Install legacy-0.20.0 first (npm --prefix legacy-0.20.0 install). Without it, npm test prints SKIP legacy check and still ends ALL PASS, covering only the 0.21.0 pause/resume.
  • Node 22 or newer: engines is node >=22 because openai@7.40.0 requires it.
  • Restore with the same agent name and tool definitions. Only deserialize state from trusted storage.
  • Reading result.finalOutput on a paused run logs "Accessed finalOutput before agent run is completed." Check result.interruptions instead.

Free starter pack

The approval-flow starter pack

Tested human-in-the-loop approval starters for LangGraph, OpenAI Agents SDK, Vercel AI SDK and Google ADK, plus the Agent Signal newsletter. Free.

FAQ

How do I pause an OpenAI Agents SDK (TypeScript) tool for approval and resume in another process?

Mark the tool with tool({ needsApproval: true }). run() stops with result.interruptions. Write result.state.toString() to disk; in the new process call RunState.fromString(makeAgent(), json), state.approve(item) for each item from state.getInterruptions(), then run(agent, state).

What happens if I resume the same snapshot twice?

The tool runs twice. Restoring the same paused state.json twice and approving twice ran the tool twice (verified: ledger = 2). Delete or mark the snapshot consumed after resume, or make the tool idempotent.

Can 0.21.0 read a snapshot saved by 0.20.0?

Yes. In the test, a schema-1.22 snapshot written by @openai/agents 0.20.0 restored under 0.21.0, ran the tool exactly once and re-serialized as 1.23. 0.20.0 only reads up to 1.22, so do not roll the SDK back after 0.21.0 has written snapshots.

Do I need an OpenAI API key?

No. Only the LLM is mocked (fake_model.mjs); everything else is real SDK code. No network model calls.

What was it tested on?

@openai/agents 0.21.0 with zod 4.6.7 on Node v22.23.4, Debian 13: npm test passed 3 of 3 runs on 2026-10-28, with the legacy-0.20.0 check installed. It needs Node 22 or newer (openai@7.40.0 requires it). Plain .mjs, MIT-licensed.