zeitlich 0.1.1 → 0.2.0

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 (58) hide show
  1. package/README.md +165 -180
  2. package/dist/index.cjs +1314 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +128 -0
  5. package/dist/index.d.ts +51 -75
  6. package/dist/index.js +741 -1091
  7. package/dist/index.js.map +1 -1
  8. package/dist/workflow-uVNF7zoe.d.cts +941 -0
  9. package/dist/workflow-uVNF7zoe.d.ts +941 -0
  10. package/dist/workflow.cjs +914 -0
  11. package/dist/workflow.cjs.map +1 -0
  12. package/dist/workflow.d.cts +5 -0
  13. package/dist/workflow.d.ts +2 -1
  14. package/dist/workflow.js +543 -423
  15. package/dist/workflow.js.map +1 -1
  16. package/package.json +19 -17
  17. package/src/activities.ts +112 -0
  18. package/src/index.ts +49 -0
  19. package/src/lib/fs.ts +80 -0
  20. package/src/lib/model-invoker.ts +75 -0
  21. package/src/lib/session.ts +216 -0
  22. package/src/lib/state-manager.ts +268 -0
  23. package/src/lib/thread-manager.ts +169 -0
  24. package/src/lib/tool-router.ts +717 -0
  25. package/src/lib/types.ts +354 -0
  26. package/src/plugin.ts +28 -0
  27. package/src/tools/ask-user-question/handler.ts +25 -0
  28. package/src/tools/ask-user-question/tool.ts +46 -0
  29. package/src/tools/bash/bash.test.ts +104 -0
  30. package/src/tools/bash/handler.ts +36 -0
  31. package/src/tools/bash/tool.ts +20 -0
  32. package/src/tools/edit/handler.ts +156 -0
  33. package/src/tools/edit/tool.ts +39 -0
  34. package/src/tools/glob/handler.ts +62 -0
  35. package/src/tools/glob/tool.ts +27 -0
  36. package/src/tools/grep/tool.ts +45 -0
  37. package/src/tools/read/tool.ts +33 -0
  38. package/src/tools/task/handler.ts +75 -0
  39. package/src/tools/task/tool.ts +96 -0
  40. package/src/tools/task-create/handler.ts +49 -0
  41. package/src/tools/task-create/tool.ts +66 -0
  42. package/src/tools/task-get/handler.ts +38 -0
  43. package/src/tools/task-get/tool.ts +11 -0
  44. package/src/tools/task-list/handler.ts +33 -0
  45. package/src/tools/task-list/tool.ts +9 -0
  46. package/src/tools/task-update/handler.ts +79 -0
  47. package/src/tools/task-update/tool.ts +20 -0
  48. package/src/tools/write/tool.ts +26 -0
  49. package/src/workflow.ts +138 -0
  50. package/tsup.config.ts +20 -0
  51. package/dist/index.d.mts +0 -152
  52. package/dist/index.mjs +0 -1587
  53. package/dist/index.mjs.map +0 -1
  54. package/dist/workflow-7_MT-5-w.d.mts +0 -1203
  55. package/dist/workflow-7_MT-5-w.d.ts +0 -1203
  56. package/dist/workflow.d.mts +0 -4
  57. package/dist/workflow.mjs +0 -739
  58. package/dist/workflow.mjs.map +0 -1
