mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)
This commit is contained in:
1 parent
3cc24288a6
commit
c3d6549f01
133 files changed
+7284
-6293
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
export type OpenCodePasswordResolver = () => string | Promise<string>
|
||||
|
||||
export function getOpenCodeBasicAuthHeader(): string | null
|
||||
export function getOpenCodeBasicAuthHeader(password: string): string | null
|
||||
export function getOpenCodeBasicAuthHeader(passwordResolver: OpenCodePasswordResolver): Promise<string | null>
|
||||
export function getOpenCodeBasicAuthHeader(source?: string | OpenCodePasswordResolver): string | null | Promise<string | null> {
|
||||
if (typeof source === 'function') {
|
||||
return Promise.resolve(source()).then((password) => getOpenCodeBasicAuthHeader(password))
|
||||
}
|
||||
|
||||
const password = source ?? ENV.OPENCODE.SERVER_PASSWORD
|
||||
const username = ENV.OPENCODE.SERVER_USERNAME
|
||||
if (!password) return null
|
||||
const token = Buffer.from(`${username}:${password}`).toString('base64')
|
||||
return `Basic ${token}`
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
|
||||
|
||||
export interface ForwardRequest {
|
||||
method: string
|
||||
path: string
|
||||
body?: string
|
||||
headers?: Record<string, string>
|
||||
directory?: string
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface JsonRequestOptions {
|
||||
directory?: string
|
||||
headers?: Record<string, string>
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export class UpstreamError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
public readonly bodyText: string,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `OpenCode upstream returned ${status}`)
|
||||
this.name = 'UpstreamError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenCodeClient {
|
||||
forward(req: ForwardRequest): Promise<Response>
|
||||
forwardRaw(request: Request): Promise<Response>
|
||||
getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T>
|
||||
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
|
||||
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
|
||||
deleteProviderAuth(providerId: string): Promise<boolean>
|
||||
startMcpAuth(serverName: string, directory?: string): Promise<Response>
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export interface FetchOpenCodeClientConfig {
|
||||
baseUrl: string
|
||||
basicAuth: string | null
|
||||
passwordResolver?: OpenCodePasswordResolver
|
||||
fetchFn?: typeof fetch
|
||||
}
|
||||
|
||||
export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
constructor(private readonly config: FetchOpenCodeClientConfig) {}
|
||||
|
||||
private get fetchFn(): typeof fetch {
|
||||
return this.config.fetchFn ?? fetch
|
||||
}
|
||||
|
||||
private async getBasicAuth(): Promise<string> {
|
||||
if (!this.config.passwordResolver) {
|
||||
return this.config.basicAuth ?? ''
|
||||
}
|
||||
|
||||
return await getOpenCodeBasicAuthHeader(this.config.passwordResolver) ?? ''
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.config.baseUrl + req.path)
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { ...(req.headers ?? {}) }
|
||||
const basicAuth = await this.getBasicAuth()
|
||||
|
||||
if (basicAuth) {
|
||||
headers.Authorization = basicAuth
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.fetchFn(url, {
|
||||
method: req.method,
|
||||
headers,
|
||||
body: req.body,
|
||||
signal: req.signal,
|
||||
})
|
||||
|
||||
const filteredHeaders: Record<string, string> = {}
|
||||
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!skipHeaders.has(key.toLowerCase())) {
|
||||
filteredHeaders[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const noBodyStatuses = new Set([101, 204, 205, 304])
|
||||
if (noBodyStatuses.has(response.status)) {
|
||||
return new Response(null, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: filteredHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
const body = await response.text()
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: filteredHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Proxy request failed for ${req.path}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async forward(req: ForwardRequest): Promise<Response> {
|
||||
return this.request(req)
|
||||
}
|
||||
|
||||
async forwardRaw(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
|
||||
|
||||
if (url.pathname.includes('/permissions/')) {
|
||||
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${cleanPathname}${url.search}`)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
request.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!['host', 'connection', 'authorization'].includes(lowerKey)) {
|
||||
headers[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const body = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
? await request.text()
|
||||
: undefined
|
||||
|
||||
return this.request({
|
||||
method: request.method,
|
||||
path: cleanPathname + url.search,
|
||||
body,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
async getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T> {
|
||||
const response = await this.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
directory: opts?.directory,
|
||||
headers: opts?.headers,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(opts?.headers ?? {}),
|
||||
}
|
||||
|
||||
const response = await this.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: JSON.stringify(body),
|
||||
headers,
|
||||
directory: opts?.directory,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async setProviderAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'PUT',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Set OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to set OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async deleteProviderAuth(providerId: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'DELETE',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to delete OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async startMcpAuth(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async authenticateMcp(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(passwordOverride?: string | OpenCodePasswordResolver): OpenCodeClient {
|
||||
const host = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
|
||||
const baseUrl = `http://${host}:${ENV.OPENCODE.PORT}`
|
||||
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
|
||||
return new FetchOpenCodeClient({ baseUrl, basicAuth, passwordResolver })
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import type { OpenCodeClient } from './client'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
|
||||
export type PatchConfigValidationIssue = {
|
||||
path: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export type PatchConfigResult = {
|
||||
success: boolean
|
||||
error?: string
|
||||
details?: PatchConfigValidationIssue[]
|
||||
removedFields?: string[]
|
||||
appliedConfig?: Record<string, unknown>
|
||||
}
|
||||
|
||||
function getIssuePath(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
const path = value
|
||||
.map((part) => typeof part === 'string' || typeof part === 'number' ? String(part) : '')
|
||||
.filter(Boolean)
|
||||
.join('.')
|
||||
return path || 'root'
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && value.length > 0) {
|
||||
if (value.startsWith('/')) {
|
||||
const pointerPath = value
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~'))
|
||||
.join('.')
|
||||
return pointerPath || 'root'
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return String(value)
|
||||
}
|
||||
|
||||
return 'root'
|
||||
}
|
||||
|
||||
function getIssueMessage(value: unknown): string {
|
||||
if (typeof value === 'string' && value.length > 0) {
|
||||
return value
|
||||
}
|
||||
|
||||
return 'Validation error'
|
||||
}
|
||||
|
||||
function extractValidationIssues(value: unknown): PatchConfigValidationIssue[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return []
|
||||
}
|
||||
|
||||
return value.flatMap((item) => {
|
||||
if (!item || typeof item !== 'object') {
|
||||
return []
|
||||
}
|
||||
|
||||
const issue = item as Record<string, unknown>
|
||||
const nestedIssues = extractValidationIssues(issue.issues ?? issue.errors)
|
||||
if (nestedIssues.length > 0) {
|
||||
return nestedIssues
|
||||
}
|
||||
|
||||
if (
|
||||
typeof issue.message === 'string'
|
||||
|| typeof issue.path === 'string'
|
||||
|| Array.isArray(issue.path)
|
||||
|| typeof issue.instancePath === 'string'
|
||||
|| Array.isArray(issue.instancePath)
|
||||
) {
|
||||
return [{
|
||||
path: getIssuePath(issue.path ?? issue.instancePath),
|
||||
message: getIssueMessage(issue.message),
|
||||
}]
|
||||
}
|
||||
|
||||
return []
|
||||
})
|
||||
}
|
||||
|
||||
function removeFieldFromConfig(config: Record<string, unknown>, path: string): Record<string, unknown> {
|
||||
const result = JSON.parse(JSON.stringify(config)) as Record<string, unknown>
|
||||
const parts = path.split('.')
|
||||
|
||||
let current: Record<string, unknown> = result
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const part = parts[i]
|
||||
if (!part || !current[part] || typeof current[part] !== 'object') {
|
||||
return result
|
||||
}
|
||||
current = current[part] as Record<string, unknown>
|
||||
}
|
||||
|
||||
const lastPart = parts[parts.length - 1]
|
||||
if (lastPart) {
|
||||
delete current[lastPart]
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function parseErrorResponse(responseText: string): { details: PatchConfigValidationIssue[]; errorMessage: string } {
|
||||
const details: PatchConfigValidationIssue[] = []
|
||||
let errorMessage = 'Unknown error'
|
||||
|
||||
try {
|
||||
const errorBody = parseJsonc(responseText) as Record<string, unknown>
|
||||
const structuredIssues = extractValidationIssues(
|
||||
errorBody?.errors
|
||||
?? errorBody?.issues
|
||||
?? (errorBody?.data && typeof errorBody.data === 'object'
|
||||
? (errorBody.data as Record<string, unknown>).errors ?? (errorBody.data as Record<string, unknown>).issues
|
||||
: undefined)
|
||||
)
|
||||
|
||||
if (structuredIssues.length > 0) {
|
||||
details.push(...structuredIssues)
|
||||
errorMessage = details.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
} else if (errorBody?.name === 'ConfigInvalidError' && errorBody?.data) {
|
||||
const data = errorBody.data as { issues?: Array<{ message: string; path?: string[] }> }
|
||||
if (data.issues) {
|
||||
for (const issue of data.issues) {
|
||||
const path = issue.path ? issue.path.join('.') : 'root'
|
||||
details.push({ path, message: issue.message })
|
||||
}
|
||||
errorMessage = details.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
}
|
||||
} else if (typeof errorBody?.error === 'string') {
|
||||
errorMessage = errorBody.error
|
||||
} else if (typeof errorBody?.message === 'string') {
|
||||
errorMessage = errorBody.message
|
||||
} else if (typeof errorBody?.success === 'boolean' && errorBody.success === false && errorBody?.data) {
|
||||
errorMessage = 'Config validation failed'
|
||||
} else {
|
||||
const snippet = responseText.slice(0, 300)
|
||||
errorMessage = `Request failed (${snippet.length < responseText.length ? 'truncated' : 'raw'} response): ${snippet}`
|
||||
}
|
||||
} catch {
|
||||
const snippet = responseText.slice(0, 300)
|
||||
errorMessage = `Parse error: ${snippet}`
|
||||
}
|
||||
|
||||
return { details, errorMessage }
|
||||
}
|
||||
|
||||
export async function patchConfigWithRecovery(
|
||||
client: OpenCodeClient,
|
||||
config: Record<string, unknown>,
|
||||
): Promise<PatchConfigResult> {
|
||||
try {
|
||||
const response = await client.forward({
|
||||
method: 'PATCH',
|
||||
path: '/config',
|
||||
body: JSON.stringify(config),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info('Patched OpenCode config via API')
|
||||
return { success: true, appliedConfig: config }
|
||||
}
|
||||
|
||||
const responseText = await response.text()
|
||||
logger.warn(`OpenCode PATCH response (${response.status}): ${responseText.slice(0, 500)}`)
|
||||
const { details, errorMessage: initialError } = parseErrorResponse(responseText)
|
||||
|
||||
if (details.length === 0) {
|
||||
logger.error(`Failed to patch OpenCode config: ${initialError}`)
|
||||
return { success: false, error: initialError, details }
|
||||
}
|
||||
|
||||
logger.warn(`OpenCode rejected config with validation errors: ${initialError}`)
|
||||
|
||||
const problematicPaths = [...new Set(details.map((d) => d.path))]
|
||||
const removablePaths = problematicPaths.filter((path) => path !== 'root' && path.split('.').length <= 3)
|
||||
const nonRemovablePaths = problematicPaths.filter((path) => path === 'root' || path.split('.').length > 3)
|
||||
|
||||
if (nonRemovablePaths.length > 0) {
|
||||
logger.error(`Failed to patch OpenCode config: ${initialError}`)
|
||||
return { success: false, error: initialError, details }
|
||||
}
|
||||
|
||||
if (removablePaths.length === 0) {
|
||||
logger.error(`Failed to patch OpenCode config: ${initialError}`)
|
||||
return { success: false, error: initialError, details }
|
||||
}
|
||||
|
||||
let cleanedConfig = config
|
||||
const removedFields: string[] = []
|
||||
|
||||
for (const path of removablePaths) {
|
||||
cleanedConfig = removeFieldFromConfig(cleanedConfig, path)
|
||||
removedFields.push(path)
|
||||
logger.info(`Removed problematic field from config: ${path}`)
|
||||
}
|
||||
|
||||
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
|
||||
const retryResponse = await client.forward({
|
||||
method: 'PATCH',
|
||||
path: '/config',
|
||||
body: JSON.stringify(cleanedConfig),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (retryResponse.ok) {
|
||||
logger.info('Patched OpenCode config via API after removing invalid fields')
|
||||
return {
|
||||
success: true,
|
||||
appliedConfig: cleanedConfig,
|
||||
removedFields,
|
||||
details
|
||||
}
|
||||
}
|
||||
|
||||
const retryResponseText = await retryResponse.text()
|
||||
const { details: retryDetails, errorMessage } = parseErrorResponse(retryResponseText)
|
||||
logger.error(`Failed to patch OpenCode config even after removing invalid fields: ${errorMessage}`)
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
details: retryDetails.length > 0 ? retryDetails : details,
|
||||
removedFields
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
||||
logger.error('Failed to patch OpenCode config:', error)
|
||||
return { success: false, error: errorMessage }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user