Repository navigation
Breaking: run TypeScript OpenAI Agents as written: agent.asTool() works, runConfig.model no longer overrides an agent's own model, agentAsTool is deprecated - #270
Conversation
…agentAsTool (breaking) TemporalOpenAIRunner now gives its inner Runner a model provider that sends every model name to the model Activity, plus the run's model. Upstream passes the runner's config to nested agent.asTool() runs, so the framework's own asTool() works in a Workflow: its model calls are model Activities with the run's model and model settings and the runner's Activity options. agentAsTool and AgentAsToolOptions are removed. Use agent.asTool().
|
Let's take option 2: keep native For now, wrap The main benefit is the developer experience: applications moving from native execution to Temporal can keep their agent-tool declarations. We also reuse upstream's tool behavior rather than maintain a separate implementation. The plugin still needs its Temporal runner, Worker setup and Activity boundaries; native syntax does not remove those requirements. Existing plugin users would still migrate from The tradeoff is that the plugin owns a temporary patch to a shared upstream class in the Workflow runtime. That makes initialization order and SDK compatibility our responsibility. The implementation must install interception before tools are created, handle repeated initialization safely, and account for subclasses and duplicate SDK module copies. Tools whose source was not recorded must be rejected with a clear error. This choice does not accept the two review findings as documented limitations. Before merging, we need to:
In parallel, request a supported upstream way to inspect an agent tool's source and options and rebuild or rebind it while preserving identity and approval restoration. Once that exists, we can replace the interception inside the plugin while keeping the same native API and tested behavior. Callers should not need another migration for that internal change. |
TemporalOpenAIRunner no longer clones the agent graph to swap in Activity-backed models. Its inner Runner's model provider already sends every model name to the model Activity, so agents run as the caller wrote them. That also fixes two defects of the clones: agent.on(...) listeners on the caller's agents now fire (#235), and a custom Handoff now hands off to the agent its callback returns (#237). convertAgent becomes checkAgent, which runs the same checks, including the nested agent.asTool() checks, without changing the graph. asTool() tools are no longer rebuilt, so the asTool() record keeps only the agent and the runConfig and runOptions the tool was made with. The same-name check goes: without clones, handoff and nested agents keep their own string models. A ModelSummaryProvider still gets the running agent, tracked from the inner Runner's agent_start and agent_handoff events; a model call during a tool call belongs to a nested agent.asTool() run and gets none. As upstream, runConfig.model now applies only to agents that set no model of their own.
brianstrauch
left a comment
There was a problem hiding this comment.
Lint, build, and all 261 existing tests pass on Node 24. A focused Worker regression probe reproduces the nested-streaming restriction bypass noted inline.
| const innerRunner = new Runner({ | ||
| ...runnerConfigOverrides, | ||
| model: modelOverride, | ||
| modelProvider: new ActivityBackedModelProvider(this.modelParams, () => |
There was a problem hiding this comment.
[P2] Enforce the local Activity streaming restriction for nested tools
With useLocalActivity: true and a nested agent.asTool({ onStream }), the child run goes directly through upstream Runner, bypassing the StreamingLocalActivityUnsupported guard in TemporalOpenAIRunner.run(). This provider inherits the local Activity options and schedules invokeModelStreamActivity locally. I reproduced this by running the existing agentToolStreamWorkflow with modelParams.useLocalActivity: true: the provider's getStreamedResponse() runs once, both stream handlers receive the answer, and the parent succeeds instead of rejecting the unsupported combination. Please enforce the restriction in ActivityBackedModel.getStreamedResponse() or the shared run check, and add nested regression coverage.
There was a problem hiding this comment.
Good catch, thanks. Fixed in 3f11f6c: ActivityBackedModel.getStreamedResponse() now rejects useLocalActivity, next to its streaming-topic check, so every streamed model call has the check, including nested agent.asTool() runs. The runner's own check stays, so a top-level streamed run still fails before it starts.
One difference from the top-level case: as upstream, asTool() returns a nested run's failure to the parent model as the tool's output, so the parent run goes on. The nested model is never called. This matches the other checks that run inside a nested run. Rejecting the parent before it starts would need every on() handler up front, and handlers can be added after the run starts.
The new Worker test, A nested agent.asTool() run fails to stream when model calls are local Activities, runs agentToolStreamWorkflow with useLocalActivity: true. It fails without the check (the nested model streams) and passes with it.
…agent.asTool() runs A nested agent.asTool() run with onStream or on() handlers streams through upstream's Runner, so it skipped the runner's useLocalActivity check and ran the streamed model call as a local Activity. Check in ActivityBackedModel.getStreamedResponse(), which every streamed model call reaches. As upstream, the nested failure is the tool's output.
DABH
left a comment
There was a problem hiding this comment.
First review, at head 3f11f6c. On a worktree at the head with pnpm 10.27.0: make lint is clean (the 8 warnings already on main) and make test passes 262 of 262. I reviewed from four angles: line by line against @openai/agents-core 0.14.3, Temporal replay semantics, removed behaviour and documentation, and tests. I checked every candidate with a probe or traced it to file:line. The probes were:
- the upstream
Runnerwith a fake provider, for model precedence; - real Workers against a dev server, for the nested
SandboxAgent, the removed export and a nested 401; - histories recorded on
main(3488fbe), replayed against this head withWorker.runReplayHistory, and runs held onmainthen continued here with no Workflow cache; RunState.fromStringon a state saved from a graph built the old way;- a mutation pass over the new checks: removing the
getSystemPromptcheck body, the run wrapper, the frozen sandbox copy, the cancellation re-raise, the nested local-Activity stream check or the other-copy installs each fails at least one test.
Refuted and dropped:
- the
getSystemPrompthook misses no model call: its only caller is#prepareModelCall(run.mjs:1544), after model selection, in both loops and on resume, and it applies to theSandboxAgentexecution clone too; - the shallow
Object.freezeof the sandbox config is safe, because upstream only reads it; - the
toolCallscounter stays balanced, because upstream emitsagent_tool_endon the error path; - interceptor modules load before the Workflow module (
importInterceptors()runs beforeimportWorkflows()), so a module-scopeasTool()is recorded; - cancellation two
asTool()levels deep, followed by cleanup inCancellationScope.nonCancellable, completes; - the second-copy test is real: it bundles a copied package and guards against
copy.Agent === Agent; - #209, #210 and #166 don't depend on anything this removes. #209 and #210 conflict with it only in the two test files, #166 merges cleanly, and #209's README line about callable
toolFiltergetting the real agent needs this PR merged first.
The nested local-Activity streaming bypass from the earlier review is fixed in 3f11f6c, and its test fails without the check. This branch now conflicts with main in src/__tests__/test-openai-agents.ts and src/__tests__/workflows/openai-agents.ts after #215. Not run locally: the Node 22, macOS and Windows cells, which are green in CI.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Where the problems cluster: removing the clones is sound, and the new checks are well covered. The problems are in what changes for someone upgrading a Generally Available 1.x package:
- runs already in flight switch models with no version gate;
- the replay guidance promises loud failures where the actual outcome is silent wrong answers;
agentAsTooldisappears without a deprecation release;- two fail-fast behaviours become tool output that the parent model is told to retry: a nested
SandboxAgentwithout sandbox config, and non-retryable nested Activity failures.
Requesting changes for two items: the runConfig.model precedence flip changes runs already in flight on a Generally Available plugin with no version gate and diverges from the Python plugin, and dropping the nested SandboxAgent check turns a configuration error into a completed run. The other items can be follow-ups or documentation.
| // Nested `agent.asTool()` runs take the model, provider and settings from this config, as upstream. | ||
| const innerRunner = new Runner({ | ||
| ...runnerConfigOverrides, | ||
| model: modelOverride, |
There was a problem hiding this comment.
P2: runConfig.model now loses to any model the agent sets, with no version gate. Runs already in flight switch models silently after the upgrade, and the TypeScript and Python plugins now give opposite answers for the same config.
Upstream selectModel (runner/modelSettings.mjs:15) returns the agent's model whenever it is a non-empty string or a Model. Probe with the upstream Runner and a fake provider: an agent with own-model and runConfig.model: 'run-model' calls own-model, and a model-less agent calls run-model. On main, convertAgent replaced every agent's model with the override.
Replay doesn't compare Activity inputs. So a run that started with runConfig.model: 'gpt-5' and agents that declare gpt-4o-mini continues on gpt-4o-mini from its next model call, with no error. The PR body says this, but users read the README, and release notes are built from the commit subject only (scripts/release/release_tool.py:456).
"As upstream" cuts both ways here:
- Upstream's own contract (
run.d.ts:61, still the same on upstreammainatpackages/agents-core/src/run.ts:318) saysRunConfig.model"will override the model set on every agent". - The Python plugin keeps the run's model winning:
test_run_config_modelsasserts that only the run model is used. This is the point raised on Add a rule to match the upstream framework's behavior to AGENTS.md #272. - In fairness, upstream JS already lets an agent's
modelSettingswin over the run's, andmainpassed that through. So this change makes model and settings consistent with each other.
Fix, one of:
- Keep the run's model winning for the outer run, matching Python and the documented upstream contract. The
Runner.prototype.runwrapper already sees each run's config and can tell the outer run from nested ones. - Keep the agent winning, but gate it with
patched('openai-agents/agent-model-precedence'), read once at the top ofrun()and captured in the provider. In TS SDK 1.24,patched()returns false when replaying history recorded before the marker, so runs started before the upgrade keep the old rule. The Python plugin gates its own changes the same way (_openai_runner.py:281).
Either way, state the rule and the upgrade effect in the README next to line 100, and either align with the Python plugin or document the difference.
There was a problem hiding this comment.
Thanks for checking both sides. We're keeping upstream's code here: selectModel and its tests in test/run.test.ts let an agent's own model win, and our rule for these fixes is to match upstream's code and tests, even where its docs say otherwise. The Python plugin follows the Python SDK, whose code lets the run's model win, so the two plugins differ because the two SDKs do. We're also not adding version gates to fixes before 1.0, so no patched() marker.
In 0ca1882, the README's runner section states the rule, says upstream's docs disagree with its code, and notes the Python difference. The new "Upgrading open runs" section says runs in progress with runConfig.model switch to the agent's own model from their next model call. The runConfig.model JSDoc says the same, and the PR body's breaking-changes entry names the docs mismatch.
| ``` | ||
|
|
||
| Nested approval interruptions are not supported. If a nested run pauses for approval, the tool invocation fails with `ApplicationFailure` type `NestedAgentInterruption`. | ||
| As in the framework, the nested run takes the run's `model` (for agents that set none) and `modelSettings`. Its model Activities use the same options as the runner's. |
There was a problem hiding this comment.
P2: the upgrade guidance overstates what a replay check catches, and it exists only in the PR body.
The PR body lists five kinds of run that "fail replay with [TMPRL1100]". That holds when the added or missing step is not a model call, for example the Timer in the PR's own check. When it is another model call, replay passes: every model call is the same Activity type, and replay compares only type and ID.
Verified with a history recorded on main:
agentAsTool's nested call gets HTTP 400, and the Workflow catches it and runs a recovery agent (threeinvokeModelActivityevents).- Replaying it against this head with
Worker.runReplayHistorygives no error. - The same run, held on
mainafter the recovery and continued on this head, completes withcompleted:recovery-text. The recovery agent's recorded answer became the Triage agent's final output, and thecatchbranch was skipped. - Likewise, a run that called native
agent.asTool()onmainand was held afterrun()continues on this head with the parent's recorded second response delivered as the nested agent's answer.
Two more cases are missing from the list:
defaultModelParams.cancellationType: ABANDONnow applies to nested calls. A run cancelled during a nested call that is still open no longer sendsRequestCancelActivityTask, which gives TMPRL1100 (by trace).- A
RunStatesaved onmaincan resume on the wrong agent when anasTool()source agent has the same name as a handoff target. Upstream now addsasTool()sources to the RunState identity map, andagentAsTooltools were never in it. Probe: a savedcurrentAgent: {name: 'X'}resolves to the tool'sX, and resuming fails withTool confirm not found. If the two agents had the same tool names, the run would continue silently as the wrong agent. The one migration test (legacyFirstRun) uses the same object as both handoff target and tool source, which hides this.
Fix: add a short "Upgrading" subsection here saying that:
- open runs that used
agentAsTool,asTool()orrunConfig.modelshould finish on the old Worker or be pinned with Worker Versioning; - a passing replay test of old histories is not evidence of safety;
- agent names must be unique across handoffs and
asTool()sources before resuming an oldRunState.
Committing one cross-version history recorded on 3488fbe would also help. The Python plugins keep such fixtures under tests/histories/.
There was a problem hiding this comment.
Agreed, and thanks for the probes. In 0ca1882 the README has an "Upgrading open runs" section. It lists the runs to let finish or pin with Worker Versioning: agentAsTool and asTool() runs, runConfig.model with agents that set their own model, useLocalActivity or cancellationType now applying to nested calls, and hooks and custom Handoff callbacks. It says a passing replay test of old histories doesn't show an upgrade is safe, because a different model call replays without an error. It also says to give agents unique names across handoffs and asTool() tools before resuming an old RunState.
I rewrote the PR body's replay section the same way, with the ABANDON and RunState cases and the silent model-call outcomes you found.
I didn't commit a cross-version history. These runs replay without an error, so a fixture would mostly pin that, and the README now says it. Happy to add one if you'd still like it.
| } | ||
| return (await innerRunner.run(converted, preparedInput as any, sharedRunOptions)) as RunResult<any, TAgent>; | ||
| const result = (await innerRunner.run(agent, preparedInput as any, sharedRunOptions)) as RunResult<any, TAgent>; | ||
| if (scope.consideredCancelled) await scope.cancelRequested; |
There was a problem hiding this comment.
P2: nested failures that main treated as terminal, including non-retryable model Activity failures, now go back to the parent model as "Please try again". The run can spend model Activities until maxTurns and then fails without the cause.
Upstream asTool() builds its tool with tool() and exposes no errorFunction option (agent.mjs:183, :209), so every thrown error becomes the tool's output (tool.mjs:505).
Verified with a nested model that returns 401, which the Worker classifies as non-retryable (src/worker/activities.ts:96, :101), and a parent that calls the tool again:
mainschedules 2 Activities and fails withFailed to run function tools: ActivityFailure;- this head schedules 20 (10 parent, 10 nested) and fails with
Agent workflow failed: Max turns (10) exceeded, with no trace of the auth failure.
This PR also adds a realistic trigger: nested runs now inherit the run's modelSettings, so a setting the nested model rejects (temperature on a reasoning model, for example) gives a 400 on every call.
The same path also catches:
- a
TimeoutFailureafter retries run out; - the plugin's own checks;
- a
ModelSummaryProviderthat readsagent.name. It is now called for nested calls withagent: undefined; onmainthe nested runner had nodefaultModelParams, so it never ran for them.
The README's nested section mentions none of this; only the cancellation bullet at line 102 touches it.
Fix: this line already re-raises a cancellation that a tool turned into output. Do the same for terminal failures: in the Runner.prototype.run wrapper, record a nested run's non-retryable ApplicationFailure, TimeoutFailure, or ActivityFailure with a non-retryable cause, and rethrow it from run(). If upstream's behaviour is the intended contract, document the maxTurns cost and the lost cause in the nested section instead.
There was a problem hiding this comment.
This is upstream's asTool() contract: its tool has no errorFunction option, so every nested error becomes the tool's output, and a native run with a 401 on the nested model loops the same way. Our rule for these fixes is to match upstream's behavior, so I took your second option. In 0ca1882, the README's nested section says which failures come back as tool output: model Activity failures that aren't retried, timeouts, the plugin's checks in the nested run, and a nested SandboxAgent without sandbox config. It also says the parent may call the tool again until maxTurns, that the final error doesn't carry the cause, and that a ModelSummaryProvider gets agent: undefined for nested calls. The cancellation re-raise stays the one exception, because a cancelled scope must not complete.
| @@ -7,8 +7,6 @@ export { WorkflowSafeMemorySession } from './workflow/session'; | |||
| export type { WorkflowSafeMemorySessionOptions } from './workflow/session'; | |||
| export { nexusOperationAsTool } from './workflow/nexus-tools'; | |||
| export type { NexusOperationToolDefinition, NexusOperationAsToolOptions } from './workflow/nexus-tools'; | |||
There was a problem hiding this comment.
P2: agentAsTool is removed from a Generally Available 1.x package without a deprecation release. A Workflow bundled without a type check ends up in a Workflow Task retry loop instead of a build error.
1.18.0 through 1.24.0 export agentAsTool and AgentAsToolOptions. The next release will be above 1.24.0, so ^1.x ranges pick up the removal.
Verified: bundleWorkflowCode with the plugin and a .ts Workflow that calls agentAsTool (swc with no type check, which is the samples' dev path) builds with only an INFO-level webpack warning. Every Workflow Task then fails with agentAsTool is not a function until the execution timeout. Projects that run tsc get TS2305 instead.
Fix: for one release, keep a @deprecated agentAsTool(agent, { toolName, toolDescription, customOutputExtractor }) that returns agent.asTool({ ... }), plus the type alias. The tool is recorded automatically, because loading agent-tools.ts installs the interception, and upstream's customOutputExtractor type is compatible. Also add the one-line migration to the README.
There was a problem hiding this comment.
Done in 0ca1882: agentAsTool and AgentAsToolOptions are back as @deprecated aliases for one release. agentAsTool returns agent.asTool({ toolName, toolDescription, customOutputExtractor }), so the tool is recorded and runs like any other asTool() tool. The README's "Upgrading open runs" section has the migration, including that a nested approval now pauses the parent run instead of failing with NestedAgentInterruption. A unit test checks the alias.
| */ | ||
| /** A reachable `SandboxAgent` needs `runConfig.sandbox`, with a Temporal sandbox client. */ | ||
| function validateSandboxRunConfig(agent: Agent<any, any>, sandbox: SandboxRunConfig | undefined): void { | ||
| if (!hasSandboxAgent(agent) && sandbox === undefined) return; |
There was a problem hiding this comment.
P2: a SandboxAgent behind an asTool() tool, in a run without runConfig.sandbox, no longer fails fast. The run completes.
hasSandboxAgent (lines 137-146) follows only handoffs, and checkAgent walks the asTool() records without asking whether a sandbox is needed. On main, the nested TemporalOpenAIRunner.run threw SandboxConfigurationError, and agent-tools.test.ts covered it ("agentAsTool: nested SandboxAgent without parent sandbox config fails"). The PR deletes that test without a replacement.
Verified with a real Worker: new SandboxAgent({...}).asTool() on a plain agent, run with no sandbox, ends COMPLETED. The tool output is An error occurred while running the tool. Please try again. Error: UserError: SandboxAgent execution requires RunConfig.sandbox. A configuration error now reaches the model as a prompt to retry.
Fix: in hasSandboxAgent, also follow getAgentToolRecord(tool)?.agent when the record sets neither runConfig.sandbox nor runOptions.sandbox, and restore the test using asTool().
There was a problem hiding this comment.
Thanks, the probe is right. Here we're following upstream: a native run with the same graph gets the same UserError as the tool's output and completes, and our rule for these fixes is not to add plugin rules that depart from upstream's behavior. On main the fail-fast came from agentAsTool's own runner, which this PR replaces. The handoff check stays, because a handoff to a SandboxAgent without sandbox config fails the run upstream too.
In 0ca1882, the README lists this case with the other nested failures that become the tool's output, and Sandbox configuration errors are raised inside the Workflow now pins it: the nested SandboxAgent fails before calling its model, and the run ends on that tool output.
| if (rawModel !== undefined && rawModel !== null && typeof rawModel !== 'string') { | ||
| throw ApplicationFailure.create({ | ||
| message: | ||
| `Agent '${agent.name}' has a Model object instead of a string model name. ` + |
There was a problem hiding this comment.
P3: this message and a few other places still describe the run's model winning.
Now that the agent wins, runConfig.model cannot override an agent's Model object. Probe: the upstream Runner with runConfig.model set still calls the agent's inline model. So "use runConfig.model to override" points the user the wrong way; the fix is to replace the Model object with a model name.
The same wording appears in:
- the JSDoc of
TemporalRunOptions.runConfig.model: "Model name override" (runner.ts:67, outside the diff); - the README feature-table row label "Model override per run" (line 744).
Older, but nearby: runner.ts:69 says the run's modelSettings "override agent-specific settings", but upstream merges the agent's settings over the run's (run.mjs:1539-1540).
Also, the README drops the nested-approval note without saying that a nested approval now pauses the parent run.
There was a problem hiding this comment.
Fixed in 0ca1882. The Model object message now says to give the agent a model name. The runConfig.model and modelSettings JSDoc say the agent's own model and settings win, as upstream. The feature-table row is now "Run model". The nested section says a nested approval pauses the parent run.
| function asTool(this: Agent<any, any>, options: AnyAgentToolOptions): AnyAgentTool { | ||
| // Upstream reads its options when the tool is made, so record them then too. | ||
| const tool = state.original.call(this, options); | ||
| state.records.set(tool, { agent: this, runConfig: options.runConfig, runOptions: options.runOptions }); |
There was a problem hiding this comment.
P3: the record is keyed by the tool object, so upstream's own toolNamespace() makes a valid asTool() tool look unrecorded, and the run is rejected.
toolNamespace() (tool.mjs:892) returns copies built with Object.create plus the original property descriptors (tool.mjs:513-519). A copy is a new object that this WeakMap doesn't know, but it keeps on, so isUnrecordedAgentTool matches and checkToolOptions throws.
Probe: a plain asTool() tool is accepted. The same tool passed through toolNamespace({ name, description, tools: [it] }) is rejected with "looks like an agent.asTool() tool that @temporalio/openai-agents did not record ... pass it as is". Upstream would run the copy, since it has the same invoke and on closures.
Fix: key the record by a closure that copies keep, such as tool.on, in both set and get. That also covers spread copies.
Separately, asTool() tools made by an agent from another copy of @openai/agents-core are always rejected, because only this copy's asTool is wrapped. README line 430 says such agents are "checked the same way". Add that case to the list at line 421.
There was a problem hiding this comment.
Good catch. In 0ca1882 the record is keyed by the tool's on closure, so spread copies and toolNamespace() copies keep it. The unit test covers both, and a namespaced tool passes checkAgent. The Worker test's unrecorded case is now an asTool() tool from a second copy of @openai/agents-core, which is rejected before any model call. The README says such tools are rejected.
| const provider = modelSummary as ModelSummaryProvider; | ||
| const systemInstructions = request.systemInstructions; | ||
| const summary = provider.provide(this.agent, systemInstructions, request.input); | ||
| const summary = provider.provide(this.agent ?? this.runningAgent?.(), systemInstructions, request.input); |
There was a problem hiding this comment.
P3 (non-blocking cleanup): setAgent and the agent field have no production caller now that convertAgent is gone.
Only activity-backed-model.test.ts:67 uses them, so this.agent ?? ... always falls through to runningAgent, here and at line 170.
Similarly, the "no model declared" branch at check-agent.ts:22 can't fire for an agents-core Agent:
- the constructor sets
model = config.model ?? ''(agent.mjs:81); rejectModelObjecthas already thrown for any non-string model;- the unit test has to force
model = undefinedto reach the branch (check-agent.test.ts:32).
main behaved the same, but in this PR the modelOverride and nestedModel plumbing exists only to feed that branch. Remove both.
There was a problem hiding this comment.
Removed in 0ca1882: setAgent and the agent field (the summary unit test passes the agent through the constructor), the unreachable no-model branch, and the modelOverride and nestedModel plumbing.
|
|
||
| // The Worker loads interceptor modules before the Workflow module, so agent.asTool() tools that | ||
| // Workflow code creates at module scope are recorded too. | ||
| installAgentToolInterception(); |
There was a problem hiding this comment.
P3: three of the new checks have no test. Removing any one of them still passes the suite, 262 of 262.
- This install. Removing the import and the call passes. But a probe with a module-scope
nested.asTool(), in a module imported before@temporalio/openai-agents/workflow, is accepted at the head and rejected as unrecorded without the install. Commit that probe as a test. - The run-start
MemorySessioncheck (check-agent.ts:161-169). No test sets aMemorySessionafter the pre-run check, for example from a listener or aninputBuilder. Atool-start-memory-sessioncase inrunningAgentRejectedWorkflowwould cover it. - The run-start
checkAgentCopy(agent)(check-agent.ts:140). It looks redundant with line 20 and theagent_startlistener, which are both covered. Test it or drop it.
The agent_handoff listener at runner.ts:264 can also be removed with no failure. It is redundant, because upstream emits agent_start on the handoff target.
There was a problem hiding this comment.
Done in 0ca1882:
- The options-reuse Worker test now also passes
ask_early, a tool made at module scope in a module imported before@temporalio/openai-agents/workflow. Without the install in the interceptor module, the run is rejected as unrecorded. runningAgentRejectedWorkflowhas atool-start-memory-sessioncase: anagent_tool_startlistener sets aMemorySessionin the tool'srunOptions. Without the run-start check, the nested run uses it.- I dropped the run-start
checkAgentCopy(agent)and theagent_handofflistener as redundant.
Both new cases fail with their check removed.
…escript-native-as-tool # Conflicts: # typescript/openai-agents/src/__tests__/test-openai-agents.ts # typescript/openai-agents/src/__tests__/workflows/openai-agents.ts
…ed failures From review of 3f11f6c: - agentAsTool and AgentAsToolOptions come back as deprecated aliases for one release; agentAsTool returns agent.asTool({ toolName, toolDescription, customOutputExtractor }). - The asTool() record is keyed by the tool's on closure, so copies, such as the ones toolNamespace() makes, keep it. - The README gets an "Upgrading open runs" section, documents which nested failures become the tool's output, the nested approval, and the runConfig.model rule next to upstream's docs and the Python plugin. - Wording that described the run's model winning is fixed. - setAgent, the unreachable no-model branch, the run-start copy check and the agent_handoff listener are removed. - Tests cover the Workflow interceptor module's install, the run-start MemorySession check, another copy's asTool() tool and a nested SandboxAgent without sandbox config.
…escript-native-as-tool # Conflicts: # typescript/openai-agents/src/__tests__/test-openai-agents.ts # typescript/openai-agents/src/__tests__/workflows/openai-agents.ts # typescript/openai-agents/src/workflow/runner.ts
DABH
left a comment
There was a problem hiding this comment.
Second round, at head 2c2dc14 (0ca1882 plus a merge of main at 88745dc). On a worktree at the head with pnpm 10.27.0: make lint is clean (the 8 warnings already on main), make test passes 270 of 270, and CI is green. I re-ran the reproductions behind each item from the last round, then reviewed the whole diff again from four angles: line by line against @openai/agents-core 0.14.3, Temporal replay, removed behaviour and parity with the Python plugin, and tests and docs. Each finding below was reproduced with real Workers against a dev server, running the same Workflow code on main (88745dc) and on this head, or with a direct probe of the upstream code, or traced to file:line.
Replay: histories recorded on main were replayed here with Worker.runReplayHistory, and runs held on main were continued here with no Workflow cache. Plain agentAsTool runs replay and continue. So do runs with runner defaults (timeout, retry, summary string, task queue), a parallel activityAsTool, MCP, handoffs, RunState resumes in place and across continueAsNew, and a streamed parent. Every case in the PR body's Replay list behaves as described there. The undisclosed breaks are below.
Tests: a mutation pass over the new checks (45 mutants) kills the interceptor-module install, the run-start MemorySession check, the on-keyed record and the agent_start listener; the two survivors are below. The headline tests for #243, #235 and #237, ported to main, fail there.
Refuted and dropped:
- false positives from
isUnrecordedAgentToolon upstream tools (in 0.14.3 onlyasTool()addson); - a model call that skips the
getSystemPrompthook (every call goes through#prepareModelCallor reuses its prepared model); - nondeterminism from the prototype patches (each execution has its own module cache, and 15 Workflow types recorded concurrently on one Worker self-replay);
- a new
ApplicationFailurelanding as a Workflow Task failure (each fails the Workflow or becomes tool output; the one task-failure path is theTypeErrorbelow); - identity dependencies on the removed clones in the MCP tool cache (keyed by names), Nexus tools,
activityAsTooland sessions; - output differences in the deprecated alias beyond whitespace in structured output.
Not verified: the strict-endpoint failure below uses a fake provider that rejects the fields, not a live endpoint.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Previous rounds. Addressed, each re-checked at this head: agentAsTool and AgentAsToolOptions are back as deprecated aliases, and a Workflow calling agentAsTool completes through one nested model Activity; the record is keyed by tool.on, so the toolNamespace() reproduction is accepted, its nested agent is still checked (a Model object in it is rejected) and spread copies pass; the README has the "Upgrading open runs" section, the nested-failure paragraph and the nested-approval note; the Model-object message, the runConfig.model and modelSettings JSDoc and the table row are corrected; setAgent, the no-model branch, the run-start copy check and the agent_handoff listener are gone; the interceptor-module install and the run-start MemorySession check now have tests that fail without them. Accepted declines: no version gate for the runConfig.model precedence (the README now states the rule, upstream's docs mismatch, the Python difference and the effect on open runs), the nested SandboxAgent failure becoming tool output (upstream behaviour, documented and pinned by a test), and no committed cross-version history. brianstrauch's nested local-Activity streaming item stays fixed. Every review thread has an answer.
Where the problems cluster: removing the clones is sound, the alias restores source compatibility with 1.24, and the new checks are well covered. What is left comes from running the caller's agents as written:
- Upstream now sees string model names. It adds implicit GPT-5 settings and prompt-template flags that
mainnever sent, and the plugin forwards them without what the Worker needs to treat them as implicit. - Sharing the caller's objects exposes upstream rules the clones hid: one active run per
SandboxAgent, andRunStatelookup by declared agents. - Several of these, and two replay effects (command order within a turn, cancelled runs), change open or closed runs silently. None of them is in the upgrade section.
Requesting changes for one item: an agent that names no model now sends GPT-5 settings computed in the Workflow to whatever model the Worker resolves, which fails the first model call on a strict OpenAI-compatible endpoint, the failure #178 fixed in the Python plugin. The other items can be fixed here or documented.
PR body and title (P3). Release notes are built from the commit subject only (scripts/release/release_tool.py:456, :473). "run agents as written, support agent.asTool() and deprecate agentAsTool (breaking)" doesn't say what breaks. Recent breaking subjects name the change (#204 "Breaking: refuse RunConfig.model_provider in OpenAI Agents workflows"). Something like "Breaking: run TypeScript OpenAI Agents as written: agent.asTool() works, runConfig.model no longer overrides an agent's own model, agentAsTool is deprecated" would carry it. Stale or inaccurate after 0ca1882:
- "checkAgent checks ... a missing model": there is no such check;
- "tracked from the inner Runner's agent_start and agent_handoff events": only
agent_startremains; - "Not covered: Usage across nested runs": usage now accumulates in the parent;
- "Not covered: a Handoff object from another copy": the plugin's
checkAgentrejects it first, with "Agent 'undefined' is not an @openai/agents-core Agent" (check-agent.ts:26,:74-79), which could name the handoff instead.
| private readonly runningAgent?: () => Agent<any, any> | undefined | ||
| ) {} | ||
|
|
||
| getModel(modelName?: string): Model { |
There was a problem hiding this comment.
P2 (blocking): implicit model settings computed in the Workflow now reach the Worker as if they were explicit. An agent that names no model fails its first model call on a strict OpenAI-compatible endpoint, and a run-level providerData.reasoning_effort is overwritten.
On main the agent's model was the ActivityBackedModel object, so #prepareModelCall (run.mjs:1524-1531) had no resolved name and added no implicit settings. Now upstream sees the name and adds getImplicitModelSettingsForResolvedModel(...) (runner/runConfig.mjs:10-18). For an agent with no model, that means the defaults for the Workflow's own default model, gpt-5.4-mini. The Workflow sandbox doesn't see the Worker's OPENAI_DEFAULT_MODEL, and the Worker's provider picks the real model later.
Probe, real Workers recording the Activity input, same Workflow on main and this head, agent new Agent({ name, instructions }):
mainsendsmodelSettings: {}. This head sends{"reasoning":{"effort":"none"},"text":{"verbosity":"low"}}. It does so also withOPENAI_DEFAULT_MODEL=gpt-4.1on the Worker. Native upstream with that variable sends{}, so this is not upstream's behaviour either.- Against a provider that rejects fields its model doesn't take (Fireworks answered
400 Extra inputs are not permitted, field: 'verbosity'in openai_agents: align implicit model settings with the model a custom provider resolves #178):mainCOMPLETED; this head FAILED on the first model call withModelInvocationError.BadRequest, non-retryable. In-flight runs hit it at their next model call.
Second effect: toSerializedModelRequest (lines 38-53) drops request._internal. The Worker's Chat Completions model therefore can't apply upstream's reasoningEffortImplicit guard (openaiChatCompletionsModel.mjs:386-389). Probe of OpenAIChatCompletionsModel with gpt-5, the implicit reasoning.effort: 'low' and a run-level providerData.reasoning_effort: 'high': with the marker it sends high; without it, as the plugin calls it, it sends low. A gpt-5.6 agent with tools likewise gets an effort that upstream omits.
The Python plugin fixed the first case in #178. The stub flags implicit settings when no model is named (_temporal_model_stub.py:184-196). The Activity then re-derives them for the model it resolved (_invoke_model_activity.py:335-356).
Fix:
- Carry
reasoningEffortImplicitin the Activity input and restore it as_internalon the Worker. - For an empty model name, port openai_agents: align implicit model settings with the model a custom provider resolves #178: send whether the settings are upstream's implicit defaults, plus the run's
modelSettings. The Activity replaces them withgetDefaultModelSettings(<resolved model name>)and re-applies the run settings. - Test with a Worker default that isn't GPT-5, and with a Chat Completions model.
There was a problem hiding this comment.
Thanks for tracing this to #178. Fixed in ea99db8, along the lines of the Python plugin:
- The run check now gives each run, nested ones included, a copy of the model provider bound to that run: the agent it's on and the run's own
modelSettings. - When no model is named and the agent has no explicit settings, the Activity input carries only the run's settings and
implicitModelSettings: true. The Worker addsgetDefaultModelSettings()for its own default model under them, as upstream does in one process, and recomputesreasoningEffortImplicitfor them. toSerializedModelRequestnow carries upstream'sreasoningEffortImplicitmarker, and the Worker restores it as_internal, so a named GPT-5 model gets the sameproviderData.reasoning_efforthandling as upstream.
The new Worker test sets OPENAI_DEFAULT_MODEL=gpt-4.1 on the Worker. A model-less agent, directly and nested, sends only { temperature: 0.3 }; with the variable unset it gets gpt-5.4-mini's defaults. A named gpt-5 lead keeps upstream's settings and its marker reaches the model. The test uses a fake model that records the request, not a live Chat Completions endpoint. With either part removed, it fails.
| - use `agentAsTool` or `agent.asTool()`; | ||
| - set `runConfig.model` and have agents with a model of their own: those agents use their own model from their next model call; | ||
| - set `useLocalActivity` or `cancellationType` in the runner's options: nested model calls now use the runner's Activity options; | ||
| - have agent hooks (`agent.on(...)`), or a custom `Handoff` whose callback returns another agent: they now take effect. |
There was a problem hiding this comment.
P2: running agents as written changes more than this list says. Each item was checked with the same Workflow on main and on this head (the last by trace). The first five follow upstream, so they need disclosure rather than code; open runs pick them up as they continue, with no replay error:
- a gpt-5-family agent without
modelSettingsnow sends upstream's implicit settings:gpt-5gets{"reasoning":{"effort":"low"},"text":{"verbosity":"low"}}andgpt-5.4-minigets effortnone, wheremainsent{}. A nestedagentAsToolagent ongpt-5gets the same.modelSettings: {}on the agent opts out (probe:{}again); - explicit GPT-5
providerData.reasoningon agpt-5agent, whichmainstripped ({"providerData":{}}), now reaches the model; - an agent with a
prompttemplate and no model or tools now gets the template's model and tools.mainsentoverridePromptModel: trueandtoolsExplicitlyProvided: true, so the Worker's default model andtools: []replaced them (run.mjs:711-714,openaiResponsesModel.mjs:2417,:2455-2457); Agentsubclass overrides such asgetSystemPromptnow run (main's clone built a plainAgent), and aSandboxAgent's compaction threshold now follows its model;- the parent's
result.state.usagenow includes nested runs (2 requests onmain, 3 here), which contradicts the PR body's "Not covered: Usage across nested runs".
Two are the plugin's own:
- a
ModelSummaryProviderthat readsagent.namewithout a check worked on 1.24, because nestedagentAsToolcalls never called it. It now throws on them, so the nested call is never scheduled, and a run held onmainafterrun()loops on[TMPRL1100]; - an upstream
Runnerwith the user's own Workflow-safe provider worked on 1.24. It is now rejected at run start in any bundle that imports/workflow(check-agent.ts:123-131). The PR body says such runs "failed ... or ran models in the Workflow", which doesn't hold for that case.
Fix: add these to Breaking changes and to this list, and name modelSettings: {} as the opt-out from implicit settings.
There was a problem hiding this comment.
Done in ea99db8. The README's "Upgrading open runs" section now lists these, with modelSettings: {} as the opt-out from GPT-5 defaults, and so does the PR body's Breaking changes list.
Of the plugin's own two:
ModelSummaryProviderno longer breaks: with the per-run provider from the blocking item, nested model calls get their own agent, so a provider that readsagent.nameworks.- The upstream
Runnerwith your own Workflow-safe provider is listed as a break, and the PR body no longer says such runs only failed or ran models in the Workflow.
The usage line is gone from "Not covered".
| return streamed; | ||
| } | ||
| return (await innerRunner.run(converted, preparedInput as any, sharedRunOptions)) as RunResult<any, TAgent>; | ||
| const result = (await innerRunner.run(agent, preparedInput as any, sharedRunOptions)) as RunResult<any, TAgent>; |
There was a problem hiding this comment.
P2: the same SandboxAgent can no longer serve two runs at once, and main histories that did so fail replay. Neither the PR body nor the upgrade section mentions it. Upstream refuses concurrent reuse of one SandboxAgent object (sandbox/runtime/agentKeys.mjs:51-60). main never hit that guard, because convertAgent gave each run its own clone; this line now runs the caller's object.
Probe, same Workflow on both sides, with a fake sandbox client:
Promise.allSettledof tworunner.run(sbx, ...)calls withrunConfig.sandbox:maingives["ok:plain","ok:plain"]. This head gives["ok:plain","err:Agent workflow failed: SandboxAgent 'sbx' cannot be reused concurrently across runs"].- A parent model making two parallel calls to
agentAsTool(sbx, ...):mainanswers both. Here the second tool output isAn error occurred while running the tool. Please try again. Error: Error: SandboxAgent 'sbx' cannot be reused concurrently across runs, and the run completes on that output. - Both
mainhistories replayed on this head fail with[TMPRL1100]. The sequential control replays cleanly.
The upgrade list's "use agentAsTool or agent.asTool()" covers the nested case only by accident, and nothing covers concurrent top-level runs. Fix: list it under Breaking changes, in the Replay list and in the upgrade section. Tell users to create one SandboxAgent per concurrent run, or to set modelSettings: { parallelToolCalls: false } on a parent that calls a sandbox agent's tool.
There was a problem hiding this comment.
Right, that's upstream's rule now reaching the caller's object. In ea99db8 it's in the PR body's Breaking changes and Replay list, and in the README's upgrade section, with your two workarounds: one SandboxAgent per concurrent run, or modelSettings: { parallelToolCalls: false } on an agent that calls a sandbox agent's tool.
| // eslint-disable-next-line @typescript-eslint/no-deprecated -- the alias takes its own deprecated options | ||
| options: AgentAsToolOptions<TAgent> | ||
| ): FunctionTool<any, any, any> { | ||
| return agent.asTool({ |
There was a problem hiding this comment.
P2 (edge): the deprecated alias rejects an agent from another copy of @openai/agents-core, which agentAsTool on main ran. agent.asTool resolves to the other copy's unwrapped method, so the tool is never recorded and checkToolOptions (check-agent.ts:183-193) fails the run as "looks like an agent.asTool() tool that @temporalio/openai-agents did not record".
Probe, bundled with a second copy as in test-openai-agents.ts: main completes through 3 model Activities. This head fails with that AgentsWorkflowError and 0 Activities. With Agent.prototype.asTool.call(agent, { ... }) here (this copy's wrapped method), the run completes through 3 Activities, as on main.
That is the fix. Otherwise the README's "returns agent.asTool(...)" and the PR body's "a deprecated alias that does the same" need the exception.
There was a problem hiding this comment.
Fixed in ea99db8 as you suggested: the alias calls this copy's Agent.prototype.asTool on the agent, so the tool is recorded. The other-copy Worker test has a deprecated-alias case that completes through two model Activities.
| // resolve manifest environment references on the Workflow thread rather than in the resume Activity. | ||
| // fromString lists tools, which runs MCP tool filters; their errors fail the run, as in the run below. | ||
| const restored = (await RunState.fromString(converted, input.toString()).catch((error: unknown) => { | ||
| const restored = (await RunState.fromString(agent, input.toString()).catch((error: unknown) => { |
There was a problem hiding this comment.
P2 (edge): resuming an approval fails when a custom Handoff's callback picked an agent that isn't declared in the graph, a path #237 now reaches. This round trip rebuilds the state from agent. Upstream's buildAgentMap (runState.mjs:2471-2502) only walks declared handoff agents and asTool() sources, and resolveSerializedAgent (:2510-2522) has no fallback for the current agent.
Probe: a Handoff declared with Declared whose callback returns Picked; Picked has a tool with needsApproval. After approving on first.state, runner.run(lead, first.state) fails with AgentsWorkflowError: Agent workflow failed: Agent Picked not found, non-retryable. Native upstream completes the same in-memory resume. main never reached Picked at all.
Fix: round-trip only when the state holds a live sandbox session, or fall back to the in-memory state when fromString can't find its current agent. Otherwise document that an agent a callback returns must also be declared, for example as a handoff of some agent in the graph, to resume its approvals.
There was a problem hiding this comment.
Fixed with your first option, in 35c2b80 and ea99db8. A resumed state is rebuilt with fromString only when it holds sandbox sessions (_sandbox), which is what the round trip protects. Other states resume as they are, as upstream. 35c2b80 came from our own review of the same round trip: approvals behind a copied asTool() tool stayed pending after it, and in a sandbox run the resume now fails with AgentsWorkflowError instead. The summary test now resumes an approval on billing, which only a custom Handoff's callback picks, and fails with Agent billing not found when the round trip always runs. A sandbox run with such an agent still can't resume its approvals; the PR body lists that under "Not covered".
Resuming in memory also keeps the run's context objects, as upstream; the round trip had rebuilt them from JSON. #209's resume test relied on that to make its tool filter throw, so its filter now throws once the run resumes, and the test still checks that the run fails cleanly.
|
|
||
| A passing replay test of old histories doesn't show these runs are safe. Every model call is the same Activity type, and replay doesn't compare Activity inputs, so a run that now makes a different model call can replay without an error and continue with the wrong answer. | ||
|
|
||
| Before resuming a `RunState` saved on an earlier version, give agents unique names across handoffs and `asTool()` tools. The framework also finds `asTool()` agents by name when it restores a `RunState`, and `agentAsTool` tools weren't included, so a saved run can resume on the wrong agent. |
There was a problem hiding this comment.
P3: this advice can resume a saved run on the wrong agent, depending on which agent is renamed. Probe with a state saved from a 1.24-shaped graph (currentAgent: {"name":"X"}, handoff target X). Renaming the handoff target resumes on the asTool() agent, with no error. Renaming the asTool() agent resumes correctly. buildAgentIdentityMap includes asTool() sources (runStateIdentity.mjs:63-66).
Suggested: "rename the asTool() agents; keep the names of the starting agent and its handoff targets".
There was a problem hiding this comment.
Good catch. In ea99db8 the README says to rename the asTool() agent and keep the names of the starting agent and its handoff targets, and the PR body says the same.
|
|
||
| Before resuming a `RunState` saved on an earlier version, give agents unique names across handoffs and `asTool()` tools. The framework also finds `asTool()` agents by name when it restores a `RunState`, and `agentAsTool` tools weren't included, so a saved run can resume on the wrong agent. | ||
|
|
||
| `agentAsTool(agent, { toolName, toolDescription, customOutputExtractor })` is deprecated and will be removed in a later release. It returns `agent.asTool({ toolName, toolDescription, customOutputExtractor })`; call that instead. As upstream, a nested approval now pauses the parent run, where `agentAsTool` failed the tool call with `NestedAgentInterruption`. |
There was a problem hiding this comment.
P3: on 1.24 a nested approval failed the whole run, and code written for that now completes with no output. "failed the tool call with NestedAgentInterruption" understates the old behaviour. Probe on main: run() threw AgentsWorkflowError: Agent workflow failed: Failed to run function tools: ApplicationFailure: Nested agent 'Nested' ... paused for 1 approval interruption(s) (upstream wraps the tool's error). Here the same Workflow completes with finalOutput undefined and one interruption.
Suggested: "where agentAsTool failed the run", plus: check result.interruptions after run() when a nested agent has tools that need approval.
There was a problem hiding this comment.
Fixed in ea99db8: the README now says agentAsTool failed the run, and to check result.interruptions after run() when a nested agent has tools that need approval.
| ``` | ||
|
|
||
| Nested approval interruptions are not supported. If a nested run pauses for approval, the tool invocation fails with `ApplicationFailure` type `NestedAgentInterruption`. | ||
| As in the framework, the nested run takes the run's `model` (for agents that set none) and `modelSettings`. Its model Activities use the same options as the runner's. A nested approval pauses the parent run: approve it on the parent's `result.state` and resume, as in [Run state and approvals](#run-state-and-approvals). |
There was a problem hiding this comment.
P3: nested runs share more with the parent than this paragraph says, and some settings do not carry over.
- They share the parent's
RunContext(agent.mjs:218-226), so context writes and usage accumulate in the parent.main'sagentAsToolpassed no context. traceIncludeSensitiveData, guardrails andhandoffInputFilterare not inherited (agentToolRunConfig.mjs:149-190). The nestedRunnerdefaultstraceIncludeSensitiveDatato true, so tool I/O from nested runs is traced with data even when the parent opted out. This matches upstream andmain; the Python plugin passes the wholeRunConfig.asTool({ onStream })or an.on(...)handler makes the nested run stream. That needs the runner'sstreamingTopicand a hostedWorkflowStream; otherwise the tool output is theStreamingTopicNotConfiguredmessage (activity-backed-model.ts:129-136). Its events are published to the parent's topic with no agent attribution.
One or two sentences each would cover it.
There was a problem hiding this comment.
Added in ea99db8. The nested section says the run shares the parent's run context, so context writes and usage add up there. It says traceIncludeSensitiveData, guardrails and handoffInputFilter aren't inherited, with runConfig: { traceIncludeSensitiveData: false } in asTool()'s options to keep nested tool data out of traces. It also says onStream or on(...) makes the nested run stream, which needs the runner's streamingTopic and a hosted WorkflowStream, and that its events go to the parent's topic without the agent's name.
| | Sessions | Supported | Via `WorkflowSafeMemorySession`; upstream `MemorySession` is rejected | | ||
| | Run state and approvals | Supported | Serialize with `result.state.toString()` and rehydrate with `RunState.fromString` | | ||
| | Guardrails | Supported | Guardrail callbacks must be deterministic | | ||
| | Agent lifecycle hooks | Supported | `agent.on(...)` listeners run in the Workflow and must be deterministic | |
There was a problem hiding this comment.
P3: listener errors behave differently from Node, and this PR is what makes these listeners fire.
- A listener that throws synchronously is ignored: the Workflow's
EventTargetpolyfill catches and drops it (load-polyfills.ts:24-30), and the run completes. In plain Node the same listener fails the run with its error, so a listener used as a guard no longer stops anything. - An
asynclistener that rejects (for example one that awaits a failing Activity) givesWorkflowTaskFailed: Unhandled Promise rejection, a retry loop that leaves the run open.
Fix: rethrow the first listener error after dispatch so the run fails as it does in Node, or at least say both in this row or in the hooks section.
There was a problem hiding this comment.
Fixed in ea99db8: the polyfill's dispatchEvent no longer catches, so as with Node's EventEmitter the first listener that throws stops the dispatch and fails the run. The hooks Worker test has an agent_start guard that now stops the run, and the polyfill unit test checks the new behavior. A rejected async listener isn't awaited, as in Node, and fails the Workflow Task; the README says so under the feature table.
| test('agentAsTool: the deprecated alias returns the agent.asTool() tool', (t) => { | ||
| const agent = new Agent({ name: 'Nested', model: 'm' }); | ||
| // eslint-disable-next-line @typescript-eslint/no-deprecated -- tests the deprecated alias | ||
| const tool = agentAsTool(agent, { toolName: 'ask_nested', toolDescription: 'Ask the nested agent.' }); |
There was a problem hiding this comment.
P3 (tests): two mutants of new code survive the full suite (270 of 270).
- Dropping
customOutputExtractorfrom the alias (agent-tools.ts:139). This test checks only the name, description and record; head behaves correctly (a Worker probe shows the parent receiving the extracted text). Assert that the extractor reachesasTool, or run it in a Worker test. - Initialising
runningAgenttoagentinstead of the state's_currentAgent(runner.ts:256-257). After resuming aRunStatepaused on a handoff target, theModelSummaryProviderlabels the resumed calls with the starting agent: head gives["agent:lead","agent:billing","agent:billing"]and the mutant gives[..., "agent:lead"]. Upstream emitsagent_starton resume only whennoActiveAgentRunis set. Add this resume case to the summary test.
There was a problem hiding this comment.
Both covered in ea99db8:
- The alias unit test runs the tool outside a Workflow with a fake default provider and checks the extractor's output.
- The summary test resumes a
RunStatepaused on billing, and expectsagent:billingfor the resumed call. With the start agent instead of the state's current one, it getsagent:lead.
The runner restored every RunState with fromString, which finds a nested agent only through the tool asTool() returned, so an approval behind a spread or toolNamespace() copy went to the parent agent and stayed pending. States without sandbox sessions now resume as given. A state with sandbox sessions still resumes restored, and the runner fails the resume when one of its approvals belongs to an agent reached only through a copy.
…ix resume, cancellation and listener errors From the second review of 2c2dc14: - Each run, nested ones included, gets a copy of the model provider bound to the agent it's on and its own modelSettings. With no model named and no agent settings, the model Activity gets the run's settings and a flag, and the Worker adds upstream's defaults for its own default model. Upstream's reasoningEffortImplicit marker reaches the Worker's model. A ModelSummaryProvider gets the agent of nested model calls too. - A RunState without sandbox sessions resumes as given, so an agent that a custom Handoff's callback picked resumes its approvals. - The graph checks fail the run instead of every Workflow Task, and a run that fails after a nested cancellation became tool output ends with the cancellation, streamed or not. - The deprecated agentAsTool records tools of agents from another copy of @openai/agents-core. - The Workflow EventTarget polyfill lets a listener's error fail the run, as Node's EventEmitter does. - The README lists what running agents as written changes for open runs.
|
Thanks for the second round. Replies are in each thread; the fixes are in ea99db8. 35c2b80 comes from our own review of the RunState round trip: approvals behind a copied |
…oval tests serially Each test starts its own Worker, and AVA starts the file's concurrent tests at once. With this round's added tests, a slow CI runner held Workflow Tasks past the sandbox's 5-second limit, which crashed Node 22 with "async hook stack has become corrupted". Serial tests run before the concurrent ones, so these ten no longer add to that burst.
DABH
left a comment
There was a problem hiding this comment.
Third round, at head 8e4ebf4 (35c2b80, ea99db8 and 8e4ebf4 on top of 2c2dc14). On a worktree at the head with pnpm 10.27.0: make lint is clean (the 8 warnings already on main), make test passes 285 of 285, and CI is green. CI ran before #166 reached main, so I also merged current main (61fe33a) locally: no conflicts, lint clean, 287 of 287. I re-ran last round's reproductions, then reviewed the three new commits from three angles: replay against main and 2c2dc14, line by line against @openai/agents-core 0.14.3, and tests and docs. Each finding below was reproduced with real Workers against a dev server, running the same Workflow code on main (61fe33a) and on this head, by replaying histories recorded on main, or with a direct probe of the upstream code; the test and wording items come from mutation runs of the suite and from reading the head.
Replay: last round's histories recorded on main replay here as they did on 2c2dc14, except one listener case (below), and four that failed on 2c2dc14 now replay (the undefined tool and a summary provider that reads agent.name). Of 82 new main histories of RunState resumes, 2c2dc14 replays all and this head fails 26 (below).
Refuted and dropped:
- a wrong agent for a model call's settings or summary (checked for handoffs, custom
Handoffs, parallel and nestedasTool()calls, nested resumes, streamed runs and resumed handoff targets); - the
await scope.cancelRequestedincatchhanging or hiding an error (it only replaces errors in a scope that really was cancelled); - a listener error escaping as an unhandled rejection from a non-streamed run (every emit site is inside the awaited run loop);
- the alias with an agent from another
@openai/agents-corecopy (it runs end to end), and false positives incheckRestoredInterruptions; - replay changes for resumes with default MCP caching, sandbox-state resumes and handoff-target resumes, and for an old Workflow Worker with a new Activity Worker;
- a per-activation cost behind the new
test.serialcalls (Workflow Tasks of a 10-turn run with a nestedasTool()take 5-11 ms cached, 13-101 ms replayed in full).
Not verified: the strict-endpoint and compaction effects use fake providers that record or reject the request, not live endpoints.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Previous rounds. The blocking item is addressed in the form upstream TypeScript takes. With no model named, the Worker now adds the defaults for its own default model: with OPENAI_DEFAULT_MODEL=gpt-4.1 there, a model-less agent sends {}, directly and nested. reasoningEffortImplicit now reaches the Worker's model: a run-level reasoning_effort: 'high' survives on a real OpenAIChatCompletionsModel. The original strict-endpoint reproduction still fails when the Worker leaves that variable unset, as native 0.14.3 does; I take that as upstream's rule, with the docs correction inline. Also addressed, each re-checked at this head:
- the upgrade list covers implicit GPT-5 settings,
providerData.reasoning, prompt templates, subclass overrides, usage in the parent and the upstreamRunnercase; - a summary provider gets each nested call's agent, so the
mainhistories that failed replay on 2c2dc14 for that reason replay again; - the one-
SandboxAgent-per-run rule is in Breaking changes, the Replay list and the upgrade section; - the alias records agents from another
@openai/agents-corecopy, and an approval behind a customHandoff's pick resumes (sandbox runs are listed under Not covered); - the cancellation re-raise covers runs that throw, plain and streamed, and an
undefinedtool fails the run; - the rename advice, the nested-approval wording, the nested-run paragraph and the reordering and cancellation replay notes are in;
- both surviving mutants from last round are killed, and removing any of the ten fixes this round names fails its test.
The title now says what breaks, and last round's stale body items are fixed. Every thread has an answer.
Where the problems cluster: last round's fixes work, but two of them changed more than they say, and the listener change exposes a path without error handling.
- Resuming a
RunStatein memory matches upstream and fixes the copied-tool and custom-Handoffapprovals. It also changes the commands of runs that resumed onmain, what their tools see in the context, and which agents a resumed run uses. None of that is in the Replay list or the upgrade section. - The implicit-settings rewrite assumes the agent a run is on is the one upstream calls the model for. For a
SandboxAgentit isn't, so its capability settings are dropped. - Listener errors now propagate, as in Node, but the streamed path passes them to Workflow code unnormalized.
Requesting changes for one item: runs that resumed a RunState on main fail replay here, and open ones get stuck, without a word in the PR body or the README. The other two P2s are regressions from this round and would be good to fix in the same pass.
Smaller docs items (P3).
- README line 120: "Histories of cancelled runs" holds only for runs cancelled during a nested model call.
- README line 441: say that nested runs drop
toolChoiceandparallelToolCallsfrom the run'smodelSettings, as the PR body does. - PR body: the hooks test it names was renamed to "agent.on listeners run, their context writes reach later turns, and one that throws stops the run".
- Release notes: the repository squash-merges with the title as the only subject (
scripts/release/release_tool.py:456), so the notes will be that one line. It's accurate, but the draft release should link the README's "Upgrading open runs" section, which is where the instruction to drain or version open runs lives.
| state: RunState<TContext, TAgent> | ||
| ): Promise<RunState<TContext, TAgent>> { | ||
| let prepared = state; | ||
| if (state._sandbox !== undefined) { |
There was a problem hiding this comment.
P2 (blocking): runs that resumed a RunState on main fail replay here, and open ones stop on Workflow Task failures. Neither the Replay list nor the upgrade section says so.
main sent every resumed state through RunState.fromString(converted, input.toString()) (main runner.ts:286). That restore lists the current agent's tools (runState.mjs:2953) before the approved tools run, and rebuilds the context from JSON. This line now skips it unless the state holds sandbox sessions, so a resumed run schedules different commands.
Histories recorded on main (61fe33a) and replayed here with Worker.runReplayHistory; each replays on main and on 2c2dc14:
- An MCP handle with
cacheToolsList: false, stateless or stateful, with an approval resumed in place or aftercontinueAsNew.mainrecordslist-tools, model, signal, list-tools, list-tools, model; this head schedules one list-tools Activity fewer:[TMPRL1100] Activity type of scheduled event 'probeMcp-stateless-list-tools' does not match activity type of activity command 'invokeModelActivity'('dangerous_action'when the approved tool is an Activity). With default caching it replays. - A context holding a
Date, aMapor a helper object. Onmainthe resumed tool saw the JSON copy (deadlinea string,services.lookup is not a function), even when the Workflow passed a live context toRunState.fromStringWithContext. Here it sees the objects and scheduleslookup:[TMPRL1100] ... 'invokeModelActivity' does not match ... 'lookup'. - A resumed run that failed and was run again with the same
result.state.mainrestored a fresh copy and ran the approved Activity tool again; here the state the failed attempt changed continues:[TMPRL1100] ... 'dangerous_action' does not match ... 'invokeModelActivity'.
Runs held after such a resume, continued here with no Workflow cache, record WorkflowTaskFailed [TMPRL1100] and stay RUNNING; runs held at the approval itself complete. One silent change too: run(rebuiltAgent, result.state) now continues the state's own agents, where main ran the rebuilt ones, so changed instructions, tools or model aren't picked up. By trace, a callable toolFilter that awaits an Activity or timer, which main ran once more per resume, breaks replay the same way.
The PR body mentions the context only under What was changed, and its sentence "neither do the checks added since: they schedule nothing for valid setups" no longer holds; its replay evidence has no resumed state. README line 565 still says a filter on a resumed run "sees the context rebuilt from JSON".
Fix: gate the in-memory resume, for example round-trip when state._sandbox !== undefined || !patched('openai-agents-in-memory-resume'), so runs that resumed before the upgrade keep main's commands. Or, following your no-gate policy, add a Replay bullet and an upgrade bullet for the four cases above, add RunState resumes to the list at README line 118, and fix line 565.
There was a problem hiding this comment.
Thanks for the probes. We're keeping the in-memory resume: it's what upstream does, it fixes the copied-tool and custom-Handoff approvals, and we don't add version gates to fixes before 1.0. So I took your second option, in b893401:
- The README's "Upgrading open runs" section has a bullet for resumes. The resumed run keeps your context objects and the state's own agents, and doesn't list tools before the approved tools run. A failed resume should run again from a fresh
RunState.fromString(...).RunStateresumes are in the list of runs to let finish or pin. - Its replay paragraph lists the histories that fail: a resume that listed tools through
cacheToolsList: falseor a filter that awaits, a tool that used the JSON copy, and a failed resume run again from the same state. - The MCP filter paragraph, and Breaking: refuse a tool meta resolver on the OpenAI Agents MCP factory's server and send _meta from the TypeScript MCP handles #210's resolver paragraph next to it, say which resumes see the context rebuilt from JSON.
- The PR body's Breaking changes and Replay list say the same, and the sentence about the checks scheduling nothing now names the resume as the exception.
| const wire = toSerializedModelRequest(request); | ||
| const hasModelSettings = (agent as { hasExplicitModelSettings?(): boolean } | undefined)?.hasExplicitModelSettings; | ||
| if (this.modelName !== '' || agent === undefined || hasModelSettings?.call(agent) !== false) return wire; | ||
| const modelSettings: ModelSettings = { ...this.run?.modelSettings() }; |
There was a problem hiding this comment.
P2: a SandboxAgent that names no model loses its compaction settings: this replacement drops the providerData that upstream merges in from the agent's capabilities.
For a SandboxAgent, upstream calls the model for the execution copy that prepareSandboxAgent makes (sandbox/runtime/agentPreparation.mjs:46-52, used at run.mjs:704-705 and :1151-1152). That copy has explicit modelSettings, { ...agent.modelSettings, providerData: <capability data> }, which is where the default compaction() capability puts context_management. The agent checked at line 198 is the original agent from agent_start, whose hasExplicitModelSettings() is false, so line 199 rebuilds modelSettings from the run's settings alone.
Probe, real Workers with a fake sandbox client, new SandboxAgent({ name, instructions }) with the default capabilities and no model, same Workflow on main (61fe33a) and this head:
main, and native 0.14.3 without Temporal:{"reasoning":{"effort":"none"},"text":{"verbosity":"low"},"providerData":{"context_management":[{"type":"compaction","compact_threshold":360000}]}}.- This head:
{"reasoning":{"effort":"none"},"text":{"verbosity":"low"}}. The same as a nestedasTool()run of that agent, and withrunConfig.modelSettings: { temperature: 0.2 }. - Controls: with a model name, with
runConfig.model, or withmodelSettings: {}on the agent,context_managementstill reaches the Worker.
So server-side compaction is never requested for these agents, and open runs lose it from their next model call. README line 111 ("a SandboxAgent's compaction threshold follows its model") doesn't hold for them.
Fix: keep the request's providerData when replacing the implicit defaults, for example const modelSettings = { ...this.run?.modelSettings(), ...(request.modelSettings.providerData !== undefined && { providerData: request.modelSettings.providerData }) }. Upstream's implicit defaults never set providerData, so for other agents that is the run's providerData as before. Add a model-less SandboxAgent case that asserts context_management reaches the Worker.
There was a problem hiding this comment.
Good catch. Fixed in b893401 as you suggested: the implicit-settings path keeps the request's providerData, which the defaults never set. A new sandbox Worker test runs a SandboxAgent with no model and the default capabilities, and checks that context_management with compaction reaches the Worker. It fails without the change.
| scope.cancelRequested.then(done, raiseError); | ||
| }; | ||
| completion._raiseError = (error: unknown) => { | ||
| if (!scope.consideredCancelled) return raiseError(error); |
There was a problem hiding this comment.
P2: in a streamed run, a listener that throws leaves the Workflow retrying its Workflow Task instead of failing the run, which README line 805 promises.
This wrapper passes upstream's stream-loop error (run.mjs:1508-1511) to the stream unchanged, while the non-streamed path normalizes it at line 294. A plain Error from a listener therefore reaches Workflow code raw from for await or completed, and fails the Workflow Task.
Probe, agent.on('agent_start', () => { throw new Error('listener boom') }), real Workers:
- non-streamed: FAILED,
AgentsWorkflowError: Agent workflow failed: listener boom; - streamed: still RUNNING after 12 s,
WorkflowTaskFailed: listener boom, retrying (anagent_endlistener does the same after one model Activity); main: both complete, because the listener never ran.
Other streamed errors already reached Workflow code raw on main: a streamed run that exceeds maxTurns: 1 loops the same way there and here. The rethrowing polyfill adds listener errors to that path. Separately, a nested agent's listener error becomes the asTool() tool's output and the parent completes, as in Node; the README sentence doesn't say that either.
Fix: raiseError(normalizeAgentsRunError(error)) in both branches (a CancelledFailure passes through it unchanged), which also fixes the older streamed cases. In README line 805, add the nested case and drop "or runner listener": TemporalOpenAIRunner has no on.
There was a problem hiding this comment.
Thanks. We're leaving the streamed path as it is in this PR. It's the existing gap where every framework error in a streamed run reaches Workflow code unconverted, and converting in _raiseError would change what Workflows that catch streamed errors get today. We're fixing that separately, with a design that throws framework errors as they are on both routes, like the native SDK. The plugin's Workflow interceptor would then convert only what nothing catches, so an Update still fails alone.
19d7cee documents the streamed case in the README. In b893401 that paragraph also says a nested agent's listener error becomes the tool's output, and it drops "or runner listener".
| modelSettings: ModelSettings; | ||
| reasoningEffortImplicit: boolean; | ||
| } { | ||
| const defaults = getDefaultModelSettings(); |
There was a problem hiding this comment.
P3: the strict-endpoint reproduction from the last round still fails. That is now upstream TypeScript's behaviour, but not the Python plugin's, which the PR body cites.
Same probe as last round: a custom provider that rejects reasoning/verbosity and picks its own model for an empty name, and an agent with no model.
main: COMPLETED,{}.- This head,
OPENAI_DEFAULT_MODELunset on the Worker: FAILED,ModelInvocationError.BadRequest, after sending{"reasoning":{"effort":"none"},"text":{"verbosity":"low"}}. - This head with
OPENAI_DEFAULT_MODEL=gpt-4.1on the Worker: COMPLETED,{}. So the Worker's environment is now used, and the_internalmarker arrives: agpt-5agent with a run-levelproviderData.reasoning_effort: 'high'reaches a realOpenAIChatCompletionsModelas'high'. - Native 0.14.3 with the same provider sends the same defaults with the variable unset, so this line matches upstream in one process.
The Python plugin goes further: _align_implicit_model_settings uses getattr(model, "model", None), the name of the model the provider resolved, so a Fireworks or Together model gets no GPT-5 settings there. "as the Python plugin does since #178" in the PR body is therefore inaccurate, and TypeScript users of an OpenAI-compatible endpoint whose agents name no model keep the failure #178 fixed in Python unless they act.
One smaller difference in the same function: run settings set to undefined to clear a default (runConfig.modelSettings: { temperature: 0.3, reasoning: undefined, text: undefined }) clear it upstream, whose merge keeps the keys, but here JSON drops them and line 60 adds the defaults back: the model gets {"reasoning":{"effort":"none"},"text":{"verbosity":"low"},"temperature":0.3}, where native 0.14.3 and main send {"temperature":0.3}.
Suggested: correct the PR body, and add to README line 109: "If the Worker's provider picks a model that isn't GPT-5 for an agent that names none in a run without runConfig.model, such as an OpenAI-compatible endpoint, set OPENAI_DEFAULT_MODEL on the Worker to that model or give the agent modelSettings: {}." Optionally, use the resolved model's name when the Model exposes one (model or name, as upstream's adjustModelSettingsForNonGPT5RunnerModel reads, or the Responses model's _model). The Chat Completions model keeps its name private, so the environment fallback would stay for it.
There was a problem hiding this comment.
Agreed on both. In b893401:
- The PR body no longer cites openai_agents: align implicit model settings with the model a custom provider resolves #178 for this. It says the plugin reads
OPENAI_DEFAULT_MODELas upstream TypeScript does, while the Python plugin uses the resolved model's name. - The README's upgrade bullet says to set
OPENAI_DEFAULT_MODELon the Worker, ormodelSettings: {}on the agent, when the Worker's provider picks a model that isn't GPT-5 for agents that name none. I didn't add the resolved-name lookup, since upstream reads the environment here too. - The
undefinedcase is fixed: the Activity input lists the run settings set toundefined, and the Worker removes those keys after adding the defaults. So{ temperature: 0.3, reasoning: undefined, text: undefined }reaches the model as{ temperature: 0.3 }. The implicit-settings test covers it.
| } | ||
| }); | ||
| } | ||
| for (const listener of [...(this._listeners[event.type] ?? [])]) listener(event); |
There was a problem hiding this comment.
P3: "Before, the error was dropped" (Breaking changes) describes 2c2dc14, not main. On main these listeners didn't run at all, and a main history with one that throws fails replay here.
The previous round's main history with a synchronous agent_start listener that throws (hookErrors, syncThrow) replays on main and on 2c2dc14, and here gives [TMPRL1100] Fail workflow machine does not handle this event: HistoryEvent(id: 5, ActivityTaskScheduled), because the listener now fails the run. The Replay bullet on listeners names only "a different Activity or Timer".
Suggested: "Before, listeners on your agents didn't run (#235)" in Breaking changes, and "a listener that throws now fails the run" in that Replay bullet.
There was a problem hiding this comment.
Fixed in the PR body. Breaking changes now says that before, listeners on your agents didn't run (#235), and the listener entry in the Replay list says a listener that throws now fails the run.
| tracing: JsonValue; | ||
| overridePromptModel?: boolean; | ||
| /** Upstream's internal `reasoningEffortImplicit` marker, which models use to drop an implicit effort. */ | ||
| reasoningEffortImplicit?: boolean; |
There was a problem hiding this comment.
P3: during a rolling deploy, a new Workflow Worker with an old Activity Worker sends named GPT-5 calls without this marker, which nothing documents.
No failures, but the old Activity code ignores reasoningEffortImplicit, and only openaiChatCompletionsModel.mjs:387-394 reads it. Probe with each side in its own process and model Activities on their own task queue: a gpt-5.6 agent with tools and a run-level providerData.reasoning_effort: 'high' reaches the model with {"reasoning":{"effort":"none"},"text":{"verbosity":"low"},"providerData":{"reasoning_effort":"high"}} and no _internal, so Chat Completions sends none, and it sends an effort with tools to gpt-5.6, which upstream leaves out. A model-less agent gets no Worker defaults in that window, as on main. An old Workflow Worker with a new Activity Worker behaves exactly like main.
Suggested: one sentence in the upgrade section to upgrade the Workers that run model Activities first.
There was a problem hiding this comment.
Added in b893401: the upgrade section says to upgrade the Workers that run model Activities before the Workers that run Workflows, since an older Activity Worker drops the marker.
| }); | ||
| }); | ||
|
|
||
| test.serial('With no model named, the Worker adds the model settings defaults for its own default model', async (t) => { |
There was a problem hiding this comment.
P3 (tests): seven mutants of the new code survive the full suite (285 of 285 each).
toWireignoringhasExplicitModelSettings(activity-backed-model.ts:198), so a model-less agent's ownmodelSettingswould be replaced by the run's. Add a model-less agent withmodelSettings: { temperature: 0.9 }.forRunkeeping the parent run's settings for nested runs (activity-backed-model.ts:218): nested model-less calls would carry the parent'stoolChoiceandparallelToolCalls. Add runtoolChoice: 'required', parallelToolCalls: truehere and assert the nested request has neither.- Dropping the
toolChoicedeletion (activity-backed-model.ts:201): a model-less agent with runtoolChoice: 'required'would keep calling tools. Assert the second call has notoolChoice. - Dropping the nested
reasoning/textmerges (activities.ts:63,:65): with runreasoning: { summary: 'auto' }the default effort is lost. Expect{ effort: 'none', summary: 'auto' }. - The marker ignoring the run's own effort (
activities.ts:68). Runreasoning: { effort: 'low' }should givefalse. validateSandboxRunConfigorprepareRunStatemoved back outside thetry(runner.ts:237,:239):handoffs: [undefined], or a sandboxfromStringfailure, would fail every Workflow Task. 35c2b80 moved the MCP-filter resume test to the in-memory path, so the second has lost its test. Add anundefinedhandoff to the rejection test and a sandbox variant of the filter test.
On suite load: once in 28 local full-suite runs at this head (not compared with main), test-openai-agents.js died with SIGSEGV in its concurrent phase, and test-openai-sandbox.js went from 9 to 17 concurrent Workers in this PR. Running each loop of variants in one test with one Worker, as the rejection test does, would cut that further than test.serial.
There was a problem hiding this comment.
Thanks for the mutation pass. In b893401:
- The implicit-settings test gains a case for each mutant: an agent with its own
modelSettings, a nested run undertoolChoice: 'required'andparallelToolCalls: true, a model-less agent that calls a tool undertoolChoice: 'required', runreasoning: { summary: 'auto' }, runreasoning: { effort: 'low' }, and run settings that clear the defaults. - The rejection test has an
undefinedhandoff. The sandbox approval test also resumes with agents that don't have the paused one, which must fail the run, not retry.
Each of these, plus the new sandbox providerData test, fails with its line reverted. On load, the sandbox copy loop is now serial too, like the nested-cancellation and copied-approval loops. I kept test.serial rather than merging each loop into one test, so each case keeps its own name.
|
|
||
| The runner now runs your agents as written. Runs started on an earlier version pick up these changes as they continue, most with no replay error: | ||
|
|
||
| - `runConfig.model` applies only to agents that set no model of their own; those agents switch to their own model from their next model call. |
There was a problem hiding this comment.
P3: "those agents" points at the wrong agents. The agents that switch to their own model are the ones that set one; the sentence's antecedent is the agents that set none. 2c2dc14 had it right: "set runConfig.model and have agents with a model of their own: those agents use their own model from their next model call".
There was a problem hiding this comment.
Fixed in b893401: "Agents that set one switch to it from their next model call."
|
|
||
| Before resuming a `RunState` saved on an earlier version, rename any `asTool()` agent that has the same name as the starting agent or one of its handoff targets, and keep the names of those agents. The framework also finds `asTool()` agents by name when it restores a `RunState`, and `agentAsTool` tools weren't included, so a saved run can resume on the wrong agent. | ||
|
|
||
| `agentAsTool(agent, { toolName, toolDescription, customOutputExtractor })` is deprecated and will be removed in a later release. It returns `agent.asTool({ toolName, toolDescription, customOutputExtractor })`; call that instead. As upstream, a nested approval now pauses the parent run, where `agentAsTool` failed the run with `NestedAgentInterruption`: after `run()`, check `result.interruptions` when a nested agent has tools that need approval. |
There was a problem hiding this comment.
P3: "call that instead" breaks agents from another copy of @openai/agents-core, which the alias now accepts. The alias records the tool through this copy's Agent.prototype.asTool, so the other-copy Worker test's deprecated-alias case runs through 2 model Activities. That agent's own agent.asTool() is the other copy's, unrecorded, and the as-tool case shows the run rejected. Say here and in the agentAsTool JSDoc (agent-tools.ts:130) that the alias also accepts such agents, and that moving to agent.asTool() needs a single copy of @openai/agents-core.
There was a problem hiding this comment.
…Tool Since ea99db8 the alias called Agent.prototype.asTool directly, so an Agent subclass whose asTool override adds needsApproval ran its nested agent with no approval through the alias. The alias now calls agent.asTool() when the agent's asTool isn't its copy's base one; a plain agent from another copy of @openai/agents-core still gets this copy's recorded asTool. The README and the polyfill comment say that a listener error in a streamed run reaches the stream unconverted.
…escript-native-as-tool # Conflicts: # typescript/openai-agents/README.md # typescript/openai-agents/src/__tests__/test-openai-agents.ts # typescript/openai-agents/src/__tests__/workflows/openai-agents.ts # typescript/openai-agents/src/workflow/runner.ts
…n settings, and document resumes From the third review of 8e4ebf4: - With no model named, the implicit-settings path keeps the request's providerData, so a SandboxAgent's compaction reaches the model, and run settings set to undefined still clear a default on the Worker. - The README documents what an in-memory RunState resume changes for open runs, the upgrade order for model Activity Workers, OPENAI_DEFAULT_MODEL for OpenAI-compatible endpoints, nested listener errors and the alias's other-copy agents, and fixes the cancelled-run, nested-settings and runConfig.model wording. - Tests cover the remaining mutants of the implicit settings, an undefined handoff, a sandbox resume that can't be restored and a model-less SandboxAgent's providerData. The sandbox copy loop runs serially.
|
Thanks for the third round. Replies are in each thread, and the fixes are in b893401.
At b893401, lint is clean (the 8 warnings already on |
DABH
left a comment
There was a problem hiding this comment.
Fourth round, at head b893401 (19d7cee, a merge of main at 5b7d9bf, and b893401 on top of 8e4ebf4); the branch is up to date with main (017d88a). On a worktree at the head with pnpm 10.27.0: make lint is clean (the 8 warnings already on main), make test passes 294 of 294, and CI is green. I re-ran last round's reproductions, replayed last round's 82 main histories of RunState resumes and the 168 older main histories against this head, and reviewed the new commits from three angles: replay and the interplay with #240, tests (19 mutants, and 13 runs of each Worker test file under load), and the docs and new code against @openai/agents-core 0.14.3. Each finding below was reproduced with real Workers against a dev server, running the same Workflow code on main (017d88a) and on this head, by replaying histories recorded on main, or with a single-process probe of upstream 0.14.3.
Replay: current main replays all 82 resume histories, and this head fails the same 26 as 8e4ebf4, which the README and the PR body now describe. The 168 older histories give the same result per history as at 8e4ebf4, and every head failure among them is in the Replay list. This round adds one class, agentAsTool with an asTool override (inline). Cross-language: the in-memory resume matches the Python runner, which passes a RunState to the upstream runner as is; the run-model and implicit-settings rules differ from Python as documented.
Refuted and dropped:
- a command change from
toWire's newproviderDatacopy orclearedModelSettings(no history changed result), andclearedModelSettingsgetting lost in the payload converter (plain, nested and streamed runs keep it); - edge cases of
overridesAsTool:Agent.create, multi-level and re-overridden subclasses, an instance-ownasTool, a mixin,SandboxAgent,Object.createof an agent, and an override that doesn't callsupereach run the expectedasTool; - other differences between the Worker's merge and upstream's
mergeModelSettings(nullvalues,reasoning: {},promptCacheOptions,retrywithbackoff, run-levelproviderDatawith aSandboxAgent); - a tracing key reaching Event History from a nested run (it appears in no history, raw or base64);
- flakiness: 13 runs of each Worker test file at load 10-20 passed, and the sandbox file now runs 10 tests concurrently instead of 17.
Not verified: live endpoints; the probes' providers record or reject requests.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Previous rounds. The blocking item is addressed in the second form I suggested. The README's upgrade section has a resume bullet, RunState resumes are in the drain list, the replay paragraph names the three triggers (a tool listing that schedules commands, the context rebuilt from JSON, a failed resume run again from the same state), the filter and resolver paragraphs say which resumes see the JSON copy, and the PR body's Breaking changes and Replay list say the same; run(rebuiltAgent, state) running the state's own agents is stated too. The 26 failing histories fall exactly in those classes. Also addressed, each re-checked at this head:
- a model-less
SandboxAgentsends its compactionproviderDataagain, directly, nested and with run settings; - top-level run settings set to
undefinedclear a default again:{ temperature: 0.3 }reaches the model, as onmainand natively; - the PR body no longer cites #178 for parity, and the README tells users of OpenAI-compatible endpoints to set
OPENAI_DEFAULT_MODELormodelSettings: {}; - Breaking changes says listeners didn't run on
main, and the Replay list says a throwing listener now fails the run; - the upgrade section says to upgrade model-Activity Workers first, which holds in both directions;
- last round's surviving mutants are now killed by the intended assertions, except the nested
textmerge (inline); - the README wording ("those agents", "call that instead", cancelled-run histories, nested
toolChoiceandparallelToolCalls), the test name in the body and the release-note request are done.
Accepted decline: a streamed run still passes a listener's error to Workflow code unconverted, where it fails the Workflow Task; the README now says so, and you plan to fix all streamed framework errors together. Every thread has an answer.
Where the problems cluster: last round's fixes hold, and what's new is smaller.
- One correctness gap, at the seam with #324, which reached the branch in the merge: nested
asTool()runs skip the tracing-key refusal at the top ofrun(), so a keyed nested run is accepted and its resumed approval is lost. - The resume documentation added this round tells users to retry a failed resume in a way that runs approved tools twice, and covers only the
RunStatethatrun()returned. - Parity and wording: nested cleared settings, model-less
SandboxAgents, the alias's new override path, and where a filter's error surfaces aftercontinueAsNew.
#240 and #239. Since my review of #240, #210 has merged, this PR has rewritten both README sentences that review said keeping the context makes false (the tool-filter one and #210's resolver one), and #240 no longer merges cleanly with main. This head fixes #239 for an in-place resume of result.state and for a state restored with RunState.fromStringWithContext(agent, s, new RunContext(live)) after continueAsNew: the approved tool writes the caller's object. It doesn't for a state with sandbox sessions, which runner.ts:367 still rebuilds with RunState.fromString: in a probe, the sandbox tool's write never reaches the caller's object (callerWrites: [], a different object). Neither the body nor the README mentions #239 or #240. With that line changed to RunState.fromStringWithContext(agent, state.toString(), state._context), the write arrives (callerWrites: ["sandbox-tool"], the same object, the same sandbox Activities), and the 20 sandbox tests and the 11 resume and approval tests pass. Landing that change later would break replay a second time for sandbox resumes started on this version: a sandbox resume whose Workflow branches on the context, recorded on this head, fails replay with the change ([TMPRL1100] Nondeterminism error: Activity machine does not handle this event: HistoryEvent(id: 83, WorkflowExecutionCompleted)), and the reverse fails too. I'd fold the line, a test and the README sentences into this PR and say it closes #239, so the drain advice for RunState resumes covers both once. #240's agent-reuse machinery has nothing to reuse once nothing is cloned, so it would then be superseded.
Approving: last round's blocking item is addressed in the form I suggested, the other P2s are fixed or reasonably declined, CI is green, and what's left is one non-blocking P2 in a setup the README already calls unsupported, plus docs and parity items.
Smaller items (P3).
- PR body, What was changed: "an
agent.on(...)or runner listener that throws fails the run";TemporalOpenAIRunnerhas noon(), and the README dropped those words last round. - PR body, Replay list: the resume bullet names a tool that acted on the JSON copy. A
toolMetaResolveror tool filter that read the context is affected the same way:mainhistories with a resolver that calls a context method or branches on it, or a filter that does, fail replay here, in place and aftercontinueAsNew. README line 121's wording already allows for this.
| } | ||
|
|
||
| /** Rejects `asTool()` options that would run model calls or sandbox operations in the Workflow. */ | ||
| export function checkAgentToolOptions({ agent, runConfig, runOptions }: AgentToolRecord, toolName: string): void { |
There was a problem hiding this comment.
P2 (non-blocking): a tracing key in an asTool() tool's runConfig or runOptions isn't refused. A fresh nested run drops it silently, and a resumed nested approval gets #324's refusal as the tool's output, so the approved tool never runs.
#324 refuses tracing: { apiKey } at the top of run() (runner.ts:208-212), and README line 701 says such a run throws in Workflow code. Nested runs start through upstream's Runner directly, and neither these checks nor the run-start check (check-agent.ts:130-187) look at tracing. A fresh nested run joins the parent's trace, so its key is ignored. When the nested run resumes a RunState, upstream applies the run's trace overrides, tracingApiKey included, to the state's trace (run.mjs:304-307, runner/tracing.mjs:182-183), so the resumed nested run carries the key, and the plugin refuses it.
Probe, real Workers, specialist.asTool({ toolName: 'ask_specialist', runOptions: { tracing: { apiKey } } }), and the same with runConfig:
- no approval in the nested agent: completes,
ask_specialist="nested-answer"; - a nested tool with
needsApproval, approved onresult.stateand resumed:ask_specialist="An error occurred while running the tool. Please try again. Error: Error: The OpenAI Agents plugin cannot pass a trace's own tracing key, ..."withinterruptions=0. The approved tool's Activity never runs, and the nested model isn't called again; - the same without the key: the approved tool's Activity runs and the nested agent answers.
The key never reaches Event History and nothing loops on Workflow Task failures, but the approval is used up, and if the model calls the tool again, the fresh nested run is accepted and pauses for approval again. On main neither form ran (native asTool() failed, and agentAsTool took no run options), so this comes with nested runs.
Fix: refuse runConfig.tracing?.apiKey and runOptions.tracing?.apiKey of the recorded asTool() tools before the run, and options?.tracing?.apiKey ?? this.config.tracing?.apiKey in the run-start check for keys set later, where the error is the tool's output before anything runs. run() refuses its own key outside the try on purpose, so that the Workflow Task fails and a fix can be deployed; checking the tools before the try keeps that, while checking them here makes the run fail. README line 701 could name asTool() options.
There was a problem hiding this comment.
Fixed in 5f121bf. agent.asTool() in Workflow code now throws when its runConfig or runOptions has tracing: { apiKey }. It throws when the tool is made, which is before run() and outside its try, so the Workflow Task fails, as with run()'s own key. The run check also refuses options.tracing?.apiKey ?? config.tracing?.apiKey when each run starts. So a key set on those options later stops the nested run before anything runs, and the error is the tool's output. README line 701 now names the asTool() options.
Tests: two new entry points in the tracing-key test (asTool() with the key in runOptions and in runConfig), and two tool-start-*-tracing-key cases in the running-agent test. Each fails when its check is removed.
| - As upstream, one `SandboxAgent` object serves one run at a time. A second concurrent run, or a second parallel call of its `asTool()` tool, fails with `SandboxAgent '...' cannot be reused concurrently across runs`. Create one `SandboxAgent` per concurrent run, or set `modelSettings: { parallelToolCalls: false }` on an agent that calls a sandbox agent's tool. | ||
| - A run cancelled during a nested model call ends cancelled, where it failed before. So does a run with `stop_on_first_tool` whose tool caught its own Activity's cancellation, which completed before. | ||
| - An upstream `Runner` can't run agents in a Workflow, even with your own Workflow-safe model provider; use `TemporalOpenAIRunner`. | ||
| - A run resumed from the `RunState` that `run()` returned continues that state as it is, as upstream: its tools see your context objects, not a copy rebuilt from JSON, the state's own agents run, not the ones you pass to `run()`, and the resume doesn't list the agent's tools before the approved tools run. A state with sandbox sessions is still restored from its string first. Run a failed resume again from a fresh `RunState.fromString(...)`, not from the state the failed attempt changed. |
There was a problem hiding this comment.
P3: the retry advice added here runs approved tools twice. Retried from the same state, a failed resume continues where it failed, as upstream, and runs each approved tool once; a fresh RunState.fromString(...) of a string saved after the approvals runs them again, as main did.
Probe, real Workers: the approved tool awaits an Activity, the model call after it fails once with HTTP 400, and the Workflow runs the resume again.
- This head: from the same state, the tool's Activity runs once and the retry continues with its output; from
state.toString()taken after the failure, also once; from a string saved afterapprove()and before the attempt, twice. main: twice in all three.- Native 0.14.3 in one process: once, twice, once.
The sentence also doesn't say which string to use: the string in the README's own continueAsNew example predates approve(), so a resume from it pauses again. My last comment listed the re-run as a replay difference, not as behaviour to keep. Suggested: "Run again from the same state, a failed resume continues where it failed, as upstream, and doesn't run the approved tools again; before, it ran them again."
The bullet also covers only "the RunState that run() returned". main sent every RunState through RunState.fromString (main runner.ts:294), so a state the Workflow restored itself after continueAsNew changes too: it isn't listed a second time, and a context given to RunState.fromStringWithContext now reaches the tools as passed, where main replaced it with a JSON copy (the main histories c-helper-canwc and m-sl-nocache-fn-can fail here for those reasons). "A RunState passed to run()" covers both, here and in the PR body's bullet.
There was a problem hiding this comment.
Thanks, fixed in 5f121bf with your wording: "A failed resume run again from the same state continues where it failed, as upstream, and doesn't run the approved tools again; before, it ran them again." The bullet now starts with "A RunState passed to run()" and says that a context given to RunState.fromStringWithContext reaches the tools as passed. The PR body's Breaking bullet says the same.
| if (request.modelSettings.providerData !== undefined) | ||
| modelSettings.providerData = request.modelSettings.providerData; | ||
| // A run setting set to `undefined` clears a default upstream, but JSON would drop it. | ||
| const cleared = (Object.keys(modelSettings) as (keyof ModelSettings)[]).filter( |
There was a problem hiding this comment.
P3: the clearing covers top-level keys only, so a run setting that clears a nested default, such as reasoning: { effort: undefined } or text: { verbosity: undefined }, still gets the Worker's default.
JSON turns { reasoning: { effort: undefined } } into { reasoning: {} }, which this filter doesn't list, and withDefaultModelSettings merges the default effort back in (activities.ts:65-67). Probe, a model-less agent, runConfig.modelSettings: { temperature: 0.3, reasoning: { effort: undefined } }, Worker without OPENAI_DEFAULT_MODEL:
- native 0.14.3:
reasoning: { effort: undefined }, so no effort is sent; - this head:
{"reasoning":{"effort":"none"},"text":{"verbosity":"low"},"temperature":0.3}; main:{"temperature":0.3,"reasoning":{}}.
text: { verbosity: undefined } gives verbosity: 'low' here, where native sends none. Spreading an optional value, as in reasoning: { effort: options.effort, summary: 'auto' }, is the likely way in. The PR body's "run settings set to undefined still clear a default" holds for top-level keys only.
Fix: also list the reasoning and text keys set to undefined (the only nested keys the defaults set), for example as 'reasoning.effort', and delete them after the merge. Separately, the text merge at activities.ts:68 still survives deletion (294 of 294); a case with run text: {}, expecting the GPT-5 defaults and the marker true, kills it.
There was a problem hiding this comment.
Fixed in 5f121bf. The Workflow now also lists the reasoning and text keys set to undefined, as reasoning.effort or text.verbosity, and the Worker deletes them after the merge. With your probe's settings the model now gets { reasoning: {}, text: {}, temperature: 0.3 } and the marker true, as natively. I added that case and a run text: {} case (GPT-5 defaults, marker true) to the implicit-settings test. The text: {} case kills the text merge mutant, and the test fails with either new deletion step removed.
| private toWire(request: ModelRequest, agent: Agent<any, any> | undefined): SerializedModelRequest { | ||
| const wire = toSerializedModelRequest(request); | ||
| const hasModelSettings = (agent as { hasExplicitModelSettings?(): boolean } | undefined)?.hasExplicitModelSettings; | ||
| if (this.modelName !== '' || agent === undefined || hasModelSettings?.call(agent) !== false) return wire; |
There was a problem hiding this comment.
P3: a SandboxAgent that names no model takes this path, but upstream calls its model with explicit settings, so run-level reasoning and text settings now override its defaults, the marker differs, and its compaction threshold still follows the Workflow's default model rather than the Worker's.
prepareSandboxAgent gives the execution copy modelSettings: { ...agent.modelSettings, providerData } (sandbox/runtime/agentPreparation.mjs:49-52), and for a model-less agent agent.modelSettings holds the constructor's defaults for the default model. #prepareModelCall therefore sees explicit settings, merges them over runConfig.modelSettings and sends the marker false (run.mjs:1525-1540). This line checks the original agent, so the path below sends the run's settings and the Worker merges its defaults under them.
Probe, new SandboxAgent({ name, instructions }) with the default capabilities, real Workers on main and this head, and native 0.14.3:
runConfig.modelSettings: { reasoning: { effort: 'high' } }: native andmainsendeffort: 'none', this head'high';{ text: { verbosity: 'high' } }likewise gives'low'against'high';- no run settings: the same settings everywhere, but the marker is
truehere andfalsenatively; OPENAI_DEFAULT_MODEL=gpt-4oon the Worker (and in the native process): this head sendscompact_threshold: 360000,main360000 with GPT-5 settings, native 115200. The threshold is computed in the Workflow, whereresolveSandboxModelfalls back togetDefaultModel(), gpt-5.4-mini (agentPreparation.mjs:95-125). Above gpt-4o's 128K window, compaction never triggers.
The first two follow what the run asks for, but they aren't upstream's behaviour, which line 193 and the PR body say this follows; the third predates the PR. README line 111 ("a SandboxAgent's compaction threshold follows its model") doesn't hold for these agents, and neither remedy at line 109 changes it. Suggested: say in the upgrade section that a model-less SandboxAgent takes the run's reasoning and text over its defaults, and that its compaction threshold follows gpt-5.4-mini unless the agent or runConfig.model names a model. Or send a flag for SandboxAgents so the Worker merges its defaults over the run's settings, as upstream's execution copy does.
There was a problem hiding this comment.
Documented in 5f121bf, as in your first suggestion, with no Worker flag. The upgrade section has a new bullet: a SandboxAgent that names no model, in a run without runConfig.model, takes the run's reasoning and text settings over its defaults, where upstream lets the defaults win, and its compaction threshold follows gpt-5.4-mini unless the agent or runConfig.model names a model. Line 111, the comment here and the PR body no longer say this follows upstream.
| // An override of `asTool` runs, as with `agent.asTool()`. Otherwise this copy's `asTool`, which | ||
| // records the tool, also for an agent from another copy of `@openai/agents-core`, as `agentAsTool` | ||
| // ran such agents before. An override on such an agent makes that copy's tool, which the runner rejects. | ||
| if (overridesAsTool(agent)) return agent.asTool(toolOptions); |
There was a problem hiding this comment.
P3: calling the override changes the commands of main runs whose agent's class overrides asTool, and makes the alias reject such an agent from another copy of @openai/agents-core. The Replay list doesn't mention the first, and README line 125 and the JSDoc at line 131 say the alias accepts other-copy agents.
On main, agentAsTool built its own tool and never called asTool (main agent-tools.ts:24). Histories recorded on main with an Agent subclass whose asTool adds needsApproval, or wraps invoke around a timer, replay on main and on 8e4ebf4 and fail here: [TMPRL1100] Nondeterminism error: Complete workflow machine does not handle this event: HistoryEvent(id: 11, ActivityTaskScheduled) (Timer machine does not handle this event for the wrapper). The history of a run held after that call fails the same way (No command scheduled for event HistoryEvent(id: 11, ActivityTaskScheduled)), so such a run stops on Workflow Task failures. An override that only changes the description replays. For another copy, this PR's deprecated-alias-override case expects the run to be rejected (looks like an agent.asTool() tool), where 8e4ebf4 and main ran that agent; only the comment at line 147 says so.
README line 119 already tells users to drain every agentAsTool run, so this is wording: add the override case to the Replay list, and "unless its class overrides asTool()" to README line 125 and the JSDoc.
There was a problem hiding this comment.
Wording fixed in 5f121bf. The Replay list has the override case: an override that adds needsApproval or wraps invoke fails with [TMPRL1100], a run held after that call stops on failed Workflow Tasks, and one that only changes the description replays. README line 125, the JSDoc and the Breaking bullet now say the alias accepts an agent from another copy "unless its class overrides asTool()".
| ``` | ||
|
|
||
| The agent applies this option in the Workflow each time it lists tools; the handle caches the server's full tool list, not the filtered one. A callable filter runs for each tool on every listing, gets the name the server was registered with as `serverName`, and must be deterministic. An Activity or timer it awaits adds commands that older plugin versions never schedule, so let Workflows that use the option finish before you roll the plugin back. A filter assigned to a stateful handle later (`server.toolFilter = ...`) gets the handle's internal name, `<name>-stateful`. A callable filter also runs when a run resumes from a `RunState`, for example after a tool approval, and then sees the context rebuilt from JSON: plain objects, without class methods. If it throws there, the run fails with an `AgentsWorkflowError`. | ||
| The agent applies this option in the Workflow each time it lists tools; the handle caches the server's full tool list, not the filtered one. A callable filter runs for each tool on every listing, gets the name the server was registered with as `serverName`, and must be deterministic. An Activity or timer it awaits adds commands that older plugin versions never schedule, so let Workflows that use the option finish before you roll the plugin back. A filter assigned to a stateful handle later (`server.toolFilter = ...`) gets the handle's internal name, `<name>-stateful`. A callable filter also runs when a run resumes from a `RunState`, for example after a tool approval. A state from `RunState.fromString`, as after `continueAsNew`, or with sandbox sessions, which the runner restores, has the context rebuilt from JSON: plain objects, without class methods. If the filter throws there, the run fails with an `AgentsWorkflowError`. |
There was a problem hiding this comment.
P3: for a state the Workflow restores with RunState.fromString, as after continueAsNew, a throwing filter doesn't fail the run with an AgentsWorkflowError: it throws its own error from that fromString call, before run().
Upstream's fromString lists the current agent's tools for an interrupted state (runState.mjs:2948-2953), so the filter runs inside the Workflow's own call. Probe, a callable filter that calls a class method on the context, an approval, then RunState.fromString(agent, state.toString()): RunState.fromString threw TypeError type=undefined: runContext.context.svc.allowed is not a function, the same on main and this head. Uncaught, it fails the Workflow Task, not the run. The sentence predates this PR, but this round's rewording names that case. Suggested: "... has the context rebuilt from JSON. A filter that throws while RunState.fromString lists tools makes that call throw its error; during a resume in run(), the run fails with an AgentsWorkflowError."
There was a problem hiding this comment.
Fixed in 5f121bf with your wording. Sandbox resumes now keep the context too (see my reply to the review summary), so this sentence and the matching one in the resolver paragraph no longer list sandbox states as rebuilt from JSON.
…gs, keep the context on sandbox resumes
- agent.asTool() in Workflow code refuses tracing: { apiKey } in its
runConfig or runOptions, as run() does with its own key. The run check
refuses a key set on those options later, so the nested run doesn't
start and the error is the tool's output.
- Run settings that set a reasoning or text key to undefined clear that
default on the Worker too.
- A RunState with sandbox sessions is rebuilt with
RunState.fromStringWithContext and its own context, so an approved tool
writes the caller's object (#239).
- README: retrying a failed resume, the alias and asTool overrides, filter
errors in RunState.fromString, tracing keys in asTool() options, and the
settings of a SandboxAgent that names no model.
|
Thanks for the fourth round. I answered the inline threads there. The summary items, all in 5f121bf:
Checks at 5f121bf: lint has 0 errors (the 8 warnings already on |
What was changed
TemporalOpenAIRunnerruns the caller's agents as they are written. It no longer clones the agent graph to swap in Activity-backed models. Its innerRunnergets a model provider,ActivityBackedModelProvider, that sends every model name to the plugin's model Activity with the runner's Activity options, and the run'smodel.agent.asTool()runs, so the framework's ownasTool()now works in a Workflow. Nested runs take the run'smodel(for agents that set none), itsmodelSettingswithouttoolChoiceandparallelToolCalls, itscontextand sandbox, and the runner's Activity options.agentAsToolandAgentAsToolOptionsbecome deprecated aliases for one release:agentAsToolreturnsagent.asTool({ toolName, toolDescription, customOutputExtractor }). The hook that passed the sandbox to it is removed.agent.on(...)listeners on the caller's agents fire, and a customHandoffhands off to the agent its callback returns.convertAgentbecomescheckAgent, which checks the graph without changing it: raw functions intoolsandModelobjects, through handoffs andasTool()tools. It also rejectsasTool()options that would run model calls or sandbox operations in the Workflow:runConfig.modelProvider(evenundefined, which upstream spreads over the runner's provider), aModelobject asrunConfig.model, a sandbox client or live session not fromtemporalSandboxClient(), and aMemorySession.Agent.prototype.getSystemPrompt, which upstream calls once per model call, after it picks the model. This covers agents the check before the run can't see: one that a customHandoff's callback returns, or one that anagent.on(...)listener changes. Its model must be a name, and itsasTool()tools must pass the checks above. In the outer run, the run fails. In a nested run, the error goes back to the parent model as the tool's output, and the model isn't called. An agent from another copy of@openai/agents-core, such as one a dependency brings, is checked the same way: the plugin wraps that copy'sAgent.prototype.getSystemPromptbefore the agent's first model call, from the check before the run, from each run's start and from the runner'sagent_startevent.asTool()tool'srunConfigandrunOptionsonly when the nested run starts, after the tool'sparametersschema, itsinputBuilderand anyagent_tool_startlistener ran. So the plugin also checks eachRunnerrun as it starts, by wrappingRunner.prototype.runin the Workflow: the run's model provider must be the runner's, itsrunConfig.modela name, its session not aMemorySession, and its sandbox config must pass the checks above. A nested run that fails this doesn't start, and the error is the tool's output. The run then uses a frozen copy of its sandbox config, which upstream reads as it goes, so a later change to the caller's object, for example in anagent_startlistener, doesn't reach it.asTool()tool made in Workflow code withtracing: { apiKey }in itsrunConfigorrunOptionsthrows, asrun()does with its own key, so the Workflow Task fails until the code changes. A resumed nested run would carry that key. The run check also refuses a key set on those options later, so that nested run doesn't start and the error is the tool's output.useLocalActivitynow fails inActivityBackedModel, not only inrun(), so a nestedasTool()run withonStreamoron()handlers is rejected too.asTool()tool returns a nested run's failure as its output, including a cancelled model Activity. If the run's cancellation scope was cancelled,run()now throws theCancelledFailureinstead of returning, and a streamed run fails with it, even when the run ended on that output, for example withtoolUseBehavior: 'stop_on_first_tool'.asTool()tool, which upstream keeps private, the plugin wrapsAgent.prototype.asToolin the Workflow before the Workflow module loads, and records each tool's agent and therunConfigandrunOptionsit was made with. The returned tool is not modified. The record is keyed by the tool'sonclosure, so copies, such as the onestoolNamespace()makes, keep it. A tool that looks like anasTool()tool but wasn't recorded, such as one made by an agent from another copy of@openai/agents-core, is rejected.agent_startand a resumed state's current agent, and its ownmodelSettings. AModelSummaryProvidergets that agent for each model call.modelSettings, the model Activity gets only the run's settings and a flag, and the Worker adds upstream's defaults for its own default model (OPENAI_DEFAULT_MODEL), as upstream TypeScript does in one process. The Python plugin goes further since openai_agents: align implicit model settings with the model a custom provider resolves #178 and uses the name of the model its provider resolved. The settings aSandboxAgent's capabilities add asproviderData, such as compaction, are kept, and run settings set toundefined, also keys ofreasoningandtext, still clear a default. ASandboxAgentthat names no model takes this path too, so the run'sreasoningandtextsettings win over its defaults, where upstream lets the defaults win, and its compaction threshold followsgpt-5.4-mini, the Workflow's default model, unless the agent orrunConfig.modelnames a model. Upstream'sreasoningEffortImplicitmarker reaches the Worker's model too.RunStateis rebuilt from its string only when it holds sandbox sessions, and then withRunState.fromStringWithContextand the state's own context objects. Other states resume as they are, as upstream, so an approval behind a copiedasTool()tool, or on an agent that a customHandoff's callback picked, resumes. Before, a resumed run's context was rebuilt from JSON, so an approved tool wrote a copy of the caller's context ([Bug] openai-agents (TypeScript): after an approval resume, tools write a copy of the run context, not the caller's object #239). A sandbox state with an approval on an agent reached only through a copiedasTool()tool fails the resume withAgentsWorkflowError, where it stayed pending.run()'s error handling, so a malformed graph, such as anundefinedtool, fails the run instead of every Workflow Task. If the scope was cancelled, a run that fails after a nested cancellation became tool output ends with the cancellation too.EventTargetpolyfill lets a listener's error reach the code that emitted the event, as Node'sEventEmitterdoes, so anagent.on(...)listener that throws fails the run.agent.asTool(), lists the rejected nested setups, the check before each model call (including agents from another copy of@openai/agents-core) and the check when each run starts, explains cancellation when a run ends on a tool's output and which nested failures become the tool's output, adds agent lifecycle hooks to the feature table, saysrunConfig.modelapplies to agents that set none, and adds an "Upgrading open runs" section.Migration: replace
agentAsTool(agent, { toolName, toolDescription })withagent.asTool({ toolName, toolDescription }), created in Workflow code.agentAsToolstill works for one release, as a deprecated alias that does the same.Why?
Three defects had the same root, the plugin's copies of the framework's objects:
agentAsTool, the plugin's partial copy ofasTool(), dropped the run's model, model settings and runner defaults. The framework's ownasTool()didn't run the nested agent at all: the parent model gotNo default model provider setas the tool result.agent.on(...)listeners on the caller's agents never fired.Handoff's callback returns, so the run went to the wrong agent.With a provider on the runner, upstream's code does the work, including fields it passes to nested runs later.
Breaking changes
agentAsToolandAgentAsToolOptionsare deprecated.agentAsToolnow returns anagent.asTool()tool, so it behaves as below. It still accepts an agent from another copy of@openai/agents-core, unless its class overridesasTool().Agents run as written, so upstream's own rules now apply to them, as the README's "Upgrading open runs" section lists. A GPT-5 agent without
modelSettingsgets upstream's defaults for its model (modelSettings: {}sends none), explicit GPT-5providerData.reasoningreaches the model, an agent with aprompttemplate and no model or tools gets the template's,Agentsubclass overrides run, and aSandboxAgent's compaction threshold follows the model it orrunConfig.modelnames. ASandboxAgentthat names no model takes the run'sreasoningandtextsettings over its defaults. OneSandboxAgentobject serves one run at a time: a second concurrent run, or a second parallel call of itsasTool()tool, fails withSandboxAgent '...' cannot be reused concurrently across runs.An
agent.on(...)listener that throws now fails the run, as in Node. In a nestedasTool()run its error is the tool's output, and in a streamed run it reaches the stream unconverted, as that route's other errors do. Before, listeners on your agents didn't run ([Bug] openai-agents (TypeScript): agent.on(...) lifecycle hooks never run through TemporalOpenAIRunner #235).A
RunStatepassed torun()is resumed as it is, as upstream: its tools see your context objects, including a context given toRunState.fromStringWithContext, not a copy rebuilt from JSON; the state's own agents run, not the ones passed torun(); and the resume doesn't list the agent's tools before the approved tools run. A state with sandbox sessions is still restored from its string first, with the same context objects. A failed resume run again from the same state continues where it failed and doesn't run the approved tools again.runConfig.modelnow applies only to agents that set no model of their own, as upstream. Before, it replaced every agent's model. Runs in progress andRunStatesaved before the upgrade follow the new rule from their next model call: an agent that sets its own model switches to it, without an error. Let those runs finish before upgrading, or use Worker Versioning. Upstream's docs sayRunConfig.modeloverrides every agent's model, but its code and tests (selectModel,test/run.test.ts) let the agent's own model win, and the plugin follows the code. The Python plugin follows the Python SDK, where the run's model wins.Nested runs behave like upstream
asTool(). A nested run's failure goes back to the parent model as the tool's output instead of failing the run. This includes model Activity failures that aren't retried, such as an authentication error, and a nestedSandboxAgentin a run withoutrunConfig.sandbox, which failed the run before. The parent model may call the tool again untilmaxTurns, and that error doesn't carry the cause. A nested approval pauses the parent run instead of failing it withNestedAgentInterruption. Nested model calls use the runner's Activity options, includinguseLocalActivityandcancellationType.A
SandboxAgentreturned by a customHandoff's callback, in a run withoutrunConfig.sandbox, fails the run with upstream's error, anAgentsWorkflowErrorwithSandboxAgent execution requires RunConfig.sandbox.An agent that a custom
Handoff's callback returns, or that anagent.on(...)listener changes, now fails the run if its model is aModelobject or one of itsasTool()tools is rejected, including an agent from another copy of@openai/agents-core. AnasTool()tool whoserunConfigorrunOptionsa listener, itsinputBuilderor itsparametersschema changes to a rejected setup doesn't start its nested run; the error is the tool's output, as upstream.An upstream
Runner, orrun(), can't run agents in a Workflow: its run is rejected unless its model provider is the plugin's. Before, it failed withNo default model provider set, ran models in the Workflow, or, with your own Workflow-safe provider, worked. UseTemporalOpenAIRunner.A
runConfig.sandbox.sessionthat isn't from a Temporal sandbox client is rejected withSandboxConfigurationError.asTool()tools must be created in Workflow code, so the plugin can record them. Copies keep the record; a tool made by an agent from another copy of@openai/agents-coreis rejected.Replay: a passing replay test of old histories doesn't show that an upgrade is safe. Every model call is the same Activity type, and replay doesn't compare Activity inputs, so a run that now makes a different model call replays without an error and continues with the wrong answer. Runs that started before the upgrade keep working, except these:
useLocalActivity: the nested model call was a regular Activity and is now local, so replay fails with[TMPRL1100];cancellationType: ABANDONthe nested call no longer requests cancellation, so replay fails with[TMPRL1100]. A run withstop_on_first_toolwhose tool caught its own Activity's cancellation completed before and now ends cancelled;agentAsToolor a parallel branch next torun(): model calls are scheduled a little later in the turn, so the two can swap places. Replay then fails with[TMPRL1100], or, when both are model calls, each gets the other's recorded answer;SandboxAgentin two runs at once, or in parallel calls of itsasTool()tool: the second now fails, so replay fails with[TMPRL1100];agent.asTool()before this change: the nested agent never ran, and now it schedules a model Activity. A run held afterrun()continues with the parent's recorded response as the nested agent's answer;agentAsToolruns whose nested run failed: the failure now goes back to the parent model. If the Workflow then did other work, such as a recovery Timer, replay fails with[TMPRL1100]. If that work was a model call, such as a recovery agent, the run replays and continues without an error, but returns the wrong answer and skips itscatchbranch;agent.on(...)listeners, or that go through a customHandoffwhose callback returns a different agent from the one it was declared with: these now take effect, and a listener that throws now fails the run. A different Activity or Timer fails replay with[TMPRL1100]; a different model call doesn't;RunState: before, the plugin restored every resumed state from its string, which listed the agent's tools again and rebuilt the context from JSON. Replay fails with[TMPRL1100]when that listing scheduled an Activity (an MCP server withcacheToolsList: false, or a tool filter that awaits an Activity or timer), when a tool, atoolMetaResolveror a tool filter used the JSON copy, such as aDatethat was a string or a class method that was missing, or when a failed resume was run again from the same state. Open runs held after such a resume stop on failed Workflow Tasks;agentAsToolruns whose agent's class overridesasTool(), for example to addneedsApprovalor to wrapinvoke: the alias now calls the override, so replay fails with[TMPRL1100], and a run held after that call stops on failed Workflow Tasks. An override that only changes the description replays;runConfig.modeland agents that set their own model, above;RunStatesaved before the upgrade in which anasTool()agent has the same name as the starting agent or a handoff target: the framework also findsasTool()agents by name when it restores aRunState, andagentAsTooltools weren't included, so the run can resume on the wrong agent. Rename theasTool()agent, not the other.Let these runs finish before upgrading, or use Worker Versioning. The README's "Upgrading open runs" section says the same.
Checklist
Closes [Bug] openai-agents (TypeScript): agentAsTool runs drop the run's model, model settings and runner defaults #243, closes [Bug] openai-agents (TypeScript): agent.on(...) lifecycle hooks never run through TemporalOpenAIRunner #235, closes [Bug] openai-agents (TypeScript): TemporalOpenAIRunner ignores the agent a custom Handoff's callback returns #237, closes [Bug] openai-agents (TypeScript): after an approval resume, tools write a copy of the run context, not the caller's object #239. Replaces fix(openai-agents): give agentAsTool runs the run model, model settings and runner defaults #244, Run agent.on(...) lifecycle hooks in TemporalOpenAIRunner #236, fix(openai-agents): hand off to the agent a custom Handoff returns #238 and Breaking: keep the caller's run context when resuming a RunState in OpenAI Agents #240.
How was this tested:
New Worker tests:
agent.asTool() runs take the run model, model settings and runner defaults;agent.on listeners run, their context writes reach later turns, and one that throws stops the run;A custom Handoff hands off to the agent its callback returns;agentAsToolreplaced byasTool();runConfig.model leaves an agent that sets its own model on that model, as upstream.Each of these fails without the change.
A ModelSummaryProvider gets the agent of each model call, in nested and resumed runs too: the lead, the nested expert, and billing, which a customHandoff's callback picks, before and after its approval resumes in memory.Tests from the review rounds, which pass on this design:
Agents picked or changed during the run are checked before they call their model. It covers aModelobject from a customHandoff's callback, a callback-returned agent with anasTool()tool that setsrunConfig.modelProvider, andagent_startlisteners in the outer and a nested run. It also covers anasTool()tool whose capturedrunConfiganagent_tool_startlistener changes to amodelProvider, tomodelProvider: undefined, or to aModelobject for a model-less nested agent; aninputBuilderthat sets amodelProvider; andasTool({ runConfig: { modelProvider: undefined } }), with a default model provider registered. Each is rejected before the nested model is called, and each replays. Without the checks, the inline model runs in the Workflow. A control, a listener that changes the tool'srunConfig.modelto another name, schedules two model Activities and the nested call uses the new name. AparametersZod refinement that sets amodelProviderwas checked the same way in a local probe (the plugin has no directzoddependency): the inline model ran without the run check and was rejected with it;Agents from another copy of @openai/agents-core are checked before they call their modelbundles a second, unmodified copy of@openai/agents-core0.14.3. It covers three ways such an agent gets aModelobject: anagent_startlistener, a customHandoff's callback, and a tool between two turns. Each is rejected before the model is called (0, 1 and 1 model Activities), and each replays. Without the fix, all three ran the inline model in the Workflow. A control agent from that copy with a string model completes through one model Activity;A sandbox client that an agent_start listener replaces with a raw one never runs: the run completes through sandbox Activities; without the frozen copy, the raw client ran in the Workflow. Theagent_tool_startvariant, on anasTool()tool'srunOptions.sandbox, is rejected as the tool's output without calling the backend. Both replay. A rawrunConfig.sandbox.sessionis rejected; without the check it ran in the Workflow;stop_on_first_tool, plain and streamed. Without the fix, both completed withActivityFailure: Activity cancelledas output. WithmaxTurns: 1, where the run fails after the tool, plain and streamed runs end CANCELLED too. Two controls, the default loop andstop_on_first_toolwithout cancelling, pass with and without the fix;continueAsNewwith an agent that is both a handoff target and anasTool()source;onStreamand toon()handlers, including a handler registered after the run starts;useLocalActivity: the nested model isn't called, and the tool's output is theStreamingLocalActivityUnsupportedmessage. Without the check, the nested model streamed through a local Activity;asTool()options object, with a tool made at module scope before@temporalio/openai-agents/workflowloads, which the Workflow interceptor module records;asTool()tool from a second copy of@openai/agents-core, rejected before any model call, and a run-startMemorySessionset from anagent_tool_startlistener, rejected as the tool's output;SandboxAgentin a run withoutrunConfig.sandbox: its error is the tool's output, as upstream;With no model named, the Worker adds the model settings defaults for its own default model: withOPENAI_DEFAULT_MODEL=gpt-4.1on the Worker, a model-less agent, directly and nested, gets only the run's{ temperature: 0.3 }, where the Workflow's own default added GPT-5 settings; with the default unset it getsgpt-5.4-mini's. A namedgpt-5lead keeps upstream's settings, and thereasoningEffortImplicitmarker reaches the model;undefinedentry intoolsorhandoffsfails the run, and so does a sandbox resume thatfromStringcan't restore;SandboxAgentthat names no model sends its compactionproviderData;agentAsToolwith an agent from a second copy of@openai/agents-coreruns through two model Activities;agent_startlistener that throws stops the run;an approval inside a nested asTool() run resumes on result.state, for theasTool()tool, the deprecated alias, a spread copy and atoolNamespace()copy, and a nested approval in a sandbox run, which resumes behind theasTool()tool and fails the resume behind a copy, with the parent namedsandbox-parentorNestedand with rebuilt agents. The copy cases stayed pending without the change.Each fix from the fourth review round fails its test when removed: the tracing key refused when an
asTool()tool is made, forrunOptionsandrunConfig, and when its nested run starts, for each; the nested cleared settings, on the Workflow and on the Worker; thetextmerge; and the sandbox resume's context, whose approved tool now writes the caller's object.Without the interceptor module's install, the module-scope tool's run is rejected; without the run-start
MemorySessioncheck, the nested run uses it. Each fix from the third review round fails its test when removed: the agent's own settings, nested settings withouttoolChoiceandparallelToolCalls, thetoolChoicereset, thereasoningmerge, the marker under the run's own effort, the cleared settings, the sandboxproviderData, and the sandbox check and resume inside the error handling. Each fix from the second review round fails its test when removed: the implicit settings flag, the marker, the resumed state's agent, the in-memory resume, the cancellation incatchand in the stream's error path, the checks inside the error handling, the alias's ownasTool, the alias'scustomOutputExtractor, and the polyfill's rethrow.check-agent.test.tscovers the checks, theasTool()record (also on spread andtoolNamespace()copies), the deprecatedagentAsToolalias and itscustomOutputExtractor, the check before each model call (also on another copy'sAgentclass, installed once) and the check when each run starts (each installed once, inactive outside a Workflow).Locally, in a Linux container with Node 24 and pnpm 10, at the head: lint, which builds (the 8 warnings already on
main, none in changed code), all 294 tests, and Prettier with the SDK settings pass. The Node 22, macOS and Windows cells did not run locally.Replay check, with Workers with no Workflow cache, on runs with no run config, a run model and settings, a local-Activity runner and native
asTool():main(agentAsTool) and this change (asTool()), in both directions;asTool()runs fail with[TMPRL1100], as listed above;[TMPRL1100]in both directions; the same run held in itscatchhandler onmaincompleted on this change through the parent model, without its recovery;agent_endlistener that schedules an Activity, and a customHandoffthat picks an agent with a different Activity tool, failed with[TMPRL1100]in both directions, while their self-replays passed; they are listed above.The same histories, and runs held across versions, replay between the first commit and the clone-free code before the review-round merge. The merge doesn't change which commands are scheduled, and the checks added since schedule nothing for valid setups. The in-memory resume from the second review round does change them, for the resumed runs listed above.
Cancelling a Workflow during a nested model call fails it on
mainand cancels it with this change.Any docs updates needed?
The README is updated here. The docs page and the samples are updated in Show agent.asTool() instead of agentAsTool on the TypeScript OpenAI Agents page documentation#5597 and Move the OpenAI Agents samples to 2.0.0 and agent.asTool() samples-typescript#534, drafts until this is released.
Not covered:
getSystemPrompt. AnAgentsubclass that overrides it without callingsuperskips the check.Runner.prototype.run. Code that replacesrunon the prototype or on aRunnerinstance skips it.Handoffobject from another copy of@openai/agents-corein an agent'shandoffs: the check before the run rejects it, withAgent 'undefined' is not an @openai/agents-core Agent.RunStatewith sandbox state is rebuilt from its string, which can't find an agent that only a customHandoff's callback picked, so such a sandbox run can't resume its approvals.Release note: this squash-merges with the title as its only line, so the draft release should link the README's "Upgrading open runs" section, which says which open runs to let finish or pin.