zeitlich 0.2.8 → 0.2.11

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.
@@ -1,6 +1,7 @@
1
- export { b as AGENT_HANDLER_NAMES, a as ActivityToolHandler, c as AgentConfig, d as AgentFile, A as AgentResponse, e as AgentState, f as AgentStateManager, g as AgentStatus, h as AppendToolResultFn, i as AskUserQuestionArgs, j as BaseAgentState, B as BashArgs, F as FileEditArgs, l as FileReadArgs, m as FileWriteArgs, G as GlobArgs, n as GrepArgs, I as InferToolResults, J as JsonPrimitive, o as JsonSerializable, p as JsonValue, P as ParsedToolCall, q as ParsedToolCallUnion, r as PostToolUseFailureHook, s as PostToolUseFailureHookContext, t as PostToolUseFailureHookResult, u as PostToolUseHook, v as PostToolUseHookContext, w as PreToolUseHook, x as PreToolUseHookContext, y as PreToolUseHookResult, z as ProcessToolCallsContext, R as RawToolCall, C as RunAgentActivity, D as RunAgentConfig, S as SessionEndHook, E as SessionEndHookContext, H as SessionExitReason, K as SessionLifecycleHooks, L as SessionStartHook, M as SessionStartHookContext, N as SubagentArgs, O as SubagentConfig, Q as SubagentHooks, T as SubagentInput, U as TaskCreateArgs, V as TaskGetArgs, W as TaskListArgs, X as TaskStatus, Y as TaskUpdateArgs, $ 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 ZeitlichSession, ah as ZeitlichSharedActivities, ai as askUserQuestionTool, aj as bashTool, ak as createAgentStateManager, al as createAskUserQuestionHandler, am as createBashToolDescription, an as createSession, ap as createSubagentTool, aq as createTaskCreateHandler, ar as createTaskGetHandler, as as createTaskListHandler, at as createTaskUpdateHandler, av as createToolRouter, aw as defineSubagent, ax as defineTool, ay as editTool, 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, aK as writeTool } from './workflow-BdAuMMjY.cjs';
1
+ export { a as ActivityToolHandler, d as AgentConfig, e as AgentFile, A as AgentResponse, f as AgentState, g as AgentStateManager, h as AgentStatus, i as AppendToolResultFn, j as AskUserQuestionArgs, k as BaseAgentState, B as BashArgs, F as FileEditArgs, m as FileReadArgs, n as FileWriteArgs, G as GlobArgs, o as GrepArgs, I as InferToolResults, J as JsonPrimitive, p as JsonSerializable, q as JsonValue, P as ParsedToolCall, r as ParsedToolCallUnion, s as PostToolUseFailureHook, t as PostToolUseFailureHookContext, u as PostToolUseFailureHookResult, v as PostToolUseHook, w as PostToolUseHookContext, x as PreToolUseHook, y as PreToolUseHookContext, z as PreToolUseHookResult, C as ProcessToolCallsContext, R as RawToolCall, D as ReadSkillArgs, E as RunAgentActivity, H as RunAgentConfig, K as SessionEndHook, L as SessionEndHookContext, M as SessionExitReason, N as SessionLifecycleHooks, O as SessionStartHook, Q as SessionStartHookContext, c as Skill, b as SkillMetadata, S as SkillProvider, T as SubagentArgs, U as SubagentConfig, V as SubagentHooks, W as SubagentInput, X as SubagentWorkflow, Y as TaskCreateArgs, Z as TaskGetArgs, _ as TaskListArgs, $ as TaskStatus, a0 as TaskUpdateArgs, a3 as ThreadOps, a4 as ToolArgs, a5 as ToolCallResult, a6 as ToolCallResultUnion, a7 as ToolDefinition, a8 as ToolHandler, a9 as ToolHandlerContext, aa as ToolHandlerResponse, ab as ToolHooks, ac as ToolMap, ad as ToolMessageContent, ae as ToolNames, af as ToolResult, ag as ToolResultConfig, ah as ToolRouter, ai as ToolWithHandler, aj as WorkflowTask, ak as ZeitlichSession, al as ZeitlichSharedActivities, am as agentQueryName, an as agentStateChangeUpdateName, ao as askUserQuestionTool, ap as bashTool, aq as createAgentStateManager, ar as createAskUserQuestionHandler, as as createBashToolDescription, at as createReadSkillHandler, au as createReadSkillTool, av as createSession, ax as createSubagentTool, ay as createTaskCreateHandler, az as createTaskGetHandler, aA as createTaskListHandler, aB as createTaskUpdateHandler, aD as createToolRouter, aE as defineSubagent, aF as defineTool, aG as editTool, aH as globTool, aI as grepTool, aJ as hasNoOtherToolCalls, aK as isTerminalStatus, aL as parseSkillFile, aM as proxyDefaultThreadOps, aN as readFileTool, aO as taskCreateTool, aP as taskGetTool, aQ as taskListTool, aR as taskUpdateTool, aT as writeFileTool } from './workflow-BhjsEQc1.cjs';
2
2
  import '@temporalio/workflow';
