feat: add skill installer (#279)

* feat: add skill installer with install/uninstall and settings UI

* feat: refactor skill installer with extracted SkillLibraryList component

* feat: simplify SkillsEditor, extract SkillLibraryList

* feat: refactor skill installer components and add github utility
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-17 23:11:29 -04:00
1 parent 24d34f28a3
commit 6e80cdfb8c
24 files changed
+2381 -577

No files matched your search

+2 -7
View File
@@ -4,6 +4,7 @@ import { readFile } from 'fs/promises'
import { opencodeServerManager } from '../services/opencode-single-server'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
import { compareVersions } from '../utils/version-utils'
import { githubFetch } from '../utils/github'
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
const GITHUB_REPO_NAME = 'opencode-manager'
@@ -24,14 +25,8 @@ async function fetchLatestRelease(): Promise<CachedRelease | null> {
}
try {
const response = await fetch(
const response = await githubFetch(
`https://api.github.com/repos/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}/releases/latest`,
{
headers: {
'Accept': 'application/vnd.github+json',
'User-Agent': 'OpenCode-Manager'
}
}
)
if (!response.ok) {
+213 -49
View File
@@ -18,6 +18,10 @@ import {
CreateSkillRequestSchema,
UpdateSkillRequestSchema,
SkillScopeSchema,
InstallSkillFromGithubRequestSchema,
InstallSkillUploadRequestSchema,
InstallSkillUploadManifestEntrySchema,
type SkillScope,
} from '@opencode-manager/shared'
import { logger } from '../utils/logger'
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
@@ -38,7 +42,11 @@ import {
createSkill,
updateSkill,
deleteSkill,
installSkillFromGithubTree,
installSkillFromUploadedFiles,
} from '../services/skills'
import { getRepoById } from '../db/queries'
import { githubFetch } from '../utils/github'
function getOpenCodeInstallMethod(): string {
const homePath = process.env.HOME || ''
@@ -92,6 +100,72 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise
await opencodeServerManager.restart()
}
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
try {
await restartOpenCode(openCodeSupervisor)
logger.info(`Restarted OpenCode server after skill ${context}`)
} catch (restartError) {
logger.warn(`Failed to restart OpenCode server after skill ${context}:`, restartError)
}
}
async function dispatchSkillReload(
db: Database,
openCodeClient: OpenCodeClient,
openCodeSupervisor: OpenCodeSupervisor | undefined,
repoId: number,
): Promise<void> {
const repo = getRepoById(db, repoId)
if (!repo) {
logger.warn(`Cannot dispatch skill reload: repo ${repoId} not found`)
return
}
await restartOpenCodeSafe(openCodeSupervisor, 'install')
try {
await openCodeClient.forward({
method: 'GET',
path: '/skill',
directory: repo.fullPath,
})
logger.info(`Dispatched skill reload for project ${repo.fullPath}`)
} catch (dispatchError) {
logger.warn('Failed to dispatch skill reload:', dispatchError)
}
}
async function reloadAfterSkillInstall(
db: Database,
openCodeClient: OpenCodeClient,
openCodeSupervisor: OpenCodeSupervisor | undefined,
scope: SkillScope,
repoId: number | undefined,
): Promise<void> {
if (scope === 'project' && repoId !== undefined) {
await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, repoId)
} else {
await restartOpenCodeSafe(openCodeSupervisor, 'install')
}
}
const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 404 | 409]> = [
['already exists', 409],
['404', 404],
['Invalid GitHub tree URL', 400],
['Invalid skill name', 400],
['Only one skill', 400],
['Skill source must contain', 400],
['Path must be relative', 400],
['Path must not contain', 400],
['escapes', 400],
['no downloadable files', 400],
['repoId is required', 400],
['Missing upload file', 400],
['Invalid repoId', 400],
['not a valid file', 400],
]
function didConfigFieldChange(
previous: Record<string, unknown> | undefined,
next: Record<string, unknown> | undefined,
@@ -107,6 +181,19 @@ function needsOpenCodeRestart(
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
}
function parseOptionalRepoId(value: string | undefined): number | undefined {
if (value === undefined) return undefined
const parsed = parseInt(value, 10)
if (isNaN(parsed)) throw new Error('Invalid repoId')
return parsed
}
function parseBooleanFormValue(value: unknown): boolean | undefined {
if (value === true || value === 'true') return true
if (value === false || value === 'false') return false
return undefined
}
function hasConfiguredPlugins(config: Record<string, unknown> | undefined): boolean {
return Array.isArray(config?.plugin) && config.plugin.length > 0
}
@@ -855,11 +942,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
try {
logger.info('Fetching available OpenCode versions from GitHub')
const response = await fetch('https://api.github.com/repos/sst/opencode/releases?per_page=20', {
headers: {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'opencode-manager'
}
const response = await githubFetch('https://api.github.com/repos/sst/opencode/releases?per_page=20', {
accept: 'application/vnd.github.v3+json',
})
if (!response.ok) {
@@ -1122,11 +1206,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
app.get('/skills', async (c) => {
try {
const repoIdParam = c.req.query('repoId')
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
if (repoId !== undefined && isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
const repoId = parseOptionalRepoId(c.req.query('repoId'))
const directory = c.req.query('directory')
const skills = await listManagedSkills(db, openCodeClient, repoId, directory)
@@ -1137,15 +1217,113 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
}
})
app.post('/skills/install', async (c) => {
try {
const contentType = c.req.header('content-type') || ''
if (contentType.includes('application/json')) {
const body = await c.req.json()
const validated = InstallSkillFromGithubRequestSchema.parse(body)
if (validated.scope === 'project' && validated.repoId === undefined) {
return c.json({ error: 'repoId is required for project scope' }, 400)
}
const result = await installSkillFromGithubTree(db, validated)
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId)
return c.json(result)
}
if (contentType.includes('multipart/form-data')) {
const formData = await c.req.parseBody({ all: true })
const scope = formData['scope']
const repoIdValue = formData['repoId']
const overwriteValue = formData['overwrite']
const fileManifestRaw = formData['fileManifest']
if (typeof fileManifestRaw !== 'string') {
return c.json({ error: 'fileManifest is required as a JSON string' }, 400)
}
let manifestEntries: unknown
try {
manifestEntries = JSON.parse(fileManifestRaw)
} catch {
return c.json({ error: 'fileManifest must be valid JSON' }, 400)
}
const manifest = InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries)
const repoId = parseOptionalRepoId(repoIdValue as string | undefined)
const overwrite = parseBooleanFormValue(overwriteValue)
const uploadRequest = InstallSkillUploadRequestSchema.parse({
sourceType: 'upload',
scope,
repoId,
overwrite,
})
if (scope === 'project' && repoId === undefined) {
return c.json({ error: 'repoId is required for project scope' }, 400)
}
if (manifest.length === 0) {
return c.json({ error: 'fileManifest must contain at least one entry' }, 400)
}
const missingFields = manifest.filter((entry) => !formData[entry.fieldName])
if (missingFields.length > 0) {
return c.json({
error: `Missing upload file(s): ${missingFields.map((e) => e.fieldName).join(', ')}`,
}, 400)
}
const files = await Promise.all(
manifest.map(async (entry) => {
const file = formData[entry.fieldName]
if (!file || !(file instanceof File)) {
throw new Error(`Field "${entry.fieldName}" is not a valid file`)
}
const content = Buffer.from(await file.arrayBuffer())
return { relativePath: entry.relativePath, content }
}),
)
const result = await installSkillFromUploadedFiles(db, uploadRequest, files)
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId)
return c.json(result)
}
return c.json({ error: 'Unsupported content type. Use application/json or multipart/form-data' }, 400)
} catch (error) {
logger.error('Failed to install skill:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid skill install data', details: error.issues }, 400)
}
if (error instanceof Error) {
const match = SKILL_INSTALL_ERROR_STATUS.find(([needle]) => error.message.includes(needle))
if (match) {
return c.json({ error: error.message }, match[1])
}
}
return c.json({ error: 'Failed to install skill' }, 500)
}
})
app.get('/skills/:name', async (c) => {
try {
const name = c.req.param('name')
const scope = SkillScopeSchema.parse(c.req.query('scope'))
const repoIdParam = c.req.query('repoId')
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
if (repoId !== undefined && isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
const repoId = parseOptionalRepoId(c.req.query('repoId'))
if (scope === 'project' && !repoId) {
return c.json({ error: 'repoId is required for project scope' }, 400)
@@ -1158,6 +1336,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400)
}
if (error instanceof Error && error.message.includes('Invalid repoId')) {
return c.json({ error: error.message }, 400)
}
if (error instanceof Error && error.message.includes('not found')) {
return c.json({ error: error.message }, 404)
}
@@ -1174,14 +1355,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const validated = CreateSkillRequestSchema.parse(body)
const skill = await createSkill(db, validated)
try {
await restartOpenCode(openCodeSupervisor)
logger.info('Restarted OpenCode server after skill creation')
} catch (restartError) {
logger.warn('Failed to restart OpenCode server after skill creation:', restartError)
}
await restartOpenCodeSafe(openCodeSupervisor, 'creation')
return c.json(skill)
} catch (error) {
logger.error('Failed to create skill:', error)
@@ -1199,11 +1375,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
try {
const name = c.req.param('name')
const scope = SkillScopeSchema.parse(c.req.query('scope'))
const repoIdParam = c.req.query('repoId')
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
if (repoId !== undefined && isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
const repoId = parseOptionalRepoId(c.req.query('repoId'))
const body = await c.req.json()
const validated = UpdateSkillRequestSchema.parse(body)
@@ -1212,20 +1384,18 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
}
const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId)
try {
await restartOpenCode(openCodeSupervisor)
logger.info('Restarted OpenCode server after skill update')
} catch (restartError) {
logger.warn('Failed to restart OpenCode server after skill update:', restartError)
}
await restartOpenCodeSafe(openCodeSupervisor, 'update')
return c.json(skill)
} catch (error) {
logger.error('Failed to update skill:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
if (error instanceof Error && error.message.includes('Invalid repoId')) {
return c.json({ error: error.message }, 400)
}
if (error instanceof Error && error.message.includes('not found')) {
return c.json({ error: error.message }, 404)
}
@@ -1240,31 +1410,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
try {
const name = c.req.param('name')
const scope = SkillScopeSchema.parse(c.req.query('scope'))
const repoIdParam = c.req.query('repoId')
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
if (repoId !== undefined && isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
const repoId = parseOptionalRepoId(c.req.query('repoId'))
if (scope === 'project' && !repoId) {
return c.json({ error: 'repoId is required for project scope' }, 400)
}
await deleteSkill(db, name, scope, repoId)
try {
await restartOpenCode(openCodeSupervisor)
logger.info('Restarted OpenCode server after skill deletion')
} catch (restartError) {
logger.warn('Failed to restart OpenCode server after skill deletion:', restartError)
}
await restartOpenCodeSafe(openCodeSupervisor, 'deletion')
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete skill:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400)
}
if (error instanceof Error && error.message.includes('Invalid repoId')) {
return c.json({ error: error.message }, 400)
}
if (error instanceof Error && error.message.includes('not found')) {
return c.json({ error: error.message }, 404)
}
+383 -24
View File
@@ -1,14 +1,16 @@
import os from 'os'
import path from 'path'
import { promises as fs } from 'fs'
import type { Database } from 'bun:sqlite'
import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest } from '@opencode-manager/shared'
import { SKILL_NAME_REGEX } from '@opencode-manager/shared'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest, InstallSkillUploadRequest, InstallSkillFromGithubRequest, InstallSkillResponse } from '@opencode-manager/shared'
import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shared'
import { getWorkspacePath, FILE_LIMITS } 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'
import { githubFetchJson, githubFetchBinary, type GithubFetchFn } from '../utils/github'
interface OpenCodeSkillInfo {
name: string
@@ -17,6 +19,308 @@ interface OpenCodeSkillInfo {
content: string
}
interface SkillInstallFile {
relativePath: string
content: Buffer
}
interface PreparedSkillFiles {
skillName: string
description: string
body: string
files: SkillInstallFile[]
filesInstalled: string[]
}
function getSkillTargetRoot(db: Database, scope: SkillScope, repoId?: number): string {
if (scope === 'global') {
return getGlobalSkillsPath()
}
if (repoId === undefined) {
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 getProjectSkillsPath(repo)
}
function normalizeInstallRelativePath(relativePath: string): string {
const normalized = relativePath.replace(/\\/g, '/')
if (path.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) {
throw new Error(`Path must be relative, got absolute path: "${relativePath}"`)
}
if (normalized === '' || normalized === '.') {
throw new Error('Path must not be empty')
}
const parts = normalized.split('/')
for (const part of parts) {
if (part === '..') {
throw new Error(`Path must not contain "..": "${relativePath}"`)
}
}
return normalized
}
function parseSkillMarkdown(content: string): { name: string; description: string; body: string } {
if (!content.startsWith('---\n')) {
throw new Error('Skill markdown must start with a frontmatter block')
}
const endIndex = content.indexOf('\n---\n', 4)
if (endIndex === -1) {
throw new Error('Skill markdown must have a closing frontmatter delimiter')
}
const frontmatterBlock = content.substring(4, endIndex)
const body = content.substring(endIndex + 5)
const lines = frontmatterBlock.split('\n')
const frontmatter: Record<string, string> = {}
for (const line of lines) {
const colonIndex = line.indexOf(':')
if (colonIndex === -1) continue
const key = line.substring(0, colonIndex).trim()
let value = line.substring(colonIndex + 1).trim()
if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith('"') && value.endsWith('"'))) {
value = value.substring(1, value.length - 1)
}
frontmatter[key] = value
}
const parsed = SkillFrontmatterSchema.parse({
name: frontmatter.name,
description: frontmatter.description,
})
return {
name: parsed.name,
description: parsed.description,
body,
}
}
function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles {
const normalized = files.map(f => ({
...f,
relativePath: normalizeInstallRelativePath(f.relativePath),
}))
const skillMdFiles = normalized.filter(f => path.basename(f.relativePath) === 'SKILL.md')
if (skillMdFiles.length === 0) {
throw new Error('Skill source must contain SKILL.md')
}
if (skillMdFiles.length > 1) {
throw new Error('Only one skill can be installed at a time')
}
const skillMd = skillMdFiles[0]!
const skillDir = path.dirname(skillMd.relativePath)
const { name, description, body } = parseSkillMarkdown(skillMd.content.toString('utf-8'))
const prefix = skillDir === '.' ? '' : skillDir + '/'
const strippedFiles = normalized
.filter(f => f.relativePath === skillMd.relativePath || f.relativePath.startsWith(prefix))
.map(f => ({
...f,
relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length),
}))
for (const f of strippedFiles) {
const checkPath = normalizeInstallRelativePath(f.relativePath)
if (checkPath.startsWith('..')) {
throw new Error(`File "${f.relativePath}" escapes the skill directory`)
}
}
const filesInstalled = strippedFiles.map(f => f.relativePath)
return {
skillName: name,
description,
body,
files: strippedFiles,
filesInstalled,
}
}
async function installSkillFiles(
db: Database,
input: InstallSkillUploadRequest | InstallSkillFromGithubRequest,
files: SkillInstallFile[],
): Promise<InstallSkillResponse> {
const prepared = prepareSingleSkillFiles(files)
const targetRoot = getSkillTargetRoot(db, input.scope, input.repoId)
const targetDir = path.join(targetRoot, prepared.skillName)
const skillPath = path.join(targetDir, 'SKILL.md')
const targetDirExists = await fileExists(targetDir)
const targetSkillExists = await fileExists(skillPath)
const existingTarget = targetDirExists || targetSkillExists
if (existingTarget && input.overwrite !== true) {
throw new Error(`Skill "${prepared.skillName}" already exists in ${input.scope} scope`)
}
await fs.mkdir(targetRoot, { recursive: true })
const stagingDir = await fs.mkdtemp(path.join(targetRoot, `.${prepared.skillName}-install-`))
try {
for (const file of prepared.files) {
const targetFilePath = path.resolve(stagingDir, file.relativePath)
if (!targetFilePath.startsWith(stagingDir + path.sep)) {
throw new Error(`File "${file.relativePath}" escapes the staging directory`)
}
await fs.mkdir(path.dirname(targetFilePath), { recursive: true })
await fs.writeFile(targetFilePath, file.content)
}
if (existingTarget && input.overwrite === true) {
await fs.rm(targetDir, { recursive: true, force: true })
}
await fs.rename(stagingDir, targetDir)
const repo = input.repoId !== undefined ? getRepoById(db, input.repoId) : null
return {
skill: {
name: prepared.skillName,
description: prepared.description,
body: prepared.body,
scope: input.scope,
location: skillPath,
repoId: input.scope === 'project' ? input.repoId : undefined,
repoName: repo?.localPath,
},
overwritten: Boolean(existingTarget),
sourceType: input.sourceType,
filesInstalled: prepared.filesInstalled,
}
} catch (error) {
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {})
throw error
}
}
export async function installSkillFromUploadedFiles(
db: Database,
input: InstallSkillUploadRequest,
files: SkillInstallFile[],
): Promise<InstallSkillResponse> {
return installSkillFiles(db, input, files)
}
interface GithubTreeSource {
owner: string
repo: string
ref: string
path: string
}
interface GithubContentEntry {
name: string
path: string
type: 'file' | 'dir'
download_url?: string | null
}
function parseGithubTreeUrl(url: string): GithubTreeSource {
let parsed: URL
try {
parsed = new URL(url)
} catch {
throw new Error('Invalid GitHub tree URL')
}
if (parsed.protocol !== 'https:' || parsed.host !== 'github.com') {
throw new Error('Invalid GitHub tree URL: only https://github.com is supported')
}
const segments = parsed.pathname.split('/').filter(Boolean)
if (segments.length < 4 || segments[2] !== 'tree') {
throw new Error('Invalid GitHub tree URL: must be a tree URL (github.com/owner/repo/tree/ref/path)')
}
const owner = segments[0]!
const repo = segments[1]!
const ref = segments[3]!
const path = segments.slice(4).join('/')
if (!path) {
throw new Error('Invalid GitHub tree URL: path is required')
}
return { owner, repo, ref, path }
}
function githubContentsApiUrl(source: GithubTreeSource, path: string): string {
const encodedPath = path.split('/').map(encodeURIComponent).join('/')
return `https://api.github.com/repos/${source.owner}/${source.repo}/contents/${encodedPath}?ref=${encodeURIComponent(source.ref)}`
}
async function fetchGithubSkillFiles(
source: GithubTreeSource,
fetchFn: GithubFetchFn = fetch,
): Promise<SkillInstallFile[]> {
const apiUrl = githubContentsApiUrl(source, source.path)
const data = await githubFetchJson(apiUrl, {}, fetchFn)
if (!Array.isArray(data)) {
const entry = data as GithubContentEntry
if (entry.name !== 'SKILL.md') {
throw new Error('GitHub tree URL must point to a skill folder containing SKILL.md')
}
const buffer = await githubFetchBinary(entry.download_url!, {}, fetchFn)
const content = Buffer.from(buffer)
if (content.length > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
throw new Error('Skill files exceed maximum upload size')
}
return [{ relativePath: 'SKILL.md', content }]
}
const MAX_FILES = 100
async function collectFileEntries(entries: GithubContentEntry[]): Promise<GithubContentEntry[]> {
const fileEntries = entries.filter((entry) => entry.type === 'file' && entry.download_url)
const dirEntries = entries.filter((entry) => entry.type === 'dir')
const nested = await Promise.all(
dirEntries.map(async (dir) => {
const dirData = await githubFetchJson(githubContentsApiUrl(source, dir.path), {}, fetchFn)
return Array.isArray(dirData) ? collectFileEntries(dirData as GithubContentEntry[]) : []
}),
)
return [...fileEntries, ...nested.flat()]
}
const collected = await collectFileEntries(data as GithubContentEntry[])
if (collected.length > MAX_FILES) {
throw new Error(`Skill contains too many files (max ${MAX_FILES})`)
}
const files = await Promise.all(
collected.map(async (entry) => {
const relativePath = entry.path.startsWith(source.path + '/')
? entry.path.substring(source.path.length + 1)
: entry.path
const arrayBuffer = await githubFetchBinary(entry.download_url!, {}, fetchFn)
return { relativePath, content: Buffer.from(arrayBuffer) }
}),
)
const totalBytes = files.reduce((sum, file) => sum + file.content.length, 0)
if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
throw new Error('Skill files exceed maximum upload size')
}
if (files.length === 0) {
throw new Error('GitHub tree URL contains no downloadable files')
}
return files
}
export async function installSkillFromGithubTree(
db: Database,
input: InstallSkillFromGithubRequest,
fetchFn: GithubFetchFn = fetch,
): Promise<InstallSkillResponse> {
const source = parseGithubTreeUrl(input.url)
const files = await fetchGithubSkillFiles(source, fetchFn)
return installSkillFiles(db, input, files)
}
function getGlobalSkillsPath(): string {
return path.join(getWorkspacePath(), '.config', 'opencode', 'skills')
}
@@ -89,17 +393,8 @@ function validateSkillName(name: string): void {
function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string {
validateSkillName(name)
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')
const targetRoot = getSkillTargetRoot(db, scope, repoId)
return path.join(targetRoot, name, 'SKILL.md')
}
function buildSkillFileContent(name: string, description: string, body: string): string {
@@ -133,18 +428,18 @@ function classifySkillLocation(
if (location.startsWith(globalPrefix + path.sep)) {
return { scope: 'global' }
}
if (customDirectory) {
const projectPrefix = path.join(customDirectory, '.opencode', 'skills')
if (location.startsWith(projectPrefix + path.sep)) {
return { scope: 'project' }
}
}
for (const repo of repos) {
const projectPrefix = getProjectSkillsPath(repo)
if (location.startsWith(projectPrefix + path.sep)) {
return { scope: 'project', repo }
}
}
if (customDirectory) {
const projectPrefix = path.join(customDirectory, '.opencode', 'skills')
if (location.startsWith(projectPrefix + path.sep)) {
return { scope: 'project' }
}
}
return null
}
@@ -163,6 +458,54 @@ function toSkillFileInfo(
}
}
async function scanSkillRoot(root: string, scope: SkillScope, repo?: Repo): Promise<SkillFileInfo[]> {
if (!await fileExists(root)) {
return []
}
let entries: Awaited<ReturnType<typeof listDirectory>>
try {
entries = await listDirectory(root)
} catch (error) {
logger.warn(`Failed to scan skills at ${root}:`, error)
return []
}
const scanned = await Promise.all(
entries
.filter((entry) => entry.isDirectory)
.map(async (entry): Promise<SkillFileInfo | null> => {
const skillPath = path.join(entry.path, 'SKILL.md')
if (!await fileExists(skillPath)) return null
try {
const content = await readFileContent(skillPath)
const parsed = parseSkillMarkdown(content)
return {
name: parsed.name,
description: parsed.description,
body: parsed.body,
scope,
location: skillPath,
repoId: scope === 'project' ? repo?.id : undefined,
repoName: scope === 'project' ? repo?.localPath : undefined,
}
} catch (error) {
logger.warn(`Failed to read skill at ${skillPath}:`, error)
return null
}
}),
)
return scanned.filter((skill): skill is SkillFileInfo => skill !== null)
}
function addSkill(result: SkillFileInfo[], seenLocations: Set<string>, skill: SkillFileInfo): void {
if (seenLocations.has(skill.location)) return
seenLocations.add(skill.location)
result.push(skill)
}
export async function listManagedSkills(
db: Database,
openCodeClient: OpenCodeClient,
@@ -181,8 +524,16 @@ export async function listManagedSkills(
if (seenLocations.has(skill.location)) continue
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos, directory)
if (!classification) continue
seenLocations.add(skill.location)
result.push(toSkillFileInfo(skill, classification))
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
}
const repo = allRepos.find(r => r.fullPath === directory)
const fallbackSkills = (await Promise.all([
scanSkillRoot(globalPrefix, 'global'),
scanSkillRoot(path.join(directory, '.opencode', 'skills'), 'project', repo),
])).flat()
for (const skill of fallbackSkills) {
addSkill(result, seenLocations, skill)
}
} else {
const targetRepos = repoId
@@ -203,10 +554,18 @@ export async function listManagedSkills(
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))
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
}
}
const [globalFallback, repoFallbacks] = await Promise.all([
scanSkillRoot(globalPrefix, 'global'),
Promise.all(targetRepos.map(repo => scanSkillRoot(getProjectSkillsPath(repo), 'project', repo))),
])
const fallbackSkills = [...globalFallback, ...repoFallbacks.flat()]
for (const skill of fallbackSkills) {
addSkill(result, seenLocations, skill)
}
}
return result
+3 -14
View File
@@ -1,4 +1,5 @@
import type { GitCredential } from '@opencode-manager/shared'
import { githubFetch } from './github'
export function isGitHubHttpsUrl(repoUrl: string): boolean {
const url = normalizeGitCredentialUrl(repoUrl)
@@ -202,20 +203,8 @@ export function createGitIdentityEnv(identity: GitIdentity): Record<string, stri
export async function fetchGitHubUserInfo(token: string): Promise<GitHubUserInfo | null> {
try {
const [userResponse, emailsResponse] = await Promise.all([
fetch('https://api.github.com/user', {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28'
}
}),
fetch('https://api.github.com/user/emails', {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28'
}
})
githubFetch('https://api.github.com/user', { token, apiVersion: '2022-11-28' }),
githubFetch('https://api.github.com/user/emails', { token, apiVersion: '2022-11-28' }),
])
if (!userResponse.ok) return null
+45
View File
@@ -0,0 +1,45 @@
export type GithubFetchFn = (url: string | URL | Request, init?: RequestInit) => Promise<Response>
interface GithubRequestOptions {
token?: string
apiVersion?: string
accept?: string
}
export function githubFetch(
url: string,
options: GithubRequestOptions = {},
fetchFn: GithubFetchFn = fetch,
): Promise<Response> {
const headers: Record<string, string> = {
Accept: options.accept ?? 'application/vnd.github+json',
'User-Agent': 'opencode-manager',
}
if (options.token) headers.Authorization = `Bearer ${options.token}`
if (options.apiVersion) headers['X-GitHub-Api-Version'] = options.apiVersion
return fetchFn(url, { headers })
}
export async function githubFetchJson<T = unknown>(
url: string,
options: GithubRequestOptions = {},
fetchFn: GithubFetchFn = fetch,
): Promise<T> {
const response = await githubFetch(url, options, fetchFn)
if (!response.ok) {
throw new Error(`GitHub request failed with status ${response.status}`)
}
return response.json() as Promise<T>
}
export async function githubFetchBinary(
url: string,
options: GithubRequestOptions = {},
fetchFn: GithubFetchFn = fetch,
): Promise<ArrayBuffer> {
const response = await githubFetch(url, options, fetchFn)
if (!response.ok) {
throw new Error(`GitHub request failed with status ${response.status}`)
}
return response.arrayBuffer()
}