@temporalio/strands-agents 1.23.0 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +6 -6
  2. package/README.md +112 -15
  3. package/lib/empty-module.d.ts +1 -1
  4. package/lib/empty-module.js +6 -1
  5. package/lib/empty-module.js.map +1 -1
  6. package/lib/index.d.ts +2 -2
  7. package/lib/index.js +21 -11
  8. package/lib/index.js.map +1 -1
  9. package/lib/load-polyfills.js +15 -0
  10. package/lib/load-polyfills.js.map +1 -1
  11. package/lib/model-activity.d.ts +57 -2
  12. package/lib/model-activity.js +100 -6
  13. package/lib/model-activity.js.map +1 -1
  14. package/lib/plugin.d.ts +33 -12
  15. package/lib/plugin.js +127 -26
  16. package/lib/plugin.js.map +1 -1
  17. package/lib/strands-errors.d.ts +39 -0
  18. package/lib/strands-errors.js +130 -0
  19. package/lib/strands-errors.js.map +1 -0
  20. package/lib/temporal-activity-tool.d.ts +18 -10
  21. package/lib/temporal-activity-tool.js +50 -29
  22. package/lib/temporal-activity-tool.js.map +1 -1
  23. package/lib/temporal-agent.d.ts +38 -4
  24. package/lib/temporal-agent.js +68 -16
  25. package/lib/temporal-agent.js.map +1 -1
  26. package/lib/temporal-mcp-client.d.ts +113 -17
  27. package/lib/temporal-mcp-client.js +376 -102
  28. package/lib/temporal-mcp-client.js.map +1 -1
  29. package/lib/temporal-mcp-tool.d.ts +3 -1
  30. package/lib/temporal-mcp-tool.js +26 -16
  31. package/lib/temporal-mcp-tool.js.map +1 -1
  32. package/lib/temporal-model.d.ts +32 -0
  33. package/lib/temporal-model.js +108 -24
  34. package/lib/temporal-model.js.map +1 -1
  35. package/lib/workflow.js +17 -7
  36. package/lib/workflow.js.map +1 -1
  37. package/package.json +46 -22
  38. package/src/empty-module.ts +5 -0
  39. package/src/index.ts +3 -1
  40. package/src/load-polyfills.ts +20 -1
  41. package/src/model-activity.ts +153 -8
  42. package/src/plugin.ts +159 -31
  43. package/src/strands-errors.ts +147 -0
  44. package/src/temporal-activity-tool.ts +43 -32
  45. package/src/temporal-agent.ts +77 -19
  46. package/src/temporal-mcp-client.ts +407 -91
  47. package/src/temporal-mcp-tool.ts +9 -9
  48. package/src/temporal-model.ts +111 -18
  49. package/lib/failure-converter.d.ts +0 -14
  50. package/lib/failure-converter.js +0 -61
  51. package/lib/failure-converter.js.map +0 -1
  52. package/src/failure-converter.ts +0 -77
@@ -1,5 +1,7 @@
1
- import { Message } from '@strands-agents/sdk';
2
- import type { Model, ModelStreamEvent, StreamOptions } from '@strands-agents/sdk';
1
+ import { Message, StateStore } from '@strands-agents/sdk';
2
+ import type { JSONValue, Model, ModelStreamEvent, StreamOptions } from '@strands-agents/sdk';
3
+ import { Context } from '@temporalio/activity';
4
+ import { ApplicationFailure } from '@temporalio/common';
3
5
  import { WorkflowStreamClient } from '@temporalio/workflow-streams/client';
4
6
  import type { Duration } from '@temporalio/common/lib/time';
5
7
  import { autoHeartbeat } from './heartbeat';
@@ -30,6 +32,32 @@ function rebuildMessages(messages: unknown): Message[] {
30
32
  );
31
33
  }
32
34
 
