zeitlich 0.2.13 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +49 -38
  2. package/dist/adapters/sandbox/daytona/index.cjs +205 -0
  3. package/dist/adapters/sandbox/daytona/index.cjs.map +1 -0
  4. package/dist/adapters/sandbox/daytona/index.d.cts +86 -0
  5. package/dist/adapters/sandbox/daytona/index.d.ts +86 -0
  6. package/dist/adapters/sandbox/daytona/index.js +202 -0
  7. package/dist/adapters/sandbox/daytona/index.js.map +1 -0
  8. package/dist/adapters/sandbox/inmemory/index.cjs +174 -0
  9. package/dist/adapters/sandbox/inmemory/index.cjs.map +1 -0
  10. package/dist/adapters/sandbox/inmemory/index.d.cts +28 -0
  11. package/dist/adapters/sandbox/inmemory/index.d.ts +28 -0
  12. package/dist/adapters/sandbox/inmemory/index.js +172 -0
  13. package/dist/adapters/sandbox/inmemory/index.js.map +1 -0
  14. package/dist/adapters/sandbox/virtual/index.cjs +405 -0
  15. package/dist/adapters/sandbox/virtual/index.cjs.map +1 -0
  16. package/dist/adapters/sandbox/virtual/index.d.cts +85 -0
  17. package/dist/adapters/sandbox/virtual/index.d.ts +85 -0
  18. package/dist/adapters/sandbox/virtual/index.js +400 -0
  19. package/dist/adapters/sandbox/virtual/index.js.map +1 -0
  20. package/dist/adapters/thread/google-genai/index.cjs +284 -0
  21. package/dist/adapters/thread/google-genai/index.cjs.map +1 -0
  22. package/dist/adapters/thread/google-genai/index.d.cts +145 -0
  23. package/dist/adapters/thread/google-genai/index.d.ts +145 -0
  24. package/dist/adapters/thread/google-genai/index.js +278 -0
  25. package/dist/adapters/thread/google-genai/index.js.map +1 -0
  26. package/dist/adapters/{langchain → thread/langchain}/index.cjs +7 -9
  27. package/dist/adapters/thread/langchain/index.cjs.map +1 -0
  28. package/dist/adapters/{langchain → thread/langchain}/index.d.cts +17 -21
  29. package/dist/adapters/{langchain → thread/langchain}/index.d.ts +17 -21
  30. package/dist/adapters/{langchain → thread/langchain}/index.js +7 -9
  31. package/dist/adapters/thread/langchain/index.js.map +1 -0
  32. package/dist/index.cjs +816 -545
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +235 -74
  35. package/dist/index.d.ts +235 -74
  36. package/dist/index.js +804 -540
  37. package/dist/index.js.map +1 -1
  38. package/dist/types-B4C9txdq.d.ts +389 -0
  39. package/dist/{thread-manager-qc0g5Rvd.d.cts → types-B9ljZewB.d.cts} +1 -6
  40. package/dist/{thread-manager-qc0g5Rvd.d.ts → types-B9ljZewB.d.ts} +1 -6
  41. package/dist/types-BMXzv7TN.d.cts +476 -0
  42. package/dist/types-BMXzv7TN.d.ts +476 -0
  43. package/dist/types-BVP87m_W.d.cts +121 -0
  44. package/dist/types-CDubRtad.d.cts +115 -0
  45. package/dist/types-CDubRtad.d.ts +115 -0
  46. package/dist/types-CwwgQ_9H.d.ts +121 -0
  47. package/dist/types-GpMU4b0w.d.cts +389 -0
  48. package/dist/workflow.cjs +444 -318
  49. package/dist/workflow.cjs.map +1 -1
  50. package/dist/workflow.d.cts +271 -222
  51. package/dist/workflow.d.ts +271 -222
  52. package/dist/workflow.js +440 -316
  53. package/dist/workflow.js.map +1 -1
  54. package/package.json +59 -6
  55. package/src/adapters/sandbox/daytona/filesystem.ts +136 -0
  56. package/src/adapters/sandbox/daytona/index.ts +149 -0
  57. package/src/adapters/sandbox/daytona/types.ts +34 -0
  58. package/src/adapters/sandbox/inmemory/index.ts +213 -0
  59. package/src/adapters/sandbox/virtual/filesystem.ts +345 -0
  60. package/src/adapters/sandbox/virtual/index.ts +88 -0
  61. package/src/adapters/sandbox/virtual/mutations.ts +38 -0
  62. package/src/adapters/sandbox/virtual/provider.ts +101 -0
  63. package/src/adapters/sandbox/virtual/tree.ts +82 -0
  64. package/src/adapters/sandbox/virtual/types.ts +127 -0
  65. package/src/adapters/sandbox/virtual/virtual-sandbox.test.ts +523 -0
  66. package/src/adapters/sandbox/virtual/with-virtual-sandbox.ts +91 -0
  67. package/src/adapters/thread/google-genai/activities.ts +121 -0
  68. package/src/adapters/thread/google-genai/index.ts +41 -0
  69. package/src/adapters/thread/google-genai/model-invoker.ts +154 -0
  70. package/src/adapters/thread/google-genai/thread-manager.ts +169 -0
  71. package/src/adapters/{langchain → thread/langchain}/activities.ts +11 -15
  72. package/src/adapters/{langchain → thread/langchain}/index.ts +1 -1
  73. package/src/adapters/{langchain → thread/langchain}/model-invoker.ts +15 -18
  74. package/src/adapters/{langchain → thread/langchain}/thread-manager.ts +1 -1
  75. package/src/index.ts +32 -24
  76. package/src/lib/activity.ts +87 -0
  77. package/src/lib/hooks/index.ts +11 -0
  78. package/src/lib/hooks/types.ts +98 -0
  79. package/src/lib/model/helpers.ts +6 -0
  80. package/src/lib/model/index.ts +13 -0
  81. package/src/lib/{model-invoker.ts → model/types.ts} +18 -1
  82. package/src/lib/sandbox/index.ts +19 -0
  83. package/src/lib/sandbox/manager.ts +76 -0
  84. package/src/lib/sandbox/sandbox.test.ts +158 -0
  85. package/src/lib/{fs.ts → sandbox/tree.ts} +6 -6
  86. package/src/lib/sandbox/types.ts +164 -0
  87. package/src/lib/session/index.ts +11 -0
  88. package/src/lib/{session.ts → session/session.ts} +76 -48
  89. package/src/lib/session/types.ts +93 -0
  90. package/src/lib/skills/fs-provider.ts +16 -15
  91. package/src/lib/skills/handler.ts +31 -0
  92. package/src/lib/skills/index.ts +5 -1
  93. package/src/lib/skills/register.ts +20 -0
  94. package/src/lib/skills/tool.ts +47 -0
  95. package/src/lib/state/index.ts +9 -0
  96. package/src/lib/{state-manager.ts → state/manager.ts} +10 -147
  97. package/src/lib/state/types.ts +134 -0
  98. package/src/lib/subagent/define.ts +71 -0
  99. package/src/lib/subagent/handler.ts +99 -0
  100. package/src/lib/subagent/index.ts +13 -0
  101. package/src/lib/subagent/register.ts +53 -0
  102. package/src/lib/subagent/tool.ts +80 -0
  103. package/src/lib/subagent/types.ts +92 -0
  104. package/src/lib/thread/index.ts +7 -0
  105. package/src/lib/{thread-manager.ts → thread/manager.ts} +1 -33
  106. package/src/lib/thread/types.ts +33 -0
  107. package/src/lib/tool-router/auto-append.ts +55 -0
  108. package/src/lib/tool-router/index.ts +41 -0
  109. package/src/lib/tool-router/router.ts +462 -0
  110. package/src/lib/tool-router/types.ts +478 -0
  111. package/src/lib/tool-router/with-sandbox.ts +70 -0
  112. package/src/lib/types.ts +5 -382
  113. package/src/tools/bash/bash.test.ts +53 -55
  114. package/src/tools/bash/handler.ts +23 -51
  115. package/src/tools/edit/handler.ts +67 -81
  116. package/src/tools/glob/handler.ts +60 -17
  117. package/src/tools/read-file/handler.ts +67 -0
  118. package/src/tools/read-skill/handler.ts +1 -31
  119. package/src/tools/read-skill/tool.ts +5 -47
  120. package/src/tools/subagent/handler.ts +1 -100
  121. package/src/tools/subagent/tool.ts +5 -93
  122. package/src/tools/task-create/handler.ts +1 -1
  123. package/src/tools/task-get/handler.ts +1 -1
  124. package/src/tools/task-list/handler.ts +1 -1
  125. package/src/tools/task-update/handler.ts +1 -1
  126. package/src/tools/write-file/handler.ts +47 -0
  127. package/src/workflow.ts +88 -47
  128. package/tsup.config.ts +8 -1
  129. package/dist/adapters/langchain/index.cjs.map +0 -1
  130. package/dist/adapters/langchain/index.js.map +0 -1
  131. package/dist/model-invoker-y_zlyMqu.d.cts +0 -892
  132. package/dist/model-invoker-y_zlyMqu.d.ts +0 -892
  133. package/src/lib/tool-router.ts +0 -977
  134. package/src/lib/workflow-helpers.ts +0 -50
  135. /package/src/lib/{thread-id.ts → thread/id.ts} +0 -0
