wave-agent-sdk 0.15.1 → 0.15.2

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 (111) hide show
  1. package/builtin/skills/loop/SKILL.md +29 -3
  2. package/dist/agent.d.ts +7 -2
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +34 -11
  5. package/dist/constants/tools.d.ts +3 -0
  6. package/dist/constants/tools.d.ts.map +1 -1
  7. package/dist/constants/tools.js +3 -0
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +1 -0
  11. package/dist/managers/aiManager.d.ts +13 -1
  12. package/dist/managers/aiManager.d.ts.map +1 -1
  13. package/dist/managers/aiManager.js +69 -17
  14. package/dist/managers/hookManager.d.ts.map +1 -1
  15. package/dist/managers/hookManager.js +9 -0
  16. package/dist/managers/mcpManager.d.ts +4 -1
  17. package/dist/managers/mcpManager.d.ts.map +1 -1
  18. package/dist/managers/mcpManager.js +25 -5
  19. package/dist/managers/permissionManager.d.ts +0 -2
  20. package/dist/managers/permissionManager.d.ts.map +1 -1
  21. package/dist/managers/permissionManager.js +0 -30
  22. package/dist/managers/slashCommandManager.d.ts +1 -0
  23. package/dist/managers/slashCommandManager.d.ts.map +1 -1
  24. package/dist/managers/slashCommandManager.js +4 -0
  25. package/dist/managers/toolManager.d.ts +6 -0
  26. package/dist/managers/toolManager.d.ts.map +1 -1
  27. package/dist/managers/toolManager.js +41 -1
  28. package/dist/prompts/index.d.ts.map +1 -1
  29. package/dist/prompts/index.js +14 -4
  30. package/dist/services/initializationService.d.ts +0 -2
  31. package/dist/services/initializationService.d.ts.map +1 -1
  32. package/dist/services/initializationService.js +3 -35
  33. package/dist/services/memory.d.ts +6 -0
  34. package/dist/services/memory.d.ts.map +1 -1
  35. package/dist/services/memory.js +27 -14
  36. package/dist/tools/cronCreateTool.d.ts.map +1 -1
  37. package/dist/tools/cronCreateTool.js +71 -6
  38. package/dist/tools/cronDeleteTool.d.ts.map +1 -1
  39. package/dist/tools/cronDeleteTool.js +5 -1
  40. package/dist/tools/cronListTool.d.ts.map +1 -1
  41. package/dist/tools/cronListTool.js +5 -1
  42. package/dist/tools/enterWorktreeTool.d.ts +8 -0
  43. package/dist/tools/enterWorktreeTool.d.ts.map +1 -0
  44. package/dist/tools/enterWorktreeTool.js +144 -0
  45. package/dist/tools/exitWorktreeTool.d.ts +8 -0
  46. package/dist/tools/exitWorktreeTool.d.ts.map +1 -0
  47. package/dist/tools/exitWorktreeTool.js +184 -0
  48. package/dist/tools/taskManagementTools.d.ts.map +1 -1
  49. package/dist/tools/taskManagementTools.js +4 -0
  50. package/dist/tools/toolSearchTool.d.ts +15 -0
  51. package/dist/tools/toolSearchTool.d.ts.map +1 -0
  52. package/dist/tools/toolSearchTool.js +185 -0
  53. package/dist/tools/types.d.ts +19 -0
  54. package/dist/tools/types.d.ts.map +1 -1
  55. package/dist/tools/webFetchTool.d.ts.map +1 -1
  56. package/dist/tools/webFetchTool.js +1 -0
  57. package/dist/types/agent.d.ts +6 -1
  58. package/dist/types/agent.d.ts.map +1 -1
  59. package/dist/types/hooks.d.ts +3 -1
  60. package/dist/types/hooks.d.ts.map +1 -1
  61. package/dist/types/hooks.js +1 -0
  62. package/dist/utils/containerSetup.d.ts.map +1 -1
  63. package/dist/utils/containerSetup.js +4 -6
  64. package/dist/utils/cronToHuman.d.ts +6 -0
  65. package/dist/utils/cronToHuman.d.ts.map +1 -0
  66. package/dist/utils/cronToHuman.js +79 -0
  67. package/dist/utils/isDeferredTool.d.ts +19 -0
  68. package/dist/utils/isDeferredTool.d.ts.map +1 -0
  69. package/dist/utils/isDeferredTool.js +31 -0
  70. package/dist/utils/mcpUtils.d.ts.map +1 -1
  71. package/dist/utils/mcpUtils.js +1 -0
  72. package/dist/utils/parseCronExpression.d.ts +6 -0
  73. package/dist/utils/parseCronExpression.d.ts.map +1 -0
  74. package/dist/utils/parseCronExpression.js +74 -0
  75. package/dist/utils/worktreeSession.d.ts +26 -0
  76. package/dist/utils/worktreeSession.d.ts.map +1 -0
  77. package/dist/utils/worktreeSession.js +14 -0
  78. package/dist/utils/worktreeUtils.d.ts +42 -0
  79. package/dist/utils/worktreeUtils.d.ts.map +1 -0
  80. package/dist/utils/worktreeUtils.js +236 -0
  81. package/package.json +1 -1
  82. package/src/agent.ts +49 -12
  83. package/src/constants/tools.ts +3 -0
  84. package/src/index.ts +1 -0
  85. package/src/managers/aiManager.ts +73 -18
  86. package/src/managers/hookManager.ts +10 -0
  87. package/src/managers/mcpManager.ts +32 -6
  88. package/src/managers/permissionManager.ts +0 -42
  89. package/src/managers/slashCommandManager.ts +6 -0
  90. package/src/managers/toolManager.ts +47 -1
  91. package/src/prompts/index.ts +17 -3
  92. package/src/services/initializationService.ts +2 -41
  93. package/src/services/memory.ts +30 -17
  94. package/src/tools/cronCreateTool.ts +81 -8
  95. package/src/tools/cronDeleteTool.ts +7 -2
  96. package/src/tools/cronListTool.ts +7 -2
  97. package/src/tools/enterWorktreeTool.ts +183 -0
  98. package/src/tools/exitWorktreeTool.ts +242 -0
  99. package/src/tools/taskManagementTools.ts +4 -0
  100. package/src/tools/toolSearchTool.ts +228 -0
  101. package/src/tools/types.ts +19 -0
  102. package/src/tools/webFetchTool.ts +1 -0
  103. package/src/types/agent.ts +6 -0
  104. package/src/types/hooks.ts +4 -0
  105. package/src/utils/containerSetup.ts +7 -8
  106. package/src/utils/cronToHuman.ts +99 -0
  107. package/src/utils/isDeferredTool.ts +36 -0
  108. package/src/utils/mcpUtils.ts +1 -0
  109. package/src/utils/parseCronExpression.ts +78 -0
  110. package/src/utils/worktreeSession.ts +36 -0
  111. package/src/utils/worktreeUtils.ts +288 -0