35
+ /**
36
+ * Run `model.stream` with the activity's own cancellation signal as `cancelSignal`. Strands passes
37
+ * the agent's `cancelSignal`, an `AbortSignal`, which reaches the activity as a plain object.
38
+ *
39
+ * Once the activity's cancellation reaches the worker, the signal is aborted. That stops the model
40
+ * call only if the model passes `cancelSignal` to its client (Strands 1.19.0's `AnthropicModel`
41
+ * does not); otherwise the call runs on and the activity can complete with its result. A remote
42
+ * activity learns of cancellation only through heartbeats, so this needs a `heartbeatTimeout`,
43
+ * which `TemporalModel` sets to 10 seconds unless the activity options set their own. Model
44
+ * clients abort with their own errors (OpenAI's is named `Error`), which Temporal would record as a
45
+ * failure, so after cancellation the activity throws the signal's `CancelledFailure` instead.
46
+ */
47
+ async function* streamWithActivityCancellation(
48
+ model: Model,
49
+ messages: Message[],
50
+ options?: StreamOptions
51
+ ): AsyncGenerator<ModelStreamEvent> {
52
+ const signal = Context.current().cancellationSignal;
53
+ try {
54
+ yield* model.stream(messages, { ...options, cancelSignal: signal });
55
+ } catch (err) {
56
+ if (signal.aborted) throw signal.reason;
57
+ throw err;
58
+ }
59
+ }
60
+
33
61
  /**
34
62
  * Input for the `invokeModel` activity. Mirrors `Model.stream(messages, options)`
35
63
  * with the chosen factory name carried alongside.
@@ -49,6 +77,44 @@ export interface InvokeModelStreamingInput extends InvokeModelInput {
49
77
  streamingBatchInterval: Duration;
50
78
  }
51
79
 
80
+ /**
81
+ * Input for the stateful model activities: a copy of the agent's model state, such as the last
82
+ * response id, which the model reads and updates.
83
+ */
84
+ export interface InvokeStatefulModelInput extends InvokeModelInput {
85
+ modelState: Record<string, JSONValue>;
86
+ }
87
+
88
+ /** Input for the streaming stateful model activity. */
89
+ export interface InvokeStatefulModelStreamingInput extends InvokeModelStreamingInput {
90
+ modelState: Record<string, JSONValue>;
91
+ }
92
+
93
+ /** A stateful model's events and its updated model state. */
94
+ export interface InvokeStatefulModelResult {
95
+ events: ModelStreamEvent[];
96
+ modelState: Record<string, JSONValue>;
97
+ }
98
+
99
+ /**
100
+ * Input for the model config activity: the factory name, as in {@link InvokeModelInput}.
101
+ */
102
+ export interface GetModelConfigInput {
103
+ modelName?: string;
104
+ }
105
+
106
+ /**
107
+ * The parts of the worker model that Strands reads in workflow code: the model id for traces, the
108
+ * context window for proactive compression, and whether the model keeps the conversation
109
+ * server-side. Nothing else is returned, so provider settings such as credentials never reach the
110
+ * workflow history.
111
+ */
112
+ export interface ModelConfigInfo {
113
+ modelId?: string;
114
+ contextWindowLimit?: number;
115
+ stateful?: boolean;
116
+ }
117
+
52
118
  /**
53
119
  * Holds the model factory map and exposes the model activities.
54
120
  *
@@ -57,7 +123,7 @@ export interface InvokeModelStreamingInput extends InvokeModelInput {
57
123
  * default-Bedrock fallback; user-supplied factories force `model: 'name'`
58
124
  * on every {@link TemporalAgent}.
59
125
  *
60
- * Both activities heartbeat at half the configured `heartbeatTimeout` via
126
+ * The model activities heartbeat at half the configured `heartbeatTimeout` via
61
127
  * {@link autoHeartbeat} so long model calls don't stall the worker's view
62
128
  * of activity liveness.
63
129
  */
@@ -70,6 +136,8 @@ export class ModelActivity {
70
136
  ) {
71
137
  this.invokeModel = autoHeartbeat(this.invokeModel.bind(this));
72
138
  this.invokeModelStreaming = autoHeartbeat(this.invokeModelStreaming.bind(this));
139
+ this.invokeStatefulModel = autoHeartbeat(this.invokeStatefulModel.bind(this));
140
+ this.invokeStatefulModelStreaming = autoHeartbeat(this.invokeStatefulModelStreaming.bind(this));
73
141
  }
74
142
 
