zeitlich 0.2.2 → 0.2.3

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 (45) hide show
  1. package/README.md +34 -31
  2. package/dist/index.cjs +305 -361
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +24 -43
  5. package/dist/index.d.ts +24 -43
  6. package/dist/index.js +277 -336
  7. package/dist/index.js.map +1 -1
  8. package/dist/{workflow-BQf5EfNN.d.cts → workflow-D-2vp4Pq.d.cts} +265 -241
  9. package/dist/{workflow-BQf5EfNN.d.ts → workflow-D-2vp4Pq.d.ts} +265 -241
  10. package/dist/workflow.cjs +206 -253
  11. package/dist/workflow.cjs.map +1 -1
  12. package/dist/workflow.d.cts +2 -3
  13. package/dist/workflow.d.ts +2 -3
  14. package/dist/workflow.js +182 -231
  15. package/dist/workflow.js.map +1 -1
  16. package/package.json +3 -2
  17. package/src/activities.ts +1 -14
  18. package/src/index.ts +14 -11
  19. package/src/lib/session.ts +56 -99
  20. package/src/lib/thread-manager.ts +45 -37
  21. package/src/lib/tool-router.ts +143 -103
  22. package/src/lib/types.ts +32 -25
  23. package/src/tools/ask-user-question/handler.ts +5 -5
  24. package/src/tools/ask-user-question/tool.ts +3 -2
  25. package/src/tools/bash/bash.test.ts +12 -12
  26. package/src/tools/bash/handler.ts +5 -5
  27. package/src/tools/bash/tool.ts +3 -2
  28. package/src/tools/edit/handler.ts +78 -123
  29. package/src/tools/edit/tool.ts +3 -2
  30. package/src/tools/glob/handler.ts +17 -48
  31. package/src/tools/glob/tool.ts +3 -2
  32. package/src/tools/grep/tool.ts +3 -2
  33. package/src/tools/{read → read-file}/tool.ts +3 -2
  34. package/src/tools/task/handler.ts +2 -2
  35. package/src/tools/task/tool.ts +2 -9
  36. package/src/tools/task-create/handler.ts +5 -11
  37. package/src/tools/task-create/tool.ts +3 -2
  38. package/src/tools/task-get/handler.ts +5 -10
  39. package/src/tools/task-get/tool.ts +3 -2
  40. package/src/tools/task-list/handler.ts +5 -10
  41. package/src/tools/task-list/tool.ts +3 -2
  42. package/src/tools/task-update/handler.ts +5 -12
  43. package/src/tools/task-update/tool.ts +3 -2
  44. package/src/tools/{write → write-file}/tool.ts +5 -6
  45. package/src/workflow.ts +23 -19
@@ -1,34 +1,37 @@
1
+ import { Workflow, proxyActivities } from '@temporalio/workflow';
1
2
  import Redis from 'ioredis';
2
3
  import { $InferMessageContent, MessageStructure, StoredMessage, MessageContent } from '@langchain/core/messages';
3
4
  import z, { z as z$1 } from 'zod';
4
5
  import * as _temporalio_common from '@temporalio/common';
5
- import { BashOptions } from 'just-bash';
6
- import { Workflow } from '@temporalio/workflow';
7
6
 
8
7
  /**
9
8
  * Content for a tool message response.
10
9
  * Can be a simple string or complex content parts (text, images, cache points, etc.)
11
10
  */
12
11
  type ToolMessageContent = $InferMessageContent<MessageStructure, "tool">;
