mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)
This commit is contained in:
1 parent
3cc24288a6
commit
c3d6549f01
133 files changed
+7284
-6293
No files matched your search
@@ -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,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
export type OpenCodePasswordResolver = () => string | Promise<string>
|
||||
|
||||
export function getOpenCodeBasicAuthHeader(): string | null
|
||||
export function getOpenCodeBasicAuthHeader(password: string): string | null
|
||||
export function getOpenCodeBasicAuthHeader(passwordResolver: OpenCodePasswordResolver): Promise<string | null>
|
||||
export function getOpenCodeBasicAuthHeader(source?: string | OpenCodePasswordResolver): string | null | Promise<string | null> {
|
||||
if (typeof source === 'function') {
|
||||
return Promise.resolve(source()).then((password) => getOpenCodeBasicAuthHeader(password))
|
||||
}
|
||||
|
||||
const password = source ?? ENV.OPENCODE.SERVER_PASSWORD
|
||||
const username = ENV.OPENCODE.SERVER_USERNAME
|
||||
if (!password) return null
|
||||
const token = Buffer.from(`${username}:${password}`).toString('base64')
|
||||
return `Basic ${token}`
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
|
||||
|
||||
export interface ForwardRequest {
|
||||
method: string
|
||||
path: string
|
||||
body?: string
|
||||
headers?: Record<string, string>
|
||||
directory?: string
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface JsonRequestOptions {
|
||||
directory?: string
|
||||
headers?: Record<string, string>
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export class UpstreamError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
public readonly bodyText: string,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `OpenCode upstream returned ${status}`)
|
||||
this.name = 'UpstreamError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenCodeClient {
|
||||
forward(req: ForwardRequest): Promise<Response>
|
||||
forwardRaw(request: Request): Promise<Response>
|
||||
getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T>
|
||||
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
|
||||
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
|
||||
deleteProviderAuth(providerId: string): Promise<boolean>
|
||||
startMcpAuth(serverName: string, directory?: string): Promise<Response>
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export interface FetchOpenCodeClientConfig {
|
||||
baseUrl: string
|
||||
basicAuth: string | null
|
||||
passwordResolver?: OpenCodePasswordResolver
|
||||
fetchFn?: typeof fetch
|
||||
}
|
||||
|
||||
export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
constructor(private readonly config: FetchOpenCodeClientConfig) {}
|
||||
|
||||
private get fetchFn(): typeof fetch {
|
||||
return this.config.fetchFn ?? fetch
|
||||
}
|
||||
|
||||
private async getBasicAuth(): Promise<string> {
|
||||
if (!this.config.passwordResolver) {
|
||||
return this.config.basicAuth ?? ''
|
||||
}
|
||||
|
||||
return await getOpenCodeBasicAuthHeader(this.config.passwordResolver) ?? ''
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.config.baseUrl + req.path)
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { ...(req.headers ?? {}) }
|
||||
const basicAuth = await this.getBasicAuth()
|
||||
|
||||
if (basicAuth) {
|
||||
headers.Authorization = basicAuth
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.fetchFn(url, {
|
||||
method: req.method,
|
||||
headers,
|
||||
body: req.body,
|
||||
signal: req.signal,
|
||||
})
|
||||
|
||||
const filteredHeaders: Record<string, string> = {}
|
||||
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!skipHeaders.has(key.toLowerCase())) {
|
||||
filteredHeaders[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const noBodyStatuses = new Set([101, 204, 205, 304])
|
||||
if (noBodyStatuses.has(response.status)) {
|
||||
return new Response(null, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: filteredHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
const body = await response.text()
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: filteredHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Proxy request failed for ${req.path}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async forward(req: ForwardRequest): Promise<Response> {
|
||||
return this.request(req)
|
||||
}
|
||||
|
||||
async forwardRaw(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
|
||||
|
||||
if (url.pathname.includes('/permissions/')) {
|
||||
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${cleanPathname}${url.search}`)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
request.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!['host', 'connection', 'authorization'].includes(lowerKey)) {
|
||||
headers[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const body = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
? await request.text()
|
||||
: undefined
|
||||
|
||||
return this.request({
|
||||
method: request.method,
|
||||
path: cleanPathname + url.search,
|
||||
body,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
async getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T> {
|
||||
const response = await this.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
directory: opts?.directory,
|
||||
headers: opts?.headers,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(opts?.headers ?? {}),
|
||||
}
|
||||
|
||||
const response = await this.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: JSON.stringify(body),
|
||||
headers,
|
||||
directory: opts?.directory,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async setProviderAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'PUT',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Set OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to set OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async deleteProviderAuth(providerId: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'DELETE',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to delete OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async startMcpAuth(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async authenticateMcp(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(passwordOverride?: string | OpenCodePasswordResolver): OpenCodeClient {
|
||||
const host = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
|
||||
const baseUrl = `http://${host}:${ENV.OPENCODE.PORT}`
|
||||
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
|
||||
return new FetchOpenCodeClient({ baseUrl, basicAuth, passwordResolver })
|
||||
}
|
||||
@@ -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' },
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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
@@ -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)}`)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user