zeitlich 0.2.7 → 0.2.9

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.
@@ -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.
@@ -566,9 +576,10 @@ interface SerializableToolDefinition {
566
576
  /**
567
577
  * Configuration passed to runAgent activity
568
578
  */
569
- interface RunAgentConfig {
579
+ interface RunAgentConfig extends AgentConfig {
580
+ /** The thread ID to use for the session */
570
581
  threadId: string;
571
- agentName: string;
582
+ /** Metadata for the session */
572
583
  metadata?: Record<string, unknown>;
573
584
  }
574
585
  /**
@@ -597,7 +608,7 @@ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
597
608
  /** Description shown to the parent agent explaining what this subagent does */
598
609
  description: string;
599
610
  /** Whether this subagent is available (default: true). Disabled subagents are excluded from the Subagent tool. */
600
- enabled?: boolean;
611
+ enabled?: () => boolean;
601
612
  /** Temporal workflow function or type name (used with executeChild) */
602
613
  workflow: string | Workflow;
603
614
  /** Optional task queue - defaults to parent's queue if not specified */
@@ -927,6 +938,23 @@ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
927
938
  deleteTask(id: string): boolean;
928
939
  /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
929
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
+ };
930
958
  }
931
959
  /**
932
960
  * Creates an agent state manager for tracking workflow state.
@@ -954,7 +982,11 @@ declare const AGENT_HANDLER_NAMES: {
954
982
  interface ZeitlichSession<M = unknown> {
955
983
  runSession<T extends JsonSerializable<T>>(args: {
956
984
  stateManager: AgentStateManager<T>;
957
- }): Promise<M | null>;
985
+ }): Promise<{
986
+ finalMessage: M | null;
987
+ exitReason: SessionExitReason;
988
+ usage: ReturnType<AgentStateManager<T>["getTotalUsage"]>;
989
+ }>;
958
990
  }
959
991
  /**
960
992
  * Session-level hooks for lifecycle events
@@ -965,7 +997,7 @@ interface SessionLifecycleHooks {
965
997
  /** Called when session ends */
966
998
  onSessionEnd?: SessionEndHook;
967
999
  }
968
- declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, appendSystemPrompt, systemPrompt, waitForInputTimeout, }: SessionConfig<T, M> & AgentConfig) => 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>>;
969
1001
  /**
970
1002
  * Proxy the default ZeitlichSharedActivities as ThreadOps<StoredMessage>.
971
1003
  * Call this in workflow code for the standard LangChain/StoredMessage setup.
@@ -1042,7 +1074,7 @@ declare const grepTool: {
1042
1074
  };
1043
1075
  type GrepArgs = z$1.infer<typeof grepTool.schema>;
1044
1076
 
1045
- declare const readTool: {
1077
+ declare const readFileTool: {
1046
1078
  name: "FileRead";
1047
1079
  description: string;
1048
1080
  schema: z$1.ZodObject<{
@@ -1052,9 +1084,9 @@ declare const readTool: {
1052
1084
  }, z$1.core.$strip>;
1053
1085
  strict: true;
1054
1086
  };
1055
- type FileReadArgs = z$1.infer<typeof readTool.schema>;
1087
+ type FileReadArgs = z$1.infer<typeof readFileTool.schema>;
1056
1088
 
1057
- declare const writeTool: {
1089
+ declare const writeFileTool: {
1058
1090
  name: "FileWrite";
1059
1091
  description: string;
1060
1092
  schema: z$1.ZodObject<{
@@ -1063,7 +1095,7 @@ declare const writeTool: {
1063
1095
  }, z$1.core.$strip>;
1064
1096
  strict: true;
1065
1097
  };
1066
- type FileWriteArgs = z$1.infer<typeof writeTool.schema>;
1098
+ type FileWriteArgs = z$1.infer<typeof writeFileTool.schema>;
1067
1099
 
1068
1100
  declare const editTool: {
1069
1101
  name: "FileEdit";
@@ -1188,7 +1220,7 @@ type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
1188
1220
  /**
1189
1221
  * Creates handler for user interaction tool - creates AI messages for display.
1190
1222
  */
