feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-02 21:51:37 -04:00
1 parent 3cc24288a6
commit c3d6549f01
133 files changed
+7284 -6293

No files matched your search

@@ -0,0 +1,19 @@
import { createMiddleware } from 'hono/factory'
import { timingSafeEqual } from 'node:crypto'
import type { Database } from 'bun:sqlite'
import { getOrCreateInternalToken } from '../services/internal-token'
export function createInternalTokenMiddleware(db: Database) {
return createMiddleware(async (c, next) => {
const header = c.req.header('authorization') ?? c.req.header('Authorization')
if (!header || !header.startsWith('Bearer ')) {
return c.json({ error: 'Unauthorized' }, 401)
}
const provided = Buffer.from(header.slice(7))
const expected = Buffer.from(getOrCreateInternalToken(db))
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
return c.json({ error: 'Unauthorized' }, 401)
}
await next()
})
}
@@ -0,0 +1,21 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 13,
name: 'app-secrets',
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS app_secrets (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
},
down(db) {
db.run('DROP TABLE IF EXISTS app_secrets')
},
}
export default migration
+2
View File
@@ -11,6 +11,7 @@ import migration009 from './009-repo-source-path'
import migration010 from './009-prompt-templates'
import migration011 from './011-repo-last-accessed'
import migration012 from './012-opencode-model-state'
import migration013 from './013-app-secrets'
export const allMigrations: Migration[] = [
migration001,
@@ -25,4 +26,5 @@ export const allMigrations: Migration[] = [
migration010,
migration011,
migration012,
migration013,
]
+21 -14
View File
@@ -29,17 +29,17 @@ import { createOAuthRoutes } from './routes/oauth'
import { createSSERoutes } from './routes/sse'
import { createSSHRoutes } from './routes/ssh'
import { createNotificationRoutes } from './routes/notifications'
import { createMemoryRoutes } from './routes/memory'
import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { createInternalRoutes } from './routes/internal'
import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
import { createOpenCodeClient } from './services/opencode/client'
import { NotificationService } from './services/notification'
import { ScheduleRunner, ScheduleService } from './services/schedules'
import { migrateGlobalSkills } from './services/skills'
@@ -85,6 +85,7 @@ app.use('/*', cors({
const db = initializeDatabase(DB_PATH)
const auth = createAuth(db)
const requireAuth = createAuthMiddleware(auth)
const openCodeClient = createOpenCodeClient(() => new SettingsService(db).getOpenCodeServerPassword())
import { DEFAULT_AGENTS_MD } from './constants'
@@ -262,6 +263,8 @@ try {
await gitAuthService.initialize(ipcServer, db)
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
await syncAdminFromEnv(auth, db)
opencodeServerManager.setDatabase(db)
const openCodeStatus = await openCodeSupervisor.start()
if (openCodeStatus.healthy) {
@@ -270,12 +273,11 @@ try {
logger.warn(`OpenCode server unavailable after startup recovery: ${openCodeStatus.lastError ?? openCodeStatus.state}`)
}
await syncAdminFromEnv(auth, db)
} catch (error) {
logger.error('Failed to initialize workspace:', error)
}
const scheduleService = new ScheduleService(db)
const scheduleService = new ScheduleService(db, openCodeClient)
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
const notificationService = new NotificationService(db)
@@ -299,28 +301,34 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
})
}
sseAggregator.setPendingActionsFetcher(openCodeClient)
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
sseAggregator.start()
void scheduleRunnerInstance.start()
const settingsService = new SettingsService(db)
app.route('/api/auth', createAuthRoutes(auth))
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeSupervisor))
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeSupervisor))
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, openCodeSupervisor))
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/providers', createProvidersRoutes(db, openCodeSupervisor))
protectedApi.route('/oauth', createOAuthRoutes(openCodeSupervisor))
protectedApi.route('/providers', createProvidersRoutes(db, openCodeClient, openCodeSupervisor))
protectedApi.route('/oauth', createOAuthRoutes(openCodeClient, openCodeSupervisor))
protectedApi.route('/tts', createTTSRoutes(db))
protectedApi.route('/stt', createSTTRoutes(db))
protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
protectedApi.route('/memory', createMemoryRoutes(db))
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
@@ -329,18 +337,17 @@ app.route('/api', protectedApi)
app.post('/api/opencode/mcp/:name/auth', requireAuth, async (c) => {
const serverName = c.req.param('name')
const directory = c.req.query('directory')
return proxyMcpAuthStart(serverName, directory)
return openCodeClient.startMcpAuth(serverName, directory)
})
app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => {
const serverName = c.req.param('name')
const directory = c.req.query('directory')
return proxyMcpAuthAuthenticate(serverName, directory)
return openCodeClient.authenticateMcp(serverName, directory)
})
app.all('/api/opencode/*', requireAuth, async (c) => {
const request = c.req.raw
return proxyRequest(request)
return openCodeClient.forwardRaw(c.req.raw)
})
const isProduction = ENV.SERVER.NODE_ENV === 'production'
+26
View File
@@ -0,0 +1,26 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import type { ScheduleService } from '../../services/schedules'
import type { NotificationService } from '../../services/notification'
import type { SettingsService } from '../../services/settings'
import { createScheduleRoutes } from '../schedules'
import { createInternalTokenMiddleware } from '../../auth/internal-token-middleware'
import { createInternalNotificationRoutes } from './notifications'
import { createInternalSettingsRoutes } from './settings'
export function createInternalRoutes(
db: Database,
scheduleService: ScheduleService,
notificationService: NotificationService,
settingsService: SettingsService,
) {
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
app.route('/schedules', createScheduleRoutes(scheduleService))
app.route('/notifications', createInternalNotificationRoutes(notificationService))
app.route('/settings', createInternalSettingsRoutes(settingsService))
const repos = new Hono()
repos.route('/:id/schedules', createScheduleRoutes(scheduleService))
app.route('/repos', repos)
return app
}
@@ -0,0 +1,57 @@
import { Hono } from 'hono'
import { AssistantNotificationRequestSchema } from '@opencode-manager/shared/schemas'
import type { NotificationService } from '../../services/notification'
import { TokenBucketRateLimiter } from '../../utils/rate-limit'
export function createInternalNotificationRoutes(notificationService: NotificationService) {
const app = new Hono()
const limiter = new TokenBucketRateLimiter({ capacity: 10, refillPerMs: 60_000 })
app.post('/send', async (c) => {
if (!notificationService.isConfigured()) {
return c.json({ error: 'Push notifications are not configured (missing VAPID env)' }, 503)
}
const token = (c.req.header('authorization') ?? '').slice('Bearer '.length)
const limit = limiter.tryConsume(token || 'anon')
if (!limit.allowed) {
c.header('Retry-After', String(Math.ceil(limit.retryAfterMs / 1000)))
return c.json({ error: 'Rate limit exceeded' }, 429)
}
let body: unknown
try {
body = await c.req.json()
} catch {
return c.json({ error: 'Invalid JSON' }, 400)
}
const parsed = AssistantNotificationRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400)
}
const userId = c.req.query('userId') ?? 'default'
const payload = {
title: parsed.data.title,
body: parsed.data.body,
tag: parsed.data.tag ?? `assistant-${Date.now()}`,
data: {
eventType: 'assistant.message',
url: parsed.data.url ?? '/',
priority: parsed.data.priority,
},
}
const stats = await notificationService.sendToUser(userId, payload)
return c.json({
delivered: stats.delivered,
expired: stats.expired,
failed: stats.failed,
noSubscriptions: stats.total === 0,
})
})
return app
}
+35
View File
@@ -0,0 +1,35 @@
import { Hono } from 'hono'
import { AssistantSettingsPatchSchema } from '@opencode-manager/shared/schemas'
import type { SettingsService } from '../../services/settings'
import type { UserPreferences } from '@opencode-manager/shared/types'
export function createInternalSettingsRoutes(settingsService: SettingsService) {
const app = new Hono()
app.get('/', (c) => {
const userId = c.req.query('userId') ?? 'default'
const settings = settingsService.getSettings(userId)
return c.json(settings)
})
app.patch('/', async (c) => {
const userId = c.req.query('userId') ?? 'default'
let body: unknown
try {
body = await c.req.json()
} catch {
return c.json({ error: 'Invalid JSON' }, 400)
}
const parsed = AssistantSettingsPatchSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400)
}
const updated = settingsService.updateSettings(parsed.data as Partial<UserPreferences>, userId)
return c.json(updated)
})
return app
}
+10 -14
View File
@@ -1,4 +1,5 @@
import { Hono } from 'hono'
import type { OpenCodeClient } from '../services/opencode/client'
import { z } from 'zod'
import crypto from 'crypto'
import path from 'path'
@@ -6,7 +7,6 @@ import { readFile, writeFile, mkdir } from 'fs/promises'
import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state'
import { logger } from '../utils/logger'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy'
const StartSchema = z.object({
serverName: z.string(),
@@ -132,8 +132,10 @@ async function registerClient(
return result
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function createMcpOauthProxyRoutes(requireAuth?: any) {
import type { MiddlewareHandler } from 'hono'
export function createMcpOauthProxyRoutes(openCodeClient: OpenCodeClient, requireAuth?: MiddlewareHandler) {
const app = new Hono()
if (requireAuth) {
@@ -292,21 +294,15 @@ export function createMcpOauthProxyRoutes(requireAuth?: any) {
markMcpOAuthFlowCompleted(state, flow.serverName)
try {
let reconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect`
if (flow.directory) {
const url = new URL(reconnectUrl)
url.searchParams.set('directory', flow.directory)
reconnectUrl = url.toString()
}
await fetch(reconnectUrl, {
await openCodeClient.forward({
method: 'POST',
headers: withOpenCodeAuth(),
path: `/mcp/${encodeURIComponent(flow.serverName)}/connect`,
directory: flow.directory,
})
if (flow.directory) {
const globalReconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect`
await fetch(globalReconnectUrl, {
await openCodeClient.forward({
method: 'POST',
headers: withOpenCodeAuth(),
path: `/mcp/${encodeURIComponent(flow.serverName)}/connect`,
})
}
} catch {
-712
View File
@@ -1,712 +0,0 @@
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from 'fs'
import { join } from 'path'
import { logger } from '../utils/logger'
import { PluginMemoryService } from '../services/plugin-memory'
import { resolveProjectId } from '../services/project-id-resolver'
import { getRepoById } from '../db/queries'
import { getWorkspacePath, getConfigPath } from '@opencode-manager/shared/config/env'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy'
import {
CreateMemoryRequestSchema,
UpdateMemoryRequestSchema,
MemoryListQuerySchema,
KvListQuerySchema,
PluginConfigSchema,
CreateKvEntryRequestSchema,
UpdateKvEntryRequestSchema,
LoopStateSchema,
type PluginConfig,
type LoopState,
} from '@opencode-manager/shared/schemas'
function resolveMemoryDataDir(): string {
return join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'memory')
}
function resolvePluginConfigPath(): string {
return join(getConfigPath(), 'memory-config.jsonc')
}
function resolveOldPluginConfigPath(): string {
return join(resolveMemoryDataDir(), 'config.json')
}
function getDefaultPluginConfig(): PluginConfig {
return {
embedding: {
provider: 'local',
model: 'all-MiniLM-L6-v2',
dimensions: 384,
},
dedupThreshold: 0.25,
}
}
function loadPluginConfigFromDisk(): PluginConfig {
const configPath = resolvePluginConfigPath()
if (!existsSync(configPath)) {
const oldPath = resolveOldPluginConfigPath()
if (existsSync(oldPath)) {
const configDir = getConfigPath()
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true })
}
copyFileSync(oldPath, configPath)
} else {
return getDefaultPluginConfig()
}
}
try {
const content = readFileSync(configPath, 'utf-8')
const parsed = parseJsonc(content)
const result = PluginConfigSchema.safeParse(parsed)
if (!result.success) {
logger.error('Invalid plugin config:', result.error)
return getDefaultPluginConfig()
}
return result.data
} catch (error) {
logger.error('Failed to load plugin config:', error)
return getDefaultPluginConfig()
}
}
function savePluginConfigToDisk(config: PluginConfig): void {
const configPath = resolvePluginConfigPath()
const configDir = getConfigPath()
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true })
}
// Read existing content to preserve comments
let existingContent = ''
if (existsSync(configPath)) {
try {
existingContent = readFileSync(configPath, 'utf-8')
} catch {
// File doesn't exist or can't be read, will create new
}
}
// If we have existing content, preserve comments by extracting them
// and re-adding them to the new content
if (existingContent) {
// Extract comments from existing content
const lines = existingContent.split('\n')
const commentLines: string[] = []
for (const line of lines) {
const trimmed = line.trim()
if (trimmed.startsWith('//')) {
commentLines.push(line.match(/\/\/\s*(.*)/)?.[1] || '')
}
}
// Create new JSON string
const newContent = JSON.stringify(config, null, 2)
// If we found comments, try to preserve them
if (commentLines.length > 0) {
const newLines = newContent.split('\n')
const result: string[] = []
// Add comments at the beginning
for (const comment of commentLines) {
result.push(`// ${comment}`)
}
result.push(...newLines)
writeFileSync(configPath, result.join('\n'), 'utf-8')
return
}
writeFileSync(configPath, newContent, 'utf-8')
} else {
writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8')
}
}
export function createMemoryRoutes(db: Database): Hono {
const app = new Hono()
const pluginMemory = new PluginMemoryService()
app.get('/', async (c) => {
const query = c.req.query()
const parsed = MemoryListQuerySchema.safeParse({
projectId: query.projectId,
scope: query.scope,
content: query.content,
limit: query.limit ? parseInt(query.limit, 10) : undefined,
offset: query.offset ? parseInt(query.offset, 10) : undefined,
})
if (!parsed.success) {
return c.json({ error: 'Invalid query parameters', details: parsed.error }, 400)
}
const filters = parsed.data
if (!filters.projectId) {
return c.json({ memories: [] })
}
const memories = pluginMemory.list(filters.projectId, {
scope: filters.scope,
content: filters.content,
limit: filters.limit,
offset: filters.offset,
})
return c.json({ memories })
})
app.post('/', async (c) => {
const body = await c.req.json()
const parsed = CreateMemoryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
const id = pluginMemory.create(parsed.data)
const memory = pluginMemory.getById(id)
if (!memory) {
return c.json({ error: 'Failed to retrieve created memory' }, 500)
}
return c.json({ memory }, 201)
} catch (error) {
logger.error('Failed to create memory:', error)
return c.json({ error: 'Failed to create memory' }, 500)
}
})
app.get('/project-summary', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId parameter' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Repository not found' }, 404)
}
const projectId = await resolveProjectId(repo.fullPath)
if (!projectId) {
return c.json({ projectId: null, stats: { total: 0, byScope: {} } })
}
const stats = pluginMemory.getStats(projectId)
const kvCount = pluginMemory.getKvCount(projectId)
return c.json({ projectId, stats, kvCount })
} catch (error) {
logger.error('Failed to get project summary:', error)
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Failed to get project summary' }, 500)
}
})
app.get('/stats', async (c) => {
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
try {
const stats = pluginMemory.getStats(projectId)
return c.json(stats)
} catch (error) {
logger.error('Failed to get memory stats:', error)
return c.json({ error: 'Failed to get stats' }, 500)
}
})
app.get('/resolve-project', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId parameter' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ projectId: null, error: 'Repository not found' }, 404)
}
const projectId = await resolveProjectId(repo.fullPath)
return c.json({ projectId })
} catch (error) {
logger.error('Failed to resolve project ID:', error)
return c.json({ projectId: null, error: 'Failed to resolve project ID' }, 500)
}
})
app.get('/plugin-config', async (c) => {
try {
const config = loadPluginConfigFromDisk()
return c.json({ config })
} catch (error) {
logger.error('Failed to get plugin config:', error)
return c.json({ error: 'Failed to get plugin config' }, 500)
}
})
app.put('/plugin-config', async (c) => {
try {
const body = await c.req.json()
const parsed = PluginConfigSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid config', details: parsed.error.flatten() }, 400)
}
const config = parsed.data
config.dedupThreshold = Math.max(0.05, Math.min(0.4, config.dedupThreshold ?? 0.25))
savePluginConfigToDisk(config)
return c.json({ success: true, config })
} catch (error) {
logger.error('Failed to save plugin config:', error)
return c.json({ error: 'Failed to save plugin config' }, 500)
}
})
app.post('/test-embedding', async (c) => {
try {
const config = loadPluginConfigFromDisk()
if (config.embedding.provider === 'local') {
const validModels = ['all-MiniLM-L6-v2']
if (!validModels.includes(config.embedding.model)) {
return c.json({
success: false,
error: `Invalid model: ${config.embedding.model}. Valid models: ${validModels.join(', ')}`
}, 400)
}
return c.json({
success: true,
message: 'Local provider configured. Model will be loaded on server restart.',
dimensions: config.embedding.dimensions ?? 384,
})
}
const endpoints: Record<string, string> = {
openai: 'https://api.openai.com/v1/embeddings',
voyage: 'https://api.voyageai.com/v1/embeddings',
}
const extractHost = (url: string): string => {
const protocolEnd = url.indexOf('://')
if (protocolEnd === -1) return url
const pathStart = url.indexOf('/', protocolEnd + 3)
return pathStart === -1 ? url : url.slice(0, pathStart)
}
const baseUrl = extractHost(config.embedding.baseUrl || '')
const endpoint = baseUrl
? `${baseUrl}/v1/embeddings`
: endpoints[config.embedding.provider] ?? ''
if (!endpoint) {
return c.json({ success: false, error: 'No endpoint configured' }, 400)
}
if (!config.embedding.apiKey) {
return c.json({ success: false, error: 'API key not configured. Please save your API key first.' }, 400)
}
const testBody = {
model: config.embedding.model,
input: ['test'],
}
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.embedding.apiKey}`,
}
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(testBody),
})
if (!response.ok) {
const errorText = await response.text()
return c.json({
success: false,
error: `API error: ${response.status}`,
message: errorText,
}, 400)
}
const data = await response.json() as {
data?: Array<{ embedding: number[] }>
embeddings?: Array<{ embedding: number[] }>
}
const embeddings = data.data || data.embeddings
if (!embeddings || embeddings.length === 0 || !embeddings[0]) {
return c.json({ success: false, error: 'Invalid response from API' }, 400)
}
const firstEmbedding = embeddings[0]
const actualDimensions = firstEmbedding.embedding.length
return c.json({
success: true,
message: `Embedding test successful. Generated ${actualDimensions}d embedding.`,
dimensions: actualDimensions,
})
} catch (error) {
logger.error('Failed to test embedding config:', error)
return c.json({
success: false,
error: 'Failed to test embedding configuration',
message: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
app.post('/reindex', async (c) => {
try {
const db = pluginMemory.getDb()
if (!db) {
return c.json({
error: 'Memory database not found. Make sure the memory plugin has been initialized.',
total: 0,
embedded: 0,
failed: 0
}, 404)
}
const memories = pluginMemory.listAll()
if (memories.length === 0) {
return c.json({
success: true,
message: 'No memories to reindex',
total: 0,
embedded: 0,
failed: 0
})
}
try {
db.exec('DELETE FROM memory_embeddings')
} catch {
return c.json({
success: true,
message: 'Cleared embeddings. Server restart required to regenerate embeddings with new model.',
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
}
return c.json({
success: true,
message: `Cleared ${memories.length} embeddings. Server restart required to regenerate embeddings.`,
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
} catch (error) {
logger.error('Failed to reindex memories:', error)
return c.json({ error: 'Failed to reindex memories', details: error instanceof Error ? error.message : 'Unknown error' }, 500)
}
})
app.get('/kv', async (c) => {
const query = c.req.query()
const parsed = KvListQuerySchema.safeParse({
projectId: query.projectId,
prefix: query.prefix,
})
if (!parsed.success) {
return c.json({ error: 'Invalid query parameters', details: parsed.error }, 400)
}
const { projectId, prefix } = parsed.data
const entries = pluginMemory.listKv(projectId, prefix)
return c.json({ entries })
})
app.post('/kv', async (c) => {
const body = await c.req.json()
const parsed = CreateKvEntryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.setKv(parsed.data.projectId, parsed.data.key, parsed.data.data, parsed.data.ttlMs)
const entry = pluginMemory.getKv(parsed.data.projectId, parsed.data.key)
return c.json({ entry }, 201)
} catch (error) {
logger.error('Failed to create KV entry:', error)
return c.json({ error: 'Failed to create KV entry' }, 500)
}
})
app.put('/kv/:key', async (c) => {
const key = decodeURIComponent(c.req.param('key'))
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
const body = await c.req.json()
const parsed = UpdateKvEntryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.setKv(projectId, key, parsed.data.data, parsed.data.ttlMs)
const entry = pluginMemory.getKv(projectId, key)
return c.json({ entry })
} catch (error) {
logger.error('Failed to update KV entry:', error)
return c.json({ error: 'Failed to update KV entry' }, 500)
}
})
app.delete('/kv/:key', async (c) => {
const key = decodeURIComponent(c.req.param('key'))
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
try {
pluginMemory.deleteKv(projectId, key)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete KV entry:', error)
return c.json({ error: 'Failed to delete KV entry' }, 500)
}
})
app.get('/loop/status', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ loops: [], projectId: null })
}
const projectId = await resolveProjectId(repo.fullPath)
if (!projectId) {
return c.json({ loops: [], projectId: null })
}
const entries = pluginMemory.listKv(projectId, 'loop:')
const loops = entries
.map(e => e.data)
.filter((data): data is Record<string, unknown> =>
data !== null && typeof data === 'object' && 'active' in data
)
.map(data => {
const result = LoopStateSchema.safeParse(data)
return result.success ? result.data : null
})
.filter((loop): loop is LoopState => loop !== null)
return c.json({ loops, projectId })
} catch (error) {
logger.error('Failed to get Loop:', error)
return c.json({ error: 'Failed to get Loop' }, 500)
}
})
app.post('/loop/cancel', async (c) => {
try {
const body = await c.req.json()
const { repoId, worktreeName, sessionId } = body
if (!repoId || (!worktreeName && !sessionId)) {
return c.json({ error: 'Missing repoId or identifier (worktreeName or sessionId)' }, 400)
}
const repo = getRepoById(db, parseInt(repoId, 10))
if (!repo) {
return c.json({ cancelled: false })
}
const projectId = await resolveProjectId(repo.fullPath)
if (!projectId) {
return c.json({ cancelled: false })
}
let worktreeNameToUse: string | undefined
if (worktreeName) {
worktreeNameToUse = worktreeName
} else if (sessionId) {
const sessionMappingEntry = pluginMemory.getKv(projectId, `loop-session:${sessionId}`)
if (!sessionMappingEntry) {
return c.json({ cancelled: false })
}
worktreeNameToUse = sessionMappingEntry.data as string
}
if (!worktreeNameToUse) {
return c.json({ cancelled: false })
}
const kvEntry = pluginMemory.getKv(projectId, `loop:${worktreeNameToUse}`)
if (!kvEntry) {
return c.json({ cancelled: false })
}
const result = LoopStateSchema.safeParse(kvEntry.data)
if (!result.success) {
logger.warn('Failed to parse Loop state for cancel:', result.error)
return c.json({ cancelled: false })
}
const state = result.data
if (!state.active) {
return c.json({ cancelled: false })
}
const updatedState = {
...state,
active: false,
terminationReason: 'cancelled',
completedAt: new Date().toISOString(),
}
pluginMemory.setKv(projectId, `loop:${worktreeNameToUse}`, updatedState)
try {
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${state.sessionId}/abort`)
abortUrl.searchParams.set('directory', repo.fullPath)
await fetch(abortUrl.toString(), { method: 'POST', headers: withOpenCodeAuth() })
} catch {
// Session may already be idle
}
return c.json({ cancelled: true, worktreeName: state.worktreeName })
} catch (error) {
logger.error('Failed to cancel Loop:', error)
return c.json({ error: 'Failed to cancel Loop' }, 500)
}
})
app.get('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
const memory = pluginMemory.getById(id)
if (!memory) {
return c.json({ error: 'Memory not found' }, 404)
}
return c.json({ memory })
})
app.put('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
const body = await c.req.json()
const parsed = UpdateMemoryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.update(id, parsed.data)
const memory = pluginMemory.getById(id)
return c.json({ memory })
} catch (error) {
logger.error('Failed to update memory:', error)
return c.json({ error: 'Failed to update memory' }, 500)
}
})
app.delete('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
try {
pluginMemory.delete(id)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete memory:', error)
return c.json({ error: 'Failed to delete memory' }, 500)
}
})
return app
}
+18 -31
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import type { OpenCodeClient } from '../services/opencode/client'
import { z } from 'zod'
import { proxyRequest, OPENCODE_SERVER_URL } from '../services/proxy'
import { logger } from '../utils/logger'
import {
OAuthAuthorizeRequestSchema,
@@ -19,7 +19,7 @@ async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Pr
await opencodeServerManager.reloadConfig()
}
export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
export function createOAuthRoutes(openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
const app = new Hono()
app.post('/:id/oauth/authorize', async (c) => {
@@ -28,17 +28,12 @@ export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
const body = await c.req.json()
const validated = OAuthAuthorizeRequestSchema.parse(body)
// Proxy to OpenCode server - only method and inputs are supported
const response = await proxyRequest(
new Request(
`${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/authorize`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validated)
}
)
)
const response = await openCodeClient.forward({
method: 'POST',
path: `/provider/${encodeURIComponent(providerId)}/oauth/authorize`,
body: JSON.stringify(validated),
headers: { 'Content-Type': 'application/json' },
})
if (!response.ok) {
const error = await response.text()
@@ -65,17 +60,12 @@ export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
const body = await c.req.json()
const validated = OAuthCallbackRequestSchema.parse(body)
// Proxy to OpenCode server
const response = await proxyRequest(
new Request(
`${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/callback`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validated)
}
)
)
const response = await openCodeClient.forward({
method: 'POST',
path: `/provider/${encodeURIComponent(providerId)}/oauth/callback`,
body: JSON.stringify(validated),
headers: { 'Content-Type': 'application/json' },
})
if (!response.ok) {
const error = await response.text()
@@ -103,13 +93,10 @@ export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
app.get('/auth-methods', async (c) => {
try {
// Proxy to OpenCode server
const response = await proxyRequest(
new Request(`${OPENCODE_SERVER_URL}/provider/auth`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
)
const response = await openCodeClient.forward({
method: 'GET',
path: '/provider/auth',
})
if (!response.ok) {
const error = await response.text()
+2 -1
View File
@@ -7,10 +7,11 @@ import { createProvidersRoutes } from './providers'
import { join, dirname } from 'node:path'
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
function createTestApp(db: Database): Hono {
const app = new Hono()
app.route('/providers', createProvidersRoutes(db, undefined))
app.route('/providers', createProvidersRoutes(db, createStubOpenCodeClient()))
return app
}
+4 -4
View File
@@ -4,7 +4,7 @@ import path from 'path'
import { AuthService } from '../services/auth'
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
import { logger } from '../utils/logger'
import { setOpenCodeAuth, deleteOpenCodeAuth } from '../services/proxy'
import type { OpenCodeClient } from '../services/opencode/client'
import { opencodeServerManager } from '../services/opencode-single-server'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
import type { Database } from 'bun:sqlite'
@@ -61,7 +61,7 @@ async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Pr
await opencodeServerManager.reloadConfig()
}
export function createProvidersRoutes(db: Database, openCodeSupervisor?: OpenCodeSupervisor) {
export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
const app = new Hono()
const authService = new AuthService()
@@ -129,7 +129,7 @@ export function createProvidersRoutes(db: Database, openCodeSupervisor?: OpenCod
const body = await c.req.json()
const validated = SetCredentialRequestSchema.parse(body)
const openCodeSuccess = await setOpenCodeAuth(providerId, validated.apiKey)
const openCodeSuccess = await openCodeClient.setProviderAuth(providerId, validated.apiKey)
if (!openCodeSuccess) {
logger.warn(`Failed to set OpenCode auth for ${providerId}, saving locally only`)
}
@@ -156,7 +156,7 @@ export function createProvidersRoutes(db: Database, openCodeSupervisor?: OpenCod
try {
const providerId = c.req.param('id')
const openCodeSuccess = await deleteOpenCodeAuth(providerId)
const openCodeSuccess = await openCodeClient.deleteProviderAuth(providerId)
if (!openCodeSuccess) {
logger.warn(`Failed to delete OpenCode auth for ${providerId}, removing locally only`)
}
+11 -7
View File
@@ -9,7 +9,7 @@ import { SettingsService } from '../services/settings'
import { writeFileContent } from '../services/file-operations'
import { opencodeServerManager } from '../services/opencode-single-server'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
import { proxyToOpenCodeWithDirectory } from '../services/proxy'
import type { OpenCodeClient } from '../services/opencode/client'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
@@ -34,6 +34,7 @@ export function createRepoRoutes(
database: Database,
gitAuthService: GitAuthService,
scheduleService: ScheduleService,
openCodeClient: OpenCodeClient,
openCodeSupervisor?: OpenCodeSupervisor,
) {
const app = new Hono()
@@ -373,11 +374,11 @@ app.get('/', async (c) => {
return c.json({ error: 'Repo not found' }, 404)
}
const response = await proxyToOpenCodeWithDirectory(
'/instance/dispose',
'POST',
repo.fullPath
)
const response = await openCodeClient.forward({
method: 'POST',
path: '/instance/dispose',
directory: repo.fullPath,
})
if (!response.ok) {
const errorText = await response.text()
@@ -421,8 +422,11 @@ app.get('/', async (c) => {
const body = await c.req.json().catch(() => ({}))
const options = AssistantModeInitRequestSchema.parse(body)
const protocol = c.req.header('x-forwarded-proto') || 'http'
const host = c.req.header('host') || 'localhost:5003'
const apiBaseUrl = `${protocol}://${host}/api/internal`
const status = await ensureAssistantMode(repo, options)
const status = await ensureAssistantMode(repo, { db: database, apiBaseUrl }, options)
return c.json(status)
} catch (error: unknown) {
logger.error('Failed to initialize assistant mode:', error)
+87 -41
View File
@@ -6,7 +6,8 @@ import { resolve, dirname } from 'path'
import type { Database } from 'bun:sqlite'
import { SettingsService } from '../services/settings'
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
import { patchOpenCodeConfig, proxyToOpenCodeWithDirectory } from '../services/proxy'
import { patchConfigWithRecovery } from '../services/opencode/config-recovery'
import type { OpenCodeClient } from '../services/opencode/client'
import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared/config/env'
import {
UserPreferencesSchema,
@@ -20,6 +21,7 @@ import {
} from '@opencode-manager/shared'
import { logger } from '../utils/logger'
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
import { sseAggregator } from '../services/sse-aggregator'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
import type { GitAuthService } from '../services/git-auth'
import { DEFAULT_AGENTS_MD } from '../constants'
@@ -28,6 +30,7 @@ import { encryptSecret } from '../utils/crypto'
import { compareVersions, isValidVersion } from '../utils/version-utils'
import { getImportedSessionDirectories, getOpenCodeImportStatus, OpenCodeImportProtectionError, syncOpenCodeImport } from '../services/opencode-import'
import { relinkReposFromSessionDirectories } from '../services/repo'
import { ENV } from '@opencode-manager/shared/config/env'
import {
listManagedSkills,
getSkill,
@@ -219,7 +222,7 @@ async function extractOpenCodeError(response: Response, defaultError: string): P
: defaultError
}
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService, openCodeSupervisor?: OpenCodeSupervisor) {
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
const app = new Hono()
const settingsService = new SettingsService(db)
@@ -234,19 +237,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
}
})
app.get('/memory-plugin-status', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configs = settingsService.getOpenCodeConfigs(userId)
const defaultConfig = configs.configs.find((cfg: { isDefault: boolean }) => cfg.isDefault)
const isEnabled = ((defaultConfig?.content?.plugin as string[] | undefined) ?? []).includes('@opencode-manager/memory')
return c.json({ memoryPluginEnabled: isEnabled })
} catch (error) {
logger.error('Failed to get memory plugin status:', error)
return c.json({ error: 'Failed to get memory plugin status' }, 500)
}
})
app.patch('/', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
@@ -371,7 +361,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
return c.json(config)
}
const patchResult = await patchOpenCodeConfig(provisionalConfig.content)
const patchResult = await patchConfigWithRecovery(openCodeClient, provisionalConfig.content)
if (!patchResult.success) {
settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId)
return c.json({
@@ -448,7 +438,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
opencodeServerManager.clearStartupError()
await restartOpenCode(openCodeSupervisor)
} else {
const patchResult = await patchOpenCodeConfig(config.content)
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
if (!patchResult.success) {
return c.json({
error: 'Config saved but failed to apply',
@@ -459,7 +449,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
}
const contentToWrite = patchResult.removedFields && patchResult.removedFields.length > 0
? JSON.stringify(config.content, null, 2)
? JSON.stringify(patchResult.appliedConfig ?? config.content, null, 2)
: config.rawContent
await writeFileContent(configPath, contentToWrite)
@@ -526,7 +516,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
return c.json(config)
}
const patchResult = await patchOpenCodeConfig(existingConfig.content)
const patchResult = await patchConfigWithRecovery(openCodeClient, existingConfig.content)
if (!patchResult.success) {
return c.json({
error: 'Config validation failed',
@@ -1137,7 +1127,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
return c.json({ error: 'Invalid repoId' }, 400)
}
const skills = await listManagedSkills(db, repoId)
const skills = await listManagedSkills(db, openCodeClient, repoId)
return c.json(skills)
} catch (error) {
logger.error('Failed to list skills:', error)
@@ -1159,7 +1149,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
return c.json({ error: 'repoId is required for project scope' }, 400)
}
const skill = await getSkill(db, name, scope, repoId)
const skill = await getSkill(db, openCodeClient, name, scope, repoId)
return c.json(skill)
} catch (error) {
logger.error('Failed to get skill:', error)
@@ -1219,7 +1209,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
return c.json({ error: 'repoId is required for project scope' }, 400)
}
const skill = await updateSkill(db, name, scope, validated, repoId)
const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId)
try {
await restartOpenCode(openCodeSupervisor)
@@ -1406,11 +1396,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const body = await c.req.json()
const { directory } = ConnectMcpDirectorySchema.parse(body)
const response = await proxyToOpenCodeWithDirectory(
`/mcp/${encodeURIComponent(serverName)}/connect`,
'POST',
directory
)
const response = await (openCodeClient).forward({
method: 'POST',
path: `/mcp/${encodeURIComponent(serverName)}/connect`,
directory,
})
if (!response.ok) {
const errorMsg = await extractOpenCodeError(response, 'Failed to connect MCP server')
@@ -1433,11 +1423,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const body = await c.req.json()
const { directory } = ConnectMcpDirectorySchema.parse(body)
const response = await proxyToOpenCodeWithDirectory(
`/mcp/${encodeURIComponent(serverName)}/disconnect`,
'POST',
directory
)
const response = await (openCodeClient).forward({
method: 'POST',
path: `/mcp/${encodeURIComponent(serverName)}/disconnect`,
directory,
})
if (!response.ok) {
const errorMsg = await extractOpenCodeError(response, 'Failed to disconnect MCP server')
@@ -1460,11 +1450,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const body = await c.req.json()
const { directory } = McpAuthDirectorySchema.parse(body)
const response = await proxyToOpenCodeWithDirectory(
`/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
'POST',
const response = await (openCodeClient).forward({
method: 'POST',
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
directory,
)
})
if (!response.ok) {
const errorMsg = await extractOpenCodeError(response, 'Failed to authenticate MCP server')
@@ -1487,11 +1477,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const body = await c.req.json()
const { directory } = ConnectMcpDirectorySchema.parse(body)
const response = await proxyToOpenCodeWithDirectory(
`/mcp/${encodeURIComponent(serverName)}/auth`,
'DELETE',
directory
)
const response = await (openCodeClient).forward({
method: 'DELETE',
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
directory,
})
if (!response.ok) {
const errorMsg = await extractOpenCodeError(response, 'Failed to remove MCP auth')
@@ -1508,5 +1498,61 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
}
})
const OpenCodeServerAuthBodySchema = z.object({
password: z.union([z.string().min(8), z.null()]),
})
app.get('/opencode-server-auth', async (c) => {
try {
const hasStored = settingsService.hasStoredOpenCodeServerPassword()
const source = hasStored ? 'db' : ENV.OPENCODE.SERVER_PASSWORD ? 'env' : 'none'
const isSet = source !== 'none'
return c.json({ isSet, source })
} catch (error) {
logger.error('Failed to get OpenCode server auth status:', error)
return c.json({ error: 'Failed to get OpenCode server auth status' }, 500)
}
})
app.patch('/opencode-server-auth', async (c) => {
try {
const body = await c.req.json()
const validated = OpenCodeServerAuthBodySchema.parse(body)
const previousPasswordState = settingsService.getStoredOpenCodeServerPasswordState()
if (validated.password === null) {
settingsService.clearOpenCodeServerPassword()
} else if (validated.password) {
settingsService.setOpenCodeServerPassword(validated.password)
}
try {
await opencodeServerManager.restart()
} catch (restartError) {
try {
settingsService.restoreOpenCodeServerPasswordState(previousPasswordState)
await opencodeServerManager.restart()
sseAggregator.reconnect()
} catch (restoreError) {
logger.error('Failed to restore OpenCode server auth runtime after restart failure:', restoreError)
}
throw restartError
}
sseAggregator.reconnect()
const hasStored = settingsService.hasStoredOpenCodeServerPassword()
const source = hasStored ? 'db' : ENV.OPENCODE.SERVER_PASSWORD ? 'env' : 'none'
const isSet = source !== 'none'
return c.json({ isSet, source })
} catch (error) {
logger.error('Failed to update OpenCode server auth:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to update OpenCode server auth' }, 500)
}
})
return app
}
+431 -4
View File
@@ -12,12 +12,21 @@ import {
ensureDirectoryExists,
} from './file-operations'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import { getOrCreateInternalToken } from './internal-token'
const ASSISTANT_MODE_DIR = 'assistant'
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
const ASSISTANT_OPENCODE_DIR = '.opencode'
const ASSISTANT_INTERNAL_TOKEN_FILENAME = 'internal-token'
const ASSISTANT_SKILLS_DIR = 'skills'
const ASSISTANT_SCHEDULES_SKILL_DIR = 'schedule-management'
const ASSISTANT_NOTIFICATIONS_SKILL_DIR = 'notifications'
const ASSISTANT_SETTINGS_SKILL_DIR = 'manager-settings'
const ASSISTANT_SKILL_FILENAME = 'SKILL.md'
export function getAssistantModeDirectory(): string {
const reposPath = getReposPath()
@@ -32,6 +41,22 @@ export function getAssistantModeDirectory(): string {
return resolvedAssistantDir
}
function getInternalTokenPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_INTERNAL_TOKEN_FILENAME)
}
function getSchedulesSkillPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SCHEDULES_SKILL_DIR, ASSISTANT_SKILL_FILENAME)
}
function getNotificationsSkillPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_NOTIFICATIONS_SKILL_DIR, ASSISTANT_SKILL_FILENAME)
}
function getSettingsSkillPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SETTINGS_SKILL_DIR, ASSISTANT_SKILL_FILENAME)
}
export function buildAssistantAgentsMd(): string {
return `# Assistant Mode Instructions
@@ -63,6 +88,327 @@ The agent MAY self-edit the following files within this workspace:
2. Update AGENTS.md when learning durable preferences
3. Maintain version control awareness
4. Document significant changes in commit messages
## Schedule Management
This workspace ships a workspace-scoped skill at \`.opencode/skills/schedule-management/SKILL.md\` that documents how to list, create, update, delete, run, inspect, and cancel schedule jobs and runs across any repo via the internal HTTP API. Load it whenever the user asks about schedules.
## Notifications
This workspace includes a skill at \`.opencode/skills/notifications/SKILL.md\` for sending push notifications to the user's registered devices via the internal HTTP API. Load it when you need to notify the user about important events.
## Settings Management
This workspace includes a skill at \`.opencode/skills/manager-settings/SKILL.md\` for reading and safely modifying user preferences via the internal HTTP API. Load it when you need to inspect or update UI settings.
`
}
function toLocalhostInternalBaseUrl(baseUrl: string): string {
const url = new URL(baseUrl)
url.protocol = 'http'
url.hostname = 'localhost'
url.port = String(ENV.SERVER.PORT)
return url.toString().replace(/\/$/, '')
}
export function buildSchedulesSkill(baseUrl: string): string {
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
return `---
name: schedule-management
description: Manage schedule jobs and runs across any repo via the internal HTTP API
---
## When to Load
Load this skill when the user asks about managing schedules, schedule jobs, schedule runs, or anything related to automated task execution across repos.
## Authentication
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
\`\`\`
Authorization: Bearer <token>
\`\`\`
## Base URL
\`${internalBaseUrl}\`
## Endpoints
### GET /schedules/all
List all schedule jobs across all repos.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/schedules/all
\`\`\`
### GET /schedules/all/runs
List all schedule runs across all repos with optional filtering.
Query params: \`limit\`, \`offset\`, \`status\`, \`repoId\`, \`jobId\`, \`triggerSource\`
\`\`\`bash
curl -H "Authorization: Bearer <token>" "${internalBaseUrl}/schedules/all/runs?limit=20"
\`\`\`
### GET /repos/:repoId/schedules
List all schedule jobs for a specific repo.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules
\`\`\`
### POST /repos/:repoId/schedules
Create a new schedule job.
Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`scheduleMode: 'interval' | 'cron'\`).
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \\
-d '{"name":"my-job","prompt":"do something","scheduleMode":"interval","intervalMinutes":60}' \\
${internalBaseUrl}/repos/:repoId/schedules
\`\`\`
### GET /repos/:repoId/schedules/:jobId
Get a specific schedule job.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId
\`\`\`
### PATCH /repos/:repoId/schedules/:jobId
Update an existing schedule job.
Body matches \`UpdateScheduleJobRequest\` schema.
\`\`\`bash
curl -X PATCH -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \\
-d '{"enabled":false}' \\
${internalBaseUrl}/repos/:repoId/schedules/:jobId
\`\`\`
### DELETE /repos/:repoId/schedules/:jobId
Delete a schedule job.
\`\`\`bash
curl -X DELETE -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId
\`\`\`
### POST /repos/:repoId/schedules/:jobId/run
Manually trigger a schedule job.
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/run
\`\`\`
### GET /repos/:repoId/schedules/:jobId/runs
List runs for a specific job.
Query params: \`limit\`
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/runs?limit=20
\`\`\`
### GET /repos/:repoId/schedules/:jobId/runs/:runId
Get a specific schedule run.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/runs/:runId
\`\`\`
### POST /repos/:repoId/schedules/:jobId/runs/:runId/cancel
Cancel a running schedule run.
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/runs/:runId/cancel
\`\`\`
## Safety
Always confirm destructive operations (\`DELETE\` jobs, \`cancel\` runs) with the user before executing.
`
}
export function buildNotificationsSkill(baseUrl: string): string {
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
return `---
name: notifications
description: Send push notifications to the user's registered devices via the internal HTTP API
---
## When to Load
Load this skill when you need to notify the user about important events, completed tasks, or questions that require their attention.
## Authentication
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
\`\`\`
Authorization: Bearer <token>
\`\`\`
## Base URL
\`${internalBaseUrl}\`
## Endpoint
### POST /notifications/send
Send a push notification to all of the user's registered devices.
**Query Parameters:**
- \`userId\` (optional): User ID. Defaults to \`"default"\`.
**Request Body:**
\`\`\`ts
{
title: string // 1-120 characters
body: string // 1-500 characters
url?: string // Optional: deep link to navigate to (1-500 chars)
tag?: string // Optional: notification tag for deduplication (max 80 chars)
priority?: 'normal' | 'high' // Defaults to 'normal'
}
\`\`\`
**Example:**
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" \\
-H "Content-Type: application/json" \\
-d '{"title":"Task Complete","body":"The build has finished successfully","url":"/repos/my-repo","priority":"high"}' \\
"${internalBaseUrl}/notifications/send?userId=default"
\`\`\`
**Response:**
\`\`\`ts
{
delivered: number // Number of successfully delivered notifications
expired: number // Number of expired subscriptions removed
failed: number // Number of failed deliveries
noSubscriptions: boolean // True if user has no registered devices
}
\`\`\`
## Rate Limiting
The endpoint enforces a rate limit of **10 requests per minute per token**. If exceeded, you'll receive a \`429 Too Many Requests\` response with a \`Retry-After\` header.
## Notes
- Notifications are only sent if the user has registered devices (browser push subscriptions)
- If VAPID is not configured on the server, the endpoint returns \`503 Service Unavailable\`
- Use \`priority: 'high'\` for urgent notifications that should interrupt the user
`
}
export function buildSettingsSkill(baseUrl: string): string {
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
return `---
name: manager-settings
description: Read and modify safe user preferences via the internal HTTP API
---
## When to Load
Load this skill when you need to inspect or update the user's UI preferences, theme, mode, or other non-sensitive settings.
## Authentication
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
\`\`\`
Authorization: Bearer <token>
\`\`\`
## Base URL
\`${internalBaseUrl}\`
## Endpoints
### GET /settings
Retrieve the user's full settings, including all preferences.
**Query Parameters:**
- \`userId\` (optional): User ID. Defaults to \`"default"\`.
**Example:**
\`\`\`bash
curl -H "Authorization: Bearer <token>" "${internalBaseUrl}/settings?userId=default"
\`\`\`
**Response:**
\`\`\`ts
{
preferences: {
theme: 'dark' | 'light' | 'system',
mode: 'plan' | 'build',
defaultModel?: string,
defaultAgent?: string,
autoScroll: boolean,
expandDiffs: boolean,
expandToolCalls: boolean,
showReasoning: boolean,
simpleChatMode: boolean,
leaderKey?: string,
directShortcuts?: string[],
keyboardShortcuts: Record<string, string>,
customCommands: Array<{ name: string; description: string; promptTemplate: string }>,
notifications?: { enabled: boolean; ... },
repoOrder?: number[],
repoSortMode: 'recent' | 'manual' | 'name',
// ... other safe preferences
},
updatedAt: number
}
\`\`\`
### PATCH /settings
Update a subset of safe user preferences.
**Allowed Keys:**
The following preference keys can be modified:
- \`theme\`, \`mode\`, \`defaultModel\`, \`defaultAgent\`
- \`autoScroll\`, \`expandDiffs\`, \`expandToolCalls\`, \`showReasoning\`
- \`simpleChatMode\`, \`leaderKey\`, \`directShortcuts\`
- \`keyboardShortcuts\`, \`customCommands\`, \`notifications\`
- \`repoOrder\`, \`repoSortMode\`
**DO NOT attempt to set:**
- \`gitCredentials\` - Git credentials must be managed via the full UI
- \`gitIdentity\` - Git identity must be managed via the full UI
- \`tts.apiKey\` - TTS credentials must be managed via the full UI
- \`stt.apiKey\` - STT credentials must be managed via the full UI
- \`lastKnownGoodConfig\` - Internal state, do not modify
- Any other keys not in the allowed list above
**Request Body:**
Partial object with any of the allowed keys.
**Example:**
\`\`\`bash
curl -X PATCH -H "Authorization: Bearer <token>" \\
-H "Content-Type: application/json" \\
-d '{"theme":"dark","mode":"build"}' \\
"${internalBaseUrl}/settings?userId=default"
\`\`\`
**Response:**
Returns the updated settings object with the same structure as GET.
## Safety
- This API intentionally rejects any attempt to modify credentials, API keys, or other sensitive settings
- If you need to change credentials (Git, TTS, STT, etc.), guide the user to use the full UI
- The settings PATCH endpoint does NOT trigger OpenCode reload or restart
`
}
@@ -92,7 +438,8 @@ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
export async function ensureAssistantMode(
repo: Repo,
options?: AssistantModeInitRequest
deps: { db: Database; apiBaseUrl: string },
options?: AssistantModeInitRequest,
): Promise<AssistantModeStatus> {
const assistantDir = getAssistantModeDirectory()
@@ -100,6 +447,8 @@ export async function ensureAssistantMode(
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
const tokenPath = getInternalTokenPath(assistantDir)
const skillPath = getSchedulesSkillPath(assistantDir)
const agentsMdExists = await fileExists(agentsMdPath)
const opencodeJsonExists = await fileExists(opencodeJsonPath)
@@ -119,6 +468,41 @@ export async function ensureAssistantMode(
await writeFileContent(opencodeJsonPath, JSON.stringify(config, null, 2))
}
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR))
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SCHEDULES_SKILL_DIR))
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_NOTIFICATIONS_SKILL_DIR))
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SETTINGS_SKILL_DIR))
const token = getOrCreateInternalToken(deps.db)
const existingTokenContent = await fileExists(tokenPath) ? await readFileContent(tokenPath) : undefined
const tokenCreated = !existingTokenContent || existingTokenContent.trim() !== token
if (tokenCreated) {
await writeFileContent(tokenPath, token)
}
const schedulesSkillContent = buildSchedulesSkill(deps.apiBaseUrl)
const existingSchedulesSkillContent = await fileExists(skillPath) ? await readFileContent(skillPath) : undefined
const schedulesSkillCreated = !existingSchedulesSkillContent || existingSchedulesSkillContent !== schedulesSkillContent
if (schedulesSkillCreated) {
await writeFileContent(skillPath, schedulesSkillContent)
}
const notificationsSkillPath = getNotificationsSkillPath(assistantDir)
const notificationsSkillContent = buildNotificationsSkill(deps.apiBaseUrl)
const existingNotificationsSkillContent = await fileExists(notificationsSkillPath) ? await readFileContent(notificationsSkillPath) : undefined
const notificationsSkillCreated = !existingNotificationsSkillContent || existingNotificationsSkillContent !== notificationsSkillContent
if (notificationsSkillCreated) {
await writeFileContent(notificationsSkillPath, notificationsSkillContent)
}
const settingsSkillPath = getSettingsSkillPath(assistantDir)
const settingsSkillContent = buildSettingsSkill(deps.apiBaseUrl)
const existingSettingsSkillContent = await fileExists(settingsSkillPath) ? await readFileContent(settingsSkillPath) : undefined
const settingsSkillCreated = !existingSettingsSkillContent || existingSettingsSkillContent !== settingsSkillContent
if (settingsSkillCreated) {
await writeFileContent(settingsSkillPath, settingsSkillContent)
}
return {
repoId: repo.id,
directory: assistantDir,
@@ -135,14 +519,33 @@ export async function ensureAssistantMode(
created: !opencodeJsonExists || overwriteOpenCodeConfig || hasLegacyOpenCodeConfig,
},
},
internalToken: {
path: tokenPath,
created: tokenCreated,
},
schedulesSkill: {
path: skillPath,
created: schedulesSkillCreated,
},
notificationsSkill: {
path: notificationsSkillPath,
created: notificationsSkillCreated,
},
settingsSkill: {
path: settingsSkillPath,
created: settingsSkillCreated,
},
}
}
async function isLegacyAssistantOpenCodeConfig(opencodeJsonPath: string): Promise<boolean> {
try {
const content = await readFileContent(opencodeJsonPath)
const config = JSON.parse(content) as { permission?: { allow?: unknown; ask?: unknown } }
return Array.isArray(config.permission?.allow) || Array.isArray(config.permission?.ask)
const config = JSON.parse(content) as {
permission?: { allow?: unknown; ask?: unknown }
}
if (Array.isArray(config.permission?.allow) || Array.isArray(config.permission?.ask)) return true
return false
} catch {
return false
}
@@ -153,9 +556,17 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
const tokenPath = getInternalTokenPath(assistantDir)
const skillPath = getSchedulesSkillPath(assistantDir)
const notificationsSkillPath = getNotificationsSkillPath(assistantDir)
const settingsSkillPath = getSettingsSkillPath(assistantDir)
const agentsMdExists = await fileExists(agentsMdPath)
const opencodeJsonExists = await fileExists(opencodeJsonPath)
await fileExists(tokenPath)
await fileExists(skillPath)
await fileExists(notificationsSkillPath)
await fileExists(settingsSkillPath)
return {
repoId: repo.id,
@@ -173,5 +584,21 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
created: false,
},
},
internalToken: {
path: tokenPath,
created: false,
},
schedulesSkill: {
path: skillPath,
created: false,
},
notificationsSkill: {
path: notificationsSkillPath,
created: false,
},
settingsSkill: {
path: settingsSkillPath,
created: false,
},
}
}
+23
View File
@@ -0,0 +1,23 @@
import type { Database } from 'bun:sqlite'
import { randomBytes } from 'node:crypto'
const KEY = 'internal_token'
export function getOrCreateInternalToken(db: Database): string {
const row = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get(KEY) as { value: string } | undefined
if (row) return row.value
const token = randomBytes(32).toString('hex')
const now = Date.now()
db.prepare('INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)').run(KEY, token, now, now)
return token
}
export function rotateInternalToken(db: Database): string {
const token = randomBytes(32).toString('hex')
const now = Date.now()
db.prepare(`
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
`).run(KEY, token, now, now)
return token
}
+14 -2
View File
@@ -263,12 +263,14 @@ export class NotificationService {
});
}
private async sendToUser(
async sendToUser(
userId: string,
payload: PushNotificationPayload
): Promise<void> {
): Promise<{ delivered: number; expired: number; failed: number; total: number }> {
const subscriptions = this.getSubscriptions(userId);
const expiredEndpoints: string[] = [];
let delivered = 0
let failed = 0
await Promise.allSettled(
subscriptions.map(async (sub) => {
@@ -286,6 +288,8 @@ export class NotificationService {
"UPDATE push_subscriptions SET last_used_at = ? WHERE id = ?"
)
.run(Date.now(), sub.id);
delivered++
} catch (error) {
const statusCode = (error as { statusCode?: number }).statusCode;
@@ -293,6 +297,7 @@ export class NotificationService {
expiredEndpoints.push(sub.endpoint);
} else {
logger.error(`Push delivery failed for ${sub.endpoint.slice(0, 50)}:`, error);
failed++
}
}
})
@@ -301,5 +306,12 @@ export class NotificationService {
for (const endpoint of expiredEndpoints) {
this.removeSubscription(endpoint);
}
return {
delivered,
expired: expiredEndpoints.length,
failed,
total: subscriptions.length,
}
}
}
+8 -21
View File
@@ -1,4 +1,4 @@
import { proxyToOpenCodeWithDirectory } from './proxy'
import type { OpenCodeClient } from './opencode/client'
interface OpenCodeConfigResponse {
model?: string
@@ -63,29 +63,16 @@ function uniqueCandidates(candidates: Array<string | null | undefined>): string[
return [...new Set(normalizedCandidates)]
}
async function fetchOpenCodeConfig(directory?: string): Promise<OpenCodeConfigResponse> {
const response = await proxyToOpenCodeWithDirectory('/config', 'GET', directory)
if (!response.ok) {
const errorText = await response.text()
throw new Error(errorText || 'Failed to fetch OpenCode config')
}
return await response.json() as OpenCodeConfigResponse
async function fetchOpenCodeConfig(client: OpenCodeClient, directory?: string): Promise<OpenCodeConfigResponse> {
return client.getJson<OpenCodeConfigResponse>('/config', { directory })
}
async function fetchOpenCodeProviders(directory?: string): Promise<OpenCodeProviderResponse> {
const response = await proxyToOpenCodeWithDirectory('/config/providers', 'GET', directory)
if (!response.ok) {
const errorText = await response.text()
throw new Error(errorText || 'Failed to fetch OpenCode providers')
}
return await response.json() as OpenCodeProviderResponse
async function fetchOpenCodeProviders(client: OpenCodeClient, directory?: string): Promise<OpenCodeProviderResponse> {
return client.getJson<OpenCodeProviderResponse>('/config/providers', { directory })
}
export async function resolveOpenCodeModel(
client: OpenCodeClient,
directory: string | undefined,
options?: {
preferredModel?: string | null
@@ -93,8 +80,8 @@ export async function resolveOpenCodeModel(
},
): Promise<ResolvedOpenCodeModel> {
const [config, providersResponse] = await Promise.all([
fetchOpenCodeConfig(directory),
fetchOpenCodeProviders(directory),
fetchOpenCodeConfig(client, directory),
fetchOpenCodeProviders(client, directory),
])
const availableModels = buildAvailableModels(providersResponse)
+69 -25
View File
@@ -20,18 +20,15 @@ import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-mana
import { parseJsonc } from '@opencode-manager/shared/utils'
import type { Database } from 'bun:sqlite'
import { compareVersions } from '../utils/version-utils'
import { patchOpenCodeConfig } from './proxy'
import { patchConfigWithRecovery } from './opencode/config-recovery'
import type { OpenCodeClient } from './opencode/client'
import { writeFileContent } from './file-operations'
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
: ''
export const OPENCODE_SERVER_CONNECT_HOST = OPENCODE_SERVER_HOST === '0.0.0.0' ? '127.0.0.1' : OPENCODE_SERVER_HOST
const MIN_OPENCODE_VERSION = '1.0.137'
const MAX_STDERR_SIZE = 10240
const HEALTH_CHECK_TIMEOUT_MS = 3000
type StartupValidationIssue = {
path: string
@@ -91,6 +88,10 @@ function formatStartupError(stderrOutput: string, fallback: string): string {
// This allows proper mocking in tests
const getOpenCodeServerDirectory = () => getWorkspacePath()
const getOpenCodeConfigPath = () => getOpenCodeConfigFilePath()
const getOpenCodeServerPort = () => ENV.OPENCODE.PORT
const getOpenCodeServerHost = () => ENV.OPENCODE.HOST
const getOpenCodeServerPublicUrl = () => ENV.OPENCODE.PUBLIC_URL
const getOpenCodeServerUsername = () => ENV.OPENCODE.SERVER_USERNAME
class OpenCodeServerManager {
private static instance: OpenCodeServerManager
@@ -101,6 +102,7 @@ class OpenCodeServerManager {
private version: string | null = null
private lastStartupError: string | null = null
private opInProgress: boolean = false
private openCodeClient: OpenCodeClient | null = null
private constructor() {}
@@ -108,6 +110,31 @@ class OpenCodeServerManager {
this.db = db
}
setOpenCodeClient(client: OpenCodeClient) {
this.openCodeClient = client
}
async rebuildClient(): Promise<void> {
const password = this.getResolvedPassword()
const { createOpenCodeClient } = await import('./opencode/client')
this.openCodeClient = createOpenCodeClient(password)
}
private getResolvedPassword(): string {
if (this.db) {
const settingsService = new SettingsService(this.db)
return settingsService.getOpenCodeServerPassword()
}
return ENV.OPENCODE.SERVER_PASSWORD
}
private requireClient(): OpenCodeClient {
if (!this.openCodeClient) {
throw new Error('OpenCodeClient not configured on OpenCodeServerManager. Call setOpenCodeClient() during startup.')
}
return this.openCodeClient
}
static getInstance(): OpenCodeServerManager {
if (!OpenCodeServerManager.instance) {
OpenCodeServerManager.instance = new OpenCodeServerManager()
@@ -154,7 +181,18 @@ class OpenCodeServerManager {
return
}
await this.rebuildClient()
const isDevelopment = ENV.SERVER.NODE_ENV !== 'production'
const password = this.getResolvedPassword()
const openCodeServerHost = getOpenCodeServerHost()
const isExposed = openCodeServerHost !== '127.0.0.1' && openCodeServerHost !== 'localhost'
if (isExposed && !password) {
const msg = `OPENCODE_HOST=${openCodeServerHost} exposes the OpenCode server externally but no password is configured. Set OPENCODE_SERVER_PASSWORD env var or configure a password via Settings → OpenCode → Server Auth.`
this.lastStartupError = msg
logger.error(msg)
throw new Error(msg)
}
let gitCredentials: GitCredential[] = []
let gitIdentityEnv: Record<string, string> = {}
@@ -174,9 +212,10 @@ class OpenCodeServerManager {
}
}
const existingProcesses = await this.findProcessesByPort(OPENCODE_SERVER_PORT)
const openCodeServerPort = getOpenCodeServerPort()
const existingProcesses = await this.findProcessesByPort(openCodeServerPort)
if (existingProcesses.length > 0) {
logger.info(`OpenCode server already running on port ${OPENCODE_SERVER_PORT}`)
logger.info(`OpenCode server already running on port ${openCodeServerPort}`)
const healthy = await this.checkHealth()
if (healthy) {
if (isDevelopment) {
@@ -276,7 +315,7 @@ class OpenCodeServerManager {
this.serverProcess = spawn(
'opencode',
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', OPENCODE_SERVER_HOST],
['serve', '--port', openCodeServerPort.toString(), '--hostname', openCodeServerHost],
{
cwd: openCodeServerDirectory,
detached: !isDevelopment,
@@ -289,11 +328,11 @@ class OpenCodeServerManager {
XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
XDG_STATE_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'),
...(OPENCODE_SERVER_PUBLIC_URL ? { OPENCODE_PUBLIC_URL: OPENCODE_SERVER_PUBLIC_URL } : {}),
...(OPENCODE_SERVER_PASSWORD
...(getOpenCodeServerPublicUrl() ? { OPENCODE_PUBLIC_URL: getOpenCodeServerPublicUrl() } : {}),
...(password
? {
OPENCODE_SERVER_PASSWORD,
OPENCODE_SERVER_USERNAME,
OPENCODE_SERVER_PASSWORD: password,
OPENCODE_SERVER_USERNAME: getOpenCodeServerUsername(),
}
: {}),
OPENCODE_CONFIG: openCodeConfigPath,
@@ -480,10 +519,10 @@ class OpenCodeServerManager {
try {
const configPath = getOpenCodeConfigFilePath()
const fileContent = await fs.readFile(configPath, 'utf-8')
const fileConfig = JSON.parse(fileContent) as Record<string, unknown>
const fileConfig = parseJsonc(fileContent) as Record<string, unknown>
logger.info(`Read config from file for reload: ${configPath}`)
const patchResult = await patchOpenCodeConfig(fileConfig)
const patchResult = await patchConfigWithRecovery(this.requireClient(), fileConfig)
if (!patchResult.success) {
const errorMessage = patchResult.error || 'Failed to reload config'
const validationIssues = patchResult.details || []
@@ -498,6 +537,11 @@ class OpenCodeServerManager {
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
}
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
await writeFileContent(configPath, JSON.stringify(patchResult.appliedConfig, null, 2))
logger.info(`Persisted cleaned config to ${configPath} after removing fields: ${patchResult.removedFields.join(', ')}`)
}
logger.info('OpenCode configuration reloaded successfully')
await new Promise(r => setTimeout(r, 500))
const healthy = await this.checkHealth()
@@ -514,7 +558,7 @@ class OpenCodeServerManager {
}
getPort(): number {
return OPENCODE_SERVER_PORT
return getOpenCodeServerPort()
}
getVersion(): string | null {
@@ -544,14 +588,14 @@ class OpenCodeServerManager {
}
async checkHealth(): Promise<boolean> {
if (!this.openCodeClient) {
return false
}
try {
const headers: Record<string, string> = {}
if (OPENCODE_BASIC_AUTH) {
headers.Authorization = OPENCODE_BASIC_AUTH
}
const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/doc`, {
signal: AbortSignal.timeout(3000),
headers
const response = await this.openCodeClient.forward({
method: 'GET',
path: '/doc',
signal: AbortSignal.timeout(HEALTH_CHECK_TIMEOUT_MS),
})
return response.ok
} catch {
+18
View File
@@ -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}`
}
+259
View File
@@ -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 })
}
@@ -1,63 +1,7 @@
import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import type { OpenCodeClient } from './client'
import { logger } from '../../utils/logger'
import { parseJsonc } from '@opencode-manager/shared/utils'
export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
: ''
export function withOpenCodeAuth(headers: Record<string, string> = {}): Record<string, string> {
if (OPENCODE_BASIC_AUTH) {
return { ...headers, Authorization: OPENCODE_BASIC_AUTH }
}
return headers
}
export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise<boolean> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
method: 'PUT',
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ type: 'api', key: apiKey }),
})
if (response.ok) {
logger.info(`Set OpenCode auth for provider: ${providerId}`)
return true
}
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
return false
} catch (error) {
logger.error('Failed to set OpenCode auth:', error)
return false
}
}
export async function deleteOpenCodeAuth(providerId: string): Promise<boolean> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
method: 'DELETE',
headers: withOpenCodeAuth(),
})
if (response.ok) {
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
return true
}
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
return false
} catch (error) {
logger.error('Failed to delete OpenCode auth:', error)
return false
}
}
export type PatchConfigValidationIssue = {
path: string
message: string
@@ -206,12 +150,16 @@ function parseErrorResponse(responseText: string): { details: PatchConfigValidat
return { details, errorMessage }
}
export async function patchOpenCodeConfig(config: Record<string, unknown>): Promise<PatchConfigResult> {
export async function patchConfigWithRecovery(
client: OpenCodeClient,
config: Record<string, unknown>,
): Promise<PatchConfigResult> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
const response = await client.forward({
method: 'PATCH',
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
path: '/config',
body: JSON.stringify(config),
headers: { 'Content-Type': 'application/json' },
})
if (response.ok) {
@@ -254,10 +202,11 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
}
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
const retryResponse = await fetch(`${OPENCODE_SERVER_URL}/config`, {
const retryResponse = await client.forward({
method: 'PATCH',
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
path: '/config',
body: JSON.stringify(cleanedConfig),
headers: { 'Content-Type': 'application/json' },
})
if (retryResponse.ok) {
@@ -286,156 +235,3 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
return { success: false, error: errorMessage }
}
}
export async function proxyRequest(request: Request) {
const url = new URL(request.url)
// Remove /api/opencode prefix from pathname before forwarding
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}`
if (url.pathname.includes('/permissions/')) {
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${targetUrl}`)
}
try {
const headers: Record<string, string> = {}
request.headers.forEach((value, key) => {
if (!['host', 'connection', 'authorization'].includes(key.toLowerCase())) {
headers[key] = value
}
})
const response = await fetch(targetUrl, {
method: request.method,
headers: withOpenCodeAuth(headers),
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
})
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
const body = await response.text()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} catch (error) {
logger.error(`Proxy request failed for ${url.pathname}${url.search}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
export async function proxyToOpenCodeWithDirectory(
path: string,
method: string,
directory: string | undefined,
body?: string,
headers?: Record<string, string>
): Promise<Response> {
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
if (directory) {
url.searchParams.set('directory', directory)
}
try {
const response = await fetch(url.toString(), {
method,
headers: withOpenCodeAuth(headers || { 'Content-Type': 'application/json' }),
body,
})
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} catch (error) {
logger.error(`Proxy to OpenCode failed for ${path}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
export async function proxyMcpAuthStart(
serverName: string,
directory: string | undefined,
): Promise<Response> {
const path = `/mcp/${encodeURIComponent(serverName)}/auth`
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
if (directory) {
url.searchParams.set('directory', directory)
}
try {
const response = await fetch(url.toString(), {
method: 'POST',
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
})
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
})
} catch (error) {
logger.error(`MCP auth start failed for ${serverName}:`, error)
return new Response(JSON.stringify({ error: 'MCP auth start failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
export async function proxyMcpAuthAuthenticate(
serverName: string,
directory: string | undefined,
): Promise<Response> {
const path = `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
if (directory) {
url.searchParams.set('directory', directory)
}
try {
const response = await fetch(url.toString(), {
method: 'POST',
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
})
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
})
} catch (error) {
logger.error(`MCP auth authenticate failed for ${serverName}:`, error)
return new Response(JSON.stringify({ error: 'MCP auth authenticate failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
-334
View File
@@ -1,334 +0,0 @@
import { Database } from 'bun:sqlite'
import path from 'path'
import { existsSync } from 'node:fs'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
export interface PluginMemory {
id: number
projectId: string
scope: 'convention' | 'decision' | 'context'
content: string
filePath: string | null
accessCount: number
lastAccessedAt: number | null
createdAt: number
updatedAt: number
}
interface DbMemoryRow {
id: number
project_id: string
scope: string
content: string
file_path: string | null
access_count: number
last_accessed_at: number | null
created_at: number
updated_at: number
}
interface DbKvRow {
project_id: string
key: string
data: string
expires_at: number
created_at: number
updated_at: number
}
interface MemoryFilters {
scope?: 'convention' | 'decision' | 'context'
content?: string
limit?: number
offset?: number
}
function getPluginDbPath(): string {
return path.join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
}
function mapRowToMemory(row: DbMemoryRow): PluginMemory {
return {
id: row.id,
projectId: row.project_id,
scope: row.scope as PluginMemory['scope'],
content: row.content,
filePath: row.file_path,
accessCount: row.access_count,
lastAccessedAt: row.last_accessed_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
function mapRowToKvEntry(row: DbKvRow): { key: string; data: unknown; createdAt: number; updatedAt: number; expiresAt: number } {
let data: unknown = null
try {
data = JSON.parse(row.data)
} catch {
data = row.data
}
return {
key: row.key,
data,
createdAt: row.created_at,
updatedAt: row.updated_at,
expiresAt: row.expires_at,
}
}
export class PluginMemoryService {
private db: Database | null = null
getDb(): Database | null {
if (this.db) return this.db
const dbPath = getPluginDbPath()
if (!existsSync(dbPath)) {
return null
}
try {
this.db = new Database(dbPath)
this.db.exec('PRAGMA journal_mode = WAL')
return this.db
} catch {
return null
}
}
list(projectId: string, filters?: MemoryFilters): PluginMemory[] {
const db = this.getDb()
if (!db) return []
let sql = 'SELECT * FROM memories WHERE project_id = ?'
const params: (string | number)[] = [projectId]
if (filters?.scope) {
sql += ' AND scope = ?'
params.push(filters.scope)
}
if (filters?.content) {
sql += ' AND content LIKE ?'
params.push(`%${filters.content}%`)
}
sql += ' ORDER BY updated_at DESC'
if (filters?.limit) {
sql += ' LIMIT ?'
params.push(filters.limit)
}
if (filters?.offset) {
sql += ' OFFSET ?'
params.push(filters.offset)
}
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbMemoryRow[]
return rows.map(mapRowToMemory)
}
listAll(filters?: { projectId?: string; scope?: string; limit?: number; offset?: number }): PluginMemory[] {
const db = this.getDb()
if (!db) return []
let sql = 'SELECT * FROM memories WHERE 1=1'
const params: (string | number)[] = []
if (filters?.projectId) {
sql += ' AND project_id = ?'
params.push(filters.projectId)
}
if (filters?.scope) {
sql += ' AND scope = ?'
params.push(filters.scope)
}
sql += ' ORDER BY updated_at DESC'
if (filters?.limit) {
sql += ' LIMIT ?'
params.push(filters.limit)
}
if (filters?.offset) {
sql += ' OFFSET ?'
params.push(filters.offset)
}
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbMemoryRow[]
return rows.map(mapRowToMemory)
}
getById(id: number): PluginMemory | undefined {
const db = this.getDb()
if (!db) return undefined
const stmt = db.prepare('SELECT * FROM memories WHERE id = ?')
const row = stmt.get(id) as DbMemoryRow | undefined
return row ? mapRowToMemory(row) : undefined
}
create(input: { projectId: string; scope: string; content: string }): number {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const now = Date.now()
const stmt = db.prepare(`
INSERT INTO memories (project_id, scope, content, access_count, created_at, updated_at)
VALUES (?, ?, ?, 0, ?, ?)
`)
const result = stmt.run(input.projectId, input.scope, input.content, now, now)
return result.lastInsertRowid as number
}
update(id: number, input: { content?: string; scope?: string }): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const updates: string[] = []
const params: (string | number)[] = []
if (input.content !== undefined) {
updates.push('content = ?')
params.push(input.content)
}
if (input.scope !== undefined) {
updates.push('scope = ?')
params.push(input.scope)
}
if (updates.length === 0) return
updates.push('updated_at = ?')
params.push(Date.now())
params.push(id)
const sql = `UPDATE memories SET ${updates.join(', ')} WHERE id = ?`
const stmt = db.prepare(sql)
stmt.run(...params)
try {
const deleteEmbeddings = db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?')
deleteEmbeddings.run(id)
} catch {
// table may not exist
}
}
delete(id: number): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
try {
const deleteEmbeddings = db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?')
deleteEmbeddings.run(id)
} catch {
// table may not exist
}
const stmt = db.prepare('DELETE FROM memories WHERE id = ?')
stmt.run(id)
}
getStats(projectId: string): { projectId: string; total: number; byScope: Record<string, number> } {
const db = this.getDb()
if (!db) {
return { projectId, total: 0, byScope: {} }
}
const totalStmt = db.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?')
const totalResult = totalStmt.get(projectId) as { count: number }
const total = totalResult.count
const byScopeStmt = db.prepare('SELECT scope, COUNT(*) as count FROM memories WHERE project_id = ? GROUP BY scope')
const byScopeRows = byScopeStmt.all(projectId) as { scope: string; count: number }[]
const byScope: Record<string, number> = {}
for (const row of byScopeRows) {
byScope[row.scope] = row.count
}
return { projectId, total, byScope }
}
listKv(projectId: string, prefix?: string): { key: string; data: unknown; createdAt: number; updatedAt: number; expiresAt: number }[] {
const db = this.getDb()
if (!db) return []
const now = Date.now()
let sql = 'SELECT project_id, key, data, expires_at, created_at, updated_at FROM project_kv WHERE project_id = ? AND expires_at > ?'
const params: (string | number)[] = [projectId, now]
if (prefix) {
sql += ' AND key LIKE ?'
params.push(`${prefix}%`)
}
sql += ' ORDER BY updated_at DESC'
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbKvRow[]
return rows.map(mapRowToKvEntry)
}
getKv(projectId: string, key: string): { key: string; data: unknown; createdAt: number; updatedAt: number; expiresAt: number } | undefined {
const db = this.getDb()
if (!db) return undefined
const stmt = db.prepare(
'SELECT project_id, key, data, expires_at, created_at, updated_at FROM project_kv WHERE project_id = ? AND key = ? AND expires_at > ?'
)
const row = stmt.get(projectId, key, Date.now()) as DbKvRow | undefined
return row ? mapRowToKvEntry(row) : undefined
}
setKv(projectId: string, key: string, data: unknown, ttlMs?: number): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const now = Date.now()
const expiresAt = ttlMs ? now + ttlMs : Number.MAX_SAFE_INTEGER
const serializedData = JSON.stringify(data)
const stmt = db.prepare(`
INSERT INTO project_kv (project_id, key, data, expires_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(project_id, key) DO UPDATE SET
data = excluded.data,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at
`)
stmt.run(projectId, key, serializedData, expiresAt, now, now)
}
deleteKv(projectId: string, key: string): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const stmt = db.prepare('DELETE FROM project_kv WHERE project_id = ? AND key = ?')
stmt.run(projectId, key)
}
getKvCount(projectId: string): number {
const db = this.getDb()
if (!db) return 0
const stmt = db.prepare('SELECT COUNT(*) as count FROM project_kv WHERE project_id = ? AND expires_at > ?')
const result = stmt.get(projectId, Date.now()) as { count: number }
return result.count
}
close(): void {
if (this.db) {
this.db.close()
this.db = null
}
}
}
+45 -36
View File
@@ -34,7 +34,7 @@ import {
computeNextRunAtForJob,
} from './schedule-config'
import { resolveOpenCodeModel } from './opencode-models'
import { proxyToOpenCodeWithDirectory } from './proxy'
import type { OpenCodeClient } from './opencode/client'
import { sseAggregator, type SSEEvent } from './sse-aggregator'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
@@ -118,9 +118,13 @@ type SkillInfo = {
content: string
}
async function fetchSkillContent(slugs: string[], repoPath: string): Promise<string[]> {
async function fetchSkillContent(slugs: string[], repoPath: string, openCodeClient: OpenCodeClient): Promise<string[]> {
try {
const response = await proxyToOpenCodeWithDirectory('/skill', 'GET', repoPath)
const response = await openCodeClient.forward({
method: 'GET',
path: '/skill',
directory: repoPath,
})
if (!response.ok) {
logger.warn(`Failed to fetch skills from OpenCode (${response.status}), falling back to name-only injection`)
return []
@@ -159,11 +163,12 @@ async function fetchSkillContent(slugs: string[], repoPath: string): Promise<str
async function buildPromptWithSkills(
prompt: string,
skillMetadata: ScheduleJob['skillMetadata'],
repoPath: string
repoPath: string,
openCodeClient: OpenCodeClient,
): Promise<string> {
if (!skillMetadata || !skillMetadata.skillSlugs || skillMetadata.skillSlugs.length === 0) return prompt
const skillBlocks = await fetchSkillContent(skillMetadata.skillSlugs, repoPath)
const skillBlocks = await fetchSkillContent(skillMetadata.skillSlugs, repoPath, openCodeClient)
const notesLine = skillMetadata.notes ? `\nSkill notes: ${skillMetadata.notes}` : ''
if (skillBlocks.length === 0) {
@@ -310,11 +315,9 @@ function getSessionStatusType(event: SSEEvent): string | null {
}
function createSessionMonitor(directory: string, sessionId: string): SessionMonitor {
const clientId = `schedule-monitor-${sessionId}-${Date.now()}`
let errorText: string | null = null
let idle = false
const removeClient = sseAggregator.addClient(clientId, () => {}, [directory])
const unsubscribe = sseAggregator.onEvent((eventDirectory, event) => {
if (eventDirectory !== directory) {
return
@@ -342,10 +345,7 @@ function createSessionMonitor(directory: string, sessionId: string): SessionMoni
return {
getErrorText: () => errorText,
isIdle: () => idle,
dispose: () => {
unsubscribe()
removeClient()
},
dispose: unsubscribe,
}
}
@@ -353,7 +353,10 @@ export class ScheduleService {
private static activeRuns = new Set<number>()
private onJobChange: ((job: ScheduleJob | null, jobId: number) => void) | null = null
constructor(private readonly db: Database) {}
constructor(
private readonly db: Database,
private readonly openCodeClient: OpenCodeClient,
) {}
setJobChangeHandler(handler: ((job: ScheduleJob | null, jobId: number) => void) | null): void {
this.onJobChange = handler
@@ -479,19 +482,20 @@ export class ScheduleService {
})
try {
const model = await resolveOpenCodeModel(repo.fullPath, {
const model = await resolveOpenCodeModel(this.openCodeClient, repo.fullPath, {
preferredModel: job.model,
})
const sessionTitle = buildSessionTitle(job)
const sessionResponse = await proxyToOpenCodeWithDirectory(
'/session',
'POST',
repo.fullPath,
JSON.stringify({
const sessionResponse = await this.openCodeClient.forward({
method: 'POST',
path: '/session',
directory: repo.fullPath,
body: JSON.stringify({
title: sessionTitle,
agent: job.agentSlug ?? undefined,
}),
)
headers: { 'Content-Type': 'application/json' },
})
if (!sessionResponse.ok) {
throw new ScheduleServiceError('Failed to create OpenCode session', 502)
@@ -591,11 +595,11 @@ export class ScheduleService {
return this.getRun(repoId, jobId, runId)
}
const abortResponse = await proxyToOpenCodeWithDirectory(
`/session/${run.sessionId}/abort`,
'POST',
repo.fullPath,
)
const abortResponse = await this.openCodeClient.forward({
method: 'POST',
path: `/session/${run.sessionId}/abort`,
directory: repo.fullPath,
})
if (!abortResponse.ok) {
const errorText = await abortResponse.text()
@@ -650,15 +654,16 @@ export class ScheduleService {
const repo = this.assertRepo(input.repoId)
try {
const promptResponse = await proxyToOpenCodeWithDirectory(
`/session/${input.sessionId}/message`,
'POST',
repo.fullPath,
JSON.stringify({
parts: [{ type: 'text', text: await buildPromptWithSkills(input.job.prompt, input.job.skillMetadata, repo.fullPath) }],
const promptResponse = await this.openCodeClient.forward({
method: 'POST',
path: `/session/${input.sessionId}/message`,
directory: repo.fullPath,
body: JSON.stringify({
parts: [{ type: 'text', text: await buildPromptWithSkills(input.job.prompt, input.job.skillMetadata, repo.fullPath, this.openCodeClient) }],
model: input.model,
}),
)
headers: { 'Content-Type': 'application/json' },
})
if (!promptResponse.ok) {
const errorText = await promptResponse.text()
@@ -1020,11 +1025,11 @@ export class ScheduleService {
}
private async listSessionMessages(directory: string, sessionId: string): Promise<SessionMessage[]> {
const messagesResponse = await proxyToOpenCodeWithDirectory(
`/session/${sessionId}/message`,
'GET',
const messagesResponse = await this.openCodeClient.forward({
method: 'GET',
path: `/session/${sessionId}/message`,
directory,
)
})
if (!messagesResponse.ok) {
const errorText = await messagesResponse.text()
@@ -1035,7 +1040,11 @@ export class ScheduleService {
}
private async getSessionStatuses(directory: string): Promise<Record<string, SessionStatus>> {
const response = await proxyToOpenCodeWithDirectory('/session/status', 'GET', directory)
const response = await this.openCodeClient.forward({
method: 'GET',
path: '/session/status',
directory,
})
if (!response.ok) {
const errorText = await response.text()
+64
View File
@@ -4,6 +4,8 @@ import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
import { logger } from '../utils/logger'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { z } from 'zod'
import { encryptSecret, decryptSecret } from '../utils/crypto'
import { ENV } from '@opencode-manager/shared/config/env'
import type {
UserPreferences,
SettingsResponse,
@@ -42,6 +44,12 @@ interface CreateOpenCodeConfigOptions {
suppressAutoDefault?: boolean
}
interface OpenCodeServerPasswordState {
value: string
createdAt: number
updatedAt: number
}
export class SettingsService {
private static lastKnownGoodConfigContent: string | null = null
@@ -597,4 +605,60 @@ export class SettingsService {
return false
}
}
getOpenCodeServerPassword(): string {
const row = this.db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string } | undefined
if (!row) {
return ENV.OPENCODE.SERVER_PASSWORD
}
try {
return decryptSecret(row.value)
} catch (error) {
logger.error('Failed to decrypt opencode_server_password, falling back to env', error)
return ENV.OPENCODE.SERVER_PASSWORD
}
}
hasStoredOpenCodeServerPassword(): boolean {
const row = this.db.prepare('SELECT 1 FROM app_secrets WHERE key = ?').get('opencode_server_password')
return Boolean(row)
}
getStoredOpenCodeServerPasswordState(): OpenCodeServerPasswordState | null {
const row = this.db.prepare('SELECT value, created_at, updated_at FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string; created_at: number; updated_at: number } | undefined
if (!row) {
return null
}
return {
value: row.value,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
restoreOpenCodeServerPasswordState(state: OpenCodeServerPasswordState | null): void {
if (!state) {
this.clearOpenCodeServerPassword()
return
}
this.db.prepare(`
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, created_at = excluded.created_at, updated_at = excluded.updated_at
`).run('opencode_server_password', state.value, state.createdAt, state.updatedAt)
}
setOpenCodeServerPassword(password: string): void {
const now = Date.now()
const encrypted = encryptSecret(password)
this.db.prepare(`
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
`).run('opencode_server_password', encrypted, now, now)
}
clearOpenCodeServerPassword(): void {
this.db.prepare('DELETE FROM app_secrets WHERE key = ?').run('opencode_server_password')
}
}
+158 -313
View File
@@ -5,9 +5,18 @@ import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest
import { SKILL_NAME_REGEX } from '@opencode-manager/shared'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import { getRepoById, listRepos } from '../db/queries'
import type { Repo } from '@opencode-manager/shared/types'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations'
import type { OpenCodeClient } from './opencode/client'
import { logger } from '../utils/logger'
interface OpenCodeSkillInfo {
name: string
description: string
location: string
content: string
}
function getGlobalSkillsPath(): string {
return path.join(getWorkspacePath(), '.config', 'opencode', 'skills')
}
@@ -16,43 +25,47 @@ function getOldGlobalSkillsPath(): string {
return path.join(os.homedir(), '.config', 'opencode', 'skills')
}
function getProjectSkillsPath(repo: Repo): string {
return path.join(repo.fullPath, '.opencode', 'skills')
}
export async function migrateGlobalSkills(): Promise<void> {
const oldSkillsPath = getOldGlobalSkillsPath()
const newSkillsPath = getGlobalSkillsPath()
const oldSkillsExist = await fileExists(oldSkillsPath)
if (!oldSkillsExist) {
logger.debug('No old global skills found to migrate')
return
}
const entries = await listDirectory(oldSkillsPath)
const skillDirs = entries.filter(entry => entry.isDirectory)
if (skillDirs.length === 0) {
logger.debug('No skill directories found in old location')
return
}
let migratedCount = 0
let skippedCount = 0
for (const entry of skillDirs) {
const oldSkillPath = path.join(entry.path, 'SKILL.md')
const newSkillPath = path.join(newSkillsPath, entry.name, 'SKILL.md')
const alreadyMigrated = await fileExists(newSkillPath)
if (alreadyMigrated) {
skippedCount++
continue
}
const skillExists = await fileExists(oldSkillPath)
if (!skillExists) {
logger.warn(`Skill ${entry.name} has no SKILL.md file, skipping`)
continue
}
try {
const content = await readFileContent(oldSkillPath)
await writeFileContent(newSkillPath, content)
@@ -62,133 +75,12 @@ export async function migrateGlobalSkills(): Promise<void> {
logger.error(`Failed to migrate skill ${entry.name}:`, error)
}
}
if (migratedCount > 0 || skippedCount > 0) {
logger.info(`Skill migration complete: ${migratedCount} migrated, ${skippedCount} skipped (already existed)`)
}
}
interface ParsedSkillFile {
frontmatter: {
name: string
description: string
license?: string
compatibility?: string
metadata?: Record<string, string>
}
body: string
}
function parseSkillFile(content: string): ParsedSkillFile {
const firstDelim = content.indexOf('---')
if (firstDelim === -1) {
throw new Error('Invalid SKILL.md format: missing frontmatter delimiters')
}
const afterFirst = firstDelim + 3
const secondDelim = content.indexOf('\n---', afterFirst)
if (secondDelim === -1) {
throw new Error('Invalid SKILL.md format: missing closing frontmatter delimiter')
}
const frontmatterStr = content.substring(afterFirst, secondDelim).trim()
const afterSecond = secondDelim + 4
const body = content.substring(afterSecond).trim()
const frontmatter: Record<string, unknown> = {}
const lines = frontmatterStr.split('\n')
let currentKey: string | null = null
const metadataObj: Record<string, string> = {}
for (const line of lines) {
const trimmedLine = line.trim()
if (!trimmedLine) continue
const kvMatch = trimmedLine.match(/^([^:]+):\s*(.*)$/)
if (kvMatch) {
const key = kvMatch[1]?.trim()
const value = kvMatch[2]?.trim()
if (key === 'metadata') {
currentKey = 'metadata'
continue
}
if (key && value !== undefined) {
frontmatter[key] = value
currentKey = null
}
} else if (currentKey === 'metadata' && trimmedLine) {
const metaMatch = trimmedLine.match(/^\s*([^:]+):\s*(.*)$/)
if (metaMatch) {
const metaKey = metaMatch[1]?.trim()
const metaValue = metaMatch[2]?.trim()
if (metaKey && metaValue !== undefined) {
metadataObj[metaKey] = metaValue
}
}
}
}
if (Object.keys(metadataObj).length > 0) {
frontmatter.metadata = metadataObj
}
return {
frontmatter: {
name: frontmatter.name as string || '',
description: frontmatter.description as string || '',
license: frontmatter.license as string | undefined,
compatibility: frontmatter.compatibility as string | undefined,
metadata: frontmatter.metadata as Record<string, string> | undefined,
},
body,
}
}
function generateSkillFrontmatter(
name: string,
description: string,
license?: string,
compatibility?: string,
metadata?: Record<string, string>
): string {
let frontmatter = `name: ${name}\ndescription: ${description}`
if (license) {
frontmatter += `\nlicense: ${license}`
}
if (compatibility) {
frontmatter += `\ncompatibility: ${compatibility}`
}
if (metadata && Object.keys(metadata).length > 0) {
frontmatter += '\nmetadata:'
for (const [key, value] of Object.entries(metadata)) {
frontmatter += `\n ${key}: ${value}`
}
}
return frontmatter
}
function getSkillDirectoryPath(db: Database, scope: SkillScope, repoId?: number): string {
if (scope === 'global') {
return getGlobalSkillsPath()
}
if (!repoId) {
throw new Error('repoId is required for project-scoped skills')
}
const repo = getRepoById(db, repoId)
if (!repo) {
throw new Error(`Repository with id ${repoId} not found`)
}
return path.join(repo.fullPath, '.opencode', 'skills')
}
function validateSkillName(name: string): void {
if (!SKILL_NAME_REGEX.test(name)) {
throw new Error('Invalid skill name. Must be lowercase alphanumeric with hyphens only.')
@@ -197,171 +89,153 @@ function validateSkillName(name: string): void {
function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string {
validateSkillName(name)
const skillsDir = getSkillDirectoryPath(db, scope, repoId)
return path.join(skillsDir, name, 'SKILL.md')
if (scope === 'global') {
return path.join(getGlobalSkillsPath(), name, 'SKILL.md')
}
if (!repoId) {
throw new Error('repoId is required for project-scoped skills')
}
const repo = getRepoById(db, repoId)
if (!repo) {
throw new Error(`Repository with id ${repoId} not found`)
}
return path.join(getProjectSkillsPath(repo), name, 'SKILL.md')
}
export async function listManagedSkills(db: Database, repoId?: number): Promise<SkillFileInfo[]> {
const skills: SkillFileInfo[] = []
const globalSkillsDir = getGlobalSkillsPath()
const globalSkillsExist = await fileExists(globalSkillsDir)
if (globalSkillsExist) {
const entries = await listDirectory(globalSkillsDir)
for (const entry of entries) {
if (entry.isDirectory) {
const skillPath = path.join(entry.path, 'SKILL.md')
const skillExists = await fileExists(skillPath)
if (skillExists) {
const skillInfo = await readSkillFile(db, 'global', entry.name)
if (skillInfo) {
skills.push(skillInfo)
}
}
}
function buildSkillFileContent(name: string, description: string, body: string): string {
return `---\nname: ${name}\ndescription: ${description}\n---\n${body}`
}
async function fetchOpenCodeSkills(openCodeClient: OpenCodeClient, directory: string): Promise<OpenCodeSkillInfo[]> {
try {
const response = await openCodeClient.forward({
method: 'GET',
path: '/skill',
directory,
})
if (!response.ok) {
logger.warn(`Failed to fetch skills from OpenCode (${response.status})`)
return []
}
return await response.json() as OpenCodeSkillInfo[]
} catch (error) {
logger.warn('Error fetching skills from OpenCode:', error)
return []
}
}
function classifySkillLocation(
location: string,
globalPrefix: string,
repos: Repo[],
): { scope: SkillScope; repo?: Repo } | null {
if (location.startsWith(globalPrefix + path.sep)) {
return { scope: 'global' }
}
for (const repo of repos) {
const projectPrefix = getProjectSkillsPath(repo)
if (location.startsWith(projectPrefix + path.sep)) {
return { scope: 'project', repo }
}
}
if (repoId) {
const repo = getRepoById(db, repoId)
if (repo) {
const projectSkillsDir = path.join(repo.fullPath, '.opencode', 'skills')
const projectSkillsExist = await fileExists(projectSkillsDir)
if (projectSkillsExist) {
const entries = await listDirectory(projectSkillsDir)
for (const entry of entries) {
if (entry.isDirectory) {
const skillPath = path.join(entry.path, 'SKILL.md')
const skillExists = await fileExists(skillPath)
if (skillExists) {
const skillInfo = await readSkillFile(db, 'project', entry.name, repoId)
if (skillInfo) {
skills.push(skillInfo)
}
}
}
}
}
}
} else {
const allRepos = listRepos(db)
for (const repo of allRepos) {
const projectSkillsDir = path.join(repo.fullPath, '.opencode', 'skills')
const projectSkillsExist = await fileExists(projectSkillsDir)
if (projectSkillsExist) {
const entries = await listDirectory(projectSkillsDir)
for (const entry of entries) {
if (entry.isDirectory) {
const skillPath = path.join(entry.path, 'SKILL.md')
const skillExists = await fileExists(skillPath)
if (skillExists) {
const skillInfo = await readSkillFile(db, 'project', entry.name, repo.id)
if (skillInfo) {
skills.push(skillInfo)
}
}
}
}
}
return null
}
function toSkillFileInfo(
skill: OpenCodeSkillInfo,
classification: { scope: SkillScope; repo?: Repo },
): SkillFileInfo {
return {
name: skill.name,
description: skill.description,
body: skill.content,
scope: classification.scope,
location: skill.location,
repoId: classification.repo?.id,
repoName: classification.repo?.localPath,
}
}
export async function listManagedSkills(
db: Database,
openCodeClient: OpenCodeClient,
repoId?: number,
): Promise<SkillFileInfo[]> {
const globalPrefix = getGlobalSkillsPath()
const allRepos = listRepos(db)
const targetRepos = repoId
? allRepos.filter(r => r.id === repoId)
: allRepos
if (repoId && targetRepos.length === 0) {
throw new Error(`Repository with id ${repoId} not found`)
}
const directories = targetRepos.length > 0
? targetRepos.map(r => r.fullPath)
: [getWorkspacePath()]
const seenLocations = new Set<string>()
const result: SkillFileInfo[] = []
for (const directory of directories) {
const skills = await fetchOpenCodeSkills(openCodeClient, directory)
for (const skill of skills) {
if (seenLocations.has(skill.location)) continue
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos)
if (!classification) continue
seenLocations.add(skill.location)
result.push(toSkillFileInfo(skill, classification))
}
}
return skills
return result
}
export async function getSkill(
db: Database,
openCodeClient: OpenCodeClient,
name: string,
scope: SkillScope,
repoId?: number
repoId?: number,
): Promise<SkillFileInfo> {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (!exists) {
validateSkillName(name)
const skills = await listManagedSkills(db, openCodeClient, repoId)
const match = skills.find(s =>
s.name === name &&
s.scope === scope &&
(scope === 'global' || s.repoId === repoId),
)
if (!match) {
throw new Error(`Skill "${name}" not found in ${scope} scope`)
}
const skillInfo = await readSkillFile(db, scope, name, repoId)
if (!skillInfo) {
throw new Error(`Failed to read skill "${name}"`)
}
return skillInfo
}
async function readSkillFile(
db: Database,
scope: SkillScope,
name: string,
repoId?: number
): Promise<SkillFileInfo | null> {
try {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const content = await readFileContent(skillPath)
const parsed = parseSkillFile(content)
const repo = repoId ? getRepoById(db, repoId) : null
return {
name: parsed.frontmatter.name,
description: parsed.frontmatter.description,
body: parsed.body,
license: parsed.frontmatter.license,
compatibility: parsed.frontmatter.compatibility,
metadata: parsed.frontmatter.metadata,
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
repoName: repo?.localPath,
}
} catch (error) {
logger.error(`Failed to read skill ${name}:`, error)
return null
}
return match
}
export async function createSkill(
db: Database,
input: CreateSkillRequest
input: CreateSkillRequest,
): Promise<SkillFileInfo> {
const { name, description, body, license, compatibility, metadata, scope, repoId } = input
const { name, description, body, scope, repoId } = input
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (exists) {
throw new Error(`Skill "${name}" already exists in ${scope} scope`)
}
const skillDir = path.dirname(skillPath)
await ensureDirectoryExists(skillDir)
const frontmatter = generateSkillFrontmatter(
name,
description,
license,
compatibility,
metadata
)
const content = `---\n${frontmatter}\n---\n${body}`
await writeFileContent(skillPath, content)
await ensureDirectoryExists(path.dirname(skillPath))
await writeFileContent(skillPath, buildSkillFileContent(name, description, body))
logger.info(`Created skill "${name}" at ${skillPath}`)
const repo = repoId ? getRepoById(db, repoId) : null
return {
name,
description,
body,
license,
compatibility,
metadata,
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
@@ -371,63 +245,35 @@ export async function createSkill(
export async function updateSkill(
db: Database,
openCodeClient: OpenCodeClient,
name: string,
scope: SkillScope,
input: UpdateSkillRequest,
repoId?: number
repoId?: number,
): Promise<SkillFileInfo> {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (!exists) {
throw new Error(`Skill "${name}" not found in ${scope} scope`)
}
const existingContent = await readFileContent(skillPath)
const parsed = parseSkillFile(existingContent)
const resolveField = <T>(field: T | null | undefined, existing: T | undefined): T | undefined => {
if (field === null) return undefined
if (field === undefined) return existing
return field
}
const updatedFrontmatter = {
name: parsed.frontmatter.name,
description: input.description ?? parsed.frontmatter.description,
license: resolveField(input.license, parsed.frontmatter.license),
compatibility: resolveField(input.compatibility, parsed.frontmatter.compatibility),
metadata: resolveField(input.metadata, parsed.frontmatter.metadata),
}
const updatedBody = input.body ?? parsed.body
const frontmatter = generateSkillFrontmatter(
updatedFrontmatter.name,
updatedFrontmatter.description,
updatedFrontmatter.license,
updatedFrontmatter.compatibility,
updatedFrontmatter.metadata
)
const content = `---\n${frontmatter}\n---\n${updatedBody}`
await writeFileContent(skillPath, content)
const existing = await getSkill(db, openCodeClient, name, scope, repoId)
const description = input.description ?? existing.description
const body = input.body ?? existing.body
await writeFileContent(skillPath, buildSkillFileContent(name, description, body))
logger.info(`Updated skill "${name}" at ${skillPath}`)
const repo = repoId ? getRepoById(db, repoId) : null
return {
name: updatedFrontmatter.name,
description: updatedFrontmatter.description,
body: updatedBody,
license: updatedFrontmatter.license,
compatibility: updatedFrontmatter.compatibility,
metadata: updatedFrontmatter.metadata,
name,
description,
body,
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
repoName: repo?.localPath,
repoId: existing.repoId,
repoName: existing.repoName,
}
}
@@ -435,16 +281,15 @@ export async function deleteSkill(
db: Database,
name: string,
scope: SkillScope,
repoId?: number
repoId?: number,
): Promise<void> {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (!exists) {
throw new Error(`Skill "${name}" not found in ${scope} scope`)
}
const skillDir = path.dirname(skillPath)
await deletePath(skillDir)
logger.info(`Deleted skill "${name}" from ${skillDir}`)
await deletePath(path.dirname(skillPath))
logger.info(`Deleted skill "${name}" from ${path.dirname(skillPath)}`)
}
+237 -216
View File
@@ -2,6 +2,7 @@ import { EventSource } from 'eventsource'
import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { DEFAULTS } from '@opencode-manager/shared/config'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './opencode/auth'
type SSEClientCallback = (event: string, data: string) => void
type SSEEventListener = (directory: string, event: SSEEvent) => void
@@ -14,33 +15,73 @@ interface SSEClient {
activeSessionId: string | null
}
interface DirectoryConnection {
eventSource: EventSource | null
reconnectTimeout: ReturnType<typeof setTimeout> | null
reconnectDelay: number
isConnected: boolean
}
export interface SSEEvent {
type: string
properties: Record<string, unknown>
}
interface GlobalEventEnvelope {
directory?: string
project?: string
workspace?: string
payload: SSEEvent
}
export interface PendingActionsFetcher {
getJson<T>(path: string, opts?: { directory?: string; signal?: AbortSignal }): Promise<T>
}
interface PendingPermission {
id: string
sessionID: string
[key: string]: unknown
}
interface PendingQuestion {
id: string
sessionID: string
[key: string]: unknown
}
const OPENCODE_PORT = ENV.OPENCODE.PORT
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, IDLE_GRACE_PERIOD_MS } = DEFAULTS.SSE
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
class SSEAggregator {
private static instance: SSEAggregator
private clients: Map<string, SSEClient> = new Map()
private connections: Map<string, DirectoryConnection> = new Map()
private activeSessions: Map<string, Set<string>> = new Map()
private idleTimeouts: Map<string, ReturnType<typeof setTimeout>> = new Map()
private sessionStateVersion: Map<string, number> = new Map()
private eventListeners: Set<SSEEventListener> = new Set()
private subagentSessions: Map<string, Set<string>> = new Map()
private upstream: EventSource | null = null
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
private reconnectDelay: number = RECONNECT_DELAY_MS
private upstreamConnected = false
private everConnected = false
private started = false
private pendingActionsFetcher: PendingActionsFetcher | null = null
private passwordResolver: OpenCodePasswordResolver | null = null
private constructor() {}
setPendingActionsFetcher(fetcher: PendingActionsFetcher | null): void {
this.pendingActionsFetcher = fetcher
}
setPasswordResolver(resolver: OpenCodePasswordResolver | null): void {
this.passwordResolver = resolver
}
reconnect(): void {
if (!this.started) return
logger.info('SSE forcing upstream reconnect (auth changed)')
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
this.reconnectDelay = RECONNECT_DELAY_MS
void this.connectUpstream()
}
static getInstance(): SSEAggregator {
if (!SSEAggregator.instance) {
SSEAggregator.instance = new SSEAggregator()
@@ -48,6 +89,12 @@ class SSEAggregator {
return SSEAggregator.instance
}
start(): void {
if (this.started) return
this.started = true
void this.connectUpstream()
}
addClient(id: string, callback: SSEClientCallback, directories: string[]): () => void {
const client: SSEClient = {
id,
@@ -57,16 +104,18 @@ class SSEAggregator {
activeSessionId: null
}
this.clients.set(id, client)
logger.info(`Client ${id} connected with directories: ${directories.length > 0 ? directories.join(', ') : '(none)'}`)
this.syncConnections()
if (directories.length > 0) {
void this.replayPendingActionsForClient(id, directories)
}
return () => this.removeClient(id)
}
removeClient(id: string): void {
this.clients.delete(id)
this.syncConnections()
}
addDirectories(clientId: string, directories: string[]): boolean {
@@ -75,9 +124,19 @@ class SSEAggregator {
logger.warn(`addDirectories: client ${clientId} not found`)
return false
}
directories.forEach(dir => client.directories.add(dir))
const newDirectories: string[] = []
directories.forEach(dir => {
if (!client.directories.has(dir)) {
newDirectories.push(dir)
}
client.directories.add(dir)
})
logger.info(`Client ${clientId} subscribed to: ${directories.join(', ')}`)
this.syncConnections()
if (newDirectories.length > 0) {
void this.replayPendingActionsForClient(clientId, newDirectories)
}
return true
}
@@ -89,114 +148,148 @@ class SSEAggregator {
}
directories.forEach(dir => client.directories.delete(dir))
logger.info(`Client ${clientId} unsubscribed from: ${directories.join(', ')}`)
this.syncConnections()
return true
}
private getRequiredDirectories(): Set<string> {
const dirs = new Set<string>()
this.clients.forEach(client => {
client.directories.forEach(dir => dirs.add(dir))
})
return dirs
private async replayPendingActionsForClient(clientId: string, directories: string[]): Promise<void> {
const fetcher = this.pendingActionsFetcher
if (!fetcher) return
await Promise.allSettled(directories.map(directory =>
this.replayPendingActionsForDirectory(clientId, directory, fetcher)
))
}
private syncConnections(): void {
const required = this.getRequiredDirectories()
private async replayPendingActionsForAllClients(): Promise<void> {
const fetcher = this.pendingActionsFetcher
if (!fetcher) return
this.connections.forEach((_, dir) => {
if (!required.has(dir)) {
this.disconnectDirectory(dir)
}
const tasks: Promise<void>[] = []
this.clients.forEach((client) => {
const directories = Array.from(client.directories)
if (directories.length === 0) return
tasks.push(this.replayPendingActionsForClient(client.id, directories))
})
required.forEach(dir => {
if (!this.connections.has(dir)) {
this.connectDirectory(dir)
}
})
if (tasks.length === 0) return
logger.info(`replay: replaying pending actions to ${tasks.length} client(s) after upstream reconnect`)
await Promise.allSettled(tasks)
}
private connectDirectory(directory: string): void {
if (this.connections.has(directory)) return
private async replayPendingActionsForDirectory(
clientId: string,
directory: string,
fetcher: PendingActionsFetcher,
): Promise<void> {
const [permissionsResult, questionsResult] = await Promise.allSettled([
fetcher.getJson<PendingPermission[]>('/permission', { directory }),
fetcher.getJson<PendingQuestion[]>('/question', { directory }),
])
const conn: DirectoryConnection = {
eventSource: null,
reconnectTimeout: null,
reconnectDelay: RECONNECT_DELAY_MS,
isConnected: false
if (permissionsResult.status === 'rejected') {
logger.warn(`replay: failed to fetch pending permissions for ${directory}: ${String(permissionsResult.reason)}`)
} else {
this.emitPendingEventsToClient(clientId, directory, 'permission.asked', permissionsResult.value)
}
this.connections.set(directory, conn)
this.establishConnection(directory)
if (questionsResult.status === 'rejected') {
logger.warn(`replay: failed to fetch pending questions for ${directory}: ${String(questionsResult.reason)}`)
} else {
this.emitPendingEventsToClient(clientId, directory, 'question.asked', questionsResult.value)
}
}
private establishConnection(directory: string): void {
const conn = this.connections.get(directory)
if (!conn) return
private emitPendingEventsToClient(
clientId: string,
directory: string,
type: 'permission.asked' | 'question.asked',
items: Array<PendingPermission | PendingQuestion> | null,
): void {
if (!items || items.length === 0) return
if (conn.eventSource) {
conn.eventSource.close()
conn.eventSource = null
}
const client = this.clients.get(clientId)
if (!client || !client.directories.has(directory)) return
const url = new URL(`http://127.0.0.1:${OPENCODE_PORT}/event`)
url.searchParams.set('directory', directory)
logger.info(`SSE connecting to OpenCode: ${directory}`)
const eventSource = new EventSource(url.toString())
conn.eventSource = eventSource
eventSource.onopen = () => {
logger.info(`SSE connected: ${directory}`)
conn.isConnected = true
conn.reconnectDelay = RECONNECT_DELAY_MS
}
eventSource.onerror = () => {
conn.isConnected = false
if (conn.eventSource) {
conn.eventSource.close()
conn.eventSource = null
}
if (this.connections.has(directory)) {
this.scheduleReconnect(directory)
for (const item of items) {
const payload = JSON.stringify({ type, properties: item, directory })
try {
client.callback('message', payload)
} catch (error) {
logger.error(`replay: failed to deliver ${type} to client ${clientId}:`, error)
return
}
}
eventSource.onmessage = (event) => {
this.broadcastToDirectory(directory, 'message', event.data)
logger.info(`replay: sent ${items.length} ${type} event(s) for ${directory} to client ${clientId}`)
}
private async connectUpstream(): Promise<void> {
if (!this.started) return
if (this.upstream) {
this.upstream.close()
this.upstream = null
}
const url = `http://127.0.0.1:${OPENCODE_PORT}/global/event`
const wasConnectedBefore = this.everConnected
logger.info(`SSE connecting to OpenCode global stream: ${url}`)
const authHeader = this.passwordResolver
? await getOpenCodeBasicAuthHeader(this.passwordResolver)
: getOpenCodeBasicAuthHeader()
if (!this.started) return
const init: ConstructorParameters<typeof EventSource>[1] = authHeader
? {
fetch: (input, fetchInit) =>
fetch(input, {
...fetchInit,
headers: {
...(fetchInit?.headers ?? {}),
Authorization: authHeader,
},
}),
}
: undefined
const es = new EventSource(url, init)
this.upstream = es
es.onopen = () => {
logger.info('SSE global stream connected')
this.upstreamConnected = true
this.reconnectDelay = RECONNECT_DELAY_MS
this.everConnected = true
if (wasConnectedBefore) {
void this.replayPendingActionsForAllClients()
}
}
es.onerror = (event) => {
this.upstreamConnected = false
if (es === this.upstream) {
const code = (event as { code?: number }).code
const message = (event as { message?: string }).message
logger.warn(`SSE upstream error${code ? ` (code=${code})` : ''}${message ? `: ${message}` : ''}`)
es.close()
this.upstream = null
this.scheduleReconnect()
}
}
es.onmessage = (event) => {
this.handleUpstreamMessage(event.data)
}
}
private disconnectDirectory(directory: string): void {
const conn = this.connections.get(directory)
if (!conn) return
if (conn.reconnectTimeout) {
clearTimeout(conn.reconnectTimeout)
}
if (conn.eventSource) {
conn.eventSource.close()
}
this.connections.delete(directory)
logger.info(`SSE disconnected: ${directory}`)
}
private scheduleReconnect(directory: string): void {
const conn = this.connections.get(directory)
if (!conn || conn.reconnectTimeout) return
conn.reconnectTimeout = setTimeout(() => {
conn.reconnectTimeout = null
conn.reconnectDelay = Math.min(conn.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
this.establishConnection(directory)
}, conn.reconnectDelay)
private scheduleReconnect(): void {
if (!this.started || this.reconnectTimeout) return
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
void this.connectUpstream()
}, this.reconnectDelay)
}
onEvent(listener: SSEEventListener): () => void {
@@ -204,24 +297,30 @@ class SSEAggregator {
return () => { this.eventListeners.delete(listener) }
}
private broadcastToDirectory(directory: string, event: string, data: string): void {
let clientData = data
private handleUpstreamMessage(data: string): void {
let envelope: GlobalEventEnvelope
try {
const parsed = JSON.parse(data) as SSEEvent
this.handleEvent(directory, parsed)
this.eventListeners.forEach(listener => {
try { listener(directory, parsed) } catch { /* ignore listener errors */ }
})
clientData = JSON.stringify({ ...parsed, directory })
envelope = JSON.parse(data) as GlobalEventEnvelope
} catch {
// Ignore parse errors
return
}
if (!envelope.directory || !envelope.payload?.type) return
const directory = envelope.directory
const parsed = envelope.payload
this.handleEvent(directory, parsed)
this.eventListeners.forEach(listener => {
try { listener(directory, parsed) } catch { /* ignore listener errors */ }
})
const clientData = JSON.stringify({ ...parsed, directory })
this.clients.forEach((client) => {
if (client.directories.has(directory)) {
try {
client.callback(event, clientData)
client.callback('message', clientData)
} catch (error) {
logger.error(`Failed to send to client ${client.id}:`, error)
}
@@ -235,11 +334,11 @@ class SSEAggregator {
if (type === 'session.status') {
const sessionID = properties.sessionID as string
const status = properties.status as { type: string }
if (!sessionID || !status) return
const isActive = status.type === 'busy' || status.type === 'retry' || status.type === 'compact'
if (isActive) {
this.markSessionActive(directory, sessionID)
} else if (status.type === 'idle') {
@@ -274,106 +373,32 @@ class SSEAggregator {
}
}
private getStateVersion(directory: string): number {
return this.sessionStateVersion.get(directory) ?? 0
}
private incrementStateVersion(directory: string): number {
const newVersion = this.getStateVersion(directory) + 1
this.sessionStateVersion.set(directory, newVersion)
return newVersion
}
private markSessionActive(directory: string, sessionID: string): void {
this.incrementStateVersion(directory)
const existingTimeout = this.idleTimeouts.get(directory)
if (existingTimeout) {
clearTimeout(existingTimeout)
this.idleTimeouts.delete(directory)
}
let sessions = this.activeSessions.get(directory)
if (!sessions) {
sessions = new Set()
this.activeSessions.set(directory, sessions)
}
sessions.add(sessionID)
logger.info(`Session active: ${sessionID} in ${directory} (${sessions.size} active)`)
}
private markSessionIdle(directory: string, sessionID: string): void {
const existingTimeout = this.idleTimeouts.get(directory)
if (existingTimeout) {
clearTimeout(existingTimeout)
this.idleTimeouts.delete(directory)
}
const sessions = this.activeSessions.get(directory)
if (sessions) {
sessions.delete(sessionID)
logger.info(`Session idle: ${sessionID} in ${directory} (${sessions.size} active)`)
if (sessions.size === 0) {
this.activeSessions.delete(directory)
this.scheduleIdleDisconnect(directory)
}
}
}
private hasActiveViewers(directory: string): boolean {
for (const client of this.clients.values()) {
if (client.directories.has(directory)) {
return true
}
}
return false
}
private scheduleIdleDisconnect(directory: string): void {
if (this.hasActiveViewers(directory)) {
logger.info(`Skipping idle disconnect for ${directory} - has active viewers`)
return
}
const existingTimeout = this.idleTimeouts.get(directory)
if (existingTimeout) {
clearTimeout(existingTimeout)
}
const versionAtSchedule = this.getStateVersion(directory)
logger.info(`Scheduling idle disconnect for ${directory} in ${IDLE_GRACE_PERIOD_MS}ms (version: ${versionAtSchedule})`)
const timeout = setTimeout(() => {
this.idleTimeouts.delete(directory)
const currentVersion = this.getStateVersion(directory)
if (currentVersion !== versionAtSchedule) {
logger.info(`Cancelled idle disconnect for ${directory} - state changed (${versionAtSchedule} -> ${currentVersion})`)
return
}
const sessions = this.activeSessions.get(directory)
const hasViewers = this.hasActiveViewers(directory)
if ((!sessions || sessions.size === 0) && !hasViewers) {
logger.info(`Idle disconnect: ${directory}`)
this.disconnectDirectory(directory)
} else if (hasViewers) {
logger.info(`Cancelled idle disconnect for ${directory} - has active viewers`)
}
}, IDLE_GRACE_PERIOD_MS)
this.idleTimeouts.set(directory, timeout)
}
getConnectionStatus(): { connected: number; total: number } {
let connected = 0
this.connections.forEach(conn => {
if (conn.isConnected) connected++
})
return { connected, total: this.connections.size }
const total = this.started ? 1 : 0
return { connected: this.upstreamConnected ? 1 : 0, total }
}
getClientCount(): number {
@@ -410,30 +435,7 @@ class SSEAggregator {
}
getActiveDirectories(): string[] {
return Array.from(this.connections.keys())
}
shutdown(): void {
this.idleTimeouts.forEach((timeout) => {
clearTimeout(timeout)
})
this.idleTimeouts.clear()
this.activeSessions.clear()
this.subagentSessions.clear()
this.sessionStateVersion.clear()
this.connections.forEach((conn, dir) => {
if (conn.reconnectTimeout) {
clearTimeout(conn.reconnectTimeout)
}
if (conn.eventSource) {
conn.eventSource.close()
}
logger.info(`SSE closed: ${dir}`)
})
this.connections.clear()
this.clients.clear()
this.eventListeners.clear()
return Array.from(this.activeSessions.keys())
}
getActiveSessions(): Record<string, string[]> {
@@ -444,6 +446,25 @@ class SSEAggregator {
return result
}
shutdown(): void {
this.started = false
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.upstream) {
this.upstream.close()
this.upstream = null
}
this.upstreamConnected = false
this.activeSessions.clear()
this.subagentSessions.clear()
this.clients.clear()
this.eventListeners.clear()
}
broadcastToAll(event: string, data: string): void {
this.clients.forEach((client) => {
try {
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest'
import { TokenBucketRateLimiter } from './rate-limit'
describe('TokenBucketRateLimiter', () => {
it('allows first 10 calls within capacity', () => {
const limiter = new TokenBucketRateLimiter({ capacity: 10, refillPerMs: 6000 })
const results: boolean[] = []
for (let i = 0; i < 10; i++) {
const result = limiter.tryConsume('test-key')
results.push(result.allowed)
}
expect(results.every((r) => r)).toBe(true)
})
it('rejects 11th call within rate window', () => {
const limiter = new TokenBucketRateLimiter({ capacity: 10, refillPerMs: 6000 })
for (let i = 0; i < 10; i++) {
limiter.tryConsume('test-key')
}
const result = limiter.tryConsume('test-key')
expect(result.allowed).toBe(false)
expect(result.retryAfterMs).toBeGreaterThan(0)
})
it('refills tokens after time advances', () => {
let currentTime = 0
const limiter = new TokenBucketRateLimiter(
{ capacity: 10, refillPerMs: 10000 },
() => currentTime,
)
for (let i = 0; i < 10; i++) {
limiter.tryConsume('test-key')
}
let result = limiter.tryConsume('test-key')
expect(result.allowed).toBe(false)
currentTime = 5000
result = limiter.tryConsume('test-key')
expect(result.allowed).toBe(true)
})
it('maintains independent buckets for distinct keys', () => {
const limiter = new TokenBucketRateLimiter({ capacity: 10, refillPerMs: 6000 })
for (let i = 0; i < 10; i++) {
limiter.tryConsume('key-a')
}
const resultA = limiter.tryConsume('key-a')
const resultB = limiter.tryConsume('key-b')
expect(resultA.allowed).toBe(false)
expect(resultB.allowed).toBe(true)
})
})
+47
View File
@@ -0,0 +1,47 @@
export interface RateLimiterOptions {
capacity: number
refillPerMs: number
}
interface BucketState {
tokens: number
lastRefill: number
}
export class TokenBucketRateLimiter {
private buckets: Map<string, BucketState>
constructor(
private opts: RateLimiterOptions,
private now: () => number = Date.now,
) {
this.buckets = new Map()
}
tryConsume(key: string, cost = 1): { allowed: boolean; retryAfterMs: number } {
const bucket = this.buckets.get(key) ?? this.createBucket(key)
const elapsed = this.now() - bucket.lastRefill
const refill = (elapsed / this.opts.refillPerMs) * this.opts.capacity
bucket.tokens = Math.min(bucket.tokens + refill, this.opts.capacity)
bucket.lastRefill = this.now()
if (bucket.tokens >= cost) {
bucket.tokens -= cost
return { allowed: true, retryAfterMs: 0 }
}
const tokensNeeded = cost - bucket.tokens
const retryAfterMs = (tokensNeeded / this.opts.capacity) * this.opts.refillPerMs
return { allowed: false, retryAfterMs }
}
private createBucket(key: string): BucketState {
const state: BucketState = {
tokens: this.opts.capacity,
lastRefill: this.now(),
}
this.buckets.set(key, state)
return state
}
}