zeitlich 0.2.6 → 0.2.8

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.
@@ -2,7 +2,7 @@ import { Workflow, proxyActivities } from '@temporalio/workflow';
2
2
  import Redis from 'ioredis';
3
3
  import { $InferMessageContent, MessageStructure, StoredMessage, MessageContent } from '@langchain/core/messages';
4
4
  import z, { z as z$1 } from 'zod';
5
- import * as _temporalio_common from '@temporalio/common';
5
+ import { Duration } from '@temporalio/common';
6
6
 
7
7
  /**
8
8
  * Content for a tool message response.
@@ -116,7 +116,7 @@ interface ToolWithHandler<TName extends string = string, TSchema extends z$1.Zod
116
116
  strict?: boolean;
117
117
  max_uses?: number;
118
118
  /** Whether this tool is available to the agent (default: true). Disabled tools are excluded from definitions and rejected at parse time. */
119
- enabled?: boolean;
119
+ enabled?: () => boolean;
120
120
  /** Per-tool lifecycle hooks (run in addition to global hooks) */
121
121
  hooks?: ToolHooks<z$1.infer<TSchema>, TResult>;
122
122
  }
@@ -135,7 +135,7 @@ type ToolMap = Record<string, {
135
135
  handler: ToolHandler<any, any, any>;
136
136
  strict?: boolean;
137
137
  max_uses?: number;
138
- enabled?: boolean;
138
+ enabled?: () => boolean;
139
139
  hooks?: ToolHooks<any, any>;
140
140
  }>;
141
141
  /**
@@ -187,6 +187,8 @@ interface ToolHandlerResponse<TResult = null> {
187
187
  * payloads through Temporal's activity payload limit.
188
188
  */
189
189
  resultAppended?: boolean;
190
+ /** Token usage from the tool execution (e.g. child agent invocations) */
191
+ usage?: TokenUsage;
190
192
  }
191
193
  /**
192
194
  * Context passed to tool handlers for additional data beyond tool args.
@@ -237,6 +239,7 @@ interface ToolCallResult<TName extends string = string, TResult = unknown> {
237
239
  toolCallId: string;
238
240
  name: TName;
239
241
  data: TResult;
242
+ usage?: TokenUsage;
240
243
  }
241
244
  /**
242
245
  * Options for creating a tool router.
@@ -465,6 +468,10 @@ interface BaseAgentState {
465
468
  turns: number;
466
469
  tasks: Map<string, WorkflowTask>;
467
470
  systemPrompt: string;
471
+ totalInputTokens: number;
472
+ totalOutputTokens: number;
473
+ cachedWriteTokens: number;
474
+ cachedReadtTokens: number;
468
475
  }
469
476
  /**
470
477
  * File representation for agent workflows
@@ -481,17 +488,20 @@ interface AgentFile {
481
488
  /** MIME type of the file */
482
489
  mimeType?: string;
483
490
  }
491
+ interface TokenUsage {
492
+ inputTokens?: number;
493
+ outputTokens?: number;
494
+ cachedWriteTokens?: number;
495
+ cachedReadTokens?: number;
496
+ reasonTokens?: number;
497
+ }
484
498
  /**
485
499
  * Agent response from LLM invocation
486
500
  */
487
501
  interface AgentResponse<M = StoredMessage> {
488
502
  message: M;
489
503
  rawToolCalls: RawToolCall[];
490
- usage?: {
491
- input_tokens?: number;
492
- output_tokens?: number;
493
- total_tokens?: number;
494
- };
504
+ usage?: TokenUsage;
495
505
  }
496
506
  /**
497
507
  * Thread operations required by a session.
@@ -509,16 +519,27 @@ interface ThreadOps {
509
519
  appendSystemMessage(threadId: string, content: string): Promise<void>;
510
520
  }
511
521
  /**
512
- * Configuration for a Zeitlich agent session
522
+ * Configuration for a Zeitlich agent
513
523
  */
