Add todo tools

This commit is contained in:
Alex Gleason committed 2026-01-22 00:42:01 -06:00
1 parent 87956df961
commit ec5dc6d963
8 files changed
+893 -5

No files matched your search

+5 -1
View File
@@ -44,6 +44,8 @@ import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerati
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
@@ -203,6 +205,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
skill: new SkillTool(fs, pluginsPath, cwd),
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
websearch: new WebSearchTool(),
todowrite: new TodoWriteTool(fs, projectId),
todoread: new TodoReadTool(fs, projectId),
};
// Add generate_image tool if imageModel is configured
@@ -254,7 +258,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit, projectId]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
+94 -2
View File
@@ -27,6 +27,7 @@ import {
TriangleAlert,
X,
Search,
Clipboard,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
@@ -100,7 +101,7 @@ function stripProjectPrefix(path: string, projectId?: string, projectsPath = '/p
/**
* Get tool information including icon, title, and calling title
*/
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string): ToolInfo {
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
switch (toolName) {
case 'shell':
return {
@@ -372,6 +373,45 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to configure image generation',
};
case 'todowrite':
case 'todoread': {
// Try to parse the result to get task counts for the title
let title = toolName === 'todowrite' ? 'Updated todo list' : 'Viewed todo list';
if (result) {
try {
const todos = JSON.parse(result);
if (Array.isArray(todos)) {
const activeTodos = todos.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completedTodos = todos.filter((x: { status: string }) => x.status === 'completed');
const inProgressTask = todos.find((x: { status: string }) => x.status === 'in_progress');
// Format: "[<completed>/<total>] <active-task>" if in_progress task exists
if (inProgressTask) {
const taskName = inProgressTask.content || 'Task';
const totalTasks = todos.length;
title = `[${completedTodos.length + 1}/${totalTasks}] ${taskName}`;
} else if (activeTodos.length === 0 && completedTodos.length > 0) {
// All tasks completed
title = `${completedTodos.length + 1} task${completedTodos.length !== 0 ? 's' : ''} completed`;
} else if (completedTodos.length === 0) {
// No completed tasks yet
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}`;
} else {
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}, ${completedTodos.length} completed`;
}
}
} catch {
// If parsing fails, use default title
}
}
return {
icon: Clipboard,
title,
callingTitle: toolName === 'todowrite' ? 'Updating todo list' : 'Viewing todo list',
errorTitle: toolName === 'todowrite' ? 'Failed to update todo list' : 'Failed to view todo list',
};
}
default: {
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
return {
@@ -408,7 +448,7 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
const [imageLoadError, setImageLoadError] = useState(false);
const { projectsPath } = useFSPaths();
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath);
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath, result);
const IconComponent = toolInfo.icon;
// Check if this is an error result
@@ -557,6 +597,58 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
);
}
// Todo tools expanded content
if (toolName === 'todowrite' || toolName === 'todoread') {
try {
const todos = JSON.parse(result);
if (!Array.isArray(todos)) {
throw new Error('Invalid todo format');
}
if (todos.length === 0) {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="text-muted-foreground italic">No todos found</div>
</div>
);
}
// Find the first in_progress task for bold styling
const firstInProgressIndex = todos.findIndex((x: { status: string }) => x.status === 'in_progress');
return (
<div className="mt-1 rounded border bg-muted/30 text-xs overflow-hidden">
<div className="px-3 py-2 space-y-1">
{todos.map((todo: { id: string; content: string; status: string; priority: string }, index: number) => {
const isChecked = todo.status === 'completed' || todo.status === 'cancelled';
const isFirstInProgress = index === firstInProgressIndex;
return (
<div key={todo.id} className="flex items-start gap-2 py-1">
<input
type="checkbox"
checked={isChecked}
readOnly
className="mt-0.5 h-4 w-4 rounded border-gray-300 cursor-default"
/>
<span className={cn(
"flex-1 text-foreground",
isChecked && "line-through text-muted-foreground",
isFirstInProgress && "font-bold"
)}>
{todo.content}
</span>
</div>
);
})}
</div>
</div>
);
} catch {
// If parsing fails, fall through to default rendering
}
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
+143
View File
@@ -0,0 +1,143 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TodoReadTool } from './TodoReadTool';
import { TodoWriteTool } from './TodoWriteTool';
import { MockFS } from '@/test/MockFS';
import type { JSRuntimeFS } from '../JSRuntime';
describe('TodoReadTool', () => {
let fs: JSRuntimeFS;
let readTool: TodoReadTool;
let writeTool: TodoWriteTool;
const projectId = 'test-project';
beforeEach(() => {
fs = new MockFS() as unknown as JSRuntimeFS;
readTool = new TodoReadTool(fs, projectId);
writeTool = new TodoWriteTool(fs, projectId);
});
it('should have a description', () => {
expect(readTool.description).toBeDefined();
expect(readTool.description.length).toBeGreaterThan(0);
});
it('should have an input schema', () => {
expect(readTool.inputSchema).toBeDefined();
});
it('should return empty message when no todos exist', async () => {
const result = await readTool.execute({});
// Should return empty JSON array
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should read todos from .git/ai/TODO file', async () => {
const todos = [
{
id: '1',
content: 'Test task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Test task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
];
// Write todos first
await writeTool.execute({ todos });
// Read them back
const result = await readTool.execute({});
// Should return JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(1);
expect(completed.length).toBe(1);
});
it('should count active and completed tasks correctly', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
{
id: '3',
content: 'Task 3',
status: 'in_progress' as const,
priority: 'low' as const,
},
{
id: '4',
content: 'Task 4',
status: 'cancelled' as const,
priority: 'low' as const,
},
];
await writeTool.execute({ todos });
const result = await readTool.execute({});
// Should return JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(2);
expect(completed.length).toBe(1);
});
it('should handle invalid JSON in TODO file', async () => {
// Write invalid JSON
await fs.mkdir(`/projects/${projectId}/.git/ai`, { recursive: true });
await fs.writeFile(`/projects/${projectId}/.git/ai/TODO`, 'invalid json');
const result = await readTool.execute({});
// Should return empty JSON array when file is invalid
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should display full todo information', async () => {
const todos = [
{
id: 'abc123',
content: 'Implement new feature',
status: 'in_progress' as const,
priority: 'high' as const,
},
];
await writeTool.execute({ todos });
const result = await readTool.execute({});
// Should return JSON
const parsed = JSON.parse(result.content);
expect(parsed[0].id).toBe('abc123');
expect(parsed[0].content).toBe('Implement new feature');
expect(parsed[0].status).toBe('in_progress');
expect(parsed[0].priority).toBe('high');
});
});
+44
View File
@@ -0,0 +1,44 @@
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import type { TodoInfo } from "./TodoWriteTool";
import { join } from "path-browserify";
type TodoReadParams = Record<string, never>;
export class TodoReadTool implements Tool<TodoReadParams> {
private fs: JSRuntimeFS;
private projectId: string;
readonly description = "Use this tool to read your todo list";
readonly inputSchema = z.object({});
constructor(fs: JSRuntimeFS, projectId: string) {
this.fs = fs;
this.projectId = projectId;
}
async execute(_args: TodoReadParams): Promise<ToolResult> {
try {
// Read todos from .git/ai/TODO file
const todoPath = join("/projects", this.projectId, ".git", "ai", "TODO");
let todos: TodoInfo[] = [];
try {
const content = await this.fs.readFile(todoPath, "utf8");
todos = JSON.parse(content);
} catch {
// File doesn't exist or is invalid - return empty array
todos = [];
}
return {
content: JSON.stringify(todos, null, 2),
};
} catch (error) {
throw new Error(`Failed to read todos: ${String(error)}`);
}
}
}
+137
View File
@@ -0,0 +1,137 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TodoWriteTool } from './TodoWriteTool';
import { MockFS } from '@/test/MockFS';
import type { JSRuntimeFS } from '../JSRuntime';
describe('TodoWriteTool', () => {
let fs: JSRuntimeFS;
let tool: TodoWriteTool;
const projectId = 'test-project';
beforeEach(() => {
fs = new MockFS() as unknown as JSRuntimeFS;
tool = new TodoWriteTool(fs, projectId);
});
it('should have a description', () => {
expect(tool.description).toBeDefined();
expect(tool.description.length).toBeGreaterThan(0);
});
it('should have an input schema', () => {
expect(tool.inputSchema).toBeDefined();
});
it('should write todos to .git/ai/TODO file', async () => {
const todos = [
{
id: '1',
content: 'Test task',
status: 'pending' as const,
priority: 'medium' as const,
},
];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Check file was written
const content = await fs.readFile(`/projects/${projectId}/.git/ai/TODO`, 'utf8');
const savedTodos = JSON.parse(content);
expect(savedTodos).toEqual(todos);
});
it('should count active and completed tasks correctly', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
{
id: '3',
content: 'Task 3',
status: 'in_progress' as const,
priority: 'low' as const,
},
];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(2);
expect(completed.length).toBe(1);
});
it('should handle cancelled tasks', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'cancelled' as const,
priority: 'low' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(0);
expect(completed.length).toBe(1);
});
it('should handle empty todo list', async () => {
const todos: Array<{ id: string; content: string; status: 'pending' | 'in_progress' | 'completed' | 'cancelled'; priority: 'high' | 'medium' | 'low' }> = [];
const result = await tool.execute({ todos });
// Result should be JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should create .git/ai directory if it does not exist', async () => {
const todos = [
{
id: '1',
content: 'Test task',
status: 'pending' as const,
priority: 'medium' as const,
},
];
await tool.execute({ todos });
// Verify directory was created
const stat = await fs.stat(`/projects/${projectId}/.git/ai`);
expect(stat.isDirectory()).toBe(true);
});
});
+231
View File
@@ -0,0 +1,231 @@
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { join } from "path-browserify";
export interface TodoInfo {
content: string;
status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
priority: 'high' | 'medium' | 'low';
id: string;
}
const TodoSchema = z.object({
content: z.string().describe("Brief description of the task"),
status: z.enum(['pending', 'in_progress', 'completed', 'cancelled']).describe("Current status of the task: pending, in_progress, completed, cancelled"),
priority: z.enum(['high', 'medium', 'low']).describe("Priority level of the task: high, medium, low"),
id: z.string().describe("Unique identifier for the todo item"),
});
interface TodoWriteParams {
todos: TodoInfo[];
}
export class TodoWriteTool implements Tool<TodoWriteParams> {
private fs: JSRuntimeFS;
private projectId: string;
readonly description = `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
It also helps the user understand the progress of the task and overall progress of their requests.
## When to Use This Tool
Use this tool proactively in these scenarios:
1. Complex multistep tasks - When a task requires 3 or more distinct steps or actions
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
3. User explicitly requests todo list - When the user directly asks you to use the todo list
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
5. After receiving new instructions - Immediately capture user requirements as todos. Feel free to edit the todo list based on new information.
6. After completing a task - Mark it complete and add any new follow-up tasks
7. When you start working on a new task, mark the todo as in_progress. Ideally you should only have one todo as in_progress at a time. Complete existing tasks before starting new ones.
## When NOT to Use This Tool
Skip using this tool when:
1. There is only a single, straightforward task
2. The task is trivial and tracking it provides no organizational benefit
3. The task can be completed in less than 3 trivial steps
4. The task is purely conversational or informational
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
## Examples of When to Use the Todo List
<example>
User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
*Creates todo list with the following items:*
1. Create dark mode toggle component in Settings page
2. Add dark mode state management (context/store)
3. Implement CSS-in-JS styles for dark theme
4. Update existing components to support theme switching
5. Run tests and build process, addressing any failures or errors that occur
*Begins working on the first task*
<reasoning>
The assistant used the todo list because:
1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
2. The user explicitly requested tests and build be run afterward
3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
</reasoning>
</example>
<example>
User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
*Uses grep or search tools to locate all instances of getCwd in the codebase*
Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
*Creates todo list with specific items for each file that needs updating*
<reasoning>
The assistant used the todo list because:
1. First, the assistant searched to understand the scope of the task
2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
3. The todo list helps ensure every instance is tracked and updated systematically
4. This approach prevents missing any occurrences and maintains code consistency
</reasoning>
</example>
<example>
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
Assistant: I'll help implement these features. First, let's add all the features to the todo list.
*Creates a todo list breaking down each feature into specific tasks based on the project architecture*
Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
<reasoning>
The assistant used the todo list because:
1. The user provided multiple complex features to implement in a comma separated list
2. The todo list helps organize these large features into manageable tasks
3. This approach allows for tracking progress across the entire implementation
</reasoning>
</example>
<example>
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
*Reviews component structure, render patterns, state management, and data fetching*
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
<reasoning>
The assistant used the todo list because:
1. First, the assistant examined the codebase to identify specific performance issues
2. Based on this analysis, it identified multiple optimization opportunities
3. Performance optimization is a non-trivial task requiring multiple steps
4. The todo list helps methodically track improvements across different components
5. This systematic approach ensures all performance bottlenecks are addressed
</reasoning>
</example>
## Examples of When NOT to Use the Todo List
<example>
User: How do I print 'Hello World' in Python?
Assistant: In Python, you can print "Hello World" with this simple code:
python
print("Hello World")
This will output the text "Hello World" to the console when executed.</assistant>
<reasoning>
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
</reasoning>
</example>
<example>
User: What does the git status command do?
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
<reasoning>
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
</reasoning>
</example>
<example>
User: Can you add a comment to the calculateTotal function to explain what it does?
Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
* Uses the Edit tool to add a comment to the calculateTotal function *
<reasoning>
The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
</reasoning>
</example>
<example>
User: Run npm install for me and tell me what happens.
Assistant: I'll run the npm install command for you.
*Executes: npm install*
The command completed successfully. Here's the output:
[Output of npm install command]
All dependencies have been installed according to your package.json file.
<reasoning>
The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
</reasoning>
</example>
## Task States and Management
1. **Task States**: Use these states to track progress:
- pending: Task not yet started
- in_progress: Currently working on (limit to ONE task at a time)
- completed: Task finished successfully
- cancelled: Task no longer needed
2. **Task Management**:
- Update task status in real-time as you work
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
- Only have ONE task in_progress at any time
- Complete current tasks before starting new ones
- Cancel tasks that become irrelevant
3. **Task Breakdown**:
- Create specific, actionable items
- Break complex tasks into smaller, manageable steps
- Use clear, descriptive task names
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
`;
readonly inputSchema = z.object({
todos: z.array(TodoSchema).describe("The updated todo list"),
});
constructor(fs: JSRuntimeFS, projectId: string) {
this.fs = fs;
this.projectId = projectId;
}
async execute(args: TodoWriteParams): Promise<ToolResult> {
const { todos } = args;
try {
// Write todos to .git/ai/TODO file
const todoPath = join("/projects", this.projectId, ".git", "ai", "TODO");
const aiDir = join("/projects", this.projectId, ".git", "ai");
// Ensure .git/ai directory exists
try {
await this.fs.stat(aiDir);
} catch {
await this.fs.mkdir(aiDir, { recursive: true });
}
// Write todos as JSON
const content = JSON.stringify(todos, null, 2) + "\n";
await this.fs.writeFile(todoPath, content);
return {
content: JSON.stringify(todos, null, 2),
};
} catch (error) {
throw new Error(`Failed to write todos: ${String(error)}`);
}
}
}
+198
View File
@@ -0,0 +1,198 @@
import { describe, it, expect } from 'vitest';
import { z } from 'zod';
import { toolToOpenAI } from './openai-adapter';
import { Tool } from './Tool';
import type OpenAI from 'openai';
describe('openai-adapter', () => {
describe('toolToOpenAI', () => {
it('should convert a simple string parameter tool', () => {
const tool: Tool<{ message: string }> = {
description: 'Test tool',
inputSchema: z.object({
message: z.string().describe('A test message'),
}),
async execute() {
return { content: 'test' };
},
};
const result = toolToOpenAI('test_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.type).toBe('function');
expect(result.function.name).toBe('test_tool');
expect(result.function.description).toBe('Test tool');
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
message: {
type: 'string',
description: 'A test message',
},
},
required: ['message'],
});
});
it('should convert nested object parameters', () => {
const tool: Tool<{ user: { name: string; age: number } }> = {
description: 'User tool',
inputSchema: z.object({
user: z.object({
name: z.string().describe('User name'),
age: z.number().describe('User age'),
}).describe('User information'),
}),
async execute() {
return { content: 'test' };
},
};
const result = toolToOpenAI('user_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
user: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'User name',
},
age: {
type: 'number',
description: 'User age',
},
},
required: ['name', 'age'],
description: 'User information',
},
},
required: ['user'],
});
});
it('should convert array of objects parameters', () => {
const tool: Tool<{ todos: Array<{ id: string; content: string; status: string }> }> = {
description: 'Todo tool',
inputSchema: z.object({
todos: z.array(
z.object({
id: z.string().describe('Todo ID'),
content: z.string().describe('Todo content'),
status: z.enum(['pending', 'completed']).describe('Todo status'),
})
).describe('List of todos'),
}),
async execute() {
return { content: 'test' };
},
};
const result = toolToOpenAI('todo_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
todos: {
type: 'array',
items: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'Todo ID',
},
content: {
type: 'string',
description: 'Todo content',
},
status: {
type: 'string',
enum: ['pending', 'completed'],
description: 'Todo status',
},
},
required: ['id', 'content', 'status'],
},
description: 'List of todos',
},
},
required: ['todos'],
});
});
it('should handle optional parameters', () => {
const tool: Tool<{ required: string; optional?: string }> = {
description: 'Test tool',
inputSchema: z.object({
required: z.string().describe('Required param'),
optional: z.string().optional().describe('Optional param'),
}),
async execute() {
return { content: 'test' };
},
};
const result = toolToOpenAI('test_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
required: {
type: 'string',
description: 'Required param',
},
optional: {
type: 'string',
description: 'Optional param',
},
},
required: ['required'],
});
});
it('should handle tools without input schema', () => {
const tool: Tool<Record<string, never>> = {
description: 'No params tool',
async execute() {
return { content: 'test' };
},
};
const result = toolToOpenAI('no_params_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toEqual({
type: 'object',
properties: {},
});
});
it('should convert enum parameters', () => {
const tool: Tool<{ priority: 'high' | 'medium' | 'low' }> = {
description: 'Priority tool',
inputSchema: z.object({
priority: z.enum(['high', 'medium', 'low']).describe('Priority level'),
}),
async execute() {
return { content: 'test' };
},
};
const result = toolToOpenAI('priority_tool', tool) as OpenAI.Chat.Completions.ChatCompletionTool & { type: 'function' };
expect(result.function.parameters).toEqual({
type: 'object',
properties: {
priority: {
type: 'string',
enum: ['high', 'medium', 'low'],
description: 'Priority level',
},
},
required: ['priority'],
});
});
});
});
+41 -2
View File
@@ -71,6 +71,8 @@ function convertZodField(field: unknown): Record<string, unknown> {
checks?: Array<{ kind: string; value: unknown }>;
innerType?: unknown;
type?: unknown;
shape?: () => Record<string, unknown>;
values?: unknown[];
}
};
@@ -93,14 +95,51 @@ function convertZodField(field: unknown): Record<string, unknown> {
type: 'boolean',
description: fieldObj._def?.description
};
case 'ZodOptional':
return convertZodField(fieldObj._def?.innerType);
case 'ZodOptional': {
const innerSchema = convertZodField(fieldObj._def?.innerType);
// Preserve description from ZodOptional if it exists
if (fieldObj._def?.description && !innerSchema.description) {
innerSchema.description = fieldObj._def.description;
}
return innerSchema;
}
case 'ZodArray':
return {
type: 'array',
items: convertZodField(fieldObj._def?.type),
description: fieldObj._def?.description
};
case 'ZodObject': {
const properties: Record<string, unknown> = {};
const required: string[] = [];
const shape = fieldObj._def?.shape?.();
if (shape) {
for (const [key, value] of Object.entries(shape)) {
const fieldSchema = value as { _def?: { typeName?: string } };
properties[key] = convertZodField(fieldSchema);
if (!fieldSchema._def?.typeName?.includes('Optional')) {
required.push(key);
}
}
}
return {
type: 'object',
properties,
required: required.length > 0 ? required : undefined,
description: fieldObj._def?.description
};
}
case 'ZodEnum': {
const values = fieldObj._def?.values as string[] | undefined;
return {
type: 'string',
enum: values || [],
description: fieldObj._def?.description
};
}
default:
return {
type: 'string',