3
3
  import 'ioredis';
4
4
  import '@langchain/core/messages';
5
5
  import 'zod';
6
6
  import '@temporalio/common';
7
+ import '@temporalio/common/lib/interfaces';
@@ -1,6 +1,7 @@
1
- export { b as AGENT_HANDLER_NAMES, a as ActivityToolHandler, c as AgentConfig, d as AgentFile, A as AgentResponse, e as AgentState, f as AgentStateManager, g as AgentStatus, h as AppendToolResultFn, i as AskUserQuestionArgs, j as BaseAgentState, B as BashArgs, F as FileEditArgs, l as FileReadArgs, m as FileWriteArgs, G as GlobArgs, n as GrepArgs, I as InferToolResults, J as JsonPrimitive, o as JsonSerializable, p as JsonValue, P as ParsedToolCall, q as ParsedToolCallUnion, r as PostToolUseFailureHook, s as PostToolUseFailureHookContext, t as PostToolUseFailureHookResult, u as PostToolUseHook, v as PostToolUseHookContext, w as PreToolUseHook, x as PreToolUseHookContext, y as PreToolUseHookResult, z as ProcessToolCallsContext, R as RawToolCall, C as RunAgentActivity, D as RunAgentConfig, S as SessionEndHook, E as SessionEndHookContext, H as SessionExitReason, K as SessionLifecycleHooks, L as SessionStartHook, M as SessionStartHookContext, N as SubagentArgs, O as SubagentConfig, Q as SubagentHooks, T as SubagentInput, U as TaskCreateArgs, V as TaskGetArgs, W as TaskListArgs, X as TaskStatus, Y as TaskUpdateArgs, $ 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 ZeitlichSession, ah as ZeitlichSharedActivities, ai as askUserQuestionTool, aj as bashTool, ak as createAgentStateManager, al as createAskUserQuestionHandler, am as createBashToolDescription, an as createSession, ap as createSubagentTool, aq as createTaskCreateHandler, ar as createTaskGetHandler, as as createTaskListHandler, at as createTaskUpdateHandler, av as createToolRouter, aw as defineSubagent, ax as defineTool, ay as editTool, 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, aK as writeTool } from './workflow-BdAuMMjY.js';
1
+ export { a as ActivityToolHandler, d as AgentConfig, e as AgentFile, A as AgentResponse, f as AgentState, g as AgentStateManager, h as AgentStatus, i as AppendToolResultFn, j as AskUserQuestionArgs, k as BaseAgentState, B as BashArgs, F as FileEditArgs, m as FileReadArgs, n as FileWriteArgs, G as GlobArgs, o as GrepArgs, I as InferToolResults, J as JsonPrimitive, p as JsonSerializable, q as JsonValue, P as ParsedToolCall, r as ParsedToolCallUnion, s as PostToolUseFailureHook, t as PostToolUseFailureHookContext, u as PostToolUseFailureHookResult, v as PostToolUseHook, w as PostToolUseHookContext, x as PreToolUseHook, y as PreToolUseHookContext, z as PreToolUseHookResult, C as ProcessToolCallsContext, R as RawToolCall, D as ReadSkillArgs, E as RunAgentActivity, H as RunAgentConfig, K as SessionEndHook, L as SessionEndHookContext, M as SessionExitReason, N as SessionLifecycleHooks, O as SessionStartHook, Q as SessionStartHookContext, c as Skill, b as SkillMetadata, S as SkillProvider, T as SubagentArgs, U as SubagentConfig, V as SubagentHooks, W as SubagentInput, X as SubagentWorkflow, Y as TaskCreateArgs, Z as TaskGetArgs, _ as TaskListArgs, $ as TaskStatus, a0 as TaskUpdateArgs, a3 as ThreadOps, a4 as ToolArgs, a5 as ToolCallResult, a6 as ToolCallResultUnion, a7 as ToolDefinition, a8 as ToolHandler, a9 as ToolHandlerContext, aa as ToolHandlerResponse, ab as ToolHooks, ac as ToolMap, ad as ToolMessageContent, ae as ToolNames, af as ToolResult, ag as ToolResultConfig, ah as ToolRouter, ai as ToolWithHandler, aj as WorkflowTask, ak as ZeitlichSession, al as ZeitlichSharedActivities, am as agentQueryName, an as agentStateChangeUpdateName, ao as askUserQuestionTool, ap as bashTool, aq as createAgentStateManager, ar as createAskUserQuestionHandler, as as createBashToolDescription, at as createReadSkillHandler, au as createReadSkillTool, av as createSession, ax as createSubagentTool, ay as createTaskCreateHandler, az as createTaskGetHandler, aA as createTaskListHandler, aB as createTaskUpdateHandler, aD as createToolRouter, aE as defineSubagent, aF as defineTool, aG as editTool, aH as globTool, aI as grepTool, aJ as hasNoOtherToolCalls, aK as isTerminalStatus, aL as parseSkillFile, aM as proxyDefaultThreadOps, aN as readFileTool, aO as taskCreateTool, aP as taskGetTool, aQ as taskListTool, aR as taskUpdateTool, aT as writeFileTool } from './workflow-BhjsEQc1.js';
2
2
  import '@temporalio/workflow';
