zeitlich 0.2.37 → 0.2.39

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 (172) hide show
  1. package/README.md +18 -0
  2. package/dist/{activities-Bb-nAjwQ.d.ts → activities-Bmu7XnaG.d.ts} +4 -4
  3. package/dist/{activities-vkI4_3CC.d.cts → activities-ByBFLvm2.d.cts} +4 -4
  4. package/dist/adapter-id-BB-mmrts.d.cts +17 -0
  5. package/dist/adapter-id-BB-mmrts.d.ts +17 -0
  6. package/dist/adapter-id-CMwVrVqv.d.cts +17 -0
  7. package/dist/adapter-id-CMwVrVqv.d.ts +17 -0
  8. package/dist/adapter-id-CbY2zeSt.d.cts +17 -0
  9. package/dist/adapter-id-CbY2zeSt.d.ts +17 -0
  10. package/dist/adapters/sandbox/bedrock/index.cjs +3 -3
  11. package/dist/adapters/sandbox/bedrock/index.cjs.map +1 -1
  12. package/dist/adapters/sandbox/bedrock/index.d.cts +6 -6
  13. package/dist/adapters/sandbox/bedrock/index.d.ts +6 -6
  14. package/dist/adapters/sandbox/bedrock/index.js +3 -3
  15. package/dist/adapters/sandbox/bedrock/index.js.map +1 -1
  16. package/dist/adapters/sandbox/bedrock/workflow.d.cts +2 -2
  17. package/dist/adapters/sandbox/bedrock/workflow.d.ts +2 -2
  18. package/dist/adapters/sandbox/daytona/index.cjs +3 -3
  19. package/dist/adapters/sandbox/daytona/index.cjs.map +1 -1
  20. package/dist/adapters/sandbox/daytona/index.d.cts +4 -4
  21. package/dist/adapters/sandbox/daytona/index.d.ts +4 -4
  22. package/dist/adapters/sandbox/daytona/index.js +3 -3
  23. package/dist/adapters/sandbox/daytona/index.js.map +1 -1
  24. package/dist/adapters/sandbox/daytona/workflow.d.cts +1 -1
  25. package/dist/adapters/sandbox/daytona/workflow.d.ts +1 -1
  26. package/dist/adapters/sandbox/e2b/index.cjs +26 -14
  27. package/dist/adapters/sandbox/e2b/index.cjs.map +1 -1
  28. package/dist/adapters/sandbox/e2b/index.d.cts +24 -4
  29. package/dist/adapters/sandbox/e2b/index.d.ts +24 -4
  30. package/dist/adapters/sandbox/e2b/index.js +26 -14
  31. package/dist/adapters/sandbox/e2b/index.js.map +1 -1
  32. package/dist/adapters/sandbox/e2b/workflow.d.cts +1 -1
  33. package/dist/adapters/sandbox/e2b/workflow.d.ts +1 -1
  34. package/dist/adapters/sandbox/inmemory/index.cjs +3 -3
  35. package/dist/adapters/sandbox/inmemory/index.cjs.map +1 -1
  36. package/dist/adapters/sandbox/inmemory/index.d.cts +4 -4
  37. package/dist/adapters/sandbox/inmemory/index.d.ts +4 -4
  38. package/dist/adapters/sandbox/inmemory/index.js +3 -3
  39. package/dist/adapters/sandbox/inmemory/index.js.map +1 -1
  40. package/dist/adapters/sandbox/inmemory/workflow.d.cts +1 -1
  41. package/dist/adapters/sandbox/inmemory/workflow.d.ts +1 -1
  42. package/dist/adapters/thread/anthropic/index.cjs +150 -13
  43. package/dist/adapters/thread/anthropic/index.cjs.map +1 -1
  44. package/dist/adapters/thread/anthropic/index.d.cts +9 -8
  45. package/dist/adapters/thread/anthropic/index.d.ts +9 -8
  46. package/dist/adapters/thread/anthropic/index.js +150 -14
  47. package/dist/adapters/thread/anthropic/index.js.map +1 -1
  48. package/dist/adapters/thread/anthropic/workflow.cjs +9 -3
  49. package/dist/adapters/thread/anthropic/workflow.cjs.map +1 -1
  50. package/dist/adapters/thread/anthropic/workflow.d.cts +6 -5
  51. package/dist/adapters/thread/anthropic/workflow.d.ts +6 -5
  52. package/dist/adapters/thread/anthropic/workflow.js +9 -4
  53. package/dist/adapters/thread/anthropic/workflow.js.map +1 -1
  54. package/dist/adapters/thread/google-genai/index.cjs +154 -13
  55. package/dist/adapters/thread/google-genai/index.cjs.map +1 -1
  56. package/dist/adapters/thread/google-genai/index.d.cts +6 -5
  57. package/dist/adapters/thread/google-genai/index.d.ts +6 -5
  58. package/dist/adapters/thread/google-genai/index.js +154 -14
  59. package/dist/adapters/thread/google-genai/index.js.map +1 -1
  60. package/dist/adapters/thread/google-genai/workflow.cjs +9 -3
  61. package/dist/adapters/thread/google-genai/workflow.cjs.map +1 -1
  62. package/dist/adapters/thread/google-genai/workflow.d.cts +6 -5
  63. package/dist/adapters/thread/google-genai/workflow.d.ts +6 -5
  64. package/dist/adapters/thread/google-genai/workflow.js +9 -4
  65. package/dist/adapters/thread/google-genai/workflow.js.map +1 -1
  66. package/dist/adapters/thread/index.cjs +16 -0
  67. package/dist/adapters/thread/index.cjs.map +1 -0
  68. package/dist/adapters/thread/index.d.cts +34 -0
  69. package/dist/adapters/thread/index.d.ts +34 -0
  70. package/dist/adapters/thread/index.js +12 -0
  71. package/dist/adapters/thread/index.js.map +1 -0
  72. package/dist/adapters/thread/langchain/index.cjs +149 -14
  73. package/dist/adapters/thread/langchain/index.cjs.map +1 -1
  74. package/dist/adapters/thread/langchain/index.d.cts +9 -8
  75. package/dist/adapters/thread/langchain/index.d.ts +9 -8
  76. package/dist/adapters/thread/langchain/index.js +149 -15
  77. package/dist/adapters/thread/langchain/index.js.map +1 -1
  78. package/dist/adapters/thread/langchain/workflow.cjs +9 -3
  79. package/dist/adapters/thread/langchain/workflow.cjs.map +1 -1
  80. package/dist/adapters/thread/langchain/workflow.d.cts +6 -5
  81. package/dist/adapters/thread/langchain/workflow.d.ts +6 -5
  82. package/dist/adapters/thread/langchain/workflow.js +9 -4
  83. package/dist/adapters/thread/langchain/workflow.js.map +1 -1
  84. package/dist/index.cjs +367 -59
  85. package/dist/index.cjs.map +1 -1
  86. package/dist/index.d.cts +11 -11
  87. package/dist/index.d.ts +11 -11
  88. package/dist/index.js +365 -61
  89. package/dist/index.js.map +1 -1
  90. package/dist/{proxy-DEtowJyd.d.cts → proxy-BAKzNGRq.d.cts} +1 -1
  91. package/dist/{proxy-0smGKvx8.d.ts → proxy-DO_MXbY4.d.ts} +1 -1
  92. package/dist/{thread-manager-C-C4pI2z.d.ts → thread-manager-CcRXasqs.d.ts} +2 -2
  93. package/dist/{thread-manager-D4vgzYrh.d.cts → thread-manager-ClwSaUnj.d.cts} +2 -2
  94. package/dist/{thread-manager-3fszQih4.d.ts → thread-manager-D-7lp1JK.d.ts} +2 -2
  95. package/dist/{thread-manager-CzYln2OC.d.cts → thread-manager-Y8Ucf0Tf.d.cts} +2 -2
  96. package/dist/{types-CPKDl-y_.d.ts → types-Bcbiq8iv.d.cts} +195 -22
  97. package/dist/{types-CNuWnvy9.d.ts → types-DAsQ21Rt.d.ts} +1 -1
  98. package/dist/{types-B37hKoWA.d.ts → types-DpHTX-iO.d.ts} +58 -1
  99. package/dist/{types-BO7Yju20.d.cts → types-Dt8-HBBT.d.ts} +195 -22
  100. package/dist/{types-D08CXPh8.d.cts → types-hFFi-Zd9.d.cts} +58 -1
  101. package/dist/{types-DWEUmYAJ.d.cts → types-lm8tMNJQ.d.cts} +1 -1
  102. package/dist/{types-tQL9njTu.d.cts → types-yx0LzPGn.d.cts} +21 -7
  103. package/dist/{types-tQL9njTu.d.ts → types-yx0LzPGn.d.ts} +21 -7
  104. package/dist/{workflow-CjXHbZZc.d.ts → workflow-Bmf9EtDW.d.ts} +83 -3
  105. package/dist/{workflow-Do_lzJpT.d.cts → workflow-Bx9utBwb.d.cts} +83 -3
  106. package/dist/workflow.cjs +266 -39
  107. package/dist/workflow.cjs.map +1 -1
  108. package/dist/workflow.d.cts +3 -3
  109. package/dist/workflow.d.ts +3 -3
  110. package/dist/workflow.js +264 -41
  111. package/dist/workflow.js.map +1 -1
  112. package/package.json +12 -2
  113. package/src/adapters/sandbox/bedrock/index.ts +12 -3
  114. package/src/adapters/sandbox/daytona/index.ts +12 -3
  115. package/src/adapters/sandbox/e2b/index.ts +36 -14
  116. package/src/adapters/sandbox/e2b/types.ts +16 -0
  117. package/src/adapters/sandbox/inmemory/index.ts +12 -3
  118. package/src/adapters/thread/adapter-id.test.ts +42 -0
  119. package/src/adapters/thread/anthropic/activities.ts +40 -5
  120. package/src/adapters/thread/anthropic/adapter-id.ts +16 -0
  121. package/src/adapters/thread/anthropic/fork-transform.test.ts +291 -0
  122. package/src/adapters/thread/anthropic/index.ts +3 -0
  123. package/src/adapters/thread/anthropic/model-invoker.ts +7 -1
  124. package/src/adapters/thread/anthropic/proxy.ts +3 -2
  125. package/src/adapters/thread/anthropic/thread-manager.ts +27 -1
  126. package/src/adapters/thread/google-genai/activities.ts +44 -5
  127. package/src/adapters/thread/google-genai/adapter-id.ts +16 -0
  128. package/src/adapters/thread/google-genai/fork-transform.test.ts +149 -0
  129. package/src/adapters/thread/google-genai/index.ts +3 -0
  130. package/src/adapters/thread/google-genai/model-invoker.ts +8 -2
  131. package/src/adapters/thread/google-genai/proxy.ts +3 -2
  132. package/src/adapters/thread/google-genai/thread-manager.ts +27 -1
  133. package/src/adapters/thread/index.ts +39 -0
  134. package/src/adapters/thread/langchain/activities.ts +40 -5
  135. package/src/adapters/thread/langchain/adapter-id.ts +16 -0
  136. package/src/adapters/thread/langchain/fork-transform.test.ts +142 -0
  137. package/src/adapters/thread/langchain/index.ts +3 -0
  138. package/src/adapters/thread/langchain/model-invoker.ts +7 -1
  139. package/src/adapters/thread/langchain/proxy.ts +3 -2
  140. package/src/adapters/thread/langchain/thread-manager.ts +27 -1
  141. package/src/lib/lifecycle.ts +14 -5
  142. package/src/lib/model/types.ts +7 -0
  143. package/src/lib/sandbox/manager.ts +26 -18
  144. package/src/lib/sandbox/types.ts +27 -7
  145. package/src/lib/session/session-edge-cases.integration.test.ts +336 -4
  146. package/src/lib/session/session.integration.test.ts +192 -2
  147. package/src/lib/session/session.ts +102 -8
  148. package/src/lib/session/types.ts +66 -3
  149. package/src/lib/state/index.ts +1 -0
  150. package/src/lib/state/manager.integration.test.ts +109 -0
  151. package/src/lib/state/manager.ts +38 -8
  152. package/src/lib/state/types.ts +25 -0
  153. package/src/lib/subagent/handler.ts +124 -11
  154. package/src/lib/subagent/index.ts +5 -1
  155. package/src/lib/subagent/subagent.integration.test.ts +628 -104
  156. package/src/lib/subagent/types.ts +63 -14
  157. package/src/lib/subagent/workflow.ts +29 -2
  158. package/src/lib/thread/index.ts +5 -0
  159. package/src/lib/thread/keys.test.ts +101 -0
  160. package/src/lib/thread/keys.ts +94 -0
  161. package/src/lib/thread/manager.test.ts +139 -0
  162. package/src/lib/thread/manager.ts +105 -9
  163. package/src/lib/thread/proxy.ts +3 -0
  164. package/src/lib/thread/types.ts +64 -1
  165. package/src/lib/tool-router/index.ts +2 -0
  166. package/src/lib/tool-router/router-edge-cases.integration.test.ts +92 -0
  167. package/src/lib/tool-router/router.integration.test.ts +12 -0
  168. package/src/lib/tool-router/router.ts +89 -16
  169. package/src/lib/tool-router/types.ts +42 -1
  170. package/src/lib/types.ts +12 -0
  171. package/src/workflow.ts +14 -1
  172. package/tsup.config.ts +1 -0
