mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 11: Phase 11: Assistant Mode writes v2 config; remove the hand-w
This commit is contained in:
1 parent
1802cdc7de
commit
0b2303a870
10 files changed
+418
-449
No files matched your search
@@ -84,7 +84,7 @@ import { RepoWorkspaceService } from './services/repo-workspace'
|
||||
import { createGitService } from './services/git/GitService'
|
||||
import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { installAssistantWorkspace, convertAssistantOpenCodeConfigToV2 } from './services/assistant-mode'
|
||||
import { detectSandboxCapability } from './services/sandbox/capability'
|
||||
import { SandboxRuntimeService, stopSandboxesOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
@@ -254,6 +254,7 @@ try {
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
void convertAssistantOpenCodeConfigToV2(openCodeClient.api)
|
||||
} else {
|
||||
logger.warn(`OpenCode server unavailable after startup recovery: ${openCodeStatus.lastError ?? openCodeStatus.state}`)
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import type { SecretsService } from '../services/secrets'
|
||||
import type { RepoWorkspaceService } from '../services/repo-workspace'
|
||||
import { createGitService } from '../services/git/GitService'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, convertAssistantOpenCodeConfigToV2 } from '../services/assistant-mode'
|
||||
import path from 'path'
|
||||
|
||||
const DeleteWorkspaceRequestSchema = z.object({
|
||||
@@ -614,6 +614,7 @@ app.get('/', async (c) => {
|
||||
const options = AssistantModeInitRequestSchema.parse(body)
|
||||
|
||||
const status = await ensureAssistantMode(repo, options)
|
||||
await convertAssistantOpenCodeConfigToV2(openCodeClient.api)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to initialize assistant mode:', error)
|
||||
|
||||
@@ -4,7 +4,6 @@ import type { Repo } from '@opencode-manager/shared/types'
|
||||
import type {
|
||||
AssistantModeStatus,
|
||||
AssistantModeInitRequest,
|
||||
OpenCodeConfigInput,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import {
|
||||
readFileContent,
|
||||
@@ -12,12 +11,17 @@ import {
|
||||
fileExists,
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY, MANAGER_TOOL_NAME } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY, MANAGER_TOOL_NAME } from '@opencode-manager/shared/schemas'
|
||||
import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME, parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import type { OpenCodeAgentConfig, OpenCodeApi, OpenCodeConfigInfo } from '@opencode-manager/shared/opencode'
|
||||
import { openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { ensureAssistantRepo } from '../db/queries'
|
||||
import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, type OpenCodeConfigPathOperation } from './opencode-config-file'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
|
||||
const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
|
||||
@@ -1126,18 +1130,25 @@ Fork a session, optionally before a specific message. Omit \`beforeMessageId\` t
|
||||
`
|
||||
}
|
||||
|
||||
export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
|
||||
const config: OpenCodeConfigInput = {
|
||||
export function buildAssistantOpenCodeConfig(): OpenCodeConfigInfo {
|
||||
const permission = buildAssistantAgentPermission()
|
||||
const config: OpenCodeConfigInfo = {
|
||||
default_agent: ASSISTANT_DEFAULT_AGENT_NAME,
|
||||
permission: buildAssistantAgentPermission(),
|
||||
agent: {
|
||||
permissions: Object.entries(permission).map(([action, effect]) => ({
|
||||
action,
|
||||
resource: '*',
|
||||
effect,
|
||||
})),
|
||||
agents: {
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: 'primary' },
|
||||
},
|
||||
}
|
||||
|
||||
const result = OpenCodeConfigSchema.safeParse(config)
|
||||
const result = validateOpenCodeConfig(config)
|
||||
if (!result.success) {
|
||||
throw new Error(`Generated OpenCode config is invalid: ${result.error.message}`)
|
||||
throw new Error(
|
||||
`Generated OpenCode config is invalid: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join(', ')}`,
|
||||
)
|
||||
}
|
||||
|
||||
return config
|
||||
@@ -1185,44 +1196,32 @@ export async function ensureAssistantMode(
|
||||
await writeFileContent(agentsMdPath, agentsMdContent)
|
||||
}
|
||||
|
||||
const hasLegacyOpenCodeConfig = opencodeJsonExists && await isLegacyAssistantOpenCodeConfig(opencodeJsonPath)
|
||||
const existingOpenCodeJsonContent = opencodeJsonExists ? await readFileContent(opencodeJsonPath) : undefined
|
||||
const parsedOpenCodeConfig = existingOpenCodeJsonContent === undefined
|
||||
? undefined
|
||||
: parseAssistantOpenCodeConfig(existingOpenCodeJsonContent)
|
||||
const hasV1OpenCodeConfig = parsedOpenCodeConfig !== undefined && hasAssistantV1OpenCodeConfig(parsedOpenCodeConfig)
|
||||
const existingOpenCodeConfig = parsedOpenCodeConfig as OpenCodeConfigInfo | undefined
|
||||
|
||||
let opencodeJsonUpdated = false
|
||||
if (!opencodeJsonExists || overwriteOpenCodeConfig || hasLegacyOpenCodeConfig) {
|
||||
const config = hasLegacyOpenCodeConfig && opencodeJsonExists
|
||||
? await (async () => {
|
||||
try {
|
||||
const existingContent = await readFileContent(opencodeJsonPath)
|
||||
const existingConfig = JSON.parse(existingContent) as OpenCodeConfigInput
|
||||
const mergedConfig = mergeAssistantOpenCodeConfig(existingConfig)
|
||||
return assistantOpenCodeConfigHasGeneratedAgentPersona(mergedConfig)
|
||||
? stripGeneratedAssistantAgentPersona(mergedConfig)
|
||||
: mergedConfig
|
||||
} catch {
|
||||
return buildAssistantOpenCodeConfig()
|
||||
}
|
||||
})()
|
||||
: buildAssistantOpenCodeConfig()
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(config, null, 2))
|
||||
opencodeJsonUpdated = true
|
||||
} else if (opencodeJsonExists) {
|
||||
try {
|
||||
const existingContent = await readFileContent(opencodeJsonPath)
|
||||
const existingConfig = JSON.parse(existingContent) as OpenCodeConfigInput
|
||||
const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingConfig)
|
||||
? mergeAssistantOpenCodeConfig(existingConfig)
|
||||
: existingConfig
|
||||
if (!hasV1OpenCodeConfig) {
|
||||
if (!opencodeJsonExists || overwriteOpenCodeConfig) {
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
|
||||
opencodeJsonUpdated = true
|
||||
} else if (existingOpenCodeConfig !== undefined) {
|
||||
const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingOpenCodeConfig)
|
||||
? mergeAssistantOpenCodeConfig(existingOpenCodeConfig)
|
||||
: existingOpenCodeConfig
|
||||
const updatedConfig = assistantOpenCodeConfigHasGeneratedAgentPersona(repairedConfig)
|
||||
? stripGeneratedAssistantAgentPersona(repairedConfig)
|
||||
: repairedConfig
|
||||
|
||||
if (updatedConfig !== existingConfig) {
|
||||
if (updatedConfig !== existingOpenCodeConfig) {
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(updatedConfig, null, 2))
|
||||
opencodeJsonUpdated = true
|
||||
}
|
||||
} catch {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(config, null, 2))
|
||||
} else {
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
|
||||
opencodeJsonUpdated = true
|
||||
}
|
||||
}
|
||||
@@ -1349,23 +1348,40 @@ export async function ensureAssistantMode(
|
||||
}
|
||||
}
|
||||
|
||||
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInput): boolean {
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function parseAssistantOpenCodeConfig(rawContent: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const parsed = parseJsonc(rawContent)
|
||||
return isPlainObject(parsed) ? parsed : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function hasAssistantV1OpenCodeConfig(config: Record<string, unknown>): boolean {
|
||||
if (config.permission !== undefined) return true
|
||||
return isPlainObject(config.agent) && isPlainObject(config.agent.assistant)
|
||||
}
|
||||
|
||||
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean {
|
||||
if (config.default_agent !== ASSISTANT_DEFAULT_AGENT_NAME) return true
|
||||
if (!config.agent || typeof config.agent !== 'object') return true
|
||||
const assistantAgent = config.agent[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
const agents = config.agents
|
||||
if (!agents || typeof agents !== 'object') return true
|
||||
const assistantAgent = agents[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
if (!assistantAgent || typeof assistantAgent !== 'object') return true
|
||||
const mode = (assistantAgent as { mode?: unknown }).mode
|
||||
if (mode !== 'primary' && mode !== 'all') return true
|
||||
if ((assistantAgent as { disable?: unknown }).disable === true) return true
|
||||
if (assistantAgent.mode !== 'primary' && assistantAgent.mode !== 'all') return true
|
||||
if (assistantAgent.disabled === true) return true
|
||||
if (assistantOpenCodeConfigHasGeneratedAgentPersona(config)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInput): boolean {
|
||||
const agent = config.agent?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInfo): boolean {
|
||||
const agent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
if (typeof agent !== 'object' || agent === null) return false
|
||||
const prompt = (agent as { prompt?: unknown }).prompt
|
||||
return matchesGeneratedAssistantAgentPrompt(prompt)
|
||||
return matchesGeneratedAssistantAgentPrompt(agent.system)
|
||||
}
|
||||
|
||||
function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
|
||||
@@ -1373,38 +1389,36 @@ function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
|
||||
return mode === 'primary' || mode === 'all' ? mode : 'primary'
|
||||
}
|
||||
|
||||
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInput): OpenCodeConfigInput {
|
||||
const existingAssistantAgent = config.agent?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo {
|
||||
const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
||||
|
||||
return {
|
||||
...config,
|
||||
agent: {
|
||||
...(config.agent ?? {}),
|
||||
agents: {
|
||||
...(config.agents ?? {}),
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: validMode },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInput): OpenCodeConfigInput {
|
||||
function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeConfigInfo {
|
||||
const generated = buildAssistantOpenCodeConfig()
|
||||
const existingAssistantAgent = existing?.agent?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
||||
|
||||
const existingIsGenerated = existingAssistantAgent != null &&
|
||||
typeof existingAssistantAgent === 'object' &&
|
||||
matchesGeneratedAssistantAgentPrompt(
|
||||
(existingAssistantAgent as { prompt?: unknown }).prompt,
|
||||
)
|
||||
const existingIsGenerated = typeof existingAssistantAgent === 'object' &&
|
||||
existingAssistantAgent !== null &&
|
||||
matchesGeneratedAssistantAgentPrompt(existingAssistantAgent.system)
|
||||
|
||||
let mergedAssistantAgent: Record<string, unknown>
|
||||
let mergedAssistantAgent: OpenCodeAgentConfig
|
||||
if (existingIsGenerated) {
|
||||
mergedAssistantAgent = { mode: validMode }
|
||||
} else {
|
||||
mergedAssistantAgent = {
|
||||
...(typeof existingAssistantAgent === 'object' && existingAssistantAgent !== null ? existingAssistantAgent : {}),
|
||||
mode: validMode,
|
||||
disable: false,
|
||||
disabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1412,24 +1426,84 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInput): OpenCodeC
|
||||
...generated,
|
||||
...existing,
|
||||
default_agent: ASSISTANT_DEFAULT_AGENT_NAME,
|
||||
instructions: existing?.instructions ?? generated.instructions,
|
||||
permission: existing?.permission ?? generated.permission,
|
||||
agent: {
|
||||
...(existing?.agent ?? {}),
|
||||
permissions: existing?.permissions ?? generated.permissions,
|
||||
agents: {
|
||||
...(existing?.agents ?? {}),
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: mergedAssistantAgent,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function isLegacyAssistantOpenCodeConfig(opencodeJsonPath: string): Promise<boolean> {
|
||||
function buildAssistantV1ConfigRemovalPaths(config: Record<string, unknown>): string[][] {
|
||||
const v1Agent = config.agent
|
||||
const removeWholeAgent = isPlainObject(v1Agent) &&
|
||||
Object.keys(v1Agent).length === 1 &&
|
||||
isPlainObject(v1Agent.assistant)
|
||||
|
||||
const paths: string[][] = [removeWholeAgent ? ['agent'] : ['agent', ASSISTANT_DEFAULT_AGENT_NAME]]
|
||||
if (config.permission !== undefined) {
|
||||
paths.push(['permission'])
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
function resolveConvertedAssistantAgent(
|
||||
agent: OpenCodeAgentConfig | undefined,
|
||||
v1Agent: unknown,
|
||||
): OpenCodeAgentConfig {
|
||||
if (agent === undefined) {
|
||||
return { mode: resolveValidAssistantMode(v1Agent) }
|
||||
}
|
||||
return matchesGeneratedAssistantAgentPrompt(agent.system)
|
||||
? { mode: resolveValidAssistantMode(agent) }
|
||||
: agent
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites a v1 Assistant `opencode.json` to the v2 shape using OpenCode's own conversion,
|
||||
* keeping comments and formatting. The file is left untouched when OpenCode is unreachable.
|
||||
*/
|
||||
export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Promise<boolean> {
|
||||
try {
|
||||
const content = await readFileContent(opencodeJsonPath)
|
||||
const config = JSON.parse(content) as {
|
||||
permission?: { allow?: unknown; ask?: unknown }
|
||||
const assistantDir = getAssistantModeDirectory()
|
||||
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
|
||||
|
||||
if (!await fileExists(opencodeJsonPath)) return false
|
||||
|
||||
const rawContent = await readFileContent(opencodeJsonPath)
|
||||
const rawConfig = parseAssistantOpenCodeConfig(rawContent)
|
||||
if (rawConfig === undefined || !hasAssistantV1OpenCodeConfig(rawConfig)) return false
|
||||
|
||||
const entries = await api.config.get(openCodeLocation(assistantDir))
|
||||
const resolvedPath = path.resolve(opencodeJsonPath)
|
||||
const documentEntry = entries.find(
|
||||
(entry) => entry.type === 'document' && entry.path !== undefined && path.resolve(entry.path) === resolvedPath,
|
||||
)
|
||||
if (documentEntry === undefined || documentEntry.type !== 'document') return false
|
||||
|
||||
const v1AssistantAgent = isPlainObject(rawConfig.agent) ? rawConfig.agent.assistant : undefined
|
||||
const setOperations: OpenCodeConfigPathOperation[] = [
|
||||
{
|
||||
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
|
||||
value: resolveConvertedAssistantAgent(
|
||||
documentEntry.info.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
|
||||
v1AssistantAgent,
|
||||
),
|
||||
},
|
||||
]
|
||||
if (documentEntry.info.permissions !== undefined) {
|
||||
setOperations.push({ path: ['permissions'], value: documentEntry.info.permissions })
|
||||
}
|
||||
if (Array.isArray(config.permission?.allow) || Array.isArray(config.permission?.ask)) return true
|
||||
return false
|
||||
} catch {
|
||||
|
||||
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
|
||||
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig)) {
|
||||
updatedText = removeOpenCodeConfigProperty(updatedText, removalPath)
|
||||
}
|
||||
|
||||
await writeFileContent(opencodeJsonPath, updatedText)
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.warn('Skipped the Assistant OpenCode config conversion:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ export type ApplyOpenCodeConfigResult =
|
||||
| { status: 'reloaded'; config: OpenCodeConfigFile }
|
||||
| { status: 'restart_pending'; config: OpenCodeConfigFile }
|
||||
|
||||
export interface ApplyOpenCodeConfigInput {
|
||||
export interface ApplyOpenCodeConfigOptions {
|
||||
content: Record<string, unknown> | string
|
||||
source?: OpenCodeConfigSourceName
|
||||
expectedRevision?: string
|
||||
@@ -99,7 +99,7 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC
|
||||
}
|
||||
|
||||
export async function applyOpenCodeConfigUpdate(
|
||||
input: ApplyOpenCodeConfigInput,
|
||||
input: ApplyOpenCodeConfigOptions,
|
||||
): Promise<ApplyOpenCodeConfigResult> {
|
||||
const { reloadRequired, config } = await withOpenCodeConfigLock(async () => {
|
||||
const { content, source, expectedRevision, mode, settingsService } = input
|
||||
|
||||
@@ -598,7 +598,10 @@ function buildOpenCodeConfigCommentPreservingRemovalEdits(
|
||||
return edits
|
||||
}
|
||||
|
||||
function removeOpenCodeConfigProperty(rawContent: string, jsonPath: JSONPath): string {
|
||||
/**
|
||||
* Removes one property from raw JSONC config text while keeping neighbouring comments and formatting.
|
||||
*/
|
||||
export function removeOpenCodeConfigProperty(rawContent: string, jsonPath: JSONPath): string {
|
||||
const edits = buildOpenCodeConfigCommentPreservingRemovalEdits(rawContent, jsonPath)
|
||||
if (!edits) return rawContent
|
||||
return applyEdits(rawContent, edits)
|
||||
|
||||
@@ -47,6 +47,7 @@ vi.mock('../../src/services/repo', () => ({
|
||||
vi.mock('../../src/services/assistant-mode', () => ({
|
||||
getAssistantModeStatus: vi.fn(),
|
||||
ensureAssistantMode: vi.fn(),
|
||||
convertAssistantOpenCodeConfigToV2: vi.fn(),
|
||||
getAssistantModeDirectory: vi.fn(),
|
||||
buildAssistantOpenCodeConfig: vi.fn(),
|
||||
buildAssistantRepo: vi.fn(),
|
||||
|
||||
@@ -3,7 +3,10 @@ import path from 'path'
|
||||
import { access, readFile, writeFile } from 'fs/promises'
|
||||
import { Hono } from 'hono'
|
||||
import { AssistantSettingsPatchSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildSessionsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import type { OpenCodeApi, OpenCodePermissionRule } from '@opencode-manager/shared/opencode'
|
||||
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildSessionsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace, convertAssistantOpenCodeConfigToV2 } from '../../src/services/assistant-mode'
|
||||
import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
@@ -12,6 +15,16 @@ import { getRepoById } from '../../src/db/queries'
|
||||
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
|
||||
import { createInternalTestApp } from '../helpers/internal-test-app'
|
||||
|
||||
const ASSISTANT_PERMISSIONS: OpenCodePermissionRule[] = [
|
||||
{ action: 'read', resource: '*', effect: 'allow' },
|
||||
{ action: 'edit', resource: '*', effect: 'allow' },
|
||||
{ action: 'glob', resource: '*', effect: 'allow' },
|
||||
{ action: 'grep', resource: '*', effect: 'allow' },
|
||||
{ action: 'list', resource: '*', effect: 'allow' },
|
||||
{ action: 'shell', resource: '*', effect: 'allow' },
|
||||
{ action: 'external_directory', resource: '*', effect: 'ask' },
|
||||
]
|
||||
|
||||
describe('buildSchedulesSkill', () => {
|
||||
it('instructs the agent to use the ocm tool request action', () => {
|
||||
const skill = buildSchedulesSkill()
|
||||
@@ -202,13 +215,15 @@ describe('buildAssistantDefaultAgentMd', () => {
|
||||
})
|
||||
|
||||
describe('buildAssistantOpenCodeConfig', () => {
|
||||
it('includes default_agent and agent.assistant with primary mode and no embedded persona', () => {
|
||||
it('writes v2 permissions and agents.assistant with primary mode and no embedded persona', () => {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
expect(config.default_agent).toBe('assistant')
|
||||
expect(config.agent?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(config.agent?.assistant?.prompt).toBeUndefined()
|
||||
expect(config.agent?.assistant?.description).toBeUndefined()
|
||||
expect(config.agent?.assistant?.permission).toBeUndefined()
|
||||
expect(config.permissions).toEqual(ASSISTANT_PERMISSIONS)
|
||||
expect(config.agents?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(config.agents?.assistant?.system).toBeUndefined()
|
||||
expect(config.agents?.assistant?.description).toBeUndefined()
|
||||
expect(config.agents?.assistant?.permissions).toBeUndefined()
|
||||
expect(validateOpenCodeConfig(config).success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -234,10 +249,11 @@ describe('ensureAssistantMode', () => {
|
||||
const parsedConfig = JSON.parse(opencodeJson)
|
||||
expect(parsedConfig.default_agent).toBe('assistant')
|
||||
expect(parsedConfig).not.toHaveProperty('mcp')
|
||||
expect(parsedConfig.agent?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(parsedConfig.agent?.assistant?.prompt).toBeUndefined()
|
||||
expect(parsedConfig.agent?.assistant?.description).toBeUndefined()
|
||||
expect(parsedConfig.agent?.assistant?.permission).toBeUndefined()
|
||||
expect(parsedConfig.permissions).toEqual(ASSISTANT_PERMISSIONS)
|
||||
expect(parsedConfig.agents?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(parsedConfig.agents?.assistant?.system).toBeUndefined()
|
||||
expect(parsedConfig.agents?.assistant?.description).toBeUndefined()
|
||||
expect(parsedConfig.agents?.assistant?.permissions).toBeUndefined()
|
||||
expect(skill).toContain('"action": "request"')
|
||||
expect(skill).not.toContain('curl')
|
||||
expect(skill).not.toContain('Authorization: Bearer')
|
||||
@@ -275,19 +291,11 @@ describe('ensureAssistantMode', () => {
|
||||
|
||||
expect(opencodeJson.default_agent).toBe('assistant')
|
||||
expect(opencodeJson.instructions).toBeUndefined()
|
||||
expect(opencodeJson.permission).toEqual({
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
shell: 'allow',
|
||||
external_directory: 'ask',
|
||||
})
|
||||
expect(opencodeJson.agent?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toBeUndefined()
|
||||
expect(opencodeJson.agent?.assistant?.description).toBeUndefined()
|
||||
expect(opencodeJson.agent?.assistant?.permission).toBeUndefined()
|
||||
expect(opencodeJson.permissions).toEqual(ASSISTANT_PERMISSIONS)
|
||||
expect(opencodeJson.agents?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(opencodeJson.agents?.assistant?.system).toBeUndefined()
|
||||
expect(opencodeJson.agents?.assistant?.description).toBeUndefined()
|
||||
expect(opencodeJson.agents?.assistant?.permissions).toBeUndefined()
|
||||
|
||||
const agentsMdContent = await readFile(agentsMdPath, 'utf8')
|
||||
expect(agentsMdContent).toContain('Assistant Mode Workspace')
|
||||
@@ -374,21 +382,22 @@ describe('ensureAssistantMode', () => {
|
||||
model: 'provider/model',
|
||||
instructions: ['AGENTS.md'],
|
||||
default_agent: 'build',
|
||||
agent: {
|
||||
custom: { mode: 'primary', prompt: 'Custom agent' },
|
||||
agents: {
|
||||
custom: { mode: 'primary', system: 'Custom agent' },
|
||||
},
|
||||
skills: { paths: ['.opencode/skills'] },
|
||||
skills: ['.opencode/skills'],
|
||||
}, null, 2))
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
||||
|
||||
expect(repaired.default_agent).toBe('assistant')
|
||||
expect(repaired.agent.assistant).toEqual({ mode: 'primary', disable: false })
|
||||
expect(repaired.agent.assistant.prompt).toBeUndefined()
|
||||
expect(repaired.agent.custom.prompt).toBe('Custom agent')
|
||||
expect(repaired.permissions).toEqual(ASSISTANT_PERMISSIONS)
|
||||
expect(repaired.agents.assistant).toEqual({ mode: 'primary', disabled: false })
|
||||
expect(repaired.agents.assistant.system).toBeUndefined()
|
||||
expect(repaired.agents.custom.system).toBe('Custom agent')
|
||||
expect(repaired.model).toBe('provider/model')
|
||||
expect(repaired.skills.paths).toEqual(['.opencode/skills'])
|
||||
expect(repaired.skills).toEqual(['.opencode/skills'])
|
||||
expect(result.files.opencodeJson?.created).toBe(true)
|
||||
})
|
||||
|
||||
@@ -397,12 +406,12 @@ describe('ensureAssistantMode', () => {
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
await writeFile(opencodeJsonPath, JSON.stringify({
|
||||
default_agent: 'assistant',
|
||||
agent: {
|
||||
agents: {
|
||||
assistant: {
|
||||
mode: 'subagent',
|
||||
prompt: 'Custom assistant prompt',
|
||||
system: 'Custom assistant prompt',
|
||||
description: 'Custom assistant',
|
||||
permission: { bash: 'ask' },
|
||||
permissions: [{ action: 'shell', resource: '*', effect: 'ask' }],
|
||||
},
|
||||
},
|
||||
}, null, 2))
|
||||
@@ -410,14 +419,32 @@ describe('ensureAssistantMode', () => {
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
||||
|
||||
expect(repaired.agent.assistant.prompt).toBe('Custom assistant prompt')
|
||||
expect(repaired.agent.assistant.description).toBe('Custom assistant')
|
||||
expect(repaired.agent.assistant.permission.bash).toBe('ask')
|
||||
expect(repaired.agent.assistant.mode).toBe('primary')
|
||||
expect(repaired.agent.assistant.disable).toBe(false)
|
||||
expect(repaired.agents.assistant.system).toBe('Custom assistant prompt')
|
||||
expect(repaired.agents.assistant.description).toBe('Custom assistant')
|
||||
expect(repaired.agents.assistant.permissions).toEqual([{ action: 'shell', resource: '*', effect: 'ask' }])
|
||||
expect(repaired.agents.assistant.mode).toBe('primary')
|
||||
expect(repaired.agents.assistant.disabled).toBe(false)
|
||||
expect(result.files.opencodeJson?.created).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves a v1 assistant opencode config untouched so the conversion can upgrade it', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
const v1Config = `{
|
||||
// keep this comment
|
||||
"default_agent": "assistant",
|
||||
"permission": { "read": "allow", "shell": "ask" },
|
||||
"agent": { "assistant": { "mode": "primary", "prompt": "Custom v1 prompt" } }
|
||||
}
|
||||
`
|
||||
await writeFile(opencodeJsonPath, v1Config)
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
|
||||
expect(await readFile(opencodeJsonPath, 'utf8')).toBe(v1Config)
|
||||
expect(result.files.opencodeJson?.created).toBe(false)
|
||||
})
|
||||
|
||||
it('migrates generated legacy AGENTS.md and assistant.md to the new split', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
|
||||
@@ -508,29 +535,13 @@ Ask before destructive operations or changes outside this assistant workspace.
|
||||
await writeFile(opencodeJsonPath, JSON.stringify({
|
||||
default_agent: 'assistant',
|
||||
instructions: ['AGENTS.md'],
|
||||
permission: {
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
},
|
||||
agent: {
|
||||
permissions: [{ action: 'read', resource: '*', effect: 'allow' }],
|
||||
agents: {
|
||||
assistant: {
|
||||
description: 'Default OpenCode Manager assistant workspace agent',
|
||||
mode: 'primary',
|
||||
prompt: legacyAssistantPrompt,
|
||||
permission: {
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
},
|
||||
system: legacyAssistantPrompt,
|
||||
permissions: [{ action: 'shell', resource: '*', effect: 'allow' }],
|
||||
},
|
||||
},
|
||||
}, null, 2))
|
||||
@@ -553,10 +564,11 @@ Ask before destructive operations or changes outside this assistant workspace.
|
||||
expect(updatedAssistantAgent).toContain('notifications')
|
||||
expect(updatedAssistantAgent).toContain('manager-settings')
|
||||
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agent.assistant.description).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agent.assistant.permission).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agent.assistant.mode).toBe('primary')
|
||||
expect(updatedOpenCodeJson.agents.assistant.system).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agents.assistant.description).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agents.assistant.permissions).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agents.assistant.mode).toBe('primary')
|
||||
expect(updatedOpenCodeJson.permissions).toEqual([{ action: 'read', resource: '*', effect: 'allow' }])
|
||||
|
||||
expect(result.files.agentsMd?.created).toBe(true)
|
||||
expect(result.files.opencodeJson?.created).toBe(true)
|
||||
@@ -673,6 +685,193 @@ Ask before destructive operations or changes outside this assistant workspace.
|
||||
})
|
||||
})
|
||||
|
||||
describe('convertAssistantOpenCodeConfigToV2', () => {
|
||||
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
|
||||
|
||||
beforeEach(async () => {
|
||||
ws = await createTempAssistantWorkspace()
|
||||
})
|
||||
afterEach(async () => { await ws.cleanup() })
|
||||
|
||||
function createConfigApi(
|
||||
getEntries: (assistantDir: string) => unknown[],
|
||||
): OpenCodeApi {
|
||||
return {
|
||||
config: {
|
||||
get: async () => getEntries(ws.assistantDir),
|
||||
},
|
||||
} as unknown as OpenCodeApi
|
||||
}
|
||||
|
||||
const v1Config = `{
|
||||
// keep this comment
|
||||
"default_agent": "assistant",
|
||||
"permission": { "read": "allow", "shell": "ask" },
|
||||
"agent": { "assistant": { "mode": "primary", "prompt": "Custom v1 prompt" } }
|
||||
}
|
||||
`
|
||||
|
||||
const convertedPermissions = [
|
||||
{ action: 'read', resource: '*', effect: 'allow' },
|
||||
{ action: 'shell', resource: '*', effect: 'ask' },
|
||||
]
|
||||
|
||||
it('writes the converted v2 values and removes the v1 keys while keeping comments', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
await writeFile(opencodeJsonPath, v1Config)
|
||||
|
||||
const api = createConfigApi((assistantDir) => [{
|
||||
type: 'document',
|
||||
path: path.join(assistantDir, 'opencode.json'),
|
||||
info: {
|
||||
default_agent: 'assistant',
|
||||
permissions: convertedPermissions,
|
||||
agents: { assistant: { mode: 'primary', system: 'Converted prompt' } },
|
||||
},
|
||||
}])
|
||||
|
||||
const converted = await convertAssistantOpenCodeConfigToV2(api)
|
||||
|
||||
const raw = await readFile(opencodeJsonPath, 'utf8')
|
||||
const config = parseJsonc<Record<string, unknown>>(raw)
|
||||
expect(converted).toBe(true)
|
||||
expect(config.agents).toEqual({ assistant: { mode: 'primary', system: 'Converted prompt' } })
|
||||
expect(config.permissions).toEqual(convertedPermissions)
|
||||
expect(config.agent).toBeUndefined()
|
||||
expect(config.permission).toBeUndefined()
|
||||
expect(raw).toContain('// keep this comment')
|
||||
})
|
||||
|
||||
it('keeps comments attached to retained keys in a commented v1 config', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
await writeFile(opencodeJsonPath, `{
|
||||
// about agent
|
||||
"agent": {
|
||||
// assistant comment
|
||||
"assistant": { "mode": "primary", "prompt": "Custom v1 prompt" },
|
||||
// kept sibling comment
|
||||
"reviewer": { "mode": "subagent", "prompt": "Reviewer" }
|
||||
},
|
||||
// about permission
|
||||
"permission": { "read": "allow", "shell": "ask" }, // trailing note
|
||||
"theme": "opencode"
|
||||
}
|
||||
`)
|
||||
|
||||
const api = createConfigApi((assistantDir) => [{
|
||||
type: 'document',
|
||||
path: path.join(assistantDir, 'opencode.json'),
|
||||
info: {
|
||||
default_agent: 'assistant',
|
||||
permissions: convertedPermissions,
|
||||
agents: { assistant: { mode: 'primary', system: 'Converted prompt' } },
|
||||
},
|
||||
}])
|
||||
|
||||
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
|
||||
|
||||
const raw = await readFile(opencodeJsonPath, 'utf8')
|
||||
const config = parseJsonc<Record<string, unknown>>(raw)
|
||||
expect(config.agents).toEqual({ assistant: { mode: 'primary', system: 'Converted prompt' } })
|
||||
expect(config.permissions).toEqual(convertedPermissions)
|
||||
expect(config.agent).toEqual({ reviewer: { mode: 'subagent', prompt: 'Reviewer' } })
|
||||
expect(config.permission).toBeUndefined()
|
||||
expect(config.theme).toBe('opencode')
|
||||
expect(raw).toContain('// about agent')
|
||||
expect(raw).toContain('// kept sibling comment')
|
||||
expect(raw).toContain('// about permission')
|
||||
expect(raw).toContain('// trailing note')
|
||||
})
|
||||
|
||||
it('keeps other v1 agent entries when only agent.assistant is converted', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
await writeFile(opencodeJsonPath, JSON.stringify({
|
||||
default_agent: 'assistant',
|
||||
agent: {
|
||||
assistant: { mode: 'primary', prompt: 'Custom v1 prompt' },
|
||||
reviewer: { mode: 'subagent', prompt: 'Reviewer' },
|
||||
},
|
||||
}, null, 2))
|
||||
|
||||
const api = createConfigApi((assistantDir) => [{
|
||||
type: 'document',
|
||||
path: path.join(assistantDir, 'opencode.json'),
|
||||
info: {
|
||||
default_agent: 'assistant',
|
||||
permissions: convertedPermissions,
|
||||
agents: { assistant: { mode: 'primary', system: 'Converted prompt' } },
|
||||
},
|
||||
}])
|
||||
|
||||
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
|
||||
|
||||
const config = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
||||
expect(config.agents.assistant.system).toBe('Converted prompt')
|
||||
expect(config.agent.assistant).toBeUndefined()
|
||||
expect(config.agent.reviewer.prompt).toBe('Reviewer')
|
||||
})
|
||||
|
||||
it('drops a generated assistant persona from the converted agent', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
await writeFile(opencodeJsonPath, JSON.stringify({
|
||||
default_agent: 'assistant',
|
||||
agent: { assistant: { mode: 'all' } },
|
||||
}, null, 2))
|
||||
|
||||
const generatedPrompt = buildAssistantDefaultAgentMd().split('---\n\n')[1]?.trimEnd()
|
||||
if (generatedPrompt === undefined) throw new Error('Generated assistant prompt is missing')
|
||||
|
||||
const api = createConfigApi((assistantDir) => [{
|
||||
type: 'document',
|
||||
path: path.join(assistantDir, 'opencode.json'),
|
||||
info: {
|
||||
default_agent: 'assistant',
|
||||
permissions: convertedPermissions,
|
||||
agents: { assistant: { mode: 'all', system: generatedPrompt, description: 'Generated persona' } },
|
||||
},
|
||||
}])
|
||||
|
||||
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
|
||||
|
||||
const config = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
||||
expect(config.agents.assistant).toEqual({ mode: 'all' })
|
||||
})
|
||||
|
||||
it('leaves the file unchanged when the OpenCode client fails', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
await writeFile(opencodeJsonPath, v1Config)
|
||||
|
||||
const api = {
|
||||
config: {
|
||||
get: async () => { throw new Error('unreachable') },
|
||||
},
|
||||
} as unknown as OpenCodeApi
|
||||
|
||||
const converted = await convertAssistantOpenCodeConfigToV2(api)
|
||||
|
||||
expect(converted).toBe(false)
|
||||
expect(await readFile(opencodeJsonPath, 'utf8')).toBe(v1Config)
|
||||
})
|
||||
|
||||
it('does nothing for a v2 config', async () => {
|
||||
await ensureAssistantMode(mockRepo)
|
||||
let calls = 0
|
||||
const api = {
|
||||
config: {
|
||||
get: async () => { calls += 1; return [] },
|
||||
},
|
||||
} as unknown as OpenCodeApi
|
||||
|
||||
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false)
|
||||
expect(calls).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('assistant-mode end-to-end', () => {
|
||||
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
|
||||
let db: ReturnType<typeof createTestDb>
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { OpenCodeConfigSchema } from "@opencode-manager/shared/schemas";
|
||||
|
||||
describe("OpenCodeConfigSchema - provider api/npm round-trip", () => {
|
||||
it("preserves a provider-level api URL through parse", () => {
|
||||
const input = {
|
||||
provider: {
|
||||
"my-api": {
|
||||
name: "My API",
|
||||
api: "https://api.example.com/v1",
|
||||
options: { baseURL: "https://api.example.com/v1" },
|
||||
},
|
||||
},
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.provider?.["my-api"]?.api).toBe("https://api.example.com/v1");
|
||||
expect(parsed.provider?.["my-api"]?.options?.baseURL).toBe("https://api.example.com/v1");
|
||||
});
|
||||
|
||||
it("preserves a provider-level npm package through parse", () => {
|
||||
const input = {
|
||||
provider: {
|
||||
"my-npm": {
|
||||
name: "My NPM Provider",
|
||||
npm: "@scope/opencode-provider",
|
||||
},
|
||||
},
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.provider?.["my-npm"]?.npm).toBe("@scope/opencode-provider");
|
||||
});
|
||||
|
||||
it("preserves whitelist and blacklist model filters through parse", () => {
|
||||
const input = {
|
||||
provider: {
|
||||
openai: {
|
||||
whitelist: ["gpt-4o", "gpt-4o-mini"],
|
||||
blacklist: ["gpt-3.5"],
|
||||
},
|
||||
},
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.provider?.openai?.whitelist).toEqual(["gpt-4o", "gpt-4o-mini"]);
|
||||
expect(parsed.provider?.openai?.blacklist).toEqual(["gpt-3.5"]);
|
||||
});
|
||||
|
||||
it("round-trips a full provider-with-models config without losing api or npm", () => {
|
||||
const input = {
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
provider: {
|
||||
custom: {
|
||||
name: "Custom",
|
||||
api: "https://api.custom.example/v1",
|
||||
npm: "custom-provider",
|
||||
models: {
|
||||
"custom-1": {
|
||||
id: "custom-1",
|
||||
name: "Custom 1",
|
||||
limit: { context: 200000, output: 8192 },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
const roundTripped = OpenCodeConfigSchema.parse(JSON.parse(JSON.stringify(parsed)));
|
||||
expect(roundTripped.provider?.custom?.api).toBe("https://api.custom.example/v1");
|
||||
expect(roundTripped.provider?.custom?.npm).toBe("custom-provider");
|
||||
expect(roundTripped.provider?.custom?.models?.["custom-1"]?.id).toBe("custom-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCodeConfigSchema - native V2 fields", () => {
|
||||
it("accepts native plugin entries with package objects", () => {
|
||||
const input = {
|
||||
plugins: ["plain-plugin", { package: "@scope/plugin", options: { enabled: true } }],
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.plugins).toEqual(input.plugins);
|
||||
});
|
||||
|
||||
it("accepts a native permissions rule set", () => {
|
||||
const input = {
|
||||
permissions: [
|
||||
{ action: "shell", resource: "*", effect: "allow" },
|
||||
{ action: "read", resource: "src/**", effect: "deny" },
|
||||
],
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.permissions).toEqual(input.permissions);
|
||||
});
|
||||
|
||||
it("accepts skills as an array of paths or urls", () => {
|
||||
const input = { skills: ["https://example.com/skill", "./skills"] };
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.skills).toEqual(input.skills);
|
||||
});
|
||||
|
||||
it("still accepts the legacy skills object", () => {
|
||||
const input = { skills: { paths: [".opencode/skills"], urls: [] } };
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.skills).toEqual(input.skills);
|
||||
});
|
||||
|
||||
it("accepts a native mcp servers record", () => {
|
||||
const input = { mcp: { servers: { docs: { type: "remote", url: "https://example.com/mcp" } } } };
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.mcp).toEqual(input.mcp);
|
||||
});
|
||||
|
||||
it("accepts native top-level fields alongside legacy ones", () => {
|
||||
const input = {
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
update: "notify",
|
||||
snapshots: true,
|
||||
username: "manager",
|
||||
agents: { assistant: { mode: "primary" } },
|
||||
commands: { review: { description: "Review changes" } },
|
||||
providers: { custom: { npm: "custom-provider" } },
|
||||
media: { image: { max_width: 2048 } },
|
||||
references: { docs: { path: "./docs" } },
|
||||
worktree: { directory: "../worktrees" },
|
||||
websearch: { provider: "random" },
|
||||
warming: false,
|
||||
compaction: { auto: true },
|
||||
experimental: { subagent_depth: 1 },
|
||||
tool_output: { max_lines: 500 },
|
||||
watcher: { ignore: ["node_modules"] },
|
||||
default_agent: "assistant",
|
||||
agent: { assistant: { mode: "primary" } },
|
||||
};
|
||||
const parsed = OpenCodeConfigSchema.parse(input);
|
||||
expect(parsed.update).toBe("notify");
|
||||
expect(parsed.snapshots).toBe(true);
|
||||
expect(parsed.username).toBe("manager");
|
||||
expect(parsed.agents?.assistant?.mode).toBe("primary");
|
||||
expect(parsed.providers?.custom?.npm).toBe("custom-provider");
|
||||
expect(parsed.default_agent).toBe("assistant");
|
||||
});
|
||||
|
||||
it("rejects an unknown update mode", () => {
|
||||
expect(() => OpenCodeConfigSchema.parse({ update: "sometimes" })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -302,164 +302,6 @@ export const UpdateSettingsRequestSchema = z.object({
|
||||
preferences: UserPreferencesSchema.partial(),
|
||||
});
|
||||
|
||||
export const ProviderApiConfigSchema = z.object({
|
||||
url: z.string(),
|
||||
npm: z.string().optional(),
|
||||
});
|
||||
|
||||
export type ProviderApiConfig = z.infer<typeof ProviderApiConfigSchema>;
|
||||
|
||||
export const ModelCapabilitiesSchema = z.object({
|
||||
temperature: z.boolean(),
|
||||
reasoning: z.boolean(),
|
||||
attachment: z.boolean(),
|
||||
toolcall: z.boolean(),
|
||||
input: z.object({
|
||||
text: z.boolean(),
|
||||
audio: z.boolean(),
|
||||
image: z.boolean(),
|
||||
video: z.boolean(),
|
||||
pdf: z.boolean(),
|
||||
}),
|
||||
output: z.object({
|
||||
text: z.boolean(),
|
||||
audio: z.boolean(),
|
||||
image: z.boolean(),
|
||||
video: z.boolean(),
|
||||
pdf: z.boolean(),
|
||||
}),
|
||||
interleaved: z.union([
|
||||
z.boolean(),
|
||||
z.object({
|
||||
field: z.enum(["reasoning_content", "reasoning_details"]),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const ModelCostSchema = z.object({
|
||||
input: z.number(),
|
||||
output: z.number(),
|
||||
cache: z.object({
|
||||
read: z.number(),
|
||||
write: z.number(),
|
||||
}).optional(),
|
||||
experimentalOver200K: z.object({
|
||||
input: z.number(),
|
||||
output: z.number(),
|
||||
cache: z.object({
|
||||
read: z.number(),
|
||||
write: z.number(),
|
||||
}).optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export const ModelLimitSchema = z.object({
|
||||
context: z.number(),
|
||||
input: z.number().optional(),
|
||||
output: z.number(),
|
||||
});
|
||||
|
||||
export const ModelConfigSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
providerID: z.string().optional(),
|
||||
api: ProviderApiConfigSchema.optional(),
|
||||
name: z.string().optional(),
|
||||
family: z.string().optional(),
|
||||
capabilities: ModelCapabilitiesSchema.optional(),
|
||||
cost: ModelCostSchema.optional(),
|
||||
limit: ModelLimitSchema.optional(),
|
||||
status: z.enum(["alpha", "beta", "deprecated", "active"]).optional(),
|
||||
options: z.record(z.string(), z.any()).optional(),
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
release_date: z.string().optional(),
|
||||
variants: z.record(z.string(), z.record(z.string(), z.any())).optional(),
|
||||
});
|
||||
|
||||
export type ModelConfig = z.infer<typeof ModelConfigSchema>;
|
||||
|
||||
export const ProviderSourceSchema = z.enum(["env", "config", "custom", "api"]);
|
||||
|
||||
export const ProviderConfigSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
source: ProviderSourceSchema.optional(),
|
||||
env: z.array(z.string()).optional().default([]),
|
||||
key: z.string().optional(),
|
||||
api: z.string().optional(),
|
||||
npm: z.string().optional(),
|
||||
whitelist: z.array(z.string()).optional(),
|
||||
blacklist: z.array(z.string()).optional(),
|
||||
options: z.record(z.string(), z.any()).optional(),
|
||||
models: z.record(z.string(), ModelConfigSchema).optional(),
|
||||
});
|
||||
|
||||
export type ProviderSource = z.infer<typeof ProviderSourceSchema>;
|
||||
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>;
|
||||
|
||||
export const OpenCodePluginOptionsSchema = z.record(z.string(), z.unknown());
|
||||
export const OpenCodePluginSpecSchema = z.union([
|
||||
z.string(),
|
||||
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(),
|
||||
model: z.string().optional(),
|
||||
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(),
|
||||
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({
|
||||
path: z.string(),
|
||||
message: z.string(),
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
SettingsResponseSchema,
|
||||
UpdateSettingsRequestSchema,
|
||||
CustomCommandSchema,
|
||||
OpenCodeConfigSchema,
|
||||
OpenCodeConfigFileSchema,
|
||||
OpenCodeConfigSourceFileSchema,
|
||||
OpenCodeConfigValidationIssueSchema,
|
||||
@@ -80,7 +79,6 @@ export type OpenCodeConfigFile = z.infer<typeof OpenCodeConfigFileSchema>
|
||||
export type { OpenCodeConfigSourceName } from '../config/defaults'
|
||||
export type OpenCodeConfigSourceFile = z.infer<typeof OpenCodeConfigSourceFileSchema>
|
||||
export type OpenCodeConfigValidationIssue = z.infer<typeof OpenCodeConfigValidationIssueSchema>
|
||||
export type OpenCodeConfigInput = z.infer<typeof OpenCodeConfigSchema>
|
||||
export type UpdateOpenCodeConfigRequest = z.infer<typeof UpdateOpenCodeConfigRequestSchema>
|
||||
|
||||
export type Repo = z.infer<typeof RepoSchema>
|
||||
@@ -145,12 +143,6 @@ export interface SuccessResponse {
|
||||
|
||||
export type { SSHHostKeyRequest, SSHHostKeyResponse, TrustedSSHHost } from '../schemas/ssh'
|
||||
export type { GitCredential, GitIdentityProfile } from '../schemas/settings'
|
||||
export type {
|
||||
ProviderApiConfig,
|
||||
ModelConfig,
|
||||
ProviderConfig,
|
||||
ProviderSource,
|
||||
} from '../schemas/settings'
|
||||
|
||||
export type {
|
||||
ScheduleMode,
|
||||
|
||||
Reference in new issue
Block a user