zeitlich 0.2.28 → 0.2.29

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 (93) hide show
  1. package/README.md +121 -13
  2. package/dist/{activities-3xj_fEJK.d.ts → activities-1xrWRrGJ.d.cts} +2 -3
  3. package/dist/{activities-BzYq6jf7.d.cts → activities-DOViDCTE.d.ts} +2 -3
  4. package/dist/adapters/thread/anthropic/index.d.cts +5 -6
  5. package/dist/adapters/thread/anthropic/index.d.ts +5 -6
  6. package/dist/adapters/thread/anthropic/workflow.d.cts +4 -5
  7. package/dist/adapters/thread/anthropic/workflow.d.ts +4 -5
  8. package/dist/adapters/thread/google-genai/index.d.cts +5 -6
  9. package/dist/adapters/thread/google-genai/index.d.ts +5 -6
  10. package/dist/adapters/thread/google-genai/workflow.d.cts +4 -5
  11. package/dist/adapters/thread/google-genai/workflow.d.ts +4 -5
  12. package/dist/adapters/thread/langchain/index.d.cts +5 -6
  13. package/dist/adapters/thread/langchain/index.d.ts +5 -6
  14. package/dist/adapters/thread/langchain/workflow.d.cts +4 -5
  15. package/dist/adapters/thread/langchain/workflow.d.ts +4 -5
  16. package/dist/index.cjs +499 -8
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +66 -15
  19. package/dist/index.d.ts +66 -15
  20. package/dist/index.js +495 -10
  21. package/dist/index.js.map +1 -1
  22. package/dist/{proxy-7e7v8ccg.d.ts → proxy-78nc985d.d.ts} +1 -1
  23. package/dist/{proxy-CsB8r0RR.d.cts → proxy-Bm2UTiO_.d.cts} +1 -1
  24. package/dist/{thread-manager-D8C5QvLi.d.ts → thread-manager-07BaYu_z.d.ts} +1 -1
  25. package/dist/{thread-manager-DdVFl1IY.d.cts → thread-manager-BRE5KkHB.d.cts} +1 -1
  26. package/dist/{thread-manager-DFJ3sKKU.d.cts → thread-manager-CatBkarc.d.cts} +1 -1
  27. package/dist/{thread-manager-B5qA4v7V.d.ts → thread-manager-CxbWo7q_.d.ts} +1 -1
  28. package/dist/types-BkVoEyiH.d.ts +1211 -0
  29. package/dist/{types-BZ75HpYd.d.ts → types-DAv_SLN8.d.ts} +1 -1
  30. package/dist/{types-HbjqzyJH.d.cts → types-Dpz2gXLk.d.cts} +1 -1
  31. package/dist/types-seDYom4M.d.cts +1211 -0
  32. package/dist/workflow-B4T3la0p.d.cts +750 -0
  33. package/dist/workflow-DCmaXLZ_.d.ts +750 -0
  34. package/dist/workflow.cjs +171 -5
  35. package/dist/workflow.cjs.map +1 -1
  36. package/dist/workflow.d.cts +5 -579
  37. package/dist/workflow.d.ts +5 -579
  38. package/dist/workflow.js +170 -7
  39. package/dist/workflow.js.map +1 -1
  40. package/package.json +3 -23
  41. package/src/index.ts +7 -0
  42. package/src/lib/observability/hooks.ts +117 -0
  43. package/src/lib/observability/index.ts +13 -0
  44. package/src/lib/observability/sinks.ts +88 -0
  45. package/src/lib/sandbox/manager.ts +3 -3
  46. package/src/lib/session/session-edge-cases.integration.test.ts +1 -0
  47. package/src/lib/session/session.integration.test.ts +1 -0
  48. package/src/lib/session/session.ts +63 -0
  49. package/src/lib/session/types.ts +21 -0
  50. package/src/lib/state/manager.integration.test.ts +1 -0
  51. package/src/lib/subagent/handler.ts +17 -0
  52. package/src/lib/subagent/subagent.integration.test.ts +1 -0
  53. package/src/lib/tool-router/router-edge-cases.integration.test.ts +2 -0
  54. package/src/lib/tool-router/router.integration.test.ts +2 -0
  55. package/src/lib/tool-router/router.ts +24 -2
  56. package/src/{adapters/sandbox/virtual → lib/virtual-fs}/filesystem.ts +4 -4
  57. package/src/lib/virtual-fs/index.ts +18 -0
  58. package/src/lib/virtual-fs/manager.ts +48 -0
  59. package/src/lib/virtual-fs/proxy.ts +45 -0
  60. package/src/{adapters/sandbox/virtual → lib/virtual-fs}/types.ts +43 -33
  61. package/src/{adapters/sandbox/virtual/virtual-sandbox.test.ts → lib/virtual-fs/virtual-fs.test.ts} +15 -130
  62. package/src/lib/virtual-fs/with-virtual-fs.ts +94 -0
  63. package/src/workflow.ts +25 -8
  64. package/tsup.config.ts +0 -2
  65. package/dist/adapters/sandbox/virtual/index.cjs +0 -487
  66. package/dist/adapters/sandbox/virtual/index.cjs.map +0 -1
  67. package/dist/adapters/sandbox/virtual/index.d.cts +0 -90
  68. package/dist/adapters/sandbox/virtual/index.d.ts +0 -90
  69. package/dist/adapters/sandbox/virtual/index.js +0 -479
  70. package/dist/adapters/sandbox/virtual/index.js.map +0 -1
  71. package/dist/adapters/sandbox/virtual/workflow.cjs +0 -33
  72. package/dist/adapters/sandbox/virtual/workflow.cjs.map +0 -1
  73. package/dist/adapters/sandbox/virtual/workflow.d.cts +0 -28
  74. package/dist/adapters/sandbox/virtual/workflow.d.ts +0 -28
  75. package/dist/adapters/sandbox/virtual/workflow.js +0 -31
  76. package/dist/adapters/sandbox/virtual/workflow.js.map +0 -1
  77. package/dist/queries-DVnukByF.d.cts +0 -44
  78. package/dist/queries-kjlvsUfz.d.ts +0 -44
  79. package/dist/types-BclYm5Ic.d.cts +0 -581
  80. package/dist/types-BclYm5Ic.d.ts +0 -581
  81. package/dist/types-BgsAwN3L.d.cts +0 -125
  82. package/dist/types-BtqbM1bO.d.ts +0 -490
  83. package/dist/types-BuCEZ4dF.d.cts +0 -490
  84. package/dist/types-yU5AINiP.d.ts +0 -125
  85. package/src/adapters/sandbox/virtual/index.ts +0 -92
  86. package/src/adapters/sandbox/virtual/provider.ts +0 -121
  87. package/src/adapters/sandbox/virtual/proxy.ts +0 -53
  88. package/src/adapters/sandbox/virtual/with-virtual-sandbox.ts +0 -97
  89. package/src/lib/.env +0 -1
  90. package/src/tools/bash/.env +0 -1
  91. /package/src/{adapters/sandbox/virtual → lib/virtual-fs}/mutations.ts +0 -0
  92. /package/src/{adapters/sandbox/virtual → lib/virtual-fs}/queries.ts +0 -0
  93. /package/src/{adapters/sandbox/virtual → lib/virtual-fs}/tree.ts +0 -0