@@ -1,5 +1,5 @@
1
1
  import { proxyActivities, ActivityInterfaceFor } from '@temporalio/workflow';
2
- import { T as ThreadOps } from './types-BO7Yju20.cjs';
2
+ import { T as ThreadOps } from './types-Bcbiq8iv.cjs';
3
3
 
4
4
  /**
5
5
  * Shared proxy helper for thread operations.
@@ -1,5 +1,5 @@
1
1
  import { proxyActivities, ActivityInterfaceFor } from '@temporalio/workflow';
2
- import { T as ThreadOps } from './types-CPKDl-y_.js';
2
+ import { T as ThreadOps } from './types-Dt8-HBBT.js';
3
3
 
4
4
  /**
5
5
  * Shared proxy helper for thread operations.
@@ -1,7 +1,7 @@
1
1
  import Redis from 'ioredis';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
- import { J as JsonValue } from './types-CPKDl-y_.js';
4
- import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-B37hKoWA.js';
3
+ import { J as JsonValue } from './types-Dt8-HBBT.js';
4
+ import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-DpHTX-iO.js';
5
5
 
6
6
  /** SDK-native content type for Anthropic human messages */
7
7
  type AnthropicContent = string | Anthropic.Messages.ContentBlockParam[];
@@ -1,7 +1,7 @@
1
1
  import Redis from 'ioredis';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