@@ -0,0 +1,941 @@
1
+ import { $InferMessageContent, MessageStructure, StoredMessage, MessageContent } from '@langchain/core/messages';
2
+ import z, { z as z$1 } from 'zod';
3
+ import { IFileSystem } from 'just-bash';
4
+ import Redis from 'ioredis';
5
+
6
+ /**
7
+ * Content for a tool message response.
8
+ * Can be a simple string or complex content parts (text, images, cache points, etc.)
9
+ */
10
+ type ToolMessageContent = $InferMessageContent<MessageStructure, "tool">;
11
+
12
+ /**
13
+ * JSON primitive types that Temporal can serialize
14
+ */
15
+ type JsonPrimitive = string | number | boolean | null | undefined;
16
+ /**
17
+ * JSON-serializable value (recursive type for Temporal compatibility)
18
+ */
19
+ type JsonValue = JsonPrimitive | JsonValue[] | {
20
+ [key: string]: JsonValue;
21
+ };
22
+ /**
23
+ * Type constraint ensuring T only contains JSON-serializable values.
24
+ * Use this for custom state to ensure Temporal workflow compatibility.
25
+ *
26
+ * Allows: primitives, arrays, plain objects, and JsonValue
27
+ * Rejects: functions, symbols, undefined, class instances with methods
28
+ */
29
+ type JsonSerializable<T> = {
30
+ [K in keyof T]: T[K] extends JsonValue ? T[K] : T[K] extends JsonPrimitive ? T[K] : T[K] extends (infer U)[] ? U extends JsonValue ? T[K] : JsonSerializable<U>[] : T[K] extends object ? JsonSerializable<T[K]> : never;
31
+ };
32
+ /**
33
+ * Full state type combining base state with custom state
34
+ */
35
+ type AgentState<TCustom extends JsonSerializable<TCustom>> = BaseAgentState & TCustom;
36
+ /**
37
+ * Agent state manager interface
38
+ * Note: Temporal handlers must be set up in the workflow file due to
39
+ * Temporal's workflow isolation requirements. This manager provides
40
+ * the state and helpers needed for those handlers.
41
+ */
42
+ interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
43
+ /** Get current status */
44
+ getStatus(): AgentStatus;
45
+ /** Check if agent is running */
46
+ isRunning(): boolean;
47
+ /** Check if agent is in terminal state */
48
+ isTerminal(): boolean;
49
+ /** Get current state version */
50
+ getVersion(): number;
51
+ /** Set status to RUNNING */
52
+ run(): void;
53
+ /** Set status to WAITING_FOR_INPUT */
54
+ waitForInput(): void;
55
+ /** Set status to COMPLETED */
56
+ complete(): void;
57
+ /** Set status to FAILED */
58
+ fail(): void;
59
+ /** Set status to CANCELLED */
60
+ cancel(): void;
61
+ /** Increment state version (call after state changes) */
62
+ incrementVersion(): void;
63
+ /** Increment turns (call after each turn) */
64
+ incrementTurns(): void;
65
+ /** Get current turns */
66
+ getTurns(): number;
67
+ /** Get a custom state value by key */
68
+ get<K extends keyof TCustom>(key: K): TCustom[K];
69
+ /** Set a custom state value by key */
70
+ set<K extends keyof TCustom>(key: K, value: TCustom[K]): void;
71
+ /** Get full state for query handler */
72
+ getCurrentState(): AgentState<TCustom>;
73
+ /** Check if should return from waitForStateChange */
74
+ shouldReturnFromWait(lastKnownVersion: number): boolean;
75
+ /** Get all tasks */
76
+ getTasks(): WorkflowTask[];
77
+ /** Get a task by ID */
78
+ getTask(id: string): WorkflowTask | undefined;
79
+ /** Add or update a task */
80
+ setTask(task: WorkflowTask): void;
81
+ /** Delete a task by ID */
82
+ deleteTask(id: string): boolean;
83
+ /** Set the tools */
84
+ setTools(newTools: ToolDefinition[]): void;
85
+ }
86
+ /**
87
+ * Creates an agent state manager for tracking workflow state.
88
+ *
89
+ * @param initialState - Optional initial values for base and custom state
90
+ * Base state defaults: status="RUNNING", version=0, turns=0, tasks=empty, fileTree=[]
91
+ *
92
+ * Note: Due to Temporal's workflow isolation, handlers must be set up
93
+ * in the workflow file using defineQuery/defineUpdate and setHandler.
94
+ * This manager provides the state and logic needed for those handlers.
95
+ */
96
+ declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>(initialState?: Partial<BaseAgentState> & TCustom): AgentStateManager<TCustom>;
97
+ /**
98
+ * Handler names used across agents
99
+ */
100
+ declare const AGENT_HANDLER_NAMES: {
101
+ readonly getAgentState: "getAgentState";
102
+ readonly waitForStateChange: "waitForStateChange";
103
+ readonly addMessage: "addMessage";
104
+ };
105
+
106
+ declare const taskCreateTool: {
107
+ name: "TaskCreate";
108
+ description: string;
109
+ schema: z.ZodObject<{
110
+ subject: z.ZodString;
111
+ description: z.ZodString;
112
+ activeForm: z.ZodString;
113
+ metadata: z.ZodRecord<z.ZodString, z.ZodString>;
114
+ }, z.core.$strip>;
115
+ };
116
+ type TaskCreateToolSchemaType = z.infer<typeof taskCreateTool.schema>;
117
+
118
+ /**
119
+ * Creates a TaskCreate handler that adds tasks to the workflow state.
120
+ *
121
+ * @param stateManager - State manager containing tasks state
122
+ * @param idGenerator - Function to generate unique task IDs (e.g., uuid4 from Temporal)
123
+ * @returns A tool handler function
124
+ *
125
+ * @example
126
+ * const handler = createTaskCreateHandler(stateManager, uuid4);
127
+ */
128
+ declare function createTaskCreateHandler<TCustom extends JsonSerializable<TCustom>>({ stateManager, idGenerator, }: {
129
+ stateManager: AgentStateManager<TCustom>;
130
+ idGenerator: () => string;
131
+ }): (args: TaskCreateToolSchemaType) => ToolHandlerResponse<WorkflowTask>;
132
+
133
+ declare const bashTool: {
134
+ name: "Bash";
135
+ description: string;
136
+ schema: z.ZodObject<{
137
+ command: z.ZodString;
138
+ }, z.core.$strip>;
139
+ strict: boolean;
140
+ };
141
+ type bashToolSchemaType = z.infer<typeof bashTool.schema>;
142
+
143
+ type BashExecOut = {
144
+ exitCode: number;
145
+ stderr: string;
146
+ stdout: string;
147
+ };
148
+ declare const handleBashTool: (fs: IFileSystem) => ActivityToolHandler<bashToolSchemaType, BashExecOut | null>;
149
+
150
+ /**
151
+ * A tool definition with a name, description, and Zod schema for arguments.
152
+ * Does not include a handler - use ToolWithHandler for tools with handlers.
153
+ */
154
+ interface ToolDefinition<TName extends string = string, TSchema extends z$1.ZodType = z$1.ZodType> {
155
+ name: TName;
156
+ description: string;
157
+ schema: TSchema;
158
+ strict?: boolean;
159
+ max_uses?: number;
160
+ }
161
+ /**
162
+ * A tool definition with an integrated handler function.
163
+ * This is the primary type for defining tools in the router.
164
+ */
165
+ interface ToolWithHandler<TName extends string = string, TSchema extends z$1.ZodType = z$1.ZodType, TResult = unknown, TContext = ToolHandlerContext> {
166
+ name: TName;
167
+ description: string;
168
+ schema: TSchema;
169
+ handler: ToolHandler<z$1.infer<TSchema>, TResult, TContext>;
170
+ strict?: boolean;
171
+ max_uses?: number;
172
+ }
173
+ /**
174
+ * A map of tool keys to tool definitions with handlers.
175
+ */
176
+ type ToolMap = Record<string, {
177
+ name: string;
178
+ description: string;
179
+ schema: z$1.ZodType;
180
+ handler: (args: any, context: any) => ToolHandlerResponse<any> | Promise<ToolHandlerResponse<any>>;
181
+ strict?: boolean;
182
+ max_uses?: number;
183
+ }>;
184
+ /**
185
+ * Extract the tool names from a tool map (uses the tool's name property, not the key).
186
+ */
187
+ type ToolNames<T extends ToolMap> = T[keyof T]["name"];
188
+ /**
189
+ * A raw tool call as received from the LLM before parsing.
190
+ */
191
+ interface RawToolCall {
192
+ id?: string;
193
+ name: string;
194
+ args: unknown;
195
+ }
196
+ /**
197
+ * A parsed tool call with validated arguments for a specific tool.
198
+ */
199
+ interface ParsedToolCall<TName extends string = string, TArgs = unknown> {
200
+ id: string;
201
+ name: TName;
202
+ args: TArgs;
203
+ }
204
+ /**
205
+ * Union type of all possible parsed tool calls from a tool map.
206
+ */
207
+ type ParsedToolCallUnion<T extends ToolMap> = {
208
+ [K in keyof T]: ParsedToolCall<T[K]["name"], z$1.infer<T[K]["schema"]>>;
209
+ }[keyof T];
210
+ /**
211
+ * Function signature for appending tool results to a thread.
212
+ */
213
+ type AppendToolResultFn = (config: ToolResultConfig) => Promise<void>;
214
+ /**
215
+ * The response from a tool handler.
216
+ * Contains the content for the tool message and the result to return from processToolCalls.
217
+ */
218
+ interface ToolHandlerResponse<TResult> {
219
+ /** Content for the tool message added to the thread */
220
+ content: ToolMessageContent;
221
+ /** Result returned from processToolCalls */
222
+ result: TResult;
223
+ }
224
+ /**
225
+ * Context passed to tool handlers for additional data beyond tool args.
226
+ * Use this to pass workflow state like file trees, user context, etc.
227
+ */
228
+ interface ToolHandlerContext {
229
+ /** Additional context data - define your own shape */
230
+ [key: string]: unknown;
231
+ }
232
+ interface BuildInToolDefinitions {
233
+ [bashTool.name]: typeof bashTool & {
234
+ handler: ReturnType<typeof handleBashTool>;
235
+ };
236
+ [taskCreateTool.name]: typeof taskCreateTool & {
237
+ handler: ReturnType<typeof createTaskCreateHandler>;
238
+ };
239
+ }
240
+ /**
241
+ * A handler function for a specific tool.
242
+ * Receives the parsed args and context, returns a response with content and result.
243
+ * Context always has a value (defaults to empty object if not provided).
244
+ */
245
+ type ToolHandler<TArgs, TResult, TContext = ToolHandlerContext> = (args: TArgs, context: TContext) => ToolHandlerResponse<TResult> | Promise<ToolHandlerResponse<TResult>>;
246
+ /**
247
+ * Activity-compatible tool handler that always returns a Promise.
248
+ * Use this for tool handlers registered as Temporal activities.
249
+ * Context always has a value (defaults to empty object if not provided).
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * // Filesystem handler with context
254
+ * const readHandler: ActivityToolHandler<
255
+ * ReadToolSchemaType,
256
+ * ReadResult,
257
+ * { scopedNodes: FileNode[]; provider: FileSystemProvider }
258
+ * > = async (args, context) => {
259
+ * return readHandler(args, context.scopedNodes, context.provider);
260
+ * };
261
+ * ```
262
+ */
263
+ type ActivityToolHandler<TArgs, TResult, TContext = ToolHandlerContext> = (args: TArgs, context: TContext) => Promise<ToolHandlerResponse<TResult>>;
264
+ /**
265
+ * Extract the args type for a specific tool name from a tool map.
266
+ */
267
+ type ToolArgs<T extends ToolMap, TName extends ToolNames<T>> = z$1.infer<Extract<T[keyof T], {
268
+ name: TName;
269
+ }>["schema"]>;
270
+ /**
271
+ * Extract the result type for a specific tool name from a tool map.
272
+ */
273
+ type ToolResult<T extends ToolMap, TName extends ToolNames<T>> = Extract<T[keyof T], {
274
+ name: TName;
275
+ }>["handler"] extends ToolHandler<unknown, infer R, unknown> ? Awaited<R> : never;
276
+ /**
277
+ * The result of processing a tool call.
278
+ */
279
+ interface ToolCallResult<TName extends string = string, TResult = unknown> {
280
+ toolCallId: string;
281
+ name: TName;
282
+ result: TResult;
283
+ }
284
+ /**
285
+ * Options for creating a tool router.
286
+ */
287
+ interface ToolRouterOptions<T extends ToolMap> {
288
+ /** File tree for the agent */
289
+ fileTree: string;
290
+ /** Map of tools with their handlers */
291
+ tools: T;
292
+ /** Thread ID for appending tool results */
293
+ threadId: string;
294
+ /** Function to append tool results to the thread (called automatically after each handler) */
295
+ appendToolResult: AppendToolResultFn;
296
+ /** Whether to process tools in parallel (default: true) */
297
+ parallel?: boolean;
298
+ /** Lifecycle hooks for tool execution */
299
+ hooks?: Hooks<T, ToolCallResultUnion<InferToolResults<T>>>;
300
+ /** Subagent configurations */
301
+ subagents?: SubagentConfig[];
302
+ /** Build in tools - accepts raw handlers or proxied activities */
303
+ buildInTools?: {
304
+ [K in keyof BuildInToolDefinitions]?: BuildInToolDefinitions[K]["handler"];
305
+ };
306
+ }
307
+ /**
308
+ * Infer result types from a tool map based on handler return types.
309
+ */
310
+ type InferToolResults<T extends ToolMap> = {
311
+ [K in keyof T as T[K]["name"]]: T[K]["handler"] extends ToolHandler<any, infer R, any> ? Awaited<R> : never;
312
+ };
313
+ /**
314
+ * Union of all possible tool call results based on handler return types.
315
+ */
316
+ type ToolCallResultUnion<TResults extends Record<string, unknown>> = {
317
+ [TName in keyof TResults & string]: ToolCallResult<TName, TResults[TName]>;
318
+ }[keyof TResults & string];
319
+ /**
320
+ * Context passed to processToolCalls for hook execution and handler invocation
321
+ */
322
+ interface ProcessToolCallsContext<THandlerContext = ToolHandlerContext> {
323
+ /** Current turn number (for hooks) */
324
+ turn?: number;
325
+ /** Context passed to each tool handler (scopedNodes, provider, etc.) */
326
+ handlerContext?: THandlerContext;
327
+ }
328
+ /**
329
+ * The tool router interface with full type inference for both args and results.
330
+ */
331
+ interface ToolRouter<T extends ToolMap> {
332
+ /** Check if the router has any tools */
333
+ hasTools(): boolean;
334
+ /**
335
+ * Parse and validate a raw tool call against the router's tools.
336
+ * Returns a typed tool call with validated arguments.
337
+ */
338
+ parseToolCall(toolCall: RawToolCall): ParsedToolCallUnion<T>;
339
+ /**
340
+ * Check if a tool with the given name exists in the router.
341
+ */
342
+ hasTool(name: string): boolean;
343
+ /**
344
+ * Get all tool names in the router.
345
+ */
346
+ getToolNames(): ToolNames<T>[];
347
+ /**
348
+ * Get all tool definitions (without handlers) for passing to LLM.
349
+ */
350
+ getToolDefinitions(): ToolDefinition[];
351
+ /**
352
+ * Process all tool calls using the registered handlers.
353
+ * Returns typed results based on handler return types.
354
+ * @param toolCalls - Array of parsed tool calls to process
355
+ * @param context - Optional context including turn number for hooks
356
+ */
357
+ processToolCalls(toolCalls: ParsedToolCallUnion<T>[], context?: ProcessToolCallsContext): Promise<ToolCallResultUnion<InferToolResults<T>>[]>;
358
+ /**
359
+ * Process tool calls matching a specific name with a custom handler.
360
+ * Useful for overriding the default handler for specific cases.
361
+ */
362
+ 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>[]>;
363
+ /**
364
+ * Filter tool calls by name.
365
+ */
366
+ filterByName<TName extends ToolNames<T>>(toolCalls: ParsedToolCallUnion<T>[], name: TName): ParsedToolCall<TName, ToolArgs<T, TName>>[];
367
+ /**
368
+ * Check if any tool call matches the given name.
369
+ */
370
+ hasToolCall(toolCalls: ParsedToolCallUnion<T>[], name: ToolNames<T>): boolean;
371
+ /**
372
+ * Filter results by tool name.
373
+ */
374
+ getResultsByName<TName extends ToolNames<T>>(results: ToolCallResultUnion<InferToolResults<T>>[], name: TName): ToolCallResult<TName, ToolResult<T, TName>>[];
375
+ }
376
+ /**
377
+ * Creates a tool router for declarative tool call processing.
378
+ * Combines tool definitions with handlers in a single API.
379
+ *
380
+ * @example
381
+ * ```typescript
382
+ * const router = createToolRouter({
383
+ * threadId,
384
+ * tools: {
385
+ * Read: {
386
+ * name: "FileRead",
387
+ * description: "Read file contents",
388
+ * schema: z.object({ path: z.string() }),
389
+ * handler: async (args, ctx) => ({
390
+ * content: `Read ${args.path}`,
391
+ * result: { path: args.path, content: "..." },
392
+ * }),
393
+ * },
394
+ * },
395
+ * hooks: { onPreToolUse, onPostToolUse },
396
+ * });
397
+ *
398
+ * // Parse raw tool calls from LLM
399
+ * const parsed = router.parseToolCall(rawToolCall);
400
+ *
401
+ * // Process tool calls
402
+ * const results = await router.processToolCalls([parsed]);
403
+ * ```
404
+ */
405
+ declare function createToolRouter<T extends ToolMap>(options: ToolRouterOptions<T>): ToolRouter<T>;
406
+ /**
407
+ * Utility to check if there were no tool calls besides a specific one
408
+ */
409
+ declare function hasNoOtherToolCalls<T extends ToolMap>(toolCalls: ParsedToolCallUnion<T>[], excludeName: ToolNames<T>): boolean;
410
+
411
+ /**
412
+ * Agent execution status
413
+ */
414
+ type AgentStatus = "RUNNING" | "WAITING_FOR_INPUT" | "COMPLETED" | "FAILED" | "CANCELLED";
415
+ /**
416
+ * Base state that all agents must have
417
+ */
418
+ interface BaseAgentState {
419
+ tools: ToolDefinition[];
420
+ status: AgentStatus;
421
+ version: number;
422
+ turns: number;
423
+ tasks: Map<string, WorkflowTask>;
424
+ }
425
+ /**
426
+ * File representation for agent workflows
427
+ */
428
+ interface AgentFile {
429
+ /** Database/S3 file ID */
430
+ id: string;
431
+ /** Virtual path for agent (e.g., "evidence/invoice.pdf") */
432
+ path: string;
433
+ /** Original filename */
434
+ filename: string;
435
+ /** Generic description for prompt */
436
+ description?: string;
437
+ /** MIME type of the file */
438
+ mimeType?: string;
439
+ }
440
+ /**
441
+ * Agent response from LLM invocation
442
+ */
443
+ interface AgentResponse {
444
+ message: StoredMessage;
445
+ stopReason: string | null;
446
+ usage?: {
447
+ input_tokens?: number;
448
+ output_tokens?: number;
449
+ total_tokens?: number;
450
+ };
451
+ }
452
+ /**
453
+ * Configuration for a Zeitlich agent session
454
+ */
455
+ interface ZeitlichAgentConfig<T extends ToolMap> {
456
+ buildFileTree?: () => Promise<string>;
457
+ threadId: string;
458
+ agentName: string;
459
+ metadata?: Record<string, unknown>;
460
+ maxTurns?: number;
461
+ /** Workflow-specific runAgent activity (with tools pre-bound) */
462
+ runAgent: RunAgentActivity;
463
+ /** Tool router for processing tool calls (optional if agent has no tools) */
464
+ tools?: T;
465
+ /** Subagent configurations */
466
+ subagents?: SubagentConfig[];
467
+ /** Session lifecycle hooks */
468
+ hooks?: Hooks<T, ToolCallResultUnion<InferToolResults<T>>>;
469
+ /** Whether to process tools in parallel */
470
+ processToolsInParallel?: boolean;
471
+ /**
472
+ * Base system prompt (e.g., Auditron identity).
473
+ * Can be a static string or async function.
474
+ */
475
+ baseSystemPrompt: string | (() => string | Promise<string>);
476
+ /**
477
+ * Agent-specific instructions prompt.
478
+ * Can be a static string or async function.
479
+ */
480
+ instructionsPrompt: string | (() => string | Promise<string>);
481
+ /**
482
+ * Build context message content from agent-specific context.
483
+ * Returns MessageContent array for the initial HumanMessage.
484
+ */
485
+ buildContextMessage: () => MessageContent | Promise<MessageContent>;
486
+ /**
487
+ * Build in tools - accepts raw handlers or proxied activities
488
+ */
489
+ buildInTools?: {
490
+ [K in keyof BuildInToolDefinitions]?: BuildInToolDefinitions[K]["handler"];
491
+ };
492
+ }
493
+ /**
494
+ * Configuration passed to runAgent activity
495
+ */
496
+ interface RunAgentConfig {
497
+ threadId: string;
498
+ agentName: string;
499
+ metadata?: Record<string, unknown>;
500
+ }
501
+ /**
502
+ * Type signature for workflow-specific runAgent activity
503
+ */
504
+ type RunAgentActivity = (config: RunAgentConfig) => Promise<AgentResponse>;
505
+ /**
506
+ * Configuration for appending a tool result
507
+ */
508
+ interface ToolResultConfig {
509
+ threadId: string;
510
+ toolCallId: string;
511
+ /** Content for the tool message (string or complex content parts) */
512
+ content: ToolMessageContent;
513
+ }
514
+ /**
515
+ * Configuration for a subagent that can be spawned by the parent workflow.
516
+ *
517
+ * @template TResult - Zod schema type for validating the child workflow's result
518
+ */
519
+ interface SubagentConfig<TResult extends z$1.ZodType = z$1.ZodType> {
520
+ /** Identifier used in Task tool's subagent parameter */
521
+ name: string;
522
+ /** Description shown to the parent agent explaining what this subagent does */
523
+ description: string;
524
+ /** Temporal workflow type name (used with executeChild) */
525
+ workflowType: string;
526
+ /** Optional task queue - defaults to parent's queue if not specified */
527
+ taskQueue?: string;
528
+ /** Optional Zod schema to validate the child workflow's result. If omitted, result is passed through as-is. */
529
+ resultSchema?: TResult;
530
+ }
531
+ /**
532
+ * Input passed to child workflows when spawned as subagents
533
+ */
534
+ interface SubagentInput {
535
+ /** The prompt/task from the parent agent */
536
+ prompt: string;
537
+ }
538
+ /**
539
+ * Status of a workflow task
540
+ */
541
+ type TaskStatus = "pending" | "in_progress" | "completed";
542
+ /**
543
+ * A task managed within a workflow for tracking work items
544
+ */
545
+ interface WorkflowTask {
546
+ /** Unique task identifier */
547
+ id: string;
548
+ /** Brief, actionable title in imperative form */
549
+ subject: string;
550
+ /** Detailed description of what needs to be done */
551
+ description: string;
552
+ /** Present continuous form shown in spinner when in_progress */
553
+ activeForm: string;
554
+ /** Current status of the task */
555
+ status: TaskStatus;
556
+ /** Arbitrary key-value pairs for tracking */
557
+ metadata: Record<string, string>;
558
+ /** IDs of tasks that must complete before this one can start */
559
+ blockedBy: string[];
560
+ /** IDs of tasks that are waiting for this one to complete */
561
+ blocks: string[];
562
+ }
563
+ /**
564
+ * Exit reasons for session termination
565
+ */
566
+ type SessionExitReason = "completed" | "max_turns" | "waiting_for_input" | "failed" | "cancelled";
567
+ /**
568
+ * Context for PreToolUse hook - called before tool execution
569
+ */
570
+ interface PreToolUseHookContext<T extends ToolMap> {
571
+ /** The tool call about to be executed */
572
+ toolCall: ParsedToolCallUnion<T>;
573
+ /** Thread identifier */
574
+ threadId: string;
575
+ /** Current turn number */
576
+ turn: number;
577
+ }
578
+ /**
579
+ * Result from PreToolUse hook - can block or modify execution
580
+ */
581
+ interface PreToolUseHookResult {
582
+ /** Skip this tool call entirely */
583
+ skip?: boolean;
584
+ /** Modified args to use instead (must match schema) */
585
+ modifiedArgs?: unknown;
586
+ }
587
+ /**
588
+ * PreToolUse hook - called before tool execution, can block or modify
589
+ */
590
+ type PreToolUseHook<T extends ToolMap> = (ctx: PreToolUseHookContext<T>) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
591
+ /**
592
+ * Context for PostToolUse hook - called after successful tool execution
593
+ */
594
+ interface PostToolUseHookContext<T extends ToolMap, TResult = unknown> {
595
+ /** The tool call that was executed */
596
+ toolCall: ParsedToolCallUnion<T>;
597
+ /** The result from the tool handler */
598
+ result: TResult;
599
+ /** Thread identifier */
600
+ threadId: string;
601
+ /** Current turn number */
602
+ turn: number;
603
+ /** Execution duration in milliseconds */
604
+ durationMs: number;
605
+ }
606
+ /**
607
+ * PostToolUse hook - called after successful tool execution
608
+ */
609
+ type PostToolUseHook<T extends ToolMap, TResult = unknown> = (ctx: PostToolUseHookContext<T, TResult>) => void | Promise<void>;
610
+ /**
611
+ * Context for PostToolUseFailure hook - called when tool execution fails
612
+ */
613
+ interface PostToolUseFailureHookContext<T extends ToolMap> {
614
+ /** The tool call that failed */
615
+ toolCall: ParsedToolCallUnion<T>;
616
+ /** The error that occurred */
617
+ error: Error;
618
+ /** Thread identifier */
619
+ threadId: string;
620
+ /** Current turn number */
621
+ turn: number;
622
+ }
623
+ /**
624
+ * Result from PostToolUseFailure hook - can recover from errors
625
+ */
626
+ interface PostToolUseFailureHookResult {
627
+ /** Provide a fallback result instead of throwing */
628
+ fallbackContent?: ToolMessageContent;
629
+ /** Whether to suppress the error (still logs, but continues) */
630
+ suppress?: boolean;
631
+ }
632
+ /**
633
+ * PostToolUseFailure hook - called when tool execution fails
634
+ */
635
+ type PostToolUseFailureHook<T extends ToolMap> = (ctx: PostToolUseFailureHookContext<T>) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
636
+ /**
637
+ * Context for SessionStart hook - called when session begins
638
+ */
639
+ interface SessionStartHookContext {
640
+ /** Thread identifier */
641
+ threadId: string;
642
+ /** Name of the agent */
643
+ agentName: string;
644
+ /** Session metadata */
645
+ metadata: Record<string, unknown>;
646
+ }
647
+ /**
648
+ * SessionStart hook - called when session begins
649
+ */
650
+ type SessionStartHook = (ctx: SessionStartHookContext) => void | Promise<void>;
651
+ /**
652
+ * Context for SessionEnd hook - called when session ends
653
+ */
654
+ interface SessionEndHookContext {
655
+ /** Thread identifier */
656
+ threadId: string;
657
+ /** Name of the agent */
658
+ agentName: string;
659
+ /** Reason the session ended */
660
+ exitReason: SessionExitReason;
661
+ /** Total turns executed */
662
+ turns: number;
663
+ /** Session metadata */
664
+ metadata: Record<string, unknown>;
665
+ }
666
+ /**
667
+ * SessionEnd hook - called when session ends
668
+ */
669
+ type SessionEndHook = (ctx: SessionEndHookContext) => void | Promise<void>;
670
+ /**
671
+ * Combined hooks interface for session lifecycle
672
+ */
673
+ interface Hooks<T extends ToolMap, TResult = unknown> {
674
+ /** Called before each tool execution - can block or modify */
675
+ onPreToolUse?: PreToolUseHook<T>;
676
+ /** Called after each successful tool execution */
677
+ onPostToolUse?: PostToolUseHook<T, TResult>;
678
+ /** Called when tool execution fails */
679
+ onPostToolUseFailure?: PostToolUseFailureHook<T>;
680
+ /** Called when session starts */
681
+ onSessionStart?: SessionStartHook;
682
+ /** Called when session ends */
683
+ onSessionEnd?: SessionEndHook;
684
+ }
685
+ /**
686
+ * Helper to check if status is terminal
687
+ */
688
+ declare function isTerminalStatus(status: AgentStatus): boolean;
689
+
690
+ interface ZeitlichSession {
691
+ runSession<T extends JsonSerializable<T>>(args: {
692
+ stateManager: AgentStateManager<T>;
693
+ }): Promise<StoredMessage | null>;
694
+ }
695
+ /**
696
+ * Session-level hooks for lifecycle events
697
+ */
698
+ interface SessionLifecycleHooks {
699
+ /** Called when session starts */
700
+ onSessionStart?: SessionStartHook;
701
+ /** Called when session ends */
702
+ onSessionEnd?: SessionEndHook;
703
+ }
704
+ declare const createSession: <T extends ToolMap>({ threadId, agentName, maxTurns, metadata, runAgent, baseSystemPrompt, instructionsPrompt, buildContextMessage, buildFileTree, subagents, tools, processToolsInParallel, buildInTools, hooks, }: ZeitlichAgentConfig<T>) => Promise<ZeitlichSession>;
705
+
706
+ /**
707
+ * Creates a Task tool configured with the available subagents.
708
+ *
709
+ * @param subagents - Array of subagent configurations (must have at least one)
710
+ * @returns A tool definition with dynamic schema based on available subagents
711
+ *
712
+ * @example
713
+ * const taskTool = createTaskTool([
714
+ * {
715
+ * name: "researcher",
716
+ * description: "Researches topics and gathers information",
717
+ * workflowType: "researcherWorkflow",
718
+ * resultSchema: z.object({ findings: z.string() }),
719
+ * },
720
+ * ]);
721
+ */
722
+ declare function createTaskTool<T extends SubagentConfig[]>(subagents: T): {
723
+ name: string;
724
+ description: string;
725
+ schema: z.ZodObject<{
726
+ subagent: z.ZodEnum<Record<string, string>>;
727
+ description: z.ZodString;
728
+ prompt: z.ZodString;
729
+ }>;
730
+ };
731
+ /**
732
+ * Infer the schema type for a task tool created with specific subagents
733
+ */
734
+ type TaskToolSchemaType<T extends SubagentConfig[]> = z.infer<ReturnType<typeof createTaskTool<T>>["schema"]>;
735
+ /**
736
+ * Generic task tool schema type (when subagent names are not known at compile time)
737
+ */
738
+ type GenericTaskToolSchemaType = {
739
+ subagent: string;
740
+ description: string;
741
+ prompt: string;
742
+ };
743
+
744
+ /**
745
+ * Result from a task handler execution
746
+ */
747
+ interface TaskHandlerResult<TResult = unknown> {
748
+ /** The validated result from the child workflow */
749
+ result: TResult;
750
+ /** The child workflow ID (for reference/debugging) */
751
+ childWorkflowId: string;
752
+ }
753
+
754
+ /**
755
+ * Shared Zeitlich activities - thread management and message handling
756
+ * Note: runAgent is workflow-specific and should be created per-workflow
757
+ */
758
+ interface ZeitlichSharedActivities {
759
+ appendSystemMessage(threadId: string, content: string): Promise<void>;
760
+ /**
761
+ * Append a tool result to the thread.
762
+ * Handles JSON serialization and optional cache points.
763
+ */
764
+ appendToolResult(config: ToolResultConfig): Promise<void>;
765
+ /**
766
+ * Initialize an empty thread.
767
+ */
768
+ initializeThread(threadId: string): Promise<void>;
769
+ /**
770
+ * Append a system message to a thread.
771
+ */
772
+ appendSystemMessage(threadId: string, content: string): Promise<void>;
773
+ /**
774
+ * Append messages to a thread.
775
+ */
776
+ appendThreadMessages(threadId: string, messages: StoredMessage[]): Promise<void>;
777
+ /**
778
+ * Append a human message to a thread.
779
+ */
780
+ appendHumanMessage(threadId: string, content: string | MessageContent): Promise<void>;
781
+ /**
782
+ * Extract raw tool calls from a stored message.
783
+ * Returns unvalidated tool calls - use toolRegistry.parseToolCall() to validate.
784
+ */
785
+ parseToolCalls(storedMessage: StoredMessage): Promise<RawToolCall[]>;
786
+ }
787
+ /**
788
+ * Creates shared Temporal activities for thread management
789
+ *
790
+ * @returns An object containing the shared activity functions
791
+ *
792
+ * @experimental The Zeitlich integration is an experimental feature; APIs may change without notice.
793
+ */
794
+ declare function createSharedActivities(redis: Redis): ZeitlichSharedActivities;
795
+
796
+ declare const askUserQuestionTool: {
797
+ name: "AskUserQuestion";
798
+ description: string;
799
+ schema: z.ZodObject<{
800
+ questions: z.ZodArray<z.ZodObject<{
801
+ question: z.ZodString;
802
+ header: z.ZodString;
803
+ options: z.ZodArray<z.ZodObject<{
804
+ label: z.ZodString;
805
+ description: z.ZodString;
806
+ }, z.core.$strip>>;
807
+ multiSelect: z.ZodBoolean;
808
+ }, z.core.$strip>>;
809
+ }, z.core.$strip>;
810
+ strict: boolean;
811
+ };
812
+ type AskUserQuestionToolSchemaType = z.infer<typeof askUserQuestionTool.schema>;
813
+
814
+ declare const globTool: {
815
+ name: "Glob";
816
+ description: string;
817
+ schema: z$1.ZodObject<{
818
+ pattern: z$1.ZodString;
819
+ root: z$1.ZodOptional<z$1.ZodString>;
820
+ }, z$1.core.$strip>;
821
+ strict: boolean;
822
+ };
823
+ type GlobToolSchemaType = z$1.infer<typeof globTool.schema>;
824
+
825
+ declare const grepTool: {
826
+ name: "Grep";
827
+ description: string;
828
+ schema: z$1.ZodObject<{
829
+ pattern: z$1.ZodString;
830
+ ignoreCase: z$1.ZodOptional<z$1.ZodBoolean>;
831
+ maxMatches: z$1.ZodOptional<z$1.ZodNumber>;
832
+ includePatterns: z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>;
833
+ excludePatterns: z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>;
834
+ contextLines: z$1.ZodOptional<z$1.ZodNumber>;
835
+ }, z$1.core.$strip>;
836
+ strict: boolean;
837
+ };
838
+ type GrepToolSchemaType = z$1.infer<typeof grepTool.schema>;
839
+
840
+ declare const readTool: {
841
+ name: "FileRead";
842
+ description: string;
843
+ schema: z$1.ZodObject<{
844
+ path: z$1.ZodString;
845
+ offset: z$1.ZodOptional<z$1.ZodNumber>;
846
+ limit: z$1.ZodOptional<z$1.ZodNumber>;
847
+ }, z$1.core.$strip>;
848
+ strict: boolean;
849
+ };
850
+ type ReadToolSchemaType = z$1.infer<typeof readTool.schema>;
851
+
852
+ declare const writeTool: {
853
+ name: "FileWrite";
854
+ description: string;
855
+ schema: z$1.ZodObject<{
856
+ file_path: z$1.ZodString;
857
+ content: z$1.ZodString;
858
+ }, z$1.core.$strip>;
859
+ strict: boolean;
860
+ };
861
+ type WriteToolSchemaType = z$1.infer<typeof writeTool.schema>;
862
+
863
+ declare const editTool: {
864
+ name: "FileEdit";
865
+ description: string;
866
+ schema: z$1.ZodObject<{
867
+ file_path: z$1.ZodString;
868
+ old_string: z$1.ZodString;
869
+ new_string: z$1.ZodString;
870
+ replace_all: z$1.ZodOptional<z$1.ZodBoolean>;
871
+ }, z$1.core.$strip>;
872
+ strict: boolean;
873
+ };
874
+ type EditToolSchemaType = z$1.infer<typeof editTool.schema>;
875
+
876
+ declare const taskGetTool: {
877
+ name: "TaskGet";
878
+ description: string;
879
+ schema: z.ZodObject<{
880
+ taskId: z.ZodString;
881
+ }, z.core.$strip>;
882
+ };
883
+ type TaskGetToolSchemaType = z.infer<typeof taskGetTool.schema>;
884
+
885
+ /**
886
+ * Creates a TaskGet handler that retrieves a task by ID.
887
+ *
888
+ * @param stateManager - State manager containing tasks state
889
+ * @returns A tool handler function
890
+ *
891
+ * @example
892
+ * const handler = createTaskGetHandler(stateManager);
893
+ */
894
+ declare function createTaskGetHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskGetToolSchemaType) => ToolHandlerResponse<WorkflowTask | null>;
895
+
896
+ declare const taskListTool: {
897
+ name: "TaskList";
898
+ description: string;
899
+ schema: z.ZodObject<{}, z.core.$strip>;
900
+ };
901
+ type TaskListToolSchemaType = z.infer<typeof taskListTool.schema>;
902
+
903
+ /**
904
+ * Creates a TaskList handler that returns all tasks.
905
+ *
906
+ * @param stateManager - State manager containing tasks state
907
+ * @returns A tool handler function
908
+ *
909
+ * @example
910
+ * const handler = createTaskListHandler(stateManager);
911
+ */
912
+ declare function createTaskListHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskListToolSchemaType) => ToolHandlerResponse<WorkflowTask[]>;
913
+
914
+ declare const taskUpdateTool: {
915
+ name: "TaskUpdate";
916
+ description: string;
917
+ schema: z.ZodObject<{
918
+ taskId: z.ZodString;
919
+ status: z.ZodEnum<{
920
+ pending: "pending";
921
+ in_progress: "in_progress";
922
+ completed: "completed";
923
+ }>;
924
+ addBlockedBy: z.ZodArray<z.ZodString>;
925
+ addBlocks: z.ZodArray<z.ZodString>;
926
+ }, z.core.$strip>;
927
+ };
928
+ type TaskUpdateToolSchemaType = z.infer<typeof taskUpdateTool.schema>;
929
+
930
+ /**
931
+ * Creates a TaskUpdate handler that modifies task status and dependencies.
932
+ *
933
+ * @param stateManager - State manager containing tasks state
934
+ * @returns A tool handler function
935
+ *
936
+ * @example
937
+ * const handler = createTaskUpdateHandler(stateManager);
938
+ */
939
+ declare function createTaskUpdateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): (args: TaskUpdateToolSchemaType) => ToolHandlerResponse<WorkflowTask | null>;
940
+
941
+ export { type ToolHandlerResponse as $, type AgentResponse as A, type BaseAgentState as B, type SessionExitReason as C, type SessionLifecycleHooks as D, type EditToolSchemaType as E, type SessionStartHook as F, type GlobToolSchemaType as G, type SessionStartHookContext as H, type InferToolResults as I, type JsonPrimitive as J, type SubagentConfig as K, type SubagentInput as L, type TaskGetToolSchemaType as M, type TaskHandlerResult as N, type TaskStatus as O, type ParsedToolCall as P, type TaskToolSchemaType as Q, type RawToolCall as R, type SessionEndHook as S, type TaskCreateToolSchemaType as T, type TaskUpdateToolSchemaType as U, type ToolArgs as V, type ToolCallResult as W, type ToolCallResultUnion as X, type ToolDefinition as Y, type ToolHandler as Z, type ToolHandlerContext as _, type ActivityToolHandler as a, type ToolMap as a0, type ToolMessageContent as a1, type ToolNames as a2, type ToolResult as a3, type ToolResultConfig as a4, type ToolRouter as a5, type ToolWithHandler as a6, type WorkflowTask as a7, type WriteToolSchemaType as a8, type ZeitlichAgentConfig as a9, type ZeitlichSession as aa, type ZeitlichSharedActivities as ab, askUserQuestionTool as ac, bashTool as ad, type bashToolSchemaType as ae, createAgentStateManager as af, createSession as ag, createSharedActivities as ah, createTaskCreateHandler as ai, createTaskGetHandler as aj, createTaskListHandler as ak, createTaskTool as al, createTaskUpdateHandler as am, createToolRouter as an, editTool as ao, globTool as ap, grepTool as aq, handleBashTool as ar, hasNoOtherToolCalls as as, isTerminalStatus as at, readTool as au, taskCreateTool as av, taskGetTool as aw, taskListTool as ax, taskUpdateTool as ay, writeTool as az, type AskUserQuestionToolSchemaType as b, AGENT_HANDLER_NAMES as c, type AgentFile as d, type AgentState as e, type AgentStateManager as f, type AgentStatus as g, type AppendToolResultFn as h, type GenericTaskToolSchemaType as i, type GrepToolSchemaType as j, type JsonSerializable as k, type JsonValue as l, type ParsedToolCallUnion as m, type PostToolUseFailureHook as n, type PostToolUseFailureHookContext as o, type PostToolUseFailureHookResult as p, type PostToolUseHook as q, type PostToolUseHookContext as r, type PreToolUseHook as s, type PreToolUseHookContext as t, type PreToolUseHookResult as u, type ProcessToolCallsContext as v, type ReadToolSchemaType as w, type RunAgentActivity as x, type RunAgentConfig as y, type SessionEndHookContext as z };