1191
- declare const createAskUserQuestionHandler: () => ToolHandler<AskUserQuestionArgs, {
1223
+ declare const createAskUserQuestionHandler: () => ActivityToolHandler<AskUserQuestionArgs, {
1192
1224
  questions: {
1193
1225
  question: string;
1194
1226
  header: string;
@@ -1200,4 +1232,4 @@ declare const createAskUserQuestionHandler: () => ToolHandler<AskUserQuestionArg
1200
1232
  }[];
1201
1233
  }>;
1202
1234
 
1203
- 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 };
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, readFileTool as aE, taskCreateTool as aF, taskGetTool as aG, taskListTool as aH, taskUpdateTool as aI, withAutoAppend as aJ, writeFileTool 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 };
@@ -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.
@@ -566,9 +576,10 @@ interface SerializableToolDefinition {
566
576
  /**
567
577
  * Configuration passed to runAgent activity
568
578
  */
569
- interface RunAgentConfig {
579
+ interface RunAgentConfig extends AgentConfig {
580
+ /** The thread ID to use for the session */
570
581
  threadId: string;
571
- agentName: string;
582
+ /** Metadata for the session */
572
583
  metadata?: Record<string, unknown>;
573
584
  }
574
585
  /**
@@ -597,7 +608,7 @@ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
597
608
  /** Description shown to the parent agent explaining what this subagent does */
598
609
  description: string;
599
610
  /** Whether this subagent is available (default: true). Disabled subagents are excluded from the Subagent tool. */
600
- enabled?: boolean;
611
+ enabled?: () => boolean;
601
612
  /** Temporal workflow function or type name (used with executeChild) */
602
613
  workflow: string | Workflow;
603
614
  /** Optional task queue - defaults to parent's queue if not specified */
@@ -927,6 +938,23 @@ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
927
938
  deleteTask(id: string): boolean;
928
939
  /** Set the tools (converts Zod schemas to JSON Schema for serialization) */
929
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
+ };
930
958
  }
931
959
  /**
932
960
  * Creates an agent state manager for tracking workflow state.
@@ -954,7 +982,11 @@ declare const AGENT_HANDLER_NAMES: {
954
982
  interface ZeitlichSession<M = unknown> {
955
983
  runSession<T extends JsonSerializable<T>>(args: {
956
984
  stateManager: AgentStateManager<T>;
957
- }): Promise<M | null>;
985
+ }): Promise<{
986
+ finalMessage: M | null;
987
+ exitReason: SessionExitReason;
988
+ usage: ReturnType<AgentStateManager<T>["getTotalUsage"]>;
989
+ }>;
958
990
  }
959
991
  /**
960
992
  * Session-level hooks for lifecycle events
@@ -965,7 +997,7 @@ interface SessionLifecycleHooks {
965
997
  /** Called when session ends */
966
998
  onSessionEnd?: SessionEndHook;
967
999
  }
968
- declare const createSession: <T extends ToolMap, M = unknown>({ threadId, agentName, maxTurns, metadata, runAgent, threadOps, buildContextMessage, subagents, tools, processToolsInParallel, hooks, appendSystemPrompt, systemPrompt, waitForInputTimeout, }: SessionConfig<T, M> & AgentConfig) => 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>>;
969
1001
  /**
970
1002
  * Proxy the default ZeitlichSharedActivities as ThreadOps<StoredMessage>.
971
1003
  * Call this in workflow code for the standard LangChain/StoredMessage setup.
@@ -1042,7 +1074,7 @@ declare const grepTool: {
1042
1074
  };
1043
1075
  type GrepArgs = z$1.infer<typeof grepTool.schema>;
1044
1076
 
1045
- declare const readTool: {
1077
+ declare const readFileTool: {
1046
1078
  name: "FileRead";
1047
1079
  description: string;
1048
1080
  schema: z$1.ZodObject<{
@@ -1052,9 +1084,9 @@ declare const readTool: {
1052
1084
  }, z$1.core.$strip>;
1053
1085
  strict: true;
1054
1086
  };
1055
- type FileReadArgs = z$1.infer<typeof readTool.schema>;
1087
+ type FileReadArgs = z$1.infer<typeof readFileTool.schema>;
1056
1088
 
1057
- declare const writeTool: {
1089
+ declare const writeFileTool: {
1058
1090
  name: "FileWrite";
1059
1091
  description: string;
1060
1092
  schema: z$1.ZodObject<{
@@ -1063,7 +1095,7 @@ declare const writeTool: {
1063
1095
  }, z$1.core.$strip>;
1064
1096
  strict: true;
1065
1097
  };
1066
- type FileWriteArgs = z$1.infer<typeof writeTool.schema>;
1098
+ type FileWriteArgs = z$1.infer<typeof writeFileTool.schema>;
1067
1099
 
1068
1100
  declare const editTool: {
1069
1101
  name: "FileEdit";
@@ -1188,7 +1220,7 @@ type AskUserQuestionArgs = z.infer<typeof askUserQuestionTool.schema>;
1188
1220
  /**
1189
1221
  * Creates handler for user interaction tool - creates AI messages for display.
1190
1222
  */