- import { J as JsonValue } from './types-BO7Yju20.cjs';
4
- import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-D08CXPh8.cjs';
3
+ import { J as JsonValue } from './types-Bcbiq8iv.cjs';
4
+ import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-hFFi-Zd9.cjs';
5
5
 
6
6
  /** SDK-native content type for Anthropic human messages */
7
7
  type AnthropicContent = string | Anthropic.Messages.ContentBlockParam[];
@@ -1,7 +1,7 @@
1
1
  import Redis from 'ioredis';
2
- import { J as JsonValue } from './types-CPKDl-y_.js';
2
+ import { J as JsonValue } from './types-Dt8-HBBT.js';
3
3
  import { MessageContent, StoredMessage, BaseMessage } from '@langchain/core/messages';
4
- import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-B37hKoWA.js';
4
+ import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-DpHTX-iO.js';
5
5
 
6
6
  /** SDK-native content type for LangChain human messages */
7
7
  type LangChainContent = string | MessageContent;
@@ -1,7 +1,7 @@
1
1
  import Redis from 'ioredis';
2
- import { J as JsonValue } from './types-BO7Yju20.cjs';
2
+ import { J as JsonValue } from './types-Bcbiq8iv.cjs';
3
3
  import { MessageContent, StoredMessage, BaseMessage } from '@langchain/core/messages';
4
- import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-D08CXPh8.cjs';
4
+ import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-hFFi-Zd9.cjs';
5
5
 
6
6
  /** SDK-native content type for LangChain human messages */
7
7
  type LangChainContent = string | MessageContent;
@@ -1,8 +1,8 @@
1
1
  import { Duration } from '@temporalio/common';
2
- import { ActivityFunctionWithOptions, QueryDefinition, ActivityInterfaceFor } from '@temporalio/workflow';
2
+ import { ActivityFunctionWithOptions, QueryDefinition, ChildWorkflowOptions, ActivityInterfaceFor } from '@temporalio/workflow';
3
3
  import { UpdateDefinition } from '@temporalio/common/lib/interfaces';
4
4
  import { z } from 'zod';
5
- import { a as SandboxFileSystem, F as FileStat, D as DirentEntry, f as SandboxSnapshot, g as SandboxOps } from './types-tQL9njTu.js';
5
+ import { f as SandboxSnapshot, a as SandboxFileSystem, F as FileStat, D as DirentEntry, d as SandboxCreateOptions, g as SandboxOps } from './types-yx0LzPGn.cjs';
6
6
 
7
7
  /**
8
8
  * A tool definition with a name, description, and Zod schema for arguments.
@@ -98,12 +98,29 @@ interface ToolHandlerResponse<TResult = null, TToolResponse = JsonValue> {
98
98
  * payloads through Temporal's activity payload limit.
99
99
  */
