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.
This commit is contained in:
Chris Scott committed 2026-09-24 08:38:26 -04:00
1 parent 6c2ebd764b
commit 7351d5f002
313 files changed
+23848 -36801

No files matched your search

+3 -2
View File
@@ -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"
}
}
+1 -3
View File
@@ -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,7 +98,7 @@ 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 type Config = typeof DEFAULTS
-4
View File
@@ -67,12 +67,10 @@ 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'),
},
DATABASE: {
@@ -85,7 +83,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 +159,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 => {
+18 -47
View File
@@ -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 : ''
}
+160
View File
@@ -0,0 +1,160 @@
import { OpenCode } from '@opencode/client'
export type {
AgentInfo,
CommandInfo,
FileDiffInfo,
FormAnswer,
FormField,
FormInfo,
IntegrationInfo,
IntegrationMethod,
McpServer,
ModelInfo,
ModelRef,
OpenCodeEvent,
PermissionRequest,
PromptAgentAttachment,
PromptFileAttachment,
PromptMention,
PromptSkillAttachment,
ProviderInfo,
SessionInfo,
SessionInboxCompaction,
SessionInboxInfo,
SessionInboxMove,
SessionInboxSynthetic,
SessionInboxUser,
SessionMessageAssistant,
SessionMessageAssistantReasoning,
SessionMessageAssistantRetry,
SessionMessageAssistantText,
SessionMessageAssistantTool,
SessionMessageCompaction,
SessionMessageInfo,
SessionMessageShell,
SessionMessageUser,
SessionRevert,
SessionStatus,
SessionStructuredError,
SessionTransferData,
SessionsResponse,
SkillInfo,
ToolContent,
ToolFileContent,
ToolTextContent,
V2Event,
WorktreeError,
} from '@opencode/client'
export { ClientError, isMcpServerNotFoundError, isWorktreeError } from '@opencode/client'
export {
MCP_OAUTH_CALLBACK_PATH,
fromV2McpServerConfig,
mcpOAuthRedirectUri,
mcpServerConfigFromConfig,
mcpServersFromConfig,
mcpStatusByName,
toV2McpServerConfig,
} from './mcp'
export type {
McpOAuthConfig,
McpServerConfig,
McpStatus,
McpStatusMap,
McpStatusName,
V2McpLocalConfig,
V2McpOAuthConfig,
V2McpRemoteConfig,
V2McpServerConfig,
V2McpTimeoutConfig,
} from './mcp'
export {
OPENCODE_MIN_VERSION,
OPENCODE_PINNED_VERSION,
buildOpenCodeReleaseAsset,
isSupportedOpenCodeVersion,
} 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 function openCodeLocation(directory: string): { location: { directory: string } } {
return { location: { directory } }
}
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
}
+212
View File
@@ -0,0 +1,212 @@
import type { McpServer } from '@opencode/client'
export const MCP_OAUTH_CALLBACK_PATH = '/api/mcp-oauth-proxy/callback'
export type McpStatusName = 'connected' | 'pending' | 'disabled' | 'failed' | 'needs_auth'
export interface McpStatus {
status: McpStatusName
error?: string
integrationID?: string
}
export type McpStatusMap = Record<string, McpStatus>
export interface McpOAuthConfig {
clientId?: string
clientSecret?: string
scope?: string
}
export interface McpServerConfig {
type: 'local' | 'remote'
enabled?: boolean
command?: string[]
url?: string
environment?: Record<string, string>
headers?: Record<string, string>
timeout?: number
oauth?: boolean | McpOAuthConfig
}
export interface V2McpTimeoutConfig {
catalog?: number
execution?: number
}
export interface V2McpOAuthConfig {
client_id?: string
client_secret?: string
scope?: string
callback_port?: number
redirect_uri?: string
auth_server_metadata_url?: string
}
export interface V2McpLocalConfig {
type: 'local'
command: string[]
cwd?: string
environment?: Record<string, string>
disabled?: boolean
timeout?: V2McpTimeoutConfig
}
export interface V2McpRemoteConfig {
type: 'remote'
url: string
headers?: Record<string, string>
oauth?: V2McpOAuthConfig | false
disabled?: boolean
timeout?: V2McpTimeoutConfig
}
export type V2McpServerConfig = V2McpLocalConfig | V2McpRemoteConfig
export function mcpOAuthRedirectUri(origin: string): string {
return new URL(MCP_OAUTH_CALLBACK_PATH, origin).toString()
}
function toV2Timeout(timeout: number | undefined): V2McpTimeoutConfig | undefined {
return timeout === undefined ? undefined : { catalog: timeout, execution: timeout }
}
function toV2OAuth(oauth: boolean | McpOAuthConfig, origin: string | undefined): V2McpOAuthConfig | false {
if (oauth === false) return false
const config = typeof oauth === 'object' ? oauth : {}
return {
...(config.clientId ? { client_id: config.clientId } : {}),
...(config.clientSecret ? { client_secret: config.clientSecret } : {}),
...(config.scope ? { scope: config.scope } : {}),
...(origin ? { redirect_uri: mcpOAuthRedirectUri(origin) } : {}),
}
}
function toV2Disabled(enabled: boolean | undefined): boolean | undefined {
return enabled === undefined ? undefined : !enabled
}
export function toV2McpServerConfig(config: McpServerConfig, origin?: string): V2McpServerConfig {
const disabled = toV2Disabled(config.enabled)
const timeout = toV2Timeout(config.timeout)
if (config.type === 'local') {
return {
type: 'local',
command: config.command ?? [],
...(config.environment ? { environment: config.environment } : {}),
...(disabled === undefined ? {} : { disabled }),
...(timeout === undefined ? {} : { timeout }),
}
}
return {
type: 'remote',
url: config.url ?? '',
...(config.headers ? { headers: config.headers } : {}),
...(config.oauth === undefined ? {} : { oauth: toV2OAuth(config.oauth, origin) }),
...(disabled === undefined ? {} : { disabled }),
...(timeout === undefined ? {} : { timeout }),
}
}
function fromV2Timeout(timeout: V2McpTimeoutConfig | undefined): number | undefined {
return timeout?.catalog ?? timeout?.execution
}
function fromV2OAuth(oauth: V2McpOAuthConfig | false | undefined): boolean | McpOAuthConfig | undefined {
if (oauth === undefined) return undefined
if (oauth === false) return false
return {
...(oauth.client_id ? { clientId: oauth.client_id } : {}),
...(oauth.client_secret ? { clientSecret: oauth.client_secret } : {}),
...(oauth.scope ? { scope: oauth.scope } : {}),
}
}
export function fromV2McpServerConfig(config: V2McpServerConfig): McpServerConfig {
const enabled = config.disabled === undefined ? undefined : !config.disabled
const timeout = fromV2Timeout(config.timeout)
if (config.type === 'local') {
return {
type: 'local',
...(enabled === undefined ? {} : { enabled }),
command: [...config.command],
...(config.environment ? { environment: config.environment } : {}),
...(timeout === undefined ? {} : { timeout }),
}
}
return {
type: 'remote',
...(enabled === undefined ? {} : { enabled }),
url: config.url,
...(config.headers ? { headers: config.headers } : {}),
...(config.oauth === undefined ? {} : { oauth: fromV2OAuth(config.oauth) }),
...(timeout === undefined ? {} : { timeout }),
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isDirectMcpServerEntry(value: unknown): boolean {
return isRecord(value) && (value.type === 'local' || value.type === 'remote')
}
export function mcpServersFromConfig(mcp: unknown): Record<string, McpServerConfig> {
if (!isRecord(mcp)) return {}
const servers: Record<string, McpServerConfig> = {}
for (const [name, value] of Object.entries(mcp)) {
if (!isRecord(value)) continue
if (name === 'servers' && !isDirectMcpServerEntry(value)) {
for (const [serverName, server] of Object.entries(value)) {
if (isRecord(server) && isDirectMcpServerEntry(server)) {
servers[serverName] = fromV2McpServerConfig(server as unknown as V2McpServerConfig)
}
}
continue
}
if (name === 'timeout' && !isDirectMcpServerEntry(value)) continue
if (isDirectMcpServerEntry(value)) {
servers[name] = value as unknown as McpServerConfig
}
}
return servers
}
export function mcpServerConfigFromConfig(mcp: unknown, name: string): V2McpServerConfig | undefined {
if (!isRecord(mcp)) return undefined
const servers = mcp.servers
if (isRecord(servers)) {
const native = servers[name]
if (isRecord(native) && isDirectMcpServerEntry(native)) return native as unknown as V2McpServerConfig
}
const legacy = mcp[name]
if (isRecord(legacy) && isDirectMcpServerEntry(legacy)) {
return toV2McpServerConfig(legacy as unknown as McpServerConfig)
}
return undefined
}
export function mcpStatusByName(servers: McpServer[]): McpStatusMap {
return Object.fromEntries(
servers.map((server) => [
server.name,
{
status: server.status.status,
...('error' in server.status ? { error: server.status.error } : {}),
...(server.integrationID ? { integrationID: server.integrationID } : {}),
},
]),
)
}
+98
View File
@@ -0,0 +1,98 @@
export const OPENCODE_MIN_VERSION = '2.0.0'
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',
}
type OpenCodePrereleaseIdentifier = number | string
interface OpenCodeVersion {
major: number
minor: number
patch: number
prerelease: OpenCodePrereleaseIdentifier[]
}
const OPENCODE_VERSION_PATTERN =
/^v?(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-]+)*))?$/
function parseOpenCodeVersion(version: string): OpenCodeVersion | null {
const match = OPENCODE_VERSION_PATTERN.exec(version.trim())
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 compareOpenCodePrereleaseIdentifiers(
left: OpenCodePrereleaseIdentifier[],
right: OpenCodePrereleaseIdentifier[],
): 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
}
function compareOpenCodeVersions(left: OpenCodeVersion, right: OpenCodeVersion): 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 compareOpenCodePrereleaseIdentifiers(left.prerelease, right.prerelease)
}
export function isSupportedOpenCodeVersion(version: string): boolean {
const parsed = parseOpenCodeVersion(version)
const minimum = parseOpenCodeVersion(OPENCODE_MIN_VERSION)
if (!parsed || !minimum) return false
return parsed.major === minimum.major && compareOpenCodeVersions(parsed, minimum) >= 0
}
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,
}
}
+106 -73
View File
@@ -1,37 +1,54 @@
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 PromptAnswerValueSchema = z.union([
z.string(),
z.number(),
z.boolean(),
z.array(z.string()),
]);
export const AuthCredentialsSchema = z.record(z.string(), AuthEntrySchema);
export const PromptAnswerSchema = z.record(z.string(), PromptAnswerValueSchema);
export type PromptAnswerValue = z.infer<typeof PromptAnswerValueSchema>;
export type PromptAnswer = z.infer<typeof PromptAnswerSchema>;
export const SetCredentialRequestSchema = z.object({
apiKey: z.string().min(1),
answer: PromptAnswerSchema.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 type CredentialListResponse = z.infer<typeof CredentialListResponseSchema>;
export const PromptConditionSchema = z.object({
key: z.string(),
op: z.enum(["eq", "neq"]),
value: z.union([z.string(), z.number(), z.boolean()]),
});
export type PromptCondition = z.infer<typeof PromptConditionSchema>;
export const PromptFieldSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("text"),
key: z.string(),
message: z.string(),
placeholder: z.string().optional(),
required: z.boolean().optional(),
default: z.string().optional(),
when: z.array(PromptConditionSchema).optional(),
}),
z.object({
type: z.literal("select"),
@@ -41,93 +58,109 @@ export const PromptFieldSchema = z.discriminatedUnion("type", [
label: z.string(),
value: z.string(),
})),
when: z.object({
key: z.string(),
required: z.boolean().optional(),
default: z.string().optional(),
when: z.array(PromptConditionSchema).optional(),
}),
z.object({
type: z.literal("boolean"),
key: z.string(),
message: z.string(),
required: z.boolean().optional(),
default: z.boolean().optional(),
when: z.array(PromptConditionSchema).optional(),
}),
z.object({
type: z.literal("multiselect"),
key: z.string(),
message: z.string(),
options: z.array(z.object({
label: z.string(),
value: z.string(),
}).optional(),
})),
required: z.boolean().optional(),
default: z.array(z.string()).optional(),
when: z.array(PromptConditionSchema).optional(),
}),
z.object({
type: z.literal("number"),
key: z.string(),
message: z.string(),
minimum: z.number().optional(),
maximum: z.number().optional(),
required: z.boolean().optional(),
default: z.number().optional(),
when: z.array(PromptConditionSchema).optional(),
}),
z.object({
type: z.literal("external"),
key: z.string(),
message: z.string(),
url: z.string(),
}),
]);
export type PromptField = z.infer<typeof PromptFieldSchema>;
export const ProviderAuthMethodSchema = z.object({
type: z.enum(["oauth", "api"]),
id: z.string(),
type: z.enum(["oauth", "key", "command", "env"]),
label: z.string(),
prompts: z.array(PromptFieldSchema).optional(),
fields: z.array(PromptFieldSchema).optional(),
});
export type ProviderAuthMethod = z.infer<typeof ProviderAuthMethodSchema>;
export const ProviderAuthMethodsSchema = z.record(z.string(), z.array(ProviderAuthMethodSchema));
export const OAuthAuthorizeRequestSchema = z.object({
method: z.number(),
inputs: z.record(z.string(), z.string()).optional(),
export type ProviderAuthMethods = z.infer<typeof ProviderAuthMethodsSchema>;
export const ProviderAuthMethodsResponseSchema = z.object({
providers: ProviderAuthMethodsSchema,
});
export type ProviderAuthMethodsResponse = z.infer<typeof ProviderAuthMethodsResponseSchema>;
export const OAuthAuthorizeRequestSchema = z.object({
methodID: z.string().min(1),
answer: PromptAnswerSchema.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 -2
View File
@@ -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;
+15 -16
View File
@@ -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>
+38 -5
View File
@@ -121,7 +121,6 @@ export const DEFAULT_SERVER_ENV_VARS = [
export const BLOCKED_SERVER_ENV_KEYS = [
'OPENCODE_SERVER_PASSWORD',
'OPENCODE_SERVER_USERNAME',
'OPENCODE_CONFIG',
'XDG_DATA_HOME',
'XDG_STATE_HOME',
@@ -334,6 +333,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 +354,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({
+2 -8
View File
@@ -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;
payload: V2Event;
}
+4
View File
@@ -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)}`