3
3
  import 'ioredis';
4
4
  import '@langchain/core/messages';
5
5
  import 'zod';
6
6
  import '@temporalio/common';
7
+ import '@temporalio/common/lib/interfaces';
package/dist/workflow.js CHANGED
@@ -1,30 +1,16 @@
1
- import { setHandler, defineUpdate, condition, proxyActivities, defineQuery, uuid4, workflowInfo, executeChild } from '@temporalio/workflow';
2
- import z13, { z } from 'zod';
1
+ import { setHandler, defineUpdate, ApplicationFailure, condition, proxyActivities, defineQuery, uuid4, workflowInfo, executeChild } from '@temporalio/workflow';
2
+ import z14, { z } from 'zod';
3
3
 
4
4
  // src/lib/session.ts
5
- var SUBAGENT_TOOL = "Subagent";
5
+ var SUBAGENT_TOOL_NAME = "Subagent";
6
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
-
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
-
12
- Available agent types:
7
+ const subagentList = subagents.map((s) => `## ${s.agentName}
8
+ ${s.description}`).join("\n\n");
9
+ return `The ${SUBAGENT_TOOL_NAME} tool launches specialized agents (subagents) that autonomously handle complex work. Each agent type has specific capabilities and tools available to it.
13
10
 
11
+ # Available subagents:
14
12
  ${subagentList}
15
-
16
- When using the ${SUBAGENT_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
17
-
18
- Usage notes:
19
-
20
- - Always include a short description (3-5 words) summarizing what the agent will do
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.
23
- - Each invocation starts fresh - provide a detailed task description with all necessary context.
24
- - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
25
- - The agent's outputs should generally be trusted
26
- - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
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.`;
13
+ `;
28
14
  }
29
15
  function createSubagentTool(subagents) {
30
16
  if (subagents.length === 0) {
@@ -32,12 +18,12 @@ function createSubagentTool(subagents) {
32
18
  }
33
19
  const names = subagents.map((s) => s.agentName);
34
20
  return {
35
- name: SUBAGENT_TOOL,
21
+ name: SUBAGENT_TOOL_NAME,
36
22
  description: buildSubagentDescription(subagents),
37
- schema: z13.object({
38
- subagent: z13.enum(names).describe("The type of subagent to launch"),
39
- description: z13.string().describe("A short (3-5 word) description of the task"),
40
- prompt: z13.string().describe("The task for the agent to perform")
23
+ schema: z14.object({
24
+ subagent: z14.enum(names).describe("The type of subagent to launch"),
25
+ description: z14.string().describe("A short (3-5 word) description of the task"),
26
+ prompt: z14.string().describe("The task for the agent to perform")
41
27
  })
42
28
  };
43
29
  }
@@ -61,23 +47,77 @@ function createSubagentHandler(subagents) {
61
47
  taskQueue: config.taskQueue ?? parentTaskQueue
62
48
  };
63
49
  const { toolResponse, data, usage } = typeof config.workflow === "string" ? await executeChild(config.workflow, childOpts) : await executeChild(config.workflow, childOpts);
64
- const validated = config.resultSchema ? config.resultSchema.parse(data) : null;
50
+ if (!toolResponse) {
51
+ return {
52
+ toolResponse: "Subagent workflow returned no response",
53
+ data: null,
54
+ ...usage && { usage }
55
+ };
56
+ }
57
+ const validated = config.resultSchema ? config.resultSchema.safeParse(data) : null;
58
+ if (validated && !validated.success) {
59
+ return {
60
+ toolResponse: `Subagent workflow returned invalid data: ${validated.error.message}`,
61
+ data: null,
62
+ ...usage && { usage }
63
+ };
64
+ }
65
65
  return {
66
66
  toolResponse,
67
- data: validated,
67
+ data: validated ? validated.data : data,
68
68
  ...usage && { usage }
69
69
  };
70
70
  };
71
71
  }
72
+ var READ_SKILL_TOOL_NAME = "ReadSkill";
73
+ function buildReadSkillDescription(skills) {
74
+ const skillList = skills.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
75
+ return `Load the full instructions for a skill. Read the skill before following its instructions.
76
+
77
+ # Available skills:
78
+ ${skillList}
79
+ `;
80
+ }
81
+ function createReadSkillTool(skills) {
82
+ if (skills.length === 0) {
83
+ throw new Error("createReadSkillTool requires at least one skill");
84
+ }
85
+ const names = skills.map((s) => s.name);
86
+ return {
87
+ name: READ_SKILL_TOOL_NAME,
88
+ description: buildReadSkillDescription(skills),
89
+ schema: z14.object({
90
+ skill_name: z14.enum(names).describe("The name of the skill to load")
91
+ })
92
+ };
93
+ }
72
94
 
73
- // src/lib/tool-router.ts
95
+ // src/tools/read-skill/handler.ts
96
+ function createReadSkillHandler(skills) {
97
+ const skillMap = new Map(skills.map((s) => [s.name, s]));
98
+ return (args) => {
99
+ const skill = skillMap.get(args.skill_name);
100
+ if (!skill) {
101
+ return {
102
+ toolResponse: JSON.stringify({
103
+ error: `Skill "${args.skill_name}" not found`
104
+ }),
105
+ data: null
106
+ };
107
+ }
108
+ return {
109
+ toolResponse: skill.instructions,
110
+ data: null
111
+ };
112
+ };
113
+ }
74
114
  function createToolRouter(options) {
75
115
  const { appendToolResult } = options;
76
116
  const toolMap = /* @__PURE__ */ new Map();
77
117
  for (const [_key, tool] of Object.entries(options.tools)) {
78
118
  toolMap.set(tool.name, tool);
79
119
  }
80
- const isEnabled = (tool) => tool.enabled?.() ?? true;
120
+ const isEnabled = (tool) => tool.enabled ?? true;
81
121
  if (options.subagents) {
82
122
  if (options.subagents.length > 0) {
83
123
  const subagentHooksMap = /* @__PURE__ */ new Map();
@@ -85,7 +125,7 @@ function createToolRouter(options) {
85
125
  if (s.hooks) subagentHooksMap.set(s.agentName, s.hooks);
86
126
  }
87
127
  const resolveSubagentName = (args) => args.subagent;
88
- toolMap.set("Subagent", {
128
+ toolMap.set(SUBAGENT_TOOL_NAME, {
89
129
  ...createSubagentTool(options.subagents),
90
130
  handler: createSubagentHandler(options.subagents),
91
131
  ...subagentHooksMap.size > 0 && {
@@ -107,6 +147,12 @@ function createToolRouter(options) {
107
147
  });
108
148
  }
109
149
  }
150
+ if (options.skills && options.skills.length > 0) {
151
+ toolMap.set(READ_SKILL_TOOL_NAME, {
152
+ ...createReadSkillTool(options.skills),
153
+ handler: createReadSkillHandler(options.skills)
154
+ });
155
+ }
110
156
  async function processToolCall(toolCall, turn, handlerContext) {
111
157
  const startTime = Date.now();
112
158
  const tool = toolMap.get(toolCall.name);
@@ -216,7 +262,9 @@ function createToolRouter(options) {
216
262
  }
217
263
  }
218
264
  if (!recovered) {
219
- throw error;
265
+ throw ApplicationFailure.fromError(error, {
266
+ nonRetryable: true
267
+ });
220
268
  }
221
269
  }
222
270
  if (!resultAppended) {
@@ -278,13 +326,21 @@ function createToolRouter(options) {
278
326
  return Array.from(toolMap.entries()).filter(([, tool]) => isEnabled(tool)).map(([name]) => name);
279
327
  },
280
328
  getToolDefinitions() {
281
- return Array.from(toolMap).filter(([, tool]) => isEnabled(tool)).map(([name, tool]) => ({
282
- name,
283
- description: tool.description,
284
- schema: tool.schema,
285
- strict: tool.strict,
286
- max_uses: tool.max_uses
287
- }));
329
+ const activeSubagents = options.subagents?.filter((subagent) => isEnabled(subagent)) ?? [];
330
+ const activeSkills = options.skills ?? [];
331
+ return [
332
+ ...Array.from(toolMap).filter(
333
+ ([, tool]) => isEnabled(tool) && tool.name !== SUBAGENT_TOOL_NAME && tool.name !== READ_SKILL_TOOL_NAME
334
+ ).map(([name, tool]) => ({
335
+ name,
336
+ description: tool.description,
337
+ schema: tool.schema,
338
+ strict: tool.strict,
339
+ max_uses: tool.max_uses
340
+ })),
341
+ ...activeSubagents.length > 0 ? [createSubagentTool(activeSubagents)] : [],
342
+ ...activeSkills.length > 0 ? [createReadSkillTool(activeSkills)] : []
343
+ ];
288
344
  },
289
345
  // --- Methods for processing tool calls ---
290
346
  async processToolCalls(toolCalls, context) {
@@ -378,18 +434,17 @@ function hasNoOtherToolCalls(toolCalls, excludeName) {
378
434
  var createSession = async ({
379
435
  threadId,
380
436
  agentName,
381
- description,
382
437
  maxTurns = 50,
383
438
  metadata = {},
384
439
  runAgent,
385
440
  threadOps,
386
441
  buildContextMessage,
387
442
  subagents,
443
+ skills,
388
444
  tools = {},
389
445
  processToolsInParallel = true,
390
446
  hooks = {},
391
447
  appendSystemPrompt = true,
392
- systemPrompt,
393
448
  waitForInputTimeout = "48h"
394
449
  }) => {
395
450
  const {
@@ -404,6 +459,7 @@ var createSession = async ({
404
459
  threadId,
405
460
  hooks,
406
461
  subagents,
462
+ skills,
407
463
  parallel: processToolsInParallel
408
464
  });
409
465
  const callSessionEnd = async (exitReason, turns) => {
@@ -447,8 +503,15 @@ var createSession = async ({
447
503
  metadata
448
504
  });
449
505
  }
506
+ const systemPrompt = stateManager.getSystemPrompt();
450
507
  await initializeThread(threadId);
451
- if (appendSystemPrompt && systemPrompt && systemPrompt.trim() !== "") {
508
+ if (appendSystemPrompt) {
509
+ if (!systemPrompt || systemPrompt.trim() === "") {
510
+ throw ApplicationFailure.create({
511
+ message: "No system prompt in state",
512
+ nonRetryable: true
513
+ });
514
+ }
452
515
  await appendSystemMessage(threadId, systemPrompt);
453
516
  }
454
517
  await appendHumanMessage(threadId, await buildContextMessage());
@@ -461,9 +524,7 @@ var createSession = async ({
461
524
  const { message, rawToolCalls, usage } = await runAgent({
462
525
  threadId,
463
526
  agentName,
464
- metadata,
465
- systemPrompt,
466
- description
527
+ metadata
467
528
  });
468
529
  if (usage) {
469
530
  stateManager.updateUsage(usage);
@@ -520,7 +581,7 @@ var createSession = async ({
520
581
  }
521
582
  } catch (error) {
522
583
  exitReason = "failed";
523
- throw error;
584
+ throw ApplicationFailure.fromError(error);
524
585
  } finally {
525
586
  await callSessionEnd(exitReason, stateManager.getTurns());
526
587
  }
@@ -535,14 +596,13 @@ var createSession = async ({
535
596
  function proxyDefaultThreadOps(options) {
536
597
  const activities = proxyActivities(
537
598
  options ?? {
538
- startToCloseTimeout: "30m",
599
+ startToCloseTimeout: "10s",
539
600
  retry: {
540
601
  maximumAttempts: 6,
541
602
  initialInterval: "5s",
542
603
  maximumInterval: "15m",
543
604
  backoffCoefficient: 4
544
- },
545
- heartbeatTimeout: "5m"
605
+ }
546
606
  }
547
607
  );
548
608
  return {
@@ -554,12 +614,14 @@ function proxyDefaultThreadOps(options) {
554
614
  }
555
615
 
556
616
  // src/lib/types.ts
617
+ var agentQueryName = (agentName) => `get${agentName}State`;
618
+ var agentStateChangeUpdateName = (agentName) => `waitFor${agentName}StateChange`;
557
619
  function isTerminalStatus(status) {
558
620
  return status === "COMPLETED" || status === "FAILED" || status === "CANCELLED";
559
621
  }
560
622
  function createAgentStateManager({
561
623
  initialState,
562
- agentConfig
624
+ agentName
563
625
  }) {
564
626
  let status = initialState?.status ?? "RUNNING";
565
627
  let version = initialState?.version ?? 0;
@@ -570,6 +632,7 @@ function createAgentStateManager({
570
632
  let totalCachedWriteTokens = 0;
571
633
  let totalCachedReadTokens = 0;
572
634
  let totalReasonTokens = 0;
635
+ let systemPrompt = initialState?.systemPrompt;
573
636
  const tasks = new Map(initialState?.tasks);
574
637
  const {
575
638
  status: _,
@@ -589,28 +652,32 @@ function createAgentStateManager({
589
652
  ...customState
590
653
  };
591
654
  }
592
- setHandler(defineQuery(`get${agentConfig.agentName}State`), () => {
655
+ const stateQuery = defineQuery(
656
+ agentQueryName(agentName)
657
+ );
658
+ const stateChangeUpdate = defineUpdate(
659
+ agentStateChangeUpdateName(agentName)
660
+ );
661
+ setHandler(stateQuery, () => buildState());
662
+ setHandler(stateChangeUpdate, async (lastKnownVersion) => {
663
+ await condition(
664
+ () => version > lastKnownVersion || isTerminalStatus(status),
665
+ "55s"
666
+ );
593
667
  return buildState();
594
668
  });
595
- setHandler(
596
- defineUpdate(
597
- `waitFor${agentConfig.agentName}StateChange`
598
- ),
599
- async (lastKnownVersion) => {
600
- await condition(
601
- () => version > lastKnownVersion || isTerminalStatus(status),
602
- "55s"
603
- );
604
- return buildState();
605
- }
606
- );
607
669
  return {
670
+ stateQuery,
671
+ stateChangeUpdate,
608
672
  getStatus() {
609
673
  return status;
610
674
  },
611
675
  isRunning() {
612
676
  return status === "RUNNING";
613
677
  },
678
+ getSystemPrompt() {
679
+ return systemPrompt;
680
+ },
614
681
  isTerminal() {
615
682
  return isTerminalStatus(status);
616
683
  },
@@ -678,6 +745,9 @@ function createAgentStateManager({
678
745
  max_uses: tool.max_uses
679
746
  }));
680
747
  },
748
+ setSystemPrompt(newSystemPrompt) {
749
+ systemPrompt = newSystemPrompt;
750
+ },
681
751
  deleteTask(id) {
682
752
  const deleted = tasks.delete(id);
683
753
  if (deleted) {
@@ -704,11 +774,79 @@ function createAgentStateManager({
704
774
  }
705
775
  };
706
776
  }
707
- var AGENT_HANDLER_NAMES = {
708
- getAgentState: "getAgentState",
709
- waitForStateChange: "waitForStateChange",
710
- addMessage: "addMessage"
711
- };
777
+
778
+ // src/lib/skills/parse.ts
779
+ function parseSkillFile(raw) {
780
+ const trimmed = raw.replace(/^\uFEFF/, "");
781
+ const match = trimmed.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?([\s\S]*)$/);
782
+ if (!match) {
783
+ throw new Error(
784
+ "SKILL.md must start with YAML frontmatter delimited by ---"
785
+ );
786
+ }
787
+ const [, yamlBlock, body] = match;
788
+ const frontmatter = parseSimpleYaml(yamlBlock);
789
+ if (!frontmatter.name || typeof frontmatter.name !== "string") {
790
+ throw new Error("SKILL.md frontmatter must include a 'name' field");
791
+ }
792
+ if (!frontmatter.description || typeof frontmatter.description !== "string") {
793
+ throw new Error("SKILL.md frontmatter must include a 'description' field");
794
+ }
795
+ const result = {
796
+ name: frontmatter.name,
797
+ description: frontmatter.description
798
+ };
799
+ if (frontmatter.license) result.license = String(frontmatter.license);
800
+ if (frontmatter.compatibility)
801
+ result.compatibility = String(frontmatter.compatibility);
802
+ if (frontmatter["allowed-tools"]) {
803
+ result.allowedTools = String(frontmatter["allowed-tools"]).split(/\s+/).filter(Boolean);
804
+ }
805
+ if (frontmatter.metadata && typeof frontmatter.metadata === "object" && !Array.isArray(frontmatter.metadata)) {
806
+ result.metadata = frontmatter.metadata;
807
+ }
808
+ return { frontmatter: result, body: body.trim() };
809
+ }
810
+ function parseSimpleYaml(yaml) {
811
+ const result = {};
812
+ const lines = yaml.split(/\r?\n/);
813
+ let currentMapKey = null;
814
+ let currentMap = null;
815
+ for (const line of lines) {
816
+ if (line.trim() === "" || line.trim().startsWith("#")) continue;
817
+ const nestedMatch = line.match(/^(\s{2,}|\t+)(\S+)\s*:\s*(.*)$/);
818
+ if (nestedMatch && currentMapKey && currentMap) {
819
+ const [, , key2, rawVal2] = nestedMatch;
820
+ currentMap[key2] = unquote(rawVal2.trim());
821
+ continue;
822
+ }
823
+ if (currentMapKey && currentMap) {
824
+ result[currentMapKey] = currentMap;
825
+ currentMapKey = null;
826
+ currentMap = null;
827
+ }
828
+ const topMatch = line.match(/^(\S+)\s*:\s*(.*)$/);
829
+ if (!topMatch) continue;
830
+ const [, key, rawVal] = topMatch;
831
+ const val = rawVal.trim();
832
+ if (val === "" || val === "|" || val === ">") {
833
+ currentMapKey = key;
834
+ currentMap = {};
835
+ } else {
836
+ result[key] = unquote(val);
837
+ }
838
+ }
839
+ if (currentMapKey && currentMap) {
840
+ result[currentMapKey] = currentMap;
841
+ }
842
+ return result;
843
+ }
844
+ function unquote(s) {
845
+ if (s.startsWith('"') && s.endsWith('"') || s.startsWith("'") && s.endsWith("'")) {
846
+ return s.slice(1, -1);
847
+ }
848
+ return s;
849
+ }
712
850
  var globTool = {
713
851
  name: "Glob",
714
852
  description: `Search for files matching a glob pattern within the available file system.