@@ -0,0 +1,228 @@
1
+ /**
2
+ * ToolSearchTool - Discovers deferred tool schemas on demand.
3
+ *
4
+ * When tool deferral is enabled, deferred tools are not sent to the API.
5
+ * The model must call this tool to discover a deferred tool's full schema
6
+ * before it can invoke it.
7
+ *
8
+ * Query formats:
9
+ * - "select:ToolName" — direct selection by name (comma-separated for multiple)
10
+ * - "notebook jupyter" — keyword search, up to max_results best matches
11
+ * - "+slack send" — require "slack" in the name, rank by remaining terms
12
+ */
13
+
14
+ import { ToolPlugin, ToolResult, ToolContext } from "./types.js";
15
+ import {
16
+ isDeferredTool,
17
+ TOOL_SEARCH_TOOL_NAME,
18
+ } from "../utils/isDeferredTool.js";
19
+
20
+ function formatSchema(tool: ToolPlugin): string {
21
+ const desc = tool.config.function.description || "";
22
+ const params = JSON.stringify(tool.config.function.parameters || {}, null, 2);
23
+ return `${tool.name}: ${desc}\nParameters: ${params}`;
24
+ }
25
+
26
+ /**
27
+ * Parse tool name into searchable parts (handles CamelCase and underscores).
28
+ */
29
+ function parseToolName(name: string): string[] {
30
+ return name
31
+ .replace(/([a-z])([A-Z])/g, "$1 $2") // CamelCase to spaces
32
+ .replace(/_/g, " ")
33
+ .toLowerCase()
34
+ .split(/\s+/)
35
+ .filter(Boolean);
36
+ }
37
+
38
+ /**
39
+ * Keyword search over deferred tools by name and description.
40
+ * Matches Claude Code's scoring: required terms (+prefix) must all match,
41
+ * optional terms contribute to ranking.
42
+ */
43
+ function keywordSearch(
44
+ query: string,
45
+ deferredTools: ToolPlugin[],
46
+ maxResults: number,
47
+ ): ToolPlugin[] {
48
+ const queryLower = query.toLowerCase().trim();
49
+ const queryTerms = queryLower.split(/\s+/).filter(Boolean);
50
+
51
+ // Exact match fast path
52
+ const exact = deferredTools.find((t) => t.name.toLowerCase() === queryLower);
53
+ if (exact) return [exact];
54
+
55
+ // Partition into required (+prefixed) and optional terms
56
+ const requiredTerms: string[] = [];
57
+ const optionalTerms: string[] = [];
58
+ for (const term of queryTerms) {
59
+ if (term.startsWith("+") && term.length > 1) {
60
+ requiredTerms.push(term.slice(1));
61
+ } else {
62
+ optionalTerms.push(term);
63
+ }
64
+ }
65
+
66
+ const allScoringTerms =
67
+ requiredTerms.length > 0
68
+ ? [...requiredTerms, ...optionalTerms]
69
+ : queryTerms;
70
+
71
+ // Pre-filter to tools matching ALL required terms
72
+ let candidateTools = deferredTools;
73
+ if (requiredTerms.length > 0) {
74
+ candidateTools = deferredTools.filter((tool) => {
75
+ const parts = parseToolName(tool.name);
76
+ const desc = (tool.config.function.description || "").toLowerCase();
77
+ return requiredTerms.every(
78
+ (term) =>
79
+ parts.includes(term) ||
80
+ parts.some((p) => p.includes(term)) ||
81
+ desc.includes(term),
82
+ );
83
+ });
84
+ }
85
+
86
+ // Score each tool
87
+ const scored = candidateTools
88
+ .map((tool) => {
89
+ const parts = parseToolName(tool.name);
90
+ const desc = (tool.config.function.description || "").toLowerCase();
91
+ let score = 0;
92
+
93
+ for (const term of allScoringTerms) {
94
+ // Exact part match (high weight)
95
+ if (parts.includes(term)) {
96
+ score += tool.isMcp ? 12 : 10;
97
+ } else if (parts.some((p) => p.includes(term))) {
98
+ score += tool.isMcp ? 6 : 5;
99
+ }
100
+
101
+ // Full name fallback
102
+ if (tool.name.toLowerCase().includes(term) && score === 0) {
103
+ score += 3;
104
+ }
105
+
106
+ // Description match
107
+ if (desc.includes(term)) {
108
+ score += 2;
109
+ }
110
+ }
111
+
112
+ return { tool, score };
113
+ })
114
+ .filter((s) => s.score > 0)
115
+ .sort((a, b) => b.score - a.score)
116
+ .slice(0, maxResults)
117
+ .map((s) => s.tool);
118
+
119
+ return scored;
120
+ }
121
+
122
+ export const toolSearchTool: ToolPlugin = {
123
+ name: TOOL_SEARCH_TOOL_NAME,
124
+ config: {
125
+ type: "function",
126
+ function: {
127
+ name: TOOL_SEARCH_TOOL_NAME,
128
+ description: `Fetches full schema definitions for deferred tools so they can be called.
129
+
130
+ Deferred tools appear by name in <available-deferred-tools> messages. Until fetched, only the name is known — there is no parameter schema, so the tool cannot be invoked. This tool takes a query, matches it against the deferred tool list, and returns the matched tools' complete JSONSchema definitions inside a <functions> block. Once a tool's schema appears in that result, it is callable exactly like any tool defined at the top of the prompt.
131
+
132
+ Result format: each matched tool appears as one <function>{"description": "...", "name": "...", "parameters": {...}}`,
133
+ },
134
+ },
135
+ shouldDefer: false, // Always available
136
+ execute: async (
137
+ args: Record<string, unknown>,
138
+ context: ToolContext,
139
+ ): Promise<ToolResult> => {
140
+ const { query, max_results = 5 } = args as {
141
+ query?: string;
142
+ max_results?: number;
143
+ };
144
+
145
+ if (!query) {
146
+ return {
147
+ success: false,
148
+ content: "",
149
+ error: "Missing required 'query' parameter",
150
+ };
151
+ }
152
+
153
+ if (!context.toolManager) {
154
+ return {
155
+ success: false,
156
+ content: "",
157
+ error: "ToolManager not available in context",
158
+ };
159
+ }
160
+
161
+ const allTools = context.toolManager.list();
162
+ const deferredTools = allTools.filter(isDeferredTool);
163
+
164
+ // Handle select: prefix
165
+ const selectMatch = query.match(/^select:(.+)$/i);
166
+ if (selectMatch) {
167
+ const requested = selectMatch[1]!
168
+ .split(",")
169
+ .map((s) => s.trim())
170
+ .filter(Boolean);
171
+
172
+ const found: ToolPlugin[] = [];
173
+ const missing: string[] = [];
174
+
175
+ for (const toolName of requested) {
176
+ const tool =
177
+ deferredTools.find((t) => t.name === toolName) ??
178
+ allTools.find((t) => t.name === toolName);
179
+ if (tool) {
180
+ if (!found.some((f) => f.name === tool.name)) found.push(tool);
181
+ } else {
182
+ missing.push(toolName);
183
+ }
184
+ }
185
+
186
+ if (found.length === 0) {
187
+ return {
188
+ success: false,
189
+ content: "",
190
+ error: `No matching deferred tools found for: ${missing.join(", ")}`,
191
+ };
192
+ }
193
+
194
+ const result = found.map(formatSchema).join("\n\n---\n\n");
195
+ const shortResult = `Discovered tools: ${found.map((t) => t.name).join(", ")}`;
196
+
197
+ return {
198
+ success: true,
199
+ content: result,
200
+ shortResult,
201
+ };
202
+ }
203
+
204
+ // Keyword search
205
+ const matches = keywordSearch(query, deferredTools, max_results);
206
+
207
+ if (matches.length === 0) {
208
+ return {
209
+ success: false,
210
+ content: "",
211
+ error: `No matching deferred tools found for query: "${query}". Available deferred tools: ${getDeferredToolNamesList(deferredTools)}`,
212
+ };
213
+ }
214
+
215
+ const result = matches.map(formatSchema).join("\n\n---\n\n");
216
+ const shortResult = `Found ${matches.length} tools: ${matches.map((t) => t.name).join(", ")}`;
217
+
218
+ return {
219
+ success: true,
220
+ content: result,
221
+ shortResult,
222
+ };
223
+ },
224
+ };
225
+
226
+ function getDeferredToolNamesList(tools: ToolPlugin[]): string {
227
+ return tools.map((t) => t.name).join(", ");
228
+ }
@@ -31,6 +31,21 @@ export interface ToolPlugin {
31
31
  workdir?: string;
32
32
  isSubagent?: boolean;
33
33
  }) => string;