514
- interface ZeitlichAgentConfig<T extends ToolMap, M = StoredMessage> {
515
- threadId: string;
524
+ interface AgentConfig {
525
+ /** The name of the agent, should be unique within the workflows, ideally Pascal Case */
516
526
  agentName: string;
517
527
  /** Description, used for sub agents */
518
528
  description?: string;
529
+ /** The system prompt to append to the thread */
519
530
  systemPrompt?: string;
531
+ }
532
+ /**
533
+ * Configuration for a Zeitlich agent session
534
+ */
535
+ interface SessionConfig<T extends ToolMap, M = StoredMessage> {
536
+ /** The thread ID to use for the session */
537
+ threadId: string;
538
+ /** Metadata for the session */
520
539
  metadata?: Record<string, unknown>;
540
+ /** Whether to append the system prompt as message to the thread */
521
541
  appendSystemPrompt?: boolean;
542
+ /** How many turns to run the session for */
522
543
  maxTurns?: number;
523
544
  /** Workflow-specific runAgent activity (with tools pre-bound) */
524
545
  runAgent: RunAgentActivity<M>;
@@ -537,6 +558,8 @@ interface ZeitlichAgentConfig<T extends ToolMap, M = StoredMessage> {
537
558
  * Returns MessageContent array for the initial HumanMessage.
538
559
  */
539
560
  buildContextMessage: () => MessageContent | Promise<MessageContent>;
561
+ /** How long to wait for input before cancelling the workflow */
562
+ waitForInputTimeout?: Duration;
540
563
  }
541
564
  /**
542
565
  * A JSON-serializable tool definition for state storage.
@@ -553,9 +576,10 @@ interface SerializableToolDefinition {
553
576
  /**
554
577
  * Configuration passed to runAgent activity
555
578
  */
556
- interface RunAgentConfig {
579
+ interface RunAgentConfig extends AgentConfig {
580
+ /** The thread ID to use for the session */
557
581
  threadId: string;
558
- agentName: string;
582
+ /** Metadata for the session */
559
583
  metadata?: Record<string, unknown>;
560
584
  }
561
585
  /**
@@ -584,7 +608,7 @@ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
584
608
  /** Description shown to the parent agent explaining what this subagent does */
585
609
  description: string;
586
610
  /** Whether this subagent is available (default: true). Disabled subagents are excluded from the Subagent tool. */
587
- enabled?: boolean;
611
+ enabled?: () => boolean;
588
612
  /** Temporal workflow function or type name (used with executeChild) */
589
613
  workflow: string | Workflow;
590
614
  /** Optional task queue - defaults to parent's queue if not specified */
@@ -745,6 +769,32 @@ interface SessionStartHookContext {
745
769
  * SessionStart hook - called when session begins
746
770
  */
747
771
  type SessionStartHook = (ctx: SessionStartHookContext) => void | Promise<void>;
772
+ /**
773
+ * Context for PreHumanMessageAppend hook - called before each human message is appended to the thread
774
+ */
775
+ interface PreHumanMessageAppendHookContext {
776
+ /** The message about to be appended */
777
+ message: MessageContent;
778
+ /** Thread identifier */
779
+ threadId: string;
780
+ }
781
+ /**
782
+ * PreHumanMessageAppend hook - called before each human message is appended to the thread
783
+ */
784
+ type PreHumanMessageAppendHook = (ctx: PreHumanMessageAppendHookContext) => void | Promise<void>;
785
+ /**
786
+ * PostHumanMessageAppend hook - called after each human message is appended to the thread
787
+ */
788
+ type PostHumanMessageAppendHook = (ctx: PostHumanMessageAppendHookContext) => void | Promise<void>;
789
+ /**
790
+ * Context for PostHumanMessageAppend hook - called after each human message is appended to the thread
791
+ */
792
+ interface PostHumanMessageAppendHookContext {
793
+ /** The message that was appended */
794
+ message: MessageContent;
795
+ /** Thread identifier */
796
+ threadId: string;
797
+ }
748
798
  /**
749
799
  * Context for SessionEnd hook - called when session ends
750
800
  */
@@ -795,6 +845,10 @@ interface ToolHooks<TArgs = unknown, TResult = unknown> {
795
845
  * Combined hooks interface for session lifecycle
796
846
  */
797
847
  interface Hooks<T extends ToolMap, TResult = unknown> {
848
+ /** Called before each human message is appended to the thread */
849
+ onPreHumanMessageAppend?: PreHumanMessageAppendHook;
850
+ /** Called after each human message is appended to the thread */
851
+ onPostHumanMessageAppend?: PostHumanMessageAppendHook;
798
852
  /** Called before each tool execution - can block or modify */
799
853
  onPreToolUse?: PreToolUseHook<T>;
800
854
  /** Called after each successful tool execution */
@@ -884,8 +938,24 @@ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
884
938
  deleteTask(id: string): boolean;
885
939
  /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
886
940
  setTools(newTools: ToolDefinition[]): void;
941
+ /** Update the usage */
942
+ updateUsage(usage: {
943
+ inputTokens?: number;
944
+ outputTokens?: number;
945
+ cachedWriteTokens?: number;
946
+ cachedReadTokens?: number;
947
+ reasonTokens?: number;
948
+ }): void;
949
+ /** Get the total usage */
950
+ getTotalUsage(): {
951
+ totalInputTokens: number;
952
+ totalOutputTokens: number;
953
+ totalCachedWriteTokens: number;
954
+ totalCachedReadTokens: number;
955
+ totalReasonTokens: number;
956
+ turns: number;
957
+ };
887
958
  }
888
- declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState, [], string>;
889
959
  /**
890
960
  * Creates an agent state manager for tracking workflow state.
891
961
  *
@@ -896,7 +966,10 @@ declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState,
896
966
  * in the workflow file using defineQuery/defineUpdate and setHandler.
897
967
  * This manager provides the state and logic needed for those handlers.
898
968
  */
899
- declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>(initialState?: Partial<BaseAgentState> & TCustom): AgentStateManager<TCustom>;
969
+ declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>({ initialState, agentConfig, }: {
970
+ initialState?: Partial<BaseAgentState> & TCustom;
971
+ agentConfig: AgentConfig;
972
+ }): AgentStateManager<TCustom>;
900
973
  /**
901
974
  * Handler names used across agents
902
975
  */
@@ -909,7 +982,11 @@ declare const AGENT_HANDLER_NAMES: {
909
982
  interface ZeitlichSession<M = unknown> {
910
983
  runSession<T extends JsonSerializable<T>>(args: {
911
984
  stateManager: AgentStateManager<T>;
912
- }): Promise<M | null>;
985
+ }): Promise<{
986
+ finalMessage: M | null;
987
+ exitReason: SessionExitReason;
988
+ usage: ReturnType<AgentStateManager<T>["getTotalUsage"]>;
989
+ }>;
913
990
  }
914
991
  /**
915
992
  * Session-level hooks for lifecycle events
@@ -920,7 +997,7 @@ interface SessionLifecycleHooks {
920
997
  /** Called when session ends */
921
998
  onSessionEnd?: SessionEndHook;
922
999
  }
923
- declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, appendSystemPrompt, systemPrompt, }: ZeitlichAgentConfig<T, M>) => Promise<ZeitlichSession<M>>;
1000
+ declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, description, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, appendSystemPrompt, systemPrompt, waitForInputTimeout, }: SessionConfig<T, M> & AgentConfig) => Promise<ZeitlichSession<M>>;
924
1001
  /**
925
1002
  * Proxy the default ZeitlichSharedActivities as ThreadOps<StoredMessage>.
926
1003
  * Call this in workflow code for the standard LangChain/StoredMessage setup.
@@ -971,24 +1048,6 @@ interface ZeitlichSharedActivities {
971
1048
  */
