-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy pathcodebuff-client.ts
More file actions
211 lines (185 loc) · 5.49 KB
/
codebuff-client.ts
File metadata and controls
211 lines (185 loc) · 5.49 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
import { getCliEnv } from './env'
import { API_KEY_ENV_VAR } from '@codebuff/common/old-constants'
import { AskUserBridge } from '@codebuff/common/utils/ask-user-bridge'
import { CodebuffClient } from '@codebuff/sdk'
import { getAuthTokenDetails } from './auth'
import { loadAgentDefinitions } from './local-agent-registry'
import { logger } from './logger'
import { getRgPath } from '../native/ripgrep'
import { getProjectRoot } from '../project-files'
import type { ClientToolCall } from '@codebuff/common/tools/list'
let clientInstance: CodebuffClient | null = null
/**
* Recursively removes undefined values from an object to ensure clean JSON serialization.
* This prevents issues with APIs that don't accept explicit undefined values.
*/
function removeUndefinedValues<T>(obj: T): T {
if (obj === null || obj === undefined) {
return obj
}
if (Array.isArray(obj)) {
return obj.map(removeUndefinedValues) as T
}
if (typeof obj === 'object') {
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(obj)) {
if (value !== undefined) {
result[key] = removeUndefinedValues(value)
}
}
return result as T
}
return obj
}
/**
* Reset the cached CodebuffClient instance.
* This should be called after login to ensure the client is re-initialized with new credentials.
*/
export function resetCodebuffClient(): void {
clientInstance = null
}
export async function getCodebuffClient(): Promise<CodebuffClient | null> {
if (!clientInstance) {
const { token: apiKey } = getAuthTokenDetails()
if (!apiKey) {
logger.warn(
{},
`No authentication token found. Please run the login flow or set ${API_KEY_ENV_VAR}.`,
)
return null
}
const projectRoot = getProjectRoot()
// Set up ripgrep path for SDK to use
const env = getCliEnv()
if (env.CODEBUFF_IS_BINARY) {
try {
const rgPath = await getRgPath()
// Note: We still set process.env here because SDK reads from it
process.env.CODEBUFF_RG_PATH = rgPath
} catch (error) {
logger.error(error, 'Failed to set up ripgrep binary for SDK')
}
}
try {
const agentDefinitions = loadAgentDefinitions()
clientInstance = new CodebuffClient({
apiKey,
cwd: projectRoot,
agentDefinitions,
overrideTools: {
ask_user: async (input: ClientToolCall<'ask_user'>['input']) => {
const response = (await AskUserBridge.request(
'cli-override',
input.questions,
)) as {
answers?: Array<{ questionIndex: number; selectedOption: string }>
skipped?: boolean
}
return [
{
type: 'json',
value: removeUndefinedValues(response),
},
]
},
},
})
} catch (error) {
logger.error(error, 'Failed to initialize CodebuffClient')
return null
}
}
return clientInstance
}
export function getToolDisplayInfo(toolName: string): {
name: string
type: string
} {
const TOOL_NAME_OVERRIDES: Record<string, string> = {
list_directory: 'List Directories',
}
const capitalizeWords = (str: string) => {
return str.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())
}
return {
name: TOOL_NAME_OVERRIDES[toolName] ?? capitalizeWords(toolName),
type: 'tool',
}
}
function toYaml(obj: any, indent = 0): string {
const spaces = ' '.repeat(indent)
if (obj === null || obj === undefined) {
return 'null'
}
if (typeof obj === 'string') {
if (obj.includes('\n')) {
const lines = obj.split('\n')
return (
'|\n' + lines.map((line) => ' '.repeat(indent + 1) + line).join('\n')
)
}
return obj.includes(':') || obj.includes('#') ? `"${obj}"` : obj
}
if (typeof obj === 'number' || typeof obj === 'boolean') {
return String(obj)
}
if (Array.isArray(obj)) {
if (obj.length === 0) return '[]'
return (
'\n' +
obj
.map((item) => spaces + '- ' + toYaml(item, indent + 1).trimStart())
.join('\n')
)
}
if (typeof obj === 'object') {
const entries = Object.entries(obj)
if (entries.length === 0) return '{}'
return entries
.map(([key, value]) => {
const yamlValue = toYaml(value, indent + 1)
if (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
Object.keys(value).length > 0
) {
return `${spaces}${key}:\n${yamlValue}`
}
if (typeof value === 'string' && value.includes('\n')) {
return `${spaces}${key}: ${yamlValue}`
}
return `${spaces}${key}: ${yamlValue}`
})
.join('\n')
}
return String(obj)
}
export function formatToolOutput(output: unknown): string {
if (!output) return ''
if (Array.isArray(output)) {
return output
.map((item) => {
if (item.type === 'json') {
// Handle errorMessage in the value object
if (
item.value &&
typeof item.value === 'object' &&
'errorMessage' in item.value
) {
return String(item.value.errorMessage)
}
return toYaml(item.value)
}
if (item.type === 'text') {
return item.text || ''
}
return String(item)
})
.join('\n')
}
if (typeof output === 'string') {
return output
}
return toYaml(output)
}