1191
- declare const createAskUserQuestionHandler: () => ToolHandler<AskUserQuestionArgs, {
1223
+ declare const createAskUserQuestionHandler: () => ActivityToolHandler<AskUserQuestionArgs, {
1192
1224
  questions: {
1193
1225
  question: string;
1194
1226
  header: string;
@@ -1200,4 +1232,4 @@ declare const createAskUserQuestionHandler: () => ToolHandler<AskUserQuestionArg
1200
1232
  }[];
1201
1233
  }>;
1202
1234
 
1203
- 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 };
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, readFileTool as aE, taskCreateTool as aF, taskGetTool as aG, taskListTool as aH, taskUpdateTool as aI, withAutoAppend as aJ, writeFileTool 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 };
package/dist/workflow.cjs CHANGED
@@ -8,18 +8,18 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
  var z13__default = /*#__PURE__*/_interopDefault(z13);
9
9
 
10
10
  // src/lib/session.ts
11
- var SUBAGENT_TOOL = "Subagent";
11
+ var SUBAGENT_TOOL_NAME = "Subagent";
12
12
  function buildSubagentDescription(subagents) {
13
13
  const subagentList = subagents.map((s) => `- **${s.agentName}**: ${s.description}`).join("\n");
14
14
  return `Launch a new agent to handle complex tasks autonomously.
15
15
 
16
- The ${SUBAGENT_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
16
+ The ${SUBAGENT_TOOL_NAME} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
17
17
 
18
18
  Available agent types:
19
19
 
20
20
  ${subagentList}
21
21
 
22
- When using the ${SUBAGENT_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
22
+ When using the ${SUBAGENT_TOOL_NAME} tool, you must specify a subagent parameter to select which agent type to use.
23
23
 
24
24
  Usage notes:
25
25
 
@@ -38,7 +38,7 @@ function createSubagentTool(subagents) {
38
38
  }
39
39
  const names = subagents.map((s) => s.agentName);
40
40
  return {
41
- name: SUBAGENT_TOOL,
41
+ name: SUBAGENT_TOOL_NAME,
42
42
  description: buildSubagentDescription(subagents),
43
43
  schema: z13__default.default.object({
44
44
  subagent: z13__default.default.enum(names).describe("The type of subagent to launch"),
@@ -66,11 +66,12 @@ function createSubagentHandler(subagents) {
66
66
  args: [input],
67
67
  taskQueue: config.taskQueue ?? parentTaskQueue
68
68
  };
69
- const { toolResponse, data } = typeof config.workflow === "string" ? await workflow.executeChild(config.workflow, childOpts) : await workflow.executeChild(config.workflow, childOpts);
69
+ const { toolResponse, data, usage } = typeof config.workflow === "string" ? await workflow.executeChild(config.workflow, childOpts) : await workflow.executeChild(config.workflow, childOpts);
70
70
  const validated = config.resultSchema ? config.resultSchema.parse(data) : null;
71
71
  return {
72
72
  toolResponse,
73
- data: validated
73
+ data: validated,
74
+ ...usage && { usage }
74
75
  };
75
76
  };
76
77
  }
@@ -82,20 +83,17 @@ function createToolRouter(options) {
82
83
  for (const [_key, tool] of Object.entries(options.tools)) {
83
84
  toolMap.set(tool.name, tool);
84
85
  }
85
- const isEnabled = (tool) => tool.enabled !== false;
86
+ const isEnabled = (tool) => tool.enabled?.() ?? true;
86
87
  if (options.subagents) {
87
- const enabledSubagents = options.subagents.filter(
88
- (s) => s.enabled !== false
89
- );
90
- if (enabledSubagents.length > 0) {
88
+ if (options.subagents.length > 0) {
91
89
  const subagentHooksMap = /* @__PURE__ */ new Map();
92
- for (const s of enabledSubagents) {
90
+ for (const s of options.subagents) {
93
91
  if (s.hooks) subagentHooksMap.set(s.agentName, s.hooks);
94
92
  }
95
93
  const resolveSubagentName = (args) => args.subagent;
96
- toolMap.set("Subagent", {
97
- ...createSubagentTool(enabledSubagents),
98
- handler: createSubagentHandler(enabledSubagents),
94
+ toolMap.set(SUBAGENT_TOOL_NAME, {
95
+ ...createSubagentTool(options.subagents),
96
+ handler: createSubagentHandler(options.subagents),
99
97
  ...subagentHooksMap.size > 0 && {
100
98
  hooks: {
101
99
  onPreToolUse: async (ctx) => {
@@ -286,13 +284,19 @@ function createToolRouter(options) {
286
284
  return Array.from(toolMap.entries()).filter(([, tool]) => isEnabled(tool)).map(([name]) => name);
287
285
  },
288
286
  getToolDefinitions() {
289
- return Array.from(toolMap).filter(([, tool]) => isEnabled(tool)).map(([name, tool]) => ({
290
- name,
291
- description: tool.description,
292
- schema: tool.schema,
293
- strict: tool.strict,
294
- max_uses: tool.max_uses
295
- }));
287
+ const activeSubagents = options.subagents?.filter((subagent) => isEnabled(subagent)) ?? [];
288
+ return [
289
+ ...Array.from(toolMap).filter(
290
+ ([, tool]) => isEnabled(tool) && tool.name !== SUBAGENT_TOOL_NAME
291
+ ).map(([name, tool]) => ({
292
+ name,
293
+ description: tool.description,
294
+ schema: tool.schema,
295
+ strict: tool.strict,
296
+ max_uses: tool.max_uses
297
+ })),
298
+ ...activeSubagents.length > 0 ? [createSubagentTool(activeSubagents)] : []
299
+ ];
296
300
  },
297
301
  // --- Methods for processing tool calls ---
298
302
  async processToolCalls(toolCalls, context) {
@@ -386,6 +390,7 @@ function hasNoOtherToolCalls(toolCalls, excludeName) {
386
390
  var createSession = async ({
387
391
  threadId,
388
392
  agentName,
393
+ description,
389
394
  maxTurns = 50,
390
395
  metadata = {},
391
396
  runAgent,
@@ -425,7 +430,9 @@ var createSession = async ({
425
430
  }
426
431
  };
427
432
  return {
428
- runSession: async ({ stateManager }) => {
433
+ runSession: async ({
434
+ stateManager
435
+ }) => {
429
436
  workflow.setHandler(
430
437
  workflow.defineUpdate(`add${agentName}Message`),
431
438
  async (message) => {
@@ -452,7 +459,6 @@ var createSession = async ({
452
459
  metadata
453
460
  });
454
461
  }
455
- stateManager.setTools(toolRouter.getToolDefinitions());
456
462
  await initializeThread(threadId);
457
463
  if (appendSystemPrompt && systemPrompt && systemPrompt.trim() !== "") {
458
464
  await appendSystemMessage(threadId, systemPrompt);
@@ -463,15 +469,25 @@ var createSession = async ({
463
469
  while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
464
470
  stateManager.incrementTurns();
465
471
  const currentTurn = stateManager.getTurns();
466
- const { message, rawToolCalls } = await runAgent({
472
+ stateManager.setTools(toolRouter.getToolDefinitions());
473
+ const { message, rawToolCalls, usage } = await runAgent({
467
474
  threadId,
468
475
  agentName,
469
- metadata
476
+ metadata,
477
+ systemPrompt,
478
+ description
470
479
  });
480
+ if (usage) {
481
+ stateManager.updateUsage(usage);
482
+ }
471
483
  if (!toolRouter.hasTools() || rawToolCalls.length === 0) {
472
484
  stateManager.complete();
473
485
  exitReason = "completed";
474
- return message;
486
+ return {
487
+ finalMessage: message,
488
+ exitReason,
489
+ usage: stateManager.getTotalUsage()
490
+ };
475
491
  }
476
492
  const parsedToolCalls = [];
477
493
  for (const tc of rawToolCalls) {
@@ -488,9 +504,17 @@ var createSession = async ({
488
504
  });
489
505
  }
490
506
  }
491
- await toolRouter.processToolCalls(parsedToolCalls, {
492
- turn: currentTurn
493
- });
507
+ const toolCallResults = await toolRouter.processToolCalls(
508
+ parsedToolCalls,
509
+ {
510
+ turn: currentTurn
511
+ }
512
+ );
513
+ for (const result of toolCallResults) {
514
+ if (result.usage) {
515
+ stateManager.updateUsage(result.usage);
516
+ }
517
+ }
494
518
  if (stateManager.getStatus() === "WAITING_FOR_INPUT") {
495
519
  const conditionMet = await workflow.condition(
496
520
  () => stateManager.getStatus() === "RUNNING",
@@ -512,7 +536,11 @@ var createSession = async ({
512
536
  } finally {
513
537
  await callSessionEnd(exitReason, stateManager.getTurns());
514
538
  }
515
- return null;
539
+ return {
540
+ finalMessage: null,
541
+ exitReason,
542
+ usage: stateManager.getTotalUsage()
543
+ };
516
544
  }
517
545
  };
518
546
  };
@@ -549,6 +577,11 @@ function createAgentStateManager({
549
577
  let version = initialState?.version ?? 0;
550
578
  let turns = initialState?.turns ?? 0;
551
579
  let tools = initialState?.tools ?? [];
580
+ let totalInputTokens = 0;
581
+ let totalOutputTokens = 0;
582
+ let totalCachedWriteTokens = 0;
583
+ let totalCachedReadTokens = 0;
584
+ let totalReasonTokens = 0;
552
585
  const tasks = new Map(initialState?.tasks);
553
586
  const {
554
587
  status: _,
@@ -663,6 +696,23 @@ function createAgentStateManager({
663
696
  version++;
664
697
  }
665
698
  return deleted;
699
+ },
700
+ updateUsage(usage) {
701
+ totalInputTokens += usage.inputTokens ?? 0;
702
+ totalOutputTokens += usage.outputTokens ?? 0;
703
+ totalCachedWriteTokens += usage.cachedWriteTokens ?? 0;
704
+ totalCachedReadTokens += usage.cachedReadTokens ?? 0;
705
+ totalReasonTokens += usage.reasonTokens ?? 0;
706
+ },
707
+ getTotalUsage() {
708
+ return {
709
+ totalInputTokens,
710
+ totalOutputTokens,
711
+ totalCachedWriteTokens,
712
+ totalCachedReadTokens,
713
+ totalReasonTokens,
714
+ turns
715
+ };
666
716
  }
667
717
  };
668
718
  }
@@ -715,7 +765,7 @@ Examples:
715
765
  }),
716
766
  strict: true
717
767
  };
718
- var readTool = {
768
+ var readFileTool = {
719
769
  name: "FileRead",
720
770
  description: `Read file contents with optional pagination.
721
771
 
@@ -738,22 +788,21 @@ The tool returns the file content in an appropriate format:
738
788
  }),