972
1049
  declare function createSharedActivities(redis: Redis): ZeitlichSharedActivities;
973
1050
 
974
- declare const askUserQuestionTool: {
975
- name: "AskUserQuestion";
976
- description: string;
977
- schema: z.ZodObject<{
978
- questions: z.ZodArray<z.ZodObject<{
979
- question: z.ZodString;
980
- header: z.ZodString;
981
- options: z.ZodArray<z.ZodObject<{
982
- label: z.ZodString;
983
- description: z.ZodString;
984
- }, z.core.$strip>>;
985
- multiSelect: z.ZodBoolean;
986
- }, z.core.$strip>>;
987
- }, z.core.$strip>;
988
- strict: true;
989
- };
990
- type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
991
-
992
1051
  declare const globTool: {
993
1052
  name: "Glob";
994
1053
  description: string;
@@ -1140,4 +1199,37 @@ declare const bashTool: {
1140
1199
  };
1141
1200
  type BashArgs = z.infer<typeof bashTool.schema>;
1142
1201
 
1143
- export { type ToolArgs 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 SubagentArgs as M, type SubagentConfig as N, type SubagentHooks as O, type ParsedToolCall as P, type SubagentInput as Q, type RawToolCall as R, type SessionEndHook as S, type TaskCreateArgs as T, type TaskGetArgs as U, type TaskListArgs as V, type TaskStatus as W, type TaskUpdateArgs as X, type ThreadManager as Y, type ThreadManagerConfig as Z, type ThreadOps as _, type ActivityToolHandler as a, type ToolCallResult as a0, type ToolCallResultUnion as a1, type ToolDefinition as a2, type ToolHandler as a3, type ToolHandlerContext as a4, type ToolHandlerResponse as a5, type ToolHooks as a6, type ToolMap as a7, type ToolMessageContent as a8, type ToolNames as a9, grepTool as aA, hasNoOtherToolCalls as aB, isTerminalStatus as aC, proxyDefaultThreadOps as aD, readTool as aE, taskCreateTool as aF, taskGetTool as aG, taskListTool as aH, taskUpdateTool as aI, withAutoAppend as aJ, writeTool as aK, type ToolResult as aa, type ToolResultConfig as ab, type ToolRouter as ac, type ToolWithHandler as ad, type WorkflowTask as ae, type ZeitlichAgentConfig as af, type ZeitlichSession as ag, type ZeitlichSharedActivities as ah, askUserQuestionTool as ai, bashTool as aj, createAgentStateManager as ak, createBashToolDescription as al, createSession as am, createSharedActivities as an, createSubagentTool as ao, createTaskCreateHandler as ap, createTaskGetHandler as aq, createTaskListHandler as ar, createTaskUpdateHandler as as, createThreadManager as at, createToolRouter as au, defineSubagent as av, defineTool as aw, editTool as ax, getStateQuery as ay, globTool 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 };
1202
+ declare const askUserQuestionTool: {
1203
+ name: "AskUserQuestion";
1204
+ description: string;
1205
+ schema: z.ZodObject<{
1206
+ questions: z.ZodArray<z.ZodObject<{
1207
+ question: z.ZodString;
1208
+ header: z.ZodString;
1209
+ options: z.ZodArray<z.ZodObject<{
1210
+ label: z.ZodString;
1211
+ description: z.ZodString;
1212
+ }, z.core.$strip>>;
1213
+ multiSelect: z.ZodBoolean;
1214
+ }, z.core.$strip>>;
1215
+ }, z.core.$strip>;
1216
+ strict: true;
1217
+ };
1218
+ type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
1219
+
1220
+ /**
1221
+ * Creates handler for user interaction tool - creates AI messages for display.
1222
+ */
1223
+ declare const createAskUserQuestionHandler: () => ToolHandler<AskUserQuestionArgs, {
1224
+ questions: {
1225
+ question: string;
1226
+ header: string;
1227
+ options: {
1228
+ label: string;
1229
+ description: string;
1230
+ }[];
1231
+ multiSelect: boolean;
1232
+ }[];
1233
+ }>;
1234
+
1235
+ export { type ThreadOps as $, type AgentResponse as A, type BashArgs as B, type RunAgentActivity as C, type RunAgentConfig as D, type SessionEndHookContext as E, type FileEditArgs as F, type GlobArgs as G, type SessionExitReason as H, type InferToolResults as I, type JsonPrimitive as J, type SessionLifecycleHooks as K, type SessionStartHook as L, type SessionStartHookContext as M, type SubagentArgs as N, type SubagentConfig as O, type ParsedToolCall as P, type SubagentHooks as Q, type RawToolCall as R, type SessionEndHook as S, type SubagentInput as T, type TaskCreateArgs as U, type TaskGetArgs 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, grepTool as aA, hasNoOtherToolCalls as aB, isTerminalStatus as aC, proxyDefaultThreadOps as aD, readTool as aE, taskCreateTool as aF, taskGetTool as aG, taskListTool as aH, taskUpdateTool as aI, withAutoAppend as aJ, writeTool as aK, 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 ZeitlichSession as ag, type ZeitlichSharedActivities as ah, askUserQuestionTool as ai, bashTool as aj, createAgentStateManager as ak, createAskUserQuestionHandler as al, createBashToolDescription as am, createSession as an, createSharedActivities as ao, createSubagentTool as ap, createTaskCreateHandler as aq, createTaskGetHandler as ar, createTaskListHandler as as, createTaskUpdateHandler as at, createThreadManager as au, createToolRouter as av, defineSubagent as aw, defineTool as ax, editTool as ay, globTool as az, AGENT_HANDLER_NAMES as b, type AgentConfig as c, type AgentFile as d, type AgentState as e, type AgentStateManager as f, type AgentStatus as g, type AppendToolResultFn as h, type AskUserQuestionArgs as i, type BaseAgentState as j, type BaseThreadManager as k, type FileReadArgs as l, type FileWriteArgs as m, type GrepArgs as n, type JsonSerializable as o, type JsonValue as p, type ParsedToolCallUnion as q, type PostToolUseFailureHook as r, type PostToolUseFailureHookContext as s, type PostToolUseFailureHookResult as t, type PostToolUseHook as u, type PostToolUseHookContext as v, type PreToolUseHook as w, type PreToolUseHookContext as x, type PreToolUseHookResult as y, type ProcessToolCallsContext as z };
@@ -2,7 +2,7 @@ import { Workflow, proxyActivities } from '@temporalio/workflow';
2
2
  import Redis from 'ioredis';
3
3
  import { $InferMessageContent, MessageStructure, StoredMessage, MessageContent } from '@langchain/core/messages';
4
4
  import z, { z as z$1 } from 'zod';
5
- import * as _temporalio_common from '@temporalio/common';
5
+ import { Duration } from '@temporalio/common';
6
6
 
7
7
  /**
8
8
  * Content for a tool message response.
@@ -116,7 +116,7 @@ interface ToolWithHandler<TName extends string = string, TSchema extends z$1.Zod
116
116
  strict?: boolean;
117
117
  max_uses?: number;
118
118
  /** Whether this tool is available to the agent (default: true). Disabled tools are excluded from definitions and rejected at parse time. */
119
- enabled?: boolean;
119
+ enabled?: () => boolean;
120
120
  /** Per-tool lifecycle hooks (run in addition to global hooks) */
121
121
  hooks?: ToolHooks<z$1.infer<TSchema>, TResult>;
122
122
  }
