zeitlich 0.2.1 → 0.2.2

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.
@@ -1,13 +1,93 @@
1
+ import Redis from 'ioredis';
1
2
  import { $InferMessageContent, MessageStructure, StoredMessage, MessageContent } from '@langchain/core/messages';
2
3
  import z, { z as z$1 } from 'zod';
4
+ import * as _temporalio_common from '@temporalio/common';
3
5
  import { BashOptions } from 'just-bash';
4
- import Redis from 'ioredis';
6
+ import { Workflow } from '@temporalio/workflow';
5
7
 
6
8
  /**
7
9
  * Content for a tool message response.
8
10
  * Can be a simple string or complex content parts (text, images, cache points, etc.)
9
11
  */
10
12
  type ToolMessageContent = $InferMessageContent<MessageStructure, "tool">;
13
+ interface ThreadManagerConfig {
14
+ redis: Redis;
15
+ threadId: string;
16
+ /** Thread key, defaults to 'messages' */
17
+ key?: string;
18
+ }
19
+ interface ThreadManager {
20
+ /** Append a system message to the thread */
21
+ appendSystemMessage(content: string): Promise<void>;
22
+ /** Initialize an empty thread */
23
+ initialize(): Promise<void>;
24
+ /** Load all messages from the thread */
25
+ load(): Promise<StoredMessage[]>;
26
+ /** Append messages to the thread */
27
+ append(messages: StoredMessage[]): Promise<void>;
28
+ /** Delete the thread */
29
+ delete(): Promise<void>;
30
+ /** Create a SystemMessage (returns StoredMessage for storage) */
31
+ createSystemMessage(content: string): StoredMessage;
32
+ /** Create a HumanMessage (returns StoredMessage for storage) */
33
+ createHumanMessage(content: string | MessageContent): StoredMessage;
34
+ /** Create an AIMessage with optional additional kwargs */
35
+ createAIMessage(content: string | MessageContent, kwargs?: {
36
+ header?: string;
37
+ options?: string[];
38
+ multiSelect?: boolean;
39
+ }): StoredMessage;
40
+ /** Create a ToolMessage */
41
+ createToolMessage(content: ToolMessageContent, toolCallId: string): StoredMessage;
42
+ /** Create and append a HumanMessage */
43
+ appendHumanMessage(content: string | MessageContent): Promise<void>;
44
+ /** Create and append a ToolMessage */
45
+ appendToolMessage(content: ToolMessageContent, toolCallId: string): Promise<void>;
46
+ /** Create and append an AIMessage */
47
+ appendAIMessage(content: string | MessageContent): Promise<void>;
48
+ }
49
+ /**
50
+ * Creates a thread manager for handling conversation state in Redis.
51
+ */
52
+ declare function createThreadManager(config: ThreadManagerConfig): ThreadManager;
53
+
54
+ /**
55
+ * Creates a Task tool configured with the available subagents.
56
+ *
57
+ * @param subagents - Array of subagent configurations (must have at least one)
58
+ * @returns A tool definition with dynamic schema based on available subagents
59
+ *
60
+ * @example
61
+ * const taskTool = createTaskTool([
62
+ * {
63
+ * name: "researcher",
64
+ * description: "Researches topics and gathers information",
65
+ * workflow: "researcherWorkflow",
66
+ * resultSchema: z.object({ findings: z.string() }),
67
+ * },
68
+ * ]);
69
+ */
70
+ declare function createTaskTool<T extends SubagentConfig[]>(subagents: T): {
71
+ name: string;
72
+ description: string;
73
+ schema: z.ZodObject<{
74
+ subagent: z.ZodEnum<Record<string, string>>;
75
+ description: z.ZodString;
76
+ prompt: z.ZodString;
77
+ }>;
78
+ };
79
+ /**
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)
85
+ */
86
+ type GenericTaskToolSchemaType = {
87
+ subagent: string;
88
+ description: string;
89
+ prompt: string;
90
+ };
11
91
 
12
92
  /**
13
93
  * JSON primitive types that Temporal can serialize
@@ -80,9 +160,10 @@ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
80
160
  setTask(task: WorkflowTask): void;
81
161
  /** Delete a task by ID */
82
162
  deleteTask(id: string): boolean;
83
- /** Set the tools */
163
+ /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
84
164
  setTools(newTools: ToolDefinition[]): void;
85
165
  }
166
+ declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState, [], string>;
86
167
  /**
87
168
  * Creates an agent state manager for tracking workflow state.
88
169
  *
@@ -125,10 +206,7 @@ type TaskCreateToolSchemaType = z.infer<typeof taskCreateTool.schema>;
125
206
  * @example
126
207
  * const handler = createTaskCreateHandler(stateManager, uuid4);
127
208
  */
