Skip to content

Commit 1c9e7ac

Browse files
Refactor user settings and session management; remove custom commands handling and update system prompt logic
1 parent 5944766 commit 1c9e7ac

8 files changed

Lines changed: 174 additions & 75 deletions

File tree

src/commands/settings.ts

Lines changed: 2 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import {parseArgs} from "jsr:@std/cli/parse-args"
22
import {loadUserSettings, saveUserSettings} from "../config/settings.ts"
3-
import {parseFlagForHelp, getCommandHelp} from "../utils/functions.ts"
4-
import {DEFAULT_TOOLS_CONFIG_PATH} from "../config/constants.ts"
3+
import {parseFlagForHelp} from "../utils/functions.ts"
54

65
export async function handleSettings(args: string[]): Promise<void> {
76
const settingsFlags = {
8-
string: ["set-name", "add-command", "remove-command", "set-jina-key", "set-config", "set-editor"],
7+
string: ["set-name", "set-jina-key", "set-config", "set-editor"],
98
boolean: ["list"],
10-
119
}
1210
const flags = parseArgs(args, settingsFlags)
1311

@@ -28,40 +26,6 @@ export async function handleSettings(args: string[]): Promise<void> {
2826
settings.jinaApiKey = flags["set-jina-key"]
2927
console.log("Jina API key has been set")
3028
}
31-
else if (flags["add-command"]) {
32-
const commandNameFromArg = flags["add-command"] as string
33-
let commandName = commandNameFromArg
34-
let commandDescription = ""
35-
if (commandNameFromArg.includes(",")) {
36-
const commandSplit = commandNameFromArg.split(",")
37-
commandName = commandSplit[0]
38-
commandDescription = commandSplit[1]
39-
}
40-
const helpInfo = await getCommandHelp(commandName)
41-
console.log(`Got help info for ${commandName}}`)
42-
43-
const existingCommandIndex = settings.customCommands.findIndex(cmd => cmd.name === commandName)
44-
if (existingCommandIndex >= 0) {
45-
settings.customCommands[existingCommandIndex] = {
46-
name: commandName,
47-
description: commandDescription || helpInfo.description,
48-
helpText: helpInfo.helpText,
49-
}
50-
} else {
51-
settings.customCommands.push({
52-
name: commandName,
53-
description: commandDescription || helpInfo.description,
54-
helpText: helpInfo.helpText,
55-
})
56-
}
57-
console.log(`Added command ${commandName} with help information`)
58-
}
59-
else if (flags["remove-command"]) {
60-
const commandNameFromArg = flags["remove-command"] as string
61-
const index = settings.customCommands.findIndex(cmd => cmd.name === commandNameFromArg)
62-
console.log(`Removing command ${flags["remove-command"]} at index ${index}`)
63-
if (index >= 0) settings.customCommands.splice(index, 1)
64-
}
6529
else if (flags.list) {
6630
console.log(JSON.stringify(settings, null, 2))
6731
return

src/config/constants.ts

Lines changed: 133 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,99 @@ ${isJinaAvailable() ? `
8787
- Arguments: {searchTerm: string}
8888
` : ''}
8989
90+
91+
92+
Your capabilities include:
93+
94+
1. File System Access:
95+
- Full access to read and edit files
96+
- All paths should be relative to current directory
97+
- Use './' or '.' for current directory references
98+
- Use relative paths for subdirectories
99+
100+
2. Command Execution:
101+
- Can execute shell commands in the current environment
102+
- Ensure commands are compatible with the system
103+
- Can navigate and manipulate the file system
104+
105+
3. Memory Management:
106+
- Access to system memory via /root/memory.json
107+
- Can add, retrieve, and clear memories
108+
- Use memory for context persistence
109+
110+
4. Clipboard Access:
111+
- Can read content from the system clipboard
112+
${isJinaAvailable() ? `
113+
5. Jina API Integration:
114+
- Can read and parse content from a URL
115+
- Can search content using Jina Search API
116+
- Can search with grounding using Jina Grounding API
117+
` : ''}
118+
90119
Before taking any action, follow these steps:
91120
92121
93122
Some tips:
94123
- For any non file operations, use the BASH_TOOL
95124
- If you need to locate the file, use BASH_TOOL to find the file path
96-
- EDITOR_TOOL works best when you have the exact file path to work with
125+
- EDITOR_TOOL works best when you have the exact file path to work with.
97126
- Best way to write or update a file is to use EDITOR_TOOL.
98127
- If an information is needed to be stored for future reference, use MEMORY_TOOLS.
128+
- If you need to read content from a URL, search online use JINA_TOOLS.
129+
`
130+
131+
export const SYSTEM_PROMPT_TEMPLATE = `
132+
You are a versatile assistant with full system access.
133+
You are currently operating in \${Deno.cwd()} directory.
134+
135+
You have access to following tools and capabilities:
136+
137+
- BASH_TOOL:
138+
- Name: "bash"
139+
- Description: Execute shell commands
140+
- Arguments:
141+
- command: string (required) - The shell command to execute
142+
- restart: boolean (optional) - Restart shell session if true
143+
- Example: {command: "ls -la", restart: false}
144+
145+
- EDITOR_TOOL:
146+
- Name: "str_replace_editor"
147+
- Description: File manipulation operations
148+
- Commands:
149+
- view:
150+
- path: string (required)
151+
- create:
152+
-path: string (required)
153+
- file_text: string (required)
154+
- str_replace:
155+
- path: string (required)
156+
- old_str: string (required)
157+
- new_str: string (required)
158+
- insert:
159+
- path: string (required)
160+
- insert_line: number (required)
161+
- new_str: string (required)
162+
- MEMORY_TOOLS:
163+
- Name: "add_memory"
164+
- Arguments: {content: string}
165+
- Name: "get_memories"
166+
- Arguments: none
167+
- Name: "clear_memories"
168+
- Arguments: none
169+
- CLIPBOARD_TOOLS:
170+
- Name: "read_clipboard"
171+
- Arguments: none
172+
\${isJinaAvailable() ? \`
173+
- JINA_TOOLS:
174+
- Name: "readPage"
175+
- Arguments: {url: string}
176+
- Name: "search"
177+
- Arguments: {searchTerm: string}
178+
- Name: "searchGrounding"
179+
- Arguments: {searchTerm: string}
180+
\` : ''}
99181
182+
\${additionalTools}
100183
101184
Your capabilities include:
102185
@@ -118,17 +201,26 @@ Your capabilities include:
118201
119202
4. Clipboard Access:
120203
- Can read content from the system clipboard
121-
${isJinaAvailable() ? `
204+
\${isJinaAvailable() ? \`
122205
5. Jina API Integration:
123206
- Can read and parse content from a URL
124207
- Can search content using Jina Search API
125208
- Can search with grounding using Jina Grounding API
126-
` : ''}
209+
\` : ''}
127210
128-
Always present your solution in this order:
129-
1. Understanding of the request
130-
2. Step-by-step plan
131-
3. Detailed execution of each step`
211+
Before taking any action, follow these steps:
212+
213+
Some tips:
214+
- For any non file operations, use the BASH_TOOL
215+
- If you need to locate the file, use BASH_TOOL to find the file path
216+
- EDITOR_TOOL works best when you have the exact file path to work with.
217+
- Best way to write or update a file is to use EDITOR_TOOL.
218+
- If an information is needed to be stored for future reference, use MEMORY_TOOLS.
219+
- If you need to read content from a URL, search online use JINA_TOOLS.
220+
221+
\${userContext}
222+
\${additionalInstructions ?? ''}
223+
`
132224

133225
export const API_CONFIG = {
134226
MODEL: "claude-3-5-sonnet-20241022",
@@ -230,18 +322,41 @@ export const JINA_TOOLS: Anthropic.Beta.BetaTool[] = [
230322
},
231323
]
232324

233-
// Remove ALL_TOOLS export and definition
325+
interface SchemaProperty {
326+
type: string
327+
description?: string
328+
}
234329

235-
export function getSystemContext(basePrompt: string): string {
330+
export function getSystemContext(
331+
additionalTools: Anthropic.Beta.Messages.BetaTool[] = [],
332+
additionalInstructions?: string
333+
): string {
236334
const settings = loadUserSettings()
237-
const customCommandsContext = settings.customCommands.length > 0
238-
? "\nAvailable Commands:\n" + settings.customCommands
239-
.map(cmd => `- ${cmd.name}: ${cmd.description}${cmd.helpCommand ? `\n Help: ${cmd.helpCommand}` : ''
240-
}${cmd.helpText ? `\n Flags: ${cmd.helpText}` : ''
241-
}`).join('\n')
242-
: ''
243-
244-
return `${basePrompt}
335+
336+
const toolsString = additionalTools.map(tool => {
337+
const schema = tool.input_schema as {
338+
type: string
339+
properties: Record<string, SchemaProperty>
340+
required?: string[]
341+
}
342+
return `
343+
- ${tool.name.toUpperCase()}:
344+
- Name: "${tool.name}"
345+
- Description: ${tool.description}
346+
- Arguments: ${Object.entries(schema.properties)
347+
.map(([name, prop]) => `
348+
- ${name}: ${prop.type}${schema.required?.includes(name) ? ' (required)' : ''} - ${prop.description || ''}`)
349+
.join('')}
350+
`
351+
}).join('\n')
352+
353+
const userContext = `
245354
User Context:
246-
- Name: ${settings.userName}${customCommandsContext}`
355+
- Name: ${settings.userName}
356+
`
357+
358+
return SYSTEM_PROMPT_TEMPLATE
359+
.replace('${additionalTools}', toolsString)
360+
.replace('${userContext}', userContext)
361+
.replace('${additionalInstructions ?? \'\'}', additionalInstructions ?? '')
247362
}

src/config/settings.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import {join} from "jsr:@std/path"
22
import {homedir} from "node:os"
33
import {UserSettings} from "../types/interfaces.ts"
4-
import {DEFAULT_EDITOR} from "./constants.ts"
54

65
const DEFAULT_SETTINGS: UserSettings = {
76
userName: "User",
8-
customCommands: [],
97
jinaApiKey: undefined,
108
toolConfigPath: join(homedir(), ".ComputerUseAgent", "tools.json"),
119
editorCommand: "nano"

src/modules/bash/bash_session.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {BaseSession} from "../../utils/session.ts"
22
import {BASH_SYSTEM_PROMPT, API_CONFIG, MEMORY_TOOLS} from "../../config/constants.ts"
33
import {log} from "../../config/logging.ts"
44
import {ToolHandler} from "../../utils/tool_handler.ts"
5+
import Anthropic from "anthropic";
56

67
export class BashSession extends BaseSession {
78
private toolHandler: ToolHandler
@@ -47,7 +48,7 @@ System Context:
4748
tools: [{type: "bash_20241022", name: "bash"}
4849
, ...MEMORY_TOOLS
4950
],
50-
system: this.getSystemPrompt(systemContext),
51+
system: this.getSystemPrompt(),
5152
betas: ["computer-use-2024-10-22"],
5253
})
5354

src/modules/hybrid/hybrid_session.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
import {BaseSession} from "../../utils/session.ts"
2-
import {COMBINED_SYSTEM_PROMPT, API_CONFIG} from "../../config/constants.ts"
2+
import {API_CONFIG} from "../../config/constants.ts"
33
import {log} from "../../config/logging.ts"
44
import {ToolHandler} from "../../utils/tool_handler.ts"
55
import {getConfigFileLocation} from "../../config/settings.ts"
66
import {ToolConfigManager} from "../../config/tool_config.ts"
77
import generatePlan from "../planner/planner.ts"
8+
import {ToolCall} from "../../types/interfaces.ts"
9+
import Anthropic from "anthropic"
810

911
export class HybridSession extends BaseSession {
1012
private toolHandler: ToolHandler
13+
private cachedSystemPrompt: string = ""
1114

1215
constructor(sessionId: string, noAgi = false) {
1316
super(sessionId)
@@ -26,6 +29,9 @@ export class HybridSession extends BaseSession {
2629
cwd: Deno.cwd(),
2730
}
2831

32+
// Cache the system prompt
33+
this.cachedSystemPrompt = this.getSystemPrompt(this.toolHandler.getDynamicTools())
34+
2935
// Generate execution plan
3036
const plan = await generatePlan(JSON.stringify(systemInfo), this.toolHandler.getAllTools(), prompt)
3137
log.info(`Plan: ${JSON.stringify(plan)}`)
@@ -54,7 +60,7 @@ export class HybridSession extends BaseSession {
5460
{type: "text_editor_20241022", name: "str_replace_editor"},
5561
...tools
5662
],
57-
system: this.getSystemPrompt(`${COMBINED_SYSTEM_PROMPT}\nSystem Context: ${JSON.stringify(systemInfo)}`),
63+
system: this.cachedSystemPrompt,
5864
betas: ["computer-use-2024-10-22"],
5965
})
6066

@@ -78,7 +84,7 @@ export class HybridSession extends BaseSession {
7884
break
7985
}
8086

81-
const toolResults = await this.toolHandler.processToolCalls(response.content)
87+
const toolResults = await this.toolHandler.processToolCalls(response.content as Anthropic.Beta.BetaToolUseBlock[])
8288
if (toolResults?.length) {
8389
this.messages.push({
8490
role: "user",
@@ -90,7 +96,6 @@ export class HybridSession extends BaseSession {
9096
stepError = error
9197
break
9298
}
93-
// Add tool result to step result
9499
stepResult += toolResults[0].output.content[0].text + "\n"
95100
}
96101
}
@@ -111,7 +116,7 @@ export class HybridSession extends BaseSession {
111116
}
112117

113118
this.logger.logTotalCost()
114-
await this.logInteraction('hybrid', prompt, "completed")
119+
await this.logInteraction('hybrid', `${this.cachedSystemPrompt}\n${prompt}`, "completed")
115120
} catch (error) {
116121
log.error(`Error in hybrid process: ${error instanceof Error ? error.message : String(error)}`)
117122
if (error instanceof Error && error.stack) {

src/types/interfaces.ts

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,6 @@ export interface MemoryFile {
4141

4242
export interface UserSettings {
4343
userName: string
44-
customCommands: {
45-
name: string
46-
description: string
47-
helpCommand?: string
48-
helpText?: string
49-
}[]
5044
jinaApiKey?: string
5145
toolConfigPath: string
5246
editorCommand: string
@@ -76,3 +70,18 @@ export interface PlanStep {
7670
export interface Plan {
7771
planSteps: PlanStep[]
7872
}
73+
74+
export interface FileTool {
75+
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit'
76+
path: string
77+
file_text?: string
78+
old_str?: string
79+
new_str?: string
80+
insert_line?: number
81+
view_range?: number[]
82+
}
83+
84+
export interface BashTools {
85+
command?: string
86+
restart?: boolean
87+
}

src/utils/session.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {Anthropic} from 'anthropic'
1+
import Anthropic from "anthropic"
22
import {format} from "jsr:@std/datetime"
33
import {crypto} from "jsr:@std/crypto"
44
import {log} from "../config/logging.ts"
@@ -94,7 +94,10 @@ export class BaseSession {
9494
})
9595
}
9696

97-
protected getSystemPrompt(basePrompt: string): string {
98-
return getSystemContext(basePrompt)
97+
protected getSystemPrompt(
98+
additionalTools: Anthropic.Beta.Messages.BetaTool[] = [],
99+
additionalInstructions?: string
100+
): string {
101+
return getSystemContext(additionalTools, additionalInstructions)
99102
}
100103
}

0 commit comments

Comments
 (0)