739
789
  strict: true
740
790
  };
741
- var writeTool = {
791
+ var writeFileTool = {
742
792
  name: "FileWrite",
743
793
  description: `Create or overwrite a file with new content.
744
794
 
745
795
  Usage:
746
- - Provide the absolute path to the file
747
796
  - The file will be created if it doesn't exist
748
797
  - If the file exists, it will be completely overwritten
749
798
 
750
799
  IMPORTANT:
751
800
  - You must read the file first (in this session) before writing to it
752
801
  - This is an atomic write operation - the entire file is replaced
753
- - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
802
+ - Path must be relative to the root of the file system (e.g., "docs/readme.md", not "/docs/readme.md")
754
803
  `,
755
804
  schema: z13.z.object({
756
- file_path: z13.z.string().describe("The absolute path to the file to write"),
805
+ file_path: z13.z.string().describe("The path to the file to write"),
757
806
  content: z13.z.string().describe("The content to write to the file")
758
807
  }),
759
808
  strict: true
@@ -1015,7 +1064,7 @@ Usage notes:
1015
1064
  };
1016
1065
 
1017
1066
  // src/tools/ask-user-question/handler.ts
1018
- var createAskUserQuestionHandler = () => (args) => {
1067
+ var createAskUserQuestionHandler = () => async (args) => {
1019
1068
  return {
1020
1069
  toolResponse: "Question submitted",
1021
1070
  data: { questions: args.questions }
@@ -1043,11 +1092,11 @@ exports.grepTool = grepTool;
1043
1092
  exports.hasNoOtherToolCalls = hasNoOtherToolCalls;
1044
1093
  exports.isTerminalStatus = isTerminalStatus;
1045
1094
  exports.proxyDefaultThreadOps = proxyDefaultThreadOps;
1046
- exports.readTool = readTool;
1095
+ exports.readFileTool = readFileTool;
1047
1096
  exports.taskCreateTool = taskCreateTool;
1048
1097
  exports.taskGetTool = taskGetTool;
1049
1098
  exports.taskListTool = taskListTool;
1050
1099
  exports.taskUpdateTool = taskUpdateTool;
1051
- exports.writeTool = writeTool;
1100
+ exports.writeFileTool = writeFileTool;
1052
1101
  //# sourceMappingURL=workflow.cjs.map
1053
1102
  //# sourceMappingURL=workflow.cjs.map