zeitlich 0.1.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.
- package/LICENSE +21 -0
- package/README.md +494 -0
- package/dist/index.d.mts +152 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.js +1623 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1582 -0
- package/dist/index.mjs.map +1 -0
- package/dist/workflow-DeVGEXSc.d.mts +1201 -0
- package/dist/workflow-DeVGEXSc.d.ts +1201 -0
- package/dist/workflow.d.mts +4 -0
- package/dist/workflow.d.ts +4 -0
- package/dist/workflow.js +762 -0
- package/dist/workflow.js.map +1 -0
- package/dist/workflow.mjs +734 -0
- package/dist/workflow.mjs.map +1 -0
- package/package.json +92 -0
|
@@ -0,0 +1,1201 @@
|
|
|
1
|
+
import { $InferMessageContent, MessageStructure, StoredMessage, MessageContent, ContentBlock } from '@langchain/core/messages';
|
|
2
|
+
import z$1, { z } from 'zod';
|
|
3
|
+
import Redis from 'ioredis';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Content for a tool message response.
|
|
7
|
+
* Can be a simple string or complex content parts (text, images, cache points, etc.)
|
|
8
|
+
*/
|
|
9
|
+
type ToolMessageContent = $InferMessageContent<MessageStructure, "tool">;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A tool definition with a name, description, and Zod schema for arguments.
|
|
13
|
+
*/
|
|
14
|
+
interface ToolDefinition<TName extends string = string, TSchema extends z.ZodType = z.ZodType> {
|
|
15
|
+
name: TName;
|
|
16
|
+
description: string;
|
|
17
|
+
schema: TSchema;
|
|
18
|
+
strict?: boolean;
|
|
19
|
+
max_uses?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A map of tool keys to tool definitions.
|
|
23
|
+
*/
|
|
24
|
+
type ToolMap = Record<string, ToolDefinition>;
|
|
25
|
+
/**
|
|
26
|
+
* Extract the tool names from a tool map (uses the tool's name property, not the key).
|
|
27
|
+
*/
|
|
28
|
+
type ToolNames<T extends ToolMap> = T[keyof T]["name"];
|
|
29
|
+
/**
|
|
30
|
+
* A raw tool call as received from the LLM before parsing.
|
|
31
|
+
*/
|
|
32
|
+
interface RawToolCall {
|
|
33
|
+
id?: string;
|
|
34
|
+
name: string;
|
|
35
|
+
args: unknown;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A parsed tool call with validated arguments for a specific tool.
|
|
39
|
+
*/
|
|
40
|
+
interface ParsedToolCall<TName extends string = string, TArgs = unknown> {
|
|
41
|
+
id: string;
|
|
42
|
+
name: TName;
|
|
43
|
+
args: TArgs;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Union type of all possible parsed tool calls from a tool map.
|
|
47
|
+
*/
|
|
48
|
+
type ParsedToolCallUnion<T extends ToolMap> = {
|
|
49
|
+
[K in keyof T]: ParsedToolCall<T[K]["name"], z.infer<T[K]["schema"]>>;
|
|
50
|
+
}[keyof T];
|
|
51
|
+
/**
|
|
52
|
+
* The tool registry interface with full type inference.
|
|
53
|
+
*/
|
|
54
|
+
interface ToolRegistry<T extends ToolMap> {
|
|
55
|
+
/**
|
|
56
|
+
* Parse and validate a raw tool call against the registry.
|
|
57
|
+
* Returns a typed tool call with validated arguments.
|
|
58
|
+
*/
|
|
59
|
+
parseToolCall(toolCall: RawToolCall): ParsedToolCallUnion<T>;
|
|
60
|
+
/**
|
|
61
|
+
* Get the list of all tools in the registry.
|
|
62
|
+
*/
|
|
63
|
+
getToolList(): T[keyof T][];
|
|
64
|
+
/**
|
|
65
|
+
* Get a specific tool by its key in the registry.
|
|
66
|
+
*/
|
|
67
|
+
getTool<K extends keyof T>(name: K): T[K];
|
|
68
|
+
/**
|
|
69
|
+
* Check if a tool with the given name exists in the registry.
|
|
70
|
+
*/
|
|
71
|
+
hasTool(name: string): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Get all tool names in the registry.
|
|
74
|
+
*/
|
|
75
|
+
getToolNames(): ToolNames<T>[];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Creates a type-safe tool registry for parsing and managing tool definitions.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* const registry = createToolRegistry({
|
|
82
|
+
* AssessAttribute: assessAttributeTool,
|
|
83
|
+
* AskUserQuestion: userInteractionTool,
|
|
84
|
+
* });
|
|
85
|
+
*
|
|
86
|
+
* const toolCalls = message.tool_calls.map(tc => registry.parseToolCall(tc));
|
|
87
|
+
* const tools = registry.getToolList();
|
|
88
|
+
*/
|
|
89
|
+
declare function createToolRegistry<T extends ToolMap>(tools: T): ToolRegistry<T>;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Agent execution status
|
|
93
|
+
*/
|
|
94
|
+
type AgentStatus = "RUNNING" | "WAITING_FOR_INPUT" | "COMPLETED" | "FAILED" | "CANCELLED";
|
|
95
|
+
/**
|
|
96
|
+
* Base state that all agents must have
|
|
97
|
+
*/
|
|
98
|
+
interface BaseAgentState {
|
|
99
|
+
status: AgentStatus;
|
|
100
|
+
version: number;
|
|
101
|
+
turns: number;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* File representation for agent workflows
|
|
105
|
+
*/
|
|
106
|
+
interface AgentFile {
|
|
107
|
+
/** Database/S3 file ID */
|
|
108
|
+
id: string;
|
|
109
|
+
/** Virtual path for agent (e.g., "evidence/invoice.pdf") */
|
|
110
|
+
path: string;
|
|
111
|
+
/** Original filename */
|
|
112
|
+
filename: string;
|
|
113
|
+
/** Generic description for prompt */
|
|
114
|
+
description?: string;
|
|
115
|
+
/** MIME type of the file */
|
|
116
|
+
mimeType?: string;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Agent response from LLM invocation
|
|
120
|
+
*/
|
|
121
|
+
interface AgentResponse {
|
|
122
|
+
message: StoredMessage;
|
|
123
|
+
stopReason: string | null;
|
|
124
|
+
usage?: {
|
|
125
|
+
input_tokens?: number;
|
|
126
|
+
output_tokens?: number;
|
|
127
|
+
total_tokens?: number;
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Configuration for a Zeitlich agent session
|
|
132
|
+
*/
|
|
133
|
+
interface ZeitlichAgentConfig {
|
|
134
|
+
threadId: string;
|
|
135
|
+
agentName: string;
|
|
136
|
+
metadata?: Record<string, unknown>;
|
|
137
|
+
maxTurns?: number;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Configuration passed to runAgent activity
|
|
141
|
+
*/
|
|
142
|
+
interface RunAgentConfig {
|
|
143
|
+
threadId: string;
|
|
144
|
+
agentName: string;
|
|
145
|
+
metadata?: Record<string, unknown>;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Type signature for workflow-specific runAgent activity
|
|
149
|
+
*/
|
|
150
|
+
type RunAgentActivity = (config: RunAgentConfig, invocationConfig: InvocationConfig) => Promise<AgentResponse>;
|
|
151
|
+
/**
|
|
152
|
+
* Per-invocation configuration passed to runAgent
|
|
153
|
+
*/
|
|
154
|
+
interface InvocationConfig {
|
|
155
|
+
systemPrompt: string;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Configuration for appending a tool result
|
|
159
|
+
*/
|
|
160
|
+
interface ToolResultConfig {
|
|
161
|
+
threadId: string;
|
|
162
|
+
toolCallId: string;
|
|
163
|
+
/** Content for the tool message (string or complex content parts) */
|
|
164
|
+
content: ToolMessageContent;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Configuration for a subagent that can be spawned by the parent workflow.
|
|
168
|
+
*
|
|
169
|
+
* @template TResult - Zod schema type for validating the child workflow's result
|
|
170
|
+
*/
|
|
171
|
+
interface SubagentConfig<TResult extends z.ZodType = z.ZodType> {
|
|
172
|
+
/** Identifier used in Task tool's subagent parameter */
|
|
173
|
+
name: string;
|
|
174
|
+
/** Description shown to the parent agent explaining what this subagent does */
|
|
175
|
+
description: string;
|
|
176
|
+
/** Temporal workflow type name (used with executeChild) */
|
|
177
|
+
workflowType: string;
|
|
178
|
+
/** Optional task queue - defaults to parent's queue if not specified */
|
|
179
|
+
taskQueue?: string;
|
|
180
|
+
/** Optional Zod schema to validate the child workflow's result. If omitted, result is passed through as-is. */
|
|
181
|
+
resultSchema?: TResult;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Input passed to child workflows when spawned as subagents
|
|
185
|
+
*/
|
|
186
|
+
interface SubagentInput {
|
|
187
|
+
/** The prompt/task from the parent agent */
|
|
188
|
+
prompt: string;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Exit reasons for session termination
|
|
192
|
+
*/
|
|
193
|
+
type SessionExitReason = "completed" | "max_turns" | "waiting_for_input" | "failed" | "cancelled";
|
|
194
|
+
/**
|
|
195
|
+
* Context for PreToolUse hook - called before tool execution
|
|
196
|
+
*/
|
|
197
|
+
interface PreToolUseHookContext<T extends ToolMap> {
|
|
198
|
+
/** The tool call about to be executed */
|
|
199
|
+
toolCall: ParsedToolCallUnion<T>;
|
|
200
|
+
/** Thread identifier */
|
|
201
|
+
threadId: string;
|
|
202
|
+
/** Current turn number */
|
|
203
|
+
turn: number;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Result from PreToolUse hook - can block or modify execution
|
|
207
|
+
*/
|
|
208
|
+
interface PreToolUseHookResult {
|
|
209
|
+
/** Skip this tool call entirely */
|
|
210
|
+
skip?: boolean;
|
|
211
|
+
/** Modified args to use instead (must match schema) */
|
|
212
|
+
modifiedArgs?: unknown;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* PreToolUse hook - called before tool execution, can block or modify
|
|
216
|
+
*/
|
|
217
|
+
type PreToolUseHook<T extends ToolMap> = (ctx: PreToolUseHookContext<T>) => PreToolUseHookResult | Promise<PreToolUseHookResult>;
|
|
218
|
+
/**
|
|
219
|
+
* Context for PostToolUse hook - called after successful tool execution
|
|
220
|
+
*/
|
|
221
|
+
interface PostToolUseHookContext<T extends ToolMap, TResult = unknown> {
|
|
222
|
+
/** The tool call that was executed */
|
|
223
|
+
toolCall: ParsedToolCallUnion<T>;
|
|
224
|
+
/** The result from the tool handler */
|
|
225
|
+
result: TResult;
|
|
226
|
+
/** Thread identifier */
|
|
227
|
+
threadId: string;
|
|
228
|
+
/** Current turn number */
|
|
229
|
+
turn: number;
|
|
230
|
+
/** Execution duration in milliseconds */
|
|
231
|
+
durationMs: number;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* PostToolUse hook - called after successful tool execution
|
|
235
|
+
*/
|
|
236
|
+
type PostToolUseHook<T extends ToolMap, TResult = unknown> = (ctx: PostToolUseHookContext<T, TResult>) => void | Promise<void>;
|
|
237
|
+
/**
|
|
238
|
+
* Context for PostToolUseFailure hook - called when tool execution fails
|
|
239
|
+
*/
|
|
240
|
+
interface PostToolUseFailureHookContext<T extends ToolMap> {
|
|
241
|
+
/** The tool call that failed */
|
|
242
|
+
toolCall: ParsedToolCallUnion<T>;
|
|
243
|
+
/** The error that occurred */
|
|
244
|
+
error: Error;
|
|
245
|
+
/** Thread identifier */
|
|
246
|
+
threadId: string;
|
|
247
|
+
/** Current turn number */
|
|
248
|
+
turn: number;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Result from PostToolUseFailure hook - can recover from errors
|
|
252
|
+
*/
|
|
253
|
+
interface PostToolUseFailureHookResult {
|
|
254
|
+
/** Provide a fallback result instead of throwing */
|
|
255
|
+
fallbackContent?: ToolMessageContent;
|
|
256
|
+
/** Whether to suppress the error (still logs, but continues) */
|
|
257
|
+
suppress?: boolean;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* PostToolUseFailure hook - called when tool execution fails
|
|
261
|
+
*/
|
|
262
|
+
type PostToolUseFailureHook<T extends ToolMap> = (ctx: PostToolUseFailureHookContext<T>) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;
|
|
263
|
+
/**
|
|
264
|
+
* Context for SessionStart hook - called when session begins
|
|
265
|
+
*/
|
|
266
|
+
interface SessionStartHookContext {
|
|
267
|
+
/** Thread identifier */
|
|
268
|
+
threadId: string;
|
|
269
|
+
/** Name of the agent */
|
|
270
|
+
agentName: string;
|
|
271
|
+
/** Session metadata */
|
|
272
|
+
metadata: Record<string, unknown>;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* SessionStart hook - called when session begins
|
|
276
|
+
*/
|
|
277
|
+
type SessionStartHook = (ctx: SessionStartHookContext) => void | Promise<void>;
|
|
278
|
+
/**
|
|
279
|
+
* Context for SessionEnd hook - called when session ends
|
|
280
|
+
*/
|
|
281
|
+
interface SessionEndHookContext {
|
|
282
|
+
/** Thread identifier */
|
|
283
|
+
threadId: string;
|
|
284
|
+
/** Name of the agent */
|
|
285
|
+
agentName: string;
|
|
286
|
+
/** Reason the session ended */
|
|
287
|
+
exitReason: SessionExitReason;
|
|
288
|
+
/** Total turns executed */
|
|
289
|
+
turns: number;
|
|
290
|
+
/** Session metadata */
|
|
291
|
+
metadata: Record<string, unknown>;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* SessionEnd hook - called when session ends
|
|
295
|
+
*/
|
|
296
|
+
type SessionEndHook = (ctx: SessionEndHookContext) => void | Promise<void>;
|
|
297
|
+
/**
|
|
298
|
+
* Combined hooks interface for session lifecycle
|
|
299
|
+
*/
|
|
300
|
+
interface SessionHooks<T extends ToolMap, TResult = unknown> {
|
|
301
|
+
/** Called before each tool execution - can block or modify */
|
|
302
|
+
onPreToolUse?: PreToolUseHook<T>;
|
|
303
|
+
/** Called after each successful tool execution */
|
|
304
|
+
onPostToolUse?: PostToolUseHook<T, TResult>;
|
|
305
|
+
/** Called when tool execution fails */
|
|
306
|
+
onPostToolUseFailure?: PostToolUseFailureHook<T>;
|
|
307
|
+
/** Called when session starts */
|
|
308
|
+
onSessionStart?: SessionStartHook;
|
|
309
|
+
/** Called when session ends */
|
|
310
|
+
onSessionEnd?: SessionEndHook;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Helper to check if status is terminal
|
|
314
|
+
*/
|
|
315
|
+
declare function isTerminalStatus(status: AgentStatus): boolean;
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* JSON primitive types that Temporal can serialize
|
|
319
|
+
*/
|
|
320
|
+
type JsonPrimitive = string | number | boolean | null | undefined;
|
|
321
|
+
/**
|
|
322
|
+
* JSON-serializable value (recursive type for Temporal compatibility)
|
|
323
|
+
*/
|
|
324
|
+
type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
325
|
+
[key: string]: JsonValue;
|
|
326
|
+
};
|
|
327
|
+
/**
|
|
328
|
+
* Type constraint ensuring T only contains JSON-serializable values.
|
|
329
|
+
* Use this for custom state to ensure Temporal workflow compatibility.
|
|
330
|
+
*
|
|
331
|
+
* Allows: primitives, arrays, plain objects, and JsonValue
|
|
332
|
+
* Rejects: functions, symbols, undefined, class instances with methods
|
|
333
|
+
*/
|
|
334
|
+
type JsonSerializable<T> = {
|
|
335
|
+
[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;
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* Configuration for creating an agent state manager
|
|
339
|
+
*/
|
|
340
|
+
interface AgentStateManagerConfig<TCustom extends JsonSerializable<TCustom>> {
|
|
341
|
+
/** Initial values for custom state keys */
|
|
342
|
+
initialState: TCustom;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Full state type combining base state with custom state
|
|
346
|
+
*/
|
|
347
|
+
type AgentState<TCustom extends JsonSerializable<TCustom>> = BaseAgentState & TCustom;
|
|
348
|
+
/**
|
|
349
|
+
* Agent state manager interface
|
|
350
|
+
* Note: Temporal handlers must be set up in the workflow file due to
|
|
351
|
+
* Temporal's workflow isolation requirements. This manager provides
|
|
352
|
+
* the state and helpers needed for those handlers.
|
|
353
|
+
*/
|
|
354
|
+
interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {
|
|
355
|
+
/** Get current status */
|
|
356
|
+
getStatus(): AgentStatus;
|
|
357
|
+
/** Check if agent is running */
|
|
358
|
+
isRunning(): boolean;
|
|
359
|
+
/** Check if agent is in terminal state */
|
|
360
|
+
isTerminal(): boolean;
|
|
361
|
+
/** Get current state version */
|
|
362
|
+
getVersion(): number;
|
|
363
|
+
/** Set status to RUNNING */
|
|
364
|
+
run(): void;
|
|
365
|
+
/** Set status to WAITING_FOR_INPUT */
|
|
366
|
+
waitForInput(): void;
|
|
367
|
+
/** Set status to COMPLETED */
|
|
368
|
+
complete(): void;
|
|
369
|
+
/** Set status to FAILED */
|
|
370
|
+
fail(): void;
|
|
371
|
+
/** Set status to CANCELLED */
|
|
372
|
+
cancel(): void;
|
|
373
|
+
/** Increment state version (call after state changes) */
|
|
374
|
+
incrementVersion(): void;
|
|
375
|
+
/** Increment turns (call after each turn) */
|
|
376
|
+
incrementTurns(): void;
|
|
377
|
+
/** Get current turns */
|
|
378
|
+
getTurns(): number;
|
|
379
|
+
/** Get a custom state value by key */
|
|
380
|
+
get<K extends keyof TCustom>(key: K): TCustom[K];
|
|
381
|
+
/** Set a custom state value by key */
|
|
382
|
+
set<K extends keyof TCustom>(key: K, value: TCustom[K]): void;
|
|
383
|
+
/** Get full state for query handler */
|
|
384
|
+
getCurrentState(): AgentState<TCustom>;
|
|
385
|
+
/** Check if should return from waitForStateChange */
|
|
386
|
+
shouldReturnFromWait(lastKnownVersion: number): boolean;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Creates an agent state manager for tracking workflow state.
|
|
390
|
+
*
|
|
391
|
+
* The manager owns all state internally:
|
|
392
|
+
* - Default state: status, version (from BaseAgentState)
|
|
393
|
+
* - Custom state: provided via initialState config
|
|
394
|
+
*
|
|
395
|
+
* Note: Due to Temporal's workflow isolation, handlers must be set up
|
|
396
|
+
* in the workflow file using defineQuery/defineUpdate and setHandler.
|
|
397
|
+
* This manager provides the state and logic needed for those handlers.
|
|
398
|
+
*/
|
|
399
|
+
declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>(config?: AgentStateManagerConfig<TCustom>): AgentStateManager<TCustom>;
|
|
400
|
+
/**
|
|
401
|
+
* Handler names used across agents
|
|
402
|
+
*/
|
|
403
|
+
declare const AGENT_HANDLER_NAMES: {
|
|
404
|
+
readonly getAgentState: "getAgentState";
|
|
405
|
+
readonly waitForStateChange: "waitForStateChange";
|
|
406
|
+
readonly addMessage: "addMessage";
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Configuration for creating a prompt manager
|
|
411
|
+
*/
|
|
412
|
+
interface PromptManagerConfig<TContext = unknown> {
|
|
413
|
+
/**
|
|
414
|
+
* Base system prompt (e.g., Auditron identity).
|
|
415
|
+
* Can be a static string or async function.
|
|
416
|
+
*/
|
|
417
|
+
baseSystemPrompt: string | (() => string | Promise<string>);
|
|
418
|
+
/**
|
|
419
|
+
* Agent-specific instructions prompt.
|
|
420
|
+
* Can be a static string or async function.
|
|
421
|
+
*/
|
|
422
|
+
instructionsPrompt: string | (() => string | Promise<string>);
|
|
423
|
+
/**
|
|
424
|
+
* Build context message content from agent-specific context.
|
|
425
|
+
* Returns MessageContent array for the initial HumanMessage.
|
|
426
|
+
*/
|
|
427
|
+
buildContextMessage: (context: TContext) => MessageContent | Promise<MessageContent>;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Prompt manager interface
|
|
431
|
+
*/
|
|
432
|
+
interface PromptManager<TContext = unknown> {
|
|
433
|
+
/**
|
|
434
|
+
* Get the full system prompt (base + instructions combined).
|
|
435
|
+
*/
|
|
436
|
+
getSystemPrompt(): Promise<string>;
|
|
437
|
+
/**
|
|
438
|
+
* Build the initial context message content.
|
|
439
|
+
*/
|
|
440
|
+
buildContextMessage(context: TContext): Promise<MessageContent>;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Creates a prompt manager for handling system prompts and context messages.
|
|
444
|
+
*
|
|
445
|
+
*/
|
|
446
|
+
declare function createPromptManager<TContext = unknown>(config: PromptManagerConfig<TContext>): PromptManager<TContext>;
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Function signature for appending tool results to a thread.
|
|
450
|
+
*/
|
|
451
|
+
type AppendToolResultFn = (config: ToolResultConfig) => Promise<void>;
|
|
452
|
+
/**
|
|
453
|
+
* The response from a tool handler.
|
|
454
|
+
* Contains the content for the tool message and the result to return from processToolCalls.
|
|
455
|
+
*/
|
|
456
|
+
interface ToolHandlerResponse<TResult> {
|
|
457
|
+
/** Content for the tool message added to the thread */
|
|
458
|
+
content: ToolMessageContent;
|
|
459
|
+
/** Result returned from processToolCalls */
|
|
460
|
+
result: TResult;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* A handler function for a specific tool.
|
|
464
|
+
* Receives the parsed args and tool call ID, returns a response with content and result.
|
|
465
|
+
*/
|
|
466
|
+
type ToolHandler<TArgs, TResult> = (args: TArgs, toolCallId: string) => ToolHandlerResponse<TResult> | Promise<ToolHandlerResponse<TResult>>;
|
|
467
|
+
/**
|
|
468
|
+
* Activity-compatible tool handler that always returns a Promise.
|
|
469
|
+
* Use this for tool handlers registered as Temporal activities.
|
|
470
|
+
*/
|
|
471
|
+
type ActivityToolHandler<TArgs, TResult> = (args: TArgs, toolCallId: string) => Promise<ToolHandlerResponse<TResult>>;
|
|
472
|
+
/**
|
|
473
|
+
* Extract the args type for a specific tool name from a tool map.
|
|
474
|
+
*/
|
|
475
|
+
type ToolArgs<T extends ToolMap, TName extends ToolNames<T>> = z.infer<Extract<T[keyof T], {
|
|
476
|
+
name: TName;
|
|
477
|
+
}>["schema"]>;
|
|
478
|
+
/**
|
|
479
|
+
* A map of tool handlers keyed by tool name with typed results.
|
|
480
|
+
* Each handler receives the properly typed args for that tool.
|
|
481
|
+
*/
|
|
482
|
+
type ToolHandlerMap<T extends ToolMap, TResults extends Record<ToolNames<T>, unknown>> = {
|
|
483
|
+
[TName in ToolNames<T>]: ToolHandler<ToolArgs<T, TName>, TResults[TName]>;
|
|
484
|
+
};
|
|
485
|
+
/**
|
|
486
|
+
* The result of processing a tool call.
|
|
487
|
+
*/
|
|
488
|
+
interface ToolCallResult<TName extends string = string, TResult = unknown> {
|
|
489
|
+
toolCallId: string;
|
|
490
|
+
name: TName;
|
|
491
|
+
result: TResult;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Union of all possible tool call results based on handler return types.
|
|
495
|
+
*/
|
|
496
|
+
type ToolCallResultUnion<TResults extends Record<string, unknown>> = {
|
|
497
|
+
[TName in keyof TResults & string]: ToolCallResult<TName, TResults[TName]>;
|
|
498
|
+
}[keyof TResults & string];
|
|
499
|
+
/**
|
|
500
|
+
* Tool-specific hooks for the router
|
|
501
|
+
*/
|
|
502
|
+
interface ToolRouterHooks<T extends ToolMap, TResult = unknown> {
|
|
503
|
+
/** Called before each tool execution - can block or modify */
|
|
504
|
+
onPreToolUse?: PreToolUseHook<T>;
|
|
505
|
+
/** Called after each successful tool execution */
|
|
506
|
+
onPostToolUse?: PostToolUseHook<T, TResult>;
|
|
507
|
+
/** Called when tool execution fails */
|
|
508
|
+
onPostToolUseFailure?: PostToolUseFailureHook<T>;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Options for tool router.
|
|
512
|
+
*/
|
|
513
|
+
interface ToolRouterOptions<T extends ToolMap, TResult = unknown> {
|
|
514
|
+
/** Tool registry - used for type inference */
|
|
515
|
+
registry: ToolRegistry<T>;
|
|
516
|
+
/** Thread ID for appending tool results */
|
|
517
|
+
threadId: string;
|
|
518
|
+
/** Function to append tool results to the thread (called automatically after each handler) */
|
|
519
|
+
appendToolResult: AppendToolResultFn;
|
|
520
|
+
/** Whether to process tools in parallel (default: true) */
|
|
521
|
+
parallel?: boolean;
|
|
522
|
+
/** Lifecycle hooks for tool execution */
|
|
523
|
+
hooks?: ToolRouterHooks<T, TResult>;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Context passed to processToolCalls for hook execution
|
|
527
|
+
*/
|
|
528
|
+
interface ProcessToolCallsContext {
|
|
529
|
+
/** Current turn number (for hooks) */
|
|
530
|
+
turn?: number;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* The tool router interface with full type inference for both args and results.
|
|
534
|
+
*/
|
|
535
|
+
interface ToolRouter<T extends ToolMap, TResults extends Record<string, unknown>> {
|
|
536
|
+
/**
|
|
537
|
+
* Process all tool calls using the registered handlers.
|
|
538
|
+
* Returns typed results based on handler return types.
|
|
539
|
+
* @param toolCalls - Array of parsed tool calls to process
|
|
540
|
+
* @param context - Optional context including turn number for hooks
|
|
541
|
+
*/
|
|
542
|
+
processToolCalls(toolCalls: ParsedToolCallUnion<T>[], context?: ProcessToolCallsContext): Promise<ToolCallResultUnion<TResults>[]>;
|
|
543
|
+
/**
|
|
544
|
+
* Process tool calls matching a specific name with a custom handler.
|
|
545
|
+
*/
|
|
546
|
+
processToolCallsByName<TName extends ToolNames<T>, TResult>(toolCalls: ParsedToolCallUnion<T>[], toolName: TName, handler: ToolHandler<ToolArgs<T, TName>, TResult>): Promise<ToolCallResult<TName, TResult>[]>;
|
|
547
|
+
/**
|
|
548
|
+
* Filter tool calls by name.
|
|
549
|
+
*/
|
|
550
|
+
filterByName<TName extends ToolNames<T>>(toolCalls: ParsedToolCallUnion<T>[], name: TName): ParsedToolCall<TName, ToolArgs<T, TName>>[];
|
|
551
|
+
/**
|
|
552
|
+
* Check if any tool call matches the given name.
|
|
553
|
+
*/
|
|
554
|
+
hasToolCall(toolCalls: ParsedToolCallUnion<T>[], name: ToolNames<T>): boolean;
|
|
555
|
+
/**
|
|
556
|
+
* Filter results by tool name.
|
|
557
|
+
*/
|
|
558
|
+
getResultsByName<TName extends ToolNames<T> & keyof TResults>(results: ToolCallResultUnion<TResults>[], name: TName): ToolCallResult<TName, TResults[TName]>[];
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Infer result types from a handler map.
|
|
562
|
+
* Uses `any` for args due to function contravariance - handlers with specific
|
|
563
|
+
* args types won't extend ToolHandler<unknown, R>.
|
|
564
|
+
*/
|
|
565
|
+
type InferHandlerResults<H> = {
|
|
566
|
+
[K in keyof H & string]: H[K] extends ToolHandler<any, infer R> ? Awaited<R> : never;
|
|
567
|
+
};
|
|
568
|
+
/**
|
|
569
|
+
* Creates a tool router for declarative tool call processing.
|
|
570
|
+
* ToolMap type is inferred from options.registry, result types from handlers.
|
|
571
|
+
*
|
|
572
|
+
* @example
|
|
573
|
+
* const router = createToolRouter(
|
|
574
|
+
* {
|
|
575
|
+
* registry: controlTestToolRegistry,
|
|
576
|
+
* threadId,
|
|
577
|
+
* appendToolResult,
|
|
578
|
+
* hooks: {
|
|
579
|
+
* onPreToolUse: (ctx) => { console.log('Before:', ctx.toolCall.name); },
|
|
580
|
+
* onPostToolUse: (ctx) => { console.log('After:', ctx.toolCall.name, ctx.durationMs); },
|
|
581
|
+
* },
|
|
582
|
+
* },
|
|
583
|
+
* {
|
|
584
|
+
* AskUserQuestion: async (args, toolCallId) => ({ content: '...', result: {...} }),
|
|
585
|
+
* // ... other handlers
|
|
586
|
+
* },
|
|
587
|
+
* );
|
|
588
|
+
*
|
|
589
|
+
* const results = await router.processToolCalls(toolCalls, { turn: 1 });
|
|
590
|
+
* // results[0].result is typed based on handler return types
|
|
591
|
+
*/
|
|
592
|
+
declare function createToolRouter<T extends ToolMap, THandlers extends {
|
|
593
|
+
[TName in ToolNames<T>]: ToolHandler<ToolArgs<T, TName>, unknown>;
|
|
594
|
+
}>(options: ToolRouterOptions<T, ToolCallResultUnion<InferHandlerResults<THandlers>>>, handlers: THandlers): ToolRouter<T, InferHandlerResults<THandlers>>;
|
|
595
|
+
/**
|
|
596
|
+
* Utility to check if there were no tool calls besides a specific one
|
|
597
|
+
*/
|
|
598
|
+
declare function hasNoOtherToolCalls<T extends ToolMap>(toolCalls: ParsedToolCallUnion<T>[], excludeName: ToolNames<T>): boolean;
|
|
599
|
+
|
|
600
|
+
declare const TASK_TOOL: "Task";
|
|
601
|
+
/**
|
|
602
|
+
* Creates a Task tool configured with the available subagents.
|
|
603
|
+
*
|
|
604
|
+
* @param subagents - Array of subagent configurations (must have at least one)
|
|
605
|
+
* @returns A tool definition with dynamic schema based on available subagents
|
|
606
|
+
*
|
|
607
|
+
* @example
|
|
608
|
+
* const taskTool = createTaskTool([
|
|
609
|
+
* {
|
|
610
|
+
* name: "researcher",
|
|
611
|
+
* description: "Researches topics and gathers information",
|
|
612
|
+
* workflowType: "researcherWorkflow",
|
|
613
|
+
* resultSchema: z.object({ findings: z.string() }),
|
|
614
|
+
* },
|
|
615
|
+
* ]);
|
|
616
|
+
*/
|
|
617
|
+
declare function createTaskTool<T extends SubagentConfig[]>(subagents: T): {
|
|
618
|
+
name: typeof TASK_TOOL;
|
|
619
|
+
description: string;
|
|
620
|
+
schema: z$1.ZodObject<{
|
|
621
|
+
subagent: z$1.ZodEnum<Record<string, string>>;
|
|
622
|
+
description: z$1.ZodString;
|
|
623
|
+
prompt: z$1.ZodString;
|
|
624
|
+
}>;
|
|
625
|
+
};
|
|
626
|
+
/**
|
|
627
|
+
* Infer the schema type for a task tool created with specific subagents
|
|
628
|
+
*/
|
|
629
|
+
type TaskToolSchemaType<T extends SubagentConfig[]> = z$1.infer<ReturnType<typeof createTaskTool<T>>["schema"]>;
|
|
630
|
+
/**
|
|
631
|
+
* Generic task tool schema type (when subagent names are not known at compile time)
|
|
632
|
+
*/
|
|
633
|
+
type GenericTaskToolSchemaType = {
|
|
634
|
+
subagent: string;
|
|
635
|
+
description: string;
|
|
636
|
+
prompt: string;
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Result from a task handler execution
|
|
641
|
+
*/
|
|
642
|
+
interface TaskHandlerResult<TResult = unknown> {
|
|
643
|
+
/** The validated result from the child workflow */
|
|
644
|
+
result: TResult;
|
|
645
|
+
/** The child workflow ID (for reference/debugging) */
|
|
646
|
+
childWorkflowId: string;
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Creates a Task tool handler that spawns child workflows for configured subagents.
|
|
650
|
+
*
|
|
651
|
+
* @param subagents - Array of subagent configurations
|
|
652
|
+
* @returns A tool handler function that can be used with the tool router
|
|
653
|
+
*
|
|
654
|
+
* @example
|
|
655
|
+
* const taskHandler = createTaskHandler([
|
|
656
|
+
* {
|
|
657
|
+
* name: "researcher",
|
|
658
|
+
* description: "Researches topics",
|
|
659
|
+
* workflowType: "researcherWorkflow",
|
|
660
|
+
* resultSchema: z.object({ findings: z.string() }),
|
|
661
|
+
* },
|
|
662
|
+
* ]);
|
|
663
|
+
*/
|
|
664
|
+
declare function createTaskHandler(subagents: SubagentConfig[]): (args: GenericTaskToolSchemaType, _toolCallId: string) => Promise<ToolHandlerResponse<TaskHandlerResult>>;
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Configuration for subagent support
|
|
668
|
+
*/
|
|
669
|
+
interface SubagentSupportConfig {
|
|
670
|
+
/** Array of subagent configurations */
|
|
671
|
+
subagents: SubagentConfig[];
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Result from withSubagentSupport - contains enhanced tools and the task handler
|
|
675
|
+
*/
|
|
676
|
+
interface SubagentSupportResult<T extends ToolMap> {
|
|
677
|
+
/** Combined tools (user tools + Task tool) */
|
|
678
|
+
tools: T & {
|
|
679
|
+
Task: ReturnType<typeof createTaskTool>;
|
|
680
|
+
};
|
|
681
|
+
/** Task handler to be added to the tool router handlers */
|
|
682
|
+
taskHandler: ToolHandler<GenericTaskToolSchemaType, TaskHandlerResult>;
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Adds subagent support to a tool map by including the Task tool and handler.
|
|
686
|
+
*
|
|
687
|
+
* Use this when you want to enable subagent spawning in your workflow.
|
|
688
|
+
* The returned tools should be passed to createToolRegistry, and the
|
|
689
|
+
* taskHandler should be included in your tool router handlers.
|
|
690
|
+
*
|
|
691
|
+
* @param userTools - Your workflow's existing tools
|
|
692
|
+
* @param config - Subagent configuration
|
|
693
|
+
* @returns Combined tools and the task handler
|
|
694
|
+
*
|
|
695
|
+
* @example
|
|
696
|
+
* const { tools, taskHandler } = withSubagentSupport(
|
|
697
|
+
* { AskUserQuestion: askUserQuestionTool },
|
|
698
|
+
* {
|
|
699
|
+
* subagents: [
|
|
700
|
+
* {
|
|
701
|
+
* name: "researcher",
|
|
702
|
+
* description: "Researches and gathers information",
|
|
703
|
+
* workflowType: "researcherWorkflow",
|
|
704
|
+
* resultSchema: z.object({ findings: z.string() }),
|
|
705
|
+
* },
|
|
706
|
+
* ],
|
|
707
|
+
* }
|
|
708
|
+
* );
|
|
709
|
+
*
|
|
710
|
+
* const toolRegistry = createToolRegistry(tools);
|
|
711
|
+
* const toolRouter = createToolRouter(
|
|
712
|
+
* { registry: toolRegistry, threadId, appendToolResult },
|
|
713
|
+
* {
|
|
714
|
+
* AskUserQuestion: handleAskUserQuestion,
|
|
715
|
+
* Task: taskHandler,
|
|
716
|
+
* }
|
|
717
|
+
* );
|
|
718
|
+
*/
|
|
719
|
+
declare function withSubagentSupport<T extends ToolMap>(userTools: T, config: SubagentSupportConfig): SubagentSupportResult<T>;
|
|
720
|
+
/**
|
|
721
|
+
* Type guard to check if a tool map includes the Task tool
|
|
722
|
+
*/
|
|
723
|
+
declare function hasTaskTool(tools: ToolMap): tools is ToolMap & {
|
|
724
|
+
Task: ToolDefinition;
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
interface ZeitlichSession {
|
|
728
|
+
runSession<T extends JsonSerializable<T>>(prompt: string, stateManager: AgentStateManager<T>): Promise<StoredMessage | null>;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Session-level hooks for lifecycle events
|
|
732
|
+
*/
|
|
733
|
+
interface SessionLifecycleHooks {
|
|
734
|
+
/** Called when session starts */
|
|
735
|
+
onSessionStart?: SessionStartHook;
|
|
736
|
+
/** Called when session ends */
|
|
737
|
+
onSessionEnd?: SessionEndHook;
|
|
738
|
+
}
|
|
739
|
+
declare const createSession: <T extends ToolMap, TResults extends Record<string, unknown>>({ threadId, agentName, maxTurns, metadata }: ZeitlichAgentConfig, { runAgent, promptManager, toolRouter, toolRegistry, hooks, }: {
|
|
740
|
+
/** Workflow-specific runAgent activity (with tools pre-bound) */
|
|
741
|
+
runAgent: RunAgentActivity;
|
|
742
|
+
promptManager: PromptManager;
|
|
743
|
+
toolRouter: ToolRouter<T, TResults>;
|
|
744
|
+
toolRegistry: ToolRegistry<T>;
|
|
745
|
+
/** Session lifecycle hooks */
|
|
746
|
+
hooks?: SessionLifecycleHooks;
|
|
747
|
+
}) => Promise<ZeitlichSession>;
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Shared Zeitlich activities - thread management and message handling
|
|
751
|
+
* Note: runAgent is workflow-specific and should be created per-workflow
|
|
752
|
+
*/
|
|
753
|
+
interface ZeitlichSharedActivities {
|
|
754
|
+
/**
|
|
755
|
+
* Append a tool result to the thread.
|
|
756
|
+
* Handles JSON serialization and optional cache points.
|
|
757
|
+
*/
|
|
758
|
+
appendToolResult(config: ToolResultConfig): Promise<void>;
|
|
759
|
+
/**
|
|
760
|
+
* Initialize an empty thread.
|
|
761
|
+
*/
|
|
762
|
+
initializeThread(threadId: string): Promise<void>;
|
|
763
|
+
/**
|
|
764
|
+
* Append messages to a thread.
|
|
765
|
+
*/
|
|
766
|
+
appendThreadMessages(threadId: string, messages: StoredMessage[]): Promise<void>;
|
|
767
|
+
/**
|
|
768
|
+
* Append a human message to a thread.
|
|
769
|
+
*/
|
|
770
|
+
appendHumanMessage(threadId: string, content: string | MessageContent): Promise<void>;
|
|
771
|
+
/**
|
|
772
|
+
* Extract raw tool calls from a stored message.
|
|
773
|
+
* Returns unvalidated tool calls - use toolRegistry.parseToolCall() to validate.
|
|
774
|
+
*/
|
|
775
|
+
parseToolCalls(storedMessage: StoredMessage): Promise<RawToolCall[]>;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Creates shared Temporal activities for thread management
|
|
779
|
+
*
|
|
780
|
+
* @returns An object containing the shared activity functions
|
|
781
|
+
*
|
|
782
|
+
* @experimental The Zeitlich integration is an experimental feature; APIs may change without notice.
|
|
783
|
+
*/
|
|
784
|
+
declare function createSharedActivities(redis: Redis): ZeitlichSharedActivities;
|
|
785
|
+
|
|
786
|
+
declare const askUserQuestionTool: {
|
|
787
|
+
name: "AskUserQuestion";
|
|
788
|
+
description: string;
|
|
789
|
+
schema: z$1.ZodObject<{
|
|
790
|
+
questions: z$1.ZodArray<z$1.ZodObject<{
|
|
791
|
+
question: z$1.ZodString;
|
|
792
|
+
header: z$1.ZodString;
|
|
793
|
+
options: z$1.ZodArray<z$1.ZodObject<{
|
|
794
|
+
label: z$1.ZodString;
|
|
795
|
+
description: z$1.ZodString;
|
|
796
|
+
}, z$1.core.$strip>>;
|
|
797
|
+
multiSelect: z$1.ZodBoolean;
|
|
798
|
+
}, z$1.core.$strip>>;
|
|
799
|
+
}, z$1.core.$strip>;
|
|
800
|
+
strict: boolean;
|
|
801
|
+
};
|
|
802
|
+
type AskUserQuestionToolSchemaType = z$1.infer<typeof askUserQuestionTool.schema>;
|
|
803
|
+
|
|
804
|
+
declare const globTool: {
|
|
805
|
+
name: "Glob";
|
|
806
|
+
description: string;
|
|
807
|
+
schema: z.ZodObject<{
|
|
808
|
+
pattern: z.ZodString;
|
|
809
|
+
root: z.ZodOptional<z.ZodString>;
|
|
810
|
+
}, z.core.$strip>;
|
|
811
|
+
strict: boolean;
|
|
812
|
+
};
|
|
813
|
+
type GlobToolSchemaType = z.infer<typeof globTool.schema>;
|
|
814
|
+
|
|
815
|
+
declare const grepTool: {
|
|
816
|
+
name: "Grep";
|
|
817
|
+
description: string;
|
|
818
|
+
schema: z.ZodObject<{
|
|
819
|
+
pattern: z.ZodString;
|
|
820
|
+
ignoreCase: z.ZodOptional<z.ZodBoolean>;
|
|
821
|
+
maxMatches: z.ZodOptional<z.ZodNumber>;
|
|
822
|
+
includePatterns: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
823
|
+
excludePatterns: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
824
|
+
contextLines: z.ZodOptional<z.ZodNumber>;
|
|
825
|
+
}, z.core.$strip>;
|
|
826
|
+
strict: boolean;
|
|
827
|
+
};
|
|
828
|
+
type GrepToolSchemaType = z.infer<typeof grepTool.schema>;
|
|
829
|
+
|
|
830
|
+
declare const readTool: {
|
|
831
|
+
name: "FileRead";
|
|
832
|
+
description: string;
|
|
833
|
+
schema: z.ZodObject<{
|
|
834
|
+
path: z.ZodString;
|
|
835
|
+
offset: z.ZodOptional<z.ZodNumber>;
|
|
836
|
+
limit: z.ZodOptional<z.ZodNumber>;
|
|
837
|
+
}, z.core.$strip>;
|
|
838
|
+
strict: boolean;
|
|
839
|
+
};
|
|
840
|
+
type ReadToolSchemaType = z.infer<typeof readTool.schema>;
|
|
841
|
+
|
|
842
|
+
declare const writeTool: {
|
|
843
|
+
name: "FileWrite";
|
|
844
|
+
description: string;
|
|
845
|
+
schema: z.ZodObject<{
|
|
846
|
+
file_path: z.ZodString;
|
|
847
|
+
content: z.ZodString;
|
|
848
|
+
}, z.core.$strip>;
|
|
849
|
+
strict: boolean;
|
|
850
|
+
};
|
|
851
|
+
type WriteToolSchemaType = z.infer<typeof writeTool.schema>;
|
|
852
|
+
|
|
853
|
+
declare const editTool: {
|
|
854
|
+
name: "FileEdit";
|
|
855
|
+
description: string;
|
|
856
|
+
schema: z.ZodObject<{
|
|
857
|
+
file_path: z.ZodString;
|
|
858
|
+
old_string: z.ZodString;
|
|
859
|
+
new_string: z.ZodString;
|
|
860
|
+
replace_all: z.ZodOptional<z.ZodBoolean>;
|
|
861
|
+
}, z.core.$strip>;
|
|
862
|
+
strict: boolean;
|
|
863
|
+
};
|
|
864
|
+
type EditToolSchemaType = z.infer<typeof editTool.schema>;
|
|
865
|
+
|
|
866
|
+
/**
|
|
867
|
+
* File node in the tree structure provided to the agent.
|
|
868
|
+
* Represents both files and directories in a virtual file system.
|
|
869
|
+
*/
|
|
870
|
+
interface FileNode {
|
|
871
|
+
/** Virtual path (e.g., "docs/readme.md") */
|
|
872
|
+
path: string;
|
|
873
|
+
/** Whether this is a file or directory */
|
|
874
|
+
type: "file" | "directory";
|
|
875
|
+
/** Optional description shown in the prompt */
|
|
876
|
+
description?: string;
|
|
877
|
+
/** MIME type for multimodal content (e.g., "image/png", "application/pdf") */
|
|
878
|
+
mimeType?: string;
|
|
879
|
+
/** Provider-specific metadata (S3 key, database ID, etc.) */
|
|
880
|
+
metadata?: Record<string, unknown>;
|
|
881
|
+
/** Child nodes for directories */
|
|
882
|
+
children?: FileNode[];
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Options for rendering the file tree in the prompt
|
|
886
|
+
*/
|
|
887
|
+
interface FileTreeRenderOptions {
|
|
888
|
+
/** Maximum depth to render (default: unlimited) */
|
|
889
|
+
maxDepth?: number;
|
|
890
|
+
/** Include file descriptions (default: true) */
|
|
891
|
+
showDescriptions?: boolean;
|
|
892
|
+
/** Show MIME types next to files (default: false) */
|
|
893
|
+
showMimeTypes?: boolean;
|
|
894
|
+
/** Glob patterns to exclude from display */
|
|
895
|
+
excludePatterns?: string[];
|
|
896
|
+
/** Custom header text (default: "Available files and directories:") */
|
|
897
|
+
headerText?: string;
|
|
898
|
+
/** Custom description text (default: "You have access to the following files. Use the Read, Glob, and Grep tools to explore them.") */
|
|
899
|
+
descriptionText?: string;
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Text file content
|
|
903
|
+
*/
|
|
904
|
+
interface TextFileContent {
|
|
905
|
+
type: "text";
|
|
906
|
+
content: string;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Image file content (base64 encoded)
|
|
910
|
+
*/
|
|
911
|
+
interface ImageFileContent {
|
|
912
|
+
type: "image";
|
|
913
|
+
mimeType: string;
|
|
914
|
+
/** Base64-encoded image data */
|
|
915
|
+
data: string;
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* PDF file content (extracted text)
|
|
919
|
+
*/
|
|
920
|
+
interface PdfFileContent {
|
|
921
|
+
type: "pdf";
|
|
922
|
+
/** Extracted text content */
|
|
923
|
+
content: string;
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* Union type for all file content types
|
|
927
|
+
*/
|
|
928
|
+
type FileContent = TextFileContent | ImageFileContent | PdfFileContent;
|
|
929
|
+
/**
|
|
930
|
+
* Options for grep operations
|
|
931
|
+
*/
|
|
932
|
+
interface GrepOptions {
|
|
933
|
+
/** Case-insensitive search */
|
|
934
|
+
ignoreCase?: boolean;
|
|
935
|
+
/** Maximum number of matches to return */
|
|
936
|
+
maxMatches?: number;
|
|
937
|
+
/** File patterns to include (glob) */
|
|
938
|
+
includePatterns?: string[];
|
|
939
|
+
/** File patterns to exclude (glob) */
|
|
940
|
+
excludePatterns?: string[];
|
|
941
|
+
/** Include N lines of context around matches */
|
|
942
|
+
contextLines?: number;
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* A single grep match result
|
|
946
|
+
*/
|
|
947
|
+
interface GrepMatch {
|
|
948
|
+
/** Path to the file containing the match */
|
|
949
|
+
path: string;
|
|
950
|
+
/** Line number (1-indexed) */
|
|
951
|
+
lineNumber: number;
|
|
952
|
+
/** The matching line content */
|
|
953
|
+
line: string;
|
|
954
|
+
/** Context lines before the match */
|
|
955
|
+
contextBefore?: string[];
|
|
956
|
+
/** Context lines after the match */
|
|
957
|
+
contextAfter?: string[];
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Provider interface for file system operations.
|
|
961
|
+
* Implement this interface to support different backends (local FS, S3, Redis, etc.)
|
|
962
|
+
*/
|
|
963
|
+
interface FileSystemProvider {
|
|
964
|
+
/**
|
|
965
|
+
* Find files matching a glob pattern
|
|
966
|
+
* @param pattern Glob pattern to match
|
|
967
|
+
* @param root Optional root path to search from
|
|
968
|
+
* @returns Array of matching file nodes
|
|
969
|
+
*/
|
|
970
|
+
glob(pattern: string, root?: string): Promise<FileNode[]>;
|
|
971
|
+
/**
|
|
972
|
+
* Search file contents for a pattern
|
|
973
|
+
* @param pattern Regex pattern to search for
|
|
974
|
+
* @param options Search options
|
|
975
|
+
* @returns Array of matches
|
|
976
|
+
*/
|
|
977
|
+
grep(pattern: string, options?: GrepOptions): Promise<GrepMatch[]>;
|
|
978
|
+
/**
|
|
979
|
+
* Read file content
|
|
980
|
+
* @param path Virtual path to the file
|
|
981
|
+
* @returns File content in appropriate format
|
|
982
|
+
*/
|
|
983
|
+
read(path: string): Promise<FileContent>;
|
|
984
|
+
/**
|
|
985
|
+
* Write content to a file
|
|
986
|
+
* @param path Virtual path to the file
|
|
987
|
+
* @param content Text content to write
|
|
988
|
+
* @returns void
|
|
989
|
+
* @optional - Providers may not support write operations
|
|
990
|
+
*/
|
|
991
|
+
write?(path: string, content: string): Promise<void>;
|
|
992
|
+
/**
|
|
993
|
+
* Check if a file or directory exists
|
|
994
|
+
* @param path Virtual path to check
|
|
995
|
+
*/
|
|
996
|
+
exists(path: string): Promise<boolean>;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Configuration for creating file system tools
|
|
1000
|
+
*/
|
|
1001
|
+
interface FileSystemToolsConfig {
|
|
1002
|
+
/** The file system provider implementation */
|
|
1003
|
+
provider: FileSystemProvider;
|
|
1004
|
+
/** The scoped file nodes the agent can access */
|
|
1005
|
+
scopedNodes: FileNode[];
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Convert FileContent to LangChain MessageContent format
|
|
1009
|
+
*/
|
|
1010
|
+
declare function fileContentToMessageContent(content: FileContent): ContentBlock[];
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* Build a text representation of the file tree for injection into the agent's prompt.
|
|
1014
|
+
*
|
|
1015
|
+
* @param nodes Array of root-level file nodes
|
|
1016
|
+
* @param options Rendering options
|
|
1017
|
+
* @returns Formatted file tree string wrapped in <file_system> tags
|
|
1018
|
+
*
|
|
1019
|
+
* @example
|
|
1020
|
+
* ```typescript
|
|
1021
|
+
* const tree = buildFileTreePrompt([
|
|
1022
|
+
* {
|
|
1023
|
+
* path: "docs",
|
|
1024
|
+
* type: "directory",
|
|
1025
|
+
* children: [
|
|
1026
|
+
* { path: "docs/readme.md", type: "file", description: "Project docs" }
|
|
1027
|
+
* ]
|
|
1028
|
+
* },
|
|
1029
|
+
* { path: "src/index.ts", type: "file", description: "Entry point" }
|
|
1030
|
+
* ], { maxDepth: 2 });
|
|
1031
|
+
*
|
|
1032
|
+
* // Output:
|
|
1033
|
+
* // <file_system>
|
|
1034
|
+
* // Available files and directories:
|
|
1035
|
+
* //
|
|
1036
|
+
* // docs/
|
|
1037
|
+
* // readme.md - Project docs
|
|
1038
|
+
* // src/index.ts - Entry point
|
|
1039
|
+
* // </file_system>
|
|
1040
|
+
* ```
|
|
1041
|
+
*/
|
|
1042
|
+
declare function buildFileTreePrompt(nodes: FileNode[], options?: FileTreeRenderOptions): string;
|
|
1043
|
+
/**
|
|
1044
|
+
* Flatten a file tree into a list of all file paths.
|
|
1045
|
+
* Useful for scope validation.
|
|
1046
|
+
*
|
|
1047
|
+
* @param nodes Array of file nodes
|
|
1048
|
+
* @returns Array of all file paths (files only, not directories)
|
|
1049
|
+
*/
|
|
1050
|
+
declare function flattenFileTree(nodes: FileNode[]): string[];
|
|
1051
|
+
/**
|
|
1052
|
+
* Check if a path is within the scoped file tree.
|
|
1053
|
+
*
|
|
1054
|
+
* @param path Path to check
|
|
1055
|
+
* @param scopedNodes The file nodes that define the allowed scope
|
|
1056
|
+
* @returns true if the path is within scope
|
|
1057
|
+
*/
|
|
1058
|
+
declare function isPathInScope(path: string, scopedNodes: FileNode[]): boolean;
|
|
1059
|
+
/**
|
|
1060
|
+
* Find a node by path in the file tree.
|
|
1061
|
+
*
|
|
1062
|
+
* @param path Path to find
|
|
1063
|
+
* @param nodes Array of file nodes to search
|
|
1064
|
+
* @returns The matching node or undefined
|
|
1065
|
+
*/
|
|
1066
|
+
declare function findNodeByPath(path: string, nodes: FileNode[]): FileNode | undefined;
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* Abstract base class for filesystem providers.
|
|
1070
|
+
* Implements scope validation and common utilities.
|
|
1071
|
+
* Subclasses only need to implement the actual I/O operations.
|
|
1072
|
+
*/
|
|
1073
|
+
declare abstract class BaseFileSystemProvider implements FileSystemProvider {
|
|
1074
|
+
protected scopedNodes: FileNode[];
|
|
1075
|
+
protected allowedPaths: Set<string>;
|
|
1076
|
+
constructor(scopedNodes: FileNode[]);
|
|
1077
|
+
/**
|
|
1078
|
+
* Validate that a path is within the allowed scope.
|
|
1079
|
+
* Throws an error if the path is not allowed.
|
|
1080
|
+
*/
|
|
1081
|
+
protected validatePath(path: string): void;
|
|
1082
|
+
/**
|
|
1083
|
+
* Filter paths by glob pattern.
|
|
1084
|
+
*/
|
|
1085
|
+
protected filterByPattern(paths: string[], pattern: string, root?: string): string[];
|
|
1086
|
+
/**
|
|
1087
|
+
* Get all file paths in scope
|
|
1088
|
+
*/
|
|
1089
|
+
protected getAllPaths(): string[];
|
|
1090
|
+
/**
|
|
1091
|
+
* Find FileNode by path
|
|
1092
|
+
*/
|
|
1093
|
+
protected findNode(path: string): FileNode | undefined;
|
|
1094
|
+
/**
|
|
1095
|
+
* Read raw file content from the backend.
|
|
1096
|
+
* This is called after scope validation.
|
|
1097
|
+
*/
|
|
1098
|
+
protected abstract readFile(node: FileNode): Promise<FileContent>;
|
|
1099
|
+
/**
|
|
1100
|
+
* Read file as text for grep operations.
|
|
1101
|
+
* Default implementation uses readFile, but can be overridden for efficiency.
|
|
1102
|
+
*/
|
|
1103
|
+
protected readFileAsText(node: FileNode): Promise<string | null>;
|
|
1104
|
+
glob(pattern: string, root?: string): Promise<FileNode[]>;
|
|
1105
|
+
grep(pattern: string, options?: GrepOptions): Promise<GrepMatch[]>;
|
|
1106
|
+
read(path: string): Promise<FileContent>;
|
|
1107
|
+
exists(path: string): Promise<boolean>;
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* A simple in-memory filesystem provider for testing.
|
|
1111
|
+
* Files are stored as a map of path -> content.
|
|
1112
|
+
*/
|
|
1113
|
+
declare class InMemoryFileSystemProvider extends BaseFileSystemProvider {
|
|
1114
|
+
private files;
|
|
1115
|
+
constructor(scopedNodes: FileNode[], files: Map<string, FileContent>);
|
|
1116
|
+
protected readFile(node: FileNode): Promise<FileContent>;
|
|
1117
|
+
/**
|
|
1118
|
+
* Add or update a file in the in-memory storage
|
|
1119
|
+
*/
|
|
1120
|
+
setFile(path: string, content: FileContent): void;
|
|
1121
|
+
/**
|
|
1122
|
+
* Write text content to a file
|
|
1123
|
+
*/
|
|
1124
|
+
write(path: string, content: string): Promise<void>;
|
|
1125
|
+
/**
|
|
1126
|
+
* Create an InMemoryFileSystemProvider from a simple object map
|
|
1127
|
+
*/
|
|
1128
|
+
static fromTextFiles(scopedNodes: FileNode[], files: Record<string, string>): InMemoryFileSystemProvider;
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* A resolver function that reads file content given a FileNode.
|
|
1132
|
+
* Use this for simple cases where you just need to provide a read function.
|
|
1133
|
+
*/
|
|
1134
|
+
type FileResolver = (node: FileNode) => Promise<FileContent>;
|
|
1135
|
+
/**
|
|
1136
|
+
* Configuration for a backend in the CompositeFileSystemProvider
|
|
1137
|
+
*/
|
|
1138
|
+
interface BackendConfig {
|
|
1139
|
+
/** The resolver function or provider for this backend */
|
|
1140
|
+
resolver: FileResolver | FileSystemProvider;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* A composite filesystem provider that routes to different backends based on file metadata.
|
|
1144
|
+
*
|
|
1145
|
+
* Files are routed based on `node.metadata.backend` field. If no backend is specified,
|
|
1146
|
+
* the default backend is used.
|
|
1147
|
+
*
|
|
1148
|
+
* @example
|
|
1149
|
+
* ```typescript
|
|
1150
|
+
* const files: FileNode[] = [
|
|
1151
|
+
* { path: "invoices/2024.pdf", type: "file", metadata: { backend: "s3", s3Key: "..." } },
|
|
1152
|
+
* { path: "cache/summary.txt", type: "file", metadata: { backend: "redis" } },
|
|
1153
|
+
* { path: "local/config.json", type: "file" }, // uses default backend
|
|
1154
|
+
* ];
|
|
1155
|
+
*
|
|
1156
|
+
* const provider = new CompositeFileSystemProvider(files, {
|
|
1157
|
+
* backends: {
|
|
1158
|
+
* s3: { resolver: async (node) => s3Client.getObject(node.metadata.s3Key) },
|
|
1159
|
+
* redis: { resolver: async (node) => redis.get(node.path) },
|
|
1160
|
+
* },
|
|
1161
|
+
* defaultBackend: "local",
|
|
1162
|
+
* defaultResolver: async (node) => fs.readFile(node.path),
|
|
1163
|
+
* });
|
|
1164
|
+
* ```
|
|
1165
|
+
*/
|
|
1166
|
+
declare class CompositeFileSystemProvider extends BaseFileSystemProvider {
|
|
1167
|
+
private backends;
|
|
1168
|
+
private defaultBackend?;
|
|
1169
|
+
private defaultResolver?;
|
|
1170
|
+
constructor(scopedNodes: FileNode[], config: {
|
|
1171
|
+
/** Map of backend name to configuration */
|
|
1172
|
+
backends: Record<string, BackendConfig>;
|
|
1173
|
+
/** Default backend name for files without metadata.backend */
|
|
1174
|
+
defaultBackend?: string;
|
|
1175
|
+
/** Fallback resolver if no backend matches (alternative to defaultBackend) */
|
|
1176
|
+
defaultResolver?: FileResolver;
|
|
1177
|
+
});
|
|
1178
|
+
/**
|
|
1179
|
+
* Get the backend name for a file node
|
|
1180
|
+
*/
|
|
1181
|
+
private getBackendName;
|
|
1182
|
+
/**
|
|
1183
|
+
* Resolve content using a resolver (function or provider)
|
|
1184
|
+
*/
|
|
1185
|
+
private resolveContent;
|
|
1186
|
+
protected readFile(node: FileNode): Promise<FileContent>;
|
|
1187
|
+
/**
|
|
1188
|
+
* Add or update a backend configuration
|
|
1189
|
+
*/
|
|
1190
|
+
setBackend(name: string, config: BackendConfig): void;
|
|
1191
|
+
/**
|
|
1192
|
+
* Remove a backend
|
|
1193
|
+
*/
|
|
1194
|
+
removeBackend(name: string): boolean;
|
|
1195
|
+
/**
|
|
1196
|
+
* Check if a backend exists
|
|
1197
|
+
*/
|
|
1198
|
+
hasBackend(name: string): boolean;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
export { type SessionHooks as $, type AgentResponse as A, type BackendConfig as B, CompositeFileSystemProvider as C, type PostToolUseFailureHookResult as D, type EditToolSchemaType as E, type FileSystemProvider as F, type GlobToolSchemaType as G, type PostToolUseHook as H, type InvocationConfig as I, type JsonPrimitive as J, type PostToolUseHookContext as K, type PreToolUseHook as L, type PreToolUseHookContext as M, type PreToolUseHookResult as N, type ProcessToolCallsContext as O, type ParsedToolCall as P, type PromptManager as Q, type ReadToolSchemaType as R, type PromptManagerConfig as S, type ToolDefinition as T, type RawToolCall as U, type RunAgentActivity as V, type WriteToolSchemaType as W, type RunAgentConfig as X, type SessionEndHook as Y, type SessionEndHookContext as Z, type SessionExitReason as _, type ActivityToolHandler as a, type SessionLifecycleHooks as a0, type SessionStartHook as a1, type SessionStartHookContext as a2, type SubagentConfig as a3, type SubagentInput as a4, type SubagentSupportConfig as a5, type SubagentSupportResult as a6, type TaskHandlerResult as a7, type TaskToolSchemaType as a8, type ToolCallResult as a9, fileContentToMessageContent as aA, findNodeByPath as aB, flattenFileTree as aC, globTool as aD, grepTool as aE, hasNoOtherToolCalls as aF, hasTaskTool as aG, isPathInScope as aH, isTerminalStatus as aI, readTool as aJ, withSubagentSupport as aK, writeTool as aL, type ToolCallResultUnion as aa, type ToolHandler as ab, type ToolHandlerMap as ac, type ToolHandlerResponse as ad, type ToolMap as ae, type ToolMessageContent as af, type ToolNames as ag, type ToolRegistry as ah, type ToolResultConfig as ai, type ToolRouter as aj, type ToolRouterHooks as ak, type ToolRouterOptions as al, type ZeitlichAgentConfig as am, type ZeitlichSession as an, type ZeitlichSharedActivities as ao, askUserQuestionTool as ap, buildFileTreePrompt as aq, createAgentStateManager as ar, createPromptManager as as, createSession as at, createSharedActivities as au, createTaskHandler as av, createTaskTool as aw, createToolRegistry as ax, createToolRouter as ay, editTool as az, type AskUserQuestionToolSchemaType as b, type FileNode as c, type GrepToolSchemaType as d, type GrepMatch as e, type FileContent as f, AGENT_HANDLER_NAMES as g, type AgentFile as h, type AgentState as i, type AgentStateManager as j, type AgentStateManagerConfig as k, type AgentStatus as l, type AppendToolResultFn as m, type BaseAgentState as n, BaseFileSystemProvider as o, type FileResolver as p, type FileSystemToolsConfig as q, type FileTreeRenderOptions as r, type GenericTaskToolSchemaType as s, type GrepOptions as t, InMemoryFileSystemProvider as u, type JsonSerializable as v, type JsonValue as w, type ParsedToolCallUnion as x, type PostToolUseFailureHook as y, type PostToolUseFailureHookContext as z };
|