@temporalio/strands-agents 1.21.0

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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +351 -0
  3. package/lib/empty-module.d.ts +4 -0
  4. package/lib/empty-module.js +21 -0
  5. package/lib/empty-module.js.map +1 -0
  6. package/lib/failure-converter.d.ts +14 -0
  7. package/lib/failure-converter.js +60 -0
  8. package/lib/failure-converter.js.map +1 -0
  9. package/lib/heartbeat.d.ts +6 -0
  10. package/lib/heartbeat.js +27 -0
  11. package/lib/heartbeat.js.map +1 -0
  12. package/lib/index.d.ts +9 -0
  13. package/lib/index.js +45 -0
  14. package/lib/index.js.map +1 -0
  15. package/lib/json-schema.d.ts +10 -0
  16. package/lib/json-schema.js +17 -0
  17. package/lib/json-schema.js.map +1 -0
  18. package/lib/load-polyfills.d.ts +1 -0
  19. package/lib/load-polyfills.js +23 -0
  20. package/lib/load-polyfills.js.map +1 -0
  21. package/lib/model-activity.d.ts +41 -0
  22. package/lib/model-activity.js +100 -0
  23. package/lib/model-activity.js.map +1 -0
  24. package/lib/plugin.d.ts +79 -0
  25. package/lib/plugin.js +152 -0
  26. package/lib/plugin.js.map +1 -0
  27. package/lib/temporal-activity-tool.d.ts +42 -0
  28. package/lib/temporal-activity-tool.js +109 -0
  29. package/lib/temporal-activity-tool.js.map +1 -0
  30. package/lib/temporal-agent.d.ts +41 -0
  31. package/lib/temporal-agent.js +80 -0
  32. package/lib/temporal-agent.js.map +1 -0
  33. package/lib/temporal-mcp-client.d.ts +107 -0
  34. package/lib/temporal-mcp-client.js +237 -0
  35. package/lib/temporal-mcp-client.js.map +1 -0
  36. package/lib/temporal-mcp-tool.d.ts +24 -0
  37. package/lib/temporal-mcp-tool.js +109 -0
  38. package/lib/temporal-mcp-tool.js.map +1 -0
  39. package/lib/temporal-model.d.ts +41 -0
  40. package/lib/temporal-model.js +88 -0
  41. package/lib/temporal-model.js.map +1 -0
  42. package/lib/workflow.d.ts +39 -0
  43. package/lib/workflow.js +66 -0
  44. package/lib/workflow.js.map +1 -0
  45. package/package.json +72 -0
  46. package/src/empty-module.ts +20 -0
  47. package/src/failure-converter.ts +76 -0
  48. package/src/heartbeat.ts +24 -0
  49. package/src/index.ts +16 -0
  50. package/src/json-schema.ts +14 -0
  51. package/src/load-polyfills.ts +24 -0
  52. package/src/model-activity.ts +124 -0
  53. package/src/plugin.ts +215 -0
  54. package/src/temporal-activity-tool.ts +127 -0
  55. package/src/temporal-agent.ts +103 -0
  56. package/src/temporal-mcp-client.ts +274 -0
  57. package/src/temporal-mcp-tool.ts +89 -0
  58. package/src/temporal-model.ts +94 -0
  59. package/src/workflow.ts +60 -0
