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/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentResponse, a as ActivityToolHandler, b as AskUserQuestionArgs, G as GlobArgs, F as FileEditArgs, B as BashArgs } from './workflow-D-2vp4Pq.cjs';
2
- export { c as AGENT_HANDLER_NAMES, d as AgentFile, e as AgentState, f as AgentStateManager, g as AgentStatus, h as AppendToolResultFn, i as BaseAgentState, j as BaseThreadManager, k as FileReadArgs, l as FileWriteArgs, m as GrepArgs, I as InferToolResults, J as JsonPrimitive, n as JsonSerializable, o as JsonValue, P as ParsedToolCall, p as ParsedToolCallUnion, q as PostToolUseFailureHook, r as PostToolUseFailureHookContext, s as PostToolUseFailureHookResult, t as PostToolUseHook, u as PostToolUseHookContext, v as PreToolUseHook, w as PreToolUseHookContext, x as PreToolUseHookResult, y as ProcessToolCallsContext, R as RawToolCall, z as RunAgentActivity, C as RunAgentConfig, S as SessionEndHook, D as SessionEndHookContext, E as SessionExitReason, H as SessionLifecycleHooks, K as SessionStartHook, L as SessionStartHookContext, M as SubagentConfig, N as SubagentHooks, O as SubagentInput, T as TaskArgs, Q as TaskCreateArgs, U as TaskGetArgs, V as TaskHandlerResult, W as TaskListArgs, X as TaskStatus, Y as TaskUpdateArgs, Z as ThreadManager, _ as ThreadManagerConfig, $ as ThreadOps, a0 as ToolArgs, a1 as ToolCallResult, a2 as ToolCallResultUnion, a3 as ToolDefinition, a4 as ToolHandler, a5 as ToolHandlerContext, a6 as ToolHandlerResponse, a7 as ToolHooks, a8 as ToolMap, a9 as ToolMessageContent, aa as ToolNames, ab as ToolResult, ac as ToolResultConfig, ad as ToolRouter, ae as ToolWithHandler, af as WorkflowTask, ag as ZeitlichAgentConfig, ah as ZeitlichSession, ai as ZeitlichSharedActivities, aj as askUserQuestionTool, ak as bashTool, al as createAgentStateManager, am as createBashToolDescription, an as createSession, ao as createSharedActivities, ap as createTaskCreateHandler, aq as createTaskGetHandler, ar as createTaskListHandler, as as createTaskTool, at as createTaskUpdateHandler, au as createThreadManager, av as createToolRouter, aw as defineSubagent, ax as defineTool, ay as editTool, az as getStateQuery, aA as globTool, aB as grepTool, aC as hasNoOtherToolCalls, aD as isTerminalStatus, aE as proxyDefaultThreadOps, aF as readTool, aG as taskCreateTool, aH as taskGetTool, aI as taskListTool, aJ as taskUpdateTool, aK as withAutoAppend, aL as writeTool } from './workflow-D-2vp4Pq.cjs';
1
+ import { A as AgentResponse, a as ActivityToolHandler, b as AskUserQuestionArgs, G as GlobArgs, F as FileEditArgs, B as BashArgs } from './workflow-Dg5JMeOC.cjs';
2
+ export { c as AGENT_HANDLER_NAMES, d as AgentFile, e as AgentState, f as AgentStateManager, g as AgentStatus, h as AppendToolResultFn, i as BaseAgentState, j as BaseThreadManager, k as FileReadArgs, l as FileWriteArgs, m as GrepArgs, I as InferToolResults, J as JsonPrimitive, n as JsonSerializable, o as JsonValue, P as ParsedToolCall, p as ParsedToolCallUnion, q as PostToolUseFailureHook, r as PostToolUseFailureHookContext, s as PostToolUseFailureHookResult, t as PostToolUseHook, u as PostToolUseHookContext, v as PreToolUseHook, w as PreToolUseHookContext, x as PreToolUseHookResult, y as ProcessToolCallsContext, R as RawToolCall, z as RunAgentActivity, C as RunAgentConfig, S as SessionEndHook, D as SessionEndHookContext, E as SessionExitReason, H as SessionLifecycleHooks, K as SessionStartHook, L as SessionStartHookContext, M as SubagentArgs, N as SubagentConfig, O as SubagentHooks, Q as SubagentInput, T as TaskCreateArgs, U as TaskGetArgs, V as TaskListArgs, W as TaskStatus, X as TaskUpdateArgs, Y as ThreadManager, Z as ThreadManagerConfig, _ as ThreadOps, $ as ToolArgs, a0 as ToolCallResult, a1 as ToolCallResultUnion, a2 as ToolDefinition, a3 as ToolHandler, a4 as ToolHandlerContext, a5 as ToolHandlerResponse, a6 as ToolHooks, a7 as ToolMap, a8 as ToolMessageContent, a9 as ToolNames, aa as ToolResult, ab as ToolResultConfig, ac as ToolRouter, ad as ToolWithHandler, ae as WorkflowTask, af as ZeitlichAgentConfig, ag as ZeitlichSession, ah as ZeitlichSharedActivities, ai as askUserQuestionTool, aj as bashTool, ak as createAgentStateManager, al as createBashToolDescription, am as createSession, an as createSharedActivities, ao as createSubagentTool, ap as createTaskCreateHandler, aq as createTaskGetHandler, ar as createTaskListHandler, as as createTaskUpdateHandler, at as createThreadManager, au as createToolRouter, av as defineSubagent, aw as defineTool, ax as editTool, ay as getStateQuery, az as globTool, aA as grepTool, aB as hasNoOtherToolCalls, aC as isTerminalStatus, aD as proxyDefaultThreadOps, aE as readTool, aF as taskCreateTool, aG as taskGetTool, aH as taskListTool, aI as taskUpdateTool, aJ as withAutoAppend, aK as writeTool } from './workflow-Dg5JMeOC.cjs';
3
3
  import { SimplePlugin } from '@temporalio/plugin';
4
4
  import Redis from 'ioredis';
5
5
  import { WorkflowClient } from '@temporalio/client';
@@ -39,10 +39,11 @@ interface InvokeModelConfig {
39
39
  /**
40
40
  * Core model invocation logic - shared utility for workflow-specific activities
41
41
  *
42
- * @param redis - Redis client for thread management
43
- * @param config - Model invocation configuration
44
- * @param model - Pre-instantiated LangChain chat model
45
- * @param invocationConfig - Per-invocation configuration (system prompt, etc.)
42
+ * @param options - Named options object
43
+ * @param options.redis - Redis client for thread management
44
+ * @param options.config - Model invocation configuration (threadId, agentName)
45
+ * @param options.model - Pre-instantiated LangChain chat model
46
+ * @param options.client - Temporal WorkflowClient for querying workflow state
46
47
  * @returns Agent response with message and metadata
47
48
  */
48
49
  declare function invokeModel({ redis, model, client, config: { threadId, agentName }, }: {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentResponse, a as ActivityToolHandler, b as AskUserQuestionArgs, G as GlobArgs, F as FileEditArgs, B as BashArgs } from './workflow-D-2vp4Pq.js';
2
- export { c as AGENT_HANDLER_NAMES, d as AgentFile, e as AgentState, f as AgentStateManager, g as AgentStatus, h as AppendToolResultFn, i as BaseAgentState, j as BaseThreadManager, k as FileReadArgs, l as FileWriteArgs, m as GrepArgs, I as InferToolResults, J as JsonPrimitive, n as JsonSerializable, o as JsonValue, P as ParsedToolCall, p as ParsedToolCallUnion, q as PostToolUseFailureHook, r as PostToolUseFailureHookContext, s as PostToolUseFailureHookResult, t as PostToolUseHook, u as PostToolUseHookContext, v as PreToolUseHook, w as PreToolUseHookContext, x as PreToolUseHookResult, y as ProcessToolCallsContext, R as RawToolCall, z as RunAgentActivity, C as RunAgentConfig, S as SessionEndHook, D as SessionEndHookContext, E as SessionExitReason, H as SessionLifecycleHooks, K as SessionStartHook, L as SessionStartHookContext, M as SubagentConfig, N as SubagentHooks, O as SubagentInput, T as TaskArgs, Q as TaskCreateArgs, U as TaskGetArgs, V as TaskHandlerResult, W as TaskListArgs, X as TaskStatus, Y as TaskUpdateArgs, Z as ThreadManager, _ as ThreadManagerConfig, $ as ThreadOps, a0 as ToolArgs, a1 as ToolCallResult, a2 as ToolCallResultUnion, a3 as ToolDefinition, a4 as ToolHandler, a5 as ToolHandlerContext, a6 as ToolHandlerResponse, a7 as ToolHooks, a8 as ToolMap, a9 as ToolMessageContent, aa as ToolNames, ab as ToolResult, ac as ToolResultConfig, ad as ToolRouter, ae as ToolWithHandler, af as WorkflowTask, ag as ZeitlichAgentConfig, ah as ZeitlichSession, ai as ZeitlichSharedActivities, aj as askUserQuestionTool, ak as bashTool, al as createAgentStateManager, am as createBashToolDescription, an as createSession, ao as createSharedActivities, ap as createTaskCreateHandler, aq as createTaskGetHandler, ar as createTaskListHandler, as as createTaskTool, at as createTaskUpdateHandler, au as createThreadManager, av as createToolRouter, aw as defineSubagent, ax as defineTool, ay as editTool, az as getStateQuery, aA as globTool, aB as grepTool, aC as hasNoOtherToolCalls, aD as isTerminalStatus, aE as proxyDefaultThreadOps, aF as readTool, aG as taskCreateTool, aH as taskGetTool, aI as taskListTool, aJ as taskUpdateTool, aK as withAutoAppend, aL as writeTool } from './workflow-D-2vp4Pq.js';
1
+ import { A as AgentResponse, a as ActivityToolHandler, b as AskUserQuestionArgs, G as GlobArgs, F as FileEditArgs, B as BashArgs } from './workflow-Dg5JMeOC.js';
2
+ export { c as AGENT_HANDLER_NAMES, d as AgentFile, e as AgentState, f as AgentStateManager, g as AgentStatus, h as AppendToolResultFn, i as BaseAgentState, j as BaseThreadManager, k as FileReadArgs, l as FileWriteArgs, m as GrepArgs, I as InferToolResults, J as JsonPrimitive, n as JsonSerializable, o as JsonValue, P as ParsedToolCall, p as ParsedToolCallUnion, q as PostToolUseFailureHook, r as PostToolUseFailureHookContext, s as PostToolUseFailureHookResult, t as PostToolUseHook, u as PostToolUseHookContext, v as PreToolUseHook, w as PreToolUseHookContext, x as PreToolUseHookResult, y as ProcessToolCallsContext, R as RawToolCall, z as RunAgentActivity, C as RunAgentConfig, S as SessionEndHook, D as SessionEndHookContext, E as SessionExitReason, H as SessionLifecycleHooks, K as SessionStartHook, L as SessionStartHookContext, M as SubagentArgs, N as SubagentConfig, O as SubagentHooks, Q as SubagentInput, T as TaskCreateArgs, U as TaskGetArgs, V as TaskListArgs, W as TaskStatus, X as TaskUpdateArgs, Y as ThreadManager, Z as ThreadManagerConfig, _ as ThreadOps, $ as ToolArgs, a0 as ToolCallResult, a1 as ToolCallResultUnion, a2 as ToolDefinition, a3 as ToolHandler, a4 as ToolHandlerContext, a5 as ToolHandlerResponse, a6 as ToolHooks, a7 as ToolMap, a8 as ToolMessageContent, a9 as ToolNames, aa as ToolResult, ab as ToolResultConfig, ac as ToolRouter, ad as ToolWithHandler, ae as WorkflowTask, af as ZeitlichAgentConfig, ag as ZeitlichSession, ah as ZeitlichSharedActivities, ai as askUserQuestionTool, aj as bashTool, ak as createAgentStateManager, al as createBashToolDescription, am as createSession, an as createSharedActivities, ao as createSubagentTool, ap as createTaskCreateHandler, aq as createTaskGetHandler, ar as createTaskListHandler, as as createTaskUpdateHandler, at as createThreadManager, au as createToolRouter, av as defineSubagent, aw as defineTool, ax as editTool, ay as getStateQuery, az as globTool, aA as grepTool, aB as hasNoOtherToolCalls, aC as isTerminalStatus, aD as proxyDefaultThreadOps, aE as readTool, aF as taskCreateTool, aG as taskGetTool, aH as taskListTool, aI as taskUpdateTool, aJ as withAutoAppend, aK as writeTool } from './workflow-Dg5JMeOC.js';
3
3
  import { SimplePlugin } from '@temporalio/plugin';
4
4
  import Redis from 'ioredis';
5
5
  import { WorkflowClient } from '@temporalio/client';
@@ -39,10 +39,11 @@ interface InvokeModelConfig {
39
39
  /**
40
40
  * Core model invocation logic - shared utility for workflow-specific activities
41
41
  *
42
- * @param redis - Redis client for thread management
43
- * @param config - Model invocation configuration
44
- * @param model - Pre-instantiated LangChain chat model
45
- * @param invocationConfig - Per-invocation configuration (system prompt, etc.)
42
+ * @param options - Named options object
43
+ * @param options.redis - Redis client for thread management
44
+ * @param options.config - Model invocation configuration (threadId, agentName)
45
+ * @param options.model - Pre-instantiated LangChain chat model
46
+ * @param options.client - Temporal WorkflowClient for querying workflow state
46
47
  * @returns Agent response with message and metadata
47
48
  */
48
49
  declare function invokeModel({ redis, model, client, config: { threadId, agentName }, }: {
package/dist/index.js CHANGED
@@ -1,44 +1,44 @@
1
1
  import { defineQuery, proxyActivities, setHandler, uuid4, workflowInfo, executeChild } from '@temporalio/workflow';
2
2
  import z3, { z } from 'zod';
3
3
  import { SimplePlugin } from '@temporalio/plugin';
4
- import { mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, AIMessage, ToolMessage, HumanMessage } from '@langchain/core/messages';
4
+ import { mapStoredMessagesToChatMessages, AIMessage, ToolMessage, HumanMessage } from '@langchain/core/messages';
5
5
  import crypto from 'crypto';
6
6
  import { Context } from '@temporalio/activity';
7
7
  import { Bash } from 'just-bash';
8
8
 
9
9
  // src/lib/session.ts
10
- var TASK_TOOL = "Task";
11
- function buildTaskDescription(subagents) {
12
- const subagentList = subagents.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
13
- return `Launch a new agent to handle complex, multi-step tasks autonomously.
10
+ var SUBAGENT_TOOL = "Subagent";
11
+ function buildSubagentDescription(subagents) {
12
+ const subagentList = subagents.map((s) => `- **${s.agentName}**: ${s.description}`).join("\n");
13
+ return `Launch a new agent to handle complex tasks autonomously.
14
14
 
15
- The ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
15
+ The ${SUBAGENT_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
16
16
 
17
17
  Available agent types:
18
18
 
19
19
  ${subagentList}
20
20
 
21
- When using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
21
+ When using the ${SUBAGENT_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
22
22
 
23
23
  Usage notes:
24
24
 
25
25
  - Always include a short description (3-5 words) summarizing what the agent will do
26
26
  - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
27
- - 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.
27
+ - When the agent is done, it will return a single message back to you.
28
28
  - Each invocation starts fresh - provide a detailed task description with all necessary context.
29
29
  - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
30
30
  - The agent's outputs should generally be trusted
31
31
  - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
32
32
  - 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.`;
33
33
  }
34
- function createTaskTool(subagents) {
34
+ function createSubagentTool(subagents) {
35
35
  if (subagents.length === 0) {
36
36
  throw new Error("createTaskTool requires at least one subagent");
37
37
  }
38
- const names = subagents.map((s) => s.name);
38
+ const names = subagents.map((s) => s.agentName);
39
39
  return {
40
- name: TASK_TOOL,
41
- description: buildTaskDescription(subagents),
40
+ name: SUBAGENT_TOOL,
41
+ description: buildSubagentDescription(subagents),
42
42
  schema: z3.object({
43
43
  subagent: z3.enum(names).describe("The type of subagent to launch"),
44
44
  description: z3.string().describe("A short (3-5 word) description of the task"),
@@ -46,16 +46,16 @@ function createTaskTool(subagents) {
46
46
  })
47
47
  };
48
48
  }
49
- function createTaskHandler(subagents) {
50
- const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } = workflowInfo();
49
+ function createSubagentHandler(subagents) {
50
+ const { taskQueue: parentTaskQueue } = workflowInfo();
51
51
  return async (args) => {
52
- const config = subagents.find((s) => s.name === args.subagent);
52
+ const config = subagents.find((s) => s.agentName === args.subagent);
53
53
  if (!config) {
54
54
  throw new Error(
55
- `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(", ")}`
55
+ `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.agentName).join(", ")}`
56
56
  );
57
57
  }
58
- const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${uuid4()}`;
58
+ const childWorkflowId = `${args.subagent}-${uuid4()}`;
59
59
  const input = {
60
60
  prompt: args.prompt,
61
61
  ...config.context && { context: config.context }
@@ -65,15 +65,11 @@ function createTaskHandler(subagents) {
65
65
  args: [input],
66
66
  taskQueue: config.taskQueue ?? parentTaskQueue
67
67
  };
68
- const childResult = typeof config.workflow === "string" ? await executeChild(config.workflow, childOpts) : await executeChild(config.workflow, childOpts);
69
- const validated = config.resultSchema ? config.resultSchema.parse(childResult) : childResult;
70
- const toolResponse = typeof validated === "string" ? validated : JSON.stringify(validated, null, 2);
68
+ const { toolResponse, data } = typeof config.workflow === "string" ? await executeChild(config.workflow, childOpts) : await executeChild(config.workflow, childOpts);
69
+ const validated = config.resultSchema ? config.resultSchema.parse(data) : null;
71
70
  return {
72
71
  toolResponse,
73
- data: {
74
- result: validated,
75
- childWorkflowId
76
- }
72
+ data: validated
77
73
  };
78
74
  };
79
75
  }
@@ -87,31 +83,36 @@ function createToolRouter(options) {
87
83
  }
88
84
  const isEnabled = (tool) => tool.enabled !== false;
89
85
  if (options.subagents) {
90
- const subagentHooksMap = /* @__PURE__ */ new Map();
91
- for (const s of options.subagents) {
92
- if (s.hooks) subagentHooksMap.set(s.name, s.hooks);
93
- }
94
- const resolveSubagentName = (args) => args.subagent;
95
- toolMap.set("Task", {
96
- ...createTaskTool(options.subagents),
97
- handler: createTaskHandler(options.subagents),
98
- ...subagentHooksMap.size > 0 && {
99
- hooks: {
100
- onPreToolUse: async (ctx) => {
101
- const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
102
- return hooks?.onPreExecution?.(ctx) ?? {};
103
- },
104
- onPostToolUse: async (ctx) => {
105
- const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
106
- await hooks?.onPostExecution?.(ctx);
107
- },
108
- onPostToolUseFailure: async (ctx) => {
109
- const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
110
- return hooks?.onExecutionFailure?.(ctx) ?? {};
86
+ const enabledSubagents = options.subagents.filter(
87
+ (s) => s.enabled !== false
88
+ );
89
+ if (enabledSubagents.length > 0) {
90
+ const subagentHooksMap = /* @__PURE__ */ new Map();
91
+ for (const s of enabledSubagents) {
92
+ if (s.hooks) subagentHooksMap.set(s.agentName, s.hooks);
93
+ }
94
+ const resolveSubagentName = (args) => args.subagent;
95
+ toolMap.set("Subagent", {
96
+ ...createSubagentTool(enabledSubagents),
97
+ handler: createSubagentHandler(enabledSubagents),
98
+ ...subagentHooksMap.size > 0 && {
99
+ hooks: {
100
+ onPreToolUse: async (ctx) => {
101
+ const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
102
+ return hooks?.onPreExecution?.(ctx) ?? {};
103
+ },
104
+ onPostToolUse: async (ctx) => {
105
+ const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
106
+ await hooks?.onPostExecution?.(ctx);
107
+ },
108
+ onPostToolUseFailure: async (ctx) => {
109
+ const hooks = subagentHooksMap.get(resolveSubagentName(ctx.args));
110
+ return hooks?.onExecutionFailure?.(ctx) ?? {};
111
+ }
111
112
  }
112
113
  }
113
- }
114
- });
114
+ });
115
+ }
115
116
  }
116
117
  async function processToolCall(toolCall, turn, handlerContext) {
117
118
  const startTime = Date.now();
@@ -382,7 +383,11 @@ function withAutoAppend(threadHandler, handler) {
382
383
  toolName,
383
384
  content: response.toolResponse
384
385
  });
385
- return { toolResponse: "", data: response.data, resultAppended: true };
386
+ return {
387
+ toolResponse: "Response appended via withAutoAppend",
388
+ data: response.data,
389
+ resultAppended: true
390
+ };
386
391
  };
387
392
  }
388
393
  function defineTool(tool) {
@@ -407,11 +412,19 @@ var createSession = async ({
407
412
  subagents,
408
413
  tools = {},
409
414
  processToolsInParallel = true,
410
- hooks = {}
415
+ hooks = {},
416
+ appendSystemPrompt = true,
417
+ systemPrompt
411
418
  }) => {
419
+ const {
420
+ appendToolResult,
421
+ appendHumanMessage,
422
+ initializeThread,
423
+ appendSystemMessage
424
+ } = threadOps ?? proxyDefaultThreadOps();
412
425
  const toolRouter = createToolRouter({
413
426
  tools,
414
- appendToolResult: threadOps.appendToolResult,
427
+ appendToolResult,
415
428
  threadId,
416
429
  hooks,
417
430
  subagents,
@@ -438,35 +451,32 @@ var createSession = async ({
438
451
  });
439
452
  }
440
453
  stateManager.setTools(toolRouter.getToolDefinitions());
441
- await threadOps.initializeThread(threadId);
442
- await threadOps.appendHumanMessage(threadId, await buildContextMessage());
454
+ await initializeThread(threadId);
455
+ if (appendSystemPrompt && systemPrompt && systemPrompt.trim() !== "") {
456
+ await appendSystemMessage(threadId, systemPrompt);
457
+ }
458
+ await appendHumanMessage(threadId, await buildContextMessage());
443
459
  let exitReason = "completed";
444
460
  try {
445
461
  while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
446
462
  stateManager.incrementTurns();
447
463
  const currentTurn = stateManager.getTurns();
448
- const { message, stopReason } = await runAgent({
464
+ const { message, rawToolCalls } = await runAgent({
449
465
  threadId,
450
466
  agentName,
451
467
  metadata
452
468
  });
453
- if (stopReason === "end_turn") {
454
- stateManager.complete();
455
- exitReason = "completed";
456
- return message;
457
- }
458
- if (!toolRouter.hasTools()) {
469
+ if (!toolRouter.hasTools() || rawToolCalls.length === 0) {
459
470
  stateManager.complete();
460
471
  exitReason = "completed";
461
472
  return message;
462
473
  }
463
- const rawToolCalls = await threadOps.parseToolCalls(message);
464
474
  const parsedToolCalls = [];
465
475
  for (const tc of rawToolCalls) {
466
476
  try {
467
477
  parsedToolCalls.push(toolRouter.parseToolCall(tc));
468
478
  } catch (error) {
469
- await threadOps.appendToolResult({
479
+ await appendToolResult({
470
480
  threadId,
471
481
  toolCallId: tc.id ?? "",
472
482
  toolName: tc.name,
@@ -514,7 +524,7 @@ function proxyDefaultThreadOps(options) {
514
524
  initializeThread: activities.initializeThread,
515
525
  appendHumanMessage: activities.appendHumanMessage,
516
526
  appendToolResult: activities.appendToolResult,
517
- parseToolCalls: activities.parseToolCalls
527
+ appendSystemMessage: activities.appendSystemMessage
518
528
  };
519
529
  }
520
530
 
@@ -1093,6 +1103,8 @@ function createThreadManager(config) {
1093
1103
  };
1094
1104
  return Object.assign(base, helpers);
1095
1105
  }
1106
+
1107
+ // src/activities.ts
1096
1108
  function createSharedActivities(redis) {
1097
1109
  return {
1098
1110
  async appendToolResult(config) {
@@ -1112,14 +1124,9 @@ function createSharedActivities(redis) {
1112
1124
  const thread = createThreadManager({ redis, threadId });
1113
1125
  await thread.appendHumanMessage(content);
1114
1126
  },
1115
- async parseToolCalls(storedMessage) {
1116
- const message = mapStoredMessageToChatMessage(storedMessage);
1117
- const toolCalls = message.tool_calls ?? [];
1118
- return toolCalls.map((toolCall) => ({
1119
- id: toolCall.id,
1120
- name: toolCall.name,
1121
- args: toolCall.args
1122
- }));
1127
+ async appendSystemMessage(threadId, content) {
1128
+ const thread = createThreadManager({ redis, threadId });
1129
+ await thread.appendSystemMessage(content);
1123
1130
  }
1124
1131
  };
1125
1132
  }
@@ -1157,9 +1164,14 @@ async function invokeModel({
1157
1164
  }
1158
1165
  );
1159
1166
  await thread.append([response.toDict()]);
1167
+ const toolCalls = response.tool_calls ?? [];
1160
1168
  return {
1161
1169
  message: response.toDict(),
1162
- stopReason: response.response_metadata?.stop_reason ?? null,
1170
+ rawToolCalls: toolCalls.map((tc) => ({
1171
+ id: tc.id,
1172
+ name: tc.name,
1173
+ args: tc.args
1174
+ })),
1163
1175
  usage: {
1164
1176
  input_tokens: response.usage_metadata?.input_tokens,
1165
1177
  output_tokens: response.usage_metadata?.output_tokens,
@@ -1349,6 +1361,6 @@ var toTree = async (fs, opts = {}) => {
1349
1361
  return base + subtree;
1350
1362
  };
1351
1363
 
1352
- export { AGENT_HANDLER_NAMES, ZeitlichPlugin, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashHandler, createBashToolDescription, createEditHandler, createGlobHandler, createSession, createSharedActivities, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskTool, createTaskUpdateHandler, createThreadManager, createToolRouter, defineSubagent, defineTool, editTool, getStateQuery, globTool, grepTool, hasNoOtherToolCalls, invokeModel, isTerminalStatus, proxyDefaultThreadOps, readTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, toTree, withAutoAppend, writeTool };
1364
+ export { AGENT_HANDLER_NAMES, ZeitlichPlugin, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashHandler, createBashToolDescription, createEditHandler, createGlobHandler, createSession, createSharedActivities, createSubagentTool, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createThreadManager, createToolRouter, defineSubagent, defineTool, editTool, getStateQuery, globTool, grepTool, hasNoOtherToolCalls, invokeModel, isTerminalStatus, proxyDefaultThreadOps, readTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, toTree, withAutoAppend, writeTool };
1353
1365
  //# sourceMappingURL=index.js.map
1354
1366
  //# sourceMappingURL=index.js.map