@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
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTEXT_WINDOW_OVERFLOW_TYPE = exports.STRANDS_MALFORMED_INTERRUPT_TYPE = exports.STRANDS_INTERRUPT_TYPE = void 0;
4
+ exports.rewriteError = rewriteError;
5
+ exports.workflowErrorFor = workflowErrorFor;
6
+ exports.applicationFailureType = applicationFailureType;
7
+ const sdk_1 = require("@strands-agents/sdk");
8
+ const common_1 = require("@temporalio/common");
9
+ exports.STRANDS_INTERRUPT_TYPE = 'StrandsInterrupt';
10
+ /** The failure type of an interrupt an activity threw that the plugin cannot read. */
11
+ exports.STRANDS_MALFORMED_INTERRUPT_TYPE = 'StrandsMalformedInterrupt';
12
+ /** The failure type of a Strands context overflow, from the model activity to `TemporalModel`. */
13
+ exports.CONTEXT_WINDOW_OVERFLOW_TYPE = 'ContextWindowOverflowError';
14
+ // Any value with a non-empty `interrupts` array is taken as an interrupt, so a malformed one fails
15
+ // as such instead of being retried as an ordinary error.
16
+ function isInterruptAttempt(err) {
17
+ if (err === null || typeof err !== 'object')
18
+ return false;
19
+ const { interrupts } = err;
20
+ return Array.isArray(interrupts) && interrupts.length > 0;
21
+ }
22
+ const TERMINAL_ERROR_TYPES = [
23
+ { ctor: sdk_1.ContextWindowOverflowError, name: exports.CONTEXT_WINDOW_OVERFLOW_TYPE },
24
+ { ctor: sdk_1.MaxTokensError, name: 'MaxTokensError' },
25
+ { ctor: sdk_1.StructuredOutputError, name: 'StructuredOutputError' },
26
+ ];
27
+ // The failure type of a Strands terminal model error, or undefined for any other value. The name
28
+ // matches an error from another copy of `@strands-agents/sdk`, or any error with that name;
29
+ // `instanceof` also matches a subclass that sets a name of its own.
30
+ function terminalType(err) {
31
+ if (!(err instanceof Error))
32
+ return undefined;
33
+ return TERMINAL_ERROR_TYPES.find(({ ctor, name }) => err instanceof ctor || err.name === name)?.name;
34
+ }
35
+ // `ApplicationFailure.fromError` keeps the error's message, stack and cause, but returns an
36
+ // `ApplicationFailure` it is given, and one decoded earlier would still be encoded from its original
37
+ // proto, without these overrides. Start a fresh failure for that case.
38
+ function retype(err, overrides) {
39
+ if (err instanceof common_1.ApplicationFailure) {
40
+ return common_1.ApplicationFailure.create({ message: err.message, ...overrides, cause: err });
41
+ }
42
+ return common_1.ApplicationFailure.fromError(err, overrides);
43
+ }
44
+ /**
45
+ * Rewrite an error an activity threw. A Strands interrupt becomes a typed,
46
+ * non-retryable failure that the worker treats as benign, and a malformed one a
47
+ * non-retryable failure of type {@link STRANDS_MALFORMED_INTERRUPT_TYPE}. A
48
+ * Strands terminal model error becomes a typed, non-retryable failure, benign
49
+ * for a context overflow when `benignOverflow` is set. Each keeps the error's
50
+ * stack and cause. Any other value is returned as it is.
51
+ */
52
+ function rewriteError(err, options = {}) {
53
+ if (isInterruptAttempt(err)) {
54
+ const details = interruptDetails(err.interrupts);
55
+ if (details === undefined) {
56
+ return retype(err, {
57
+ message: `malformed interrupt (${String(err.message)}): each entry needs a toJSON() that returns an object with a unique string name, and JSON-encodable values`,
58
+ type: exports.STRANDS_MALFORMED_INTERRUPT_TYPE,
59
+ nonRetryable: true,
60
+ });
61
+ }
62
+ return retype(err, {
63
+ message: `interrupt:${details.map((d) => d.name).join(',')}`,
64
+ type: exports.STRANDS_INTERRUPT_TYPE,
65
+ nonRetryable: true,
66
+ details,
67
+ category: common_1.ApplicationFailureCategory.BENIGN,
68
+ });
69
+ }
70
+ const type = terminalType(err);
71
+ if (type === undefined)
72
+ return err;
73
+ const benign = options.benignOverflow === true && type === exports.CONTEXT_WINDOW_OVERFLOW_TYPE;
74
+ return retype(err, { type, nonRetryable: true, ...(benign ? { category: common_1.ApplicationFailureCategory.BENIGN } : {}) });
75
+ }
76
+ /**
77
+ * The error a `TemporalAgent` turn ends with in workflow code, in place of one
78
+ * that would only fail the workflow task on every attempt. A Strands terminal
79
+ * model error becomes a typed, non-retryable failure with the original error as
80
+ * its cause. A Strands `ModelError` that wraps a Temporal failure, such as a
81
+ * model activity that failed or was cancelled, becomes that failure, so the run
82
+ * fails or is cancelled. Any other value is returned as it is.
83
+ */
84
+ function workflowErrorFor(err) {
85
+ const type = terminalType(err);
86
+ if (type !== undefined) {
87
+ return common_1.ApplicationFailure.create({
88
+ message: err.message,
89
+ type,
90
+ nonRetryable: true,
91
+ cause: err,
92
+ });
93
+ }
94
+ if (err instanceof sdk_1.ModelError && err.cause instanceof common_1.TemporalFailure)
95
+ return err.cause;
96
+ return err;
97
+ }
98
+ /**
99
+ * The application failure type of a decoded failure. It also reads the type from
100
+ * the failure's proto when the failure converter returned another kind of
101
+ * `TemporalFailure`.
102
+ */
103
+ function applicationFailureType(failure) {
104
+ if (failure instanceof common_1.ApplicationFailure)
105
+ return failure.type ?? undefined;
106
+ if (failure instanceof common_1.TemporalFailure)
107
+ return failure.failure?.applicationFailureInfo?.type ?? undefined;
108
+ return undefined;
109
+ }
110
+ // The details of each interrupt, or undefined when an entry is missing or has no toJSON(), returns
111
+ // no object with a string name, repeats another entry's name, or holds a value JSON cannot encode.
112
+ // `Array.from` visits the holes in a sparse array, which `map` and `every` skip and the worker cannot
113
+ // encode as details. Strands keys a tool's interrupts by name, so a repeated name would get the first
114
+ // entry's response. The JSON check applies whatever payload converter the worker uses.
115
+ function interruptDetails(interrupts) {
116
+ try {
117
+ const details = Array.from(interrupts, (i) => i.toJSON());
118
+ const named = details.every((d) => d !== null && typeof d === 'object' && typeof d.name === 'string');
119
+ if (!named)
120
+ return undefined;
121
+ if (new Set(details.map((d) => d.name)).size !== details.length)
122
+ return undefined;
123
+ JSON.stringify(details);
124
+ return details;
125
+ }
126
+ catch {
127
+ return undefined;
128
+ }
129
+ }
130
+ //# sourceMappingURL=strands-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strands-errors.js","sourceRoot":"","sources":["../src/strands-errors.ts"],"names":[],"mappings":";;;AAuEA,oCAsBC;AAUD,4CAYC;AAOD,wDAIC;AA9HD,6CAAoH;AACpH,+CAK4B;AAEf,QAAA,sBAAsB,GAAG,kBAAkB,CAAC;AAEzD,sFAAsF;AACzE,QAAA,gCAAgC,GAAG,2BAA2B,CAAC;AAE5E,kGAAkG;AACrF,QAAA,4BAA4B,GAAG,4BAA4B,CAAC;AAiBzE,mGAAmG;AACnG,yDAAyD;AACzD,SAAS,kBAAkB,CAAC,GAAY;IACtC,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC1D,MAAM,EAAE,UAAU,EAAE,GAAG,GAA+B,CAAC;IACvD,OAAO,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,oBAAoB,GAAG;IAC3B,EAAE,IAAI,EAAE,gCAA0B,EAAE,IAAI,EAAE,oCAA4B,EAAE;IACxE,EAAE,IAAI,EAAE,oBAAc,EAAE,IAAI,EAAE,gBAAgB,EAAE;IAChD,EAAE,IAAI,EAAE,2BAAqB,EAAE,IAAI,EAAE,uBAAuB,EAAE;CAC/D,CAAC;AAEF,iGAAiG;AACjG,4FAA4F;AAC5F,oEAAoE;AACpE,SAAS,YAAY,CAAC,GAAY;IAChC,IAAI,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9C,OAAO,oBAAoB,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,GAAG,YA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CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,EAAE,CAAE,CAAmB,CAAC,MAAM,EAAE,CAAC,CAAC;QAC7E,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CACzB,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAQ,CAAwB,CAAC,IAAI,KAAK,QAAQ,CACjG,CAAC;QACF,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC7B,IAAI,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAE,CAAsB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC;QACxG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QACxB,OAAO,OAA6B,CAAC;IACvC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC"}
@@ -1,14 +1,14 @@
1
- import { Tool, type JSONSchema, type ToolContext, type ToolSpec, type ToolStreamGenerator } from '@strands-agents/sdk';
1
+ import { Tool, ToolResultBlock, type JSONSchema, type ToolContext, type ToolSpec, type ToolStreamGenerator } from '@strands-agents/sdk';
2
2
  import type { z } from 'zod';
