Skip to content

[Bug] openai-agents (TypeScript): TemporalOpenAIRunner ignores the agent a custom Handoff's callback returns #237

Closed

Description

@campoy

What happens

The upstream handoffs guide says: "Use a custom Handoff when your own handoff code must decide
which agent to return at invocation time." Handoff.onInvokeHandoff must return an agent, and the
upstream Runner hands off to the agent it returns, not to handoff.agent.

TemporalOpenAIRunner (@temporalio/openai-agents/workflow) hands off to the Handoff's agent
field instead. The callback still runs, but the agent it returns is dropped, and the run continues
with the wrong agent, its instructions and its tools. Nothing fails or warns.

The cause is in convertAgent (src/workflow/convert-agent.ts): it replaces each Handoff with
h.clone({ agent: convertAgent(h.agent) }). Given only agent, the framework's Handoff.clone
wraps the callback as await this.onInvokeHandoff(context, args); return agent;, so the returned
agent is always the converted h.agent.

Handoffs made with handoff(agent) or a plain Agent are not affected: their callback returns
their own agent.

Reproduction

One file. It runs a router whose only handoff is a custom Handoff that returns vip for a VIP
run, first with the upstream Runner (control), then in a Workflow on a local test server
(@temporalio/testing). A scripted model makes the router call the handoff. It exits 1 while the
bug is present.

// A custom Handoff whose callback picks the receiving agent. The upstream Runner hands off to the
// agent the callback returns; TemporalOpenAIRunner hands off to the Handoff's `agent` field.
// One file: the Workflow is bundled from this file. Exits 1 while the bug is present.
//   npm i @temporalio/openai-agents @temporalio/testing @temporalio/worker @openai/agents-core
//   node repro.cjs
const { Agent, Handoff } = require('@openai/agents-core');
const { TemporalOpenAIRunner } = require('@temporalio/openai-agents/workflow');

// As the handoffs guide suggests: "Use a custom Handoff when your own handoff code must decide
// which agent to return at invocation time."
function makeRouter() {
  const standard = new Agent({ name: 'standard', model: 'standard-model' });
  const vip = new Agent({ name: 'vip', model: 'vip-model' });
  const desk = new Handoff(standard, async (runContext) => (runContext.context.tier === 'vip' ? vip : standard));
  desk.toolName = 'transfer_to_desk';
  desk.toolDescription = 'Route to the right desk';
  return new Agent({ name: 'router', model: 'router-model', handoffs: [desk] });
}

async function deskWorkflow(tier) {
  const result = await new TemporalOpenAIRunner().run(makeRouter(), 'help me', { context: { tier } });
  return result.lastAgent.name;
}
module.exports = { deskWorkflow };

async function main() {
  // Node-only modules, kept out of the Workflow bundle.
  const nodeRequire = require('module').createRequire(__filename);
  const { Runner, Usage, setTracingDisabled } = nodeRequire('@openai/agents-core');
  setTracingDisabled(true);
  const { TestWorkflowEnvironment } = nodeRequire('@temporalio/testing');
  const { Worker } = nodeRequire('@temporalio/worker');
  const { OpenAIAgentsPlugin } = nodeRequire('@temporalio/openai-agents');

  // The router always calls transfer_to_desk; the other models answer.
  const modelProvider = {
    getModel: (name) => ({
      async getResponse() {
        const usage = new Usage({ requests: 1, inputTokens: 1, outputTokens: 1, totalTokens: 2 });
        if (name === 'router-model') {
          return { usage, output: [{ type: 'function_call', callId: 'c1', name: 'transfer_to_desk', arguments: '{}', status: 'completed' }] };
        }
        return { usage, output: [{ type: 'message', id: 'm', role: 'assistant', status: 'completed',
          content: [{ type: 'output_text', text: `answered by ${name}` }] }] };
      },
      async *getStreamedResponse() {
        throw new Error('not used');
      },
    }),
  };

  // Control: the upstream Runner, no Temporal.
  const native = (await new Runner({ modelProvider, tracingDisabled: true }).run(makeRouter(), 'help me', { context: { tier: 'vip' } })).lastAgent.name;

  const env = await TestWorkflowEnvironment.createLocal();
  try {
    const worker = await Worker.create({
      connection: env.nativeConnection,
      taskQueue: 'desk',
      workflowsPath: __filename,
      bundlerOptions: { ignoreModules: ['module'] },
      plugins: [new OpenAIAgentsPlugin({ modelProvider })],
    });
    const run = (tier) => env.client.workflow.execute(deskWorkflow, { taskQueue: 'desk', workflowId: `desk-${tier}-${Date.now()}`, args: [tier] });
    const [vip, standard] = await worker.runUntil(async () => [await run('vip'), await run('standard')]);
    console.log(`upstream Runner, tier vip:      hands off to ${native}`);
    console.log(`TemporalOpenAIRunner, tier vip: hands off to ${vip}`);
    console.log(`TemporalOpenAIRunner, tier standard (control): hands off to ${standard}`);
    const ok = vip === native && standard === 'standard';
    console.log(ok ? 'OK: the Workflow handed off to the agent the callback returned' : 'BUG: the Workflow ignored the agent the callback returned');
    process.exitCode = ok ? 0 : 1;
  } finally {
    await env.teardown();
  }
}

if (typeof process === 'object' && require.main === module) {
  main().catch((e) => {
    console.error(e);
    process.exit(2);
  });
}

With @temporalio/openai-agents 1.24.0 (npm, the latest release) and with the package built from
this repository's main (c664a34), both with @temporalio/* 1.24.0, @openai/agents-core
0.14.3 and Node 24.22:

$ node repro.cjs
upstream Runner, tier vip:      hands off to vip
TemporalOpenAIRunner, tier vip: hands off to standard
TemporalOpenAIRunner, tier standard (control): hands off to standard
BUG: the Workflow ignored the agent the callback returned
exit=1

Both versions print the same lines. The test server's banner and the Worker's log lines are left out.

Expected

The same agent as the upstream Runner: the one the callback returns (vip here).

Impact

Any agent with a custom Handoff whose callback can return an agent other than its agent field.
The wrong agent answers, with its own tools. In one check, a VIP request that the upstream Runner
sent to a support agent went to billing instead, and billing's refund Activity ran. The
Workflow completes normally, so the mistake only shows in the result.

Workaround: one handoff per destination, letting the model choose, with isEnabled to hide the
ones a run must not use.

Proposed fix

In convertAgent, give each cloned Handoff an onInvokeHandoff that runs the original callback
and converts the agent it returns, through the same seen-map. When the callback returns its own
agent, nothing changes. Runs that already handed off to the agent field would replay into a
different agent and its tools, so the new path needs a patched() gate, asked only when the
callback returns another agent. A PR follows.

Activity

  1. added
    bug
    on Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions