zeitlich 0.2.3 → 0.2.5

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/dist/workflow.js CHANGED
@@ -2,38 +2,38 @@ import { defineQuery, proxyActivities, setHandler, uuid4, workflowInfo, executeC
2
2
  import z3, { z } from 'zod';
3
3
 
4
4
  // src/lib/session.ts
5
- var TASK_TOOL = "Task";
6
- function buildTaskDescription(subagents) {
7
- const subagentList = subagents.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
8
- return `Launch a new agent to handle complex, multi-step tasks autonomously.
5
+ var SUBAGENT_TOOL = "Subagent";
6
+ function buildSubagentDescription(subagents) {
7
+ const subagentList = subagents.map((s) => `- **${s.agentName}**: ${s.description}`).join("\n");
8
+ return `Launch a new agent to handle complex tasks autonomously.
9
9
 
10
- The ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
10
+ The ${SUBAGENT_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
11
11
 
12
12
  Available agent types:
13
13
 
14
14
  ${subagentList}
15
15
 
16
- When using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
16
+ When using the ${SUBAGENT_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
17
17
 
18
18
  Usage notes:
19
19
 
20
20
  - Always include a short description (3-5 words) summarizing what the agent will do
21
21
  - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
22
- - When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
22
+ - When the agent is done, it will return a single message back to you.
23
23
  - Each invocation starts fresh - provide a detailed task description with all necessary context.
24
24
  - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
25
25
  - The agent's outputs should generally be trusted
26
26
  - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
27
27
  - If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.`;
28
28
  }
29
- function createTaskTool(subagents) {
29
+ function createSubagentTool(subagents) {
30
30
  if (subagents.length === 0) {
31
31
  throw new Error("createTaskTool requires at least one subagent");
32
32
  }
33
- const names = subagents.map((s) => s.name);
33
+ const names = subagents.map((s) => s.agentName);
34
34
  return {
35
- name: TASK_TOOL,
36
- description: buildTaskDescription(subagents),
35
+ name: SUBAGENT_TOOL,
36
+ description: buildSubagentDescription(subagents),
37
37
  schema: z3.object({
38
38
  subagent: z3.enum(names).describe("The type of subagent to launch"),
39
39
  description: z3.string().describe("A short (3-5 word) description of the task"),
@@ -41,16 +41,16 @@ function createTaskTool(subagents) {
41
41
  })
42
42
  };
43
43
  }
44
- function createTaskHandler(subagents) {
45
- const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } = workflowInfo();
44
+ function createSubagentHandler(subagents) {
45
+ const { taskQueue: parentTaskQueue } = workflowInfo();
46
46
  return async (args) => {
47
- const config = subagents.find((s) => s.name === args.subagent);
47
+ const config = subagents.find((s) => s.agentName === args.subagent);
48
48
  if (!config) {
49
49
  throw new Error(
50
- `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(", ")}`
50
+ `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.agentName).join(", ")}`
51
51
  );
52
52
  }
53
- const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${uuid4()}`;
53
+ const childWorkflowId = `${args.subagent}-${uuid4()}`;
54
54
  const input = {
55
55
  prompt: args.prompt,
56
56
  ...config.context && { context: config.context }
@@ -60,15 +60,11 @@ function createTaskHandler(subagents) {
60
60
  args: [input],
61
61
  taskQueue: config.taskQueue ?? parentTaskQueue
62
62
  };
63
- const childResult = typeof config.workflow === "string" ? await executeChild(config.workflow, childOpts) : await executeChild(config.workflow, childOpts);
64
- const validated = config.resultSchema ? config.resultSchema.parse(childResult) : childResult;
65
- const toolResponse = typeof validated === "string" ? validated : JSON.stringify(validated, null, 2);
63
+ const { toolResponse, data } = typeof config.workflow === "string" ? await executeChild(config.workflow, childOpts) : await executeChild(config.workflow, childOpts);
64
+ const validated = config.resultSchema ? config.resultSchema.parse(data) : null;
66
65
  return {
67
66
  toolResponse,
68
- data: {
69
- result: validated,
70
- childWorkflowId
71
- }
67
+ data: validated
72
68
  };
73
69
  };
74
70
  }
@@ -82,31 +78,36 @@ function createToolRouter(options) {
82
78
  }
83
79
  const isEnabled = (tool) => tool.enabled !== false;