@@ -135,7 +135,7 @@ type ToolMap = Record<string, {
135
135
  handler: ToolHandler<any, any, any>;
136
136
  strict?: boolean;
137
137
  max_uses?: number;
138
- enabled?: boolean;
138
+ enabled?: () => boolean;
139
139
  hooks?: ToolHooks<any, any>;
140
140
  }>;
141
141
  /**
@@ -187,6 +187,8 @@ interface ToolHandlerResponse<TResult = null> {
187
187
  * payloads through Temporal's activity payload limit.
188
188
  */
189
189
  resultAppended?: boolean;
190
+ /** Token usage from the tool execution (e.g. child agent invocations) */
191
+ usage?: TokenUsage;
190
192
  }
191
193
  /**
192
194
  * Context passed to tool handlers for additional data beyond tool args.
@@ -237,6 +239,7 @@ interface ToolCallResult<TName extends string = string, TResult = unknown> {
237
239
  toolCallId: string;
238
240
  name: TName;
239
241
  data: TResult;
242
+ usage?: TokenUsage;
240
243
  }
241
244
  /**
242
245
  * Options for creating a tool router.
@@ -465,6 +468,10 @@ interface BaseAgentState {
465
468
  turns: number;
466
469
  tasks: Map<string, WorkflowTask>;
467
470
  systemPrompt: string;
471
+ totalInputTokens: number;
472
+ totalOutputTokens: number;
473
+ cachedWriteTokens: number;
474
+ cachedReadtTokens: number;
468
475
  }
469
476
  /**
470
477
  * File representation for agent workflows
@@ -481,17 +488,20 @@ interface AgentFile {
481
488
  /** MIME type of the file */
