mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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
@@ -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,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user