3
3
  import type { ActivityOptions } from '@temporalio/workflow';
4
4
  /**
5
5
  * Options accepted by {@link activityAsTool}.
6
6
  *
7
- * `name` defaults to the activity function's `.name`. `description` defaults
8
- * to an empty string and SHOULD be supplied so the model has signal about
9
- * when to call the tool. `inputSchema` describes the activity's single
10
- * argument; pass either a literal JSON Schema object or a Zod schema, which
11
- * is converted to JSON Schema for you.
7
+ * `name` defaults to the registered activity name. `description` is omitted
8
+ * when not supplied; supply one to help the model decide when to call the
9
+ * tool. `inputSchema` describes the activity's single argument; pass either a
10
+ * literal JSON Schema object or a Zod schema, which is converted to JSON
11
+ * Schema for you.
12
12
  */
13
13
  export interface ActivityAsToolOptions {
14
14
  name?: string;
@@ -21,10 +21,12 @@ export interface ActivityAsToolOptions {
21
21
  * {@link workflow.executeActivity}.
22
22
  *
23
23
  * When the activity fails with an {@link ApplicationFailure} whose `type`
24
- * matches {@link STRANDS_INTERRUPT_TYPE} — see {@link StrandsFailureConverter} —
25
- * `stream()` re-throws an {@link InterruptError} so the agent loop handles
26
- * the interrupt the same way as a hook- or tool-body interrupt. Other
27
- * failures are converted to an error {@link ToolResultBlock}.
24
+ * matches {@link STRANDS_INTERRUPT_TYPE} — {@link StrandsPlugin} turns an
25
+ * interrupt the activity throws into one —
26
+ * `stream()` raises each interrupt in its details, in order, so the agent loop
27
+ * handles them the same way as hook- or tool-body interrupts: the agent pauses
28
+ * at the first one without a response. Other failures, including a malformed
29
+ * interrupt, are converted to an error {@link ToolResultBlock}.
28
30
  */
29
31
  export declare class TemporalActivityTool extends Tool {
30
32
  readonly name: string;
@@ -40,3 +42,9 @@ export declare class TemporalActivityTool extends Tool {
40
42
  });
41
43
  stream(toolContext: ToolContext): ToolStreamGenerator;
42
44
  }
45
+ /**
46
+ * The error result for a tool call whose activity failed. An `ActivityFailure`'s own message is
47
+ * the generic "Activity task failed", so the result carries its cause instead: what the activity
48
+ * threw, or the timeout or cancellation that ended it. The error is attached for hooks.
49
+ */
50
+ export declare function activityErrorResult(toolUseId: string, err: unknown): ToolResultBlock;
@@ -15,33 +15,45 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.TemporalActivityTool = void 0;
37
+ exports.activityErrorResult = activityErrorResult;
27
38
  const sdk_1 = require("@strands-agents/sdk");
28
39
  const workflow = __importStar(require("@temporalio/workflow"));
29
40
  const common_1 = require("@temporalio/common");
30
- const failure_converter_1 = require("./failure-converter");
41
+ const strands_errors_1 = require("./strands-errors");
31
42
  const json_schema_1 = require("./json-schema");
32
43
  /**
33
44
  * A Strands {@link Tool} whose body dispatches a Temporal activity via
34
45
  * {@link workflow.executeActivity}.
35
46
  *
36
47
  * When the activity fails with an {@link ApplicationFailure} whose `type`
37
- * matches {@link STRANDS_INTERRUPT_TYPE} — see {@link StrandsFailureConverter} —
38
- * `stream()` re-throws an {@link InterruptError} so the agent loop handles
39
- * the interrupt the same way as a hook- or tool-body interrupt. Other
40
- * failures are converted to an error {@link ToolResultBlock}.
48
+ * matches {@link STRANDS_INTERRUPT_TYPE} — {@link StrandsPlugin} turns an
49
+ * interrupt the activity throws into one —
50
+ * `stream()` raises each interrupt in its details, in order, so the agent loop
51
+ * handles them the same way as hook- or tool-body interrupts: the agent pauses
52
+ * at the first one without a response. Other failures, including a malformed
53
+ * interrupt, are converted to an error {@link ToolResultBlock}.
41
54
  */
42
55
  class TemporalActivityTool extends sdk_1.Tool {
43
56
  name;
44
- description;
45
57
  toolSpec;
46
58
  activityName;
47
59
  activityOptions;
@@ -49,12 +61,14 @@ class TemporalActivityTool extends sdk_1.Tool {
49
61
  super();
50
62
  this.activityName = activityName;
51
63
  this.name = options.name ?? activityName;
52
- this.description = options.description ?? '';
53
64
  this.toolSpec = {
54
65
  name: this.name,
55
- description: this.description,
56
66
  inputSchema: (0, json_schema_1.toJsonSchema)(options.inputSchema) ?? { type: 'object', properties: {} },
57
67
  };
68
+ if (options.description !== undefined) {
69
+ this.description = options.description;
70
+ this.toolSpec.description = this.description;
71
+ }
58
72
  this.activityOptions = options.activityOptions ?? {};
59
73
  }
60
74
  // eslint-disable-next-line require-yield
@@ -72,26 +86,18 @@ class TemporalActivityTool extends sdk_1.Tool {
72
86
  catch (err) {
73
87
  if (err instanceof common_1.ActivityFailure &&
74
88
  err.cause instanceof common_1.ApplicationFailure &&
75
- err.cause.type === failure_converter_1.STRANDS_INTERRUPT_TYPE) {
89
+ err.cause.type === strands_errors_1.STRANDS_INTERRUPT_TYPE) {
76
90
  const details = (err.cause.details ?? []);
77
- const first = details[0];
78
- // Route through the agent's interrupt() helper: throws InterruptError to
79
- // halt on first call, returns the user's response on resume.
80
- const response = toolContext.interrupt({
81
- name: first?.name ?? 'interrupt',
82
- reason: first?.reason,
83
- });
91
+ // Route each interrupt through the agent's interrupt() helper, in order: the first one with
92
+ // no response throws InterruptError and halts; on resume the answered ones return theirs.
93
+ const responses = (details.length > 0 ? details : [{ name: 'interrupt' }]).map((d) => toolContext.interrupt({ name: d.name ?? 'interrupt', reason: d.reason }));
84
94
  return new sdk_1.ToolResultBlock({
85
95
  toolUseId,
86
96
  status: 'success',
87
- content: [toResultContent(response)],
97
+ content: [toResultContent(responses.length === 1 ? responses[0] : responses)],
88
98
  });
89
99
  }
90
- return new sdk_1.ToolResultBlock({
91
- toolUseId,
92
- status: 'error',
93
- content: [new sdk_1.TextBlock(String(err instanceof Error ? err.message : err))],
94
- });
100
+ return activityErrorResult(toolUseId, err);
95
101
  }
96
102
  return new sdk_1.ToolResultBlock({
97
103
  toolUseId,
@@ -101,6 +107,21 @@ class TemporalActivityTool extends sdk_1.Tool {
101
107
  }
102
108
  }
103
109
  exports.TemporalActivityTool = TemporalActivityTool;
110
+ /**
111
+ * The error result for a tool call whose activity failed. An `ActivityFailure`'s own message is
112
+ * the generic "Activity task failed", so the result carries its cause instead: what the activity
113
+ * threw, or the timeout or cancellation that ended it. The error is attached for hooks.
114
+ */
115
+ function activityErrorResult(toolUseId, err) {
116
+ const cause = err instanceof common_1.ActivityFailure && err.cause ? err.cause : err;
117
+ const error = cause instanceof Error ? cause : new Error(String(cause));
118
+ return new sdk_1.ToolResultBlock({
119
+ toolUseId,
120
+ status: 'error',
121
+ content: [new sdk_1.TextBlock(error.message)],
122
+ error,
123
+ });
124
+ }
104
125
  function toResultContent(value) {
105
126
  if (typeof value === 'string')
106
127
  return new sdk_1.TextBlock(value);
@@ -1 +1 @@
1
- {"version":3,"file":"temporal-activity-tool.js","sourceRoot":"","sources":["../src/temporal-activity-tool.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6CAU6B;AAE7B,+DAAiD;AAEjD,+CAAyE;AACzE,2DAA6D;AAC7D,+CAA6C;AAkB7C;;;;;;;;;GASG;AACH,MAAa,oBAAqB,SAAQ,UAAI;IACnC,IAAI,CAAS;IACb,WAAW,CAAS;IACpB,QAAQ,CAAW;IACX,YAAY,CAAS;IACrB,eAAe,CAAkB;IAElD,YACE,YAAoB,EACpB,OAKC;QAED,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,YAAY,CAAC;QACzC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC;QAC7C,IAAI,CAAC,QAAQ,GAAG;YACd,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,WAAW,EAAE,IAAA,0BAAY,EAAC,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,IA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CAAC,KAAK,CAAC,CAAC;IAC3D,OAAO,IAAI,eAAS,CAAC,EAAE,IAAI,EAAE,KAAkB,EAAE,CAAC,CAAC;AACrD,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { Agent } from '@strands-agents/sdk';
2
- import type { AgentConfig } from '@strands-agents/sdk';
2
+ import type { AgentConfig, AgentResult, AgentStreamEvent, InvokeArgs, InvokeOptions } from '@strands-agents/sdk';
3
3
  import type { ActivityOptions } from '@temporalio/workflow';
4
4
  import type { Duration } from '@temporalio/common/lib/time';
5
5
  /**
@@ -7,7 +7,7 @@ import type { Duration } from '@temporalio/common/lib/time';
7
7
  *
8
8
  * Accepts everything {@link AgentConfig} accepts except `model` (which is a
9
9
  * factory name selecting a worker-side {@link Model}, not an instance) and
10
- * `retryStrategy` (always disabled — Temporal handles retries via
10
+ * `retryStrategy` (only `null` is accepted — Temporal handles retries via
11
11
  * `activityOptions.retry`).
12
12
  *
13
13
  * The {@link ActivityOptions} apply to every model invocation this agent
@@ -16,6 +16,8 @@ import type { Duration } from '@temporalio/common/lib/time';
16
16
  */
17
17
  export interface TemporalAgentOptions extends Omit<AgentConfig, 'model' | 'retryStrategy'> {
18
18
  model?: string;
19
+ /** Disable Strands retries explicitly; Temporal manages retries via `activityOptions.retry`. */
20
+ retryStrategy?: null;
19
21
  activityOptions?: ActivityOptions;
20
22
  streamingTopic?: string;
21
23
  streamingBatchInterval?: Duration;
@@ -33,9 +35,41 @@ export interface TemporalAgentOptions extends Omit<AgentConfig, 'model' | 'retry
33
35
  * Strands' `retryStrategy` is disabled; configure retries via
34
36
  * `activityOptions.retry` here and on the activity options accepted by
35
37
  * {@link activityAsTool}, {@link activityAsHook}, and {@link TemporalMCPClient}.
38
+ *
39
+ * `activityOptions.heartbeatTimeout` defaults to 10 seconds, and the model
40
+ * activities heartbeat at half of it; `heartbeatTimeout: 0` turns them off.
41
+ * Cancelling a model activity aborts the model call only when the activity
42
+ * heartbeats, since the worker learns of the cancellation through its
43
+ * heartbeats, and only when the model passes `cancelSignal` to its client
44
+ * (Strands' `AnthropicModel` does not). A model that ignores it keeps running
45
+ * and its activity can still complete with the model's result. A workflow
46
+ * cancel during a model call cancels the model activity. With `TRY_CANCEL` the
47
+ * run ends as cancelled at once. With `WAIT_CANCELLATION_COMPLETED` it ends as
48
+ * cancelled only if the activity does; if the activity completes, the turn
49
+ * continues with the model's result.
36
50
  */
37
51
  export declare class TemporalAgent extends Agent {
52
+ private readonly managerGiven;
38
53
  constructor(options?: TemporalAgentOptions);
39
- takeSnapshot(): never;
40
- loadSnapshot(): never;
54
+ /**
55
+ * Read the worker model's id, context window and stateful flag before Strands initializes the
56
+ * agent, so its traces, proactive compression and stateful handling use them from the first
57
+ * model call.
58
+ *
59
+ * Not `async`: once the config is read, this returns Strands' own `initialize()` promise, so it
60
+ * adds no microtask before Strands' hooks and model call.
61
+ */
62
+ initialize(): Promise<void>;
63
+ private initializeWithConfig;
64
+ /**
65
+ * Strands' stream, ending in a Temporal failure where Strands would end in an error that only
66
+ * fails the workflow task: a terminal model error becomes a typed, non-retryable failure, and a
67
+ * model activity that failed or was cancelled ends the turn with that activity's failure. So the
68
+ * run, or the update that runs the turn, fails or is cancelled. `invoke()` uses this too.
69
+ *
70
+ * Its awaits add microtasks to each agent event, and those are part of replay: when two turns run
71
+ * at once in one workflow, they can change the order in which the turns schedule activities. So
72
+ * removing this override, or wrapping the stream in another layer, can break replay of such runs.
73
+ */
74
+ stream(args: InvokeArgs, options?: InvokeOptions): AsyncGenerator<AgentStreamEvent, AgentResult, undefined>;
41
75
  }
@@ -4,12 +4,12 @@ exports.TemporalAgent = void 0;
4
4
  const sdk_1 = require("@strands-agents/sdk");
5
5
  const temporal_model_1 = require("./temporal-model");
6
6
  const temporal_mcp_client_1 = require("./temporal-mcp-client");
7
- const SNAPSHOT_DISABLED = 'TemporalAgent disables takeSnapshot()/loadSnapshot(). Temporal workflows ' +
8
- 'already persist agent state durably via the event history at a finer ' +
9
- 'granularity than Strands snapshots. Remove the snapshot call and rely on ' +
10
- "Temporal's durable execution instead.";
11
- const RETRY_STRATEGY_DISABLED = 'TemporalAgent disables Strands retries; configure retries via retryPolicy ' +
12
- 'in the model activity options on TemporalAgent, and on the activity options ' +
7
+ const strands_errors_1 = require("./strands-errors");
8
+ // Strands' own message, which its Agent throws at construction for a stateful model.
9
+ const STATEFUL_MANAGER_REFUSED = 'contextManager and conversationManager cannot be used with a stateful model. ' +
10
+ 'The model manages conversation state server-side.';
11
+ const RETRY_STRATEGY_DISABLED = 'TemporalAgent disables Strands retries; configure retries via activityOptions.retry ' +
12
+ 'on TemporalAgent, and on the activity options ' +
13
13
  'passed to workflow.activityAsTool, workflow.activityAsHook, or TemporalMCPClient. ' +
14
14
  'Remove retryStrategy from TemporalAgent(...) or pass retryStrategy: null.';
15
15
  /**
@@ -25,11 +25,24 @@ const RETRY_STRATEGY_DISABLED = 'TemporalAgent disables Strands retries; configu
25
25
  * Strands' `retryStrategy` is disabled; configure retries via
26
26
  * `activityOptions.retry` here and on the activity options accepted by
27
27
  * {@link activityAsTool}, {@link activityAsHook}, and {@link TemporalMCPClient}.
28
+ *
29
+ * `activityOptions.heartbeatTimeout` defaults to 10 seconds, and the model
30
+ * activities heartbeat at half of it; `heartbeatTimeout: 0` turns them off.
31
+ * Cancelling a model activity aborts the model call only when the activity
32
+ * heartbeats, since the worker learns of the cancellation through its
33
+ * heartbeats, and only when the model passes `cancelSignal` to its client
34
+ * (Strands' `AnthropicModel` does not). A model that ignores it keeps running
35
+ * and its activity can still complete with the model's result. A workflow
36
+ * cancel during a model call cancels the model activity. With `TRY_CANCEL` the
37
+ * run ends as cancelled at once. With `WAIT_CANCELLATION_COMPLETED` it ends as
38
+ * cancelled only if the activity does; if the activity completes, the turn
39
+ * continues with the model's result.
28
40
  */
29
41
  class TemporalAgent extends sdk_1.Agent {
42
+ managerGiven;
30
43
  constructor(options = {}) {
31
- const { model, activityOptions, streamingTopic, streamingBatchInterval, ...rest } = options;
32
- if (rest.retryStrategy !== undefined) {
44
+ const { model, retryStrategy, activityOptions, streamingTopic, streamingBatchInterval, ...rest } = options;
45
+ if (retryStrategy !== undefined && retryStrategy !== null) {
33
46
  throw new Error(RETRY_STRATEGY_DISABLED);
34
47
  }
35
48
  const temporalModel = new temporal_model_1.TemporalModel({
@@ -43,22 +56,61 @@ class TemporalAgent extends sdk_1.Agent {
43
56
  model: temporalModel,
44
57
  retryStrategy: null,
45
58
  });
59
+ this.managerGiven = Boolean(rest.conversationManager || rest.contextManager);
46
60
  // Strands lists each MCP client's tools once at agent initialization and
47
61
  // reuses that list for every turn. For clients with `cacheTools: false`,
48
62
  // re-list on each turn so a mid-workflow MCP-server restart is picked up.
49
63
  // `AfterToolsEvent` fires after a tool round completes, before the next
50
64
  // model call reads the tool registry — so the refresh lands on that call.
51
- for (const client of collectMcpClients(rest.tools)) {
52
- if (!client.cacheTools) {
53
- this.addHook(sdk_1.AfterToolsEvent, (event) => client.refreshTools(event.agent.toolRegistry));
54
- }
65
+ // One hook per client, as each lists its server. Strands runs them last to
66
+ // first, so the first client's hook runs last: it checks the round's
67
+ // listings together and applies them, so a name can move from one server
68
+ // to another.
69
+ const mcpClients = collectMcpClients(rest.tools);
70
+ for (const hook of temporal_mcp_client_1.TemporalMCPClient.refreshHooks(mcpClients.filter((client) => !client.cacheTools))) {
71
+ this.addHook(sdk_1.AfterToolsEvent, hook);
55
72
  }
73
+ // A name that Strands adds a client's tool under is that client's until a
74
+ // re-listing of that client drops it.
75
+ temporal_mcp_client_1.TemporalMCPClient.holdAdded(mcpClients, this.toolRegistry);
76
+ }
77
+ /**
78
+ * Read the worker model's id, context window and stateful flag before Strands initializes the
79
+ * agent, so its traces, proactive compression and stateful handling use them from the first
80
+ * model call.
81
+ *
82
+ * Not `async`: once the config is read, this returns Strands' own `initialize()` promise, so it
83
+ * adds no microtask before Strands' hooks and model call.
84
+ */
85
+ initialize() {
86
+ const loading = this.model instanceof temporal_model_1.TemporalModel ? this.model.loadConfig() : undefined;
87
+ return loading ? loading.then(() => this.initializeWithConfig()) : this.initializeWithConfig();
56
88
  }
57
- takeSnapshot() {
58
- throw new Error(SNAPSHOT_DISABLED);
89
+ initializeWithConfig() {
90
+ // Strands' Agent refuses these managers for a stateful model at construction, before
91
+ // TemporalAgent can read the worker model's stateful flag, so refuse them here.
92
+ if (this.model.stateful && this.managerGiven) {
93
+ return Promise.reject(new Error(STATEFUL_MANAGER_REFUSED));
94
+ }
95
+ return super.initialize();
59
96
  }
60
- loadSnapshot() {
61
- throw new Error(SNAPSHOT_DISABLED);
97
+ /**
98
+ * Strands' stream, ending in a Temporal failure where Strands would end in an error that only
99
+ * fails the workflow task: a terminal model error becomes a typed, non-retryable failure, and a
100
+ * model activity that failed or was cancelled ends the turn with that activity's failure. So the
101
+ * run, or the update that runs the turn, fails or is cancelled. `invoke()` uses this too.
102
+ *
103
+ * Its awaits add microtasks to each agent event, and those are part of replay: when two turns run
104
+ * at once in one workflow, they can change the order in which the turns schedule activities. So
105
+ * removing this override, or wrapping the stream in another layer, can break replay of such runs.
106
+ */
107
+ async *stream(args, options) {
108
+ try {
109
+ return yield* super.stream(args, options);
110
+ }
111
+ catch (err) {
112
+ throw (0, strands_errors_1.workflowErrorFor)(err);
113
+ }
62
114
  }
63
115
  }
64
116
  exports.TemporalAgent = TemporalAgent;
@@ -1 +1 @@
1
- {"version":3,"file":"temporal-agent.js","sourceRoot":"","sources":["../src/temporal-agent.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAI7D,qDAAiD;AACjD,+DAA0D;AAE1D,MAAM,iBAAiB,GACrB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,uCAAuC,CAAC;AAE1C,MAAM,uBAAuB,GAC3B,4EAA4E;IAC5E,8EAA8E;IAC9E,oFAAoF;IACpF,2EAA2E,CAAC;AAqB9E;;;;;;;;;;;;;GAaG;AACH,MAAa,aAAc,SAAQ,WAAK;IACtC,YAAY,UAAgC,EAAE;QAC5C,MAAM,EAAE,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