34
+ /**
35
+ * When true, this tool is deferred — it's not sent to the API until the model
36
+ * discovers it via ToolSearch. MCP tools are always deferred.
37
+ */
38
+ shouldDefer?: boolean;
39
+ /**
40
+ * When true, this tool is never deferred — its full schema always appears in
41
+ * the initial prompt even when tool search is enabled.
42
+ */
43
+ alwaysLoad?: boolean;
44
+ /**
45
+ * When true, this is an MCP tool (auto-set by McpManager). MCP tools are
46
+ * always deferred unless they have alwaysLoad: true.
47
+ */
48
+ isMcp?: boolean;
34
49
  }
35
50
 
36
51
  export interface ToolResult {
@@ -58,6 +73,8 @@ export interface ToolContext {
58
73
  abortSignal?: AbortSignal;
59
74
  backgroundTaskManager?: import("../managers/backgroundTaskManager.js").BackgroundTaskManager;
60
75
  workdir: string;
76
+ /** Tool manager instance for tool discovery (used by ToolSearchTool) */
77
+ toolManager?: import("../managers/toolManager.js").ToolManager;
61
78
  /** Permission mode for this tool execution */
62
79
  permissionMode?: PermissionMode;
63
80
  /** Custom permission callback */
@@ -103,4 +120,6 @@ export interface ToolContext {
103
120
  };
104
121
  /** State of files read in the current session for deduplication */
105
122
  readFileState?: Map<string, { mtime: number; hash: string }>;
123
+ /** Hook manager instance for executing hooks */
124
+ hookManager?: import("../managers/hookManager.js").HookManager;
106
125
  }
@@ -103,6 +103,7 @@ const GITHUB_URL_ERROR =
103
103
 
104
104
  export const webFetchTool: ToolPlugin = {
105
105
  name: WEB_FETCH_TOOL_NAME,
106
+ shouldDefer: true,
106
107
  config: {
107
108
  type: "function",
108
109
  function: {
@@ -8,6 +8,7 @@ import type {
8
8
  ILspManager,
9
9
  PluginConfig,
10
10
  BackgroundTask,
11
+ McpServerConfig,
11
12
  } from "./index.js";
12
13
  import type { MessageManagerCallbacks } from "../managers/messageManager.js";
13
14
  import type { BackgroundTaskManagerCallbacks } from "../managers/backgroundTaskManager.js";
@@ -78,6 +79,11 @@ export interface AgentOptions {
78
79
  * These rules follow the standard permission rule syntax: `ToolName` or `ToolName(pattern)`.
79
80
  */
80
81
  disallowedTools?: string[];
82
+ /**
83
+ * Optional MCP server configs to connect at startup.
84
+ * Overrides .mcp.json for specified server names.
85
+ */
86
+ mcpServers?: Record<string, McpServerConfig>;
81
87
  [key: string]: unknown;
82
88
  }
83
89
 
@@ -21,6 +21,7 @@ export type HookEvent =
21
21
  | "SubagentStop"
22
22
  | "PermissionRequest"
23
23
  | "WorktreeCreate"
24
+ | "WorktreeRemove"
24
25
  | "SessionStart"
25
26
  | "SessionEnd";
26
27
 
@@ -45,6 +46,8 @@ export interface HookExecutionContext {
45
46
  toolName?: string; // Present for PreToolUse/PostToolUse events
46
47
  projectDir: string; // Absolute path for $WAVE_PROJECT_DIR
47
48
  timestamp: Date;
49
+ worktreeName?: string; // Present for WorktreeCreate
50
+ worktreePath?: string; // Present for WorktreeRemove
48
51
  }
49
52
 
50
53
  // Result of hook execution
@@ -109,6 +112,7 @@ export function isValidHookEvent(event: string): event is HookEvent {
109
112
  "SubagentStop",
110
113
  "PermissionRequest",
111
114
  "WorktreeCreate",
115
+ "WorktreeRemove",
112
116
  "SessionStart",
113
117
  "SessionEnd",
114
118
  ].includes(event);
@@ -26,9 +26,8 @@ import { ConfigurationService } from "../services/configurationService.js";
26
26
  import { ReversionService } from "../services/reversionService.js";
27
27
  import { MemoryService } from "../services/memory.js";
28
28
  import { AutoMemoryService } from "../services/autoMemoryService.js";
29
- import { getGitMainRepoRoot } from "./gitUtils.js";
30
29
  import { USER_MEMORY_FILE } from "./constants.js";
31
- import type { AgentOptions } from "../types/index.js";
30
+ import type { AgentOptions, McpServerConfig } from "../types/index.js";
32
31
  import type {
33
32
  PermissionMode,
34
33
  Usage,
@@ -89,11 +88,6 @@ export function setupAgentContainer(
89
88
  container.register("ForegroundTaskManager", foregroundTaskManager);
90
89
  container.register("ConfigurationService", configurationService);
91
90
 
92
- if (options.worktreeName) {
93
- container.register("WorktreeName", options.worktreeName);
94
- container.register("MainRepoRoot", getGitMainRepoRoot(workdir));
95
- }
96
-
97
91
  const memoryService = new MemoryService(container);
98
92
  container.register("MemoryService", memoryService);
99
93
 
@@ -145,7 +139,12 @@ export function setupAgentContainer(
145
139
  });
146
140
  container.register("BackgroundTaskManager", backgroundTaskManager);
147
141
 
148
- const mcpManager = new McpManager(container, { callbacks });
142
+ const mcpManager = new McpManager(container, {
143
+ callbacks,
144
+ mcpServers: options.mcpServers as
145
+ | Record<string, McpServerConfig>
146
+ | undefined,
147
+ });
149
148
  container.register("McpManager", mcpManager);
150
149
 
151
150
  const lspManager = options.lspManager || new LspManager(container);
@@ -0,0 +1,99 @@
1
+ // Human-readable cron expression display.
2
+ // Intentionally narrow: covers common patterns; falls through to raw cron
3
+ // string for anything else. Based on Claude Code's cronToHuman implementation.
4
+
5
+ const DAY_NAMES = [
6
+ "Sunday",
7
+ "Monday",
8
+ "Tuesday",
9
+ "Wednesday",
10
+ "Thursday",
11
+ "Friday",
12
+ "Saturday",
13
+ ];
14
+
15
+ function formatLocalTime(minute: number, hour: number): string {
16
+ const d = new Date(2000, 0, 1, hour, minute);
17
+ return d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
18
+ }
19
+
20
+ /**
21
+ * Convert a cron expression to a human-readable string.
22
+ * Covers common patterns; falls through to raw cron for anything else.
23
+ */
24
+ export function cronToHuman(cron: string): string {
25
+ const parts = cron.trim().split(/\s+/);
26
+ if (parts.length !== 5) return cron;
27
+
28
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = parts as [
29
+ string,
30
+ string,
31
+ string,
32
+ string,
33
+ string,
34
+ ];
35
+
36
+ // Every N minutes: step/N * * * *
37
+ const everyMinMatch = minute.match(/^\*\/(\d+)$/);
38
+ if (
39
+ everyMinMatch &&
40
+ hour === "*" &&
41
+ dayOfMonth === "*" &&
42
+ month === "*" &&
43
+ dayOfWeek === "*"
44
+ ) {
45
+ const n = parseInt(everyMinMatch[1]!, 10);
46
+ return n === 1 ? "Every minute" : `Every ${n} minutes`;
47
+ }
48
+
49
+ // Every hour: 0 * * * *
50
+ if (
51
+ minute.match(/^\d+$/) &&
52
+ hour === "*" &&
53
+ dayOfMonth === "*" &&
54
+ month === "*" &&
55
+ dayOfWeek === "*"
56
+ ) {
57
+ const m = parseInt(minute, 10);
58
+ if (m === 0) return "Every hour";
59
+ return `Every hour at :${m.toString().padStart(2, "0")}`;
60
+ }
61
+
62
+ // Every N hours: 0 step/N * * *
63
+ const everyHourMatch = hour.match(/^\*\/(\d+)$/);
64
+ if (
65
+ minute.match(/^\d+$/) &&
66
+ everyHourMatch &&
67
+ dayOfMonth === "*" &&
68
+ month === "*" &&
69
+ dayOfWeek === "*"
70
+ ) {
71
+ const n = parseInt(everyHourMatch[1]!, 10);
72
+ const m = parseInt(minute, 10);
73
+ const suffix = m === 0 ? "" : ` at :${m.toString().padStart(2, "0")}`;
74
+ return n === 1 ? `Every hour${suffix}` : `Every ${n} hours${suffix}`;
75
+ }
76
+
77
+ if (!minute.match(/^\d+$/) || !hour.match(/^\d+$/)) return cron;
78
+ const m = parseInt(minute, 10);
79
+ const h = parseInt(hour, 10);
80
+
81
+ // Daily at specific time: M H * * *
82
+ if (dayOfMonth === "*" && month === "*" && dayOfWeek === "*") {
83
+ return `Every day at ${formatLocalTime(m, h)}`;
84
+ }
85
+
86
+ // Specific day of week: M H * * D
87
+ if (dayOfMonth === "*" && month === "*" && dayOfWeek.match(/^\d$/)) {
88
+ const dayIndex = parseInt(dayOfWeek, 10) % 7;
89
+ const dayName = DAY_NAMES[dayIndex];
90
+ if (dayName) return `Every ${dayName} at ${formatLocalTime(m, h)}`;
91
+ }
92
+
93
+ // Weekdays: M H * * 1-5
94
+ if (dayOfMonth === "*" && month === "*" && dayOfWeek === "1-5") {
95
+ return `Weekdays at ${formatLocalTime(m, h)}`;
96
+ }
97
+
98
+ return cron;
99
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Determines if a tool should be deferred (not sent to the API until discovered).
3
+ *
4
+ * A tool is deferred if:
5
+ * - It has shouldDefer: true
6
+ * - It is an MCP tool (isMcp: true)
7
+ *
8
+ * A tool is NEVER deferred if:
9
+ * - It has alwaysLoad: true
10
+ * - It is the ToolSearch tool itself (must always be available)
11
+ */
12
+
13
+ import type { ToolPlugin } from "../tools/types.js";
14
+
15
+ export const TOOL_SEARCH_TOOL_NAME = "ToolSearch";
16
+
17
+ export function isDeferredTool(tool: ToolPlugin): boolean {
18
+ // Never defer if explicitly marked as alwaysLoad
19
+ if (tool.alwaysLoad === true) return false;
20
+
21
+ // Never defer ToolSearch itself — the model needs it to discover other tools
22
+ if (tool.name === TOOL_SEARCH_TOOL_NAME) return false;
23
+
24
+ // MCP tools are always deferred (workflow-specific, potentially many)
25
+ if (tool.isMcp === true) return true;
26
+
27
+ // Defer if marked with shouldDefer flag
28
+ return tool.shouldDefer === true;
29
+ }
30
+
31
+ /**
32
+ * Get the list of deferred tool names from a tools array.
33
+ */
34
+ export function getDeferredToolNames(tools: ToolPlugin[]): string[] {
35
+ return tools.filter(isDeferredTool).map((t) => t.name);
36
+ }
@@ -91,6 +91,7 @@ export function createMcpToolPlugin(
91
91
  return {
92
92
  name: prefixedName,
93
93
  config: mcpToolToOpenAITool(mcpTool, serverName),
94
+ isMcp: true, // MCP tools are always deferred
94
95
  async execute(
95
96
  args: Record<string, unknown>,
96
97
  context?: ToolContext,
@@ -0,0 +1,78 @@
1
+ // Minimal cron expression validation.
2
+ // Supports the standard 5-field cron subset:
3
+ // minute hour day-of-month month day-of-week
4
+ //
5
+ // Field syntax: wildcard, N, step (star-slash-N), range (N-M), list (N,M,...).
6
+ // No L, W, ?, or name aliases. Based on Claude Code's parseCronExpression.
7
+
8
+ type FieldRange = { min: number; max: number };
9
+
10
+ const FIELD_RANGES: FieldRange[] = [
11
+ { min: 0, max: 59 }, // minute
12
+ { min: 0, max: 23 }, // hour
13
+ { min: 1, max: 31 }, // dayOfMonth
14
+ { min: 1, max: 12 }, // month
15
+ { min: 0, max: 6 }, // dayOfWeek (0=Sunday; 7 accepted as Sunday alias)
16
+ ];
17
+
18
+ function expandField(field: string, range: FieldRange): number[] | null {
19
+ const { min, max } = range;
20
+ const out = new Set<number>();
21
+
22
+ for (const part of field.split(",")) {
23
+ // wildcard or star-slash-N
24
+ const stepMatch = part.match(/^\*(?:\/(\d+))?$/);
25
+ if (stepMatch) {
26
+ const step = stepMatch[1] ? parseInt(stepMatch[1], 10) : 1;
27
+ if (step < 1) return null;
28
+ for (let i = min; i <= max; i += step) out.add(i);
29
+ continue;
30
+ }
31
+
32
+ // N-M or N-M/S
33
+ const rangeMatch = part.match(/^(\d+)-(\d+)(?:\/(\d+))?$/);
34
+ if (rangeMatch) {
35
+ const lo = parseInt(rangeMatch[1]!, 10);
36
+ const hi = parseInt(rangeMatch[2]!, 10);
37
+ const step = rangeMatch[3] ? parseInt(rangeMatch[3], 10) : 1;
38
+ const isDow = min === 0 && max === 6;
39
+ const effMax = isDow ? 7 : max;
40
+ if (lo > hi || step < 1 || lo < min || hi > effMax) return null;
41
+ for (let i = lo; i <= hi; i += step) {
42
+ out.add(isDow && i === 7 ? 0 : i);
43
+ }
44
+ continue;
45
+ }
46
+
47
+ // plain N
48
+ const singleMatch = part.match(/^\d+$/);
49
+ if (singleMatch) {
50
+ let n = parseInt(part, 10);
51
+ if (min === 0 && max === 6 && n === 7) n = 0;
52
+ if (n < min || n > max) return null;
53
+ out.add(n);
54
+ continue;
55
+ }
56
+
57
+ return null;
58
+ }
59
+
60
+ if (out.size === 0) return null;
61
+ return Array.from(out).sort((a, b) => a - b);
62
+ }
63
+
64
+ /**
65
+ * Validate a 5-field cron expression.
66
+ * Returns true if valid, false otherwise.
67
+ */
68
+ export function parseCronExpression(expr: string): boolean {
69
+ const parts = expr.trim().split(/\s+/);
70
+ if (parts.length !== 5) return false;
71
+
72
+ for (let i = 0; i < 5; i++) {
73
+ const result = expandField(parts[i]!, FIELD_RANGES[i]!);
74
+ if (!result) return false;
75
+ }
76
+
77
+ return true;
78
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Module-level worktree session state tracking.
3
+ * Analogous to Claude Code's currentWorktreeSession in worktree.ts.
4
+ *
5
+ * Tracks whether the current session entered a worktree via EnterWorktree tool,
6
+ * so ExitWorktree can validate scope and restore the original CWD.
7
+ */
8
+
9
+ export interface WorktreeSession {
10
+ /** The working directory the session was in before EnterWorktree */
11
+ originalCwd: string;
12
+ /** Path to the worktree directory */
13
+ worktreePath: string;
14
+ /** Git branch name for the worktree */
15
+ worktreeBranch: string;
16
+ /** User-provided or auto-generated worktree name */
17
+ worktreeName: string;
18
+ /** Whether this worktree was newly created (vs resumed existing) */
19
+ isNew: boolean;
20
+ /** The canonical git repo root */
21
+ repoRoot: string;
22
+ /** The HEAD commit of the original branch at worktree creation time */
23
+ originalHeadCommit?: string;
24
+ }
25
+
26
+ let currentWorktreeSession: WorktreeSession | null = null;
27
+
28
+ export function getCurrentWorktreeSession(): WorktreeSession | null {
29
+ return currentWorktreeSession;
30
+ }
31
+
32
+ export function setCurrentWorktreeSession(
33
+ session: WorktreeSession | null,
34
+ ): void {
35
+ currentWorktreeSession = session;
36
+ }