@@ -1,581 +1,7 @@
1
- import { k as SessionConfig, Z as ZeitlichSession, j as SandboxShutdown, B as ThreadInit, i as SandboxInit, r as SubagentDefinition, u as SubagentHooks, v as SubagentSandboxConfig, q as SubagentConfig, w as SubagentSandboxShutdown, x as SubagentSessionInput, s as SubagentFnResult, c as SkillMetadata, d as Skill } from './types-BtqbM1bO.js';
2
- export { A as AgentResponse, H as Hooks, a as ModelInvoker, M as ModelInvokerConfig, e as PostHumanMessageAppendHook, f as PostHumanMessageAppendHookContext, g as PreHumanMessageAppendHook, h as PreHumanMessageAppendHookContext, P as PrefixedThreadOps, R as RunAgentActivity, S as ScopedPrefix, l as SessionEndHook, m as SessionEndHookContext, n as SessionResult, o as SessionStartHook, p as SessionStartHookContext, b as SkillProvider, t as SubagentHandlerResponse, y as SubagentWorkflow, z as SubagentWorkflowInput, T as ThreadOps } from './types-BtqbM1bO.js';
3
- import { g as SandboxOps } from './types-ChAMwU3q.js';
4
- export { h as ExecOptions, E as ExecResult, P as PrefixedSandboxOps, S as Sandbox, c as SandboxCapabilities, d as SandboxCreateOptions, e as SandboxCreateResult, D as SandboxDirentEntry, F as SandboxFileStat, a as SandboxFileSystem, i as SandboxNotFoundError, j as SandboxNotSupportedError, b as SandboxProvider, f as SandboxSnapshot } from './types-ChAMwU3q.js';
5
- import { a as ToolMap, i as JsonSerializable, B as BaseAgentState, j as AgentStateManager, Q as ToolRouterOptions, M as ToolRouter, R as RouterContext, J as JsonValue, N as ToolWithHandler, r as ParsedToolCallUnion, K as ToolNames, T as ToolHandlerResponse, G as ToolHandler, W as WorkflowTask, A as ActivityToolHandler } from './types-BclYm5Ic.js';
6
- export { k as AgentConfig, l as AgentFile, m as AgentState, n as AgentStatus, o as AppendToolResultFn, I as InferToolResults, p as JsonPrimitive, q as ParsedToolCall, s as PostToolUseFailureHook, t as PostToolUseFailureHookContext, c as PostToolUseFailureHookResult, u as PostToolUseHook, v as PostToolUseHookContext, w as PreToolUseHook, x as PreToolUseHookContext, P as PreToolUseHookResult, y as ProcessToolCallsContext, d as RawToolCall, f as RunAgentConfig, z as SerializableToolDefinition, S as SessionExitReason, C as TaskStatus, e as TokenUsage, D as ToolArgs, E as ToolCallResult, h as ToolCallResultUnion, F as ToolDefinition, H as ToolHooks, L as ToolResult, g as ToolResultConfig, b as ToolRouterHooks, O as isTerminalStatus } from './types-BclYm5Ic.js';
7
- import z$1, { z } from 'zod';
8
- import { a as FileEntryMetadata, e as VirtualFileTree, T as TreeMutation, F as FileEntry } from './types-yU5AINiP.js';
9
- export { b as FileResolver, g as VirtualSandboxState } from './types-yU5AINiP.js';
10
- export { f as filesWithMimeType, h as hasDirectory, a as hasFileWithMimeType } from './queries-kjlvsUfz.js';
11
- import '@temporalio/common';
1
+ export { A as AskUserQuestionArgs, B as BashArgs, F as FileEditArgs, a as FileReadArgs, b as FileWriteArgs, G as GlobArgs, d as GrepArgs, O as ObservabilityHooks, R as ReadSkillArgs, S as SessionEndedEvent, e as SessionStartedEvent, f as SubagentArgs, T as TaskCreateArgs, g as TaskGetArgs, h as TaskListArgs, i as TaskUpdateArgs, j as ToolExecutedEvent, k as TurnCompletedEvent, W as WorkflowConfig, l as WorkflowInput, m as WorkflowSessionInput, Z as ZeitlichObservabilitySinks, n as applyVirtualTreeMutations, o as askUserQuestionTool, p as bashTool, q as composeHooks, r as createAgentStateManager, s as createAskUserQuestionHandler, t as createBashToolDescription, u as createObservabilityHooks, v as createReadSkillHandler, w as createReadSkillTool, x as createSession, y as createTaskCreateHandler, z as createTaskGetHandler, C as createTaskListHandler, D as createTaskUpdateHandler, E as createToolRouter, H as defineSubagent, I as defineSubagentWorkflow, J as defineTool, K as defineWorkflow, L as editTool, M as filesWithMimeType, N as formatVirtualFileTree, P as getShortId, Q as globTool, U as grepTool, V as hasDirectory, X as hasFileWithMimeType, Y as hasNoOtherToolCalls, _ as parseSkillFile, $ as proxyVirtualFsOps, a0 as readFileTool, a1 as taskCreateTool, a2 as taskGetTool, a3 as taskListTool, a4 as taskUpdateTool, a5 as writeFileTool } from './workflow-DCmaXLZ_.js';
2
+ export { c as ActivityToolHandler, l as AgentConfig, m as AgentFile, A as AgentResponse, n as AgentState, o as AgentStateManager, p as AgentStatus, q as AppendToolResultFn, B as BaseAgentState, r as FileEntry, F as FileEntryMetadata, i as FileResolver, H as Hooks, I as InferToolResults, s as JsonPrimitive, t as JsonSerializable, J as JsonValue, a as ModelInvoker, M as ModelInvokerConfig, u as ParsedToolCall, v as ParsedToolCallUnion, w as PostHumanMessageAppendHook, x as PostHumanMessageAppendHookContext, y as PostToolUseFailureHook, z as PostToolUseFailureHookContext, C as PostToolUseFailureHookResult, D as PostToolUseHook, E as PostToolUseHookContext, G as PreHumanMessageAppendHook, K as PreHumanMessageAppendHookContext, L as PreToolUseHook, N as PreToolUseHookContext, O as PreToolUseHookResult, P as PrefixedThreadOps, k as PrefixedVirtualFsOps, Q as ProcessToolCallsContext, U as RawToolCall, R as RouterContext, W as RunAgentActivity, e as RunAgentConfig, X as SandboxInit, Y as SandboxShutdown, S as ScopedPrefix, Z as SerializableToolDefinition, _ as SessionConfig, $ as SessionEndHook, a0 as SessionEndHookContext, a1 as SessionExitReason, a2 as SessionResult, a3 as SessionStartHook, a4 as SessionStartHookContext, h as Skill, g as SkillMetadata, f as SkillProvider, a5 as SubagentConfig, a6 as SubagentDefinition, a7 as SubagentFnResult, a8 as SubagentHandlerResponse, a9 as SubagentHooks, aa as SubagentSandboxConfig, ab as SubagentSandboxShutdown, ac as SubagentSessionInput, ad as SubagentWorkflow, ae as SubagentWorkflowInput, af as TaskStatus, ag as ThreadInit, T as ThreadOps, ah as TokenUsage, ai as ToolArgs, aj as ToolCallResult, ak as ToolCallResultUnion, al as ToolDefinition, am as ToolHandler, b as ToolHandlerResponse, an as ToolHooks, ao as ToolMap, ap as ToolNames, aq as ToolResult, d as ToolResultConfig, ar as ToolRouter, as as ToolRouterHooks, at as ToolWithHandler, j as TreeMutation, av as VirtualFileTree, aw as VirtualFsOps, ax as VirtualFsState, ay as WorkflowTask, az as ZeitlichSession, aA as isTerminalStatus } from './types-BkVoEyiH.js';
3
+ export { h as ExecOptions, E as ExecResult, P as PrefixedSandboxOps, S as Sandbox, c as SandboxCapabilities, d as SandboxCreateOptions, e as SandboxCreateResult, D as SandboxDirentEntry, F as SandboxFileStat, a as SandboxFileSystem, i as SandboxNotFoundError, j as SandboxNotSupportedError, g as SandboxOps, b as SandboxProvider, f as SandboxSnapshot } from './types-ChAMwU3q.js';
4
+ import 'zod';
12
5
  import '@temporalio/workflow';