128
- declare function createTaskCreateHandler<TCustom extends JsonSerializable<TCustom>>({ stateManager, idGenerator, }: {
129
- stateManager: AgentStateManager<TCustom>;
130
- idGenerator: () => string;
131
- }): (args: TaskCreateToolSchemaType) => ToolHandlerResponse<WorkflowTask>;
209
+ declare function createTaskCreateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskCreateToolSchemaType) => ToolHandlerResponse<WorkflowTask>;
132
210
 
133
211
  declare const bashTool: {
134
212
  name: "Bash";
@@ -171,6 +249,8 @@ interface ToolWithHandler<TName extends string = string, TSchema extends z$1.Zod
171
249
  handler: ToolHandler<z$1.infer<TSchema>, TResult, TContext>;
172
250
  strict?: boolean;
173
251
  max_uses?: number;
252
+ /** Per-tool lifecycle hooks (run in addition to global hooks) */
253
+ hooks?: ToolHooks<z$1.infer<TSchema>, TResult>;
174
254
  }
175
255
  /**
176
256
  * A map of tool keys to tool definitions with handlers.
@@ -182,6 +262,7 @@ type ToolMap = Record<string, {
182
262
  handler: (args: any, context: any) => ToolHandlerResponse<any> | Promise<ToolHandlerResponse<any>>;
183
263
  strict?: boolean;
184
264
  max_uses?: number;
265
+ hooks?: ToolHooks<any, any>;
185
266
  }>;
186
267
  /**
187
268
  * Extract the tool names from a tool map (uses the tool's name property, not the key).
@@ -218,10 +299,10 @@ type AppendToolResultFn = (config: ToolResultConfig) => Promise<void>;
218
299
  * Contains the content for the tool message and the result to return from processToolCalls.
219
300
  */
220
301
  interface ToolHandlerResponse<TResult> {
221
- /** Content for the tool message added to the thread */
222
- content: ToolMessageContent;
223
- /** Result returned from processToolCalls */
224
- result: TResult;
302
+ /** Content sent back to the LLM as the tool call response */
303
+ toolResponse: ToolMessageContent;
304
+ /** Data returned to the workflow and hooks for further processing */
305
+ data: TResult | null;
225
306
  }
226
307
  /**
227
308
  * Context passed to tool handlers for additional data beyond tool args.
@@ -281,7 +362,7 @@ type ToolResult<T extends ToolMap, TName extends ToolNames<T>> = Extract<T[keyof
281
362
  interface ToolCallResult<TName extends string = string, TResult = unknown> {
282
363
  toolCallId: string;
283
364
  name: TName;
284
- result: TResult;
365
+ data: TResult | null;
285
366
  }
286
367
  /**
287
368
  * Options for creating a tool router.
@@ -405,6 +486,70 @@ interface ToolRouter<T extends ToolMap> {
405
486
  * ```
406
487
  */
407
488
  declare function createToolRouter<T extends ToolMap>(options: ToolRouterOptions<T>): ToolRouter<T>;
489
+ /**
490
+ * Identity function that creates a generic inference context for a tool definition.
491
+ * TypeScript infers TResult from the handler and flows it to hooks automatically.
492
+ *
493
+ * @example
494
+ * ```typescript
495
+ * tools: {
496
+ * AskUser: defineTool({
497
+ * ...askUserTool,
498
+ * handler: handleAskUser,
499
+ * hooks: {
500
+ * onPostToolUse: ({ result }) => {
501
+ * // result is correctly typed as the handler's return data type
502
+ * },
503
+ * },
504
+ * }),
505
+ * }
506
+ * ```
507
+ */
508
+ declare function defineTool<TName extends string, TSchema extends z$1.ZodType, TResult, TContext = ToolHandlerContext>(tool: ToolWithHandler<TName, TSchema, TResult, TContext>): ToolWithHandler<TName, TSchema, TResult, TContext>;
509
+ /**
510
+ * Identity function that provides full type inference for subagent configurations.
511
+ * Verifies the workflow function's input parameters match the configured context,
512
+ * and properly types the lifecycle hooks with Task tool args and inferred result type.
513
+ *
514
+ * @example
515
+ * ```ts
516
+ * // With typed context — workflow must accept { prompt, context }
517
+ * const researcher = defineSubagent({
518
+ * name: "researcher",
519
+ * description: "Researches topics",
520
+ * workflow: researcherWorkflow, // (input: { prompt: string; context: { apiKey: string } }) => Promise<...>
521
+ * context: { apiKey: "..." },
522
+ * resultSchema: z.object({ findings: z.string() }),
523
+ * hooks: {
524
+ * onPostExecution: ({ result }) => {
525
+ * // result is typed as { findings: string }
526
+ * },
527
+ * },
528
+ * });
529
+ *
530
+ * // Without context — workflow only needs { prompt }
531
+ * const writer = defineSubagent({
532
+ * name: "writer",
533
+ * description: "Writes content",
534
+ * workflow: writerWorkflow, // (input: { prompt: string }) => Promise<...>
535
+ * resultSchema: z.object({ content: z.string() }),
536
+ * });
537
+ * ```
538
+ */
539
+ declare function defineSubagent<TResult extends z$1.ZodType = z$1.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow" | "context"> & {
540
+ workflow: string | ((input: {
541
+ prompt: string;
542
+ context: TContext;
543
+ }) => Promise<any>);
544
+ context: TContext;
545
+ hooks?: SubagentHooks<GenericTaskToolSchemaType, z$1.infer<TResult>>;
546
+ }): SubagentConfig<TResult>;
547
+ declare function defineSubagent<TResult extends z$1.ZodType = z$1.ZodType>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow"> & {
548
+ workflow: string | ((input: {
549
+ prompt: string;
550
+ }) => Promise<any>);
551
+ hooks?: SubagentHooks<GenericTaskToolSchemaType, z$1.infer<TResult>>;
552
+ }): SubagentConfig<TResult>;
408
553
  /**
409
554
  * Utility to check if there were no tool calls besides a specific one
410
555
  */
