Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
294 lines (271 loc) · 9.26 KB
/
Copy pathindex.ts
File metadata and controls
294 lines (271 loc) · 9.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// biome-ignore assist/source/organizeImports: dotenv needs imported first
import "dotenv/config";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
// import { ChatOpenAI } from "@langchain/openai";
import { ChatOllama } from "@langchain/ollama";
import {
AIMessage,
SystemMessage,
HumanMessage,
ToolMessage,
type BaseMessageLike,
} from "@langchain/core/messages";
import inquirer from "inquirer";
import { createTools } from "./tools";
import { resolve } from "node:path";
// Parse command-line arguments
const args = process.argv.slice(2);
const workingDirectory = args[0] ? resolve(args[0]) : process.cwd();
console.log(`🔒 Working directory: ${workingDirectory}`);
console.log("Agent can only access files within this directory.\n");
// const model = new ChatGoogleGenerativeAI({
// model: "gemini-flash-lite-latest",
// maxOutputTokens: 2048,
// apiKey: process.env.GOOGLE_API_KEY,
// });
// const model = new ChatOpenAI({
// model: "gemini-flash-lite-latest",
// maxOutputTokens: 2048,
// apiKey: process.env.OPEN_ROUTER_API_KEY,
// });
const model = new ChatOllama({
model: "qwen3:8b",
temperature: 0,
think: false,
});
// Create tools with the specified working directory and model
const tools = createTools(workingDirectory, model);
const streamAndAccumulateChunks = async (
stream: Awaited<ReturnType<typeof model.stream>>,
showThoughts = false,
) => {
const chunks = [];
enum StreamType {
thought = "thought",
response = "response",
none = "none",
}
const streamState = {
currentStreamType: StreamType.thought,
lastStreamType: StreamType.none,
};
const setCurrentStreamType = (type: StreamType) => {
streamState.lastStreamType = streamState.currentStreamType;
streamState.currentStreamType = type;
};
for await (const chunk of stream) {
if (
streamState.currentStreamType !== streamState.lastStreamType &&
showThoughts
) {
if (streamState.currentStreamType === StreamType.thought)
console.log("\n### THOUGHT ###\n");
}
if (chunk.content?.length) setCurrentStreamType(StreamType.response);
if (chunk.additional_kwargs.reasoning_content)
setCurrentStreamType(StreamType.thought);
if (chunk.additional_kwargs.reasoning_content && showThoughts) {
process.stdout.write(String(chunk.additional_kwargs.reasoning_content));
}
if (
streamState.currentStreamType !== streamState.lastStreamType &&
showThoughts
) {
if (streamState.currentStreamType === StreamType.response)
console.log("\n###############\n");
}
process.stdout.write(chunk.content.toString());
chunks.push(chunk);
}
console.log("\n\n");
const accumulated = chunks.reduce((acc, chunk) => {
if (chunk.additional_kwargs.reasoning_content) {
acc.additional_kwargs.reasoning_content =
(acc.additional_kwargs.reasoning_content as string) +
chunk.additional_kwargs.reasoning_content;
}
if (chunk.content) {
acc.content = acc.content.toString() + chunk.content.toString();
}
if (chunk.tool_calls) {
acc.tool_calls?.push(...chunk.tool_calls);
}
return acc;
});
return accumulated;
};
const chatHistory: BaseMessageLike[] = [
new SystemMessage(
`You are a skilled coding assistant capable of:
1. Analyzing entire codebases by studying file structures and code patterns
2. Performing precise code modifications using file system operations
3. Maintaining code quality through best practices and documentation
4. Break a problem down into step-by-step execution plan
Your capabilities include:
- Understanding code architecture and component relationships
- Identifying technical debt and opportunities for improvement
- Executing refactoring, bug fixes, and feature implementations
- Collaborating with developers through structured prompts
When operating on a codebase, you will:
1. Use the 'listFiles' tool to understand directory structures
2. Employ 'readFile' to study existing code implementations
3. Modify files using 'writeFile' for code changes
4. Use 'promptTool' for clarification when needed
5. Leverage the calculator tool for arithmetic operations in code
Always:
- Verify file paths before performing operations
- Maintain code readability and documentation
- Handle edge cases in file operations
- Ask for confirmation when making significant changes
- Provide clear explanations of your modifications
You are currently working on the code base at ${workingDirectory}.
When given a result of think tool, follow its instruction closely, using other tools at each step specified.
`,
),
];
const toolsMap = new Map(tools.map((t) => [t.name, t]));
// Define tools that require user approval before execution
const SENSITIVE_TOOLS = new Set([
"writeFile",
"bash",
// Add more sensitive tools here as needed
]);
const generateThoughts = async ({
userPrompt,
chatHistory,
}: {
userPrompt: string;
chatHistory: BaseMessageLike[];
}) => {
const conversation = chatHistory
.slice(0, chatHistory.length - 1)
.map((message) => {
const role = message.type === "tool" ? `${message.type} (${message.name})` : message.type;
return `${role} >>>>: ${(message as any).content}`;
})
.join("\n");
const systemPrompt = `You are a thought generator for an agent. Given the user's prompt, respond with your thought about how to resolve the user's request.
You have access to the following tools: ${JSON.stringify(tools.map((tool) => ({ name: tool.name, description: tool.description, input: tool.schema.toJSONSchema() })))}.
Respond by providing a step-by-step guide on how to perform the task, explicitly stating any tool that should be used at each step. DO NOT give your final solution, focus on how to get there only.
Here is the conversation so far:
--- START
${conversation}
--- END
`;
const stream = await model.stream([
new SystemMessage(systemPrompt),
new HumanMessage(
`The user said: "${userPrompt}". How should we approach this?`,
),
]);
console.log("🧠🧠🧠 Thoughts 🧠🧠🧠");
const thoughtMessage = await streamAndAccumulateChunks(stream);
console.log("🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠");
return `Bellow are an expert's thoughts about how to perform this task. Follow instruction one step at a time: \n${thoughtMessage.content}`;
};
while (true) {
const { userPrompt } = await inquirer.prompt([
{
type: "input",
name: "userPrompt",
message: ">",
},
]);
chatHistory.push(new HumanMessage(userPrompt));
const thinkingToolId = crypto.randomUUID();
chatHistory.push(
...[
new AIMessage({
tool_calls: [
{
id: thinkingToolId,
name: "think",
args: { userPrompt },
type: "tool_call",
},
],
}),
new ToolMessage({
tool_call_id: thinkingToolId,
content: await generateThoughts({ userPrompt, chatHistory }),
}),
],
);
const response = await model.stream(chatHistory, { tools });
const accumulated = await streamAndAccumulateChunks(response);
chatHistory.push(accumulated);
while ((chatHistory.at(-1) as AIMessage).tool_calls?.length) {
const lastMessage = chatHistory.at(-1) as AIMessage;
// Check if any of the tool calls are sensitive
const sensitiveToolCalls =
lastMessage.tool_calls?.filter((toolCall) =>
SENSITIVE_TOOLS.has(toolCall.name),
) ?? [];
const hasSensitiveTools = sensitiveToolCalls.length > 0;
// Display tool calls
console.log("===========");
console.log("📋 Tool calls requested:");
for (const toolCall of lastMessage.tool_calls || []) {
const isSensitive = SENSITIVE_TOOLS.has(toolCall.name);
const prefix = isSensitive ? "🔒" : " ";
console.log(
`${prefix} - ${toolCall.name}(${JSON.stringify(toolCall.args)})`,
);
}
// Only ask for approval if there are sensitive tools
const approved = await (async () => {
if (hasSensitiveTools) {
return (
await inquirer.prompt([
{
type: "confirm",
name: "approved",
message: `Do you approve these ${sensitiveToolCalls.length} sensitive tool call(s)?`,
default: true,
},
])
).approved;
}
console.log("✅ Auto-approved (no sensitive tools). Executing...\n");
return true;
})();
if (!approved) {
console.log("❌ Tool calls rejected by user.\n");
// Create tool call result messages for each rejected tool call
const rejectionMessages =
lastMessage.tool_calls?.map(
(toolCall) =>
new ToolMessage({
content:
"Tool call rejected by user. Please ask the user what they would like you to do instead.",
tool_call_id: toolCall.id || "",
}),
) ?? [];
chatHistory.push(...rejectionMessages);
} else {
if (hasSensitiveTools) {
console.log("✅ Tool calls approved. Executing...\n");
}
const toolcallMessages = (
await Promise.allSettled(
lastMessage.tool_calls?.map(async (toolCall) => {
console.log(
`#toolcall: ${toolCall.name} ${JSON.stringify(toolCall.args)}`,
);
const tool = toolsMap.get(toolCall.name);
const result = tool
? await (tool.invoke as any)(toolCall)
: undefined;
console.log(`#result: ${JSON.stringify(result.content)}`);
console.log("===========")
return result;
}) ?? [],
)
).map((r) => (r.status === "fulfilled" ? r.value : r.reason));
chatHistory.push(...toolcallMessages);
}
const response = await model.stream(chatHistory, { tools });
const accumulated = await streamAndAccumulateChunks(response);
chatHistory.push(accumulated);
}
}