75
143
  private getModel(name?: string): Model {
@@ -93,18 +161,74 @@ export class ModelActivity {
93
161
  return model;
94
162
  }
95
163
 
96
- async invokeModel(input: InvokeModelInput): Promise<ModelStreamEvent[]> {
164
+ async getModelConfig(input: GetModelConfigInput): Promise<ModelConfigInfo> {
97
165
  const model = this.getModel(input.modelName);
166
+ const { modelId, contextWindowLimit } = model.getConfig();
167
+ return { modelId, contextWindowLimit, stateful: model.stateful };
168
+ }
169
+
170
+ async invokeModel(input: InvokeModelInput): Promise<ModelStreamEvent[]> {
171
+ return this.runModel(this.getStatelessModel(input.modelName), input);
172
+ }
173
+
174
+ async invokeModelStreaming(input: InvokeModelStreamingInput): Promise<ModelStreamEvent[]> {
175
+ return this.runModelStreaming(this.getStatelessModel(input.modelName), input);
176
+ }
177
+
178
+ /**
179
+ * The model for a stateless call. A stateful model cannot run here without the agent's model
180
+ * state, and retrying does not bring it: the workflow chose this activity because its config
181
+ * read had no stateful flag, from a worker without stateful support or from a model that became
182
+ * stateful later, or because `TemporalModel` runs without `TemporalAgent` and never read the
183
+ * config.
184
+ */
185
+ private getStatelessModel(name?: string): Model {
186
+ const model = this.getModel(name);
187
+ if (model.stateful) {
188
+ throw ApplicationFailure.create({
189
+ type: 'StatefulModelOnStatelessPath',
190
+ nonRetryable: true,
191
+ message:
192
+ `The worker model ${JSON.stringify(name ?? this.defaultName)} is stateful, but the workflow ` +
193
+ `called it without its model state. Its config was read from a worker without stateful ` +
194
+ `support, the worker model became stateful after the run read its config, or ` +
195
+ `TemporalModel runs without TemporalAgent and did not read it. Reset or terminate the run.`,
196
+ });
197
+ }
198
+ return model;
199
+ }
200
+
201
+ /**
202
+ * The model for a stateful call. A model that is no longer stateful ignores the model state, and
203
+ * the agent, which read a stateful config, clears its messages after each turn, so the model
204
+ * would see only each turn's new message: the worker model became stateless after the run read
205
+ * its config.
206
+ */
207
+ private getStatefulModel(name?: string): Model {
208
+ const model = this.getModel(name);
209
+ if (!model.stateful) {
210
+ throw ApplicationFailure.create({
211
+ type: 'StatelessModelOnStatefulPath',
212
+ nonRetryable: true,
213
+ message:
214
+ `The worker model ${JSON.stringify(name ?? this.defaultName)} is not stateful, but the run ` +
215
+ `read a stateful config, so its agent does not keep the messages this model needs. The ` +
216
+ `worker model became stateless after the run read its config. Reset or terminate the run.`,
217
+ });
218
+ }
219
+ return model;
220
+ }
221
+
222
+ private async runModel(model: Model, input: InvokeModelInput): Promise<ModelStreamEvent[]> {
98
223
  const messages = rebuildMessages(input.messages);
99
224
  const events: ModelStreamEvent[] = [];
100
- for await (const event of model.stream(messages, input.options)) {
225
+ for await (const event of streamWithActivityCancellation(model, messages, input.options)) {
101
226
  events.push(event);
102
227
  }
103
228
  return events;
104
229
  }
105
230
 
106
- async invokeModelStreaming(input: InvokeModelStreamingInput): Promise<ModelStreamEvent[]> {
107
- const model = this.getModel(input.modelName);
231
+ private async runModelStreaming(model: Model, input: InvokeModelStreamingInput): Promise<ModelStreamEvent[]> {
108
232
  const messages = rebuildMessages(input.messages);
109
233
  const stream = WorkflowStreamClient.fromWithinActivity({
110
234
  batchInterval: input.streamingBatchInterval,
@@ -112,7 +236,7 @@ export class ModelActivity {
112
236
  const topic = stream.topic(input.streamingTopic);
113
237
  const events: ModelStreamEvent[] = [];
114
238
  try {
115
- for await (const event of model.stream(messages, input.options)) {
239
+ for await (const event of streamWithActivityCancellation(model, messages, input.options)) {
116
240
  events.push(event);
117
241
  topic.publish(event);
118
242
  }
@@ -121,4 +245,25 @@ export class ModelActivity {
121
245
  }
122
246
  return events;
123
247
  }
248
+
249
+ // Stateful calls use their own activity types. A worker without stateful support does not
250
+ // register them, so it cannot take such a call, drop the model state and return no updated state
251
+ // while the agent clears its messages: the call fails there and is retried until a worker with
252
+ // stateful support takes it.
253
+
254
+ /** Run a stateful model with the agent's model state; return its events and the updated state. */
255
+ async invokeStatefulModel(input: InvokeStatefulModelInput): Promise<InvokeStatefulModelResult> {
256
+ const modelState = new StateStore(input.modelState);
257
+ const model = this.getStatefulModel(input.modelName);
258
+ const events = await this.runModel(model, { ...input, options: { ...input.options, modelState } });
259
+ return { events, modelState: modelState.getAll() };
260
+ }
261
+
262
+ /** As {@link invokeStatefulModel}, publishing each event as {@link invokeModelStreaming} does. */
263
+ async invokeStatefulModelStreaming(input: InvokeStatefulModelStreamingInput): Promise<InvokeStatefulModelResult> {
264
+ const modelState = new StateStore(input.modelState);
265
+ const model = this.getStatefulModel(input.modelName);
266
+ const events = await this.runModelStreaming(model, { ...input, options: { ...input.options, modelState } });
267
+ return { events, modelState: modelState.getAll() };
268
+ }
124
269
  }
package/src/plugin.ts CHANGED
@@ -2,18 +2,49 @@ import type { McpClient } from '@strands-agents/sdk';
2
2
  import { BedrockModel, type Model } from '@strands-agents/sdk';
3
3
  import type { Duration } from '@temporalio/common';
4
4
  import { msOptionalToNumber } from '@temporalio/common/lib/time';
5
- import type { BundleOptions } from '@temporalio/worker';
5
+ import type { Context as ActivityContext } from '@temporalio/activity';
6
+ import type { ActivityInboundCallsInterceptor, BundleOptions, Worker, WorkerOptions } from '@temporalio/worker';
6
7
  import { SimplePlugin } from '@temporalio/plugin';
8
+ import { rewriteError } from './strands-errors';
7
9
  import { ModelActivity } from './model-activity';
8
- import type { InvokeModelInput, InvokeModelStreamingInput } from './model-activity';
10
+ import type {
11
+ GetModelConfigInput,
12
+ InvokeModelInput,
13
+ InvokeModelStreamingInput,
14
+ InvokeStatefulModelInput,
15
+ InvokeStatefulModelStreamingInput,
16
+ } from './model-activity';
17
+ import {
18
+ GET_MODEL_CONFIG_ACTIVITY,
19
+ INVOKE_STATEFUL_MODEL_ACTIVITY,
20
+ INVOKE_STATEFUL_MODEL_STREAMING_ACTIVITY,
21
+ } from './temporal-model';
9
22
  import {
10
23
  buildCallToolActivity,
11
24
  buildListToolsActivity,
12
25
  callToolActivityName,
26
+ describeValue,
13
27
  listToolsActivityName,
14
- _evictConnection,
28
+ MCP_CONNECTION_IDLE_MS,
29
+ McpConnections,
15
30
  } from './temporal-mcp-client';
16
31
 
32
+ // What each Activity a StrandsPlugin builds was built from: its name, then what it depends on.
33
+ // configureWorker lets one of these replace another with the same entries: that is the same
34
+ // instance, or one built from the same options, registered twice (e.g. on the NativeConnection
35
+ // and the Worker).
36
+ const activitySources = new WeakMap<object, readonly unknown[]>();
37
+
38
+ function sameSources(a: object, b: object): boolean {
39
+ const x = activitySources.get(a);
40
+ const y = activitySources.get(b);
41
+ return x !== undefined && y !== undefined && x.length === y.length && x.every((v, i) => v === y[i]);
42
+ }
43
+
44
+ const REMEDY =
45
+ 'Rename or remove the other Activity, run the other integration on its own Worker and task queue, ' +
46
+ 'or use one StrandsPlugin instance on this Worker.';
47
+
17
48
  /**
18
49
  * Options for {@link StrandsPlugin}.
19
50
  *
@@ -26,13 +57,14 @@ import {
26
57
  * - `mcpClients` — name → MCP client factory map. Workflow-side
27
58
  * `TemporalMCPClient({ server: 'name' })` selects a factory by name; the
28
59
  * per-server `{name}-listTools` and `{name}-callTool` activities reuse one
29
- * lazily-opened worker-process connection. Tools are enumerated live on each
60
+ * lazily-opened connection, which belongs to this plugin instance and closes
61
+ * when the last worker using the plugin stops. Tools are enumerated live on each
30
62
  * `listTools`. By default (`TemporalMCPClient`'s `cacheTools: false`) the
31
63
  * agent re-lists on each turn, so it picks up MCP-server changes (including
32
64
  * redeploys) mid-workflow without restarting the worker; set `cacheTools:
33
65
  * true` to list once at the start of the workflow instead.
34
66
  *
35
- * - `mcpConnectionIdleTimeout` — how long a worker-process MCP connection is
67
+ * - `mcpConnectionIdleTimeout` — how long an idle MCP connection is
36
68
  * kept open between `callTool` activities before it's disconnected. The window
37
69
  * only starts once no activity is using the connection, so it never cuts off
38
70
  * an in-flight call, however long it runs. Accepts a millisecond number or a
@@ -45,22 +77,52 @@ export interface StrandsPluginOptions {
45
77
  mcpConnectionIdleTimeout?: Duration;
46
78
  }
47
79
 
80
+ /** The plugin's model activities, whose context overflows the agent recovers from. */
81
+ const MODEL_ACTIVITIES = new Set(['invokeModel', 'invokeModelStreaming']);
82
+
83
+ /**
84
+ * Rethrows Strands' interrupt and terminal errors from activities as typed, non-retryable
85
+ * failures. The worker turns any other error an activity throws into a retryable
86
+ * `ApplicationFailure` before a failure converter sees it, so this cannot be left to one.
87
+ */
88
+ function strandsActivityInbound(ctx: ActivityContext): ActivityInboundCallsInterceptor {
89
+ return {
90
+ async execute(input, next) {
91
+ try {
92
+ return await next(input);
93
+ } catch (err) {
94
+ throw rewriteError(err, { benignOverflow: MODEL_ACTIVITIES.has(ctx.info.activityType) });
95
+ }
96
+ },
97
+ };
98
+ }
99
+
100
+ /** Reads this package's version, which worker heartbeats report. Empty if it can't be read. */
101
+ function packageVersion(): string {
102
+ try {
103
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
104
+ return (require('../package.json') as { version?: string }).version ?? '';
105
+ } catch {
106
+ return '';
107
+ }
108
+ }
109
+
48
110
  /**
49
111
  * Temporal plugin that runs Strands Agents inside Temporal workflows. Model,
50
112
  * MCP tool, and (via {@link workflow.activityAsTool}) custom-tool invocations
51
113
  * are routed through Temporal Activities for durable execution, retries, and
52
114
  * timeouts.
53
115
  *
54
- * Register on the worker (and on the client when using `activityAsTool` with
55
- * interrupts, so the client-side data converter picks up the failure
56
- * converter):
116
+ * Register on the worker:
57
117
  *
58
118
  * ```ts
59
- * const client = await Client.connect({ plugins: [new StrandsPlugin({...})] });
60
119
  * const worker = new Worker({ ..., plugins: [new StrandsPlugin({...})] });
61
120
  * ```
62
121
  */
63
122
  export class StrandsPlugin extends SimplePlugin {
123
+ /** The package version, reported in worker heartbeats. */
124
+ readonly version = packageVersion();
125
+
64
126
  constructor(options: StrandsPluginOptions = {}) {
65
127
  let modelFactories = options.models;
66
128
  let defaultName: string | undefined;
@@ -78,37 +140,97 @@ export class StrandsPlugin extends SimplePlugin {
78
140
  const activities: Record<string, (...args: never[]) => unknown> = {
79
141
  invokeModel: (input: InvokeModelInput) => modelActivity.invokeModel(input),
80
142
  invokeModelStreaming: (input: InvokeModelStreamingInput) => modelActivity.invokeModelStreaming(input),
143
+ [INVOKE_STATEFUL_MODEL_ACTIVITY]: (input: InvokeStatefulModelInput) => modelActivity.invokeStatefulModel(input),
144
+ [INVOKE_STATEFUL_MODEL_STREAMING_ACTIVITY]: (input: InvokeStatefulModelStreamingInput) =>
145
+ modelActivity.invokeStatefulModelStreaming(input),
146
+ [GET_MODEL_CONFIG_ACTIVITY]: (input: GetModelConfigInput) => modelActivity.getModelConfig(input),
81
147
  };
148
+ // Without `models`, every plugin builds the same default.
149
+ const modelSources = options.models === undefined ? [] : [options.models, defaultName];
150
+ for (const [name, fn] of Object.entries(activities)) {
151
+ activitySources.set(fn, [name, ...modelSources]);
152
+ }
82
153
 
83
154
  const mcpClients = options.mcpClients ?? {};
84
155
  const idleMs = msOptionalToNumber(options.mcpConnectionIdleTimeout);
156
+ // This plugin's own MCP connections: the Workers that share this instance share
157
+ // them, and another StrandsPlugin opens its own, even for the same server name.
158
+ const connections = new McpConnections(idleMs);
85
159
  for (const [server, factory] of Object.entries(mcpClients)) {
86
- activities[listToolsActivityName(server)] = buildListToolsActivity(server, factory, idleMs);
87
- activities[callToolActivityName(server)] = buildCallToolActivity(server, factory, idleMs);
160
+ // Fail when the Worker is built, not in every MCP Activity.
161
+ if (typeof factory !== 'function') {
162
+ throw new TypeError(`MCP client factory '${server}' is ${describeValue(factory)}, not a function.`);
163
+ }
164
+ const serverActivities = {
165
+ [listToolsActivityName(server)]: buildListToolsActivity(server, factory, connections),
166
+ [callToolActivityName(server)]: buildCallToolActivity(server, factory, connections),
167
+ };
168
+ for (const [name, fn] of Object.entries(serverActivities)) {
169
+ activities[name] = fn;
170
+ activitySources.set(fn, [name, factory, idleMs ?? MCP_CONNECTION_IDLE_MS]);
171
+ }
88
172
  }
89
173
 
90
- const runContext = async (next: () => Promise<void>): Promise<void> => {
91
- try {
92
- await next();
93
- } finally {
94
- // Close any worker-process MCP connections opened lazily by the
95
- // listTools/callTool activities.
96
- for (const server of Object.keys(mcpClients)) {
97
- await _evictConnection(server);
98
- }
99
- }
100
- };
174
+ // Closes the MCP connections once the last Worker using this plugin stops.
175
+ const runContext = (next: () => Promise<void>): Promise<void> => connections.use(next);
101
176
 
102
177
  super({
103
178
  name: 'StrandsPlugin',
104
179
  activities,
105
180
  runContext,
106
- dataConverter: {
107
- failureConverterPath: require.resolve('./failure-converter'),
108
- },
181
+ // A function, because the object form rebuilds the worker's interceptors without the
182
+ // deprecated `activityInbound` key.
183
+ workerInterceptors: (existing) => ({
184
+ ...existing,
185
+ activity: [...(existing?.activity ?? []), (ctx) => ({ inbound: strandsActivityInbound(ctx) })],
186
+ }),
109
187
  });
110
188
  }
111
189
 
190
+ /**
191
+ * Adds the model and MCP Activities to the Worker.
192
+ *
193
+ * @throws TypeError if the Worker already has a different Activity with one of these names: a
194
+ * caller Activity, another integration's Activity, or one from a `StrandsPlugin` that doesn't share
195
+ * this one's `models` object, MCP client factories and idle timeout.
196
+ */
197
+ override configureWorker(options: WorkerOptions): WorkerOptions {
198
+ const existing = options.activities as Record<string, unknown> | undefined;
199
+ for (const [name, fn] of Object.entries(this.options.activities as object)) {
200
+ const other = existing && Object.prototype.propertyIsEnumerable.call(existing, name) ? existing[name] : undefined;
201
+ if (typeof other === 'function' && other !== fn && !sameSources(other, fn)) {
202
+ throw new TypeError(
203
+ `Duplicate registration of Activity '${name}': StrandsPlugin would replace a different Activity ` +
204
+ `with this name. ${REMEDY}`
205
+ );
206
+ }
207
+ }
208
+ return super.configureWorker(options);
209
+ }
210
+
211
+ /**
212
+ * Runs the Worker.
213
+ *
214
+ * @throws TypeError, before the Worker polls, if a plugin applied after this one replaced one of
215
+ * its Activities with a different one. `Worker.create` applies the Worker's plugins in order, then
216
+ * the `NativeConnection`'s.
217
+ */
218
+ override async runWorker(worker: Worker, next: (worker: Worker) => Promise<void>): Promise<void> {
219
+ for (const [name, fn] of Object.entries(this.options.activities as object)) {
220
+ const kept = worker.options.activities.get(name);
221
+ if (kept === undefined || kept === fn || sameSources(kept, fn)) continue;
222
+ // There is no public way to stop a Worker that has not run yet. Stopping it first means it
223
+ // never polls; `next` then releases it as `run()` does, so `connection.close()` still works.
224
+ (worker as unknown as { nativeWorker: { initiateShutdown(): void } }).nativeWorker.initiateShutdown();
225
+ await next(worker).catch(() => undefined);
226
+ throw new TypeError(
227
+ `Duplicate registration of Activity '${name}': a plugin applied after StrandsPlugin replaced its ` +
228
+ `Activity with this name. ${REMEDY}`
229
+ );
230
+ }
231
+ return super.runWorker(worker, next);
232
+ }
233
+
112
234
  /**
113
235
  * Extend the bundler config so workflow code can bundle `@strands-agents/sdk`:
114
236
  *
@@ -121,18 +243,23 @@ export class StrandsPlugin extends SimplePlugin {
121
243
  * `@google/genai`, `ai`). The workers constructs models worker-side;
122
244
  * workflow code only goes through {@link TemporalModel}.
123
245
  * - `@aws-sdk/client-s3`, dynamically imported by the SDK's S3-backed
124
- * `context-offloader` vended plugin — worker-only, never reached from
125
- * workflow code.
246
+ * `context-offloader` vended plugin. The offloader can run in workflows
247
+ * with in-memory storage; S3 I/O must run in Activities.
248
+ * - `@aws-sdk/client-s3vectors`, dynamically imported by the SDK's
249
+ * `S3VectorSearchStrategy`, which `S3Storage` imports.
126
250
  * - `@temporalio/activity` and `@temporalio/client`, which the
127
251
  * worker-only halves of {@link TemporalMCPClient}, {@link autoHeartbeat},
128
252
  * and `@temporalio/workflow-streams/client` import.
129
253
  * - `path` / `crypto`, pulled in transitively by the same worker-only code.
254
+ * - `node:crypto`, dynamically imported by `LocalFileStorage` through the
255
+ * unified storage entrypoint. In-memory storage does not use it.
130
256
  *
131
257
  * - Replace the dynamic-imported MCP transport helpers
132
258
  * (`@modelcontextprotocol/sdk/client/{stdio,sse,streamableHttp}.js` and
133
- * their `node:*` dependencies, plus `eventsource-parser/stream` which
134
- * `streamableHttp.js` reaches) with an empty module. They live in
135
- * `mcp-config.js`'s server-only code paths.
259
+ * their `node:*` dependencies, plus `eventsource` and
260
+ * `eventsource-parser/stream`) with a stub module. MCP v2 bundles its
261
+ * transports into the client entrypoint, so their static EventSource
262
+ * imports must also be stubbed. Transport I/O only runs worker-side.
136
263
  *
137
264
  * - Inline async chunks so the bundle stays a single file — webpack's
138
265
  * default JSONP chunk loader references `self`/`document`, neither of
@@ -150,6 +277,7 @@ export class StrandsPlugin extends SimplePlugin {
150
277
  '@temporalio/client',
151
278
  '@aws-sdk/client-bedrock-runtime',
152
279
  '@aws-sdk/client-s3',
280
+ '@aws-sdk/client-s3vectors',
153
281
  '@aws-sdk/middleware-websocket',
154
282
  '@anthropic-ai/sdk',
155
283
  'openai',
@@ -208,7 +336,7 @@ interface WebpackCompiler {
208
336
  function emptyModuleRewritesPlugin(): WebpackPlugin {
209
337
  const empty = require.resolve('./empty-module');
210
338
  const ignorePattern =
211
- /^(?:node:(?:fs\/promises|os|path|process|stream)|@modelcontextprotocol\/sdk\/client\/(?:stdio|sse|streamableHttp)\.js|eventsource-parser\/stream)$/;
339
+ /^(?:node:(?:crypto|fs\/promises|os|path|process|stream)|@modelcontextprotocol\/sdk\/client\/(?:stdio|sse|streamableHttp)\.js|eventsource|eventsource-parser\/stream)$/;
212
340
  return {
213
341
  apply(compiler) {
214
342
  const { NormalModuleReplacementPlugin } = compiler.webpack;
@@ -0,0 +1,147 @@
1
+ import { ContextWindowOverflowError, MaxTokensError, ModelError, StructuredOutputError } from '@strands-agents/sdk';
2
+ import {
3
+ ApplicationFailure,
4
+ ApplicationFailureCategory,
5
+ type ApplicationFailureOptions,
6
+ TemporalFailure,
7
+ } from '@temporalio/common';
8
+
9
+ export const STRANDS_INTERRUPT_TYPE = 'StrandsInterrupt';
10
+
11
+ /** The failure type of an interrupt an activity threw that the plugin cannot read. */
12
+ export const STRANDS_MALFORMED_INTERRUPT_TYPE = 'StrandsMalformedInterrupt';
13
+
14
+ /** The failure type of a Strands context overflow, from the model activity to `TemporalModel`. */
15
+ export const CONTEXT_WINDOW_OVERFLOW_TYPE = 'ContextWindowOverflowError';
16
+
17
+ // Strands does not re-export `InterruptError` from its public index, so detect
18
+ // it structurally instead of via `instanceof`.
19
+ interface InterruptLike {
20
+ toJSON(): unknown;
21
+ }
22
+
23
+ /** What each entry in a `StrandsInterrupt` failure's details holds. */
24
+ export interface InterruptDetails {
25
+ id?: string;
26
+ name: string;
27
+ reason?: unknown;
28
+ response?: unknown;
29
+ source?: string;
30
+ }
31
+
32
+ // Any value with a non-empty `interrupts` array is taken as an interrupt, so a malformed one fails
33
+ // as such instead of being retried as an ordinary error.
34
+ function isInterruptAttempt(err: unknown): err is { interrupts: unknown[] } {
35
+ if (err === null || typeof err !== 'object') return false;
36
+ const { interrupts } = err as { interrupts?: unknown };
37
+ return Array.isArray(interrupts) && interrupts.length > 0;
38
+ }
39
+
40
+ const TERMINAL_ERROR_TYPES = [
41
+ { ctor: ContextWindowOverflowError, name: CONTEXT_WINDOW_OVERFLOW_TYPE },
42
+ { ctor: MaxTokensError, name: 'MaxTokensError' },
43
+ { ctor: StructuredOutputError, name: 'StructuredOutputError' },
44
+ ];
45
+
46
+ // The failure type of a Strands terminal model error, or undefined for any other value. The name
47
+ // matches an error from another copy of `@strands-agents/sdk`, or any error with that name;
48
+ // `instanceof` also matches a subclass that sets a name of its own.
49
+ function terminalType(err: unknown): string | undefined {
50
+ if (!(err instanceof Error)) return undefined;
51
+ return TERMINAL_ERROR_TYPES.find(({ ctor, name }) => err instanceof ctor || err.name === name)?.name;
52
+ }
53
+
54
+ // `ApplicationFailure.fromError` keeps the error's message, stack and cause, but returns an
55
+ // `ApplicationFailure` it is given, and one decoded earlier would still be encoded from its original
56
+ // proto, without these overrides. Start a fresh failure for that case.
57
+ function retype(err: unknown, overrides: ApplicationFailureOptions): ApplicationFailure {
58
+ if (err instanceof ApplicationFailure) {
59
+ return ApplicationFailure.create({ message: err.message, ...overrides, cause: err });
60
+ }
61
+ return ApplicationFailure.fromError(err, overrides);
62
+ }
63
+
64
+ /**
65
+ * Rewrite an error an activity threw. A Strands interrupt becomes a typed,
66
+ * non-retryable failure that the worker treats as benign, and a malformed one a
67
+ * non-retryable failure of type {@link STRANDS_MALFORMED_INTERRUPT_TYPE}. A
68
+ * Strands terminal model error becomes a typed, non-retryable failure, benign
69
+ * for a context overflow when `benignOverflow` is set. Each keeps the error's
70
+ * stack and cause. Any other value is returned as it is.
71
+ */
72
+ export function rewriteError(err: unknown, options: { benignOverflow?: boolean } = {}): unknown {
73
+ if (isInterruptAttempt(err)) {
74
+ const details = interruptDetails(err.interrupts);
75
+ if (details === undefined) {
76
+ return retype(err, {
77
+ message: `malformed interrupt (${String((err as { message?: unknown }).message)}): each entry needs a toJSON() that returns an object with a unique string name, and JSON-encodable values`,
78
+ type: STRANDS_MALFORMED_INTERRUPT_TYPE,
79
+ nonRetryable: true,
80
+ });
81
+ }
82
+ return retype(err, {
83
+ message: `interrupt:${details.map((d) => d.name).join(',')}`,
84
+ type: STRANDS_INTERRUPT_TYPE,
85
+ nonRetryable: true,
86
+ details,
87
+ category: ApplicationFailureCategory.BENIGN,
88
+ });
89
+ }
90
+ const type = terminalType(err);
91
+ if (type === undefined) return err;
92
+ const benign = options.benignOverflow === true && type === CONTEXT_WINDOW_OVERFLOW_TYPE;
93
+ return retype(err, { type, nonRetryable: true, ...(benign ? { category: ApplicationFailureCategory.BENIGN } : {}) });
94
+ }
95
+
96
+ /**
97
+ * The error a `TemporalAgent` turn ends with in workflow code, in place of one
98
+ * that would only fail the workflow task on every attempt. A Strands terminal
99
+ * model error becomes a typed, non-retryable failure with the original error as
100
+ * its cause. A Strands `ModelError` that wraps a Temporal failure, such as a
101
+ * model activity that failed or was cancelled, becomes that failure, so the run
102
+ * fails or is cancelled. Any other value is returned as it is.
103
+ */
104
+ export function workflowErrorFor(err: unknown): unknown {
105
+ const type = terminalType(err);
106
+ if (type !== undefined) {
107
+ return ApplicationFailure.create({
108
+ message: (err as Error).message,
109
+ type,
110
+ nonRetryable: true,
111
+ cause: err as Error,
112
+ });
113
+ }
114
+ if (err instanceof ModelError && err.cause instanceof TemporalFailure) return err.cause;
115
+ return err;
116
+ }
117
+
118
+ /**
119
+ * The application failure type of a decoded failure. It also reads the type from
120
+ * the failure's proto when the failure converter returned another kind of
121
+ * `TemporalFailure`.
122
+ */
123
+ export function applicationFailureType(failure: unknown): string | undefined {
124
+ if (failure instanceof ApplicationFailure) return failure.type ?? undefined;
125
+ if (failure instanceof TemporalFailure) return failure.failure?.applicationFailureInfo?.type ?? undefined;
126
+ return undefined;
127
+ }
128
+
129
+ // The details of each interrupt, or undefined when an entry is missing or has no toJSON(), returns
130
+ // no object with a string name, repeats another entry's name, or holds a value JSON cannot encode.
131
+ // `Array.from` visits the holes in a sparse array, which `map` and `every` skip and the worker cannot
132
+ // encode as details. Strands keys a tool's interrupts by name, so a repeated name would get the first
133
+ // entry's response. The JSON check applies whatever payload converter the worker uses.
134
+ function interruptDetails(interrupts: unknown[]): InterruptDetails[] | undefined {
135
+ try {
136
+ const details = Array.from(interrupts, (i) => (i as InterruptLike).toJSON());
137
+ const named = details.every(
138
+ (d) => d !== null && typeof d === 'object' && typeof (d as { name?: unknown }).name === 'string'
139
+ );
140
+ if (!named) return undefined;
141
+ if (new Set(details.map((d) => (d as InterruptDetails).name)).size !== details.length) return undefined;
142
+ JSON.stringify(details);
143
+ return details as InterruptDetails[];
144
+ } catch {
145
+ return undefined;
146
+ }
147
+ }