482
489
  mimeType?: string;
483
490
  }
491
+ interface TokenUsage {
492
+ inputTokens?: number;
493
+ outputTokens?: number;
494
+ cachedWriteTokens?: number;
495
+ cachedReadTokens?: number;
496
+ reasonTokens?: number;
497
+ }
484
498
  /**
485
499
  * Agent response from LLM invocation
486
500
  */
487
501
  interface AgentResponse<M = StoredMessage> {
488
502
  message: M;
489
503
  rawToolCalls: RawToolCall[];
490
- usage?: {
491
- input_tokens?: number;
492
- output_tokens?: number;
493
- total_tokens?: number;
494
- };
504
+ usage?: TokenUsage;
495
505
  }
496
506
  /**
497
507
  * Thread operations required by a session.
@@ -509,16 +519,27 @@ interface ThreadOps {
509
519
  appendSystemMessage(threadId: string, content: string): Promise<void>;
510
520
  }
511
521
  /**
512
- * Configuration for a Zeitlich agent session
522
+ * Configuration for a Zeitlich agent
513
523
  */
514
- interface ZeitlichAgentConfig<T extends ToolMap, M = StoredMessage> {
515
- threadId: string;
524
+ interface AgentConfig {
525
+ /** The name of the agent, should be unique within the workflows, ideally Pascal Case */
516
526
  agentName: string;
517
527
  /** Description, used for sub agents */
518
528
  description?: string;
529
+ /** The system prompt to append to the thread */
519
530
  systemPrompt?: string;
531
+ }
532
+ /**
533
+ * Configuration for a Zeitlich agent session
534
+ */
535
+ interface SessionConfig<T extends ToolMap, M = StoredMessage> {
536
+ /** The thread ID to use for the session */
537
+ threadId: string;
538
+ /** Metadata for the session */
520
539
  metadata?: Record<string, unknown>;
540
+ /** Whether to append the system prompt as message to the thread */
521
541
  appendSystemPrompt?: boolean;
542
+ /** How many turns to run the session for */
522
543
  maxTurns?: number;
523
544
  /** Workflow-specific runAgent activity (with tools pre-bound) */
524
545
  runAgent: RunAgentActivity<M>;
@@ -537,6 +558,8 @@ interface ZeitlichAgentConfig<T extends ToolMap, M = StoredMessage> {
537
558
  * Returns MessageContent array for the initial HumanMessage.
538
559
  */
539
560
  buildContextMessage: () => MessageContent | Promise<MessageContent>;
561
+ /** How long to wait for input before cancelling the workflow */
562
+ waitForInputTimeout?: Duration;
540
563
  }
541
564
  /**
542
565
  * A JSON-serializable tool definition for state storage.
@@ -553,9 +576,10 @@ interface SerializableToolDefinition {
553
576
  /**
554
577
  * Configuration passed to runAgent activity
555
578
  */
556
- interface RunAgentConfig {
579
+ interface RunAgentConfig extends AgentConfig {
580
+ /** The thread ID to use for the session */
557
581
  threadId: string;
558
- agentName: string;
582
+ /** Metadata for the session */
559
583
  metadata?: Record<string, unknown>;
560
584
  }
561
585
  /**
@@ -584,7 +608,7 @@ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
584
608
  /** Description shown to the parent agent explaining what this subagent does */
585
609
  description: string;
586
610
  /** Whether this subagent is available (default: true). Disabled subagents are excluded from the Subagent tool. */
587
- enabled?: boolean;
611
+ enabled?: () => boolean;
588
612
  /** Temporal workflow function or type name (used with executeChild) */
589
613
  workflow: string | Workflow;
590
614
  /** Optional task queue - defaults to parent's queue if not specified */
@@ -745,6 +769,32 @@ interface SessionStartHookContext {
745
769
  * SessionStart hook - called when session begins
746
770
  */
747
771
  type SessionStartHook = (ctx: SessionStartHookContext) => void | Promise<void>;
772
+ /**
773
+ * Context for PreHumanMessageAppend hook - called before each human message is appended to the thread
774
+ */
775
+ interface PreHumanMessageAppendHookContext {
776
+ /** The message about to be appended */
777
+ message: MessageContent;
778
+ /** Thread identifier */
779
+ threadId: string;
780
+ }
781
+ /**
782
+ * PreHumanMessageAppend hook - called before each human message is appended to the thread
783
+ */
784
+ type PreHumanMessageAppendHook = (ctx: PreHumanMessageAppendHookContext) => void | Promise<void>;
785
+ /**
786
+ * PostHumanMessageAppend hook - called after each human message is appended to the thread
787
+ */
788
+ type PostHumanMessageAppendHook = (ctx: PostHumanMessageAppendHookContext) => void | Promise<void>;
789
+ /**
790
+ * Context for PostHumanMessageAppend hook - called after each human message is appended to the thread
791
+ */
792
+ interface PostHumanMessageAppendHookContext {
793
+ /** The message that was appended */
794
+ message: MessageContent;
795
+ /** Thread identifier */
796
+ threadId: string;
797
+ }
748
798
  /**
749
799
  * Context for SessionEnd hook - called when session ends
750
800
  */
@@ -795,6 +845,10 @@ interface ToolHooks<TArgs = unknown, TResult = unknown> {
795
845
  * Combined hooks interface for session lifecycle
796
846
  */
797
847
  interface Hooks<T extends ToolMap, TResult = unknown> {
848
+ /** Called before each human message is appended to the thread */
849
+ onPreHumanMessageAppend?: PreHumanMessageAppendHook;
850
+ /** Called after each human message is appended to the thread */
851
+ onPostHumanMessageAppend?: PostHumanMessageAppendHook;
798
852
  /** Called before each tool execution - can block or modify */
799
853
  onPreToolUse?: PreToolUseHook<T>;
800
854
  /** Called after each successful tool execution */
@@ -884,8 +938,24 @@ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
884
938
  deleteTask(id: string): boolean;
885
939
  /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
886
940
  setTools(newTools: ToolDefinition[]): void;
941
+ /** Update the usage */
942
+ updateUsage(usage: {
943
+ inputTokens?: number;
944
+ outputTokens?: number;
945
+ cachedWriteTokens?: number;
946
+ cachedReadTokens?: number;
947
+ reasonTokens?: number;
948
+ }): void;
949
+ /** Get the total usage */
950
+ getTotalUsage(): {
951
+ totalInputTokens: number;
952
+ totalOutputTokens: number;
953
+ totalCachedWriteTokens: number;
954
+ totalCachedReadTokens: number;
955
+ totalReasonTokens: number;
956
+ turns: number;
957
+ };
887
958
  }
888
- declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState, [], string>;
889
959
  /**
890
960
  * Creates an agent state manager for tracking workflow state.
891
961
  *
@@ -896,7 +966,10 @@ declare const getStateQuery: _temporalio_common.QueryDefinition<BaseAgentState,
896
966
  * in the workflow file using defineQuery/defineUpdate and setHandler.
897
967
  * This manager provides the state and logic needed for those handlers.
898
968
  */
899
- declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>(initialState?: Partial<BaseAgentState> & TCustom): AgentStateManager<TCustom>;
969
+ declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>({ initialState, agentConfig, }: {
970
+ initialState?: Partial<BaseAgentState> & TCustom;
971
+ agentConfig: AgentConfig;
972
+ }): AgentStateManager<TCustom>;
900
973
  /**
901
974
  * Handler names used across agents
902
975
  */
@@ -909,7 +982,11 @@ declare const AGENT_HANDLER_NAMES: {
909
982
  interface ZeitlichSession<M = unknown> {
910
983
  runSession<T extends JsonSerializable<T>>(args: {
911
984
  stateManager: AgentStateManager<T>;
912
- }): Promise<M | null>;
985
+ }): Promise<{
986
+ finalMessage: M | null;
987
+ exitReason: SessionExitReason;
988
+ usage: ReturnType<AgentStateManager<T>["getTotalUsage"]>;
989
+ }>;
913
990
  }
914
991
  /**
915
992
  * Session-level hooks for lifecycle events
@@ -920,7 +997,7 @@ interface SessionLifecycleHooks {
920
997
  /** Called when session ends */
921
998
  onSessionEnd?: SessionEndHook;
922
999
  }
923
- declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, appendSystemPrompt, systemPrompt, }: ZeitlichAgentConfig<T, M>) => Promise<ZeitlichSession<M>>;
1000
+ declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, description, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, appendSystemPrompt, systemPrompt, waitForInputTimeout, }: SessionConfig<T, M> & AgentConfig) => Promise<ZeitlichSession<M>>;
924
1001
  /**
925
1002
  * Proxy the default ZeitlichSharedActivities as ThreadOps<StoredMessage>.
926
1003
  * Call this in workflow code for the standard LangChain/StoredMessage setup.
@@ -971,24 +1048,6 @@ interface ZeitlichSharedActivities {
971
1048
  */