@@ -753,7 +891,7 @@ Examples:
753
891
  }),
754
892
  strict: true
755
893
  };
756
- var readTool = {
894
+ var readFileTool = {
757
895
  name: "FileRead",
758
896
  description: `Read file contents with optional pagination.
759
897
 
@@ -776,22 +914,21 @@ The tool returns the file content in an appropriate format:
776
914
  }),
777
915
  strict: true
778
916
  };
779
- var writeTool = {
917
+ var writeFileTool = {
780
918
  name: "FileWrite",
781
919
  description: `Create or overwrite a file with new content.
782
920
 
783
921
  Usage:
784
- - Provide the absolute path to the file
785
922
  - The file will be created if it doesn't exist
786
923
  - If the file exists, it will be completely overwritten
787
924
 
788
925
  IMPORTANT:
789
926
  - You must read the file first (in this session) before writing to it
790
927
  - This is an atomic write operation - the entire file is replaced
791
- - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
928
+ - Path must be relative to the root of the file system (e.g., "docs/readme.md", not "/docs/readme.md")
792
929
  `,
793
930
  schema: z.object({
794
- file_path: z.string().describe("The absolute path to the file to write"),
931
+ file_path: z.string().describe("The path to the file to write"),
795
932
  content: z.string().describe("The content to write to the file")
796
933
  }),
797
934
  strict: true
@@ -826,7 +963,7 @@ IMPORTANT:
826
963
  };
827
964
  var taskCreateTool = {
828
965
  name: "TaskCreate",
829
- description: `Use this tool to create a structured task list for the control test. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
966
+ description: `Use this tool to create a structured task list. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
830
967
  It also helps the user understand the progress of the task and overall progress of their requests.
831
968
 
832
969
  ## When to Use This Tool
@@ -865,17 +1002,17 @@ var taskCreateTool = {
865
1002
  - Include enough detail in the description for another agent to understand and complete the task
866
1003
  - After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed
867
1004
  - Check TaskList first to avoid creating duplicate tasks`,
868
- schema: z13.object({
869
- subject: z13.string().describe(
1005
+ schema: z14.object({
1006
+ subject: z14.string().describe(
870
1007
  'A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")'
871
1008
  ),
872
- description: z13.string().describe(
1009
+ description: z14.string().describe(
873
1010
  "Detailed description of what needs to be done, including context and acceptance criteria"
874
1011
  ),
875
- activeForm: z13.string().describe(
1012
+ activeForm: z14.string().describe(
876
1013
  'Present continuous form shown in spinner when task is in_progress (e.g., "Fixing authentication bug"). This is displayed to the user while you work on the task.'
877
1014
  ),
878
- metadata: z13.record(z13.string(), z13.string()).describe("Arbitrary key-value pairs for tracking")
1015
+ metadata: z14.record(z14.string(), z14.string()).describe("Arbitrary key-value pairs for tracking")
879
1016
  })
880
1017
  };
881
1018
  function createTaskCreateHandler(stateManager) {
@@ -900,8 +1037,8 @@ function createTaskCreateHandler(stateManager) {
900
1037
  var taskGetTool = {
901
1038
  name: "TaskGet",
902
1039
  description: `Retrieve full task details including dependencies.`,
903
- schema: z13.object({
904
- taskId: z13.string().describe("The ID of the task to get")
1040
+ schema: z14.object({
1041
+ taskId: z14.string().describe("The ID of the task to get")
905
1042
  })
906
1043
  };
907
1044
 
@@ -924,7 +1061,7 @@ function createTaskGetHandler(stateManager) {
924
1061
  var taskListTool = {
925
1062
  name: "TaskList",
926
1063
  description: `List all tasks with current state.`,
927
- schema: z13.object({})
1064
+ schema: z14.object({})
928
1065
  };
929
1066
 
930
1067
  // src/tools/task-list/handler.ts
@@ -940,11 +1077,11 @@ function createTaskListHandler(stateManager) {
940
1077
  var taskUpdateTool = {
941
1078
  name: "TaskUpdate",
942
1079
  description: `Update status, add blockers, modify details.`,
943
- schema: z13.object({
944
- taskId: z13.string().describe("The ID of the task to get"),
945
- status: z13.enum(["pending", "in_progress", "completed"]).describe("The status of the task"),
946
- addBlockedBy: z13.array(z13.string()).describe("The IDs of the tasks that are blocking this task"),
947
- addBlocks: z13.array(z13.string()).describe("The IDs of the tasks that this task is blocking")
1080
+ schema: z14.object({
1081
+ taskId: z14.string().describe("The ID of the task to get"),
1082
+ status: z14.enum(["pending", "in_progress", "completed"]).describe("The status of the task"),
1083
+ addBlockedBy: z14.array(z14.string()).describe("The IDs of the tasks that are blocking this task"),
1084
+ addBlocks: z14.array(z14.string()).describe("The IDs of the tasks that this task is blocking")
948
1085
  })
949
1086
  };
950
1087
 
@@ -1012,8 +1149,8 @@ Use this tool to:
1012
1149
  - Execute scripts and chain commands with pipes (|) or logical operators (&&, ||)
1013
1150
  - Inspect files and directories
1014
1151
  `,
1015
- schema: z13.object({
1016
- command: z13.string().describe(
1152
+ schema: z14.object({
1153
+ command: z14.string().describe(
1017
1154
  "The bash command to execute. Can include pipes (|), redirects (>, >>), logical operators (&&, ||), and shell features like command substitution $(...)."
1018
1155
  )
1019
1156
  }),
@@ -1034,18 +1171,18 @@ Usage notes:
1034
1171
  * Use multiSelect: true to allow multiple answers to be selected for a question
1035
1172
  * If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
1036
1173
  `,
1037
- schema: z13.object({
1038
- questions: z13.array(
1039
- z13.object({
1040
- question: z13.string().describe("The full question text to display"),
1041
- header: z13.string().describe("Short label for the question (max 12 characters)"),
1042
- options: z13.array(
1043
- z13.object({
1044
- label: z13.string(),
1045
- description: z13.string()
1174
+ schema: z14.object({
1175
+ questions: z14.array(
1176
+ z14.object({
1177
+ question: z14.string().describe("The full question text to display"),
1178
+ header: z14.string().describe("Short label for the question (max 12 characters)"),
1179
+ options: z14.array(
1180
+ z14.object({
1181
+ label: z14.string(),
1182
+ description: z14.string()
1046
1183
  })
1047
1184
  ).min(0).max(4).describe("Array of 0-4 choices, each with label and description"),
1048
- multiSelect: z13.boolean().describe("If true, users can select multiple options")
1185
+ multiSelect: z14.boolean().describe("If true, users can select multiple options")
1049
1186
  })
1050
1187
  )
1051
1188
  }),
@@ -1053,13 +1190,13 @@ Usage notes:
1053
1190
  };
1054
1191
 
1055
1192
  // src/tools/ask-user-question/handler.ts
1056
- var createAskUserQuestionHandler = () => (args) => {
1193
+ var createAskUserQuestionHandler = () => async (args) => {
1057
1194
  return {
1058
1195
  toolResponse: "Question submitted",
1059
1196
  data: { questions: args.questions }
1060
1197
  };
1061
1198
  };
1062
1199
 
1063
- export { AGENT_HANDLER_NAMES, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createSession, createSubagentTool, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, globTool, grepTool, hasNoOtherToolCalls, isTerminalStatus, proxyDefaultThreadOps, readTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeTool };
1200
+ export { agentQueryName, agentStateChangeUpdateName, askUserQuestionTool, bashTool, createAgentStateManager, createAskUserQuestionHandler, createBashToolDescription, createReadSkillHandler, createReadSkillTool, createSession, createSubagentTool, createTaskCreateHandler, createTaskGetHandler, createTaskListHandler, createTaskUpdateHandler, createToolRouter, defineSubagent, defineTool, editTool, globTool, grepTool, hasNoOtherToolCalls, isTerminalStatus, parseSkillFile, proxyDefaultThreadOps, readFileTool, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, writeFileTool };
1064
1201
  //# sourceMappingURL=workflow.js.map
1065
1202
  //# sourceMappingURL=workflow.js.map