@@ -418,7 +563,7 @@ type AgentStatus = "RUNNING" | "WAITING_FOR_INPUT" | "COMPLETED" | "FAILED" | "C
418
563
  * Base state that all agents must have
419
564
  */
420
565
  interface BaseAgentState {
421
- tools: ToolDefinition[];
566
+ tools: SerializableToolDefinition[];
422
567
  status: AgentStatus;
423
568
  version: number;
424
569
  turns: number;
@@ -492,6 +637,18 @@ interface ZeitlichAgentConfig<T extends ToolMap> {
492
637
  [K in keyof BuildInToolDefinitions]?: BuildInToolDefinitions[K]["handler"];
493
638
  };
494
639
  }
640
+ /**
641
+ * A JSON-serializable tool definition for state storage.
642
+ * Uses a plain JSON Schema object instead of a live Zod instance,
643
+ * so it survives Temporal serialization without losing constraints (min, max, etc.).
644
+ */
645
+ interface SerializableToolDefinition {
646
+ name: string;
647
+ description: string;
648
+ schema: Record<string, unknown>;
649
+ strict?: boolean;
650
+ max_uses?: number;
651
+ }
495
652
  /**
496
653
  * Configuration passed to runAgent activity
497
654
  */
@@ -523,12 +680,43 @@ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
523
680
  name: string;
524
681
  /** Description shown to the parent agent explaining what this subagent does */
525
682
  description: string;
526
- /** Temporal workflow type name (used with executeChild) */
527
- workflowType: string;
683
+ /** Temporal workflow function or type name (used with executeChild) */
684
+ workflow: string | Workflow;
528
685
  /** Optional task queue - defaults to parent's queue if not specified */
529
686
  taskQueue?: string;
530
687
  /** Optional Zod schema to validate the child workflow's result. If omitted, result is passed through as-is. */
531
688
  resultSchema?: TResult;
689
+ /** Optional static context passed to the subagent on every invocation */
690
+ context?: Record<string, unknown>;
691
+ /** Per-subagent lifecycle hooks */
692
+ hooks?: SubagentHooks;
693
+ }
694
+ /**
695
+ * Per-subagent lifecycle hooks - defined on a SubagentConfig.
696
+ * Runs in addition to global hooks (global pre → subagent pre → execute → subagent post → global post).
697
+ */
698
+ interface SubagentHooks<TArgs = unknown, TResult = unknown> {
699
+ /** Called before this subagent executes - can skip or modify args */
700
+ onPreExecution?: (ctx: {
701
+ args: TArgs;
702
+ threadId: string;
703
+ turn: number;
704
+ }) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
705
+ /** Called after this subagent executes successfully */
706
+ onPostExecution?: (ctx: {
707
+ args: TArgs;
708
+ result: TResult;
709
+ threadId: string;
710
+ turn: number;
711
+ durationMs: number;
712
+ }) => void | Promise<void>;
713
+ /** Called when this subagent execution fails */
714
+ onExecutionFailure?: (ctx: {
715
+ args: TArgs;
716
+ error: Error;
717
+ threadId: string;
718
+ turn: number;
719
+ }) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
532
720
  }
533
721
  /**
534
722
  * Input passed to child workflows when spawned as subagents
@@ -536,6 +724,8 @@ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
536
724
  interface SubagentInput {
537
725
  /** The prompt/task from the parent agent */
538
726
  prompt: string;
727
+ /** Optional context parameters passed from the parent agent */
728
+ context?: Record<string, unknown>;
539
729
  }
540
730
  /**
541
731
  * Status of a workflow task
@@ -669,6 +859,33 @@ interface SessionEndHookContext {
669
859
  * SessionEnd hook - called when session ends
670
860
  */
