mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)
* feat(opencode): migrate OpenCode Manager to OpenCode 2 Port the backend lifecycle, generated plugins, event aggregation, schedules, worktrees, provider credentials, MCP, config handling, the frontend chat model, and the ocm CLI to OpenCode 2. Adopt @opencode/client 2.0.15 as the single typed V2 API contract, require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every V1-only code path. * refactor(opencode): reload config in place and drop v1 compatibility shims Route config/skill/AGENTS.md changes through the OpenCode location reload API instead of a full server restart, stop auto-resuming interrupted sessions, remove the restart coordinator and v1 MCP/version shims, and pin support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries, service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers. * refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows - extract shared semver and model-ref utilities, reuse across version checks - share the OpenCode release download script across Docker, entrypoint, dev setup - unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN - scope the repo proxy location rewrite and surface ocm proxy errors - rework frontend session projection, permission lookup, and cache invalidation * fix(schedules): reject unavailable agents before creating a session * feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
1 parent
6c2ebd764b
commit
dacde879d6
383 files changed
+29905
-46566
No files matched your search
+3
-2
@@ -16,9 +16,11 @@
|
||||
"./config/client": "./src/config/client.ts",
|
||||
"./utils": "./src/utils/index.ts",
|
||||
"./notifications": "./src/notifications/index.ts",
|
||||
"./project-id": "./src/project-id-resolver.ts"
|
||||
"./project-id": "./src/project-id-resolver.ts",
|
||||
"./opencode": "./src/opencode/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@opencode/client": "2.0.15",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
@@ -29,7 +31,6 @@
|
||||
"dotenv": "^17.2.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@opencode-ai/sdk": "1.18.31",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ export const DEFAULTS = {
|
||||
OPENCODE: {
|
||||
PORT: 5551,
|
||||
HOST: '127.0.0.1',
|
||||
PUBLIC_URL: '', // Optional: public URL for OAuth callbacks (e.g., https://mydomain.com)
|
||||
HEALTH_WATCH_ENABLED: true,
|
||||
HEALTH_POLL_MS: 30000,
|
||||
HEALTH_FAILURE_THRESHOLD: 2,
|
||||
@@ -28,7 +27,6 @@ export const DEFAULTS = {
|
||||
REPOS_DIR: 'repos',
|
||||
SCHEDULE_WORKTREES_DIR: 'schedule-worktrees',
|
||||
CONFIG_DIR: '.config/opencode',
|
||||
AUTH_FILE: '.opencode/state/opencode/auth.json',
|
||||
},
|
||||
|
||||
SANDBOX: {
|
||||
@@ -100,9 +98,11 @@ export const GIT_PROVIDERS = {
|
||||
BITBUCKET: 'bitbucket.org',
|
||||
} as const
|
||||
|
||||
export const OPENCODE_CONFIG_SOURCE_NAMES = ['config.json', 'opencode.json', 'opencode.jsonc'] as const
|
||||
export const OPENCODE_CONFIG_SOURCE_NAMES = ['opencode.json', 'opencode.jsonc'] as const
|
||||
export type OpenCodeConfigSourceName = (typeof OPENCODE_CONFIG_SOURCE_NAMES)[number]
|
||||
|
||||
export const LEGACY_OPENCODE_CONFIG_SOURCE_NAME = 'config.json'
|
||||
|
||||
export type Config = typeof DEFAULTS
|
||||
export type AllowedMimeType = (typeof ALLOWED_MIME_TYPES)[number]
|
||||
export type GitProvider = (typeof GIT_PROVIDERS)[keyof typeof GIT_PROVIDERS]
|
||||
@@ -67,12 +67,11 @@ export const ENV = {
|
||||
OPENCODE: {
|
||||
PORT: getEnvNumber('OPENCODE_SERVER_PORT', DEFAULTS.OPENCODE.PORT),
|
||||
HOST: getEnvString('OPENCODE_HOST', DEFAULTS.OPENCODE.HOST),
|
||||
PUBLIC_URL: getEnvString('OPENCODE_PUBLIC_URL', ''), // Public URL for OAuth callbacks
|
||||
HEALTH_WATCH_ENABLED: getEnvBoolean('OPENCODE_HEALTH_WATCH_ENABLED', defaultHealthWatchEnabled),
|
||||
HEALTH_POLL_MS: getEnvNumber('OPENCODE_HEALTH_POLL_MS', DEFAULTS.OPENCODE.HEALTH_POLL_MS),
|
||||
HEALTH_FAILURE_THRESHOLD: getEnvNumber('OPENCODE_HEALTH_FAILURE_THRESHOLD', DEFAULTS.OPENCODE.HEALTH_FAILURE_THRESHOLD),
|
||||
SERVER_PASSWORD: getEnvString('OPENCODE_SERVER_PASSWORD', ''),
|
||||
SERVER_USERNAME: getEnvString('OPENCODE_SERVER_USERNAME', 'opencode'),
|
||||
LEGACY_PUBLIC_URL: getEnvString('OPENCODE_PUBLIC_URL', ''),
|
||||
},
|
||||
|
||||
DATABASE: {
|
||||
@@ -85,7 +84,6 @@ export const ENV = {
|
||||
REPOS_DIR: DEFAULTS.WORKSPACE.REPOS_DIR,
|
||||
SCHEDULE_WORKTREES_DIR: DEFAULTS.WORKSPACE.SCHEDULE_WORKTREES_DIR,
|
||||
CONFIG_DIR: DEFAULTS.WORKSPACE.CONFIG_DIR,
|
||||
AUTH_FILE: DEFAULTS.WORKSPACE.AUTH_FILE,
|
||||
},
|
||||
|
||||
SANDBOX: {
|
||||
@@ -162,7 +160,6 @@ export const getConfigPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSP
|
||||
export { OPENCODE_CONFIG_SOURCE_NAMES } from './defaults'
|
||||
export const getOpenCodeConfigFilePath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR, 'opencode.json')
|
||||
export const getAgentsMdPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR, 'AGENTS.md')
|
||||
export const getAuthPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.AUTH_FILE)
|
||||
export const getDatabasePath = () => ENV.DATABASE.PATH
|
||||
|
||||
export const getApiUrl = (port: number = ENV.SERVER.PORT): string => {
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
const PERMISSION_LABELS: Record<string, string> = {
|
||||
read: 'Read File',
|
||||
edit: 'Edit File',
|
||||
write: 'Write File',
|
||||
glob: 'Search Files',
|
||||
grep: 'Search Content',
|
||||
list: 'List Directory',
|
||||
bash: 'Run Command',
|
||||
task: 'Run Task',
|
||||
shell: 'Run Command',
|
||||
subagent: 'Run Subagent',
|
||||
external_directory: 'External Access',
|
||||
todowrite: 'Write Todo',
|
||||
todoread: 'Read Todo',
|
||||
question: 'Ask Question',
|
||||
webfetch: 'Fetch URL',
|
||||
websearch: 'Web Search',
|
||||
codesearch: 'Code Search',
|
||||
lsp: 'LSP Action',
|
||||
doom_loop: 'Repeated Action',
|
||||
skill: 'Use Skill',
|
||||
}
|
||||
|
||||
export function getPermissionLabel(permission: string): string {
|
||||
@@ -24,9 +18,9 @@ export function getPermissionLabel(permission: string): string {
|
||||
}
|
||||
|
||||
interface PermissionLike {
|
||||
permission?: unknown
|
||||
action?: unknown
|
||||
metadata?: unknown
|
||||
patterns?: unknown
|
||||
resources?: unknown
|
||||
}
|
||||
|
||||
export interface PermissionDetail {
|
||||
@@ -35,21 +29,18 @@ export interface PermissionDetail {
|
||||
}
|
||||
|
||||
export function getPermissionDetail(input: PermissionLike): PermissionDetail {
|
||||
const permission = typeof input.permission === 'string' ? input.permission : ''
|
||||
const action = typeof input.action === 'string' ? input.action : ''
|
||||
const metadata = (input.metadata && typeof input.metadata === 'object' ? input.metadata : {}) as Record<string, unknown>
|
||||
const resources = Array.isArray(input.resources) ? input.resources.filter((resource): resource is string => typeof resource === 'string') : []
|
||||
const str = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 ? v : undefined)
|
||||
|
||||
switch (permission) {
|
||||
case 'bash': {
|
||||
const command = str(metadata.command)
|
||||
if (command) return { primary: command }
|
||||
break
|
||||
}
|
||||
case 'edit':
|
||||
case 'write': {
|
||||
const filePath = str(metadata.filePath)
|
||||
switch (action) {
|
||||
case 'edit': {
|
||||
const files = Array.isArray(metadata.files) ? metadata.files : []
|
||||
const first = (files[0] && typeof files[0] === 'object' ? files[0] : {}) as Record<string, unknown>
|
||||
const filePath = str(first.file) ?? str(metadata.filepath)
|
||||
if (filePath) {
|
||||
const diff = str(metadata.diff)
|
||||
const diff = str(first.patch) ?? str(metadata.diff)
|
||||
return { primary: filePath, secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined }
|
||||
}
|
||||
break
|
||||
@@ -59,35 +50,15 @@ export function getPermissionDetail(input: PermissionLike): PermissionDetail {
|
||||
if (url) return { primary: url }
|
||||
break
|
||||
}
|
||||
case 'external_directory': {
|
||||
const value = str(metadata.command) ?? str(metadata.filepath)
|
||||
if (value) return { primary: value }
|
||||
break
|
||||
}
|
||||
case 'doom_loop': {
|
||||
const tool = str(metadata.tool)
|
||||
if (tool) {
|
||||
const input2 = metadata.input
|
||||
return { primary: `Tool: ${tool}`, secondary: input2 ? JSON.stringify(input2, null, 2).slice(0, 300) : undefined }
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return { primary: fallbackPattern(input) }
|
||||
return { primary: resources.join('\n') }
|
||||
}
|
||||
|
||||
function fallbackPattern(input: PermissionLike): string {
|
||||
const patterns = Array.isArray(input.patterns) ? input.patterns.filter((p): p is string => typeof p === 'string') : []
|
||||
return patterns.join('\n')
|
||||
interface FormLike {
|
||||
title?: unknown
|
||||
}
|
||||
|
||||
interface QuestionLike {
|
||||
questions?: unknown
|
||||
}
|
||||
|
||||
export function getQuestionText(input: QuestionLike): string {
|
||||
const questions = Array.isArray(input.questions) ? input.questions : []
|
||||
const first = questions[0] as { question?: unknown } | undefined
|
||||
return first && typeof first.question === 'string' && first.question.length > 0 ? first.question : ''
|
||||
export function getFormText(form: FormLike | null | undefined): string {
|
||||
return form && typeof form.title === 'string' && form.title.length > 0 ? form.title : ''
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { SessionMessageAssistant, ToolContent } from '@opencode/client'
|
||||
|
||||
const THINK_BLOCK_PATTERN = /<think>[\s\S]*?<\/think>\s*/g
|
||||
|
||||
export function sessionIDFromEvent(event: { data: unknown }): string | undefined {
|
||||
const data = event.data
|
||||
if (typeof data !== 'object' || data === null) return undefined
|
||||
if (!('sessionID' in data) || typeof data.sessionID !== 'string') return undefined
|
||||
return data.sessionID
|
||||
}
|
||||
|
||||
export interface AssistantTextOptions {
|
||||
stripThink?: boolean
|
||||
}
|
||||
|
||||
export function assistantText(
|
||||
content: SessionMessageAssistant['content'] | undefined,
|
||||
options: AssistantTextOptions = {},
|
||||
): string {
|
||||
const texts = (content ?? []).filter((part) => part.type === 'text').map((part) => part.text)
|
||||
if (!options.stripThink) return texts.join('\n\n')
|
||||
return texts
|
||||
.map((text) => text.replace(THINK_BLOCK_PATTERN, '').trim())
|
||||
.filter(Boolean)
|
||||
.join('\n\n')
|
||||
}
|
||||
|
||||
export interface ToolContentTextOptions {
|
||||
separator?: string
|
||||
}
|
||||
|
||||
export function toolContentText(
|
||||
content: readonly ToolContent[] | undefined,
|
||||
options: ToolContentTextOptions = {},
|
||||
): string {
|
||||
return (content ?? [])
|
||||
.filter((entry) => entry.type === 'text')
|
||||
.map((entry) => entry.text)
|
||||
.join(options.separator ?? '\n\n')
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { OpenCode } from '@opencode/client'
|
||||
|
||||
export type {
|
||||
AgentInfo,
|
||||
CommandInfo,
|
||||
ConfigEntry,
|
||||
FileDiffInfo,
|
||||
FormAnswer,
|
||||
FormExternalField,
|
||||
FormField,
|
||||
FormInfo,
|
||||
FormValue,
|
||||
FormWhen,
|
||||
IntegrationInfo,
|
||||
IntegrationKeyMethod,
|
||||
IntegrationMethod,
|
||||
IntegrationOAuthMethod,
|
||||
McpServer,
|
||||
ModelInfo,
|
||||
ModelRef,
|
||||
PermissionRequest,
|
||||
PromptAgentAttachment,
|
||||
PromptFileAttachment,
|
||||
PromptMention,
|
||||
PromptSkillAttachment,
|
||||
SessionInfo,
|
||||
SessionInboxCompaction,
|
||||
SessionInboxInfo,
|
||||
SessionInboxUser,
|
||||
SessionMessageAssistant,
|
||||
SessionMessageAssistantReasoning,
|
||||
SessionMessageAssistantRetry,
|
||||
SessionMessageAssistantText,
|
||||
SessionMessageAssistantTool,
|
||||
SessionMessageCompaction,
|
||||
SessionMessageInfo,
|
||||
SessionMessageShell,
|
||||
SessionMessageUser,
|
||||
SessionRevert,
|
||||
SessionStatus,
|
||||
SessionStructuredError,
|
||||
SessionTransferData,
|
||||
SkillInfo,
|
||||
V2Event,
|
||||
} from '@opencode/client'
|
||||
|
||||
export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSessionNotFoundError, isWorktreeError } from '@opencode/client'
|
||||
|
||||
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
|
||||
|
||||
export { formatOpenCodeModelRef, parseOpenCodeModelRef } from './modelRef'
|
||||
|
||||
export {
|
||||
MCP_OAUTH_CALLBACK_PATH,
|
||||
mcpOAuthRedirectUri,
|
||||
mcpServersFromConfig,
|
||||
mcpStatusByName,
|
||||
} from './mcp'
|
||||
|
||||
export type {
|
||||
McpServerConfig,
|
||||
McpStatus,
|
||||
McpStatusMap,
|
||||
McpTimeoutConfig,
|
||||
} from './mcp'
|
||||
|
||||
export {
|
||||
OPENCODE_PINNED_VERSION,
|
||||
OPENCODE_SUPPORTED_VERSION_RANGE,
|
||||
buildOpenCodeReleaseAsset,
|
||||
compareOpenCodeVersions,
|
||||
describeUnsupportedOpenCodeVersion,
|
||||
isStableOpenCodeVersion,
|
||||
isSupportedOpenCodeVersion,
|
||||
normalizeOpenCodeVersion,
|
||||
parseOpenCodeVersion,
|
||||
parseOpenCodeVersionOutput,
|
||||
} from './release'
|
||||
|
||||
export const OPENCODE_SERVER_USERNAME = 'opencode'
|
||||
|
||||
export type OpenCodeApi = ReturnType<typeof OpenCode.make>
|
||||
|
||||
export interface OpenCodeApiOptions {
|
||||
baseUrl: string
|
||||
password?: string
|
||||
fetch?: typeof fetch
|
||||
headers?: Record<string, string>
|
||||
}
|
||||
|
||||
export function buildOpenCodeBasicAuth(password: string): string {
|
||||
const bytes = new TextEncoder().encode(`${OPENCODE_SERVER_USERNAME}:${password}`)
|
||||
let binary = ''
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte)
|
||||
return `Basic ${btoa(binary)}`
|
||||
}
|
||||
|
||||
export function createOpenCodeApi(options: OpenCodeApiOptions): OpenCodeApi {
|
||||
return OpenCode.make({
|
||||
baseUrl: options.baseUrl,
|
||||
fetch: options.fetch,
|
||||
headers: {
|
||||
...options.headers,
|
||||
...(options.password ? { Authorization: buildOpenCodeBasicAuth(options.password) } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface OpenCodeLocation {
|
||||
location: { directory: string }
|
||||
}
|
||||
|
||||
export function openCodeLocation(directory: string | undefined): OpenCodeLocation | undefined {
|
||||
return directory ? { location: { directory } } : undefined
|
||||
}
|
||||
|
||||
const OPENCODE_ERROR_STATUS_BY_TAG: Record<string, number> = {
|
||||
InvalidRequestError: 400,
|
||||
RpcError: 400,
|
||||
InvalidCursorError: 400,
|
||||
FormInvalidAnswerError: 400,
|
||||
UnauthorizedError: 401,
|
||||
ForbiddenError: 403,
|
||||
ProviderNotFoundError: 404,
|
||||
IntegrationNotFoundError: 404,
|
||||
IntegrationAttemptNotFoundError: 404,
|
||||
IntegrationMethodNotFoundError: 404,
|
||||
ProjectNotFoundError: 404,
|
||||
FileNotFoundError: 404,
|
||||
AgentNotFoundError: 404,
|
||||
SessionNotFoundError: 404,
|
||||
MessageNotFoundError: 404,
|
||||
SkillNotFoundError: 404,
|
||||
McpServerNotFoundError: 404,
|
||||
CommandNotFoundError: 404,
|
||||
PermissionNotFoundError: 404,
|
||||
FormNotFoundError: 404,
|
||||
PtyNotFoundError: 404,
|
||||
ShellNotFoundError: 404,
|
||||
ConflictError: 409,
|
||||
SessionBusyError: 409,
|
||||
FormAlreadySettledError: 409,
|
||||
InstructionEntryValueTooLargeError: 413,
|
||||
CommandExecutionError: 500,
|
||||
RpcInternalError: 500,
|
||||
UnknownError: 500,
|
||||
ServiceUnavailableError: 503,
|
||||
}
|
||||
|
||||
export function openCodeErrorStatus(error: unknown): number | undefined {
|
||||
if (error === null || typeof error !== 'object') return undefined
|
||||
|
||||
const tag = (error as { _tag?: unknown })._tag
|
||||
if (typeof tag === 'string' && OPENCODE_ERROR_STATUS_BY_TAG[tag] !== undefined) {
|
||||
return OPENCODE_ERROR_STATUS_BY_TAG[tag]
|
||||
}
|
||||
|
||||
const name = (error as { name?: unknown }).name
|
||||
if (typeof name === 'string') return OPENCODE_ERROR_STATUS_BY_TAG[name]
|
||||
|
||||
return undefined
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ConfigEntry, McpServer } from '@opencode/client'
|
||||
|
||||
export const MCP_OAUTH_CALLBACK_PATH = '/api/mcp-oauth-proxy/callback'
|
||||
|
||||
type ConfigDocumentInfo = Extract<ConfigEntry, { type: 'document' }>['info']
|
||||
|
||||
type McpConfig = NonNullable<ConfigDocumentInfo['mcp']>
|
||||
|
||||
export type McpServerConfig = NonNullable<McpConfig['servers']>[string]
|
||||
|
||||
export type McpTimeoutConfig = NonNullable<McpServerConfig['timeout']>
|
||||
|
||||
export type McpStatus = McpServer['status'] & Pick<McpServer, 'integrationID'>
|
||||
|
||||
export type McpStatusMap = Record<string, McpStatus>
|
||||
|
||||
export function mcpOAuthRedirectUri(origin: string): string {
|
||||
return new URL(MCP_OAUTH_CALLBACK_PATH, origin).toString()
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function isMcpServerConfig(value: unknown): value is McpServerConfig {
|
||||
return isRecord(value) && (value.type === 'local' || value.type === 'remote')
|
||||
}
|
||||
|
||||
export function mcpServersFromConfig(mcp: unknown): Record<string, McpServerConfig> {
|
||||
if (!isRecord(mcp) || !isRecord(mcp.servers)) return {}
|
||||
return Object.fromEntries(Object.entries(mcp.servers).filter((entry): entry is [string, McpServerConfig] => isMcpServerConfig(entry[1])))
|
||||
}
|
||||
|
||||
export function mcpStatusByName(servers: McpServer[]): McpStatusMap {
|
||||
return Object.fromEntries(
|
||||
servers.map((server) => [
|
||||
server.name,
|
||||
{
|
||||
...server.status,
|
||||
...(server.integrationID ? { integrationID: server.integrationID } : {}),
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ModelRef } from '@opencode/client'
|
||||
|
||||
export function parseOpenCodeModelRef(model: string): ModelRef | undefined {
|
||||
const providerEnd = model.indexOf('/')
|
||||
if (providerEnd <= 0) return undefined
|
||||
|
||||
const providerID = model.slice(0, providerEnd)
|
||||
const variantStart = model.indexOf('#', providerEnd + 1)
|
||||
const id = model.slice(providerEnd + 1, variantStart === -1 ? undefined : variantStart)
|
||||
const variant = variantStart === -1 ? undefined : model.slice(variantStart + 1)
|
||||
|
||||
if (!id || providerID.includes('#') || (variant !== undefined && (!variant || variant.includes('#')))) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return { providerID, id, ...(variant ? { variant } : {}) }
|
||||
}
|
||||
|
||||
export function formatOpenCodeModelRef(ref: ModelRef): string {
|
||||
return ref.variant ? `${ref.providerID}/${ref.id}#${ref.variant}` : `${ref.providerID}/${ref.id}`
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { compareParsedSemver, compareSemver, normalizeSemver, parseSemver, type Semver } from '../utils/semver'
|
||||
|
||||
export const OPENCODE_PINNED_VERSION = '2.0.15'
|
||||
|
||||
const OPENCODE_RELEASE_BASE_URL = 'https://opencode.ai/files/bin'
|
||||
|
||||
const OPENCODE_ARCH_ALIASES: Record<string, string> = {
|
||||
x64: 'x64',
|
||||
amd64: 'x64',
|
||||
x86_64: 'x64',
|
||||
arm64: 'arm64',
|
||||
aarch64: 'arm64',
|
||||
}
|
||||
|
||||
const OPENCODE_PLATFORM_ARCHIVES: Partial<Record<NodeJS.Platform, 'tar.gz' | 'zip'>> = {
|
||||
linux: 'tar.gz',
|
||||
darwin: 'zip',
|
||||
}
|
||||
|
||||
export type OpenCodeVersion = Semver
|
||||
|
||||
const OPENCODE_STABLE_VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/
|
||||
|
||||
const OPENCODE_VERSION_OUTPUT_PATTERN = /(?<![\d.])v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)/g
|
||||
|
||||
export function normalizeOpenCodeVersion(version: string): string {
|
||||
return normalizeSemver(version)
|
||||
}
|
||||
|
||||
export function parseOpenCodeVersion(version: string): OpenCodeVersion | null {
|
||||
return parseSemver(version)
|
||||
}
|
||||
|
||||
export function isStableOpenCodeVersion(version: string): boolean {
|
||||
return OPENCODE_STABLE_VERSION_PATTERN.test(normalizeOpenCodeVersion(version))
|
||||
}
|
||||
|
||||
export function parseOpenCodeVersionOutput(output: string): string | null {
|
||||
for (const match of output.matchAll(OPENCODE_VERSION_OUTPUT_PATTERN)) {
|
||||
const candidate = (match[1] ?? '').replace(/[.+-]+$/, '')
|
||||
if (parseOpenCodeVersion(candidate)) return candidate
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function compareOpenCodeVersions(left: string, right: string): number {
|
||||
return compareSemver(left, right)
|
||||
}
|
||||
|
||||
function parsePinnedOpenCodeVersion(): OpenCodeVersion {
|
||||
const pinned = parseOpenCodeVersion(OPENCODE_PINNED_VERSION)
|
||||
if (!pinned) throw new Error(`OPENCODE_PINNED_VERSION is not a valid version: ${OPENCODE_PINNED_VERSION}`)
|
||||
return pinned
|
||||
}
|
||||
|
||||
const OPENCODE_PINNED = parsePinnedOpenCodeVersion()
|
||||
|
||||
export const OPENCODE_SUPPORTED_VERSION_RANGE = `>=${OPENCODE_PINNED_VERSION} <${OPENCODE_PINNED.major + 1}.0.0`
|
||||
|
||||
export function isSupportedOpenCodeVersion(version: string): boolean {
|
||||
const parsed = parseOpenCodeVersion(version)
|
||||
if (!parsed) return false
|
||||
return parsed.major === OPENCODE_PINNED.major && compareParsedSemver(parsed, OPENCODE_PINNED) >= 0
|
||||
}
|
||||
|
||||
export function describeUnsupportedOpenCodeVersion(version: string): string {
|
||||
return `OpenCode ${version} is not supported; OpenCode Manager requires OpenCode ${OPENCODE_SUPPORTED_VERSION_RANGE}`
|
||||
}
|
||||
|
||||
export function buildOpenCodeReleaseAsset(
|
||||
version: string,
|
||||
target: { platform: NodeJS.Platform; arch: string; musl: boolean },
|
||||
): { url: string; archive: 'tar.gz' | 'zip' } {
|
||||
const archive = OPENCODE_PLATFORM_ARCHIVES[target.platform]
|
||||
if (!archive) throw new Error(`Unsupported OpenCode platform: ${target.platform}`)
|
||||
|
||||
const arch = OPENCODE_ARCH_ALIASES[target.arch]
|
||||
if (!arch) throw new Error(`Unsupported OpenCode architecture: ${target.arch}`)
|
||||
|
||||
const muslSuffix = target.musl ? '-musl' : ''
|
||||
return {
|
||||
url: `${OPENCODE_RELEASE_BASE_URL}/${version}/opencode-${target.platform}-${arch}${muslSuffix}.${archive}`,
|
||||
archive,
|
||||
}
|
||||
}
|
||||
+36
-96
@@ -1,133 +1,73 @@
|
||||
import { z } from "zod";
|
||||
import type {
|
||||
ProviderOauthAuthorizeErrors,
|
||||
ProviderOauthCallbackErrors,
|
||||
} from "@opencode-ai/sdk/v2/types";
|
||||
|
||||
export const AuthEntrySchema = z.object({
|
||||
type: z.enum(["api", "oauth"]),
|
||||
key: z.string().optional(),
|
||||
refresh: z.string().optional(),
|
||||
access: z.string().optional(),
|
||||
expires: z.number().optional(),
|
||||
});
|
||||
export const FormAnswerValueSchema = z.union([
|
||||
z.string(),
|
||||
z.number(),
|
||||
z.boolean(),
|
||||
z.array(z.string()),
|
||||
]);
|
||||
|
||||
export const AuthCredentialsSchema = z.record(z.string(), AuthEntrySchema);
|
||||
export const FormAnswerSchema = z.record(z.string(), FormAnswerValueSchema);
|
||||
|
||||
export const SetCredentialRequestSchema = z.object({
|
||||
apiKey: z.string().min(1),
|
||||
answer: FormAnswerSchema.optional(),
|
||||
});
|
||||
|
||||
export type SetCredentialRequest = z.infer<typeof SetCredentialRequestSchema>;
|
||||
|
||||
export const CredentialStatusResponseSchema = z.object({
|
||||
hasCredentials: z.boolean(),
|
||||
});
|
||||
|
||||
export type CredentialStatusResponse = z.infer<typeof CredentialStatusResponseSchema>;
|
||||
|
||||
export const CredentialListResponseSchema = z.object({
|
||||
providers: z.array(z.string()),
|
||||
});
|
||||
|
||||
export const PromptFieldSchema = z.discriminatedUnion("type", [
|
||||
z.object({
|
||||
type: z.literal("text"),
|
||||
key: z.string(),
|
||||
message: z.string(),
|
||||
placeholder: z.string().optional(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("select"),
|
||||
key: z.string(),
|
||||
message: z.string(),
|
||||
options: z.array(z.object({
|
||||
label: z.string(),
|
||||
value: z.string(),
|
||||
})),
|
||||
when: z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
}).optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const ProviderAuthMethodSchema = z.object({
|
||||
type: z.enum(["oauth", "api"]),
|
||||
label: z.string(),
|
||||
prompts: z.array(PromptFieldSchema).optional(),
|
||||
});
|
||||
|
||||
export const ProviderAuthMethodsSchema = z.record(z.string(), z.array(ProviderAuthMethodSchema));
|
||||
export type CredentialListResponse = z.infer<typeof CredentialListResponseSchema>;
|
||||
|
||||
export const OAuthAuthorizeRequestSchema = z.object({
|
||||
method: z.number(),
|
||||
inputs: z.record(z.string(), z.string()).optional(),
|
||||
methodID: z.string().min(1),
|
||||
answer: FormAnswerSchema.optional(),
|
||||
});
|
||||
|
||||
export type OAuthAuthorizeRequest = z.infer<typeof OAuthAuthorizeRequestSchema>;
|
||||
|
||||
export const OAuthAuthorizeResponseSchema = z.object({
|
||||
attemptID: z.string(),
|
||||
url: z.string(),
|
||||
method: z.enum(["auto", "code"]),
|
||||
instructions: z.string(),
|
||||
mode: z.enum(["auto", "code"]),
|
||||
});
|
||||
|
||||
export type OAuthAuthorizeResponse = z.infer<typeof OAuthAuthorizeResponseSchema>;
|
||||
|
||||
export const OAuthAttemptStatusSchema = z.object({
|
||||
status: z.enum(["pending", "complete", "failed", "expired"]),
|
||||
message: z.string().optional(),
|
||||
});
|
||||
|
||||
export type OAuthAttemptStatus = z.infer<typeof OAuthAttemptStatusSchema>;
|
||||
|
||||
export const OAuthCallbackRequestSchema = z.object({
|
||||
method: z.number(),
|
||||
attemptID: z.string().min(1),
|
||||
code: z.string().optional(),
|
||||
});
|
||||
|
||||
export const ProviderAuthMethodsResponseSchema = z.object({
|
||||
providers: z.record(z.string(), z.array(ProviderAuthMethodSchema)),
|
||||
}).or(ProviderAuthMethodsSchema);
|
||||
|
||||
export const PROVIDER_AUTH_ERROR_NAMES = [
|
||||
"BadRequest",
|
||||
"ProviderAuthOauthMissing",
|
||||
"ProviderAuthOauthCodeMissing",
|
||||
"ProviderAuthOauthCallbackFailed",
|
||||
"ProviderAuthValidationFailed",
|
||||
] as const;
|
||||
|
||||
export type ProviderAuthErrorName = (typeof PROVIDER_AUTH_ERROR_NAMES)[number];
|
||||
|
||||
export const ProviderAuthErrorSchema = z.object({
|
||||
name: z.enum(PROVIDER_AUTH_ERROR_NAMES),
|
||||
data: z.object({
|
||||
providerID: z.string().optional(),
|
||||
field: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
kind: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const InvalidRequestErrorSchema = z.object({
|
||||
_tag: z.literal("InvalidRequestError"),
|
||||
message: z.string(),
|
||||
kind: z.string().optional(),
|
||||
field: z.string().optional(),
|
||||
});
|
||||
|
||||
export const OpenCodeOAuthErrorSchema = z.union([
|
||||
ProviderAuthErrorSchema,
|
||||
InvalidRequestErrorSchema,
|
||||
]);
|
||||
|
||||
export type OpenCodeOAuthError = z.infer<typeof OpenCodeOAuthErrorSchema>;
|
||||
export type OAuthCallbackRequest = z.infer<typeof OAuthCallbackRequestSchema>;
|
||||
|
||||
export const OAUTH_ERROR_CODES = [
|
||||
...PROVIDER_AUTH_ERROR_NAMES,
|
||||
"IntegrationNotFoundError",
|
||||
"IntegrationAttemptNotFoundError",
|
||||
"IntegrationMethodNotFoundError",
|
||||
"InvalidRequestError",
|
||||
"ClientError",
|
||||
] as const;
|
||||
|
||||
export type OAuthErrorCode = (typeof OAUTH_ERROR_CODES)[number];
|
||||
|
||||
export function oauthErrorCode(error: OpenCodeOAuthError): OAuthErrorCode {
|
||||
return "_tag" in error ? error._tag : error.name;
|
||||
export function isOAuthErrorCode(code: string): code is OAuthErrorCode {
|
||||
return (OAUTH_ERROR_CODES as readonly string[]).includes(code);
|
||||
}
|
||||
|
||||
type MutuallyAssignable<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
||||
type Assert<T extends true> = T;
|
||||
|
||||
export type OpenCodeOAuthErrorMatchesAuthorize = Assert<
|
||||
MutuallyAssignable<OpenCodeOAuthError, ProviderOauthAuthorizeErrors[400]>
|
||||
>;
|
||||
|
||||
export type OpenCodeOAuthErrorMatchesCallback = Assert<
|
||||
MutuallyAssignable<OpenCodeOAuthError, ProviderOauthCallbackErrors[400]>
|
||||
>;
|
||||
@@ -2,8 +2,8 @@ import { z } from "zod";
|
||||
|
||||
export const NotificationEventType = {
|
||||
PERMISSION_ASKED: "permission.asked",
|
||||
QUESTION_ASKED: "question.asked",
|
||||
SESSION_ERROR: "session.error",
|
||||
FORM_CREATED: "form.created",
|
||||
SESSION_FAILED: "session.execution.failed",
|
||||
SESSION_IDLE: "session.idle",
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const OpenCodeTargetStateSchema = z.enum([
|
||||
'missing',
|
||||
'starting',
|
||||
'healthy',
|
||||
'unhealthy',
|
||||
'failed',
|
||||
'stopped',
|
||||
])
|
||||
|
||||
export const OpenCodeTargetSchema = z.object({
|
||||
repoId: z.number(),
|
||||
state: OpenCodeTargetStateSchema,
|
||||
openCodeUrl: z.string().optional(),
|
||||
token: z.string().optional(),
|
||||
startedAt: z.number().optional(),
|
||||
lastUsedAt: z.number().optional(),
|
||||
lastError: z.string().optional(),
|
||||
reused: z.boolean(),
|
||||
})
|
||||
|
||||
export const EnsureOpenCodeTargetRequestSchema = z.object({
|
||||
workspaceId: z.string().optional(),
|
||||
clientId: z.string().optional(),
|
||||
})
|
||||
|
||||
export const EnsureOpenCodeTargetResponseSchema = z.object({
|
||||
repoId: z.number(),
|
||||
state: OpenCodeTargetStateSchema,
|
||||
openCodeUrl: z.string(),
|
||||
headers: z.record(z.string(), z.string()),
|
||||
reused: z.boolean(),
|
||||
})
|
||||
|
||||
export const SyncRepoSessionRequestSchema = z.object({
|
||||
sessionId: z.string(),
|
||||
reason: z.enum(['idle', 'completed', 'stop', 'manual']),
|
||||
})
|
||||
|
||||
export const SyncRepoSessionResponseSchema = z.object({
|
||||
repoId: z.number(),
|
||||
sessionId: z.string(),
|
||||
replayedEvents: z.number(),
|
||||
})
|
||||
@@ -37,17 +37,17 @@ export const SchedulePermissionConfigSchema = z.object({
|
||||
})
|
||||
export type SchedulePermissionConfig = z.infer<typeof SchedulePermissionConfigSchema>
|
||||
|
||||
export type SchedulePermissionAction = 'allow' | 'deny' | 'ask'
|
||||
export type SchedulePermissionEffect = 'allow' | 'deny' | 'ask'
|
||||
|
||||
/**
|
||||
* A single OpenCode session permission rule. `permission` is the tool name
|
||||
* (e.g. `bash`, `external_directory`, or `*` for all), `pattern` is the glob
|
||||
* matched against the tool argument, and `action` is the resulting decision.
|
||||
* A single OpenCode 2 session permission rule. `action` is the tool or permission
|
||||
* action (e.g. `shell`, `external_directory`, or `*` for all), `resource` is the
|
||||
* glob matched against the tool argument, and `effect` is the resulting decision.
|
||||
*/
|
||||
export interface SchedulePermissionRule {
|
||||
permission: string
|
||||
pattern: string
|
||||
action: SchedulePermissionAction
|
||||
action: string
|
||||
resource: string
|
||||
effect: SchedulePermissionEffect
|
||||
}
|
||||
|
||||
export type SchedulePermissionRuleset = SchedulePermissionRule[]
|
||||
@@ -55,11 +55,11 @@ export type SchedulePermissionRuleset = SchedulePermissionRule[]
|
||||
/**
|
||||
* Builds the OpenCode session permission ruleset for an unattended scheduled run.
|
||||
*
|
||||
* OpenCode's `POST /session` `permission` field expects an ordered array of
|
||||
* `{ permission, pattern, action }` rules (`PermissionV1.Ruleset`), evaluated
|
||||
* with last-match-wins semantics (see https://opencode.ai/docs/permissions).
|
||||
* OpenCode's `POST /session` `permissions` field expects an ordered array of
|
||||
* `{ action, resource, effect }` rules (`Permission.Ruleset`), evaluated with
|
||||
* last-match-wins semantics (see https://opencode.ai/docs/permissions).
|
||||
* A leading `*`/`*` allow rule sets the allow-all baseline; the trailing
|
||||
* `external_directory`, `question` and `bash` deny rules then override it for
|
||||
* `external_directory`, `question` and `shell` deny rules then override it for
|
||||
* external directory access, agent questions that would block an unattended run
|
||||
* with nobody to answer them, and matching destructive command patterns.
|
||||
*/
|
||||
@@ -67,15 +67,15 @@ export function buildSchedulePermissionRuleset(
|
||||
config: SchedulePermissionConfig | null | undefined,
|
||||
): SchedulePermissionRuleset {
|
||||
const cfg = SchedulePermissionConfigSchema.parse(config ?? {})
|
||||
const ruleset: SchedulePermissionRuleset = [{ permission: '*', pattern: '*', action: 'allow' }]
|
||||
const ruleset: SchedulePermissionRuleset = [{ action: '*', resource: '*', effect: 'allow' }]
|
||||
if (!cfg.allowExternalDirectory) {
|
||||
ruleset.push({ permission: 'external_directory', pattern: '*', action: 'deny' })
|
||||
ruleset.push({ action: 'external_directory', resource: '*', effect: 'deny' })
|
||||
}
|
||||
if (!cfg.allowQuestions) {
|
||||
ruleset.push({ permission: 'question', pattern: '*', action: 'deny' })
|
||||
ruleset.push({ action: 'question', resource: '*', effect: 'deny' })
|
||||
}
|
||||
for (const pattern of cfg.bashDenyPatterns) {
|
||||
ruleset.push({ permission: 'bash', pattern, action: 'deny' })
|
||||
ruleset.push({ action: 'shell', resource: pattern, effect: 'deny' })
|
||||
}
|
||||
return ruleset
|
||||
}
|
||||
@@ -120,7 +120,6 @@ export const ScheduleRunSchema = z.object({
|
||||
runBranch: z.string().nullable(),
|
||||
commitHash: z.string().nullable(),
|
||||
worktreePath: z.string().nullable(),
|
||||
workspaceId: z.string().nullable(),
|
||||
})
|
||||
export type ScheduleRun = z.infer<typeof ScheduleRunSchema>
|
||||
|
||||
|
||||
@@ -112,17 +112,12 @@ export const ServerEnvVarSchema = z.object({
|
||||
|
||||
type ServerEnvVar = z.infer<typeof ServerEnvVarSchema>
|
||||
|
||||
export const DEFAULT_SERVER_ENV_VARS = [
|
||||
{
|
||||
key: 'OPENCODE_EXPERIMENTAL_WORKSPACES',
|
||||
value: 'true',
|
||||
},
|
||||
] as const satisfies readonly ServerEnvVar[];
|
||||
|
||||
export const BLOCKED_SERVER_ENV_KEYS = [
|
||||
'OPENCODE_PASSWORD',
|
||||
'OPENCODE_SERVER_PASSWORD',
|
||||
'OPENCODE_SERVER_USERNAME',
|
||||
'OPENCODE_CONFIG',
|
||||
'OPENCODE_CONFIG_DIR',
|
||||
'OPENCODE_CONFIG_CONTENT',
|
||||
'XDG_DATA_HOME',
|
||||
'XDG_STATE_HOME',
|
||||
'XDG_CONFIG_HOME',
|
||||
@@ -222,7 +217,6 @@ export const DEFAULT_USER_PREFERENCES = {
|
||||
repoSortMode: 'recent' as const,
|
||||
serverEnvVars: [] as ServerEnvVar[],
|
||||
sandbox: DEFAULT_SANDBOX_PREFERENCES,
|
||||
disabledDefaultServerEnvVars: [] as string[],
|
||||
};
|
||||
|
||||
export const SettingsResponseSchema = z.object({
|
||||
@@ -334,6 +328,20 @@ export const OpenCodePluginSpecSchema = z.union([
|
||||
z.tuple([z.string(), OpenCodePluginOptionsSchema]),
|
||||
]);
|
||||
|
||||
export const OpenCodeNativePluginSchema = z.union([
|
||||
z.string(),
|
||||
z.object({
|
||||
package: z.string(),
|
||||
options: OpenCodePluginOptionsSchema.optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const OpenCodePermissionRuleSchema = z.object({
|
||||
action: z.string(),
|
||||
resource: z.string(),
|
||||
effect: z.enum(["allow", "deny", "ask"]),
|
||||
});
|
||||
|
||||
export const OpenCodeConfigSchema = z.object({
|
||||
$schema: z.string().optional(),
|
||||
theme: z.string().optional(),
|
||||
@@ -341,21 +349,41 @@ export const OpenCodeConfigSchema = z.object({
|
||||
small_model: z.string().optional(),
|
||||
default_agent: z.string().optional(),
|
||||
provider: z.record(z.string(), ProviderConfigSchema).optional(),
|
||||
providers: z.record(z.string(), z.record(z.string(), z.any())).optional(),
|
||||
agent: z.record(z.string(), z.any()).optional(),
|
||||
agents: z.record(z.string(), z.record(z.string(), z.any())).optional(),
|
||||
command: z.record(z.string(), z.any()).optional(),
|
||||
commands: z.record(z.string(), z.record(z.string(), z.any())).optional(),
|
||||
keybinds: z.record(z.string(), z.any()).optional(),
|
||||
autoupdate: z.union([z.boolean(), z.literal("notify")]).optional(),
|
||||
update: z.enum(["disable", "notify", "auto"]).optional(),
|
||||
formatter: z.record(z.string(), z.any()).optional(),
|
||||
permission: z.record(z.string(), z.any()).optional(),
|
||||
permissions: z.array(OpenCodePermissionRuleSchema).optional(),
|
||||
mcp: z.record(z.string(), z.any()).optional(),
|
||||
instructions: z.array(z.string()).optional(),
|
||||
disabled_providers: z.array(z.string()).optional(),
|
||||
share: z.enum(["manual", "auto", "disabled"]).optional(),
|
||||
plugin: z.array(OpenCodePluginSpecSchema).optional(),
|
||||
skills: z.object({
|
||||
paths: z.array(z.string()).optional(),
|
||||
urls: z.array(z.string()).optional(),
|
||||
}).optional(),
|
||||
plugins: z.array(OpenCodeNativePluginSchema).optional(),
|
||||
skills: z.union([
|
||||
z.array(z.string()),
|
||||
z.object({
|
||||
paths: z.array(z.string()).optional(),
|
||||
urls: z.array(z.string()).optional(),
|
||||
}),
|
||||
]).optional(),
|
||||
snapshots: z.boolean().optional(),
|
||||
username: z.string().optional(),
|
||||
media: z.record(z.string(), z.any()).optional(),
|
||||
references: z.record(z.string(), z.any()).optional(),
|
||||
worktree: z.record(z.string(), z.any()).optional(),
|
||||
websearch: z.union([z.literal(false), z.record(z.string(), z.any())]).optional(),
|
||||
warming: z.union([z.boolean(), z.record(z.string(), z.any())]).optional(),
|
||||
compaction: z.record(z.string(), z.any()).optional(),
|
||||
experimental: z.record(z.string(), z.any()).optional(),
|
||||
tool_output: z.record(z.string(), z.any()).optional(),
|
||||
watcher: z.record(z.string(), z.any()).optional(),
|
||||
}).strip();
|
||||
|
||||
export const OpenCodeConfigValidationIssueSchema = z.object({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import type { V2Event } from "../opencode";
|
||||
|
||||
export const SSESubscribeSchema = z.object({
|
||||
clientId: z.string().min(1),
|
||||
@@ -14,14 +15,7 @@ export const SSEVisibilitySchema = z.object({
|
||||
export type SSESubscribeRequest = z.infer<typeof SSESubscribeSchema>;
|
||||
export type SSEVisibilityRequest = z.infer<typeof SSEVisibilitySchema>;
|
||||
|
||||
export interface SSEEventPayload {
|
||||
type: string;
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface SSEEventEnvelope {
|
||||
directory?: string;
|
||||
project?: string;
|
||||
workspace?: string;
|
||||
payload: SSEEventPayload;
|
||||
directory?: string | null;
|
||||
payload: V2Event;
|
||||
}
|
||||
@@ -104,7 +104,7 @@ export type AssistantSettingsPatch = z.infer<typeof AssistantSettingsPatchSchema
|
||||
|
||||
export { FetchError } from './errors'
|
||||
export type { ApiErrorResponse, ApiErrorCode, GitErrorCode } from './errors'
|
||||
export { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '../schemas/settings'
|
||||
export { BLOCKED_SERVER_ENV_KEYS } from '../schemas/settings'
|
||||
|
||||
export interface SuccessResponse {
|
||||
success: boolean
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
OpenCodeTargetStateSchema,
|
||||
OpenCodeTargetSchema,
|
||||
EnsureOpenCodeTargetRequestSchema,
|
||||
EnsureOpenCodeTargetResponseSchema,
|
||||
SyncRepoSessionRequestSchema,
|
||||
SyncRepoSessionResponseSchema,
|
||||
} from '../schemas/opencode-target'
|
||||
|
||||
export type OpenCodeTargetState = z.infer<typeof OpenCodeTargetStateSchema>
|
||||
export type OpenCodeTarget = z.infer<typeof OpenCodeTargetSchema>
|
||||
export type EnsureOpenCodeTargetRequest = z.infer<typeof EnsureOpenCodeTargetRequestSchema>
|
||||
export type EnsureOpenCodeTargetResponse = z.infer<typeof EnsureOpenCodeTargetResponseSchema>
|
||||
export type SyncRepoSessionRequest = z.infer<typeof SyncRepoSessionRequestSchema>
|
||||
export type SyncRepoSessionResponse = z.infer<typeof SyncRepoSessionResponseSchema>
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from './jsonc'
|
||||
export * from './repo'
|
||||
export * from './sandbox-command'
|
||||
export * from './semver'
|
||||
@@ -56,6 +56,10 @@ export function sanitizeBranchForDirectory(branch: string): string {
|
||||
return branch.replace(/[\\/]/g, '-')
|
||||
}
|
||||
|
||||
export function isWorktreeSibling(sibling: { worktreeStrategy?: string }): boolean {
|
||||
return sibling.worktreeStrategy !== undefined
|
||||
}
|
||||
|
||||
export function getRepoBaseDirectoryName(repo: { localPath: string; branch?: string; isWorktree?: boolean }): string {
|
||||
if (repo.isWorktree && repo.branch) {
|
||||
const suffix = `-${sanitizeBranchForDirectory(repo.branch)}`
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
export type SemverPrereleaseIdentifier = number | string
|
||||
|
||||
export interface Semver {
|
||||
major: number
|
||||
minor: number
|
||||
patch: number
|
||||
prerelease: SemverPrereleaseIdentifier[]
|
||||
}
|
||||
|
||||
const SEMVER_PATTERN =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/
|
||||
|
||||
export function normalizeSemver(version: string): string {
|
||||
return version.trim().replace(/^v/, '')
|
||||
}
|
||||
|
||||
export function parseSemver(version: string): Semver | null {
|
||||
const match = SEMVER_PATTERN.exec(normalizeSemver(version))
|
||||
if (!match) return null
|
||||
return {
|
||||
major: Number(match[1]),
|
||||
minor: Number(match[2]),
|
||||
patch: Number(match[3]),
|
||||
prerelease: match[4]
|
||||
? match[4].split('.').map((identifier) => (/^\d+$/.test(identifier) ? Number(identifier) : identifier))
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifiers(
|
||||
left: SemverPrereleaseIdentifier[],
|
||||
right: SemverPrereleaseIdentifier[],
|
||||
): number {
|
||||
if (left.length === 0 || right.length === 0) return right.length - left.length
|
||||
|
||||
for (let index = 0; index < Math.max(left.length, right.length); index++) {
|
||||
const leftIdentifier = left[index]
|
||||
const rightIdentifier = right[index]
|
||||
|
||||
if (leftIdentifier === undefined) return -1
|
||||
if (rightIdentifier === undefined) return 1
|
||||
if (leftIdentifier === rightIdentifier) continue
|
||||
|
||||
const leftNumeric = typeof leftIdentifier === 'number'
|
||||
const rightNumeric = typeof rightIdentifier === 'number'
|
||||
if (leftNumeric && rightNumeric) return leftIdentifier > rightIdentifier ? 1 : -1
|
||||
if (leftNumeric) return -1
|
||||
if (rightNumeric) return 1
|
||||
return leftIdentifier > rightIdentifier ? 1 : -1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
export function compareParsedSemver(left: Semver, right: Semver): number {
|
||||
if (left.major !== right.major) return left.major - right.major
|
||||
if (left.minor !== right.minor) return left.minor - right.minor
|
||||
if (left.patch !== right.patch) return left.patch - right.patch
|
||||
return comparePrereleaseIdentifiers(left.prerelease, right.prerelease)
|
||||
}
|
||||
|
||||
export function compareSemver(left: string, right: string): number {
|
||||
const parsedLeft = parseSemver(left)
|
||||
const parsedRight = parseSemver(right)
|
||||
if (!parsedLeft || !parsedRight) {
|
||||
throw new Error(`Cannot compare invalid semver versions: ${left} and ${right}`)
|
||||
}
|
||||
return compareParsedSemver(parsedLeft, parsedRight)
|
||||
}
|
||||
Reference in new issue
Block a user