zeitlich 0.2.15 → 0.2.17

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 (78) hide show
  1. package/README.md +125 -64
  2. package/dist/adapters/sandbox/daytona/index.cjs +52 -23
  3. package/dist/adapters/sandbox/daytona/index.cjs.map +1 -1
  4. package/dist/adapters/sandbox/daytona/index.d.cts +10 -2
  5. package/dist/adapters/sandbox/daytona/index.d.ts +10 -2
  6. package/dist/adapters/sandbox/daytona/index.js +52 -23
  7. package/dist/adapters/sandbox/daytona/index.js.map +1 -1
  8. package/dist/adapters/sandbox/inmemory/index.cjs +21 -16
  9. package/dist/adapters/sandbox/inmemory/index.cjs.map +1 -1
  10. package/dist/adapters/sandbox/inmemory/index.d.cts +1 -1
  11. package/dist/adapters/sandbox/inmemory/index.d.ts +1 -1
  12. package/dist/adapters/sandbox/inmemory/index.js +21 -16
  13. package/dist/adapters/sandbox/inmemory/index.js.map +1 -1
  14. package/dist/adapters/sandbox/virtual/index.cjs +83 -38
  15. package/dist/adapters/sandbox/virtual/index.cjs.map +1 -1
  16. package/dist/adapters/sandbox/virtual/index.d.cts +6 -6
  17. package/dist/adapters/sandbox/virtual/index.d.ts +6 -6
  18. package/dist/adapters/sandbox/virtual/index.js +80 -38
  19. package/dist/adapters/sandbox/virtual/index.js.map +1 -1
  20. package/dist/adapters/thread/google-genai/index.d.cts +2 -2
  21. package/dist/adapters/thread/google-genai/index.d.ts +2 -2
  22. package/dist/adapters/thread/langchain/index.cjs +2 -2
  23. package/dist/adapters/thread/langchain/index.cjs.map +1 -1
  24. package/dist/adapters/thread/langchain/index.d.cts +2 -2
  25. package/dist/adapters/thread/langchain/index.d.ts +2 -2
  26. package/dist/adapters/thread/langchain/index.js +2 -2
  27. package/dist/adapters/thread/langchain/index.js.map +1 -1
  28. package/dist/index.cjs +102 -10
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +6 -6
  31. package/dist/index.d.ts +6 -6
  32. package/dist/index.js +98 -11
  33. package/dist/index.js.map +1 -1
  34. package/dist/{types-CwwgQ_9H.d.ts → queries-BlC1I3DK.d.ts} +48 -3
  35. package/dist/{types-BVP87m_W.d.cts → queries-DlJ3jE48.d.cts} +48 -3
  36. package/dist/{types-CDubRtad.d.cts → types-BMRzfELQ.d.cts} +2 -0
  37. package/dist/{types-CDubRtad.d.ts → types-BMRzfELQ.d.ts} +2 -0
  38. package/dist/{types-Dje1TdH6.d.cts → types-Bh-BbfCp.d.cts} +31 -12
  39. package/dist/{types-BWvIYK28.d.ts → types-NkiAxU4t.d.ts} +31 -12
  40. package/dist/workflow.cjs +102 -10
  41. package/dist/workflow.cjs.map +1 -1
  42. package/dist/workflow.d.cts +114 -40
  43. package/dist/workflow.d.ts +114 -40
  44. package/dist/workflow.js +98 -11
  45. package/dist/workflow.js.map +1 -1
  46. package/package.json +1 -1
  47. package/src/adapters/sandbox/daytona/filesystem.ts +43 -19
  48. package/src/adapters/sandbox/daytona/index.ts +16 -3
  49. package/src/adapters/sandbox/daytona/types.ts +4 -0
  50. package/src/adapters/sandbox/inmemory/index.ts +22 -16
  51. package/src/adapters/sandbox/virtual/filesystem.ts +29 -31
  52. package/src/adapters/sandbox/virtual/index.ts +7 -3
  53. package/src/adapters/sandbox/virtual/provider.ts +5 -2
  54. package/src/adapters/sandbox/virtual/queries.ts +97 -0
  55. package/src/adapters/sandbox/virtual/types.ts +3 -0
  56. package/src/adapters/sandbox/virtual/with-virtual-sandbox.ts +4 -3
  57. package/src/adapters/thread/langchain/activities.ts +7 -5
  58. package/src/lib/sandbox/tree.integration.test.ts +153 -0
  59. package/src/lib/sandbox/types.ts +2 -0
  60. package/src/lib/session/session-edge-cases.integration.test.ts +962 -0
  61. package/src/lib/session/session.integration.test.ts +853 -0
  62. package/src/lib/session/session.ts +5 -4
  63. package/src/lib/skills/skills.integration.test.ts +308 -0
  64. package/src/lib/state/manager.integration.test.ts +342 -0
  65. package/src/lib/subagent/define.ts +34 -47
  66. package/src/lib/subagent/handler.ts +9 -6
  67. package/src/lib/subagent/index.ts +4 -1
  68. package/src/lib/subagent/subagent.integration.test.ts +573 -0
  69. package/src/lib/subagent/types.ts +40 -10
  70. package/src/lib/subagent/workflow.ts +114 -0
  71. package/src/lib/thread/id.test.ts +50 -0
  72. package/src/lib/tool-router/auto-append-sandbox.integration.test.ts +344 -0
  73. package/src/lib/tool-router/router-edge-cases.integration.test.ts +623 -0
  74. package/src/lib/tool-router/router.integration.test.ts +699 -0
  75. package/src/lib/types.test.ts +29 -0
  76. package/src/lib/workflow.test.ts +131 -0
  77. package/src/lib/workflow.ts +45 -0
  78. package/src/workflow.ts +12 -2