6
+ import '@temporalio/common';
13
7
  import '@temporalio/common/lib/interfaces';
14
-
15
- /**
16
- * Creates an agent session that manages the agent loop: LLM invocation,
17
- * tool routing, subagent coordination, and lifecycle hooks.
18
- *
19
- * When `sandboxOps` is provided the returned session result is guaranteed to
20
- * include `sandboxId: string`. Without it, `sandboxId` is `undefined`.
21
- *
22
- * @param config - Session and agent configuration (merged `SessionConfig` and `AgentConfig`)
23
- * @returns A session object with `runSession()` to start the agent loop
24
- *
25
- * @example
26
- * ```typescript
27
- * import { createSession, createAgentStateManager, defineTool, bashTool } from 'zeitlich/workflow';
28
- * import { proxyGoogleGenAIThreadOps } from 'zeitlich/adapters/thread/google-genai/workflow';
29
- *
30
- * const session = await createSession({
31
- * agentName: "my-agent",
32
- * maxTurns: 20,
33
- * thread: { mode: "new" },
34
- * threadOps: proxyGoogleGenAIThreadOps(),
35
- * runAgent: runAgentActivity,
36
- * buildContextMessage: () => [{ type: "text", text: prompt }],
37
- * subagents: [researcherSubagent],
38
- * tools: {
39
- * Bash: defineTool({ ...bashTool, handler: bashHandlerActivity }),
40
- * },
41
- * });
42
- *
43
- * const { finalMessage, exitReason } = await session.runSession({ stateManager });
44
- * ```
45
- */
46
- declare function createSession<T extends ToolMap, M = unknown, TContent = string>(config: SessionConfig<T, M, TContent> & {
47
- sandboxOps: SandboxOps;
48
- }): Promise<ZeitlichSession<M, true>>;
49
- declare function createSession<T extends ToolMap, M = unknown, TContent = string>(config: SessionConfig<T, M, TContent>): Promise<ZeitlichSession<M, false>>;
50
-
51
- /**
52
- * Session config fields derived from a main workflow input, ready to spread
53
- * into `createSession`.
54
- */
55
- interface WorkflowSessionInput {
56
- /** Agent name — spread directly into `createSession` */
57
- agentName: string;
58
- /** Thread initialization strategy */
59
- thread?: ThreadInit;
60
- /** Sandbox initialization strategy */
61
- sandbox?: SandboxInit;
62
- /** Sandbox shutdown policy (default: "destroy") */
63
- sandboxShutdown?: SandboxShutdown;
64
- }
65
- /** Raw workflow input fields that map into `WorkflowSessionInput`. */
66
- interface WorkflowInput {
67
- /** Thread initialization strategy (default: `{ mode: "new" }`) */
68
- thread?: ThreadInit;
69
- /** Sandbox initialization strategy */
70
- sandbox?: SandboxInit;
71
- }
72
- interface WorkflowConfig {
73
- /** Workflow name — used as the Temporal workflow function name */
74
- name: string;
75
- /**
76
- * Sandbox shutdown policy applied when the main agent session exits.
77
- *
78
- * - `"destroy"` (default) — destroy the sandbox on exit.
79
- * - `"pause"` — pause the sandbox so it can be resumed later.
80
- * - `"keep"` — leave the sandbox running (no-op on exit).
81
- */
82
- sandboxShutdown?: SandboxShutdown;
83
- }
84
- /**
85
- * Wraps a main workflow function, translating workflow input fields into
86
- * session-compatible fields that can be spread directly into `createSession`.
87
- *
88
- * The wrapper:
89
- * - Accepts a `config` with at least a `name` (used for Temporal workflow naming)
90
- * - Accepts a handler `fn` receiving `(input, sessionInput)`
91
- * - Derives thread / sandbox init from `workflowInput`
92
- * - Applies the configured `sandboxShutdown` policy
93
- */
94
- declare function defineWorkflow<TInput, TResult>(config: WorkflowConfig, fn: (input: TInput, sessionInput: WorkflowSessionInput) => Promise<TResult>): (input: TInput, workflowInput?: WorkflowInput) => Promise<TResult>;
95
-
96
- /**
97
- * Generate a compact, workflow-deterministic identifier.
98
- *
99
- * Uses Temporal's `uuid4()` internally (seeded by the workflow's RNG),
100
- * then re-encodes the hex bytes into a base-62 alphabet for a shorter,
101
- * more token-efficient identifier (~3 tokens vs ~10 for a full UUID).
102
- *
103
- * Suitable for thread IDs, child workflow IDs, or any workflow-scoped identifier.
104
- *
105
- * @param length - Number of base-62 characters (default 12, ~71 bits of entropy)
106
- */
107
- declare function getShortId(length?: number): string;
108
-
109
- /**
110
- * Creates an agent state manager for tracking workflow state.
111
- * Automatically registers Temporal query and update handlers for the agent.
112
- *
113
- * @param options.agentName - Unique agent name, used to derive query/update handler names
114
- * @param options.initialState - Optional initial values for base and custom state.
115
- * Use `systemPrompt` here to set the agent's system prompt.
116
- * Base state defaults: status="RUNNING", version=0, turns=0, tasks=empty
117
- *
118
- * @example
119
- * ```typescript
120
- * const stateManager = createAgentStateManager({
121
- * initialState: {
122
- * systemPrompt: "You are a helpful assistant.",
123
- * },
124
- * agentName: "my-agent",
125
- * });
126
- *
127
- * // With custom state fields
128
- * const stateManager = createAgentStateManager({
129
- * initialState: {
130
- * systemPrompt: agentConfig.systemPrompt,
131
- * customField: "value",
132
- * },
133
- * agentName: agentConfig.agentName,
134
- * });
135
- * ```
136
- */
137
- declare function createAgentStateManager<TCustom extends JsonSerializable<TCustom> = Record<string, never>>({ initialState, }: {
138
- initialState?: Partial<BaseAgentState> & TCustom;
139
- }): AgentStateManager<TCustom>;
140
-
141
- /**
142
- * Creates a tool router for declarative tool call processing.
143
- * Combines tool definitions with handlers in a single API.
144
- *
145
- * @example
146
- * ```typescript
147
- * const router = createToolRouter({
148
- * threadId,
149
- * tools: {
150
- * Read: {
151
- * name: "FileRead",
152
- * description: "Read file contents",
153
- * schema: z.object({ path: z.string() }),
154
- * handler: async (args, ctx) => ({
155
- * content: `Read ${args.path}`,
156
- * result: { path: args.path, content: "..." },
157
- * }),
158
- * },
159
- * },
160
- * hooks: { onPreToolUse, onPostToolUse },
161
- * });
162
- *
163
- * // Parse raw tool calls from LLM
164
- * const parsed = router.parseToolCall(rawToolCall);
165
- *
166
- * // Process tool calls
167
- * const results = await router.processToolCalls([parsed]);
168
- * ```
169
- */
170
- declare function createToolRouter<T extends ToolMap>(options: ToolRouterOptions<T>): ToolRouter<T>;
171
- /**
172
- * Identity function that creates a generic inference context for a tool definition.
173
- * TypeScript infers TResult from the handler and flows it to hooks automatically.
174
- *
175
- * @example
176
- * ```typescript
177
- * tools: {
178
- * AskUser: defineTool({
179
- * ...askUserTool,
180
- * handler: handleAskUser,
181
- * hooks: {
182
- * onPostToolUse: ({ result }) => {
183
- * // result is correctly typed as the handler's return data type
184
- * },
185
- * },
186
- * }),
187
- * }
188
- * ```
189
- */
190
- declare function defineTool<TName extends string, TSchema extends z.ZodType, TResult, TContext extends RouterContext = RouterContext, TToolResponse = JsonValue>(tool: ToolWithHandler<TName, TSchema, TResult, TContext, TToolResponse>): ToolWithHandler<TName, TSchema, TResult, TContext, TToolResponse>;
191
- /**
192
- * Utility to check if there were no tool calls besides a specific one
193
- */
194
- declare function hasNoOtherToolCalls<T extends ToolMap>(toolCalls: ParsedToolCallUnion<T>[], excludeName: ToolNames<T>): boolean;
195
-
196
- /**
197
- * Subagent tool args type (when subagent names are not known at compile time)
198
- */
199
- type SubagentArgs = {
200
- subagent: string;
201
- description: string;
202
- prompt: string;
203
- threadId?: string | null;
204
- };
205
-
206
- /**
207
- * Creates a `SubagentConfig` from a `SubagentDefinition` (returned by `defineSubagentWorkflow`).
208
- * Metadata (name, description, resultSchema) is read from the definition — only configure
209
- * what's specific to this usage in the parent workflow.
210
- *
211
- * @example
212
- * ```ts
213
- * // Minimal — all metadata comes from the definition
214
- * export const researcher = defineSubagent(researcherWorkflow);
215
- *
216
- * // With parent-specific overrides
217
- * export const researcher = defineSubagent(researcherWorkflow, {
218
- * thread: "fork",
219
- * sandbox: { source: "own", shutdown: "pause" },
220
- * hooks: {
221
- * onPostExecution: ({ result }) => console.log(result),
222
- * },
223
- * });
224
- *
225
- * // With typed context
226
- * export const researcher = defineSubagent(researcherWorkflow, {
227
- * context: { apiKey: "..." },
228
- * });
229
- * ```
230
- */
231
- declare function defineSubagent<TResult extends z.ZodType = z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(definition: SubagentDefinition<TResult, TContext>, overrides?: {
232
- context?: TContext | (() => TContext);
233
- hooks?: SubagentHooks<SubagentArgs, z.infer<TResult>>;
234
- enabled?: boolean | (() => boolean);
235
- taskQueue?: string;
236
- thread?: "new" | "fork" | "continue";
237
- sandbox?: SubagentSandboxConfig;
238
- }): SubagentConfig<TResult>;
239
-
240
- /**
241
- * Defines a subagent workflow with embedded metadata (name, description, resultSchema).
242
- * The returned value can be passed directly to `defineSubagent` — no need to repeat
243
- * the name, description, or resultSchema in the parent workflow.
244
- *
245
- * Internally maps `SubagentWorkflowInput` fields to session-compatible `SubagentSessionInput`.
246
- *
247
- * @example
248
- * ```ts
249
- * import {
250
- * defineSubagentWorkflow,
251
- * defineSubagent,
252
- * createSession,
253
- * createAgentStateManager,
254
- * } from 'zeitlich/workflow';
255
- *
256
- * // Define once — carries name, description, resultSchema
257
- * export const researcherWorkflow = defineSubagentWorkflow(
258
- * {
259
- * name: "researcher",
260
- * description: "Researches topics on the web",
261
- * resultSchema: z.object({ findings: z.string() }),
262
- * },
263
- * async (prompt, sessionInput) => {
264
- * const stateManager = createAgentStateManager({
265
- * initialState: { systemPrompt: "You are a researcher." },
266
- * });
267
- *
268
- * const session = await createSession({
269
- * ...sessionInput,
270
- * agentName: "researcher",
271
- * runAgent: runAgentActivity,
272
- * buildContextMessage: () => [{ type: "text", text: prompt }],
273
- * });
274
- *
275
- * const { finalMessage, threadId } = await session.runSession({ stateManager });
276
- * return { toolResponse: finalMessage ?? "No response", data: null, threadId };
277
- * },
278
- * );
279
- *
280
- * // Use in parent — only configure what's parent-specific
281
- * export const researcher = defineSubagent(researcherWorkflow, {
282
- * hooks: { onPostExecution: ({ result }) => console.log(result) },
283
- * });
284
- * ```
285
- */
286
- declare function defineSubagentWorkflow<TSandboxShutdown extends SubagentSandboxShutdown = "destroy", TContext extends Record<string, unknown> = Record<string, unknown>>(config: {
287
- name: string;
288
- description: string;
289
- sandboxShutdown?: TSandboxShutdown;
290
- }, fn: (prompt: string, sessionInput: SubagentSessionInput, context: TContext) => Promise<SubagentFnResult<null, TSandboxShutdown>>): SubagentDefinition<z.ZodNull, TContext>;
291
- declare function defineSubagentWorkflow<TResult extends z.ZodType, TSandboxShutdown extends SubagentSandboxShutdown = "destroy", TContext extends Record<string, unknown> = Record<string, unknown>>(config: {
292
- name: string;
293
- description: string;
294
- resultSchema: TResult;
295
- sandboxShutdown?: TSandboxShutdown;
296
- }, fn: (prompt: string, sessionInput: SubagentSessionInput, context: TContext) => Promise<SubagentFnResult<z.infer<TResult> | null, TSandboxShutdown>>): SubagentDefinition<TResult, TContext>;
297
-
298
- /**
299
- * Apply a list of {@link TreeMutation}s to the `fileTree` stored in a state
300
- * manager instance, updating it in place and returning the new tree.
301
- *
302
- * The `stateManager` parameter is structurally typed so any
303
- * {@link AgentStateManager} whose custom state includes
304
- * `fileTree: VirtualFileTree<TMeta>` will satisfy it.
305
- */
306
- declare function applyVirtualTreeMutations<TMeta = FileEntryMetadata>(stateManager: {
307
- get(key: "fileTree"): VirtualFileTree<TMeta>;
308
- set(key: "fileTree", value: VirtualFileTree<TMeta>): void;
309
- }, mutations: TreeMutation<TMeta>[]): VirtualFileTree<TMeta>;
310
-
311
- /**
312
- * Generates a formatted file tree string from a flat {@link FileEntry} list.
313
- * Directories are inferred from file paths — no filesystem access needed.
314
- *
315
- * @param entries - Flat list of file entries
316
- * @param opts - Optional configuration
317
- * @param opts.sort - Sort entries alphabetically with directories first (defaults to true)
318
- * @returns Formatted file tree string
319
- *
320
- * @example
321
- * ```typescript
322
- * const tree = formatVirtualFileTree(state.fileTree);
323
- * // /
324
- * // ├─ src/
325
- * // │ ├─ index.ts
326
- * // │ └─ utils.ts
327
- * // └─ package.json
328
- * ```
329
- */
330
- declare function formatVirtualFileTree<T>(entries: FileEntry<T>[], opts?: {
331
- sort?: boolean;
332
- }): string;
333
-
334
- /**
335
- * Parse a SKILL.md file into its frontmatter fields and markdown body.
336
- *
337
- * Handles the limited YAML subset used by the agentskills.io spec:
338
- * flat key-value pairs plus one-level nested `metadata` map.
339
- * No external YAML dependency required.
340
- */
341
- declare function parseSkillFile(raw: string): {
342
- frontmatter: SkillMetadata;
343
- body: string;
344
- };
345
-
346
- /**
347
- * Creates a ReadSkill tool configured with the available skills.
348
- * The tool description embeds skill metadata so the agent discovers
349
- * skills purely through the tool definition.
350
- */
351
- declare function createReadSkillTool(skills: Skill[]): {
352
- name: string;
353
- description: string;
354
- schema: z$1.ZodObject<{
355
- skill_name: z$1.ZodEnum<Record<string, string>>;
356
- }>;
357
- };
358
- type ReadSkillArgs = {
359
- skill_name: string;
360
- };
361
-
362
- /**
363
- * Creates a ReadSkill handler that looks up skills from an in-memory array.
364
- * Runs directly in the workflow (like task tools) — no activity needed.
365
- *
366
- * The response uses structured wrapping per the agentskills.io spec:
367
- * instructions are enclosed in `<skill_content>` tags, the skill directory
368
- * is included, and bundled resources are listed so the agent can load them
369
- * individually via its file-read tool.
370
- */
371
- declare function createReadSkillHandler(skills: Skill[]): (args: ReadSkillArgs) => ToolHandlerResponse<null>;
372
-
373
- declare const globTool: {
374
- name: "Glob";
375
- description: string;
376
- schema: z.ZodObject<{
377
- pattern: z.ZodString;
378
- root: z.ZodOptional<z.ZodString>;
379
- }, z.core.$strip>;
380
- strict: true;
381
- };
382
- type GlobArgs = z.infer<typeof globTool.schema>;
383
-
384
- declare const grepTool: {
385
- name: "Grep";
386
- description: string;
387
- schema: z.ZodObject<{
388
- pattern: z.ZodString;
389
- ignoreCase: z.ZodOptional<z.ZodBoolean>;
390
- maxMatches: z.ZodOptional<z.ZodNumber>;
391
- includePatterns: z.ZodOptional<z.ZodArray<z.ZodString>>;
392
- excludePatterns: z.ZodOptional<z.ZodArray<z.ZodString>>;
393
- contextLines: z.ZodOptional<z.ZodNumber>;
394
- }, z.core.$strip>;
395
- strict: true;
396
- };
397
- type GrepArgs = z.infer<typeof grepTool.schema>;
398
-
399
- declare const readFileTool: {
400
- name: "FileRead";
401
- description: string;
402
- schema: z.ZodObject<{
403
- path: z.ZodString;
404
- offset: z.ZodOptional<z.ZodNumber>;
405
- limit: z.ZodOptional<z.ZodNumber>;
406
- }, z.core.$strip>;
407
- strict: true;
408
- };
409
- type FileReadArgs = z.infer<typeof readFileTool.schema>;
410
-
411
- declare const writeFileTool: {
412
- name: "FileWrite";
413
- description: string;
414
- schema: z.ZodObject<{
415
- file_path: z.ZodString;
416
- content: z.ZodString;
417
- }, z.core.$strip>;
418
- strict: true;
419
- };
420
- type FileWriteArgs = z.infer<typeof writeFileTool.schema>;
421
-
422
- declare const editTool: {
423
- name: "FileEdit";
424
- description: string;
425
- schema: z.ZodObject<{
426
- file_path: z.ZodString;
427
- old_string: z.ZodString;
428
- new_string: z.ZodString;
429
- replace_all: z.ZodOptional<z.ZodBoolean>;
430
- }, z.core.$strip>;
431
- strict: true;
432
- };
433
- type FileEditArgs = z.infer<typeof editTool.schema>;
434
-
435
- declare const taskCreateTool: {
436
- name: "TaskCreate";
437
- description: string;
438
- schema: z$1.ZodObject<{
439
- subject: z$1.ZodString;
440
- description: z$1.ZodString;
441
- activeForm: z$1.ZodString;
442
- metadata: z$1.ZodRecord<z$1.ZodString, z$1.ZodString>;
443
- }, z$1.core.$strip>;
444
- };
445
- type TaskCreateArgs = z$1.infer<typeof taskCreateTool.schema>;
446
-
447
- /**
448
- * Creates a TaskCreate handler that adds tasks to the workflow state.
449
- *
450
- * @param stateManager - State manager containing tasks state
451
- * @returns A ToolHandler for TaskCreate tool calls
452
- */
453
- declare function createTaskCreateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskCreateArgs, WorkflowTask>;
454
-
455
- declare const taskGetTool: {
456
- name: "TaskGet";
457
- description: string;
458
- schema: z$1.ZodObject<{
459
- taskId: z$1.ZodString;
460
- }, z$1.core.$strip>;
461
- };
462
- type TaskGetArgs = z$1.infer<typeof taskGetTool.schema>;
463
-
464
- /**
465
- * Creates a TaskGet handler that retrieves a task by ID.
466
- *
467
- * @param stateManager - State manager containing tasks state
468
- * @returns A ToolHandler for TaskGet tool calls
469
- */
470
- declare function createTaskGetHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskGetArgs, WorkflowTask | null>;
471
-
472
- declare const taskListTool: {
473
- name: "TaskList";
474
- description: string;
475
- schema: z$1.ZodObject<{}, z$1.core.$strip>;
476
- };
477
- type TaskListArgs = z$1.infer<typeof taskListTool.schema>;
478
-
479
- /**
480
- * Creates a TaskList handler that returns all tasks.
481
- *
482
- * @param stateManager - State manager containing tasks state
483
- * @returns A ToolHandler for TaskList tool calls
484
- */
485
- declare function createTaskListHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskListArgs, WorkflowTask[]>;
486
-
487
- declare const taskUpdateTool: {
488
- name: "TaskUpdate";
489
- description: string;
490
- schema: z$1.ZodObject<{
491
- taskId: z$1.ZodString;
492
- status: z$1.ZodEnum<{
493
- pending: "pending";
494
- in_progress: "in_progress";
495
- completed: "completed";
496
- }>;
497
- addBlockedBy: z$1.ZodArray<z$1.ZodString>;
498
- addBlocks: z$1.ZodArray<z$1.ZodString>;
499
- }, z$1.core.$strip>;
500
- };
501
- type TaskUpdateArgs = z$1.infer<typeof taskUpdateTool.schema>;
502
-
503
- /**
504
- * Creates a TaskUpdate handler that modifies task status and dependencies.
505
- *
506
- * @param stateManager - State manager containing tasks state
507
- * @returns A ToolHandler for TaskUpdate tool calls
508
- */
509
- declare function createTaskUpdateHandler<TCustom extends JsonSerializable<TCustom>>(stateManager: AgentStateManager<TCustom>): ToolHandler<TaskUpdateArgs, WorkflowTask | null>;
510
-
511
- declare const createBashToolDescription: ({ fileTree, }: {
512
- fileTree: string;
513
- }) => string;
514
- declare const bashTool: {
515
- name: "Bash";
516
- description: string;
517
- schema: z$1.ZodObject<{
518
- command: z$1.ZodString;
519
- }, z$1.core.$strip>;
520
- strict: true;
521
- };
522
- type BashArgs = z$1.infer<typeof bashTool.schema>;
523
-
524
- declare const askUserQuestionTool: {
525
- name: "AskUserQuestion";
526
- description: string;
527
- schema: z$1.ZodObject<{
528
- questions: z$1.ZodArray<z$1.ZodObject<{
529
- question: z$1.ZodString;
530
- header: z$1.ZodString;
531
- options: z$1.ZodArray<z$1.ZodObject<{
532
- label: z$1.ZodString;
533
- description: z$1.ZodString;
534
- }, z$1.core.$strip>>;
535
- multiSelect: z$1.ZodBoolean;
536
- }, z$1.core.$strip>>;
537
- }, z$1.core.$strip>;
538
- strict: true;
539
- };
540
- type AskUserQuestionArgs = z$1.infer<typeof askUserQuestionTool.schema>;
541
-
542
- /**
543
- * Creates a handler for the AskUserQuestion tool.
544
- * Returns question data for display to the user via your UI layer.
545
- *
546
- * Typically paired with `stateManager.waitForInput()` in a `hooks.onPostToolUse`
547
- * callback to pause the agent loop until the user responds.
548
- *
549
- * @example
550
- * ```typescript
551
- * import { createAskUserQuestionHandler } from 'zeitlich';
552
- * import { askUserQuestionTool, defineTool } from 'zeitlich/workflow';
553
- *
554
- * // In activities
555
- * const askUserQuestionHandlerActivity = createAskUserQuestionHandler();
556
- *
557
- * // In workflow
558
- * tools: {
559
- * AskUserQuestion: defineTool({
560
- * ...askUserQuestionTool,
561
- * handler: askUserQuestionHandlerActivity,
562
- * hooks: {
563
- * onPostToolUse: () => { stateManager.waitForInput(); },
564
- * },
565
- * }),
566
- * }
567
- * ```
568
- */
569
- declare const createAskUserQuestionHandler: () => ActivityToolHandler<AskUserQuestionArgs, {
570
- questions: {
571
- question: string;
572
- header: string;
573
- options: {
574
- label: string;
575
- description: string;
576
- }[];
577
- multiSelect: boolean;
578
- }[];
579
- }>;
580
-
581
- export { ActivityToolHandler, AgentStateManager, type AskUserQuestionArgs, BaseAgentState, type BashArgs, type FileEditArgs, FileEntry, FileEntryMetadata, type FileReadArgs, type FileWriteArgs, type GlobArgs, type GrepArgs, JsonSerializable, JsonValue, ParsedToolCallUnion, type ReadSkillArgs, RouterContext, SandboxInit, SandboxOps, SandboxShutdown, SessionConfig, Skill, SkillMetadata, type SubagentArgs, SubagentConfig, SubagentDefinition, SubagentFnResult, SubagentHooks, SubagentSandboxConfig, SubagentSandboxShutdown, SubagentSessionInput, type TaskCreateArgs, type TaskGetArgs, type TaskListArgs, type TaskUpdateArgs, ThreadInit, ToolHandler, ToolHandlerResponse, ToolMap, ToolNames, ToolRouter, ToolWithHandler, TreeMutation, VirtualFileTree, type WorkflowConfig, type WorkflowInput, type WorkflowSessionInput, WorkflowTask, ZeitlichSession, applyVirtualTreeMutations, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createReadSkillHandler, createReadSkillTool, createSession, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineSubagentWorkflow, defineTool, defineWorkflow, editTool, formatVirtualFileTree, getShortId, globTool, grepTool, hasNoOtherToolCalls, parseSkillFile, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };