pulse-coder-engine 0.0.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/examples/new-engine-usage.ts +52 -0
- package/package.json +54 -0
- package/src/Engine.ts +150 -0
- package/src/ai/index.ts +116 -0
- package/src/built-in/index.ts +27 -0
- package/src/built-in/mcp-plugin/index.ts +104 -0
- package/src/built-in/skills-plugin/index.ts +223 -0
- package/src/built-in/sub-agent-plugin/index.ts +203 -0
- package/src/config/index.ts +35 -0
- package/src/context/index.ts +134 -0
- package/src/core/loop.ts +147 -0
- package/src/index.ts +17 -0
- package/src/plugin/EnginePlugin.ts +60 -0
- package/src/plugin/PluginManager.ts +426 -0
- package/src/plugin/UserConfigPlugin.ts +183 -0
- package/src/prompt/index.ts +1 -0
- package/src/prompt/system.ts +126 -0
- package/src/shared/types.ts +50 -0
- package/src/tools/bash.ts +59 -0
- package/src/tools/clarify.ts +74 -0
- package/src/tools/edit.ts +79 -0
- package/src/tools/grep.ts +148 -0
- package/src/tools/index.ts +44 -0
- package/src/tools/ls.ts +20 -0
- package/src/tools/read.ts +69 -0
- package/src/tools/tavily.ts +55 -0
- package/src/tools/utils.ts +16 -0
- package/src/tools/write.ts +42 -0
- package/tsconfig.json +9 -0
- package/tsup.config.ts +11 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 用户配置插件接口 - 面向终端用户
|
|
5
|
+
* 使用声明式配置扩展引擎能力
|
|
6
|
+
*/
|
|
7
|
+
export interface UserConfigPlugin {
|
|
8
|
+
version: string;
|
|
9
|
+
name?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
|
|
12
|
+
// 工具配置 - 使用现有工具类型的具体配置
|
|
13
|
+
tools?: Record<string, ToolConfig>;
|
|
14
|
+
|
|
15
|
+
// MCP 服务器配置
|
|
16
|
+
mcp?: {
|
|
17
|
+
servers: MCPServerConfig[];
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// 提示词配置
|
|
21
|
+
prompts?: {
|
|
22
|
+
system?: string;
|
|
23
|
+
user?: string;
|
|
24
|
+
assistant?: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// 子代理配置
|
|
28
|
+
subAgents?: SubAgentConfig[];
|
|
29
|
+
|
|
30
|
+
// 技能配置 (向后兼容)
|
|
31
|
+
skills?: {
|
|
32
|
+
directories?: string[];
|
|
33
|
+
autoScan?: boolean;
|
|
34
|
+
cache?: boolean;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// 环境配置
|
|
38
|
+
env?: Record<string, string>;
|
|
39
|
+
|
|
40
|
+
// 条件配置
|
|
41
|
+
conditions?: {
|
|
42
|
+
environment?: string;
|
|
43
|
+
features?: string[];
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 工具配置接口
|
|
49
|
+
*/
|
|
50
|
+
export const ToolConfigSchema = z.object({
|
|
51
|
+
type: z.enum(['bash', 'http', 'javascript', 'skill', 'custom']),
|
|
52
|
+
|
|
53
|
+
// Bash 工具配置
|
|
54
|
+
command: z.string().optional(),
|
|
55
|
+
args: z.array(z.string()).optional(),
|
|
56
|
+
cwd: z.string().optional(),
|
|
57
|
+
env: z.any().optional(),
|
|
58
|
+
timeout: z.number().optional(),
|
|
59
|
+
|
|
60
|
+
// HTTP 工具配置
|
|
61
|
+
method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).optional(),
|
|
62
|
+
url: z.string().optional(),
|
|
63
|
+
baseUrl: z.string().optional(),
|
|
64
|
+
headers: z.any().optional(),
|
|
65
|
+
params: z.any().optional(),
|
|
66
|
+
data: z.any().optional(),
|
|
67
|
+
|
|
68
|
+
// JavaScript 工具配置
|
|
69
|
+
code: z.string().optional(),
|
|
70
|
+
|
|
71
|
+
// 通用字段
|
|
72
|
+
description: z.string().optional(),
|
|
73
|
+
enabled: z.boolean().optional().default(true),
|
|
74
|
+
|
|
75
|
+
// 条件字段
|
|
76
|
+
conditions: z.object({
|
|
77
|
+
environment: z.string().optional(),
|
|
78
|
+
platform: z.string().optional()
|
|
79
|
+
}).optional()
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export type ToolConfig = z.infer<typeof ToolConfigSchema>;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* MCP 服务器配置接口
|
|
86
|
+
*/
|
|
87
|
+
export const MCPServerConfigSchema = z.object({
|
|
88
|
+
name: z.string(),
|
|
89
|
+
command: z.string(),
|
|
90
|
+
args: z.array(z.string()).optional(),
|
|
91
|
+
env: z.any().optional(),
|
|
92
|
+
cwd: z.string().optional(),
|
|
93
|
+
timeout: z.number().optional(),
|
|
94
|
+
description: z.string().optional(),
|
|
95
|
+
enabled: z.boolean().optional().default(true)
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export type MCPServerConfig = z.infer<typeof MCPServerConfigSchema>;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 子代理配置接口
|
|
102
|
+
*/
|
|
103
|
+
export const SubAgentConfigSchema = z.object({
|
|
104
|
+
name: z.string(),
|
|
105
|
+
trigger: z.array(z.string()),
|
|
106
|
+
prompt: z.string(),
|
|
107
|
+
model: z.string().optional(),
|
|
108
|
+
temperature: z.number().optional(),
|
|
109
|
+
maxTokens: z.number().optional(),
|
|
110
|
+
tools: z.array(z.string()).optional(),
|
|
111
|
+
enabled: z.boolean().optional().default(true)
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
export type SubAgentConfig = z.infer<typeof SubAgentConfigSchema>;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 用户配置插件加载选项
|
|
118
|
+
*/
|
|
119
|
+
export interface UserConfigPluginLoadOptions {
|
|
120
|
+
configs?: UserConfigPlugin[];
|
|
121
|
+
dirs?: string[];
|
|
122
|
+
scan?: boolean;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 默认用户配置插件目录
|
|
127
|
+
*/
|
|
128
|
+
export const DEFAULT_USER_CONFIG_PLUGIN_DIRS = [
|
|
129
|
+
'.pulse-coder/config',
|
|
130
|
+
'.coder/config',
|
|
131
|
+
'~/.pulse-coder/config',
|
|
132
|
+
'~/.coder/config',
|
|
133
|
+
'./config'
|
|
134
|
+
];
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 支持的文件格式
|
|
138
|
+
*/
|
|
139
|
+
export const SUPPORTED_CONFIG_FORMATS = ['.json', '.yaml', '.yml'];
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 配置验证结果
|
|
143
|
+
*/
|
|
144
|
+
export interface ConfigValidationResult {
|
|
145
|
+
valid: boolean;
|
|
146
|
+
errors?: string[];
|
|
147
|
+
warnings?: string[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 环境变量替换工具
|
|
152
|
+
*/
|
|
153
|
+
export class ConfigVariableResolver {
|
|
154
|
+
private env: Record<string, string>;
|
|
155
|
+
|
|
156
|
+
constructor(env: Record<string, string> = {}) {
|
|
157
|
+
this.env = env;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
resolve(value: string): string {
|
|
161
|
+
return value.replace(/\$\{([^}]+)\}/g, (match, varName) => {
|
|
162
|
+
const [name, defaultValue] = varName.split(':-');
|
|
163
|
+
return this.env[name] || defaultValue || match;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
resolveObject(obj: any): any {
|
|
168
|
+
if (typeof obj === 'string') {
|
|
169
|
+
return this.resolve(obj);
|
|
170
|
+
}
|
|
171
|
+
if (Array.isArray(obj)) {
|
|
172
|
+
return obj.map(item => this.resolveObject(item));
|
|
173
|
+
}
|
|
174
|
+
if (typeof obj === 'object' && obj !== null) {
|
|
175
|
+
const resolved: any = {};
|
|
176
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
177
|
+
resolved[key] = this.resolveObject(value);
|
|
178
|
+
}
|
|
179
|
+
return resolved;
|
|
180
|
+
}
|
|
181
|
+
return obj;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './system';
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
export const generateSystemPrompt = () => {
|
|
2
|
+
const basePrompt = `
|
|
3
|
+
You are Pulse Coder, the best coding agent on the planet.
|
|
4
|
+
|
|
5
|
+
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
6
|
+
|
|
7
|
+
## Editing constraints
|
|
8
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
9
|
+
- Only add comments if they are necessary to make a non-obvious block easier to understand.
|
|
10
|
+
- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).
|
|
11
|
+
|
|
12
|
+
## Skills
|
|
13
|
+
- If query matches an available skill's description or instruction [use skill], use the skill tool to get detailed instructions.
|
|
14
|
+
- You should Load a skill to get detailed instructions for a specific task. It always is a complex task that requires multiple steps.
|
|
15
|
+
- You should check the skill is complete and follow the step-by-step guidance. If the skill is not complete, you should ask the user for more information.
|
|
16
|
+
|
|
17
|
+
## Tool usage
|
|
18
|
+
- Prefer specialized tools over shell for file operations:
|
|
19
|
+
- Use Read to view files, Edit to modify files, and Write only when needed.
|
|
20
|
+
- Use Glob to find files by name and Grep to search file contents.
|
|
21
|
+
- Use Bash for terminal operations (git, bun, builds, tests, running scripts).
|
|
22
|
+
- Run tool calls in parallel when neither call needs the other’s output; otherwise run sequentially.
|
|
23
|
+
|
|
24
|
+
## Git and workspace hygiene
|
|
25
|
+
- You may be in a dirty git worktree.
|
|
26
|
+
* NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
|
|
27
|
+
* If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
|
|
28
|
+
* If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
|
|
29
|
+
* If the changes are in unrelated files, just ignore them and don't revert them.
|
|
30
|
+
- Do not amend commits unless explicitly requested.
|
|
31
|
+
- **NEVER** use destructive commands like \`git reset --hard\` or \`git checkout--\` unless specifically requested or approved by the user.
|
|
32
|
+
|
|
33
|
+
## Frontend tasks
|
|
34
|
+
When doing frontend design tasks, avoid collapsing into bland, generic layouts.
|
|
35
|
+
Aim for interfaces that feel intentional and deliberate.
|
|
36
|
+
- Typography: Use expressive, purposeful fonts and avoid default stacks (Inter, Roboto, Arial, system).
|
|
37
|
+
- Color & Look: Choose a clear visual direction; define CSS variables; avoid purple-on-white defaults. No purple bias or dark mode bias.
|
|
38
|
+
- Motion: Use a few meaningful animations (page-load, staggered reveals) instead of generic micro-motions.
|
|
39
|
+
- Background: Don't rely on flat, single-color backgrounds; use gradients, shapes, or subtle patterns to build atmosphere.
|
|
40
|
+
- Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
|
|
41
|
+
- Ensure the page loads properly on both desktop and mobile.
|
|
42
|
+
|
|
43
|
+
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
|
|
44
|
+
|
|
45
|
+
## Presenting your work and final message
|
|
46
|
+
|
|
47
|
+
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
|
48
|
+
|
|
49
|
+
- Default: be very concise; friendly coding teammate tone.
|
|
50
|
+
- Default: do the work without asking questions. Treat short tasks as sufficient direction; infer missing details by reading the codebase and following existing conventions.
|
|
51
|
+
- Questions: only ask when you are truly blocked after checking relevant context AND you cannot safely pick a reasonable default. This usually means one of:
|
|
52
|
+
* The request is ambiguous in a way that materially changes the result and you cannot disambiguate by reading the repo.
|
|
53
|
+
* The action is destructive/irreversible, touches production, or changes billing/security posture.
|
|
54
|
+
* You need a secret/credential/value that cannot be inferred (API key, account id, etc.).
|
|
55
|
+
- If you must ask: do all non-blocked work first, then ask exactly one targeted question, include your recommended default, and state what would change based on the answer.
|
|
56
|
+
- Never ask permission questions like "Should I proceed?" or "Do you want me to run tests?"; proceed with the most reasonable option and mention what you did.
|
|
57
|
+
|
|
58
|
+
## Clarification Tool
|
|
59
|
+
|
|
60
|
+
Use the 'clarify' tool when you genuinely need information from the user to proceed. This tool pauses execution and waits for user input.
|
|
61
|
+
|
|
62
|
+
**When to use clarify:**
|
|
63
|
+
- The request is ambiguous in a way that materially affects the implementation and cannot be resolved by reading the codebase
|
|
64
|
+
- You cannot safely infer the answer from existing code, conventions, or context
|
|
65
|
+
- You need confirmation before destructive or irreversible actions (e.g., deleting resources, modifying production data)
|
|
66
|
+
- You need specific values that cannot be guessed (API keys, account IDs, specific user choices between valid alternatives)
|
|
67
|
+
|
|
68
|
+
**When NOT to use clarify:**
|
|
69
|
+
- For trivial decisions you can make based on codebase conventions or common practices
|
|
70
|
+
- For permission questions like "Should I proceed?" (just proceed with the best option)
|
|
71
|
+
- For information that's likely in the codebase, configuration files, or documentation (read those first)
|
|
72
|
+
- Multiple times in a row - complete all non-blocked work first, then ask one clear question
|
|
73
|
+
- For choices where a reasonable default exists (use the default and mention what you chose)
|
|
74
|
+
|
|
75
|
+
**How to use clarify:**
|
|
76
|
+
- Ask ONE clear, specific question per clarification
|
|
77
|
+
- Provide context if needed to help the user understand the choice
|
|
78
|
+
- Include a recommended default answer when applicable
|
|
79
|
+
- Explain briefly what would change based on the answer
|
|
80
|
+
|
|
81
|
+
Example usage: Call clarify with a question, optional context, and optional default answer. The tool will pause and wait for the user's response.
|
|
82
|
+
- For substantial work, summarize clearly; follow final‑answer formatting.
|
|
83
|
+
- Skip heavy formatting for simple confirmations.
|
|
84
|
+
- Don't dump large files you've written; reference paths only.
|
|
85
|
+
- No "save/copy this file" - User is on the same machine.
|
|
86
|
+
- Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.
|
|
87
|
+
- For code changes:
|
|
88
|
+
* Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with "summary", just jump right in.
|
|
89
|
+
* If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.
|
|
90
|
+
* When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.
|
|
91
|
+
- The user does not command execution outputs. When asked to show the output of a command (e.g. \`git show\`), relay the important details in your answer or summarize the key lines so the user understands the result.
|
|
92
|
+
|
|
93
|
+
## Final answer structure and style guidelines
|
|
94
|
+
|
|
95
|
+
- Plain text; CLI handles styling. Use structure only when it helps scanability.
|
|
96
|
+
- Headers: optional; short Title Case (1-3 words) wrapped in **…**; no blank line before the first bullet; add only if they truly help.
|
|
97
|
+
- Bullets: use - ; merge related points; keep to one line when possible; 4–6 per list ordered by importance; keep phrasing consistent.
|
|
98
|
+
- Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.
|
|
99
|
+
- Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible.
|
|
100
|
+
- Structure: group related bullets; order sections general → specific → supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.
|
|
101
|
+
- Tone: collaborative, concise, factual; present tense, active voice; self‑contained; no "above/below"; parallel wording.
|
|
102
|
+
- Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short—wrap/reformat if long; avoid naming formatting styles in answers.
|
|
103
|
+
- Adaptation: code explanations → precise, structured with code refs; simple tasks → lead with outcome; big changes → logical walkthrough + rationale + next actions; casual one-offs → plain sentences, no headers/bullets.
|
|
104
|
+
- File References: When referencing files in your response follow the below rules:
|
|
105
|
+
* Use inline code to make file paths clickable.
|
|
106
|
+
* Each reference should have a stand alone path. Even if it's the same file.
|
|
107
|
+
* Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
|
|
108
|
+
* Optionally include line/column (1‑based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
|
|
109
|
+
* Do not use URIs like file://, vscode://, or https://.
|
|
110
|
+
* Do not provide range of lines
|
|
111
|
+
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
|
|
112
|
+
|
|
113
|
+
Here is some useful information about the environment you are running in:
|
|
114
|
+
<env>
|
|
115
|
+
Working directory: ${process.cwd()}
|
|
116
|
+
Platform: darwin
|
|
117
|
+
Today's date: ${new Date().toLocaleDateString()}
|
|
118
|
+
</env>
|
|
119
|
+
<files>
|
|
120
|
+
|
|
121
|
+
</files>`;
|
|
122
|
+
|
|
123
|
+
return basePrompt;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
export default generateSystemPrompt;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { FlexibleSchema, ModelMessage } from "ai";
|
|
2
|
+
|
|
3
|
+
export interface ClarificationRequest {
|
|
4
|
+
id: string;
|
|
5
|
+
question: string;
|
|
6
|
+
context?: string;
|
|
7
|
+
defaultAnswer?: string;
|
|
8
|
+
timeout: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ToolExecutionContext {
|
|
12
|
+
onClarificationRequest?: (request: ClarificationRequest) => Promise<string>;
|
|
13
|
+
abortSignal?: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface Tool<Input = any, Output = any> {
|
|
17
|
+
name: string;
|
|
18
|
+
description: string;
|
|
19
|
+
inputSchema: FlexibleSchema<Input>;
|
|
20
|
+
execute: (input: Input, context?: ToolExecutionContext) => Promise<Output>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Context {
|
|
24
|
+
messages: ModelMessage[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface IPlugin {
|
|
28
|
+
name: string;
|
|
29
|
+
version: string;
|
|
30
|
+
extensions: Extension[];
|
|
31
|
+
activate(context: IExtensionContext): Promise<void>;
|
|
32
|
+
deactivate?(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface Extension {
|
|
36
|
+
type: 'skill' | 'mcp' | 'tool' | 'context';
|
|
37
|
+
provider: any;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface IExtensionContext {
|
|
41
|
+
registerTools(toolName: string, tool: Tool<any, any>): void;
|
|
42
|
+
logger: ILogger;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ILogger {
|
|
46
|
+
debug(message: string, meta?: Record<string, unknown>): void;
|
|
47
|
+
info(message: string, meta?: Record<string, unknown>): void;
|
|
48
|
+
warn(message: string, meta?: Record<string, unknown>): void;
|
|
49
|
+
error(message: string, error?: Error, meta?: Record<string, unknown>): void;
|
|
50
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import z from "zod";
|
|
2
|
+
import { execSync } from "child_process";
|
|
3
|
+
import type { Tool } from "../shared/types";
|
|
4
|
+
import { truncateOutput } from "./utils";
|
|
5
|
+
|
|
6
|
+
export const BashTool: Tool<
|
|
7
|
+
{ command: string; timeout?: number; cwd?: string; description?: string },
|
|
8
|
+
{ output: string; error?: string; exitCode?: number }
|
|
9
|
+
> = {
|
|
10
|
+
name: 'bash',
|
|
11
|
+
description: 'Execute a bash command and return the output. Supports timeout and working directory configuration.',
|
|
12
|
+
inputSchema: z.object({
|
|
13
|
+
command: z.string().describe('The bash command to execute'),
|
|
14
|
+
timeout: z.number().optional().describe('Optional timeout in milliseconds (max 600000ms / 10 minutes). Defaults to 120000ms (2 minutes).'),
|
|
15
|
+
cwd: z.string().optional().describe('Optional working directory for command execution. Defaults to current directory.'),
|
|
16
|
+
description: z.string().optional().describe('Optional description of what this command does (for logging/debugging)'),
|
|
17
|
+
}),
|
|
18
|
+
execute: async ({ command, timeout = 120000, cwd, description }) => {
|
|
19
|
+
// Validate timeout
|
|
20
|
+
if (timeout && (timeout < 0 || timeout > 600000)) {
|
|
21
|
+
throw new Error('Timeout must be between 0 and 600000ms (10 minutes)');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
const output = execSync(command, {
|
|
26
|
+
encoding: 'utf-8',
|
|
27
|
+
maxBuffer: 1024 * 1024 * 10, // 10MB
|
|
28
|
+
timeout: timeout || 120000,
|
|
29
|
+
cwd: cwd || process.cwd(),
|
|
30
|
+
shell: '/bin/bash',
|
|
31
|
+
});
|
|
32
|
+
return {
|
|
33
|
+
output: truncateOutput(output || '(command completed with no output)'),
|
|
34
|
+
exitCode: 0,
|
|
35
|
+
};
|
|
36
|
+
} catch (error: any) {
|
|
37
|
+
const exitCode = error.status || error.code || 1;
|
|
38
|
+
const stdout = String(error.stdout || '');
|
|
39
|
+
const stderr = String(error.stderr || error.message || '');
|
|
40
|
+
|
|
41
|
+
// Check if it's a timeout error
|
|
42
|
+
if (error.killed && error.signal === 'SIGTERM') {
|
|
43
|
+
return {
|
|
44
|
+
output: truncateOutput(stdout),
|
|
45
|
+
error: truncateOutput(`Command timed out after ${timeout}ms\n${stderr}`),
|
|
46
|
+
exitCode,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
output: truncateOutput(stdout),
|
|
52
|
+
error: truncateOutput(stderr),
|
|
53
|
+
exitCode,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export default BashTool;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import z from "zod";
|
|
2
|
+
import type { Tool, ToolExecutionContext } from "../shared/types";
|
|
3
|
+
import { CLARIFICATION_TIMEOUT } from "../config/index.js";
|
|
4
|
+
import { randomUUID } from "crypto";
|
|
5
|
+
|
|
6
|
+
export interface ClarifyInput {
|
|
7
|
+
question: string;
|
|
8
|
+
context?: string;
|
|
9
|
+
defaultAnswer?: string;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ClarifyOutput {
|
|
14
|
+
answer: string;
|
|
15
|
+
timedOut: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const ClarifyTool: Tool<ClarifyInput, ClarifyOutput> = {
|
|
19
|
+
name: 'clarify',
|
|
20
|
+
description: 'Ask the user a clarifying question and wait for their response. Use this when you need information from the user to proceed with the task.',
|
|
21
|
+
inputSchema: z.object({
|
|
22
|
+
question: z.string().describe('The question to ask the user'),
|
|
23
|
+
context: z.string().optional().describe('Additional context to help the user answer'),
|
|
24
|
+
defaultAnswer: z.string().optional().describe('Default answer if user does not respond within timeout'),
|
|
25
|
+
timeout: z.number().optional().describe('Timeout in milliseconds (default: 5 minutes)')
|
|
26
|
+
}),
|
|
27
|
+
execute: async (input, toolContext) => {
|
|
28
|
+
if (!toolContext?.onClarificationRequest) {
|
|
29
|
+
throw new Error('Clarification is not supported in this context. The clarify tool requires a CLI interface with user interaction.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const timeout = input.timeout ?? CLARIFICATION_TIMEOUT;
|
|
33
|
+
const requestId = randomUUID();
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
// Create a promise that rejects on timeout
|
|
37
|
+
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
38
|
+
setTimeout(() => {
|
|
39
|
+
reject(new Error(`Clarification request timed out after ${timeout}ms`));
|
|
40
|
+
}, timeout);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Race between user response and timeout
|
|
44
|
+
const answer = await Promise.race([
|
|
45
|
+
toolContext.onClarificationRequest({
|
|
46
|
+
id: requestId,
|
|
47
|
+
question: input.question,
|
|
48
|
+
context: input.context,
|
|
49
|
+
defaultAnswer: input.defaultAnswer,
|
|
50
|
+
timeout
|
|
51
|
+
}),
|
|
52
|
+
timeoutPromise
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
answer,
|
|
57
|
+
timedOut: false
|
|
58
|
+
};
|
|
59
|
+
} catch (error: any) {
|
|
60
|
+
// If timeout occurred and we have a default answer, use it
|
|
61
|
+
if (error?.message?.includes('timed out') && input.defaultAnswer) {
|
|
62
|
+
return {
|
|
63
|
+
answer: input.defaultAnswer,
|
|
64
|
+
timedOut: true
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Otherwise, re-throw the error
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export default ClarifyTool;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import z from "zod";
|
|
2
|
+
import { readFileSync, writeFileSync } from "fs";
|
|
3
|
+
import type { Tool } from "../shared/types";
|
|
4
|
+
import { truncateOutput } from "./utils";
|
|
5
|
+
|
|
6
|
+
export const EditTool: Tool<
|
|
7
|
+
{ filePath: string; oldString: string; newString: string; replaceAll?: boolean },
|
|
8
|
+
{ success: boolean; replacements: number; preview?: string }
|
|
9
|
+
> = {
|
|
10
|
+
name: 'edit',
|
|
11
|
+
description: 'Performs exact string replacements in files. Use this to edit existing files by replacing old_string with new_string.',
|
|
12
|
+
inputSchema: z.object({
|
|
13
|
+
filePath: z.string().describe('The absolute path to the file to modify'),
|
|
14
|
+
oldString: z.string().describe('The exact text to replace (must match exactly)'),
|
|
15
|
+
newString: z.string().describe('The text to replace it with (must be different from old_string)'),
|
|
16
|
+
replaceAll: z.boolean().optional().default(false).describe('Replace all occurrences of old_string (default false)'),
|
|
17
|
+
}),
|
|
18
|
+
execute: async ({ filePath, oldString, newString, replaceAll = false }) => {
|
|
19
|
+
// Validate that old and new strings are different
|
|
20
|
+
if (oldString === newString) {
|
|
21
|
+
throw new Error('old_string and new_string must be different');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Read the file
|
|
25
|
+
const content = readFileSync(filePath, 'utf-8');
|
|
26
|
+
|
|
27
|
+
// Check if oldString exists in the file
|
|
28
|
+
if (!content.includes(oldString)) {
|
|
29
|
+
throw new Error(`old_string not found in file: ${filePath}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
let newContent: string;
|
|
33
|
+
let replacements = 0;
|
|
34
|
+
|
|
35
|
+
if (replaceAll) {
|
|
36
|
+
// Replace all occurrences
|
|
37
|
+
const parts = content.split(oldString);
|
|
38
|
+
replacements = parts.length - 1;
|
|
39
|
+
newContent = parts.join(newString);
|
|
40
|
+
} else {
|
|
41
|
+
// Replace only the first occurrence
|
|
42
|
+
const index = content.indexOf(oldString);
|
|
43
|
+
if (index === -1) {
|
|
44
|
+
throw new Error(`old_string not found in file: ${filePath}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Check if the string is unique (appears only once)
|
|
48
|
+
const secondIndex = content.indexOf(oldString, index + oldString.length);
|
|
49
|
+
if (secondIndex !== -1) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
'old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance.'
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
newContent = content.slice(0, index) + newString + content.slice(index + oldString.length);
|
|
56
|
+
replacements = 1;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Write the modified content back
|
|
60
|
+
writeFileSync(filePath, newContent, 'utf-8');
|
|
61
|
+
|
|
62
|
+
// Generate a preview of the changes (show the changed section with context)
|
|
63
|
+
const changedIndex = newContent.indexOf(newString);
|
|
64
|
+
const contextLength = 200;
|
|
65
|
+
const start = Math.max(0, changedIndex - contextLength);
|
|
66
|
+
const end = Math.min(newContent.length, changedIndex + newString.length + contextLength);
|
|
67
|
+
const preview = truncateOutput(
|
|
68
|
+
`...${newContent.slice(start, end)}...`
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
success: true,
|
|
73
|
+
replacements,
|
|
74
|
+
preview,
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export default EditTool;
|