972
1049
  declare function createSharedActivities(redis: Redis): ZeitlichSharedActivities;
973
1050
 
974
- declare const askUserQuestionTool: {
975
- name: "AskUserQuestion";
976
- description: string;
977
- schema: z.ZodObject<{
978
- questions: z.ZodArray<z.ZodObject<{
979
- question: z.ZodString;
980
- header: z.ZodString;
981
- options: z.ZodArray<z.ZodObject<{
982
- label: z.ZodString;
983
- description: z.ZodString;
984
- }, z.core.$strip>>;
985
- multiSelect: z.ZodBoolean;
986
- }, z.core.$strip>>;
987
- }, z.core.$strip>;
988
- strict: true;
989
- };
990
- type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
991
-
992
1051
  declare const globTool: {
993
1052
  name: "Glob";
994
1053
  description: string;
@@ -1140,4 +1199,37 @@ declare const bashTool: {
1140
1199
  };
1141
1200
  type BashArgs = z.infer<typeof bashTool.schema>;
1142
1201
 
1143
- export { type ToolArgs 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 SubagentArgs as M, type SubagentConfig as N, type SubagentHooks as O, type ParsedToolCall as P, type SubagentInput as Q, type RawToolCall as R, type SessionEndHook as S, type TaskCreateArgs as T, type TaskGetArgs as U, type TaskListArgs as V, type TaskStatus as W, type TaskUpdateArgs as X, type ThreadManager as Y, type ThreadManagerConfig as Z, type ThreadOps as _, type ActivityToolHandler as a, type ToolCallResult as a0, type ToolCallResultUnion as a1, type ToolDefinition as a2, type ToolHandler as a3, type ToolHandlerContext as a4, type ToolHandlerResponse as a5, type ToolHooks as a6, type ToolMap as a7, type ToolMessageContent as a8, type ToolNames as a9, grepTool as aA, hasNoOtherToolCalls as aB, isTerminalStatus as aC, proxyDefaultThreadOps as aD, readTool as aE, taskCreateTool as aF, taskGetTool as aG, taskListTool as aH, taskUpdateTool as aI, withAutoAppend as aJ, writeTool as aK, type ToolResult as aa, type ToolResultConfig as ab, type ToolRouter as ac, type ToolWithHandler as ad, type WorkflowTask as ae, type ZeitlichAgentConfig as af, type ZeitlichSession as ag, type ZeitlichSharedActivities as ah, askUserQuestionTool as ai, bashTool as aj, createAgentStateManager as ak, createBashToolDescription as al, createSession as am, createSharedActivities as an, createSubagentTool as ao, createTaskCreateHandler as ap, createTaskGetHandler as aq, createTaskListHandler as ar, createTaskUpdateHandler as as, createThreadManager as at, createToolRouter as au, defineSubagent as av, defineTool as aw, editTool as ax, getStateQuery as ay, globTool 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 };
1202
+ declare const askUserQuestionTool: {
1203
+ name: "AskUserQuestion";
1204
+ description: string;
1205
+ schema: z.ZodObject<{
1206
+ questions: z.ZodArray<z.ZodObject<{
1207
+ question: z.ZodString;
1208
+ header: z.ZodString;
1209
+ options: z.ZodArray<z.ZodObject<{
1210
+ label: z.ZodString;
1211
+ description: z.ZodString;
1212
+ }, z.core.$strip>>;
1213
+ multiSelect: z.ZodBoolean;
1214
+ }, z.core.$strip>>;
1215
+ }, z.core.$strip>;
1216
+ strict: true;
1217
+ };
1218
+ type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
1219
+
1220
+ /**
1221
+ * Creates handler for user interaction tool - creates AI messages for display.
1222
+ */
1223
+ declare const createAskUserQuestionHandler: () => ToolHandler<AskUserQuestionArgs, {
1224
+ questions: {
1225
+ question: string;
1226
+ header: string;
1227
+ options: {
1228
+ label: string;
1229
+ description: string;
1230
+ }[];
1231
+ multiSelect: boolean;
1232
+ }[];
1233
+ }>;
1234
+
1235
+ export { type ThreadOps as $, type AgentResponse as A, type BashArgs as B, type RunAgentActivity as C, type RunAgentConfig as D, type SessionEndHookContext as E, type FileEditArgs as F, type GlobArgs as G, type SessionExitReason as H, type InferToolResults as I, type JsonPrimitive as J, type SessionLifecycleHooks as K, type SessionStartHook as L, type SessionStartHookContext as M, type SubagentArgs as N, type SubagentConfig as O, type ParsedToolCall as P, type SubagentHooks as Q, type RawToolCall as R, type SessionEndHook as S, type SubagentInput as T, type TaskCreateArgs as U, type TaskGetArgs 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, grepTool as aA, hasNoOtherToolCalls as aB, isTerminalStatus as aC, proxyDefaultThreadOps as aD, readTool as aE, taskCreateTool as aF, taskGetTool as aG, taskListTool as aH, taskUpdateTool as aI, withAutoAppend as aJ, writeTool as aK, 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 ZeitlichSession as ag, type ZeitlichSharedActivities as ah, askUserQuestionTool as ai, bashTool as aj, createAgentStateManager as ak, createAskUserQuestionHandler as al, createBashToolDescription as am, createSession as an, createSharedActivities as ao, createSubagentTool as ap, createTaskCreateHandler as aq, createTaskGetHandler as ar, createTaskListHandler as as, createTaskUpdateHandler as at, createThreadManager as au, createToolRouter as av, defineSubagent as aw, defineTool as ax, editTool as ay, globTool as az, AGENT_HANDLER_NAMES as b, type AgentConfig as c, type AgentFile as d, type AgentState as e, type AgentStateManager as f, type AgentStatus as g, type AppendToolResultFn as h, type AskUserQuestionArgs as i, type BaseAgentState as j, type BaseThreadManager as k, type FileReadArgs as l, type FileWriteArgs as m, type GrepArgs as n, type JsonSerializable as o, type JsonValue as p, type ParsedToolCallUnion as q, type PostToolUseFailureHook as r, type PostToolUseFailureHookContext as s, type PostToolUseFailureHookResult as t, type PostToolUseHook as u, type PostToolUseHookContext as v, type PreToolUseHook as w, type PreToolUseHookContext as x, type PreToolUseHookResult as y, type ProcessToolCallsContext as z };