package/src/plugin.ts ADDED
@@ -0,0 +1,215 @@
1
+ import type { McpClient } from '@strands-agents/sdk';
2
+ import { BedrockModel, type Model } from '@strands-agents/sdk';
3
+ import type { Duration } from '@temporalio/common';
4
+ import { msOptionalToNumber } from '@temporalio/common/lib/time';
5
+ import type { BundleOptions } from '@temporalio/worker';
6
+ import { SimplePlugin } from '@temporalio/plugin';
7
+ import { ModelActivity } from './model-activity';
8
+ import type { InvokeModelInput, InvokeModelStreamingInput } from './model-activity';
9
+ import {
10
+ buildCallToolActivity,
11
+ buildListToolsActivity,
12
+ callToolActivityName,
13
+ listToolsActivityName,
14
+ _evictConnection,
15
+ } from './temporal-mcp-client';
16
+
17
+ /**
18
+ * Options for {@link StrandsPlugin}.
19
+ *
20
+ * - `models` — name → factory map. Each factory is called lazily on first
21
+ * use and the constructed model is cached for the worker's lifetime.
22
+ * `TemporalAgent({ model: 'name', ... })` selects which factory to invoke.
23
+ * If omitted, the plugin registers a single `BedrockModel` factory under
24
+ * the name `'bedrock'` to match Strands' own implicit default.
25
+ *
26
+ * - `mcpClients` — name → MCP client factory map. Workflow-side
27
+ * `TemporalMCPClient({ server: 'name' })` selects a factory by name; the
28
+ * per-server `{name}-listTools` and `{name}-callTool` activities reuse one
29
+ * lazily-opened worker-process connection. Tools are enumerated live on each
30
+ * `listTools`. By default (`TemporalMCPClient`'s `cacheTools: false`) the
31
+ * agent re-lists on each turn, so it picks up MCP-server changes (including
32
+ * redeploys) mid-workflow without restarting the worker; set `cacheTools:
33
+ * true` to list once at the start of the workflow instead.
34
+ *
35
+ * - `mcpConnectionIdleTimeout` — how long a worker-process MCP connection is
36
+ * kept open between `callTool` activities before it's disconnected. The timer
37
+ * resets on every reuse. Accepts a millisecond number or a duration string
38
+ * (e.g. `'5 minutes'`), like `startToCloseTimeout`. Defaults to
39
+ * {@link MCP_CONNECTION_IDLE_MS} (5 minutes).
40
+ */
41
+ export interface StrandsPluginOptions {
42
+ models?: Record<string, () => Model>;
43
+ mcpClients?: Record<string, () => McpClient>;
44
+ mcpConnectionIdleTimeout?: Duration;
45
+ }
46
+
47
+ /**
48
+ * Temporal plugin that runs Strands Agents inside Temporal workflows. Model,
49
+ * MCP tool, and (via {@link workflow.activityAsTool}) custom-tool invocations
50
+ * are routed through Temporal Activities for durable execution, retries, and
51
+ * timeouts.
52
+ *
53
+ * Register on the worker (and on the client when using `activityAsTool` with
54
+ * interrupts, so the client-side data converter picks up the failure
55
+ * converter):
56
+ *
57
+ * ```ts
58
+ * const client = await Client.connect({ plugins: [new StrandsPlugin({...})] });
59
+ * const worker = new Worker({ ..., plugins: [new StrandsPlugin({...})] });
60
+ * ```
61
+ */
62
+ export class StrandsPlugin extends SimplePlugin {
63
+ constructor(options: StrandsPluginOptions = {}) {
64
+ let modelFactories = options.models;
65
+ let defaultName: string | undefined;
66
+ if (modelFactories === undefined) {
67
+ modelFactories = { bedrock: () => new BedrockModel({}) };
68
+ defaultName = 'bedrock';
69
+ } else {
70
+ const names = Object.keys(modelFactories);
71
+ if (names.length === 1) {
72
+ defaultName = names[0];
73
+ }
74
+ }
75
+
76
+ const modelActivity = new ModelActivity(modelFactories, defaultName);
77
+ const activities: Record<string, (...args: never[]) => unknown> = {
78
+ invokeModel: (input: InvokeModelInput) => modelActivity.invokeModel(input),
79
+ invokeModelStreaming: (input: InvokeModelStreamingInput) => modelActivity.invokeModelStreaming(input),
80
+ };
81
+
82
+ const mcpClients = options.mcpClients ?? {};
83
+ const idleMs = msOptionalToNumber(options.mcpConnectionIdleTimeout);
84
+ for (const [server, factory] of Object.entries(mcpClients)) {
85
+ activities[listToolsActivityName(server)] = buildListToolsActivity(server, factory, idleMs);
86
+ activities[callToolActivityName(server)] = buildCallToolActivity(server, factory, idleMs);
87
+ }
88
+
89
+ const runContext = async (next: () => Promise<void>): Promise<void> => {
90
+ try {
91
+ await next();
92
+ } finally {
93
+ // Close any worker-process MCP connections opened lazily by the
94
+ // listTools/callTool activities.
95
+ for (const server of Object.keys(mcpClients)) {
96
+ await _evictConnection(server);
97
+ }
98
+ }
99
+ };
100
+
101
+ super({
102
+ name: 'StrandsPlugin',
103
+ activities,
104
+ runContext,
105
+ dataConverter: {
106
+ failureConverterPath: require.resolve('./failure-converter'),
107
+ },
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Extend the bundler config so workflow code can bundle `@strands-agents/sdk`:
113
+ *
114
+ * - Ignore worker-only / non-workflow-safe modules that the SDK index
115
+ * transitively pulls in but that are unreachable from workflow code.
116
+ * This covers:
117
+ * - `fs` (statically imported by `vended-plugins` and `vended-tools`).
118
+ * - Every `@strands-agents/sdk` model provider's HTTP SDK
119
+ * (`@aws-sdk/client-bedrock-runtime`, `@anthropic-ai/sdk`, `openai`,
120
+ * `@google/genai`, `ai`). The workers constructs models worker-side;
121
+ * workflow code only goes through {@link TemporalModel}.
122
+ * - `@temporalio/activity` and `@temporalio/client`, which the
123
+ * worker-only halves of {@link TemporalMCPClient}, {@link autoHeartbeat},
124
+ * and `@temporalio/workflow-streams/client` import.
125
+ * - `path` / `crypto`, pulled in transitively by the same worker-only code.
126
+ *
127
+ * - Replace the dynamic-imported MCP transport helpers
128
+ * (`@modelcontextprotocol/sdk/client/{stdio,sse,streamableHttp}.js` and
129
+ * their `node:*` dependencies, plus `eventsource-parser/stream` which
130
+ * `streamableHttp.js` reaches) with an empty module. They live in
131
+ * `mcp-config.js`'s server-only code paths.
132
+ *
133
+ * - Inline async chunks so the bundle stays a single file — webpack's
134
+ * default JSONP chunk loader references `self`/`document`, neither of
135
+ * which exists in the workflow VM.
136
+ */
137
+ override configureBundler(options: BundleOptions): BundleOptions {
138
+ const base = super.configureBundler(options);
139
+ const prevHook = base.webpackConfigHook;
140
+ const ignoreModules = [
141
+ ...(base.ignoreModules ?? []),
142
+ 'fs',
143
+ 'path',
144
+ 'crypto',
145
+ '@temporalio/activity',
146
+ '@temporalio/client',
147
+ '@aws-sdk/client-bedrock-runtime',
148
+ '@aws-sdk/middleware-websocket',
149
+ '@anthropic-ai/sdk',
150
+ 'openai',
151
+ '@google/genai',
152
+ 'ai',
153
+ ];
154
+ return {
155
+ ...base,
156
+ ignoreModules,
157
+ webpackConfigHook: (config) => {
158
+ (config.output ??= {}).asyncChunks = false;
159
+ (config.optimization ??= {}).splitChunks = false;
160
+
161
+ const plugins = [...(config.plugins ?? [])];
162
+ plugins.push(emptyModuleRewritesPlugin() as (typeof plugins)[number]);
163
+ const merged = { ...config, plugins };
164
+
165
+ return prevHook ? prevHook(merged) : merged;
166
+ },
167
+ };
168
+ }
169
+ }
170
+
171
+ /**
172
+ * The slice of webpack's runtime API these rewrites use, read off the running
173
+ * compiler (see {@link emptyModuleRewritesPlugin}).
174
+ */
175
+ interface WebpackApi {
176
+ NormalModuleReplacementPlugin: new (
177
+ resourceRegExp: RegExp,
178
+ newResource: (resource: { request: string }) => void
179
+ ) => WebpackPlugin;
180
+ }
181
+
182
+ interface WebpackPlugin {
183
+ apply(compiler: WebpackCompiler): void;
184
+ }
185
+
186
+ interface WebpackCompiler {
187
+ /** webpack 5 exposes its own runtime API on the compiler. */
188
+ webpack: WebpackApi;
189
+ }
190
+
191
+ /**
192
+ * A webpack plugin that stubs out `@strands-agents/sdk`'s worker-only static and
193
+ * dynamic imports — `node:*` builtins and the MCP client transports — with an
194
+ * empty module, so they never reach the Workflow isolate. Paired with the
195
+ * `ignoreModules` whitelist (see {@link StrandsPlugin.configureBundler}).
196
+ *
197
+ * webpack is taken from `compiler.webpack` rather than imported or borrowed off
198
+ * another plugin's constructor: `@temporalio/strands-agents` doesn't depend on
199
+ * webpack directly, and using the compiler's own webpack guarantees the exact
200
+ * instance running the bundle regardless of how the SDK orders its own bundler
201
+ * plugins — never a second copy.
202
+ */
203
+ function emptyModuleRewritesPlugin(): WebpackPlugin {
204
+ const empty = require.resolve('./empty-module');
205
+ const ignorePattern =
206
+ /^(?:node:(?:fs\/promises|os|path|process|stream)|@modelcontextprotocol\/sdk\/client\/(?:stdio|sse|streamableHttp)\.js|eventsource-parser\/stream)$/;
207
+ return {
208
+ apply(compiler) {
209
+ const { NormalModuleReplacementPlugin } = compiler.webpack;
210
+ new NormalModuleReplacementPlugin(ignorePattern, (resource) => {
211
+ resource.request = empty;
212
+ }).apply(compiler);
213
+ },
214
+ };
215
+ }
@@ -0,0 +1,127 @@
1
+ import {
2
+ JsonBlock,
3
+ TextBlock,
4
+ Tool,
5
+ ToolResultBlock,
6
+ type JSONSchema,
7
+ type JSONValue,
8
+ type ToolContext,
9
+ type ToolSpec,
10
+ type ToolStreamGenerator,
11
+ } from '@strands-agents/sdk';
12
+ import type { z } from 'zod';
13
+ import * as workflow from '@temporalio/workflow';
14
+ import type { ActivityOptions } from '@temporalio/workflow';
15
+ import { ActivityFailure, ApplicationFailure } from '@temporalio/common';
16
+ import { STRANDS_INTERRUPT_TYPE } from './failure-converter';
17
+ import { toJsonSchema } from './json-schema';
18
+
19
+ /**
20
+ * Options accepted by {@link activityAsTool}.
21
+ *
22
+ * `name` defaults to the activity function's `.name`. `description` defaults
23
+ * to an empty string and SHOULD be supplied so the model has signal about
24
+ * when to call the tool. `inputSchema` describes the activity's single
25
+ * argument; pass either a literal JSON Schema object or a Zod schema, which
26
+ * is converted to JSON Schema for you.
27
+ */
28
+ export interface ActivityAsToolOptions {
29
+ name?: string;
30
+ description?: string;
31
+ inputSchema?: JSONSchema | z.ZodType;
32
+ activityOptions?: ActivityOptions;
33
+ }
34
+
35
+ /**
36
+ * A Strands {@link Tool} whose body dispatches a Temporal activity via
37
+ * {@link workflow.executeActivity}.
38
+ *
39
+ * When the activity fails with an {@link ApplicationFailure} whose `type`
40
+ * matches {@link STRANDS_INTERRUPT_TYPE} — see {@link StrandsFailureConverter} —
41
+ * `stream()` re-throws an {@link InterruptError} so the agent loop handles
42
+ * the interrupt the same way as a hook- or tool-body interrupt. Other
43
+ * failures are converted to an error {@link ToolResultBlock}.
44
+ */
45
+ export class TemporalActivityTool extends Tool {
46
+ readonly name: string;
47
+ readonly description: string;
48
+ readonly toolSpec: ToolSpec;
49
+ private readonly activityName: string;
50
+ private readonly activityOptions: ActivityOptions;
51
+
52
+ constructor(
53
+ activityName: string,
54
+ options: {
55
+ name?: string;
56
+ description?: string;
57
+ inputSchema?: JSONSchema | z.ZodType;
58
+ activityOptions?: ActivityOptions;
59
+ }
60
+ ) {
61
+ super();
62
+ this.activityName = activityName;
63
+ this.name = options.name ?? activityName;
64
+ this.description = options.description ?? '';
65
+ this.toolSpec = {
66
+ name: this.name,
67
+ description: this.description,
68
+ inputSchema: toJsonSchema(options.inputSchema) ?? { type: 'object', properties: {} },
69
+ };
70
+ this.activityOptions = options.activityOptions ?? {};
71
+ }
72
+
73
+ // eslint-disable-next-line require-yield
74
+ async *stream(toolContext: ToolContext): ToolStreamGenerator {
75
+ const { toolUseId, input } = toolContext.toolUse;
76
+ const activities = workflow.proxyActivities<{
77
+ [key: string]: (input: JSONValue) => Promise<unknown>;
78
+ }>({
79
+ startToCloseTimeout: '10 minutes',
80
+ summary: this.name,
81
+ ...this.activityOptions,
82
+ });
83
+ let activityResult: unknown;
84
+ try {
85
+ activityResult = await activities[this.activityName]!(input);
86
+ } catch (err) {
87
+ if (
88
+ err instanceof ActivityFailure &&
89
+ err.cause instanceof ApplicationFailure &&
90
+ err.cause.type === STRANDS_INTERRUPT_TYPE
91
+ ) {
92
+ const details = (err.cause.details ?? []) as Array<{
93
+ name: string;
94
+ reason?: unknown;
95
+ response?: unknown;
96
+ }>;
97
+ const first = details[0];
98
+ // Route through the agent's interrupt() helper: throws InterruptError to
99
+ // halt on first call, returns the user's response on resume.
100
+ const response = toolContext.interrupt<unknown>({
101
+ name: first?.name ?? 'interrupt',
102
+ reason: first?.reason as JSONValue,
103
+ });
104
+ return new ToolResultBlock({
105
+ toolUseId,
106
+ status: 'success',
107
+ content: [toResultContent(response)],
108
+ });
109
+ }
110
+ return new ToolResultBlock({
111
+ toolUseId,
112
+ status: 'error',
113
+ content: [new TextBlock(String(err instanceof Error ? err.message : err))],
114
+ });
115
+ }
116
+ return new ToolResultBlock({
117
+ toolUseId,
118
+ status: 'success',
119
+ content: [toResultContent(activityResult)],
120
+ });
121
+ }
122
+ }
123
+
124
+ function toResultContent(value: unknown): TextBlock | JsonBlock {
125
+ if (typeof value === 'string') return new TextBlock(value);
126
+ return new JsonBlock({ json: value as JSONValue });
127
+ }
@@ -0,0 +1,103 @@
1
+ import { Agent, AfterToolsEvent } from '@strands-agents/sdk';
2
+ import type { AgentConfig } from '@strands-agents/sdk';
3
+ import type { ActivityOptions } from '@temporalio/workflow';
4
+ import type { Duration } from '@temporalio/common/lib/time';
5
+ import { TemporalModel } from './temporal-model';
6
+ import { TemporalMCPClient } from './temporal-mcp-client';
7
+
8
+ const SNAPSHOT_DISABLED =
9
+ 'TemporalAgent disables takeSnapshot()/loadSnapshot(). Temporal workflows ' +
10
+ 'already persist agent state durably via the event history at a finer ' +
11
+ 'granularity than Strands snapshots. Remove the snapshot call and rely on ' +
12
+ "Temporal's durable execution instead.";
13
+
14
+ const RETRY_STRATEGY_DISABLED =
15
+ 'TemporalAgent disables Strands retries; configure retries via retryPolicy ' +
16
+ 'in the model activity options on TemporalAgent, and on the activity options ' +
17
+ 'passed to workflow.activityAsTool, workflow.activityAsHook, or TemporalMCPClient. ' +
18
+ 'Remove retryStrategy from TemporalAgent(...) or pass retryStrategy: null.';
19
+
20
+ /**
21
+ * Options for {@link TemporalAgent}.
22
+ *
23
+ * Accepts everything {@link AgentConfig} accepts except `model` (which is a
24
+ * factory name selecting a worker-side {@link Model}, not an instance) and
25
+ * `retryStrategy` (always disabled — Temporal handles retries via
26
+ * `activityOptions.retry`).
27
+ *
28
+ * The {@link ActivityOptions} apply to every model invocation this agent
29
+ * makes. `streamingTopic`/`streamingBatchInterval` route each
30
+ * {@link ModelStreamEvent} to a {@link WorkflowStream} topic of that name.
31
+ */
32
+ export interface TemporalAgentOptions extends Omit<AgentConfig, 'model' | 'retryStrategy'> {
33
+ model?: string;
34
+ activityOptions?: ActivityOptions;
35
+ streamingTopic?: string;
36
+ streamingBatchInterval?: Duration;
37
+ }
38
+
39
+ /**
40
+ * A Strands {@link Agent} that routes every model call through a Temporal
41
+ * activity.
42
+ *
43
+ * `model` is the name of a factory registered in
44
+ * `StrandsPlugin({ models: {...} })`. The `activityOptions` apply to every
45
+ * model invocation this agent makes. All other options are forwarded to
46
+ * Strands' {@link Agent} constructor (`tools`, `plugins`, `systemPrompt`,
47
+ * `structuredOutputSchema`, `messages`, etc.).
48
+ *
49
+ * Strands' `retryStrategy` is disabled; configure retries via
50
+ * `activityOptions.retry` here and on the activity options accepted by
51
+ * {@link activityAsTool}, {@link activityAsHook}, and {@link TemporalMCPClient}.
52
+ */
53
+ export class TemporalAgent extends Agent {
54
+ constructor(options: TemporalAgentOptions = {}) {
55
+ const { model, activityOptions, streamingTopic, streamingBatchInterval, ...rest } = options;
56
+ if ((rest as { retryStrategy?: unknown }).retryStrategy !== undefined) {
57
+ throw new Error(RETRY_STRATEGY_DISABLED);
58
+ }
59
+ const temporalModel = new TemporalModel({
60
+ modelName: model,
61
+ activityOptions,
62
+ streamingTopic,
63
+ streamingBatchInterval,
64
+ });
65
+ super({
66
+ ...rest,
67
+ model: temporalModel,
68
+ retryStrategy: null,
69
+ });
70
+
71
+ // Strands lists each MCP client's tools once at agent initialization and
72
+ // reuses that list for every turn. For clients with `cacheTools: false`,
73
+ // re-list on each turn so a mid-workflow MCP-server restart is picked up.
74
+ // `AfterToolsEvent` fires after a tool round completes, before the next
75
+ // model call reads the tool registry — so the refresh lands on that call.
76
+ for (const client of collectMcpClients(rest.tools)) {
77
+ if (!client.cacheTools) {
78
+ this.addHook(AfterToolsEvent, (event) => client.refreshTools(event.agent.toolRegistry));
79
+ }
80
+ }
81
+ }
82
+
83
+ override takeSnapshot(): never {
84
+ throw new Error(SNAPSHOT_DISABLED);
85
+ }
86
+
87
+ override loadSnapshot(): never {
88
+ throw new Error(SNAPSHOT_DISABLED);
89
+ }
90
+ }
91
+
92
+ /** Collect every {@link TemporalMCPClient} in a (possibly nested) tool list. */
93
+ function collectMcpClients(tools: AgentConfig['tools']): TemporalMCPClient[] {
94
+ const found: TemporalMCPClient[] = [];
95
+ const walk = (items: NonNullable<AgentConfig['tools']>): void => {
96
+ for (const item of items) {
97
+ if (Array.isArray(item)) walk(item);
98
+ else if (item instanceof TemporalMCPClient) found.push(item);
99
+ }
100
+ };
101
+ if (tools) walk(tools);
102
+ return found;
103
+ }