84
80
  if (options.subagents) {
85
- const subagentHooksMap = /* @__PURE__ */ new Map();
86
- for (const s of options.subagents) {
87
- if (s.hooks) subagentHooksMap.set(s.name, s.hooks);
88
- }
89
- const resolveSubagentName = (args) => args.subagent;
90
- toolMap.set("Task", {
91
- ...createTaskTool(options.subagents),
92
- handler: createTaskHandler(options.subagents),
93
- ...subagentHooksMap.size > 0 && {
94
- hooks: {
95
- onPreToolUse: async (ctx) => {
96
- const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
97
- return hooks?.onPreExecution?.(ctx) ?? {};
98
- },
99
- onPostToolUse: async (ctx) => {
100
- const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
101
- await hooks?.onPostExecution?.(ctx);
102
- },
103
- onPostToolUseFailure: async (ctx) => {
104
- const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
105
- return hooks?.onExecutionFailure?.(ctx) ?? {};
81
+ const enabledSubagents = options.subagents.filter(
82
+ (s) => s.enabled !== false
83
+ );
84
+ if (enabledSubagents.length > 0) {
85
+ const subagentHooksMap = /* @__PURE__ */ new Map();
86
+ for (const s of enabledSubagents) {
87
+ if (s.hooks) subagentHooksMap.set(s.agentName, s.hooks);
88
+ }
89
+ const resolveSubagentName = (args) => args.subagent;
90
+ toolMap.set("Subagent", {
91
+ ...createSubagentTool(enabledSubagents),
92
+ handler: createSubagentHandler(enabledSubagents),
93
+ ...subagentHooksMap.size > 0 && {
94
+ hooks: {
95
+ onPreToolUse: async (ctx) => {
96
+ const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
97
+ return hooks?.onPreExecution?.(ctx) ?? {};
98
+ },
99
+ onPostToolUse: async (ctx) => {
100
+ const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
101
+ await hooks?.onPostExecution?.(ctx);
102
+ },
103
+ onPostToolUseFailure: async (ctx) => {
104
+ const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
105
+ return hooks?.onExecutionFailure?.(ctx) ?? {};
106
+ }
106
107
  }
107
108
  }
108
- }
109
- });
109
+ });
110
+ }
110
111
  }
111
112
  async function processToolCall(toolCall, turn, handlerContext) {
112
113
  const startTime = Date.now();
@@ -387,11 +388,19 @@ var createSession = async ({
387
388
  subagents,
388
389
  tools = {},
389
390
  processToolsInParallel = true,
390
- hooks = {}
391
+ hooks = {},
392
+ appendSystemPrompt = true,
393
+ systemPrompt
391
394
  }) => {
395
+ const {
396
+ appendToolResult,
397
+ appendHumanMessage,
398
+ initializeThread,
399
+ appendSystemMessage
400
+ } = threadOps ?? proxyDefaultThreadOps();
392
401
  const toolRouter = createToolRouter({
393
402
  tools,
394
- appendToolResult: threadOps.appendToolResult,
403
+ appendToolResult,
395
404
  threadId,
396
405
  hooks,
397
406
  subagents,
@@ -418,35 +427,32 @@ var createSession = async ({
418
427
  });
419
428
  }
420
429
  stateManager.setTools(toolRouter.getToolDefinitions());
421
- await threadOps.initializeThread(threadId);
422
- await threadOps.appendHumanMessage(threadId, await buildContextMessage());
430
+ await initializeThread(threadId);
431
+ if (appendSystemPrompt && systemPrompt && systemPrompt.trim() !== "") {
432
+ await appendSystemMessage(threadId, systemPrompt);
433
+ }
434
+ await appendHumanMessage(threadId, await buildContextMessage());
423
435
  let exitReason = "completed";
424
436
  try {
425
437
  while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
426
438
  stateManager.incrementTurns();
427
439
  const currentTurn = stateManager.getTurns();
428
- const { message, stopReason } = await runAgent({
440
+ const { message, rawToolCalls } = await runAgent({
429
441
  threadId,
430
442
  agentName,
431
443
  metadata
432
444
  });
433
- if (stopReason === "end_turn") {
434
- stateManager.complete();
435
- exitReason = "completed";
436
- return message;
437
- }
438
- if (!toolRouter.hasTools()) {
445
+ if (!toolRouter.hasTools() || rawToolCalls.length === 0) {
439
446
  stateManager.complete();
440
447
  exitReason = "completed";
441
448
  return message;
442
449
  }
443
- const rawToolCalls = await threadOps.parseToolCalls(message);
444
450
  const parsedToolCalls = [];
445
451
  for (const tc of rawToolCalls) {
446
452
  try {
447
453
  parsedToolCalls.push(toolRouter.parseToolCall(tc));
448
454
  } catch (error) {
449
- await threadOps.appendToolResult({
455
+ await appendToolResult({
450
456
  threadId,
451
457
  toolCallId: tc.id ?? "",
452
458
  toolName: tc.name,
@@ -494,7 +500,7 @@ function proxyDefaultThreadOps(options) {
494
500
  initializeThread: activities.initializeThread,
495
501
  appendHumanMessage: activities.appendHumanMessage,
496
502
  appendToolResult: activities.appendToolResult,
497
- parseToolCalls: activities.parseToolCalls
503
+ appendSystemMessage: activities.appendSystemMessage
498
504
  };
499
505
  }
500
506
 
@@ -961,6 +967,6 @@ Use this tool to:
961
967
  strict: true
962
968
  };
963
969
 
964
- export { AGENT_HANDLER_NAMES, askUserQuestionTool, bashTool, createAgentStateManager, createBashToolDescription, createSession, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskTool, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, globTool, grepTool, hasNoOtherToolCalls, isTerminalStatus, proxyDefaultThreadOps, readTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeTool };
970
+ export { AGENT_HANDLER_NAMES, askUserQuestionTool, bashTool, createAgentStateManager, createBashToolDescription, createSession, createSubagentTool, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, globTool, grepTool, hasNoOtherToolCalls, isTerminalStatus, proxyDefaultThreadOps, readTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeTool };
965
971
  //# sourceMappingURL=workflow.js.map
966
972
  //# sourceMappingURL=workflow.js.map