@@ -1,13 +1,13 @@
1
1
  import { proxyActivities } from '@temporalio/workflow';
2
- import { k as SessionConfig, Z as ZeitlichSession, T as ThreadOps, f as JsonSerializable, e as AgentStateManager, p as SubagentConfig, q as SubagentHandlerResponse, r as SubagentHooks, b as SkillMetadata, c as Skill } from './types-Dje1TdH6.cjs';
3
- export { A as AgentResponse, d as AgentState, H as Hooks, J as JsonPrimitive, g as JsonValue, M as ModelInvoker, a as ModelInvokerConfig, P as PostHumanMessageAppendHook, h as PostHumanMessageAppendHookContext, i as PreHumanMessageAppendHook, j as PreHumanMessageAppendHookContext, R as RunAgentActivity, l as SessionEndHook, m as SessionEndHookContext, n as SessionStartHook, o as SessionStartHookContext, S as SkillProvider, s as SubagentInput, t as SubagentWorkflow } from './types-Dje1TdH6.cjs';
4
- import { g as SandboxOps } from './types-CDubRtad.cjs';
5
- export { h as ExecOptions, E as ExecResult, 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-CDubRtad.cjs';
2
+ import { k as SessionConfig, Z as ZeitlichSession, T as ThreadOps, f as JsonSerializable, e as AgentStateManager, q as SubagentDefinition, s as SubagentHooks, p as SubagentConfig, t as SubagentSessionInput, r as SubagentHandlerResponse, b as SkillMetadata, c as Skill } from './types-Bh-BbfCp.cjs';
3
+ export { A as AgentResponse, d as AgentState, H as Hooks, J as JsonPrimitive, g as JsonValue, M as ModelInvoker, a as ModelInvokerConfig, P as PostHumanMessageAppendHook, h as PostHumanMessageAppendHookContext, i as PreHumanMessageAppendHook, j as PreHumanMessageAppendHookContext, R as RunAgentActivity, l as SessionEndHook, m as SessionEndHookContext, n as SessionStartHook, o as SessionStartHookContext, S as SkillProvider, u as SubagentWorkflow, v as SubagentWorkflowInput } from './types-Bh-BbfCp.cjs';
4
+ import { g as SandboxOps } from './types-BMRzfELQ.cjs';
5
+ export { h as ExecOptions, E as ExecResult, 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-BMRzfELQ.cjs';
6
6
  import { a as ToolMap, B as BaseAgentState, N as ToolRouterOptions, J as ToolRouter, R as RouterContext, K as ToolWithHandler, p as ParsedToolCallUnion, G as ToolNames, c as ToolHandlerResponse, E as ToolHandler, W as WorkflowTask, A as ActivityToolHandler } from './types-BMXzv7TN.cjs';
7
7
  export { l as AgentConfig, m as AgentFile, h as AgentStatus, n as AppendToolResultFn, C as ContentPart, I as InferToolResults, M as MessageContent, o as ParsedToolCall, q as PostToolUseFailureHook, r as PostToolUseFailureHookContext, d as PostToolUseFailureHookResult, s as PostToolUseHook, t as PostToolUseHookContext, u as PreToolUseHook, v as PreToolUseHookContext, P as PreToolUseHookResult, w as ProcessToolCallsContext, e as RawToolCall, g as RunAgentConfig, x as SerializableToolDefinition, S as SessionExitReason, y as TaskStatus, f as TokenUsage, z as ToolArgs, D as ToolCallResult, k as ToolCallResultUnion, i as ToolDefinition, F as ToolHooks, T as ToolMessageContent, H as ToolResult, j as ToolResultConfig, b as ToolRouterHooks, L as isTerminalStatus } from './types-BMXzv7TN.cjs';
8
8
  import z$1, { z } from 'zod';
9
- import { F as FileEntryMetadata, e as VirtualFileTree, T as TreeMutation, c as FileEntry } from './types-BVP87m_W.cjs';
10
- export { a as FileResolver, g as VirtualSandboxState } from './types-BVP87m_W.cjs';
9
+ import { F as FileEntryMetadata, f as VirtualFileTree, T as TreeMutation, c as FileEntry } from './queries-DlJ3jE48.cjs';
10
+ export { a as FileResolver, h as VirtualSandboxState, i as filesWithMimeType, j as hasDirectory, k as hasFileWithMimeType } from './queries-DlJ3jE48.cjs';
11
11
  import '@temporalio/common';
12
12
  import '@temporalio/common/lib/interfaces';
13
13
 
@@ -71,6 +71,37 @@ declare function proxyDefaultThreadOps(options?: Parameters<typeof proxyActiviti
71
71
  */
72
72
  declare function proxySandboxOps(options?: Parameters<typeof proxyActivities>[0]): SandboxOps;
73
73
 
74
+ /**
75
+ * Session config fields derived from a main workflow input, ready to spread
76
+ * into `createSession`.
77
+ */
78
+ interface WorkflowSessionInput {
79
+ /** Thread ID to continue (set from `input.previousThreadId`) */
80
+ threadId?: string;
81
+ /** Whether to continue an existing thread (true when `previousThreadId` is present) */
82
+ continueThread?: boolean;
83
+ /** Optional sandbox ID forwarded to the session */
84
+ sandboxId?: string;
85
+ }
86
+ /** Raw workflow input fields that map into `WorkflowSessionInput`. */
87
+ interface WorkflowInput {
88
+ /** When set, continue this thread instead of starting fresh */
89
+ previousThreadId?: string;
90
+ /** Optional sandbox ID to reuse */
91
+ sandboxId?: string;
92
+ }
93
+ /**
94
+ * Wraps a main workflow function, translating workflow input fields into
95
+ * session-compatible fields that can be spread directly into `createSession`.
96
+ *
97
+ * The wrapper:
98
+ * - Accepts a generic typed `input` as first argument
99
+ * - Accepts optional `workflowInput` ({ previousThreadId, sandboxId }) as second argument
100
+ * - Derives `threadId` + `continueThread` from `workflowInput.previousThreadId`
101
+ * - Derives `sandboxId` from `workflowInput.sandboxId`
102
+ */
103
+ declare function defineWorkflow<TInput, TResult>(fn: (input: TInput, sessionInput: WorkflowSessionInput) => Promise<TResult>): (input: TInput, workflowInput?: WorkflowInput) => Promise<TResult>;
104
+
74
105
  /**
75
106
  * Generate a compact, workflow-deterministic identifier.
76
107
  *
@@ -182,52 +213,95 @@ type SubagentArgs = {
182
213
  };
183
214
 
184
215
  /**
185
- * Identity function that provides full type inference for subagent configurations.
186
- * Verifies the workflow function's input parameters match the configured context,
187
- * and properly types the lifecycle hooks with Task tool args and inferred result type.
216
+ * Creates a `SubagentConfig` from a `SubagentDefinition` (returned by `defineSubagentWorkflow`).
217
+ * Metadata (name, description, resultSchema) is read from the definition — only configure
218
+ * what's specific to this usage in the parent workflow.
188
219
  *
189
220
  * @example
190
221
  * ```ts
191
- * // With typed context workflow must accept { prompt, context }
192
- * const researcher = defineSubagent({
193
- * name: "researcher",
194
- * description: "Researches topics",
195
- * workflow: researcherWorkflow, // (input: { prompt: string; context: { apiKey: string } }) => Promise<...>
196
- * context: { apiKey: "..." },
197
- * resultSchema: z.object({ findings: z.string() }),
222
+ * // Minimalall metadata comes from the definition
223
+ * export const researcher = defineSubagent(researcherWorkflow);
224
+ *
225
+ * // With parent-specific overrides
226
+ * export const researcher = defineSubagent(researcherWorkflow, {
227
+ * allowThreadContinuation: true,
228
+ * sandbox: "own",
198
229
  * hooks: {
199
- * onPostExecution: ({ result }) => {
200
- * // result is typed as { findings: string }
201
- * },
230
+ * onPostExecution: ({ result }) => console.log(result),
202
231
  * },
203
232
  * });
204
233
  *
205
- * // Without context — workflow only needs { prompt }
206
- * const writer = defineSubagent({
207
- * name: "writer",
208
- * description: "Writes content",
209
- * workflow: writerWorkflow, // (input: { prompt: string }) => Promise<...>
210
- * resultSchema: z.object({ content: z.string() }),
234
+ * // With typed context
235
+ * export const researcher = defineSubagent(researcherWorkflow, {
236
+ * context: { apiKey: "..." },
211
237
  * });
212
238
  * ```
213
239
  */
214
- declare function defineSubagent<TResult extends z.ZodType = z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow" | "context"> & {
215
- workflow: string | ((input: {
216
- prompt: string;
217
- previousThreadId?: string;
218
- context: TContext;
219
- }) => Promise<SubagentHandlerResponse<z.infer<TResult> | null>>);
220
- context: TContext;
221
- hooks?: SubagentHooks<SubagentArgs, z.infer<TResult>>;
222
- }): SubagentConfig<TResult>;
223
- declare function defineSubagent<TResult extends z.ZodType = z.ZodType>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow"> & {
224
- workflow: string | ((input: {
225
- prompt: string;
226
- previousThreadId?: string;
227
- }) => Promise<SubagentHandlerResponse<z.infer<TResult> | null>>);
240
+ declare function defineSubagent<TResult extends z.ZodType = z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(definition: SubagentDefinition<TResult, TContext>, overrides?: {
241
+ context?: TContext;
228
242
  hooks?: SubagentHooks<SubagentArgs, z.infer<TResult>>;
243
+ enabled?: boolean;
244
+ taskQueue?: string;
245
+ allowThreadContinuation?: boolean;
246
+ sandbox?: "inherit" | "own";
229
247
  }): SubagentConfig<TResult>;
230
248
 
249
+ /**
250
+ * Defines a subagent workflow with embedded metadata (name, description, resultSchema).
251
+ * The returned value can be passed directly to `defineSubagent` — no need to repeat
252
+ * the name, description, or resultSchema in the parent workflow.
253
+ *
254
+ * Internally maps `SubagentWorkflowInput` fields to session-compatible `SubagentSessionInput`.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * import {
259
+ * defineSubagentWorkflow,
260
+ * defineSubagent,
261
+ * createSession,
262
+ * createAgentStateManager,
263
+ * } from 'zeitlich/workflow';
264
+ *
265
+ * // Define once — carries name, description, resultSchema
266
+ * export const researcherWorkflow = defineSubagentWorkflow(
267
+ * {
268
+ * name: "researcher",
269
+ * description: "Researches topics on the web",
270
+ * resultSchema: z.object({ findings: z.string() }),
271
+ * },
272
+ * async (prompt, sessionInput) => {
273
+ * const stateManager = createAgentStateManager({
274
+ * initialState: { systemPrompt: "You are a researcher." },
275
+ * });
276
+ *
277
+ * const session = await createSession({
278
+ * ...sessionInput,
279
+ * agentName: "researcher",
280
+ * runAgent: runAgentActivity,
281
+ * buildContextMessage: () => [{ type: "text", text: prompt }],
282
+ * });
283
+ *
284
+ * const { finalMessage, threadId } = await session.runSession({ stateManager });
285
+ * return { toolResponse: finalMessage ?? "No response", data: null, threadId };
286
+ * },
287
+ * );
288
+ *
289
+ * // Use in parent — only configure what's parent-specific
290
+ * export const researcher = defineSubagent(researcherWorkflow, {
291
+ * hooks: { onPostExecution: ({ result }) => console.log(result) },
292
+ * });
293
+ * ```
294
+ */
295
+ declare function defineSubagentWorkflow<TContext extends Record<string, unknown> = Record<string, unknown>>(config: {
296
+ name: string;
297
+ description: string;
298
+ }, fn: (prompt: string, sessionInput: SubagentSessionInput, context: TContext) => Promise<SubagentHandlerResponse<null>>): SubagentDefinition<z.ZodNull, TContext>;
299
+ declare function defineSubagentWorkflow<TResult extends z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(config: {
300
+ name: string;
301
+ description: string;
302
+ resultSchema: TResult;
303
+ }, fn: (prompt: string, sessionInput: SubagentSessionInput, context: TContext) => Promise<SubagentHandlerResponse<z.infer<TResult> | null>>): SubagentDefinition<TResult, TContext>;
304
+
231
305
  /**
232
306
  * Apply a list of {@link TreeMutation}s to the `fileTree` stored in a state
233
307
  * manager instance, updating it in place and returning the new tree.
@@ -506,4 +580,4 @@ declare const createAskUserQuestionHandler: () => ActivityToolHandler<AskUserQue
506
580
  }[];
507
581
  }>;
508
582
 
509
- export { ActivityToolHandler, AgentStateManager, type AskUserQuestionArgs, BaseAgentState, type BashArgs, type FileEditArgs, FileEntry, FileEntryMetadata, type FileReadArgs, type FileWriteArgs, type GlobArgs, type GrepArgs, JsonSerializable, ParsedToolCallUnion, type ReadSkillArgs, RouterContext, SandboxOps, SessionConfig, Skill, SkillMetadata, type SubagentArgs, SubagentConfig, SubagentHandlerResponse, SubagentHooks, type TaskCreateArgs, type TaskGetArgs, type TaskListArgs, type TaskUpdateArgs, ThreadOps, ToolHandler, ToolHandlerResponse, ToolMap, ToolNames, ToolRouter, ToolWithHandler, TreeMutation, VirtualFileTree, WorkflowTask, ZeitlichSession, applyVirtualTreeMutations, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createReadSkillHandler, createReadSkillTool, createSession, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, formatVirtualFileTree, getShortId, globTool, grepTool, hasNoOtherToolCalls, parseSkillFile, proxyDefaultThreadOps, proxySandboxOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
583
+ export { ActivityToolHandler, AgentStateManager, type AskUserQuestionArgs, BaseAgentState, type BashArgs, type FileEditArgs, FileEntry, FileEntryMetadata, type FileReadArgs, type FileWriteArgs, type GlobArgs, type GrepArgs, JsonSerializable, ParsedToolCallUnion, type ReadSkillArgs, RouterContext, SandboxOps, SessionConfig, Skill, SkillMetadata, type SubagentArgs, SubagentConfig, SubagentDefinition, SubagentHandlerResponse, SubagentHooks, SubagentSessionInput, type TaskCreateArgs, type TaskGetArgs, type TaskListArgs, type TaskUpdateArgs, ThreadOps, ToolHandler, ToolHandlerResponse, ToolMap, ToolNames, ToolRouter, ToolWithHandler, TreeMutation, VirtualFileTree, 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, proxyDefaultThreadOps, proxySandboxOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
@@ -1,13 +1,13 @@
1
1
  import { proxyActivities } from '@temporalio/workflow';
2
- import { k as SessionConfig, Z as ZeitlichSession, T as ThreadOps, f as JsonSerializable, e as AgentStateManager, p as SubagentConfig, q as SubagentHandlerResponse, r as SubagentHooks, b as SkillMetadata, c as Skill } from './types-BWvIYK28.js';
3
- export { A as AgentResponse, d as AgentState, H as Hooks, J as JsonPrimitive, g as JsonValue, M as ModelInvoker, a as ModelInvokerConfig, P as PostHumanMessageAppendHook, h as PostHumanMessageAppendHookContext, i as PreHumanMessageAppendHook, j as PreHumanMessageAppendHookContext, R as RunAgentActivity, l as SessionEndHook, m as SessionEndHookContext, n as SessionStartHook, o as SessionStartHookContext, S as SkillProvider, s as SubagentInput, t as SubagentWorkflow } from './types-BWvIYK28.js';
4
- import { g as SandboxOps } from './types-CDubRtad.js';
5
- export { h as ExecOptions, E as ExecResult, 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-CDubRtad.js';
2
+ import { k as SessionConfig, Z as ZeitlichSession, T as ThreadOps, f as JsonSerializable, e as AgentStateManager, q as SubagentDefinition, s as SubagentHooks, p as SubagentConfig, t as SubagentSessionInput, r as SubagentHandlerResponse, b as SkillMetadata, c as Skill } from './types-NkiAxU4t.js';
3
+ export { A as AgentResponse, d as AgentState, H as Hooks, J as JsonPrimitive, g as JsonValue, M as ModelInvoker, a as ModelInvokerConfig, P as PostHumanMessageAppendHook, h as PostHumanMessageAppendHookContext, i as PreHumanMessageAppendHook, j as PreHumanMessageAppendHookContext, R as RunAgentActivity, l as SessionEndHook, m as SessionEndHookContext, n as SessionStartHook, o as SessionStartHookContext, S as SkillProvider, u as SubagentWorkflow, v as SubagentWorkflowInput } from './types-NkiAxU4t.js';
4
+ import { g as SandboxOps } from './types-BMRzfELQ.js';
5
+ export { h as ExecOptions, E as ExecResult, 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-BMRzfELQ.js';
6
6
  import { a as ToolMap, B as BaseAgentState, N as ToolRouterOptions, J as ToolRouter, R as RouterContext, K as ToolWithHandler, p as ParsedToolCallUnion, G as ToolNames, c as ToolHandlerResponse, E as ToolHandler, W as WorkflowTask, A as ActivityToolHandler } from './types-BMXzv7TN.js';
7
7
  export { l as AgentConfig, m as AgentFile, h as AgentStatus, n as AppendToolResultFn, C as ContentPart, I as InferToolResults, M as MessageContent, o as ParsedToolCall, q as PostToolUseFailureHook, r as PostToolUseFailureHookContext, d as PostToolUseFailureHookResult, s as PostToolUseHook, t as PostToolUseHookContext, u as PreToolUseHook, v as PreToolUseHookContext, P as PreToolUseHookResult, w as ProcessToolCallsContext, e as RawToolCall, g as RunAgentConfig, x as SerializableToolDefinition, S as SessionExitReason, y as TaskStatus, f as TokenUsage, z as ToolArgs, D as ToolCallResult, k as ToolCallResultUnion, i as ToolDefinition, F as ToolHooks, T as ToolMessageContent, H as ToolResult, j as ToolResultConfig, b as ToolRouterHooks, L as isTerminalStatus } from './types-BMXzv7TN.js';
8
8
  import z$1, { z } from 'zod';
9
- import { F as FileEntryMetadata, e as VirtualFileTree, T as TreeMutation, c as FileEntry } from './types-CwwgQ_9H.js';
10
- export { a as FileResolver, g as VirtualSandboxState } from './types-CwwgQ_9H.js';
9
+ import { F as FileEntryMetadata, f as VirtualFileTree, T as TreeMutation, c as FileEntry } from './queries-BlC1I3DK.js';
10
+ export { a as FileResolver, h as VirtualSandboxState, i as filesWithMimeType, j as hasDirectory, k as hasFileWithMimeType } from './queries-BlC1I3DK.js';
11
11
  import '@temporalio/common';
12
12
  import '@temporalio/common/lib/interfaces';
13
13
 
@@ -71,6 +71,37 @@ declare function proxyDefaultThreadOps(options?: Parameters<typeof proxyActiviti
71
71
  */
72
72
  declare function proxySandboxOps(options?: Parameters<typeof proxyActivities>[0]): SandboxOps;
73
73
 
74
+ /**
75
+ * Session config fields derived from a main workflow input, ready to spread
76
+ * into `createSession`.
77
+ */
78
+ interface WorkflowSessionInput {
79
+ /** Thread ID to continue (set from `input.previousThreadId`) */
80
+ threadId?: string;
81
+ /** Whether to continue an existing thread (true when `previousThreadId` is present) */
82
+ continueThread?: boolean;
83
+ /** Optional sandbox ID forwarded to the session */
84
+ sandboxId?: string;
85
+ }
86
+ /** Raw workflow input fields that map into `WorkflowSessionInput`. */
87
+ interface WorkflowInput {
88
+ /** When set, continue this thread instead of starting fresh */
89
+ previousThreadId?: string;
90
+ /** Optional sandbox ID to reuse */
91
+ sandboxId?: string;
92
+ }
93
+ /**
94
+ * Wraps a main workflow function, translating workflow input fields into
95
+ * session-compatible fields that can be spread directly into `createSession`.
96
+ *
97
+ * The wrapper:
98
+ * - Accepts a generic typed `input` as first argument
99
+ * - Accepts optional `workflowInput` ({ previousThreadId, sandboxId }) as second argument
100
+ * - Derives `threadId` + `continueThread` from `workflowInput.previousThreadId`
101
+ * - Derives `sandboxId` from `workflowInput.sandboxId`
102
+ */
103
+ declare function defineWorkflow<TInput, TResult>(fn: (input: TInput, sessionInput: WorkflowSessionInput) => Promise<TResult>): (input: TInput, workflowInput?: WorkflowInput) => Promise<TResult>;
104
+
74
105
  /**
75
106
  * Generate a compact, workflow-deterministic identifier.
76
107
  *
@@ -182,52 +213,95 @@ type SubagentArgs = {
182
213
  };
183
214
 
184
215
  /**
185
- * Identity function that provides full type inference for subagent configurations.
186
- * Verifies the workflow function's input parameters match the configured context,
187
- * and properly types the lifecycle hooks with Task tool args and inferred result type.
216
+ * Creates a `SubagentConfig` from a `SubagentDefinition` (returned by `defineSubagentWorkflow`).
217
+ * Metadata (name, description, resultSchema) is read from the definition — only configure
218
+ * what's specific to this usage in the parent workflow.
188
219
  *
189
220
  * @example
190
221
  * ```ts
191
- * // With typed context workflow must accept { prompt, context }
192
- * const researcher = defineSubagent({
193
- * name: "researcher",
194
- * description: "Researches topics",
195
- * workflow: researcherWorkflow, // (input: { prompt: string; context: { apiKey: string } }) => Promise<...>
196
- * context: { apiKey: "..." },
197
- * resultSchema: z.object({ findings: z.string() }),
222
+ * // Minimalall metadata comes from the definition
223
+ * export const researcher = defineSubagent(researcherWorkflow);
224
+ *
225
+ * // With parent-specific overrides
226
+ * export const researcher = defineSubagent(researcherWorkflow, {
227
+ * allowThreadContinuation: true,
228
+ * sandbox: "own",
198
229
  * hooks: {
199
- * onPostExecution: ({ result }) => {
200
- * // result is typed as { findings: string }
201
- * },
230
+ * onPostExecution: ({ result }) => console.log(result),
202
231
  * },
203
232
  * });
204
233
  *
205
- * // Without context — workflow only needs { prompt }
206
- * const writer = defineSubagent({
207
- * name: "writer",
208
- * description: "Writes content",
209
- * workflow: writerWorkflow, // (input: { prompt: string }) => Promise<...>
210
- * resultSchema: z.object({ content: z.string() }),
234
+ * // With typed context
235
+ * export const researcher = defineSubagent(researcherWorkflow, {
236
+ * context: { apiKey: "..." },
211
237
  * });
212
238
  * ```
213
239
  */
214
- declare function defineSubagent<TResult extends z.ZodType = z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow" | "context"> & {
215
- workflow: string | ((input: {
216
- prompt: string;
217
- previousThreadId?: string;
218
- context: TContext;
219
- }) => Promise<SubagentHandlerResponse<z.infer<TResult> | null>>);
220
- context: TContext;
221
- hooks?: SubagentHooks<SubagentArgs, z.infer<TResult>>;
222
- }): SubagentConfig<TResult>;
223
- declare function defineSubagent<TResult extends z.ZodType = z.ZodType>(config: Omit<SubagentConfig<TResult>, "hooks" | "workflow"> & {
224
- workflow: string | ((input: {
225
- prompt: string;
226
- previousThreadId?: string;
227
- }) => Promise<SubagentHandlerResponse<z.infer<TResult> | null>>);
240
+ declare function defineSubagent<TResult extends z.ZodType = z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(definition: SubagentDefinition<TResult, TContext>, overrides?: {
241
+ context?: TContext;
228
242
  hooks?: SubagentHooks<SubagentArgs, z.infer<TResult>>;
243
+ enabled?: boolean;
244
+ taskQueue?: string;
245
+ allowThreadContinuation?: boolean;
246
+ sandbox?: "inherit" | "own";
229
247
  }): SubagentConfig<TResult>;
230
248
 
249
+ /**
250
+ * Defines a subagent workflow with embedded metadata (name, description, resultSchema).
251
+ * The returned value can be passed directly to `defineSubagent` — no need to repeat
252
+ * the name, description, or resultSchema in the parent workflow.
253
+ *
254
+ * Internally maps `SubagentWorkflowInput` fields to session-compatible `SubagentSessionInput`.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * import {
259
+ * defineSubagentWorkflow,
260
+ * defineSubagent,
261
+ * createSession,
262
+ * createAgentStateManager,
263
+ * } from 'zeitlich/workflow';
264
+ *
265
+ * // Define once — carries name, description, resultSchema
266
+ * export const researcherWorkflow = defineSubagentWorkflow(
267
+ * {
268
+ * name: "researcher",
269
+ * description: "Researches topics on the web",
270
+ * resultSchema: z.object({ findings: z.string() }),
271
+ * },
272
+ * async (prompt, sessionInput) => {
273
+ * const stateManager = createAgentStateManager({
274
+ * initialState: { systemPrompt: "You are a researcher." },
275
+ * });
276
+ *
277
+ * const session = await createSession({
278
+ * ...sessionInput,
279
+ * agentName: "researcher",
280
+ * runAgent: runAgentActivity,
281
+ * buildContextMessage: () => [{ type: "text", text: prompt }],
282
+ * });
283
+ *
284
+ * const { finalMessage, threadId } = await session.runSession({ stateManager });
285
+ * return { toolResponse: finalMessage ?? "No response", data: null, threadId };
286
+ * },
287
+ * );
288
+ *
289
+ * // Use in parent — only configure what's parent-specific
290
+ * export const researcher = defineSubagent(researcherWorkflow, {
291
+ * hooks: { onPostExecution: ({ result }) => console.log(result) },
292
+ * });
293
+ * ```
294
+ */
295
+ declare function defineSubagentWorkflow<TContext extends Record<string, unknown> = Record<string, unknown>>(config: {
296
+ name: string;
297
+ description: string;
298
+ }, fn: (prompt: string, sessionInput: SubagentSessionInput, context: TContext) => Promise<SubagentHandlerResponse<null>>): SubagentDefinition<z.ZodNull, TContext>;
299
+ declare function defineSubagentWorkflow<TResult extends z.ZodType, TContext extends Record<string, unknown> = Record<string, unknown>>(config: {
300
+ name: string;
301
+ description: string;
302
+ resultSchema: TResult;
303
+ }, fn: (prompt: string, sessionInput: SubagentSessionInput, context: TContext) => Promise<SubagentHandlerResponse<z.infer<TResult> | null>>): SubagentDefinition<TResult, TContext>;
304
+
231
305
  /**
232
306
  * Apply a list of {@link TreeMutation}s to the `fileTree` stored in a state
233
307
  * manager instance, updating it in place and returning the new tree.
@@ -506,4 +580,4 @@ declare const createAskUserQuestionHandler: () => ActivityToolHandler<AskUserQue
506
580
  }[];
507
581
  }>;
508
582
 
509
- export { ActivityToolHandler, AgentStateManager, type AskUserQuestionArgs, BaseAgentState, type BashArgs, type FileEditArgs, FileEntry, FileEntryMetadata, type FileReadArgs, type FileWriteArgs, type GlobArgs, type GrepArgs, JsonSerializable, ParsedToolCallUnion, type ReadSkillArgs, RouterContext, SandboxOps, SessionConfig, Skill, SkillMetadata, type SubagentArgs, SubagentConfig, SubagentHandlerResponse, SubagentHooks, type TaskCreateArgs, type TaskGetArgs, type TaskListArgs, type TaskUpdateArgs, ThreadOps, ToolHandler, ToolHandlerResponse, ToolMap, ToolNames, ToolRouter, ToolWithHandler, TreeMutation, VirtualFileTree, WorkflowTask, ZeitlichSession, applyVirtualTreeMutations, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createReadSkillHandler, createReadSkillTool, createSession, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, formatVirtualFileTree, getShortId, globTool, grepTool, hasNoOtherToolCalls, parseSkillFile, proxyDefaultThreadOps, proxySandboxOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
583
+ export { ActivityToolHandler, AgentStateManager, type AskUserQuestionArgs, BaseAgentState, type BashArgs, type FileEditArgs, FileEntry, FileEntryMetadata, type FileReadArgs, type FileWriteArgs, type GlobArgs, type GrepArgs, JsonSerializable, ParsedToolCallUnion, type ReadSkillArgs, RouterContext, SandboxOps, SessionConfig, Skill, SkillMetadata, type SubagentArgs, SubagentConfig, SubagentDefinition, SubagentHandlerResponse, SubagentHooks, SubagentSessionInput, type TaskCreateArgs, type TaskGetArgs, type TaskListArgs, type TaskUpdateArgs, ThreadOps, ToolHandler, ToolHandlerResponse, ToolMap, ToolNames, ToolRouter, ToolWithHandler, TreeMutation, VirtualFileTree, 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, proxyDefaultThreadOps, proxySandboxOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
package/dist/workflow.js CHANGED
@@ -330,15 +330,15 @@ function createSubagentHandler(subagents) {
330
330
  const childWorkflowId = `${args.subagent}-${getShortId()}`;
331
331
  const { sandboxId: parentSandboxId } = context;
332
332
  const inheritSandbox = config.sandbox !== "own" && !!parentSandboxId;
333
- const input = {
334
- prompt: args.prompt,
335
- ...config.context && { context: config.context },
336
- ...args.threadId && args.threadId !== null && config.allowThreadContinuation && { previousThreadId: args.threadId },
333
+ const workflowInput = {
334
+ ...args.threadId && args.threadId !== null && config.allowThreadContinuation && {
335
+ previousThreadId: args.threadId
336
+ },
337
337
  ...inheritSandbox && { sandboxId: parentSandboxId }
338
338
  };
339
339
  const childOpts = {
340
340
  workflowId: childWorkflowId,
341
- args: [input],
341
+ args: config.context === void 0 ? [args.prompt, workflowInput] : [args.prompt, workflowInput, config.context],
342
342
  taskQueue: config.taskQueue ?? parentTaskQueue
343
343
  };
344
344
  const {
@@ -553,9 +553,7 @@ var createSession = async ({
553
553
  const result = await sandboxOps.createSandbox({ id: threadId });
554
554
  sandboxId = result.sandboxId;
555
555
  if (result.stateUpdate) {
556
- stateManager.mergeUpdate(
557
- result.stateUpdate
558
- );
556
+ stateManager.mergeUpdate(result.stateUpdate);
559
557
  }
560
558
  }
561
559
  if (hooks.onSessionStart) {
@@ -640,6 +638,7 @@ var createSession = async ({
640
638
  );
641
639
  if (!conditionMet) {
642
640
  stateManager.cancel();
641
+ exitReason = "cancelled";
643
642
  await condition(() => false, "2s");
644
643
  break;
645
644
  }
@@ -693,6 +692,20 @@ function proxySandboxOps(options) {
693
692
  );
694
693
  }
695
694
 
695
+ // src/lib/workflow.ts
696
+ function defineWorkflow(fn) {
697
+ return async (input, workflowInput = {}) => {
698
+ const sessionInput = {
699
+ ...workflowInput.previousThreadId && {
700
+ threadId: workflowInput.previousThreadId,
701
+ continueThread: true
702
+ },
703
+ ...workflowInput.sandboxId && { sandboxId: workflowInput.sandboxId }
704
+ };
705
+ return fn(input, sessionInput);
706
+ };
707
+ }
708
+
696
709
  // src/lib/types.ts
697
710
  function isTerminalStatus(status) {
698
711
  return status === "COMPLETED" || status === "FAILED" || status === "CANCELLED";
@@ -855,8 +868,40 @@ function createAgentStateManager({
855
868
  }
856
869
 
857
870
  // src/lib/subagent/define.ts
858
- function defineSubagent(config) {
859
- return config;
871
+ function defineSubagent(definition, overrides) {
872
+ return {
873
+ agentName: definition.agentName,
874
+ description: definition.description,
875
+ workflow: definition,
876
+ ...definition.resultSchema !== void 0 && {
877
+ resultSchema: definition.resultSchema
878
+ },
879
+ ...overrides
880
+ };
881
+ }
882
+
883
+ // src/lib/subagent/workflow.ts
884
+ function defineSubagentWorkflow(config, fn) {
885
+ const workflow = async (prompt, workflowInput, context) => {
886
+ const sessionInput = {
887
+ agentName: config.name,
888
+ ...workflowInput.previousThreadId && {
889
+ threadId: workflowInput.previousThreadId,
890
+ continueThread: true
891
+ },
892
+ ...workflowInput.sandboxId && { sandboxId: workflowInput.sandboxId }
893
+ };
894
+ return fn(prompt, sessionInput, context ?? {});
895
+ };
896
+ Object.defineProperty(workflow, "name", { value: config.name });
897
+ return Object.assign(workflow, {
898
+ agentName: config.name,
899
+ description: config.description,
900
+ ...config.resultSchema !== void 0 && {
901
+ resultSchema: config.resultSchema
902
+ }
903
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
904
+ });
860
905
  }
861
906
  var SandboxNotSupportedError = class extends ApplicationFailure$1 {
862
907
  constructor(operation) {
@@ -943,6 +988,48 @@ function formatVirtualFileTree(entries, opts = {}) {
943
988
  return "/" + printNode(root, "", sort);
944
989
  }
945
990
 
991
+ // src/adapters/sandbox/virtual/queries.ts
992
+ function hasFileWithMimeType(stateManager, pattern) {
993
+ const tree = stateManager.get("fileTree");
994
+ const matchers = (Array.isArray(pattern) ? pattern : [pattern]).map(buildMatcher);
995
+ return tree.some((entry) => {
996
+ const meta = entry.metadata;
997
+ const mime = meta?.mimeType;
998
+ return typeof mime === "string" && matchers.some((m) => m(mime));
999
+ });
1000
+ }
1001
+ function filesWithMimeType(stateManager, pattern) {
1002
+ const tree = stateManager.get("fileTree");
1003
+ const match = buildMatcher(pattern);
1004
+ return tree.filter((entry) => {
1005
+ const meta = entry.metadata;
1006
+ const mime = meta?.mimeType;
1007
+ return typeof mime === "string" && match(mime);
1008
+ });
1009
+ }
1010
+ function hasDirectory(stateManager, pattern) {
1011
+ const tree = stateManager.get("fileTree");
1012
+ const match = buildGlobMatcher(pattern);
1013
+ return tree.some((entry) => {
1014
+ const segments = entry.path.split("/").filter(Boolean);
1015
+ return segments.slice(0, -1).some(match);
1016
+ });
1017
+ }
1018
+ function buildMatcher(pattern) {
1019
+ if (pattern.endsWith("/*")) {
1020
+ const prefix = pattern.slice(0, -1);
1021
+ return (v) => v.startsWith(prefix);
1022
+ }
1023
+ return (v) => v === pattern;
1024
+ }
1025
+ function buildGlobMatcher(pattern) {
1026
+ if (!pattern.includes("*")) return (v) => v === pattern;
1027
+ const re = new RegExp(
1028
+ "^" + pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$"
1029
+ );
1030
+ return (v) => re.test(v);
1031
+ }
1032
+
946
1033
  // src/lib/skills/parse.ts
947
1034
  function parseSkillFile(raw) {
948
1035
  const trimmed = raw.replace(/^\uFEFF/, "");
@@ -1365,6 +1452,6 @@ var createAskUserQuestionHandler = () => async (args) => {
1365
1452
  };
1366
1453
  };
1367
1454
 
1368
- export { SandboxNotFoundError, SandboxNotSupportedError, applyVirtualTreeMutations, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createReadSkillHandler, createReadSkillTool, createSession, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, formatVirtualFileTree, getShortId, globTool, grepTool, hasNoOtherToolCalls, isTerminalStatus, parseSkillFile, proxyDefaultThreadOps, proxySandboxOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
1455
+ export { SandboxNotFoundError, SandboxNotSupportedError, applyVirtualTreeMutations, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createReadSkillHandler, createReadSkillTool, createSession, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineSubagentWorkflow, defineTool, defineWorkflow, editTool, filesWithMimeType, formatVirtualFileTree, getShortId, globTool, grepTool, hasDirectory, hasFileWithMimeType, hasNoOtherToolCalls, isTerminalStatus, parseSkillFile, proxyDefaultThreadOps, proxySandboxOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
1369
1456
  //# sourceMappingURL=workflow.js.map
1370
1457
  //# sourceMappingURL=workflow.js.map