671
861
  type SessionEndHook = (ctx: SessionEndHookContext) => void | Promise<void>;
862
+ /**
863
+ * Per-tool lifecycle hooks - defined directly on a tool definition.
864
+ * Runs in addition to global hooks (global pre → tool pre → execute → tool post → global post).
865
+ */
866
+ interface ToolHooks<TArgs = unknown, TResult = unknown> {
867
+ /** Called before this tool executes - can skip or modify args */
868
+ onPreToolUse?: (ctx: {
869
+ args: TArgs;
870
+ threadId: string;
871
+ turn: number;
872
+ }) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
873
+ /** Called after this tool executes successfully */
874
+ onPostToolUse?: (ctx: {
875
+ args: TArgs;
876
+ result: TResult | null;
877
+ threadId: string;
878
+ turn: number;
879
+ durationMs: number;
880
+ }) => void | Promise<void>;
881
+ /** Called when this tool execution fails */
882
+ onPostToolUseFailure?: (ctx: {
883
+ args: TArgs;
884
+ error: Error;
885
+ threadId: string;
886
+ turn: number;
887
+ }) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
888
+ }
672
889
  /**
673
890
  * Combined hooks interface for session lifecycle
674
891
  */
@@ -705,44 +922,6 @@ interface SessionLifecycleHooks {
705
922
  }
706
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>;
707
924
 
708
- /**
709
- * Creates a Task tool configured with the available subagents.
710
- *
711
- * @param subagents - Array of subagent configurations (must have at least one)
712
- * @returns A tool definition with dynamic schema based on available subagents
713
- *
714
- * @example
715
- * const taskTool = createTaskTool([
716
- * {
717
- * name: "researcher",
718
- * description: "Researches topics and gathers information",
719
- * workflowType: "researcherWorkflow",
720
- * resultSchema: z.object({ findings: z.string() }),
721
- * },
722
- * ]);
723
- */
724
- declare function createTaskTool<T extends SubagentConfig[]>(subagents: T): {
725
- name: string;
726
- description: string;
727
- schema: z.ZodObject<{
728
- subagent: z.ZodEnum<Record<string, string>>;
729
- description: z.ZodString;
730
- prompt: z.ZodString;
731
- }>;
732
- };
733
- /**
734
- * Infer the schema type for a task tool created with specific subagents
735
- */
736
- type TaskToolSchemaType<T extends SubagentConfig[]> = z.infer<ReturnType<typeof createTaskTool<T>>["schema"]>;
737
- /**
738
- * Generic task tool schema type (when subagent names are not known at compile time)
739
- */
740
- type GenericTaskToolSchemaType = {
741
- subagent: string;
742
- description: string;
743
- prompt: string;
744
- };
745
-
746
925
  /**
747
926
  * Result from a task handler execution
748
927
  */
@@ -940,4 +1119,4 @@ type TaskUpdateToolSchemaType = z.infer<typeof taskUpdateTool.schema>;
940
1119
  */
941
1120
  declare function createTaskUpdateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskUpdateToolSchemaType) => ToolHandlerResponse<WorkflowTask | null>;
942
1121
 
943
- export { type ToolHandlerResponse 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 SubagentInput as L, type TaskGetToolSchemaType as M, type TaskHandlerResult as N, type TaskStatus as O, type ParsedToolCall as P, type TaskToolSchemaType as Q, type RawToolCall as R, type SessionEndHook as S, type TaskCreateToolSchemaType as T, type TaskUpdateToolSchemaType as U, type ToolArgs as V, type ToolCallResult as W, type ToolCallResultUnion as X, type ToolDefinition as Y, type ToolHandler as Z, type ToolHandlerContext as _, type ActivityToolHandler as a, type ToolMap as a0, type ToolMessageContent as a1, type ToolNames as a2, type ToolResult as a3, type ToolResultConfig as a4, type ToolRouter as a5, type ToolWithHandler as a6, type WorkflowTask as a7, type WriteToolSchemaType as a8, type ZeitlichAgentConfig as a9, type ZeitlichSession as aa, type ZeitlichSharedActivities as ab, askUserQuestionTool as ac, bashTool as ad, type bashToolSchemaType as ae, createAgentStateManager as af, createSession as ag, createSharedActivities as ah, createTaskCreateHandler as ai, createTaskGetHandler as aj, createTaskListHandler as ak, createTaskTool as al, createTaskUpdateHandler as am, createToolRouter as an, editTool as ao, globTool as ap, grepTool as aq, handleBashTool as ar, hasNoOtherToolCalls as as, isTerminalStatus as at, readTool as au, taskCreateTool as av, taskGetTool as aw, taskListTool as ax, taskUpdateTool as ay, writeTool 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 };
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 };