@@ -1,892 +0,0 @@
1
- import z, { z as z$1 } from 'zod';
2
- import { Duration } from '@temporalio/common';
3
-
4
- /**
5
- * Skill metadata — the lightweight subset loaded at startup for all skills.
6
- * Follows the agentskills.io specification frontmatter fields.
7
- */
8
- interface SkillMetadata {
9
- /** Lowercase alphanumeric + hyphens, max 64 chars, must match directory name */
10
- name: string;
11
- /** What the skill does and when to use it (max 1024 chars) */
12
- description: string;
13
- /** License name or reference to a bundled license file */
14
- license?: string;
15
- /** Environment requirements (intended product, system packages, network access) */
16
- compatibility?: string;
17
- /** Arbitrary key-value pairs for additional metadata */
18
- metadata?: Record<string, string>;
19
- /** Space-delimited list of pre-approved tools the skill may use */
20
- allowedTools?: string[];
21
- }
22
- /**
23
- * A fully-loaded skill including the SKILL.md instruction body.
24
- * Progressive disclosure: metadata is always available, instructions
25
- * are loaded on-demand via the ReadSkill tool.
26
- */
27
- interface Skill extends SkillMetadata {
28
- /** The markdown body of SKILL.md (everything after the frontmatter) */
29
- instructions: string;
30
- }
31
- /**
32
- * Abstraction for discovering and loading skills.
33
- *
34
- * Implement this interface to provide skills from any source
35
- * (filesystem, database, API, in-memory, etc.).
36
- */
37
- interface SkillProvider {
38
- /** Return lightweight metadata for all available skills */
39
- listSkills(): Promise<SkillMetadata[]>;
40
- /** Load a single skill with full instructions by name */
41
- getSkill(name: string): Promise<Skill>;
42
- }
43
-
44
- declare const SUBAGENT_TOOL_NAME: "Subagent";
45
- /**
46
- * Creates a Subagent tool configured with the available subagents.
47
- *
48
- * @param subagents - Array of subagent configurations (must have at least one)
49
- * @returns A tool definition with dynamic schema based on available subagents
50
- *
51
- * @example
52
- * const subagentTool = createSubagentTool([
53
- * {
54
- * agentName: "researcher",
55
- * description: "Researches topics and gathers information",
56
- * workflow: "researcherWorkflow",
57
- * resultSchema: z.object({ findings: z.string() }),
58
- * },
59
- * ]);
60
- */
61
- declare function createSubagentTool<T extends SubagentConfig[]>(subagents: T): {
62
- readonly name: typeof SUBAGENT_TOOL_NAME;
63
- readonly description: string;
64
- readonly schema: z.ZodObject<z.ZodRawShape>;
65
- };
66
- /**
67
- * Subagent tool args type (when subagent names are not known at compile time)
68
- */
69
- type SubagentArgs = {
70
- subagent: string;
71
- description: string;
72
- prompt: string;
73
- threadId?: string;
74
- };
75
-
76
- /**
77
- * A tool definition with a name, description, and Zod schema for arguments.
78
- * Does not include a handler - use ToolWithHandler for tools with handlers.
79
- */
80
- interface ToolDefinition<TName extends string = string, TSchema extends z$1.ZodType = z$1.ZodType> {
81
- name: TName;
82
- description: string;
83
- schema: TSchema;
84
- strict?: boolean;
85
- max_uses?: number;
86
- }
87
- /**
88
- * A tool definition with an integrated handler function.
89
- * This is the primary type for defining tools in the router.
90
- */
91
- interface ToolWithHandler<TName extends string = string, TSchema extends z$1.ZodType = z$1.ZodType, TResult = unknown, TContext = ToolHandlerContext> {
92
- name: TName;
93
- description: string;
94
- schema: TSchema;
95
- handler: ToolHandler<z$1.infer<TSchema>, TResult, TContext>;
96
- strict?: boolean;
97
- max_uses?: number;
98
- /** Whether this tool is available to the agent (default: true). Disabled tools are excluded from definitions and rejected at parse time. */
99
- enabled?: boolean;
100
- /** Per-tool lifecycle hooks (run in addition to global hooks) */
101
- hooks?: ToolHooks<z$1.infer<TSchema>, TResult>;
102
- }
103
- /**
104
- * A map of tool keys to tool definitions with handlers.
105
- *
106
- * Handler uses `any` intentionally — this is a type-system boundary where heterogeneous
107
- * tool types are stored together. Type safety for individual tools is enforced by
108
- * `defineTool()` at the definition site and generic inference utilities like
109
- * `InferToolResults<T>` at the consumption site.
110
- */
111
- type ToolMap = Record<string, {
112
- name: string;
113
- description: string;
114
- schema: z$1.ZodType;
115
- handler: ToolHandler<any, any, any>;
116
- strict?: boolean;
117
- max_uses?: number;
118
- enabled?: boolean;
119
- hooks?: ToolHooks<any, any>;
120
- }>;
121
- /**
122
- * Extract the tool names from a tool map (uses the tool's name property, not the key).
123
- */
124
- type ToolNames<T extends ToolMap> = T[keyof T]["name"];
125
- /**
126
- * A raw tool call as received from the LLM before parsing.
127
- */
128
- interface RawToolCall {
129
- id?: string;
130
- name: string;
131
- args: unknown;
132
- }
133
- /**
134
- * A parsed tool call with validated arguments for a specific tool.
135
- */
136
- interface ParsedToolCall<TName extends string = string, TArgs = unknown> {
137
- id: string;
138
- name: TName;
139
- args: TArgs;
140
- }
141
- /**
142
- * Union type of all possible parsed tool calls from a tool map.
143
- */
144
- type ParsedToolCallUnion<T extends ToolMap> = {
145
- [K in keyof T]: ParsedToolCall<T[K]["name"], z$1.infer<T[K]["schema"]>>;
146
- }[keyof T];
147
- /**
148
- * Function signature for appending tool results to a thread.
149
- */
150
- type AppendToolResultFn = (config: ToolResultConfig) => Promise<void>;
151
- /**
152
- * The response from a tool handler.
153
- * Contains the content for the tool message and the result to return from processToolCalls.
154
- *
155
- * Tools that don't return additional data should use `data: null` (TResult defaults to null).
156
- * Tools that may fail to produce data should type TResult as `SomeType | null`.
157
- */
158
- interface ToolHandlerResponse<TResult = null> {
159
- /** Content sent back to the LLM as the tool call response */
160
- toolResponse: ToolMessageContent;
161
- /** Data returned to the workflow and hooks for further processing */
162
- data: TResult;
163
- /**
164
- * When true, the tool result has already been appended to the thread
165
- * by the handler itself (e.g. via `withAutoAppend`), so the router
166
- * will skip the `appendToolResult` call. This avoids sending large
167
- * payloads through Temporal's activity payload limit.
168
- */
169
- resultAppended?: boolean;
170
- /** Token usage from the tool execution (e.g. child agent invocations) */
171
- usage?: TokenUsage;
172
- /** Thread ID used by the handler (surfaced to the LLM for subagent thread continuation) */
173
- threadId?: string;
174
- }
175
- /**
176
- * Context passed to tool handlers for additional data beyond tool args.
177
- * Use this to pass workflow state like file trees, user context, etc.
178
- * Generic so callers can type the context shape, e.g. ToolHandlerContext<ControlTestFsParams>.
179
- */
180
- type ToolHandlerContext<T = Record<string, unknown>> = T;
181
- /**
182
- * A handler function for a specific tool.
183
- * Receives the parsed args and context, returns a response with content and result.
184
- * Context always has a value (defaults to empty object if not provided).
185
- */
186
- type ToolHandler<TArgs, TResult, TContext = ToolHandlerContext> = (args: TArgs, context: TContext) => ToolHandlerResponse<TResult> | Promise<ToolHandlerResponse<TResult>>;
187
- /**
188
- * Activity-compatible tool handler that always returns a Promise.
189
- * Use this for tool handlers registered as Temporal activities.
190
- * Context always has a value (defaults to empty object if not provided).
191
- *
192
- * @example
193
- * ```typescript
194
- * // Filesystem handler with context
195
- * const readHandler: ActivityToolHandler<
196
- * FileReadArgs,
197
- * ReadResult,
198
- * { scopedNodes: FileNode[]; provider: FileSystemProvider }
199
- * > = async (args, context) => {
200
- * return readHandler(args, context.scopedNodes, context.provider);
201
- * };
202
- * ```
203
- */
204
- type ActivityToolHandler<TArgs, TResult, TContext = ToolHandlerContext> = (args: TArgs, context: TContext) => Promise<ToolHandlerResponse<TResult>>;
205
- /**
206
- * Extract the args type for a specific tool name from a tool map.
207
- */
208
- type ToolArgs<T extends ToolMap, TName extends ToolNames<T>> = z$1.infer<Extract<T[keyof T], {
209
- name: TName;
210
- }>["schema"]>;
211
- /**
212
- * Extract the result type for a specific tool name from a tool map.
213
- */
214
- type ToolResult<T extends ToolMap, TName extends ToolNames<T>> = Extract<T[keyof T], {
215
- name: TName;
216
- }>["handler"] extends ToolHandler<unknown, infer R, unknown> ? Awaited<R> : never;
217
- /**
218
- * The result of processing a tool call.
219
- */
220
- interface ToolCallResult<TName extends string = string, TResult = unknown> {
221
- toolCallId: string;
222
- name: TName;
223
- data: TResult;
224
- usage?: TokenUsage;
225
- }
226
- /**
227
- * Options for creating a tool router.
228
- */
229
- interface ToolRouterOptions<T extends ToolMap> {
230
- /** Map of tools with their handlers */
231
- tools: T;
232
- /** Thread ID for appending tool results */
233
- threadId: string;
234
- /** Function to append tool results to the thread (called automatically after each handler) */
235
- appendToolResult: AppendToolResultFn;
236
- /** Whether to process tools in parallel (default: true) */
237
- parallel?: boolean;
238
- /** Lifecycle hooks for tool execution */
239
- hooks?: Hooks<T, ToolCallResultUnion<InferToolResults<T>>>;
240
- /** Subagent configurations */
241
- subagents?: SubagentConfig[];
242
- /** Skills available to the agent (auto-adds ReadSkill tool when non-empty) */
243
- skills?: Skill[];
244
- }
245
- /**
246
- * Infer result types from a tool map based on handler return types.
247
- */
248
- type InferToolResults<T extends ToolMap> = {
249
- [K in keyof T as T[K]["name"]]: T[K]["handler"] extends ToolHandler<any, infer R, any> ? Awaited<R> : never;
250
- };
251
- /**
252
- * Union of all possible tool call results based on handler return types.
253
- */
254
- type ToolCallResultUnion<TResults extends Record<string, unknown>> = {
255
- [TName in keyof TResults & string]: ToolCallResult<TName, TResults[TName]>;
256
- }[keyof TResults & string];
257
- /**
258
- * Context passed to processToolCalls for hook execution and handler invocation
259
- */
260
- interface ProcessToolCallsContext<THandlerContext = ToolHandlerContext> {
261
- /** Current turn number (for hooks) */
262
- turn?: number;
263
- /** Context passed to each tool handler (scopedNodes, provider, etc.) */
264
- handlerContext?: THandlerContext;
265
- }
266
- /**
267
- * The tool router interface with full type inference for both args and results.
268
- */
269
- interface ToolRouter<T extends ToolMap> {
270
- /** Check if the router has any tools */
271
- hasTools(): boolean;
272
- /**
273
- * Parse and validate a raw tool call against the router's tools.
274
- * Returns a typed tool call with validated arguments.
275
- */
276
- parseToolCall(toolCall: RawToolCall): ParsedToolCallUnion<T>;
277
- /**
278
- * Check if a tool with the given name exists in the router.
279
- */
280
- hasTool(name: string): boolean;
281
- /**
282
- * Get all tool names in the router.
283
- */
284
- getToolNames(): ToolNames<T>[];
285
- /**
286
- * Get all tool definitions (without handlers) for passing to LLM.
287
- */
288
- getToolDefinitions(): ToolDefinition[];
289
- /**
290
- * Process all tool calls using the registered handlers.
291
- * Returns typed results based on handler return types.
292
- * @param toolCalls - Array of parsed tool calls to process
293
- * @param context - Optional context including turn number for hooks
294
- */
295
- processToolCalls(toolCalls: ParsedToolCallUnion<T>[], context?: ProcessToolCallsContext): Promise<ToolCallResultUnion<InferToolResults<T>>[]>;
296
- /**
297
- * Process tool calls matching a specific name with a custom handler.
298
- * Useful for overriding the default handler for specific cases.
299
- */
300
- processToolCallsByName<TName extends ToolNames<T>, TResult, TContext = ToolHandlerContext>(toolCalls: ParsedToolCallUnion<T>[], toolName: TName, handler: ToolHandler<ToolArgs<T, TName>, TResult, TContext>, context?: ProcessToolCallsContext<TContext>): Promise<ToolCallResult<TName, TResult>[]>;
301
- /**
302
- * Filter tool calls by name.
303
- */
304
- filterByName<TName extends ToolNames<T>>(toolCalls: ParsedToolCallUnion<T>[], name: TName): ParsedToolCall<TName, ToolArgs<T, TName>>[];
305
- /**
306
- * Check if any tool call matches the given name.
307
- */
308
- hasToolCall(toolCalls: ParsedToolCallUnion<T>[], name: ToolNames<T>): boolean;
309
- /**
310
- * Filter results by tool name.
311
- */
312
- getResultsByName<TName extends ToolNames<T>>(results: ToolCallResultUnion<InferToolResults<T>>[], name: TName): ToolCallResult<TName, ToolResult<T, TName>>[];
313
- }
314
- /**
315
- * Creates a tool router for declarative tool call processing.
316
- * Combines tool definitions with handlers in a single API.
317
- *
318
- * @example
319
- * ```typescript
320
- * const router = createToolRouter({
321
- * threadId,
322
- * tools: {
323
- * Read: {
324
- * name: "FileRead",
325
- * description: "Read file contents",
326
- * schema: z.object({ path: z.string() }),
327
- * handler: async (args, ctx) => ({
328
- * content: `Read ${args.path}`,
329
- * result: { path: args.path, content: "..." },
330
- * }),
331
- * },
332
- * },
333
- * hooks: { onPreToolUse, onPostToolUse },
334
- * });
335
- *
336
- * // Parse raw tool calls from LLM
337
- * const parsed = router.parseToolCall(rawToolCall);
338
- *
339
- * // Process tool calls
340
- * const results = await router.processToolCalls([parsed]);
341
- * ```
342
- */
343
- declare function createToolRouter<T extends ToolMap>(options: ToolRouterOptions<T>): ToolRouter<T>;
344
- /**
345
- * Wraps a tool handler to automatically append its result directly to the
346
- * thread and sets `resultAppended: true` on the response.
347
- *
348
- * Use this for tools whose responses may exceed Temporal's activity payload
349
- * limit. The wrapper appends to the thread inside the activity (where Redis
350
- * is available), then replaces `toolResponse` with an empty string so the
351
- * large payload never travels through the Temporal workflow boundary.
352
- *
353
- * @param getThread - Factory that returns a thread manager for the given threadId
354
- * @param handler - The original tool handler
355
- * @returns A wrapped handler that auto-appends and flags the response
356
- *
357
- * @example
358
- * ```typescript
359
- * import { withAutoAppend } from '@bead-ai/zeitlich/workflow';
360
- * import { createThreadManager } from '@bead-ai/zeitlich';
361
- *
362
- * const handler = withAutoAppend(
363
- * (threadId) => createThreadManager({ redis, threadId }),
364
- * async (args, ctx) => ({
365
- * toolResponse: JSON.stringify(largeResult), // appended directly to Redis
366
- * data: { summary: "..." }, // small data for workflow
367
- * }),
368
- * );
369
- * ```
370
- */
371
- declare function withAutoAppend<TArgs, TResult, TContext extends ToolHandlerContext = ToolHandlerContext>(threadHandler: (config: ToolResultConfig) => Promise<void>, handler: ActivityToolHandler<TArgs, TResult, TContext>): ActivityToolHandler<TArgs, TResult, TContext>;
372
- /**
373
- * Identity function that creates a generic inference context for a tool definition.
374
- * TypeScript infers TResult from the handler and flows it to hooks automatically.
375
- *
376
- * @example
377
- * ```typescript
378
- * tools: {
379
- * AskUser: defineTool({
380
- * ...askUserTool,
381
- * handler: handleAskUser,
382
- * hooks: {
383
- * onPostToolUse: ({ result }) => {
384
- * // result is correctly typed as the handler's return data type
385
- * },
386
- * },
387
- * }),
388
- * }
389
- * ```
390
- */
391
- 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>;
392
- /**
393
- * Identity function that provides full type inference for subagent configurations.
394
- * Verifies the workflow function's input parameters match the configured context,
395
- * and properly types the lifecycle hooks with Task tool args and inferred result type.
396
- *
397
- * @example
398
- * ```ts
399
- * // With typed context — workflow must accept { prompt, context }
400
- * const researcher = defineSubagent({
401
- * name: "researcher",
402
- * description: "Researches topics",
403
- * workflow: researcherWorkflow, // (input: { prompt: string; context: { apiKey: string } }) => Promise<...>
404
- * context: { apiKey: "..." },
405
- * resultSchema: z.object({ findings: z.string() }),
406
- * hooks: {
407
- * onPostExecution: ({ result }) => {
408
- * // result is typed as { findings: string }
409
- * },
410
- * },
411
- * });
412
- *
413
- * // Without context — workflow only needs { prompt }
414
- * const writer = defineSubagent({
415
- * name: "writer",
416
- * description: "Writes content",
417
- * workflow: writerWorkflow, // (input: { prompt: string }) => Promise<...>
418
- * resultSchema: z.object({ content: z.string() }),
419
- * });
420
- * ```
421
- */
422
- 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"> & {
423
- workflow: string | ((input: {
424
- prompt: string;
425
- context: TContext;
426
- }) => Promise<ToolHandlerResponse<z$1.infer<TResult> | null>>);
427
- context: TContext;
428
- hooks?: SubagentHooks<SubagentArgs, z$1.infer<TResult>>;
429
- }): SubagentConfig<TResult>;
430
- declare function defineSubagent<TResult extends z$1.ZodType = z$1.ZodType>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow"> & {
431
- workflow: string | ((input: {
432
- prompt: string;
433
- }) => Promise<ToolHandlerResponse<z$1.infer<TResult> | null>>);
434
- hooks?: SubagentHooks<SubagentArgs, z$1.infer<TResult>>;
435
- }): SubagentConfig<TResult>;
436
- /**
437
- * Utility to check if there were no tool calls besides a specific one
438
- */
439
- declare function hasNoOtherToolCalls<T extends ToolMap>(toolCalls: ParsedToolCallUnion<T>[], excludeName: ToolNames<T>): boolean;
440
-
441
- /** A single content part within a structured message (text, image, etc.) */
442
- type ContentPart = {
443
- type: string;
444
- [key: string]: unknown;
445
- };
446
- /** Message content — plain string or an array of structured content parts */
447
- type MessageContent = string | ContentPart[];
448
- /** Content returned by a tool handler */
449
- type ToolMessageContent = MessageContent;
450
- /**
451
- * Agent execution status
452
- */
453
- type AgentStatus = "RUNNING" | "WAITING_FOR_INPUT" | "COMPLETED" | "FAILED" | "CANCELLED";
454
- /**
455
- * Base state that all agents must have
456
- */
457
- interface BaseAgentState {
458
- tools: SerializableToolDefinition[];
459
- status: AgentStatus;
460
- version: number;
461
- turns: number;
462
- tasks: Map<string, WorkflowTask>;
463
- systemPrompt?: string;
464
- totalInputTokens: number;
465
- totalOutputTokens: number;
466
- cachedWriteTokens: number;
467
- cachedReadTokens: number;
468
- }
469
- /**
470
- * File representation for agent workflows
471
- */
472
- interface AgentFile {
473
- /** Database/S3 file ID */
474
- id: string;
475
- /** Virtual path for agent (e.g., "evidence/invoice.pdf") */
476
- path: string;
477
- /** Original filename */
478
- filename: string;
479
- /** Generic description for prompt */
480
- description?: string;
481
- /** MIME type of the file */
482
- mimeType?: string;
483
- }
484
- interface TokenUsage {
485
- inputTokens?: number;
486
- outputTokens?: number;
487
- cachedWriteTokens?: number;
488
- cachedReadTokens?: number;
489
- reasonTokens?: number;
490
- }
491
- /**
492
- * Agent response from LLM invocation
493
- */
494
- interface AgentResponse<M = unknown> {
495
- message: M;
496
- rawToolCalls: RawToolCall[];
497
- usage?: TokenUsage;
498
- }
499
- /**
500
- * Thread operations required by a session.
501
- * Consumers provide these — typically by wrapping Temporal activities.
502
- */
503
- interface ThreadOps {
504
- /** Initialize an empty thread */
505
- initializeThread(threadId: string): Promise<void>;
506
- /** Append a human message to the thread */
507
- appendHumanMessage(threadId: string, content: string | MessageContent): Promise<void>;
508
- /** Append a tool result to the thread */
509
- appendToolResult(config: ToolResultConfig): Promise<void>;
510
- /** Append a system message to the thread */
511
- appendSystemMessage(threadId: string, content: string): Promise<void>;
512
- }
513
- /**
514
- * Configuration for a Zeitlich agent
515
- */
516
- interface AgentConfig {
517
- /** The name of the agent, should be unique within the workflows, ideally Pascal Case */
518
- agentName: string;
519
- /** Description, used for sub agents */
520
- description?: string;
521
- }
522
- /**
523
- * Configuration for a Zeitlich agent session
524
- */
525
- interface SessionConfig<T extends ToolMap, M = unknown> {
526
- /** The thread ID to use for the session (defaults to a short generated ID) */
527
- threadId?: string;
528
- /** Metadata for the session */
529
- metadata?: Record<string, unknown>;
530
- /** Whether to append the system prompt as message to the thread */
531
- appendSystemPrompt?: boolean;
532
- /** How many turns to run the session for */
533
- maxTurns?: number;
534
- /** Workflow-specific runAgent activity (with tools pre-bound) */
535
- runAgent: RunAgentActivity<M>;
536
- /** Thread operations (initialize, append messages, parse tool calls) */
537
- threadOps?: ThreadOps;
538
- /** Tool router for processing tool calls (optional if agent has no tools) */
539
- tools?: T;
540
- /** Subagent configurations */
541
- subagents?: SubagentConfig[];
542
- /** Skills available to this agent (metadata + instructions, loaded activity-side) */
543
- skills?: Skill[];
544
- /** Session lifecycle hooks */
545
- hooks?: Hooks<T, ToolCallResultUnion<InferToolResults<T>>>;
546
- /** Whether to process tools in parallel */
547
- processToolsInParallel?: boolean;
548
- /**
549
- * Build context message content from agent-specific context.
550
- * Returns MessageContent array for the initial HumanMessage.
551
- */
552
- buildContextMessage: () => MessageContent | Promise<MessageContent>;
553
- /** When true, skip thread initialization and system prompt — append only the new human message to the existing thread. */
554
- continueThread?: boolean;
555
- /** How long to wait for input before cancelling the workflow */
556
- waitForInputTimeout?: Duration;
557
- }
558
- /**
559
- * A JSON-serializable tool definition for state storage.
560
- * Uses a plain JSON Schema object instead of a live Zod instance,
561
- * so it survives Temporal serialization without losing constraints (min, max, etc.).
562
- */
563
- interface SerializableToolDefinition {
564
- name: string;
565
- description: string;
566
- schema: Record<string, unknown>;
567
- strict?: boolean;
568
- max_uses?: number;
569
- }
570
- /**
571
- * Configuration passed to runAgent activity
572
- */
573
- interface RunAgentConfig extends AgentConfig {
574
- /** The thread ID to use for the session */
575
- threadId: string;
576
- /** Metadata for the session */
577
- metadata?: Record<string, unknown>;
578
- }
579
- /**
580
- * Type signature for workflow-specific runAgent activity
581
- */
582
- type RunAgentActivity<M = unknown> = (config: RunAgentConfig) => Promise<AgentResponse<M>>;
583
- /**
584
- * Configuration for appending a tool result
585
- */
586
- interface ToolResultConfig {
587
- threadId: string;
588
- toolCallId: string;
589
- /** The name of the tool that produced this result */
590
- toolName: string;
591
- /** Content for the tool message (string or complex content parts) */
592
- content: ToolMessageContent;
593
- }
594
- type SubagentWorkflow<TResult extends z$1.ZodType = z$1.ZodType> = (input: SubagentInput) => Promise<ToolHandlerResponse<z$1.infer<TResult> | null>>;
595
- /**
596
- * Configuration for a subagent that can be spawned by the parent workflow.
597
- *
598
- * @template TResult - Zod schema type for validating the child workflow's result
599
- */
600
- interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
601
- /** Identifier used in Task tool's subagent parameter */
602
- agentName: string;
603
- /** Description shown to the parent agent explaining what this subagent does */
604
- description: string;
605
- /** Whether this subagent is available (default: true). Disabled subagents are excluded from the Subagent tool. */
606
- enabled?: boolean;
607
- /** Temporal workflow function or type name (used with executeChild) */
608
- workflow: string | SubagentWorkflow<TResult>;
609
- /** Optional task queue - defaults to parent's queue if not specified */
610
- taskQueue?: string;
611
- /** Optional Zod schema to validate the child workflow's result. If omitted, result is passed through as-is. */
612
- resultSchema?: TResult;
613
- /** Optional static context passed to the subagent on every invocation */
614
- context?: Record<string, unknown>;
615
- /** Allow the parent agent to pass a threadId for this subagent to continue (default: false) */
616
- allowThreadContinuation?: boolean;
617
- /** Per-subagent lifecycle hooks */
618
- hooks?: SubagentHooks;
619
- }
620
- /**
621
- * Per-subagent lifecycle hooks - defined on a SubagentConfig.
622
- * Runs in addition to global hooks (global pre → subagent pre → execute → subagent post → global post).
623
- */
624
- interface SubagentHooks<TArgs = unknown, TResult = unknown> {
625
- /** Called before this subagent executes - can skip or modify args */
626
- onPreExecution?: (ctx: {
627
- args: TArgs;
628
- threadId: string;
629
- turn: number;
630
- }) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
631
- /** Called after this subagent executes successfully */
632
- onPostExecution?: (ctx: {
633
- args: TArgs;
634
- result: TResult;
635
- threadId: string;
636
- turn: number;
637
- durationMs: number;
638
- }) => void | Promise<void>;
639
- /** Called when this subagent execution fails */
640
- onExecutionFailure?: (ctx: {
641
- args: TArgs;
642
- error: Error;
643
- threadId: string;
644
- turn: number;
645
- }) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
646
- }
647
- /**
648
- * Input passed to child workflows when spawned as subagents
649
- */
650
- interface SubagentInput {
651
- /** The prompt/task from the parent agent */
652
- prompt: string;
653
- /** Optional context parameters passed from the parent agent */
654
- context?: Record<string, unknown>;
655
- /** When set, the subagent should continue this thread instead of starting a new one */
656
- threadId?: string;
657
- }
658
- /**
659
- * Status of a workflow task
660
- */
661
- type TaskStatus = "pending" | "in_progress" | "completed";
662
- /**
663
- * A task managed within a workflow for tracking work items
664
- */
665
- interface WorkflowTask {
666
- /** Unique task identifier */
667
- id: string;
668
- /** Brief, actionable title in imperative form */
669
- subject: string;
670
- /** Detailed description of what needs to be done */
671
- description: string;
672
- /** Present continuous form shown in spinner when in_progress */
673
- activeForm: string;
674
- /** Current status of the task */
675
- status: TaskStatus;
676
- /** Arbitrary key-value pairs for tracking */
677
- metadata: Record<string, string>;
678
- /** IDs of tasks that must complete before this one can start */
679
- blockedBy: string[];
680
- /** IDs of tasks that are waiting for this one to complete */
681
- blocks: string[];
682
- }
683
- /**
684
- * Exit reasons for session termination
685
- */
686
- type SessionExitReason = "completed" | "max_turns" | "waiting_for_input" | "failed" | "cancelled";
687
- /**
688
- * Context for PreToolUse hook - called before tool execution
689
- */
690
- interface PreToolUseHookContext<T extends ToolMap> {
691
- /** The tool call about to be executed */
692
- toolCall: ParsedToolCallUnion<T>;
693
- /** Thread identifier */
694
- threadId: string;
695
- /** Current turn number */
696
- turn: number;
697
- }
698
- /**
699
- * Result from PreToolUse hook - can block or modify execution
700
- */
701
- interface PreToolUseHookResult {
702
- /** Skip this tool call entirely */
703
- skip?: boolean;
704
- /** Modified args to use instead (must match schema) */
705
- modifiedArgs?: unknown;
706
- }
707
- /**
708
- * PreToolUse hook - called before tool execution, can block or modify
709
- */
710
- type PreToolUseHook<T extends ToolMap> = (ctx: PreToolUseHookContext<T>) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
711
- /**
712
- * Context for PostToolUse hook - called after successful tool execution
713
- */
714
- interface PostToolUseHookContext<T extends ToolMap, TResult = unknown> {
715
- /** The tool call that was executed */
716
- toolCall: ParsedToolCallUnion<T>;
717
- /** The result from the tool handler */
718
- result: TResult;
719
- /** Thread identifier */
720
- threadId: string;
721
- /** Current turn number */
722
- turn: number;
723
- /** Execution duration in milliseconds */
724
- durationMs: number;
725
- }
726
- /**
727
- * PostToolUse hook - called after successful tool execution
728
- */
729
- type PostToolUseHook<T extends ToolMap, TResult = unknown> = (ctx: PostToolUseHookContext<T, TResult>) => void | Promise<void>;
730
- /**
731
- * Context for PostToolUseFailure hook - called when tool execution fails
732
- */
733
- interface PostToolUseFailureHookContext<T extends ToolMap> {
734
- /** The tool call that failed */
735
- toolCall: ParsedToolCallUnion<T>;
736
- /** The error that occurred */
737
- error: Error;
738
- /** Thread identifier */
739
- threadId: string;
740
- /** Current turn number */
741
- turn: number;
742
- }
743
- /**
744
- * Result from PostToolUseFailure hook - can recover from errors
745
- */
746
- interface PostToolUseFailureHookResult {
747
- /** Provide a fallback result instead of throwing */
748
- fallbackContent?: ToolMessageContent;
749
- /** Whether to suppress the error (still logs, but continues) */
750
- suppress?: boolean;
751
- }
752
- /**
753
- * PostToolUseFailure hook - called when tool execution fails
754
- */
755
- type PostToolUseFailureHook<T extends ToolMap> = (ctx: PostToolUseFailureHookContext<T>) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
756
- /**
757
- * Context for SessionStart hook - called when session begins
758
- */
759
- interface SessionStartHookContext {
760
- /** Thread identifier */
761
- threadId: string;
762
- /** Name of the agent */
763
- agentName: string;
764
- /** Session metadata */
765
- metadata: Record<string, unknown>;
766
- }
767
- /**
768
- * SessionStart hook - called when session begins
769
- */
770
- type SessionStartHook = (ctx: SessionStartHookContext) => void | Promise<void>;
771
- /**
772
- * Context for PreHumanMessageAppend hook - called before each human message is appended to the thread
773
- */
774
- interface PreHumanMessageAppendHookContext {
775
- /** The message about to be appended */
776
- message: MessageContent;
777
- /** Thread identifier */
778
- threadId: string;
779
- }
780
- /**
781
- * PreHumanMessageAppend hook - called before each human message is appended to the thread
782
- */
783
- type PreHumanMessageAppendHook = (ctx: PreHumanMessageAppendHookContext) => void | Promise<void>;
784
- /**
785
- * PostHumanMessageAppend hook - called after each human message is appended to the thread
786
- */
787
- type PostHumanMessageAppendHook = (ctx: PostHumanMessageAppendHookContext) => void | Promise<void>;
788
- /**
789
- * Context for PostHumanMessageAppend hook - called after each human message is appended to the thread
790
- */
791
- interface PostHumanMessageAppendHookContext {
792
- /** The message that was appended */
793
- message: MessageContent;
794
- /** Thread identifier */
795
- threadId: string;
796
- }
797
- /**
798
- * Context for SessionEnd hook - called when session ends
799
- */
800
- interface SessionEndHookContext {
801
- /** Thread identifier */
802
- threadId: string;
803
- /** Name of the agent */
804
- agentName: string;
805
- /** Reason the session ended */
806
- exitReason: SessionExitReason;
807
- /** Total turns executed */
808
- turns: number;
809
- /** Session metadata */
810
- metadata: Record<string, unknown>;
811
- }
812
- /**
813
- * SessionEnd hook - called when session ends
814
- */
815
- type SessionEndHook = (ctx: SessionEndHookContext) => void | Promise<void>;
816
- /**
817
- * Per-tool lifecycle hooks - defined directly on a tool definition.
818
- * Runs in addition to global hooks (global pre → tool pre → execute → tool post → global post).
819
- */
820
- interface ToolHooks<TArgs = unknown, TResult = unknown> {
821
- /** Called before this tool executes - can skip or modify args */
822
- onPreToolUse?: (ctx: {
823
- args: TArgs;
824
- threadId: string;
825
- turn: number;
826
- }) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
827
- /** Called after this tool executes successfully */
828
- onPostToolUse?: (ctx: {
829
- args: TArgs;
830
- result: TResult;
831
- threadId: string;
832
- turn: number;
833
- durationMs: number;
834
- }) => void | Promise<void>;
835
- /** Called when this tool execution fails */
836
- onPostToolUseFailure?: (ctx: {
837
- args: TArgs;
838
- error: Error;
839
- threadId: string;
840
- turn: number;
841
- }) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
842
- }
843
- /**
844
- * Combined hooks interface for session lifecycle
845
- */
846
- interface Hooks<T extends ToolMap, TResult = unknown> {
847
- /** Called before each human message is appended to the thread */
848
- onPreHumanMessageAppend?: PreHumanMessageAppendHook;
849
- /** Called after each human message is appended to the thread */
850
- onPostHumanMessageAppend?: PostHumanMessageAppendHook;
851
- /** Called before each tool execution - can block or modify */
852
- onPreToolUse?: PreToolUseHook<T>;
853
- /** Called after each successful tool execution */
854
- onPostToolUse?: PostToolUseHook<T, TResult>;
855
- /** Called when tool execution fails */
856
- onPostToolUseFailure?: PostToolUseFailureHook<T>;
857
- /** Called when session starts */
858
- onSessionStart?: SessionStartHook;
859
- /** Called when session ends */
860
- onSessionEnd?: SessionEndHook;
861
- }
862
- /** Derives the query name for an agent's state (usable in both workflow and activity code) */
863
- declare const agentQueryName: (agentName: string) => `get${string}State`;
864
- /** Derives the update name for waiting on an agent's state change */
865
- declare const agentStateChangeUpdateName: (agentName: string) => `waitFor${string}StateChange`;
866
- /**
867
- * Helper to check if status is terminal
868
- */
869
- declare function isTerminalStatus(status: AgentStatus): boolean;
870
-
871
- /**
872
- * Configuration passed to a ModelInvoker.
873
- * Includes the full agent state so adapters can read tools, system prompt,
874
- * token usage, or any custom state fields for model configuration.
875
- */
876
- interface ModelInvokerConfig {
877
- threadId: string;
878
- agentName: string;
879
- state: BaseAgentState;
880
- metadata?: Record<string, unknown>;
881
- }
882
- /**
883
- * Generic model invocation contract.
884
- * Implementations load the thread, call the LLM, append the response,
885
- * and return a normalised AgentResponse.
886
- *
887
- * Framework adapters (e.g. `zeitlich/langchain`) provide concrete
888
- * implementations of this type.
889
- */
890
- type ModelInvoker<M = unknown> = (config: ModelInvokerConfig) => Promise<AgentResponse<M>>;
891
-
892
- export { type ToolHandlerContext as $, type AgentResponse as A, type BaseAgentState as B, type ContentPart as C, type SessionEndHook as D, type SessionEndHookContext as E, type SessionExitReason as F, type SessionStartHook as G, type Hooks as H, type InferToolResults as I, type SessionStartHookContext as J, type SubagentArgs as K, type SubagentConfig as L, type ModelInvoker as M, type SubagentHooks as N, type SubagentInput as O, type ParsedToolCall as P, type SubagentWorkflow as Q, type RunAgentConfig as R, type SkillProvider as S, type ThreadOps as T, type TaskStatus as U, type TokenUsage as V, type ToolArgs as W, type ToolCallResult as X, type ToolCallResultUnion as Y, type ToolDefinition as Z, type ToolHandler as _, type ModelInvokerConfig 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, agentQueryName as aa, agentStateChangeUpdateName as ab, createSubagentTool as ac, createToolRouter as ad, defineSubagent as ae, defineTool as af, hasNoOtherToolCalls as ag, isTerminalStatus as ah, withAutoAppend as ai, type ActivityToolHandler as b, type SkillMetadata as c, type Skill as d, type AgentConfig as e, type AgentFile as f, type AgentStatus as g, type AppendToolResultFn as h, type MessageContent as i, type ParsedToolCallUnion as j, type PostHumanMessageAppendHook as k, type PostHumanMessageAppendHookContext as l, type PostToolUseFailureHook as m, type PostToolUseFailureHookContext as n, type PostToolUseFailureHookResult as o, type PostToolUseHook as p, type PostToolUseHookContext as q, type PreHumanMessageAppendHook as r, type PreHumanMessageAppendHookContext as s, type PreToolUseHook as t, type PreToolUseHookContext as u, type PreToolUseHookResult as v, type ProcessToolCallsContext as w, type RawToolCall as x, type RunAgentActivity as y, type SessionConfig as z };