100
100
  resultAppended?: boolean;
101
+ /**
102
+ * When true, the session will rewind: any in-flight parallel tool
103
+ * calls are cancelled and the LLM call is retried. The session reuses
104
+ * the same `assistantMessageId` for the retry; the next `runAgent`
105
+ * activity truncates the thread from that id on entry, wiping the
106
+ * triggering assistant message and any tool results already appended
107
+ * before re-invoking the LLM.
108
+ *
109
+ * The `toolResponse` for a rewinding tool call is ignored (never
110
+ * appended) since the thread is rewound back to the pre-assistant
111
+ * state on the next invocation.
112
+ */
113
+ rewind?: boolean;
101
114
  /** Token usage from the tool execution (e.g. child agent invocations) */
102
115
  usage?: TokenUsage;
103
116
  /** Thread ID used by the handler (surfaced to the LLM for subagent thread continuation) */
104
117
  threadId?: string;
105
118
  /** Sandbox ID created or used by the handler (e.g. child agent sandbox) */
106
119
  sandboxId?: string;
120
+ /** Snapshot captured on exit when `sandboxShutdown === "snapshot"`. */
121
+ snapshot?: SandboxSnapshot;
122
+ /** Snapshot captured immediately after sandbox seeding (before the agent loop starts) when `sandbox.mode === "new"` and `sandboxShutdown === "snapshot"`. Intended as a reusable "base" for new threads that want to skip re-seeding. */
123
+ baseSnapshot?: SandboxSnapshot;
107
124
  /** Unvalidated metadata passthrough from handler to hooks (e.g. infrastructure state) */
108
125
  metadata?: Record<string, unknown>;
109
126
  }
@@ -186,6 +203,28 @@ interface ProcessToolCallsContext {
186
203
  /** Active sandbox ID (when a sandbox is configured for this session) */
187
204
  sandboxId?: string;
188
205
  }
206
+ /**
207
+ * Signal that a tool handler requested a rewind. Attached to the
208
+ * {@link ProcessToolCallsResult} so the session can reuse the same
209
+ * `assistantMessageId` for the retry; the next `runAgent` activity
210
+ * then truncates the thread from that id on entry.
211
+ */
212
+ interface RewindSignal {
213
+ toolCallId: string;
214
+ toolName: string;
215
+ }
216
+ /**
217
+ * Result returned by {@link ToolRouter.processToolCalls}.
218
+ *
219
+ * The object is a standard array of tool call results for successful
220
+ * tool calls (cancelled or rewinding siblings are omitted), extended
221
+ * with a `rewind` property when any tool in the batch requested a
222
+ * rewind. Using an array-with-property lets existing code that treats
223
+ * the return value as `ToolCallResultUnion[]` continue to work.
224
+ */
225
+ type ProcessToolCallsResult<TResults extends Record<string, unknown>> = ToolCallResultUnion<TResults>[] & {
226
+ rewind?: RewindSignal;
227
+ };
189
228
  /**
190
229
  * Result from PreToolUse hook - can block or modify execution
191
230
  */