13
- interface ThreadManagerConfig {
12
+ interface ThreadManagerConfig<T = StoredMessage> {
14
13
  redis: Redis;
15
14
  threadId: string;
16
15
  /** Thread key, defaults to 'messages' */
17
16
  key?: string;
17
+ /** Custom serializer, defaults to JSON.stringify */
18
+ serialize?: (message: T) => string;
19
+ /** Custom deserializer, defaults to JSON.parse */
20
+ deserialize?: (raw: string) => T;
18
21
  }
19
- interface ThreadManager {
20
- /** Append a system message to the thread */
21
- appendSystemMessage(content: string): Promise<void>;
22
+ /** Generic thread manager for any message type */
23
+ interface BaseThreadManager<T> {
22
24
  /** Initialize an empty thread */
23
25
  initialize(): Promise<void>;
24
26
  /** Load all messages from the thread */
25
- load(): Promise<StoredMessage[]>;
27
+ load(): Promise<T[]>;
26
28
  /** Append messages to the thread */
27
- append(messages: StoredMessage[]): Promise<void>;
29
+ append(messages: T[]): Promise<void>;
28
30
  /** Delete the thread */
29
31
  delete(): Promise<void>;
30
- /** Create a SystemMessage (returns StoredMessage for storage) */
31
- createSystemMessage(content: string): StoredMessage;
32
+ }
33
+ /** Thread manager with StoredMessage convenience helpers */
34
+ interface ThreadManager extends BaseThreadManager<StoredMessage> {
32
35
  /** Create a HumanMessage (returns StoredMessage for storage) */
33
36
  createHumanMessage(content: string | MessageContent): StoredMessage;
34
37
  /** Create an AIMessage with optional additional kwargs */
@@ -48,8 +51,11 @@ interface ThreadManager {
48
51
  }
49
52
  /**
50
53
  * Creates a thread manager for handling conversation state in Redis.
54
+ * Without generic args, returns a full ThreadManager with StoredMessage helpers.
55
+ * With a custom type T, returns a BaseThreadManager<T>.
51
56
  */
52
57
  declare function createThreadManager(config: ThreadManagerConfig): ThreadManager;
58
+ declare function createThreadManager<T>(config: ThreadManagerConfig<T>): BaseThreadManager<T>;
53
59
 
54
60
  /**
55
61
  * Creates a Task tool configured with the available subagents.
@@ -77,156 +83,14 @@ declare function createTaskTool<T extends SubagentConfig[]>(subagents: T): {
77
83
  }>;
78
84
  };
79
85
  /**
80
- * Infer the schema type for a task tool created with specific subagents
81
- */
82
- type TaskToolSchemaType<T extends SubagentConfig[]> = z.infer<ReturnType<typeof createTaskTool<T>>["schema"]>;
83
- /**
84
- * Generic task tool schema type (when subagent names are not known at compile time)
86
+ * Task tool args type (when subagent names are not known at compile time)
85
87
  */
86
- type GenericTaskToolSchemaType = {
88
+ type TaskArgs = {
87
89
  subagent: string;
88
90
  description: string;
89
91
  prompt: string;
90
92
  };
91
93
 
92
- /**
93
- * JSON primitive types that Temporal can serialize
94
- */
95
- type JsonPrimitive = string | number | boolean | null | undefined;
96
- /**
97
- * JSON-serializable value (recursive type for Temporal compatibility)
98
- */
99
- type JsonValue = JsonPrimitive | JsonValue[] | {
100
- [key: string]: JsonValue;
101
- };
102
- /**
103
- * Type constraint ensuring T only contains JSON-serializable values.
104
- * Use this for custom state to ensure Temporal workflow compatibility.
105
- *
106
- * Allows: primitives, arrays, plain objects, and JsonValue
107
- * Rejects: functions, symbols, undefined, class instances with methods
108
- */
109
- type JsonSerializable<T> = {
110
- [K in keyof T]: T[K] extends JsonValue ? T[K] : T[K] extends JsonPrimitive ? T[K] : T[K] extends (infer U)[] ? U extends JsonValue ? T[K] : JsonSerializable<U>[] : T[K] extends object ? JsonSerializable<T[K]> : never;
111
- };
112
- /**
113
- * Full state type combining base state with custom state
114
- */
115
- type AgentState<TCustom extends JsonSerializable<TCustom>> = BaseAgentState & TCustom;
116
- /**
117
- * Agent state manager interface
118
- * Note: Temporal handlers must be set up in the workflow file due to
119
- * Temporal's workflow isolation requirements. This manager provides
120
- * the state and helpers needed for those handlers.
121
- */
122
- interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
123
- /** Get current status */
124
- getStatus(): AgentStatus;
125
- /** Check if agent is running */
126
- isRunning(): boolean;
127
- /** Check if agent is in terminal state */
128
- isTerminal(): boolean;
129
- /** Get current state version */
130
- getVersion(): number;
131
- /** Set status to RUNNING */
132
- run(): void;
133
- /** Set status to WAITING_FOR_INPUT */
134
- waitForInput(): void;
135
- /** Set status to COMPLETED */
136
- complete(): void;
137
- /** Set status to FAILED */
138
- fail(): void;
139
- /** Set status to CANCELLED */
140
- cancel(): void;
141
- /** Increment state version (call after state changes) */
142
- incrementVersion(): void;
143
- /** Increment turns (call after each turn) */
144
- incrementTurns(): void;
145
- /** Get current turns */
146
- getTurns(): number;
147
- /** Get a custom state value by key */
148
- get<K extends keyof TCustom>(key: K): TCustom[K];
149
- /** Set a custom state value by key */
150
- set<K extends keyof TCustom>(key: K, value: TCustom[K]): void;
151
- /** Get full state for query handler */
152
- getCurrentState(): AgentState<TCustom>;
153
- /** Check if should return from waitForStateChange */
154
- shouldReturnFromWait(lastKnownVersion: number): boolean;
155
- /** Get all tasks */
156
- getTasks(): WorkflowTask[];
157
- /** Get a task by ID */
158
- getTask(id: string): WorkflowTask | undefined;
159
- /** Add or update a task */
160
- setTask(task: WorkflowTask): void;
161
- /** Delete a task by ID */
162
- deleteTask(id: string): boolean;
163
- /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
164
- setTools(newTools: ToolDefinition[]): void;
165
- }
166
- declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState, [], string>;
167
- /**
168
- * Creates an agent state manager for tracking workflow state.
169
- *
170
- * @param initialState - Optional initial values for base and custom state
171
- * Base state defaults: status="RUNNING", version=0, turns=0, tasks=empty, fileTree=[]
172
- *
173
- * Note: Due to Temporal's workflow isolation, handlers must be set up
174
- * in the workflow file using defineQuery/defineUpdate and setHandler.
175
- * This manager provides the state and logic needed for those handlers.
176
- */
177
- declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>(initialState?: Partial<BaseAgentState> & TCustom): AgentStateManager<TCustom>;
178
- /**
179
- * Handler names used across agents
180
- */
181
- declare const AGENT_HANDLER_NAMES: {
182
- readonly getAgentState: "getAgentState";
183
- readonly waitForStateChange: "waitForStateChange";
184
- readonly addMessage: "addMessage";
185
- };
186
-
187
- declare const taskCreateTool: {
188
- name: "TaskCreate";
189
- description: string;
190
- schema: z.ZodObject<{
191
- subject: z.ZodString;
192
- description: z.ZodString;
193
- activeForm: z.ZodString;
194
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
195
- }, z.core.$strip>;
196
- };
197
- type TaskCreateToolSchemaType = z.infer<typeof taskCreateTool.schema>;
198
-
199
- /**
200
- * Creates a TaskCreate handler that adds tasks to the workflow state.
201
- *
202
- * @param stateManager - State manager containing tasks state
203
- * @param idGenerator - Function to generate unique task IDs (e.g., uuid4 from Temporal)
204
- * @returns A tool handler function
205
- *
206
- * @example
207
- * const handler = createTaskCreateHandler(stateManager, uuid4);
208
- */
209
- declare function createTaskCreateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskCreateToolSchemaType) => ToolHandlerResponse<WorkflowTask>;
210
-
211
- declare const bashTool: {
212
- name: "Bash";
213
- description: string;
214
- schema: z.ZodObject<{
215
- command: z.ZodString;
216
- }, z.core.$strip>;
217
- strict: boolean;
218
- };
219
- type bashToolSchemaType = z.infer<typeof bashTool.schema>;
220
-
221
- type BashExecOut = {
222
- exitCode: number;
223
- stderr: string;
224
- stdout: string;
225
- };
226
- /** BashOptions with `fs` required */
227
- type BashToolOptions = Required<Pick<BashOptions, "fs">> & Omit<BashOptions, "fs">;
228
- declare const handleBashTool: (bashOptions: BashToolOptions) => ActivityToolHandler<bashToolSchemaType, BashExecOut | null>;
229
-
230
94
  /**
231
95
  * A tool definition with a name, description, and Zod schema for arguments.
232
96
  * Does not include a handler - use ToolWithHandler for tools with handlers.
@@ -249,19 +113,27 @@ interface ToolWithHandler<TName extends string = string, TSchema extends z$1.Zod
249
113
  handler: ToolHandler<z$1.infer<TSchema>, TResult, TContext>;
250
114
  strict?: boolean;
251
115
  max_uses?: number;
116
+ /** Whether this tool is available to the agent (default: true). Disabled tools are excluded from definitions and rejected at parse time. */
117
+ enabled?: boolean;
252
118
  /** Per-tool lifecycle hooks (run in addition to global hooks) */
253
119
  hooks?: ToolHooks<z$1.infer<TSchema>, TResult>;
254
120
  }
255
121
  /**
256
122
  * A map of tool keys to tool definitions with handlers.
123
+ *
124
+ * Handler uses `any` intentionally — this is a type-system boundary where heterogeneous
125
+ * tool types are stored together. Type safety for individual tools is enforced by
126
+ * `defineTool()` at the definition site and generic inference utilities like
127
+ * `InferToolResults<T>` at the consumption site.
257
128
  */
258
129
  type ToolMap = Record<string, {
259
130
  name: string;
260
131
  description: string;
261
132
  schema: z$1.ZodType;
262
- handler: (args: any, context: any) => ToolHandlerResponse<any> | Promise<ToolHandlerResponse<any>>;
133
+ handler: ToolHandler<any, any, any>;
263
134
  strict?: boolean;
264
135
  max_uses?: number;
136
+ enabled?: boolean;
265
137
  hooks?: ToolHooks<any, any>;
266
138
  }>;
267
139
  /**
@@ -297,29 +169,29 @@ type AppendToolResultFn = (config: ToolResultConfig) => Promise<void>;
297
169
  /**
298
170
  * The response from a tool handler.
299
171
  * Contains the content for the tool message and the result to return from processToolCalls.
172
+ *
173
+ * Tools that don't return additional data should use `data: null` (TResult defaults to null).
174
+ * Tools that may fail to produce data should type TResult as `SomeType | null`.
300
175
  */
301
- interface ToolHandlerResponse<TResult> {
176
+ interface ToolHandlerResponse<TResult = null> {
302
177
  /** Content sent back to the LLM as the tool call response */
303
178
  toolResponse: ToolMessageContent;
304
179
  /** Data returned to the workflow and hooks for further processing */
305
- data: TResult | null;
180
+ data: TResult;
181
+ /**
182
+ * When true, the tool result has already been appended to the thread
183
+ * by the handler itself (e.g. via `withAutoAppend`), so the router
184
+ * will skip the `appendToolResult` call. This avoids sending large
185
+ * payloads through Temporal's activity payload limit.
186
+ */
187
+ resultAppended?: boolean;
306
188
  }
307
189
  /**
308
190
  * Context passed to tool handlers for additional data beyond tool args.
309
191
  * Use this to pass workflow state like file trees, user context, etc.
192
+ * Generic so callers can type the context shape, e.g. ToolHandlerContext<ControlTestFsParams>.
310
193
  */
311
- interface ToolHandlerContext {
312
- /** Additional context data - define your own shape */
313
- [key: string]: unknown;
314
- }
315
- interface BuildInToolDefinitions {
316
- [bashTool.name]: typeof bashTool & {
317
- handler: ReturnType<typeof handleBashTool>;
318
- };
319
- [taskCreateTool.name]: typeof taskCreateTool & {
320
- handler: ReturnType<typeof createTaskCreateHandler>;
321
- };
322
- }
194
+ type ToolHandlerContext<T = Record<string, unknown>> = T;
323
195
  /**
324
196
  * A handler function for a specific tool.
325
197
  * Receives the parsed args and context, returns a response with content and result.
@@ -335,7 +207,7 @@ type ToolHandler<TArgs, TResult, TContext = ToolHandlerContext> = (args: TArgs,
335
207
  * ```typescript
336
208
  * // Filesystem handler with context
337
209
  * const readHandler: ActivityToolHandler<
338
- * ReadToolSchemaType,
210
+ * FileReadArgs,
339
211
  * ReadResult,
340
212
  * { scopedNodes: FileNode[]; provider: FileSystemProvider }
341
213
  * > = async (args, context) => {
@@ -362,14 +234,12 @@ type ToolResult<T extends ToolMap, TName extends ToolNames<T>> = Extract<T[keyof
362
234
  interface ToolCallResult<TName extends string = string, TResult = unknown> {
363
235
  toolCallId: string;
364
236
  name: TName;
365
- data: TResult | null;
237
+ data: TResult;
366
238
  }
367
239
  /**
368
240
  * Options for creating a tool router.
369
241
  */
370
242
  interface ToolRouterOptions<T extends ToolMap> {
371
- /** File tree for the agent */
372
- fileTree: string;
373
243
  /** Map of tools with their handlers */
374
244
  tools: T;
375
245
  /** Thread ID for appending tool results */
@@ -382,10 +252,6 @@ interface ToolRouterOptions<T extends ToolMap> {
382
252
  hooks?: Hooks<T, ToolCallResultUnion<InferToolResults<T>>>;
383
253
  /** Subagent configurations */
384
254
  subagents?: SubagentConfig[];
385
- /** Build in tools - accepts raw handlers or proxied activities */
386
- buildInTools?: {
387
- [K in keyof BuildInToolDefinitions]?: BuildInToolDefinitions[K]["handler"];
388
- };
389
255
  }
390
256
  /**
391
257
  * Infer result types from a tool map based on handler return types.
@@ -486,6 +352,34 @@ interface ToolRouter<T extends ToolMap> {
486
352
  * ```
487
353
  */
488
354
  declare function createToolRouter<T extends ToolMap>(options: ToolRouterOptions<T>): ToolRouter<T>;
355
+ /**
356
+ * Wraps a tool handler to automatically append its result directly to the
357
+ * thread and sets `resultAppended: true` on the response.
358
+ *
359
+ * Use this for tools whose responses may exceed Temporal's activity payload
360
+ * limit. The wrapper appends to the thread inside the activity (where Redis
361
+ * is available), then replaces `toolResponse` with an empty string so the
362
+ * large payload never travels through the Temporal workflow boundary.
363
+ *
364
+ * @param getThread - Factory that returns a thread manager for the given threadId
365
+ * @param handler - The original tool handler
366
+ * @returns A wrapped handler that auto-appends and flags the response
367
+ *
368
+ * @example
369
+ * ```typescript
370
+ * import { withAutoAppend } from '@bead-ai/zeitlich/workflow';
371
+ * import { createThreadManager } from '@bead-ai/zeitlich';
372
+ *
373
+ * const handler = withAutoAppend(
374
+ * (threadId) => createThreadManager({ redis, threadId }),
375
+ * async (args, ctx) => ({
376
+ * toolResponse: JSON.stringify(largeResult), // appended directly to Redis
377
+ * data: { summary: "..." }, // small data for workflow
378
+ * }),
379
+ * );
380
+ * ```
381
+ */
382
+ declare function withAutoAppend<TArgs, TResult, TContext extends ToolHandlerContext = ToolHandlerContext>(threadHandler: (config: ToolResultConfig) => Promise<void>, handler: ActivityToolHandler<TArgs, TResult, TContext>): ActivityToolHandler<TArgs, TResult, TContext>;
489
383
  /**
490
384
  * Identity function that creates a generic inference context for a tool definition.
491
385
  * TypeScript infers TResult from the handler and flows it to hooks automatically.
@@ -542,13 +436,13 @@ declare function defineSubagent<TResult extends z$1.ZodType = z$1.ZodType, TCont
542
436
  context: TContext;
543
437
  }) => Promise<any>);
544
438
  context: TContext;
545
- hooks?: SubagentHooks<GenericTaskToolSchemaType, z$1.infer<TResult>>;
439
+ hooks?: SubagentHooks<TaskArgs, z$1.infer<TResult>>;
546
440
  }): SubagentConfig<TResult>;
547
441
  declare function defineSubagent<TResult extends z$1.ZodType = z$1.ZodType>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow"> & {
548
442
  workflow: string | ((input: {
549
443
  prompt: string;
550
444
  }) => Promise<any>);
551
- hooks?: SubagentHooks<GenericTaskToolSchemaType, z$1.infer<TResult>>;
445
+ hooks?: SubagentHooks<TaskArgs, z$1.infer<TResult>>;
552
446
  }): SubagentConfig<TResult>;
553
447
  /**
554
448
  * Utility to check if there were no tool calls besides a specific one
@@ -568,6 +462,7 @@ interface BaseAgentState {
568
462
  version: number;
569
463
  turns: number;
570
464
  tasks: Map<string, WorkflowTask>;
465
+ systemPrompt: string;
571
466
  }
572
467
  /**
573
468
  * File representation for agent workflows
@@ -587,8 +482,8 @@ interface AgentFile {
587
482
  /**
588
483
  * Agent response from LLM invocation
589
484
  */
590
- interface AgentResponse {
591
- message: StoredMessage;
485
+ interface AgentResponse<M = StoredMessage> {
486
+ message: M;
592
487
  stopReason: string | null;
593
488
  usage?: {
594
489
  input_tokens?: number;
@@ -596,17 +491,33 @@ interface AgentResponse {
596
491
  total_tokens?: number;
597
492
  };
598
493
  }
494
+ /**
495
+ * Thread operations required by a session.
496
+ * Consumers provide these — typically by wrapping Temporal activities.
497
+ * Use `proxyDefaultThreadOps()` for the default StoredMessage implementation.
498
+ */
499
+ interface ThreadOps<M = StoredMessage> {
500
+ /** Initialize an empty thread */
501
+ initializeThread(threadId: string): Promise<void>;
502
+ /** Append a human message to the thread */
503
+ appendHumanMessage(threadId: string, content: string | MessageContent): Promise<void>;
504
+ /** Append a tool result to the thread */
505
+ appendToolResult(config: ToolResultConfig): Promise<void>;
506
+ /** Extract raw tool calls from a message */
507
+ parseToolCalls(message: M): Promise<RawToolCall[]>;
508
+ }
599
509
  /**
600
510
  * Configuration for a Zeitlich agent session
601
511
  */
602
- interface ZeitlichAgentConfig<T extends ToolMap> {
603
- buildFileTree?: () => Promise<string>;
512
+ interface ZeitlichAgentConfig<T extends ToolMap, M = StoredMessage> {
604
513
  threadId: string;
605
514
  agentName: string;
606
515
  metadata?: Record<string, unknown>;
607
516
  maxTurns?: number;
608
517
  /** Workflow-specific runAgent activity (with tools pre-bound) */
609
- runAgent: RunAgentActivity;
518
+ runAgent: RunAgentActivity<M>;
519
+ /** Thread operations (initialize, append messages, parse tool calls) */
520
+ threadOps: ThreadOps<M>;
610
521
  /** Tool router for processing tool calls (optional if agent has no tools) */
611
522
  tools?: T;
612
523
  /** Subagent configurations */
@@ -615,27 +526,11 @@ interface ZeitlichAgentConfig<T extends ToolMap> {
615
526
  hooks?: Hooks<T, ToolCallResultUnion<InferToolResults<T>>>;
616
527
  /** Whether to process tools in parallel */
617
528
  processToolsInParallel?: boolean;
618
- /**
619
- * Base system prompt (e.g., Auditron identity).
620
- * Can be a static string or async function.
621
- */
622
- baseSystemPrompt: string | (() => string | Promise<string>);
623
- /**
624
- * Agent-specific instructions prompt.
625
- * Can be a static string or async function.
626
- */
627
- instructionsPrompt: string | (() => string | Promise<string>);
628
529
  /**
629
530
  * Build context message content from agent-specific context.
630
531
  * Returns MessageContent array for the initial HumanMessage.
631
532
  */
632
533
  buildContextMessage: () => MessageContent | Promise<MessageContent>;
633
- /**
634
- * Build in tools - accepts raw handlers or proxied activities
635
- */
636
- buildInTools?: {
637
- [K in keyof BuildInToolDefinitions]?: BuildInToolDefinitions[K]["handler"];
638
- };
639
534
  }
640
535
  /**
641
536
  * A JSON-serializable tool definition for state storage.
@@ -660,13 +555,15 @@ interface RunAgentConfig {
660
555
  /**
661
556
  * Type signature for workflow-specific runAgent activity
662
557
  */
663
- type RunAgentActivity = (config: RunAgentConfig) => Promise<AgentResponse>;
558
+ type RunAgentActivity<M = StoredMessage> = (config: RunAgentConfig) => Promise<AgentResponse<M>>;
664
559
  /**
665
560
  * Configuration for appending a tool result
666
561
  */
667
562
  interface ToolResultConfig {
668
563
  threadId: string;
669
564
  toolCallId: string;
565
+ /** The name of the tool that produced this result */
566
+ toolName: string;
670
567
  /** Content for the tool message (string or complex content parts) */
671
568
  content: ToolMessageContent;
672
569
  }
@@ -873,7 +770,7 @@ interface ToolHooks<TArgs = unknown, TResult = unknown> {
873
770
  /** Called after this tool executes successfully */
874
771
  onPostToolUse?: (ctx: {
875
772
  args: TArgs;
876
- result: TResult | null;
773
+ result: TResult;
877
774
  threadId: string;
878
775
  turn: number;
879
776
  durationMs: number;
@@ -906,10 +803,105 @@ interface Hooks<T extends ToolMap, TResult = unknown> {
906
803
  */
907
804
  declare function isTerminalStatus(status: AgentStatus): boolean;
908
805
 
909
- interface ZeitlichSession {
806
+ /**
807
+ * JSON primitive types that Temporal can serialize
808
+ */
809
+ type JsonPrimitive = string | number | boolean | null | undefined;
810
+ /**
811
+ * JSON-serializable value (recursive type for Temporal compatibility)
812
+ */
813
+ type JsonValue = JsonPrimitive | JsonValue[] | {
814
+ [key: string]: JsonValue;
815
+ };
816
+ /**
817
+ * Type constraint ensuring T only contains JSON-serializable values.
818
+ * Use this for custom state to ensure Temporal workflow compatibility.
819
+ *
820
+ * Allows: primitives, arrays, plain objects, and JsonValue
821
+ * Rejects: functions, symbols, undefined, class instances with methods
822
+ */
823
+ type JsonSerializable<T> = {
824
+ [K in keyof T]: T[K] extends JsonValue ? T[K] : T[K] extends JsonPrimitive ? T[K] : T[K] extends (infer U)[] ? U extends JsonValue ? T[K] : JsonSerializable<U>[] : T[K] extends object ? JsonSerializable<T[K]> : never;
825
+ };
826
+ /**
827
+ * Full state type combining base state with custom state
828
+ */
829
+ type AgentState<TCustom extends JsonSerializable<TCustom>> = BaseAgentState & TCustom;
830
+ /**
831
+ * Agent state manager interface
832
+ * Note: Temporal handlers must be set up in the workflow file due to
833
+ * Temporal's workflow isolation requirements. This manager provides
834
+ * the state and helpers needed for those handlers.
835
+ */
836
+ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
837
+ /** Get current status */
838
+ getStatus(): AgentStatus;
839
+ /** Check if agent is running */
840
+ isRunning(): boolean;
841
+ /** Check if agent is in terminal state */
842
+ isTerminal(): boolean;
843
+ /** Get current state version */
844
+ getVersion(): number;
845
+ /** Set status to RUNNING */
846
+ run(): void;
847
+ /** Set status to WAITING_FOR_INPUT */
848
+ waitForInput(): void;
849
+ /** Set status to COMPLETED */
850
+ complete(): void;
851
+ /** Set status to FAILED */
852
+ fail(): void;
853
+ /** Set status to CANCELLED */
854
+ cancel(): void;
855
+ /** Increment state version (call after state changes) */
856
+ incrementVersion(): void;
857
+ /** Increment turns (call after each turn) */
858
+ incrementTurns(): void;
859
+ /** Get current turns */
860
+ getTurns(): number;
861
+ /** Get a custom state value by key */
862
+ get<K extends keyof TCustom>(key: K): TCustom[K];
863
+ /** Set a custom state value by key */
864
+ set<K extends keyof TCustom>(key: K, value: TCustom[K]): void;
865
+ /** Get full state for query handler */
866
+ getCurrentState(): AgentState<TCustom>;
867
+ /** Check if should return from waitForStateChange */
868
+ shouldReturnFromWait(lastKnownVersion: number): boolean;
869
+ /** Get all tasks */
870
+ getTasks(): WorkflowTask[];
871
+ /** Get a task by ID */
872
+ getTask(id: string): WorkflowTask | undefined;
873
+ /** Add or update a task */
874
+ setTask(task: WorkflowTask): void;
875
+ /** Delete a task by ID */
876
+ deleteTask(id: string): boolean;
877
+ /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
878
+ setTools(newTools: ToolDefinition[]): void;
879
+ }
880
+ declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState, [], string>;
881
+ /**
882
+ * Creates an agent state manager for tracking workflow state.
883
+ *
884
+ * @param initialState - Optional initial values for base and custom state
885
+ * Base state defaults: status="RUNNING", version=0, turns=0, tasks=empty, fileTree=[]
886
+ *
887
+ * Note: Due to Temporal's workflow isolation, handlers must be set up
888
+ * in the workflow file using defineQuery/defineUpdate and setHandler.
889
+ * This manager provides the state and logic needed for those handlers.
890
+ */
891
+ declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>(initialState?: Partial<BaseAgentState> & TCustom): AgentStateManager<TCustom>;
892
+ /**
893
+ * Handler names used across agents
894
+ */
895
+ declare const AGENT_HANDLER_NAMES: {
896
+ readonly getAgentState: "getAgentState";
897
+ readonly waitForStateChange: "waitForStateChange";
898
+ readonly addMessage: "addMessage";
899
+ };
900
+
901
+ interface ZeitlichSession<M = unknown> {
910
902
  runSession<T extends JsonSerializable<T>>(args: {
911
903
  stateManager: AgentStateManager<T>;
912
- }): Promise<StoredMessage | null>;
904
+ }): Promise<M | null>;
913
905
  }
914
906
  /**
915
907
  * Session-level hooks for lifecycle events
@@ -920,7 +912,20 @@ interface SessionLifecycleHooks {
920
912
  /** Called when session ends */
921
913
  onSessionEnd?: SessionEndHook;
922
914
  }
923
- declare const createSession: <T extends ToolMap>({ threadId, agentName, maxTurns, metadata, runAgent, baseSystemPrompt, instructionsPrompt, buildContextMessage, buildFileTree, subagents, tools, processToolsInParallel, buildInTools, hooks, }: ZeitlichAgentConfig<T>) => Promise<ZeitlichSession>;
915
+ declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, }: ZeitlichAgentConfig<T, M>) => Promise<ZeitlichSession<M>>;
916
+ /**
917
+ * Proxy the default ZeitlichSharedActivities as ThreadOps<StoredMessage>.
918
+ * Call this in workflow code for the standard LangChain/StoredMessage setup.
919
+ *
920
+ * @example
921
+ * ```typescript
922
+ * const session = await createSession({
923
+ * threadOps: proxyDefaultThreadOps(),
924
+ * // ...
925
+ * });
926
+ * ```
927
+ */
928
+ declare function proxyDefaultThreadOps(options?: Parameters<typeof proxyActivities>[0]): ThreadOps<StoredMessage>;
924
929
 
925
930
  /**
926
931
  * Result from a task handler execution
@@ -937,7 +942,6 @@ interface TaskHandlerResult<TResult = unknown> {
937
942
  * Note: runAgent is workflow-specific and should be created per-workflow
938
943
  */
939
944
  interface ZeitlichSharedActivities {
940
- appendSystemMessage(threadId: string, content: string): Promise<void>;
941
945
  /**
942
946
  * Append a tool result to the thread.
943
947
  * Handles JSON serialization and optional cache points.
@@ -947,10 +951,6 @@ interface ZeitlichSharedActivities {
947
951
  * Initialize an empty thread.
948
952
  */
949
953
  initializeThread(threadId: string): Promise<void>;
950
- /**
951
- * Append a system message to a thread.
952
- */
953
- appendSystemMessage(threadId: string, content: string): Promise<void>;
954
954
  /**
955
955
  * Append messages to a thread.
956
956
  */
@@ -988,9 +988,9 @@ declare const askUserQuestionTool: {
988
988
  multiSelect: z.ZodBoolean;
989
989
  }, z.core.$strip>>;
990
990
  }, z.core.$strip>;
991
- strict: boolean;
991
+ strict: true;
992
992
  };
993
- type AskUserQuestionToolSchemaType = z.infer<typeof askUserQuestionTool.schema>;
993
+ type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
994
994
 
995
995
  declare const globTool: {
996
996
  name: "Glob";
@@ -999,9 +999,9 @@ declare const globTool: {
999
999
  pattern: z$1.ZodString;
1000
1000
  root: z$1.ZodOptional<z$1.ZodString>;
1001
1001
  }, z$1.core.$strip>;
1002
- strict: boolean;
1002
+ strict: true;
1003
1003
  };
1004
- type GlobToolSchemaType = z$1.infer<typeof globTool.schema>;
1004
+ type GlobArgs = z$1.infer<typeof globTool.schema>;
1005
1005
 
1006
1006
  declare const grepTool: {
1007
1007
  name: "Grep";
@@ -1014,9 +1014,9 @@ declare const grepTool: {
1014
1014
  excludePatterns: z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>;
1015
1015
  contextLines: z$1.ZodOptional<z$1.ZodNumber>;
1016
1016
  }, z$1.core.$strip>;
1017
- strict: boolean;
1017
+ strict: true;
1018
1018
  };
1019
- type GrepToolSchemaType = z$1.infer<typeof grepTool.schema>;
1019
+ type GrepArgs = z$1.infer<typeof grepTool.schema>;
1020
1020
 
1021
1021
  declare const readTool: {
1022
1022
  name: "FileRead";
@@ -1026,9 +1026,9 @@ declare const readTool: {
1026
1026
  offset: z$1.ZodOptional<z$1.ZodNumber>;
1027
1027
  limit: z$1.ZodOptional<z$1.ZodNumber>;
1028
1028
  }, z$1.core.$strip>;
1029
- strict: boolean;
1029
+ strict: true;
1030
1030
  };
1031
- type ReadToolSchemaType = z$1.infer<typeof readTool.schema>;
1031
+ type FileReadArgs = z$1.infer<typeof readTool.schema>;
1032
1032
 
1033
1033
  declare const writeTool: {
1034
1034
  name: "FileWrite";
@@ -1037,9 +1037,9 @@ declare const writeTool: {
1037
1037
  file_path: z$1.ZodString;
1038
1038
  content: z$1.ZodString;
1039
1039
  }, z$1.core.$strip>;
1040
- strict: boolean;
1040
+ strict: true;
1041
1041
  };
1042
- type WriteToolSchemaType = z$1.infer<typeof writeTool.schema>;
1042
+ type FileWriteArgs = z$1.infer<typeof writeTool.schema>;
1043
1043
 
1044
1044
  declare const editTool: {
1045
1045
  name: "FileEdit";
@@ -1050,9 +1050,29 @@ declare const editTool: {
1050
1050
  new_string: z$1.ZodString;
1051
1051
  replace_all: z$1.ZodOptional<z$1.ZodBoolean>;
1052
1052
  }, z$1.core.$strip>;
1053
- strict: boolean;
1053
+ strict: true;
1054
1054
  };
1055
- type EditToolSchemaType = z$1.infer<typeof editTool.schema>;
1055
+ type FileEditArgs = z$1.infer<typeof editTool.schema>;
1056
+
1057
+ declare const taskCreateTool: {
1058
+ name: "TaskCreate";
1059
+ description: string;
1060
+ schema: z.ZodObject<{
1061
+ subject: z.ZodString;
1062
+ description: z.ZodString;
1063
+ activeForm: z.ZodString;
1064
+ metadata: z.ZodRecord<z.ZodString, z.ZodString>;
1065
+ }, z.core.$strip>;
1066
+ };
1067
+ type TaskCreateArgs = z.infer<typeof taskCreateTool.schema>;
1068
+
1069
+ /**
1070
+ * Creates a TaskCreate handler that adds tasks to the workflow state.
1071
+ *
1072
+ * @param stateManager - State manager containing tasks state
1073
+ * @returns A ToolHandler for TaskCreate tool calls
1074
+ */
1075
+ declare function createTaskCreateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskCreateArgs, WorkflowTask>;
1056
1076
 
1057
1077
  declare const taskGetTool: {
1058
1078
  name: "TaskGet";
@@ -1061,36 +1081,30 @@ declare const taskGetTool: {
1061
1081
  taskId: z.ZodString;
1062
1082
  }, z.core.$strip>;
1063
1083
  };
1064
- type TaskGetToolSchemaType = z.infer<typeof taskGetTool.schema>;
1084
+ type TaskGetArgs = z.infer<typeof taskGetTool.schema>;
1065
1085
 
1066
1086
  /**
1067
1087
  * Creates a TaskGet handler that retrieves a task by ID.
1068
1088
  *
1069
1089
  * @param stateManager - State manager containing tasks state
1070
- * @returns A tool handler function
1071
- *
1072
- * @example
1073
- * const handler = createTaskGetHandler(stateManager);
1090
+ * @returns A ToolHandler for TaskGet tool calls
1074
1091
  */
1075
- declare function createTaskGetHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskGetToolSchemaType) => ToolHandlerResponse<WorkflowTask | null>;
1092
+ declare function createTaskGetHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskGetArgs, WorkflowTask | null>;
1076
1093
 
1077
1094
  declare const taskListTool: {
1078
1095
  name: "TaskList";
1079
1096
  description: string;
1080
1097
  schema: z.ZodObject<{}, z.core.$strip>;
1081
1098
  };
1082
- type TaskListToolSchemaType = z.infer<typeof taskListTool.schema>;
1099
+ type TaskListArgs = z.infer<typeof taskListTool.schema>;
1083
1100
 
1084
1101
  /**
1085
1102
  * Creates a TaskList handler that returns all tasks.
1086
1103
  *
1087
1104
  * @param stateManager - State manager containing tasks state
1088
- * @returns A tool handler function
1089
- *
1090
- * @example
1091
- * const handler = createTaskListHandler(stateManager);
1105
+ * @returns A ToolHandler for TaskList tool calls
1092
1106
  */
1093
- declare function createTaskListHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskListToolSchemaType) => ToolHandlerResponse<WorkflowTask[]>;
1107
+ declare function createTaskListHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskListArgs, WorkflowTask[]>;
1094
1108
 
1095
1109
  declare const taskUpdateTool: {
1096
1110
  name: "TaskUpdate";
@@ -1106,17 +1120,27 @@ declare const taskUpdateTool: {
1106
1120
  addBlocks: z.ZodArray<z.ZodString>;
1107
1121
  }, z.core.$strip>;
1108
1122
  };
1109
- type TaskUpdateToolSchemaType = z.infer<typeof taskUpdateTool.schema>;
1123
+ type TaskUpdateArgs = z.infer<typeof taskUpdateTool.schema>;
1110
1124
 
1111
1125
  /**
1112
1126
  * Creates a TaskUpdate handler that modifies task status and dependencies.
1113
1127
  *
1114
1128
  * @param stateManager - State manager containing tasks state
1115
- * @returns A tool handler function
1116
- *
1117
- * @example
1118
- * const handler = createTaskUpdateHandler(stateManager);
1129
+ * @returns A ToolHandler for TaskUpdate tool calls
1119
1130
  */
1120
- declare function createTaskUpdateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskUpdateToolSchemaType) => ToolHandlerResponse<WorkflowTask | null>;
1131
+ declare function createTaskUpdateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskUpdateArgs, WorkflowTask | null>;
1132
+
1133
+ declare const createBashToolDescription: ({ fileTree, }: {
1134
+ fileTree: string;
1135
+ }) => string;
1136
+ declare const bashTool: {
1137
+ name: "Bash";
1138
+ description: string;
1139
+ schema: z.ZodObject<{
1140
+ command: z.ZodString;
1141
+ }, z.core.$strip>;
1142
+ strict: true;
1143
+ };
1144
+ type BashArgs = z.infer<typeof bashTool.schema>;
1121
1145
 
1122
- export { type ToolHandlerContext as $, type AgentResponse as A, type BaseAgentState as B, type SessionExitReason as C, type SessionLifecycleHooks as D, type EditToolSchemaType as E, type SessionStartHook as F, type GlobToolSchemaType as G, type SessionStartHookContext as H, type InferToolResults as I, type JsonPrimitive as J, type SubagentConfig as K, type SubagentHooks as L, type SubagentInput as M, type TaskGetToolSchemaType as N, type TaskHandlerResult as O, type ParsedToolCall as P, type TaskStatus as Q, type RawToolCall as R, type SessionEndHook as S, type TaskCreateToolSchemaType as T, type TaskToolSchemaType as U, type TaskUpdateToolSchemaType as V, type ToolArgs as W, type ToolCallResult as X, type ToolCallResultUnion as Y, type ToolDefinition as Z, type ToolHandler as _, type ActivityToolHandler as a, type ToolHandlerResponse as a0, type ToolHooks as a1, type ToolMap as a2, type ToolMessageContent as a3, type ToolNames as a4, type ToolResult as a5, type ToolResultConfig as a6, type ToolRouter as a7, type ToolWithHandler as a8, type WorkflowTask as a9, readTool as aA, taskCreateTool as aB, taskGetTool as aC, taskListTool as aD, taskUpdateTool as aE, writeTool as aF, type WriteToolSchemaType as aa, type ZeitlichAgentConfig as ab, type ZeitlichSession as ac, type ZeitlichSharedActivities as ad, askUserQuestionTool as ae, bashTool as af, type bashToolSchemaType as ag, createAgentStateManager as ah, createSession as ai, createSharedActivities as aj, createTaskCreateHandler as ak, createTaskGetHandler as al, createTaskListHandler as am, createTaskTool as an, createTaskUpdateHandler as ao, createThreadManager as ap, createToolRouter as aq, defineSubagent as ar, defineTool as as, editTool as at, getStateQuery as au, globTool as av, grepTool as aw, handleBashTool as ax, hasNoOtherToolCalls as ay, isTerminalStatus as az, type AskUserQuestionToolSchemaType as b, AGENT_HANDLER_NAMES as c, type AgentFile as d, type AgentState as e, type AgentStateManager as f, type AgentStatus as g, type AppendToolResultFn as h, type GenericTaskToolSchemaType as i, type GrepToolSchemaType as j, type JsonSerializable as k, type JsonValue as l, type ParsedToolCallUnion as m, type PostToolUseFailureHook as n, type PostToolUseFailureHookContext as o, type PostToolUseFailureHookResult as p, type PostToolUseHook as q, type PostToolUseHookContext as r, type PreToolUseHook as s, type PreToolUseHookContext as t, type PreToolUseHookResult as u, type ProcessToolCallsContext as v, type ReadToolSchemaType as w, type RunAgentActivity as x, type RunAgentConfig as y, type SessionEndHookContext as z };
1146
+ export { type ThreadOps as $, type AgentResponse as A, type BashArgs as B, type RunAgentConfig as C, type SessionEndHookContext as D, type SessionExitReason as E, type FileEditArgs as F, type GlobArgs as G, type SessionLifecycleHooks as H, type InferToolResults as I, type JsonPrimitive as J, type SessionStartHook as K, type SessionStartHookContext as L, type SubagentConfig as M, type SubagentHooks as N, type SubagentInput as O, type ParsedToolCall as P, type TaskCreateArgs as Q, type RawToolCall as R, type SessionEndHook as S, type TaskArgs as T, type TaskGetArgs as U, type TaskHandlerResult as V, type TaskListArgs as W, type TaskStatus as X, type TaskUpdateArgs as Y, type ThreadManager as Z, type ThreadManagerConfig as _, type ActivityToolHandler as a, type ToolArgs as a0, type ToolCallResult as a1, type ToolCallResultUnion as a2, type ToolDefinition as a3, type ToolHandler as a4, type ToolHandlerContext as a5, type ToolHandlerResponse as a6, type ToolHooks as a7, type ToolMap as a8, type ToolMessageContent as a9, globTool as aA, grepTool as aB, hasNoOtherToolCalls as aC, isTerminalStatus as aD, proxyDefaultThreadOps as aE, readTool as aF, taskCreateTool as aG, taskGetTool as aH, taskListTool as aI, taskUpdateTool as aJ, withAutoAppend as aK, writeTool as aL, type ToolNames as aa, type ToolResult as ab, type ToolResultConfig as ac, type ToolRouter as ad, type ToolWithHandler as ae, type WorkflowTask as af, type ZeitlichAgentConfig as ag, type ZeitlichSession as ah, type ZeitlichSharedActivities as ai, askUserQuestionTool as aj, bashTool as ak, createAgentStateManager as al, createBashToolDescription as am, createSession as an, createSharedActivities as ao, createTaskCreateHandler as ap, createTaskGetHandler as aq, createTaskListHandler as ar, createTaskTool as as, createTaskUpdateHandler as at, createThreadManager as au, createToolRouter as av, defineSubagent as aw, defineTool as ax, editTool as ay, getStateQuery as az, type AskUserQuestionArgs as b, AGENT_HANDLER_NAMES as c, type AgentFile as d, type AgentState as e, type AgentStateManager as f, type AgentStatus as g, type AppendToolResultFn as h, type BaseAgentState as i, type BaseThreadManager as j, type FileReadArgs as k, type FileWriteArgs as l, type GrepArgs as m, type JsonSerializable as n, type JsonValue as o, type ParsedToolCallUnion as p, type PostToolUseFailureHook as q, type PostToolUseFailureHookContext as r, type PostToolUseFailureHookResult as s, type PostToolUseHook as t, type PostToolUseHookContext as u, type PreToolUseHook as v, type PreToolUseHookContext as w, type PreToolUseHookResult as x, type ProcessToolCallsContext as y, type RunAgentActivity as z };