Repository navigation
Description
What are you really trying to do?
Run a Strands agent whose model keeps the conversation server-side, new OpenAIModel({ stateful: true }),
as a TemporalAgent. Strands documents
this mode: each request chains to the last response with previous_response_id and sends only the
new message, and the agent clears its local messages after each turn.
Describe the bug
Through the plugin, every model call with that model fails before it reaches the provider:
TypeError: options?.modelState?.get is not a function
Strands passes the agent's modelState, a StateStore, in the model's stream options.
TemporalModel.stream() sends those options to the invokeModel Activity, and the payload
converter turns the store into a plain object ({"_state":{}}). The stateful OpenAIModel
calls modelState.get('responseId') while it builds the request, and that throws. The plugin's
default Activity options set no attempt limit, so a run retries the Activity without end.
Fixing only that call would not be enough. The model writes the new response id into
modelState inside the Activity, but the Activity returns only the events, so the agent never
gets it. And TemporalModel.stateful is always false, so the agent would keep and resend its
whole history instead of clearing it.
The same model with stateful: false works through the plugin (the control below).
The Python plugin had the same gap: #195, fixed in #196.
Minimal Reproduction
Two files. The real Strands OpenAIModel runs in both routes; only its fetch is a recording
fake. The script runs two turns natively, then the same two turns in a Workflow on a Worker with
StrandsPlugin({ models: { stateful: ... } }), and compares the requests and the agent's message
count after each turn. It exits 1 when the plugin route differs from native.
node reproduce.cjs stateless runs the same check with stateful: false as a control.
npm install @temporalio/[email protected] @temporalio/[email protected] @temporalio/[email protected] \
@temporalio/[email protected] @temporalio/[email protected] @strands-agents/[email protected] openai@6 zod@4
node reproduce.cjsreproduce.cjs
'use strict';
// OpenAIModel({ stateful: true }): two agent turns natively, then through the Strands plugin.
//
// The real Strands OpenAIModel runs in both cases; only its `fetch` is a recording fake. Natively,
// the second request chains to the first reply with previous_response_id and sends only the new
// message, and the agent clears its messages after each turn. The script prints both routes and
// exits 1 when the plugin route differs. `node reproduce.cjs stateless` runs the same check with
// `stateful: false`, as a control.
const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
const { Agent } = require('@strands-agents/sdk');
const { OpenAIModel } = require('@strands-agents/sdk/models/openai');
const { StrandsPlugin } = require('@temporalio/strands-agents');
const { Worker, Runtime, DefaultLogger } = require('@temporalio/worker');
const { TestWorkflowEnvironment } = require('@temporalio/testing');
const activity = require('@temporalio/activity');
const mode = process.argv[2] ?? 'stateful';
const requests = [];
// A text reply in the Responses API streaming format.
function reply(id, text) {
const base = { id, object: 'response', created_at: 1, model: 'gpt-test', output: [], error: null, incomplete_details: null, instructions: null, metadata: {}, parallel_tool_calls: true, temperature: 1, tool_choice: 'auto', tools: [], top_p: 1 };
const message = { type: 'message', id: `msg_${id}`, role: 'assistant', status: 'completed', content: [{ type: 'output_text', text, annotations: [] }] };
return [
{ type: 'response.created', response: { ...base, status: 'in_progress' } },
{ type: 'response.output_item.added', item: { ...message, status: 'in_progress', content: [] }, output_index: 0 },
{ type: 'response.output_text.delta', item_id: message.id, output_index: 0, content_index: 0, delta: text, logprobs: [] },
{ type: 'response.output_item.done', item: message, output_index: 0 },
{ type: 'response.completed', response: { ...base, status: 'completed', output: [message] } },
].map((e, n) => `event: ${e.type}\ndata: ${JSON.stringify({ ...e, sequence_number: n })}\n\n`).join('');
}
async function recordingFetch(_url, init) {
const body = JSON.parse(init.body);
let inActivity = false;
try {
inActivity = Boolean(activity.Context.current());
} catch {}
const id = `resp_${requests.length + 1}`;
requests.push({
inActivity,
store: body.store,
previous_response_id: body.previous_response_id ?? null,
input: body.input.map((i) => (typeof i.content === 'string' ? i.content : i.content[0].text)),
});
return new Response(reply(id, `answer ${requests.length}`), { status: 200, headers: { 'content-type': 'text/event-stream' } });
}
const model = () =>
new OpenAIModel({ modelId: 'gpt-test', apiKey: 'test-key', stateful: mode === 'stateful', clientConfig: { baseURL: 'http://fake-openai.test/v1', fetch: recordingFetch } });
async function main() {
const versions = {};
for (const p of ['@temporalio/strands-agents', '@temporalio/worker', '@strands-agents/sdk', 'openai']) {
versions[p] = JSON.parse(fs.readFileSync(path.join(__dirname, 'node_modules', p, 'package.json'), 'utf8')).version;
}
console.log(JSON.stringify({ mode, versions }));
// Native control: the same model, outside Temporal.
const agent = new Agent({ model: model(), printer: false });
const native = [];
for (const prompt of ['turn one', 'turn two']) {
const result = await agent.invoke(prompt);
native.push({ reply: result.toString(), messagesAfterTurn: agent.messages.length });
}
const nativeRequests = requests.splice(0);
console.log(JSON.stringify({ route: 'native', turns: native, requests: nativeRequests }));
Runtime.install({ logger: new DefaultLogger('ERROR') });
const env = await TestWorkflowEnvironment.createLocal();
let plugin;
try {
const taskQueue = `stateful-${crypto.randomUUID()}`;
const worker = await Worker.create({
connection: env.nativeConnection,
taskQueue,
workflowsPath: require.resolve('./workflows.js'),
plugins: [new StrandsPlugin({ models: { [mode]: model } })],
});
plugin = await worker.runUntil(env.client.workflow.execute('twoTurns', { taskQueue, workflowId: crypto.randomUUID(), args: [mode] }));
} finally {
await env.teardown();
}
const pluginRequests = requests.splice(0);
console.log(JSON.stringify({ route: 'plugin', turns: plugin, requests: pluginRequests }));
// Natively, the second request chains to the first reply and carries only the new message.
const same =
JSON.stringify(plugin) === JSON.stringify(native) &&
JSON.stringify(pluginRequests.map(({ inActivity, ...r }) => r)) === JSON.stringify(nativeRequests.map(({ inActivity, ...r }) => r)) &&
pluginRequests.every((r) => r.inActivity);
console.log(JSON.stringify({ result: same ? 'plugin route matches native' : 'plugin route differs from native' }));
process.exitCode = same ? 0 : 1;
}
main().catch((err) => {
console.error(err);
process.exitCode = 2;
});workflows.js
'use strict';
const { TemporalAgent } = require('@temporalio/strands-agents');
// Two turns on one agent with the named Worker model. A failed model Activity ends the run
// after two attempts, so the script does not wait on endless retries.
async function twoTurns(model) {
const agent = new TemporalAgent({
model,
printer: false,
activityOptions: { startToCloseTimeout: '10 seconds', retry: { maximumAttempts: 2 } },
});
const turns = [];
for (const prompt of ['turn one', 'turn two']) {
try {
const result = await agent.invoke(prompt);
turns.push({ reply: result.toString(), messagesAfterTurn: agent.messages.length });
} catch (err) {
const chain = [];
for (let e = err; e; e = e.cause) chain.push(`${e.name}: ${e.message}`);
turns.push({ error: chain.join(' <- ') });
break;
}
}
return turns;
}
module.exports = { twoTurns };Output on 1.24.0:
{"mode":"stateful","versions":{"@temporalio/strands-agents":"1.24.0","@temporalio/worker":"1.24.0","@strands-agents/sdk":"1.6.0","openai":"6.49.0"}}
{"route":"native","turns":[{"reply":"answer 1","messagesAfterTurn":0},{"reply":"answer 2","messagesAfterTurn":0}],"requests":[{"inActivity":false,"store":true,"previous_response_id":null,"input":["turn one"]},{"inActivity":false,"store":true,"previous_response_id":"resp_1","input":["turn two"]}]}
{"route":"plugin","turns":[{"error":"ModelError: Activity task failed <- ActivityFailure: Activity task failed <- ApplicationFailure: options?.modelState?.get is not a function"}],"requests":[]}
{"result":"plugin route differs from native"}
The control (node reproduce.cjs stateless) matches native on 1.24.0:
{"mode":"stateless","versions":{"@temporalio/strands-agents":"1.24.0","@temporalio/worker":"1.24.0","@strands-agents/sdk":"1.6.0","openai":"6.49.0"}}
{"route":"native","turns":[{"reply":"answer 1","messagesAfterTurn":2},{"reply":"answer 2","messagesAfterTurn":4}],"requests":[{"inActivity":false,"store":false,"previous_response_id":null,"input":["turn one"]},{"inActivity":false,"store":false,"previous_response_id":null,"input":["turn one","answer 1","turn two"]}]}
{"route":"plugin","turns":[{"reply":"answer 1","messagesAfterTurn":2},{"reply":"answer 2","messagesAfterTurn":4}],"requests":[{"inActivity":true,"store":false,"previous_response_id":null,"input":["turn one"]},{"inActivity":true,"store":false,"previous_response_id":null,"input":["turn one","answer 1","turn two"]}]}
{"result":"plugin route matches native"}
main at 3af00d9 gives the same results with @strands-agents/sdk 1.6.0, and the same stateful
failure with 1.19.0 (the plugin's locked version) and 1.22.0.
With 1.19.0 and 1.22.0, the stateless control also fails on main, for another reason: Strands
now passes an AbortSignal (cancelSignal) in the stream options, which also reaches the Activity
as a plain object, and the OpenAI client fails with signal.addEventListener is not a function.
That is a separate bug and not part of this issue.
Environment/Versions
@temporalio/strands-agents1.24.0 (npm) andmainat3af00d9@temporalio/worker,@temporalio/testing,@temporalio/client1.24.0@strands-agents/sdk1.6.0; onmainalso 1.19.0 and 1.22.0openai6.49.0- Node 24.22.0 on Linux, Temporal CLI 1.9.1 (Server 1.32.0)
Additional context
Expected: the plugin route sends what the native route sends. The second request has
previous_response_id: "resp_1" and only the new message, and the agent has 0 messages after
each turn. As natively, a stateful model with a conversationManager or contextManager throws.
Proposed fix, the same design as #196:
- The model config Activity (
strandsGetModelConfig, from fix(strands): give Strands the worker model's id and context window (breaking) #158) also returns the Worker model's
statefulflag, andTemporalModel.statefulreports it. - A stateful model's calls run as their own Activities,
strandsInvokeStatefulModeland
strandsInvokeStatefulModelStreaming. They take a copy of the agent's model state, give the
model aStateStorewith it, and return the events with the updated state, which
TemporalModelcopies back. Strands then clears the messages after each turn. A Worker without
these Activity types fails such a call, and Temporal retries it on an upgraded Worker. Stateless
calls keepinvokeModel. TemporalAgentthrows Strands' own error for aconversationManagerorcontextManagerwith a
stateful model. Natively this happens at construction;TemporalAgentlearns the flag at its
first invocation, so it throws then.- The README's continue-as-new example also carries
agent.modelState.
Nothing that works today breaks, since every stateful call fails now. But a run that used a
stateful model on the fixed version does not replay on an earlier version. A PR follows.
Activity