@@ -344,7 +383,7 @@ interface ToolRouter<T extends ToolMap> {
344
383
  * @param toolCalls - Array of parsed tool calls to process
345
384
  * @param context - Optional context including turn number for hooks
346
385
  */
347
- processToolCalls(toolCalls: ParsedToolCallUnion<T>[], context?: ProcessToolCallsContext): Promise<ToolCallResultUnion<InferToolResults<T>>[]>;
386
+ processToolCalls(toolCalls: ParsedToolCallUnion<T>[], context?: ProcessToolCallsContext): Promise<ProcessToolCallsResult<InferToolResults<T>>>;
348
387
  /**
349
388
  * Process tool calls matching a specific name with a custom handler.
350
389
  * Useful for overriding the default handler for specific cases.
@@ -388,6 +427,22 @@ type JsonSerializable<T> = {
388
427
  * Full state type combining base state with custom state
389
428
  */
390
429
  type AgentState<TCustom extends JsonSerializable<TCustom>> = BaseAgentState & TCustom;
430
+ /**
431
+ * The slice of agent state that is persisted alongside the thread in the
432
+ * thread store (e.g. Redis) so that a workflow can terminate, store its
433
+ * state, and be continued or forked later with that state rehydrated.
434
+ *
435
+ * Only fields that make sense to carry across workflow runs belong here.
436
+ * Runtime bookkeeping like status, version, turns, tools, fileTree, token
437
+ * counters, and the system prompt is intentionally NOT persisted — each run
438
+ * rebuilds those from scratch.
439
+ */
440
+ interface PersistedThreadState {
441
+ /** Task map serialized as entries so it round-trips through JSON. */
442
+ tasks: [string, WorkflowTask][];
443
+ /** All custom state fields declared by the caller. */
444
+ custom: Record<string, JsonValue>;
445
+ }
391
446
  /**
392
447
  * Agent state manager interface
393
448
  * Note: Temporal handlers must be set up in the workflow file due to
@@ -447,6 +502,13 @@ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
447
502
  deleteTask(id: string): boolean;
448
503
  /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
449
504
  setTools(newTools: ToolDefinition[]): void;
505
+ /**
506
+ * Snapshot the fields that should survive across workflow runs
507
+ * (tasks + all custom state). Safe to pass directly to
508
+ * {@link ThreadOps.saveThreadState}. Rehydrate on the next run with
509
+ * `mergeUpdate({ tasks: new Map(slice.tasks), ...slice.custom })`.
510
+ */
511
+ getPersistedSlice(): PersistedThreadState;
450
512
  /** Update the usage */
451
513
  updateUsage(usage: TokenUsage): void;
452
514
  /** Get the total usage */
@@ -667,6 +729,18 @@ interface RunAgentConfig extends AgentConfig {
667
729
  threadKey?: string;
668
730
  /** Metadata for the session */
669
731
  metadata?: Record<string, unknown>;
732
+ /**
733
+ * The id under which the assistant message produced by this call will
734
+ * be appended. The activity truncates the thread from this id on
735
+ * entry (no-op on the first attempt) so that:
736
+ *
737
+ * - Rewind retries can reuse the same id and the previous (bad)
738
+ * assistant + its tool results are wiped before the retry LLM call.
739
+ * - Resetting the Temporal workflow to this activity restores the
740
+ * pre-call thread state: replay re-truncates, re-invokes, and
741
+ * appends under the same id.
742
+ */
743
+ assistantMessageId: string;
670
744
  }
671
745
  /**
672
746
  * Configuration for appending a tool result
@@ -785,7 +859,9 @@ interface Hooks<T extends ToolMap, TResult = unknown, TContent = unknown> extend
785
859
  * - `"new"` — start a fresh thread (optionally specify its ID).
786
860
  * - `"continue"` — append directly to an existing thread in-place.
787
861
  * - `"fork"` — copy all messages from an existing thread into a new one and
788
- * continue there.
862
+ * continue there. When the adapter has `onForkPrepareThread` and/or
863
+ * `onForkTransform` hooks configured, they are applied once to the forked
864
+ * thread before the session starts.
789
865
  */
790
866
  type ThreadInit = {
791
867
  mode: "new";
@@ -808,9 +884,12 @@ type ThreadInit = {
808
884
  * Paused sandboxes are automatically resumed. The shutdown policy applies
809
885
  * on exit.
810
886
  * - `"fork"` — fork from an existing (or paused) sandbox; a new sandbox is
811
- * created and owned by this session.
887
+ * created and owned by this session. `options` is an optional per-call
888
+ * override merged on top of the provider's static defaults.
812
889
  * - `"from-snapshot"` — restore a fresh sandbox from a previously captured
813
890
  * {@link SandboxSnapshot}. The new sandbox is owned by this session.
891
+ * `options` is an optional per-call override merged on top of the
892
+ * provider's static defaults.
814
893
  * - `"inherit"` — use a sandbox owned by someone else (e.g. a parent agent).
815
894
  * The session will **not** manage its lifecycle on exit.
816
895
  */
@@ -823,9 +902,11 @@ type SandboxInit = {
823
902
  } | {
824
903
  mode: "fork";
825
904
  sandboxId: string;
905
+ options?: SandboxCreateOptions;
826
906
  } | {
827
907
  mode: "from-snapshot";
828
908
  snapshot: SandboxSnapshot;
909
+ options?: SandboxCreateOptions;
829
910
  } | {
830
911
  mode: "inherit";
831
912
  sandboxId: string;
@@ -852,19 +933,20 @@ type SandboxShutdown = "destroy" | "pause" | "keep" | "snapshot";
852
933
  */
853
934
  type SubagentSandboxShutdown = SandboxShutdown | "pause-until-parent-close" | "keep-until-parent-close";
854
935
 
936
+ /**
937
+ * Subset of {@link ChildWorkflowOptions} that callers may override when a
938
+ * subagent is invoked. `workflowId`, `taskQueue`, and `args` are managed by
939
+ * the subagent handler itself and therefore cannot be set here.
940
+ *
941
+ * Configuring `workflowRunTimeout` (or `workflowExecutionTimeout`) is strongly
942
+ * recommended: it is the only reliable way to guarantee that a child workflow
943
+ * which fails during initialization or repeatedly fails workflow tasks will
944
+ * eventually be terminated, allowing the parent's `Subagent` tool call to fail
945
+ * deterministically instead of hanging forever waiting for a result.
946
+ */
947
+ type SubagentChildWorkflowOptions = Omit<ChildWorkflowOptions, "workflowId" | "taskQueue" | "args">;
855
948
  /** ToolHandlerResponse with threadId required (subagents must always surface their thread) */
856
- type SubagentHandlerResponse<TResult = null, TToolResponse = JsonValue> = ToolHandlerResponse<TResult, TToolResponse> & {
857
- threadId: string;
858
- sandboxId?: string;
859
- /** Snapshot captured on session exit when `sandboxShutdown === "snapshot"`. */
860
- snapshot?: SandboxSnapshot;
861
- /**
862
- * Snapshot captured immediately after the sandbox was seeded (before the
863
- * first agent turn) when `continuation === "snapshot"`. Only set on the
864
- * first call that actually created the sandbox.
865
- */
866
- baseSnapshot?: SandboxSnapshot;
867
- };
949
+ type SubagentHandlerResponse<TResult = null, TToolResponse = JsonValue> = ToolHandlerResponse<TResult, TToolResponse>;
868
950
  /**
869
951
  * Raw workflow input fields passed from parent to child workflow.
870
952
  * `defineSubagentWorkflow` maps this into `SubagentSessionInput`.
@@ -935,6 +1017,24 @@ interface SubagentConfig<TResult extends z.ZodType = z.ZodType> {
935
1017
  workflow: SubagentWorkflow<TResult>;
936
1018
  /** Optional task queue - defaults to parent's queue if not specified */
937
1019
  taskQueue?: string;
1020
+ /**
1021
+ * Optional child workflow options forwarded to `executeChild` when the
1022
+ * subagent is spawned. Use this to configure timeouts, retry policies, or
1023
+ * parent-close behavior for the child workflow.
1024
+ *
1025
+ * **Recommended:** configure a `workflowRunTimeout` (or
1026
+ * `workflowExecutionTimeout`) so that a child workflow that fails to
1027
+ * initialize — or repeatedly fails workflow tasks without ever reaching a
1028
+ * terminal state — is eventually terminated by the Temporal server. Without
1029
+ * such a timeout, the parent's `Subagent` tool call can hang indefinitely
1030
+ * waiting for the child to finish. When Temporal terminates the child, the
1031
+ * tool call fails with a structured `ChildWorkflowFailure` that the router's
1032
+ * failure hooks can handle just like any other tool error.
1033
+ *
1034
+ * `workflowId`, `taskQueue`, and `args` are managed by the subagent handler
1035
+ * and cannot be overridden here.
1036
+ */
1037
+ workflowOptions?: SubagentChildWorkflowOptions;
938
1038
  /** Optional Zod schema to validate the child workflow's result. If omitted, result is passed through as-is. */
939
1039
  resultSchema?: TResult;
940
1040
  /** Optional context passed to the subagent — a static object or a function evaluated at invocation time */
@@ -1026,8 +1126,26 @@ interface SubagentSessionInput {
1026
1126
  sandbox?: SandboxInit;
1027
1127
  /** Sandbox shutdown policy (default: "destroy") */
1028
1128
  sandboxShutdown?: SubagentSandboxShutdown;
1029
- /** Called by the session as soon as the sandbox is created, before the agent loop starts. */
1030
- onSandboxReady?: (sandboxId: string) => void;
1129
+ /**
1130
+ * Called by the session as soon as the sandbox is created, before the
1131
+ * agent loop starts. `baseSnapshot` is populated only when the session
1132
+ * captured a seed snapshot (fresh creation + `sandboxShutdown === "snapshot"`).
1133
+ */
1134
+ onSandboxReady?: (args: {
1135
+ sandboxId: string;
1136
+ baseSnapshot?: SandboxSnapshot;
1137
+ }) => void;
1138
+ /**
1139
+ * Called by the session right before `runSession` returns. Installed by
1140
+ * `defineSubagentWorkflow` to capture sandbox outputs and auto-forward
1141
+ * them to the subagent's final result so user code never has to thread
1142
+ * `sandboxId` / `snapshot` manually.
1143
+ */
1144
+ onSessionExit?: (result: {
1145
+ sandboxId?: string;
1146
+ snapshot?: SandboxSnapshot;
1147
+ threadId: string;
1148
+ }) => void;
1031
1149
  }
1032
1150
 
1033
1151
  /**
@@ -1100,6 +1218,13 @@ interface ModelInvokerConfig {
1100
1218
  agentName: string;
1101
1219
  state: BaseAgentState;
1102
1220
  metadata?: Record<string, unknown>;
1221
+ /**
1222
+ * The id the assistant message produced by this call will be stored
1223
+ * under. Invokers truncate the thread from this id on entry so that
1224
+ * rewind retries and Temporal workflow resets restore the pre-call
1225
+ * state before re-invoking the LLM. See {@link RunAgentConfig}.
1226
+ */
1227
+ assistantMessageId: string;
1103
1228
  }
1104
1229
  /**
1105
1230
  * Generic model invocation contract.
@@ -1131,8 +1256,39 @@ interface ThreadOps<TContent = string> {
1131
1256
  appendAgentMessage(threadId: string, id: string, message: unknown, threadKey?: string): Promise<void>;
1132
1257
  /** Append a system message to the thread */
1133
1258
  appendSystemMessage(threadId: string, id: string, content: unknown, threadKey?: string): Promise<void>;
1134
- /** Copy all messages from sourceThreadId into a new thread at targetThreadId */
1259
+ /**
1260
+ * Copy all messages AND the persisted state slice (tasks + custom
1261
+ * state) from `sourceThreadId` into a new thread at `targetThreadId`.
1262
+ * Adapters that have `onForkPrepareThread` and/or `onForkTransform`
1263
+ * hooks configured apply them once to the new thread's messages
1264
+ * before returning.
1265
+ */
1135
1266
  forkThread(sourceThreadId: string, targetThreadId: string, threadKey?: string): Promise<void>;
1267
+ /**
1268
+ * Truncate the thread starting at `messageId`: that message and every
1269
+ * message after it are removed. If `messageId` is not present the call
1270
+ * is a no-op.
1271
+ *
1272
+ * The `runAgent` activity invokes this on entry with the pre-generated
1273
+ * `assistantMessageId`. On the happy path the id is not yet in the
1274
+ * thread and the call is a no-op. On a rewind retry (same assistant
1275
+ * id reused) or a Temporal workflow reset-to-this-activity the id is
1276
+ * present, so the bad assistant + any tool results it produced are
1277
+ * wiped and the call is then replayable.
1278
+ */
1279
+ truncateThread(threadId: string, messageId: string, threadKey?: string): Promise<void>;
1280
+ /**
1281
+ * Load the persisted state slice (tasks + custom state) associated with
1282
+ * the thread, or `null` if none has been saved yet. Called on session
1283
+ * start for `continue`/`fork` threads to rehydrate {@link AgentStateManager}.
1284
+ */
1285
+ loadThreadState(threadId: string, threadKey?: string): Promise<PersistedThreadState | null>;
1286
+ /**
1287
+ * Overwrite the persisted state slice for the thread. Called once from
1288
+ * the session's `finally` block on every exit path so that "finish,
1289
+ * store, continue later" works regardless of exit reason.
1290
+ */
1291
+ saveThreadState(threadId: string, state: PersistedThreadState, threadKey?: string): Promise<void>;
1136
1292
  }
1137
1293
  /**
1138
1294
  * Composes an adapter prefix + workflow scope for activity naming.
@@ -1237,8 +1393,25 @@ interface SessionConfig<T extends ToolMap, M = unknown, TContent = string> {
1237
1393
  /**
1238
1394
  * Called as soon as the sandbox is created (or resumed/forked), before the
1239
1395
  * agent loop starts. Useful for signalling sandbox readiness to a parent.
1396
+ *
1397
+ * `baseSnapshot` is only populated when the sandbox was freshly created
1398
+ * this run and `sandboxShutdown === "snapshot"` — i.e. when the session
1399
+ * captured a seed snapshot intended for reuse.
1400
+ */
1401
+ onSandboxReady?: (args: {
1402
+ sandboxId: string;
1403
+ baseSnapshot?: SandboxSnapshot;
1404
+ }) => void;
1405
+ /**
1406
+ * Called right before `runSession` returns, with the session's sandbox
1407
+ * outputs. Useful for callers (e.g. `defineSubagentWorkflow`) that want to
1408
+ * forward these fields to their own return value without requiring user
1409
+ * code to manually thread them through.
1240
1410
  */
1241
- onSandboxReady?: (sandboxId: string) => void;
1411
+ onSessionExit?: (result: {
1412
+ sandboxId?: string;
1413
+ snapshot?: SandboxSnapshot;
1414
+ }) => void;
1242
1415
  virtualFsOps?: VirtualFsOps;
1243
1416
  /**
1244
1417
  * Virtual filesystem configuration (optional — independent of sandbox).
@@ -1281,4 +1454,4 @@ interface ZeitlichSession<M = unknown, HasSandbox extends boolean = boolean> {
1281
1454
  }): Promise<SessionResult<M, T, HasSandbox>>;
1282
1455
  }
1283
1456
 
1284
- export { type SessionEndHook as $, type AgentResponse as A, type BaseAgentState as B, type PostToolUseFailureHookResult as C, type PostToolUseHook as D, type PostToolUseHookContext as E, type FileEntryMetadata as F, type PreHumanMessageAppendHook as G, type Hooks as H, type InferToolResults as I, type JsonValue as J, type PreHumanMessageAppendHookContext as K, type PreToolUseHook as L, type ModelInvokerConfig as M, type PreToolUseHookContext as N, type PreToolUseHookResult as O, type PrefixedThreadOps as P, type ProcessToolCallsContext as Q, type RouterContext as R, type ScopedPrefix as S, type ThreadOps as T, type RawToolCall as U, type VirtualFsContext as V, type RunAgentActivity as W, type SandboxInit as X, type SandboxShutdown as Y, type SerializableToolDefinition as Z, type SessionConfig as _, type ModelInvoker as a, type SessionEndHookContext as a0, type SessionExitReason as a1, type SessionResult as a2, type SessionStartHook as a3, type SessionStartHookContext as a4, type SubagentConfig as a5, type SubagentDefinition as a6, type SubagentFnResult as a7, type SubagentHandlerResponse as a8, type SubagentHooks as a9, isTerminalStatus as aA, type ToolRouterOptions as aB, type SubagentSandboxConfig as aa, type SubagentSandboxShutdown as ab, type SubagentSessionInput as ac, type SubagentWorkflow as ad, type SubagentWorkflowInput as ae, type TaskStatus as af, type ThreadInit as ag, type TokenUsage as ah, type ToolArgs as ai, type ToolCallResult as aj, type ToolCallResultUnion as ak, type ToolDefinition as al, type ToolHandler as am, type ToolHooks as an, type ToolMap as ao, type ToolNames as ap, type ToolResult as aq, type ToolRouter as ar, type ToolRouterHooks as as, type ToolWithHandler as at, VirtualFileSystem as au, type VirtualFileTree as av, type VirtualFsOps as aw, type VirtualFsState as ax, type WorkflowTask as ay, type ZeitlichSession as az, type ToolHandlerResponse as b, type ActivityToolHandler as c, type ToolResultConfig as d, type RunAgentConfig as e, type SkillProvider as f, type SkillMetadata as g, type Skill as h, type FileResolver as i, type TreeMutation as j, type PrefixedVirtualFsOps as k, type AgentConfig as l, type AgentFile as m, type AgentState as n, type AgentStateManager as o, type AgentStatus as p, type AppendToolResultFn as q, type FileEntry as r, type JsonPrimitive as s, type JsonSerializable as t, type ParsedToolCall as u, type ParsedToolCallUnion as v, type PostHumanMessageAppendHook as w, type PostHumanMessageAppendHookContext as x, type PostToolUseFailureHook as y, type PostToolUseFailureHookContext as z };
1457
+ export { type SandboxShutdown as $, type AgentResponse as A, type BaseAgentState as B, type PostToolUseFailureHookContext as C, type PostToolUseFailureHookResult as D, type PostToolUseHook as E, type FileEntryMetadata as F, type PostToolUseHookContext as G, type Hooks as H, type InferToolResults as I, type JsonValue as J, type PreHumanMessageAppendHook as K, type PreHumanMessageAppendHookContext as L, type ModelInvokerConfig as M, type PreToolUseHook as N, type PreToolUseHookContext as O, type PersistedThreadState as P, type PreToolUseHookResult as Q, type RouterContext as R, type ScopedPrefix as S, type ThreadOps as T, type ProcessToolCallsContext as U, type VirtualFsContext as V, type ProcessToolCallsResult as W, type RawToolCall as X, type RewindSignal as Y, type RunAgentActivity as Z, type SandboxInit as _, type ModelInvoker as a, type SerializableToolDefinition as a0, type SessionConfig as a1, type SessionEndHook as a2, type SessionEndHookContext as a3, type SessionExitReason as a4, type SessionResult as a5, type SessionStartHook as a6, type SessionStartHookContext as a7, type SubagentChildWorkflowOptions as a8, type SubagentConfig as a9, type VirtualFsOps as aA, type VirtualFsState as aB, type WorkflowTask as aC, type ZeitlichSession as aD, isTerminalStatus as aE, type ToolRouterOptions as aF, type SubagentDefinition as aa, type SubagentFnResult as ab, type SubagentHandlerResponse as ac, type SubagentHooks as ad, type SubagentSandboxConfig as ae, type SubagentSandboxShutdown as af, type SubagentSessionInput as ag, type SubagentWorkflow as ah, type SubagentWorkflowInput as ai, type TaskStatus as aj, type ThreadInit as ak, type TokenUsage as al, type ToolArgs as am, type ToolCallResult as an, type ToolCallResultUnion as ao, type ToolDefinition as ap, type ToolHandler as aq, type ToolHooks as ar, type ToolMap as as, type ToolNames as at, type ToolResult as au, type ToolRouter as av, type ToolRouterHooks as aw, type ToolWithHandler as ax, VirtualFileSystem as ay, type VirtualFileTree as az, type PrefixedThreadOps as b, type ToolHandlerResponse as c, type ActivityToolHandler as d, type ToolResultConfig as e, type RunAgentConfig as f, type SkillProvider as g, type SkillMetadata as h, type Skill as i, type FileResolver as j, type TreeMutation as k, type PrefixedVirtualFsOps as l, type AgentConfig as m, type AgentFile as n, type AgentState as o, type AgentStateManager as p, type AgentStatus as q, type AppendToolResultFn as r, type FileEntry as s, type JsonPrimitive as t, type JsonSerializable as u, type ParsedToolCall as v, type ParsedToolCallUnion as w, type PostHumanMessageAppendHook as x, type PostHumanMessageAppendHookContext as y, type PostToolUseFailureHook as z };
@@ -1,4 +1,4 @@
1
- import { a as SandboxFileSystem, F as FileStat, D as DirentEntry, S as Sandbox, d as SandboxCreateOptions } from './types-tQL9njTu.js';
1
+ import { a as SandboxFileSystem, F as FileStat, D as DirentEntry, S as Sandbox, d as SandboxCreateOptions } from './types-yx0LzPGn.js';
2
2
  import { BedrockAgentCoreClient, BedrockAgentCoreClientConfig } from '@aws-sdk/client-bedrock-agentcore';
3
3
 
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import Redis from 'ioredis';
2
- import { J as JsonValue } from './types-CPKDl-y_.js';
2
+ import { P as PersistedThreadState, J as JsonValue } from './types-Dt8-HBBT.js';
3
3
 
4
4
  interface ThreadManagerConfig<T> {
5
5
  redis: Redis;
@@ -34,8 +34,50 @@ interface BaseThreadManager<T> {
34
34
  * forks — each call creates an independent copy.
35
35
  */
36
36
  fork(newThreadId: string): Promise<BaseThreadManager<T>>;
37
+ /**
38
+ * Atomically replace the entire contents of the thread with `messages`.
39
+ * The existing list is cleared, the new messages are appended in order,
40
+ * and dedup markers from prior appends are cleared so future idempotent
41
+ * appends with ids that were removed aren't silently skipped.
42
+ *
43
+ * Requires the thread manager to be configured with `idOf`.
44
+ */
45
+ replaceAll(messages: T[]): Promise<void>;
37
46
  /** Delete the thread */
38
47
  delete(): Promise<void>;
48
+ /** Get the number of stored messages currently in the thread */
49
+ length(): Promise<number>;
50
+ /**
51
+ * Truncate the thread starting at the message with id `messageId`.
52
+ * That message and every message after it are removed. If `messageId`
53
+ * is not present in the thread this is a no-op — useful as the
54
+ * "truncate on entry" step of the `runAgent` activity, which becomes a
55
+ * no-op on the first attempt and a cleanup on Temporal workflow reset
56
+ * or in-workflow rewind retries.
57
+ *
58
+ * Dedup markers for removed single-message appends are also cleared so
59
+ * that appending the same id again (e.g. the same assistant message id
60
+ * on a rewind retry) is not silently skipped.
61
+ *
62
+ * Requires the thread manager to be configured with `idOf`.
63
+ */
64
+ truncateFromId(messageId: string): Promise<void>;
65
+ /**
66
+ * Load the persisted state slice associated with this thread, or
67
+ * `null` if none has been saved yet. Safe to call on any thread —
68
+ * treats a missing slice as a non-error.
69
+ */
70
+ loadState(): Promise<PersistedThreadState | null>;
71
+ /**
72
+ * Overwrite the persisted state slice for this thread. The thread
73
+ * itself must already exist (same TTL as the message list).
74
+ *
75
+ * Note: {@link BaseThreadManager.fork} already copies the slice to
76
+ * the new thread, so there's no separate `forkState` method.
77
+ */
78
+ saveState(state: PersistedThreadState): Promise<void>;
79
+ /** Delete just the persisted state slice, leaving messages intact. */
80
+ deleteState(): Promise<void>;
39
81
  }
40
82
  /**
41
83
  * Shared contract for provider-specific thread managers.
@@ -63,6 +105,21 @@ interface ThreadManagerHooks<TStored, TPrepared = TStored> {
63
105
  onPrepareMessage?: (message: TStored, index: number, thread: readonly TStored[]) => TStored;
64
106
  /** Called for each SDK-native message after all processing, right before the payload is returned */
65
107
  onPreparedMessage?: (message: TPrepared, index: number, messages: readonly TPrepared[]) => TPrepared;
108
+ /**
109
+ * One-shot list-level pre-pass applied once when a thread is forked with
110
+ * `transform: true`. Runs before {@link onForkTransform}. May filter,
111
+ * compact, prepend, or otherwise rewrite the whole forked thread — so the
112
+ * returned length need not match the input length. Async, so implementations
113
+ * may call an LLM or other I/O.
114
+ */
115
+ onForkPrepareThread?: (messages: readonly TStored[]) => TStored[] | Promise<TStored[]>;
116
+ /**
117
+ * Per-message final pass applied once when a thread is forked with
118
+ * `transform: true`. Runs after {@link onForkPrepareThread}. Pure 1:1 map —
119
+ * must return a value for every input message; length cannot change. Same
120
+ * shape as {@link onPreparedMessage}.
121
+ */
122
+ onForkTransform?: (message: TStored, index: number, messages: readonly TStored[]) => TStored;
66
123
  }
67
124
  interface ProviderThreadManager<TStored, TContent = string, TToolContent = JsonValue, TSystemContent = string> extends BaseThreadManager<TStored> {
68
125
  appendUserMessage(id: string, content: TContent): Promise<void>;