mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +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
+34
-109
@@ -1,76 +1,60 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { callOpenCode } from './opencodeApi'
|
||||
import {
|
||||
isMcpServerNotFoundError,
|
||||
mcpStatusByName,
|
||||
openCodeLocation,
|
||||
type McpServerConfig,
|
||||
type McpStatusMap,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
|
||||
export type McpStatus =
|
||||
| { status: 'connected' }
|
||||
| { status: 'disabled' }
|
||||
| { status: 'failed'; error: string }
|
||||
| { status: 'needs_auth' }
|
||||
| { status: 'needs_client_registration'; error: string }
|
||||
|
||||
export type McpStatusMap = Record<string, McpStatus>
|
||||
|
||||
export interface McpServerConfig {
|
||||
type: 'local' | 'remote'
|
||||
enabled?: boolean
|
||||
command?: string[]
|
||||
url?: string
|
||||
environment?: Record<string, string>
|
||||
headers?: Record<string, string>
|
||||
timeout?: number
|
||||
oauth?: boolean | {
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
scope?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface AddMcpServerRequest {
|
||||
name: string
|
||||
config: McpServerConfig
|
||||
}
|
||||
export type { McpServerConfig, McpStatus } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export interface McpAuthStartResponse {
|
||||
authorizationUrl: string
|
||||
flowId: string
|
||||
}
|
||||
|
||||
export type McpOAuthFlowStatus =
|
||||
type McpOAuthFlowStatus =
|
||||
| { status: 'pending' }
|
||||
| { status: 'completed'; serverName: string }
|
||||
| { status: 'failed'; error: string }
|
||||
| { status: 'unknown' }
|
||||
|
||||
export const mcpApi = {
|
||||
async getStatus(): Promise<McpStatusMap> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp`)
|
||||
async getStatus(directory?: string): Promise<McpStatusMap> {
|
||||
const { data } = await callOpenCode((api) => api.mcp.list(openCodeLocation(directory)))
|
||||
return mcpStatusByName(data)
|
||||
},
|
||||
|
||||
async addServer(name: string, config: McpServerConfig): Promise<McpStatusMap> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, config }),
|
||||
async addServer(name: string, config: McpServerConfig): Promise<void> {
|
||||
await callOpenCode((api) => api.mcp.add({ server: name, config }))
|
||||
},
|
||||
|
||||
async removeServer(name: string): Promise<void> {
|
||||
await callOpenCode(async (api) => {
|
||||
try {
|
||||
await api.mcp.remove({ server: name })
|
||||
} catch (error) {
|
||||
if (!isMcpServerNotFoundError(error)) throw error
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
async connect(name: string): Promise<boolean> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/connect`, {
|
||||
method: 'POST',
|
||||
})
|
||||
async connect(name: string, directory?: string): Promise<void> {
|
||||
await callOpenCode((api) => api.mcp.connect({ server: name, ...openCodeLocation(directory) }))
|
||||
},
|
||||
|
||||
async disconnect(name: string): Promise<boolean> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/disconnect`, {
|
||||
method: 'POST',
|
||||
})
|
||||
async disconnect(name: string, directory?: string): Promise<void> {
|
||||
await callOpenCode((api) => api.mcp.disconnect({ server: name, ...openCodeLocation(directory) }))
|
||||
},
|
||||
|
||||
async startAuth(name: string, serverUrl: string, scope?: string, clientId?: string, clientSecret?: string, directory?: string): Promise<McpAuthStartResponse> {
|
||||
async startAuth(name: string, directory?: string): Promise<McpAuthStartResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/start`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ serverName: name, serverUrl, scope, clientId, clientSecret, directory }),
|
||||
body: JSON.stringify({ serverName: name, directory }),
|
||||
})
|
||||
},
|
||||
|
||||
@@ -82,69 +66,10 @@ export const mcpApi = {
|
||||
}
|
||||
},
|
||||
|
||||
async completeAuth(name: string, code: string): Promise<McpStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/auth/callback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
})
|
||||
},
|
||||
|
||||
async authenticate(name: string): Promise<McpStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/auth/authenticate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
},
|
||||
|
||||
async removeAuth(name: string): Promise<{ success: true }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/auth`, {
|
||||
async removeAuth(name: string, directory?: string): Promise<{ success: true }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/credentials/${encodeURIComponent(name)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
},
|
||||
|
||||
async getStatusFor(directory: string): Promise<McpStatusMap> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp`, {
|
||||
params: { directory },
|
||||
})
|
||||
},
|
||||
|
||||
async getConfigForDirectory(directory: string): Promise<Record<string, unknown>> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/opencode/config`, {
|
||||
params: { directory },
|
||||
})
|
||||
},
|
||||
|
||||
async connectDirectory(name: string, directory: string): Promise<boolean> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/connectdirectory`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
},
|
||||
|
||||
async disconnectDirectory(name: string, directory: string): Promise<boolean> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/disconnectdirectory`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
},
|
||||
|
||||
async authenticateDirectory(name: string, directory: string): Promise<McpStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/authdirectedir`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
},
|
||||
|
||||
async removeAuthDirectory(name: string, directory: string): Promise<{ success: true }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/authdir`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
params: directory ? { directory } : undefined,
|
||||
})
|
||||
},
|
||||
}
|
||||
+29
-19
@@ -1,38 +1,48 @@
|
||||
import { API_BASE_URL } from "@/config"
|
||||
import type { components, operations } from "./opencode-types"
|
||||
import { fetchWrapper } from "./fetchWrapper"
|
||||
import type { FormAnswer, IntegrationMethod } from "@opencode-manager/shared/opencode"
|
||||
import type { OAuthAttemptStatus, OAuthAuthorizeResponse } from "@opencode-manager/shared/schemas"
|
||||
import { fetchWrapper, fetchWrapperVoid } from "./fetchWrapper"
|
||||
|
||||
type OpenCodeAuthorizeRequest = NonNullable<operations["provider.oauth.authorize"]["requestBody"]>["content"]["application/json"]
|
||||
export type {
|
||||
FormAnswer,
|
||||
FormField,
|
||||
FormValue,
|
||||
IntegrationKeyMethod,
|
||||
IntegrationMethod,
|
||||
IntegrationOAuthMethod,
|
||||
} from "@opencode-manager/shared/opencode"
|
||||
|
||||
export type OAuthAuthorizeResponse = components["schemas"]["ProviderAuthAuthorization"]
|
||||
export type { OAuthAuthorizeResponse } from "@opencode-manager/shared/schemas"
|
||||
|
||||
export type OAuthCallbackRequest = NonNullable<operations["provider.oauth.callback"]["requestBody"]>["content"]["application/json"]
|
||||
|
||||
export type ProviderAuthMethod = components["schemas"]["ProviderAuthMethod"]
|
||||
|
||||
export interface ProviderAuthMethods {
|
||||
[providerId: string]: ProviderAuthMethod[]
|
||||
}
|
||||
type ProviderAuthMethods = Record<string, IntegrationMethod[]>
|
||||
|
||||
export const oauthApi = {
|
||||
authorize: async (providerId: string, method: number, inputs?: OpenCodeAuthorizeRequest["inputs"]): Promise<OAuthAuthorizeResponse> =>
|
||||
fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, {
|
||||
authorize: async (providerId: string, methodID: string, answer?: FormAnswer): Promise<OAuthAuthorizeResponse> =>
|
||||
fetchWrapper<OAuthAuthorizeResponse>(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ method, inputs }),
|
||||
body: JSON.stringify({ methodID, answer }),
|
||||
}),
|
||||
|
||||
callback: async (providerId: string, request: OAuthCallbackRequest): Promise<boolean> =>
|
||||
fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, {
|
||||
getStatus: async (providerId: string, attemptID: string): Promise<OAuthAttemptStatus> =>
|
||||
fetchWrapper<OAuthAttemptStatus>(`${API_BASE_URL}/api/oauth/${providerId}/oauth/${attemptID}`),
|
||||
|
||||
callback: async (providerId: string, attemptID: string, code?: string): Promise<void> =>
|
||||
fetchWrapperVoid(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
body: JSON.stringify({ attemptID, code }),
|
||||
}),
|
||||
|
||||
cancel: async (providerId: string, attemptID: string): Promise<void> =>
|
||||
fetchWrapperVoid(`${API_BASE_URL}/api/oauth/${providerId}/oauth/${attemptID}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
|
||||
getAuthMethods: async (): Promise<ProviderAuthMethods> => {
|
||||
const { providers, ...rest } = await fetchWrapper<{ providers?: ProviderAuthMethods } & ProviderAuthMethods>(
|
||||
const { providers } = await fetchWrapper<{ providers: ProviderAuthMethods }>(
|
||||
`${API_BASE_URL}/api/oauth/auth-methods`
|
||||
)
|
||||
return providers || rest
|
||||
return providers
|
||||
},
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+487
-169
@@ -1,7 +1,49 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OpenCodeClient } from './opencode'
|
||||
import {
|
||||
activateSkill,
|
||||
cancelForm,
|
||||
clearRevert,
|
||||
commitRevert,
|
||||
compactSession,
|
||||
createSession,
|
||||
deleteSession,
|
||||
findFiles,
|
||||
forkSession,
|
||||
getSession,
|
||||
interruptSession,
|
||||
listCommands,
|
||||
listPendingForms,
|
||||
listPendingPermissions,
|
||||
listSessionMessages,
|
||||
listSessionPage,
|
||||
readSessionSnapshot,
|
||||
renameSession,
|
||||
replyForm,
|
||||
replyPermission,
|
||||
runCommand,
|
||||
runShell,
|
||||
sendPrompt,
|
||||
stageRevert,
|
||||
switchSessionAgent,
|
||||
switchSessionModel,
|
||||
} from './opencode'
|
||||
import { FetchError } from './fetchWrapper'
|
||||
|
||||
describe('OpenCodeClient', () => {
|
||||
const jsonResponse = (body: unknown) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
const sessionInfo = (id: string, directory: string) => ({
|
||||
id,
|
||||
projectID: 'proj_1',
|
||||
title: `Session ${id}`,
|
||||
time: { created: 1000, updated: 2000 },
|
||||
location: { directory },
|
||||
})
|
||||
|
||||
describe('OpenCode facade', () => {
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -13,213 +55,489 @@ describe('OpenCodeClient', () => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('treats empty successful session deletes as success', async () => {
|
||||
const lastRequest = () => {
|
||||
const [input, init] = fetchMock.mock.calls.at(-1) ?? []
|
||||
return { url: String(input), init: init as RequestInit }
|
||||
}
|
||||
|
||||
it('lists root sessions for a directory through the V2 cursor API', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ data: [sessionInfo('ses_1', '/repo')], cursor: { next: 'cursor_next' } }),
|
||||
)
|
||||
|
||||
const page = await listSessionPage({
|
||||
directory: '/repo',
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: 'deploy',
|
||||
})
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&search=deploy&parentID=null&directory=%2Frepo',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(page.items).toEqual([sessionInfo('ses_1', '/repo')])
|
||||
expect(page.nextCursor).toBe('cursor_next')
|
||||
})
|
||||
|
||||
it('passes the directory and cursor for continuation pages', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: [], cursor: {} }))
|
||||
|
||||
const page = await listSessionPage({ directory: '/repo', cursor: 'cursor_1' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?parentID=null&directory=%2Frepo&cursor=cursor_1',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(page.items).toEqual([])
|
||||
expect(page.nextCursor).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads a single session from the V2 session route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_1', '/repo') }))
|
||||
|
||||
const session = await getSession('ses_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1')
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(session).toEqual(sessionInfo('ses_1', '/repo'))
|
||||
})
|
||||
|
||||
it('creates a session with location and a parsed model reference', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_new', '/repo') }))
|
||||
|
||||
const session = await createSession({
|
||||
directory: '/repo',
|
||||
title: 'New session',
|
||||
agent: 'build',
|
||||
model: 'anthropic/claude#v1',
|
||||
})
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({
|
||||
title: 'New session',
|
||||
agent: 'build',
|
||||
model: { providerID: 'anthropic', id: 'claude', variant: 'v1' },
|
||||
location: { directory: '/repo' },
|
||||
}))
|
||||
expect(session.id).toBe('ses_new')
|
||||
})
|
||||
|
||||
it('creates a session with the required location and no optional fields', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_new', '/repo') }))
|
||||
|
||||
await createSession({ directory: '/repo' })
|
||||
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ location: { directory: '/repo' } }))
|
||||
})
|
||||
|
||||
it('deletes a session through the V2 session route', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await expect(new OpenCodeClient('/api/opencode', '/repo').deleteSession('ses_1')).resolves.toBeUndefined()
|
||||
await expect(deleteSession('ses_1')).resolves.toBeUndefined()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/session/ses_1?directory=%2Frepo',
|
||||
expect.objectContaining({ method: 'DELETE' }),
|
||||
)
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1')
|
||||
expect(lastRequest().init.method).toBe('DELETE')
|
||||
})
|
||||
|
||||
it('deletes workspaces with directory routing', async () => {
|
||||
it('renames a session with a title update', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await expect(new OpenCodeClient('/api/opencode', '/repo').deleteWorkspace('wrk_stale')).resolves.toBeUndefined()
|
||||
await renameSession('ses_1', 'Renamed')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/experimental/workspace/wrk_stale?directory=%2Frepo',
|
||||
expect.objectContaining({ method: 'DELETE' }),
|
||||
)
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1')
|
||||
expect(lastRequest().init.method).toBe('PATCH')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ title: 'Renamed' }))
|
||||
})
|
||||
|
||||
it('preserves text error responses', async () => {
|
||||
fetchMock.mockResolvedValue(new Response('Workspace not found: wrk_stale', { status: 500 }))
|
||||
it('forks a session before a message', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_child', '/repo') }))
|
||||
|
||||
await expect(new OpenCodeClient('/api/opencode', '/repo').deleteSession('ses_1')).rejects.toThrow(
|
||||
'Workspace not found: wrk_stale',
|
||||
)
|
||||
const forked = await forkSession('ses_1', 'msg_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/fork')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ before: 'msg_1' }))
|
||||
expect(forked.id).toBe('ses_child')
|
||||
})
|
||||
|
||||
it('responds to permission requests via the request-scoped reply endpoint', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({}), { status: 200 }))
|
||||
it('forks a session without a boundary when none is given', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_child', '/repo') }))
|
||||
|
||||
await new OpenCodeClient('/api/opencode', '/repo').respondToPermission('per_1', 'reject')
|
||||
await forkSession('ses_1')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/permission/per_1/reply?directory=%2Frepo',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: expect.objectContaining({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ reply: 'reject' }),
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/fork')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({}))
|
||||
})
|
||||
|
||||
it('finds files through the V2 filesystem route and returns paths', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{ path: 'src/index.ts', type: 'file' },
|
||||
{ path: 'src/app.ts', type: 'file' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
const files = await findFiles({ directory: '/repo', query: 'index', limit: 20 })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/fs/find?location%5Bdirectory%5D=%2Frepo&query=index&type=file&limit=20',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(files).toEqual(['src/index.ts', 'src/app.ts'])
|
||||
})
|
||||
|
||||
describe('listSessionsPage', () => {
|
||||
it('handles v1.16.0+ API response format with data envelope and nested location', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{
|
||||
id: 'ses_v2_1',
|
||||
projectID: 'proj_v2',
|
||||
parentID: 'parent_v2',
|
||||
title: 'V2 Session',
|
||||
time: { created: 3000, updated: 4000 },
|
||||
location: { directory: '/my-repo', workspaceID: 'ws_v2' },
|
||||
agent: 'default',
|
||||
model: { id: 'gpt-4', providerID: 'openai' },
|
||||
cost: 0.05,
|
||||
tokens: { input: 100, output: 50, reasoning: 10, cache: { read: 0, write: 0 } },
|
||||
},
|
||||
],
|
||||
cursor: { next: 'v2_cursor' },
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
it('finds files without a limit when none is given', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ location: { directory: '/repo' }, data: [] }))
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({ limit: 10 })
|
||||
await findFiles({ directory: '/repo', query: 'index' })
|
||||
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.items[0]).toMatchObject({
|
||||
id: 'ses_v2_1',
|
||||
projectID: 'proj_v2',
|
||||
workspaceID: 'ws_v2',
|
||||
directory: '/repo',
|
||||
parentID: 'parent_v2',
|
||||
title: 'V2 Session',
|
||||
version: 'v2',
|
||||
})
|
||||
expect(result.nextCursor).toBe('v2_cursor')
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/fs/find?location%5Bdirectory%5D=%2Frepo&query=index&type=file',
|
||||
)
|
||||
})
|
||||
|
||||
it('reads a session snapshot from the message page, inbox, and active sessions', async () => {
|
||||
const message = {
|
||||
id: 'msg_1',
|
||||
type: 'user' as const,
|
||||
text: 'Run the tests',
|
||||
time: { created: 1000 },
|
||||
}
|
||||
const inbox = {
|
||||
id: 'msg_2',
|
||||
sessionID: 'ses_1',
|
||||
time: { created: 2000 },
|
||||
type: 'user' as const,
|
||||
payload: { text: 'Wait for me' },
|
||||
delivery: 'queue' as const,
|
||||
}
|
||||
fetchMock.mockImplementation((input: unknown) => {
|
||||
const url = String(input)
|
||||
if (url.endsWith('/api/session/ses_1/inbox')) {
|
||||
return Promise.resolve(jsonResponse({ data: [inbox] }))
|
||||
}
|
||||
if (url.endsWith('/api/session/active')) {
|
||||
return Promise.resolve(jsonResponse({ data: { ses_1: { type: 'running' } } }))
|
||||
}
|
||||
return Promise.resolve(jsonResponse({ data: [message], cursor: { next: 'cursor_next' } }))
|
||||
})
|
||||
|
||||
it('sends first-page params to /api/session with directory and returns adapted sessions', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: 'ses_1',
|
||||
projectID: 'proj_1',
|
||||
workspaceID: 'ws_1',
|
||||
parentID: 'parent_1',
|
||||
title: 'My Session',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
},
|
||||
],
|
||||
cursor: { next: 'cursor_next' },
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
const snapshot = await readSessionSnapshot('ses_1')
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: 'deploy',
|
||||
})
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&search=deploy&directory=%2Frepo',
|
||||
expect.any(Object),
|
||||
)
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.items[0]).toMatchObject({
|
||||
id: 'ses_1',
|
||||
projectID: 'proj_1',
|
||||
directory: '/repo',
|
||||
parentID: 'parent_1',
|
||||
title: 'My Session',
|
||||
version: 'v2',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
})
|
||||
expect(snapshot).toEqual({
|
||||
messages: [message],
|
||||
nextCursor: 'cursor_next',
|
||||
pending: [inbox],
|
||||
status: 'busy',
|
||||
})
|
||||
expect(fetchMock.mock.calls.map(([input]) => String(input)).sort()).toEqual([
|
||||
'http://localhost/api/opencode/api/session/active',
|
||||
'http://localhost/api/opencode/api/session/ses_1/inbox',
|
||||
'http://localhost/api/opencode/api/session/ses_1/message?order=desc',
|
||||
])
|
||||
})
|
||||
|
||||
it('sends cursor-only params without directory for cursor-based requests', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
it('requests the newest message page with descending order', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ data: [{ id: 'msg_3' }, { id: 'msg_2' }], cursor: { next: 'cursor_2' } }),
|
||||
)
|
||||
|
||||
await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({ cursor: 'cursor_123' })
|
||||
const page = await listSessionMessages('ses_1', { limit: 20 })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/api/session?cursor=cursor_123',
|
||||
expect.any(Object),
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session/ses_1/message?limit=20&order=desc',
|
||||
)
|
||||
expect(page.messages.map((message) => message.id)).toEqual(['msg_2', 'msg_3'])
|
||||
expect(page.nextCursor).toBe('cursor_2')
|
||||
})
|
||||
|
||||
it('omits order on continuation pages so the server accepts the cursor', async () => {
|
||||
const server = vi.fn((input: unknown) => {
|
||||
const url = String(input)
|
||||
if (url.includes('cursor=') && url.includes('order=')) {
|
||||
return Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({ _tag: 'InvalidCursorError', message: 'Cursor cannot be combined with order' }),
|
||||
{ status: 400, headers: { 'Content-Type': 'application/json' } },
|
||||
),
|
||||
)
|
||||
}
|
||||
return Promise.resolve(
|
||||
jsonResponse({ data: [{ id: 'msg_2' }, { id: 'msg_1' }], cursor: { next: 'cursor_2' } }),
|
||||
)
|
||||
})
|
||||
fetchMock.mockImplementation(server)
|
||||
|
||||
it('exposes response cursor as nextCursor', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [],
|
||||
cursor: { next: 'next_1' },
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
const page = await listSessionMessages('ses_1', { cursor: 'cursor_1' })
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({ limit: 10 })
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session/ses_1/message?cursor=cursor_1',
|
||||
)
|
||||
expect(page.messages.map((message) => message.id)).toEqual(['msg_1', 'msg_2'])
|
||||
expect(page.nextCursor).toBe('cursor_2')
|
||||
})
|
||||
|
||||
expect(result.nextCursor).toBe('next_1')
|
||||
it('wraps V2 client failures in a FetchError', async () => { fetchMock.mockResolvedValue(new Response('upstream exploded', { status: 500 }))
|
||||
|
||||
const failure = await getSession('ses_1').catch((error: unknown) => error)
|
||||
|
||||
expect(failure).toBeInstanceOf(FetchError)
|
||||
expect((failure as FetchError).statusCode).toBe(500)
|
||||
})
|
||||
|
||||
it('maps a declared V2 not-found error to 404 instead of a network failure', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ _tag: 'SessionNotFoundError', sessionID: 'ses_1', message: 'Session not found' }),
|
||||
{ status: 404, headers: { 'Content-Type': 'application/json' } },
|
||||
),
|
||||
)
|
||||
|
||||
const failure = await getSession('ses_1').catch((error: unknown) => error)
|
||||
|
||||
expect(failure).toBeInstanceOf(FetchError)
|
||||
expect((failure as FetchError).statusCode).toBe(404)
|
||||
expect((failure as FetchError).message).toBe('Session not found')
|
||||
})
|
||||
|
||||
it('maps a declared V2 conflict error to 409', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ _tag: 'SessionBusyError', sessionID: 'ses_1', message: 'Session is busy' }),
|
||||
{ status: 409, headers: { 'Content-Type': 'application/json' } },
|
||||
),
|
||||
)
|
||||
|
||||
const failure = await sendPrompt({ sessionID: 'ses_1', text: 'Hi' }).catch((error: unknown) => error)
|
||||
|
||||
expect(failure).toBeInstanceOf(FetchError)
|
||||
expect((failure as FetchError).statusCode).toBe(409)
|
||||
})
|
||||
|
||||
it('sends a prompt with files, agents, skills, and delivery', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({
|
||||
data: {
|
||||
id: 'msg_1',
|
||||
sessionID: 'ses_1',
|
||||
time: { created: 1000 },
|
||||
type: 'user',
|
||||
payload: { text: 'Hello @src/a.ts' },
|
||||
delivery: 'queue',
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
const inbox = await sendPrompt({
|
||||
sessionID: 'ses_1',
|
||||
text: 'Hello @src/a.ts',
|
||||
files: [{ uri: 'file:///repo/src/a.ts', name: 'a.ts', mention: { start: 6, end: 15, text: '@src/a.ts' } }],
|
||||
agents: [{ name: 'build', mention: { start: 6, end: 12, text: '@build' } }],
|
||||
skills: [{ id: 'review' }],
|
||||
delivery: 'queue',
|
||||
})
|
||||
|
||||
it('uses Untitled Session for empty title', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: 'ses_2',
|
||||
projectID: 'proj_2',
|
||||
title: '',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/prompt')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({
|
||||
text: 'Hello @src/a.ts',
|
||||
files: [{ uri: 'file:///repo/src/a.ts', name: 'a.ts', mention: { start: 6, end: 15, text: '@src/a.ts' } }],
|
||||
agents: [{ name: 'build', mention: { start: 6, end: 12, text: '@build' } }],
|
||||
skills: [{ id: 'review' }],
|
||||
delivery: 'queue',
|
||||
}))
|
||||
expect(inbox.id).toBe('msg_1')
|
||||
})
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage()
|
||||
it('switches the session model through the V2 model route', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
expect(result.items[0].title).toBe('Untitled Session')
|
||||
await switchSessionModel('ses_1', { providerID: 'anthropic', id: 'claude', variant: 'v1' })
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/model')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ model: { providerID: 'anthropic', id: 'claude', variant: 'v1' } }))
|
||||
})
|
||||
|
||||
it('switches the session agent through the V2 agent route', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await switchSessionAgent('ses_1', 'build')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/agent')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ agent: 'build' }))
|
||||
})
|
||||
|
||||
it('runs a session command', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await runCommand({
|
||||
sessionID: 'ses_1',
|
||||
name: 'init',
|
||||
text: 'extra context',
|
||||
agents: [{ name: 'build' }],
|
||||
})
|
||||
|
||||
it('works without directory set', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: 'ses_3',
|
||||
projectID: 'proj_3',
|
||||
title: 'No Dir',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/command')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({
|
||||
name: 'init',
|
||||
text: 'extra context',
|
||||
agents: [{ name: 'build' }],
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode').listSessionsPage({ limit: 5 })
|
||||
it('runs a session shell command', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/api/session?limit=5',
|
||||
expect.any(Object),
|
||||
)
|
||||
expect(result.items[0].directory).toBe('')
|
||||
})
|
||||
await runShell('ses_1', 'ls -la')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/shell')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ command: 'ls -la' }))
|
||||
})
|
||||
|
||||
it('interrupts a session', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: { interrupted: true } }))
|
||||
|
||||
await interruptSession('ses_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/interrupt')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
})
|
||||
|
||||
it('stages, commits, and clears a session revert', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: { messageID: 'msg_1' } }))
|
||||
|
||||
await stageRevert('ses_1', 'msg_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/revert/stage')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ messageID: 'msg_1' }))
|
||||
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await commitRevert('ses_1')
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/revert/commit')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
|
||||
await clearRevert('ses_1')
|
||||
expect(lastRequest().url).toMatch(/\/revert$/)
|
||||
expect(lastRequest().init.method).toBe('DELETE')
|
||||
})
|
||||
|
||||
it('compacts a session', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ data: { id: 'cmp_1', sessionID: 'ses_1', time: { created: 1000 }, type: 'compaction', delivery: 'steer' } }),
|
||||
)
|
||||
|
||||
const compaction = await compactSession('ses_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/compact')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(compaction.id).toBe('cmp_1')
|
||||
})
|
||||
|
||||
it('activates a skill on the experimental session route', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await activateSkill('ses_1', 'review')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/experimental/session/ses_1/skill')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ id: 'review' }))
|
||||
})
|
||||
|
||||
it('lists commands scoped to a directory', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ location: { directory: '/repo' }, data: [{ name: 'init', description: 'Init' }] }),
|
||||
)
|
||||
|
||||
const commands = await listCommands('/repo')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/command?location%5Bdirectory%5D=%2Frepo')
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(commands).toEqual([{ name: 'init', description: 'Init' }])
|
||||
})
|
||||
|
||||
it('lists pending permissions scoped to a directory', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({
|
||||
location: { directory: '/repo' },
|
||||
data: [{ id: 'perm_1', sessionID: 'ses_1', action: 'shell', resources: ['ls'] }],
|
||||
}),
|
||||
)
|
||||
|
||||
const permissions = await listPendingPermissions('/repo')
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/permission/request?location%5Bdirectory%5D=%2Frepo',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(permissions).toEqual([{ id: 'perm_1', sessionID: 'ses_1', action: 'shell', resources: ['ls'] }])
|
||||
})
|
||||
|
||||
it('replies to a permission with a decision and rejection message', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await replyPermission('ses_1', 'perm_1', 'reject', 'not allowed')
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session/ses_1/permission/perm_1/reply',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ decision: 'reject', message: 'not allowed' }))
|
||||
})
|
||||
|
||||
it('replies to a permission without a message', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await replyPermission('ses_1', 'perm_1', 'once')
|
||||
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ decision: 'once' }))
|
||||
})
|
||||
|
||||
it('lists pending forms scoped to a directory', async () => {
|
||||
const form = {
|
||||
id: 'form_1',
|
||||
sessionID: 'ses_1',
|
||||
title: 'Continue?',
|
||||
fields: [{ key: 'q0', type: 'string' }],
|
||||
}
|
||||
fetchMock.mockResolvedValue(jsonResponse({ location: { directory: '/repo' }, data: [form] }))
|
||||
|
||||
const forms = await listPendingForms('/repo')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/form?location%5Bdirectory%5D=%2Frepo')
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(forms).toEqual([form])
|
||||
})
|
||||
|
||||
it('replies to a form with an answer keyed by field', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await replyForm('ses_1', 'form_1', { q0: 'Yes' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session/ses_1/form/form_1/reply',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ answer: { q0: 'Yes' } }))
|
||||
})
|
||||
|
||||
it('cancels a form', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
await cancelForm('ses_1', 'form_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/form/form_1')
|
||||
expect(lastRequest().init.method).toBe('DELETE')
|
||||
})
|
||||
})
|
||||
+261
-341
@@ -1,356 +1,276 @@
|
||||
import type { paths } from './opencode-types'
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { callOpenCode } from './opencodeApi'
|
||||
import type {
|
||||
AgentInfo,
|
||||
CommandInfo,
|
||||
FormAnswer,
|
||||
FormInfo,
|
||||
ModelRef,
|
||||
OpenCodeApi,
|
||||
PermissionRequest,
|
||||
SessionInboxCompaction,
|
||||
SessionInboxUser,
|
||||
SessionInfo,
|
||||
SessionMessageInfo,
|
||||
SessionRevert,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import type { SessionSnapshot } from '@/lib/session-projection'
|
||||
|
||||
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
|
||||
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
|
||||
type SessionListParams = NonNullable<paths['/session']['get']['parameters']['query']> & {
|
||||
roots?: boolean
|
||||
}
|
||||
type CreateSessionRequest = NonNullable<paths['/session']['post']['requestBody']>['content']['application/json']
|
||||
type MessageListResponse = paths['/session/{sessionID}/message']['get']['responses']['200']['content']['application/json']
|
||||
type SendPromptAsyncRequest = NonNullable<paths['/session/{sessionID}/prompt_async']['post']['requestBody']>['content']['application/json']
|
||||
type ConfigResponse = paths['/config']['get']['responses']['200']['content']['application/json']
|
||||
type CommandListResponse = paths['/command']['get']['responses']['200']['content']['application/json']
|
||||
type CommandRequest = NonNullable<paths['/session/{sessionID}/command']['post']['requestBody']>['content']['application/json']
|
||||
type SendCommandResponse = paths['/session/{sessionID}/command']['post']['responses']['200']['content']['application/json']
|
||||
type ShellRequest = NonNullable<paths['/session/{sessionID}/shell']['post']['requestBody']>['content']['application/json']
|
||||
type AgentListResponse = paths['/agent']['get']['responses']['200']['content']['application/json']
|
||||
type PermissionListResponse = paths['/permission']['get']['responses']['200']['content']['application/json']
|
||||
type QuestionListResponse = paths['/question']['get']['responses']['200']['content']['application/json']
|
||||
type LspStatusResponse = paths['/lsp']['get']['responses']['200']['content']['application/json']
|
||||
type LspStatus = LspStatusResponse[number]
|
||||
type SessionPromptInput = Parameters<OpenCodeApi['session']['prompt']>[0]
|
||||
|
||||
type LegacySession = SessionListResponse[number]
|
||||
export type PromptFileInput = NonNullable<SessionPromptInput['files']>[number]
|
||||
|
||||
/** Pre-v1.16.0 session shape returned by /api/session */
|
||||
type SessionV2InfoV1 = {
|
||||
id: string
|
||||
parentID?: string
|
||||
projectID: string
|
||||
workspaceID?: string
|
||||
title: string
|
||||
time: { created: number; updated: number; compacting?: number; archived?: number }
|
||||
path?: unknown
|
||||
export type PromptAgentInput = NonNullable<SessionPromptInput['agents']>[number]
|
||||
|
||||
export type PromptSkillInput = NonNullable<SessionPromptInput['skills']>[number]
|
||||
|
||||
export type ActiveSessions = Awaited<ReturnType<OpenCodeApi['session']['active']>>
|
||||
|
||||
export interface SessionPage {
|
||||
items: SessionInfo[]
|
||||
nextCursor?: string
|
||||
}
|
||||
|
||||
/** v1.16.0+ session shape returned by /api/session */
|
||||
type SessionV2InfoV2 = {
|
||||
id: string
|
||||
parentID?: string
|
||||
projectID: string
|
||||
title: string
|
||||
time: { created: number; updated: number; archived?: number }
|
||||
location: { directory: string; workspaceID?: string }
|
||||
export interface SessionPageInput {
|
||||
directory: string
|
||||
limit?: number
|
||||
order?: 'asc' | 'desc'
|
||||
search?: string
|
||||
cursor?: string
|
||||
}
|
||||
|
||||
export interface CreateSessionInput {
|
||||
directory: string
|
||||
title?: string
|
||||
agent?: string
|
||||
model?: { id: string; providerID: string; variant?: string }
|
||||
cost: number
|
||||
tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
|
||||
subpath?: string
|
||||
model?: string
|
||||
}
|
||||
|
||||
type SessionV2Info = SessionV2InfoV1 | SessionV2InfoV2
|
||||
type SessionPageCursor = { previous?: string; next?: string }
|
||||
|
||||
/** Response from /api/session — may be old (items) or new (data) format */
|
||||
type SessionPageResponse = {
|
||||
data?: SessionV2InfoV2[]
|
||||
items?: SessionV2InfoV1[]
|
||||
cursor?: SessionPageCursor
|
||||
}
|
||||
type SessionPageParams = { limit?: number; order?: 'asc' | 'desc'; search?: string; cursor?: string }
|
||||
type SessionPage = { items: LegacySession[]; nextCursor?: string }
|
||||
|
||||
function isNewSession(session: SessionV2Info): session is SessionV2InfoV2 {
|
||||
return 'location' in session && session.location !== undefined
|
||||
export interface FindFilesInput {
|
||||
directory?: string
|
||||
query: string
|
||||
limit?: number
|
||||
}
|
||||
|
||||
function toLegacySession(session: SessionV2Info, directory?: string): LegacySession {
|
||||
if (isNewSession(session)) {
|
||||
return {
|
||||
id: session.id,
|
||||
projectID: session.projectID,
|
||||
workspaceID: session.location.workspaceID,
|
||||
directory: directory ?? session.location.directory ?? '',
|
||||
parentID: session.parentID,
|
||||
title: session.title || 'Untitled Session',
|
||||
version: 'v2',
|
||||
time: session.time,
|
||||
} as LegacySession
|
||||
}
|
||||
export interface SessionMessagesPage {
|
||||
messages: SessionMessageInfo[]
|
||||
nextCursor?: string
|
||||
}
|
||||
|
||||
export interface SessionMessagesInput {
|
||||
cursor?: string
|
||||
limit?: number
|
||||
}
|
||||
|
||||
export interface SendPromptInput {
|
||||
sessionID: string
|
||||
text: string
|
||||
files?: PromptFileInput[]
|
||||
agents?: PromptAgentInput[]
|
||||
skills?: PromptSkillInput[]
|
||||
delivery?: 'steer' | 'queue'
|
||||
}
|
||||
|
||||
export type RunCommandInput = SendPromptInput & { name: string }
|
||||
|
||||
type PromptFields = Pick<SendPromptInput, 'text' | 'files' | 'agents' | 'skills' | 'delivery'>
|
||||
|
||||
function buildPromptFields(input: PromptFields) {
|
||||
return {
|
||||
id: session.id,
|
||||
projectID: session.projectID,
|
||||
workspaceID: session.workspaceID,
|
||||
directory: directory ?? '',
|
||||
parentID: session.parentID,
|
||||
title: session.title || 'Untitled Session',
|
||||
version: 'v2',
|
||||
time: session.time,
|
||||
} as LegacySession
|
||||
}
|
||||
|
||||
export type { SendCommandResponse, LspStatus }
|
||||
|
||||
export class OpenCodeClient {
|
||||
private baseURL: string
|
||||
private directory?: string
|
||||
|
||||
constructor(baseURL: string, directory?: string) {
|
||||
this.baseURL = baseURL
|
||||
this.directory = directory
|
||||
}
|
||||
|
||||
setDirectory(directory: string) {
|
||||
this.directory = directory
|
||||
}
|
||||
|
||||
private getParams(params?: Record<string, string | number | boolean | undefined>) {
|
||||
if (!this.directory) return params
|
||||
return { ...params, directory: this.directory }
|
||||
}
|
||||
|
||||
async listSessions(params?: SessionListParams) {
|
||||
return fetchWrapper<SessionListResponse>(`${this.baseURL}/session`, {
|
||||
params: this.getParams(params),
|
||||
})
|
||||
}
|
||||
|
||||
async listSessionsPage(params?: SessionPageParams): Promise<SessionPage> {
|
||||
const isCursorRequest = params?.cursor !== undefined
|
||||
const queryParams = isCursorRequest
|
||||
? { cursor: params.cursor }
|
||||
: this.getParams({
|
||||
...(params?.limit !== undefined && { limit: params.limit }),
|
||||
...(params?.order !== undefined && { order: params.order }),
|
||||
...(params?.search !== undefined && { search: params.search }),
|
||||
})
|
||||
const response = await fetchWrapper<SessionPageResponse>(`${this.baseURL}/api/session`, {
|
||||
params: queryParams,
|
||||
})
|
||||
const rawItems = response.data ?? response.items ?? []
|
||||
return {
|
||||
items: rawItems.map((item) => toLegacySession(item, this.directory)),
|
||||
nextCursor: response.cursor?.next,
|
||||
}
|
||||
}
|
||||
|
||||
async getSession(sessionID: string) {
|
||||
return fetchWrapper<SessionResponse>(`${this.baseURL}/session/${sessionID}`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async createSession(data: CreateSessionRequest) {
|
||||
return fetchWrapper<SessionResponse>(`${this.baseURL}/session`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
async deleteSession(sessionID: string) {
|
||||
return fetchWrapperVoid(`${this.baseURL}/session/${sessionID}`, {
|
||||
method: 'DELETE',
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async deleteWorkspace(workspaceID: string) {
|
||||
return fetchWrapperVoid(`${this.baseURL}/experimental/workspace/${workspaceID}`, {
|
||||
method: 'DELETE',
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async updateSession(sessionID: string, data: { title?: string }) {
|
||||
return fetchWrapper(`${this.baseURL}/session/${sessionID}`, {
|
||||
method: 'PATCH',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
async forkSession(sessionID: string, messageID?: string) {
|
||||
return fetchWrapper<SessionResponse>(`${this.baseURL}/session/${sessionID}/fork`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ messageID }),
|
||||
})
|
||||
}
|
||||
|
||||
async abortSession(sessionID: string) {
|
||||
return fetchWrapper(`${this.baseURL}/session/${sessionID}/abort`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async listMessages(sessionID: string) {
|
||||
return fetchWrapper<MessageListResponse>(`${this.baseURL}/session/${sessionID}/message`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async sendPromptAsync(sessionID: string, data: SendPromptAsyncRequest): Promise<void> {
|
||||
return fetchWrapperVoid(
|
||||
`${this.baseURL}/session/${sessionID}/prompt_async`,
|
||||
{
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
timeout: 0,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async summarizeSession(sessionID: string, providerID: string, modelID: string) {
|
||||
return fetchWrapper(`${this.baseURL}/session/${sessionID}/summarize`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ providerID, modelID }),
|
||||
})
|
||||
}
|
||||
|
||||
async getConfig() {
|
||||
return fetchWrapper<ConfigResponse>(`${this.baseURL}/config`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async getLSPStatus() {
|
||||
return fetchWrapper<LspStatusResponse>(`${this.baseURL}/lsp`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async updateConfig(config: Partial<ConfigResponse>) {
|
||||
return fetchWrapper<ConfigResponse>(`${this.baseURL}/config`, {
|
||||
method: 'PATCH',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config),
|
||||
})
|
||||
}
|
||||
|
||||
async getProviders() {
|
||||
return fetchWrapper(`${this.baseURL}/provider`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async getConfigProviders() {
|
||||
return fetchWrapper(`${this.baseURL}/config/providers`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async listCommands() {
|
||||
return fetchWrapper<CommandListResponse>(`${this.baseURL}/command`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async sendCommand(sessionID: string, data: CommandRequest): Promise<SendCommandResponse> {
|
||||
return fetchWrapper<SendCommandResponse>(`${this.baseURL}/session/${sessionID}/command`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
timeout: 0,
|
||||
})
|
||||
}
|
||||
|
||||
async sendShell(sessionID: string, data: ShellRequest) {
|
||||
return fetchWrapper(`${this.baseURL}/session/${sessionID}/shell`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
async respondToPermission(permissionID: string, response: 'once' | 'always' | 'reject') {
|
||||
return fetchWrapper(`${this.baseURL}/permission/${permissionID}/reply`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reply: response }),
|
||||
})
|
||||
}
|
||||
|
||||
async listPendingPermissions() {
|
||||
return fetchWrapper<PermissionListResponse>(`${this.baseURL}/permission`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async replyToQuestion(requestID: string, answers: string[][]) {
|
||||
return fetchWrapper(`${this.baseURL}/question/${requestID}/reply`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ answers }),
|
||||
})
|
||||
}
|
||||
|
||||
async rejectQuestion(requestID: string) {
|
||||
return fetchWrapper(`${this.baseURL}/question/${requestID}/reject`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async listPendingQuestions() {
|
||||
return fetchWrapper<QuestionListResponse>(`${this.baseURL}/question`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async listAgents() {
|
||||
return fetchWrapper<AgentListResponse>(`${this.baseURL}/agent`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async revertMessage(sessionID: string, data: { messageID: string, partID?: string }) {
|
||||
return fetchWrapper(`${this.baseURL}/session/${sessionID}/revert`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
async unrevertSession(sessionID: string) {
|
||||
return fetchWrapper(`${this.baseURL}/session/${sessionID}/unrevert`, {
|
||||
method: 'POST',
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
async getSessionStatuses() {
|
||||
return fetchWrapper<Record<string, { type: 'idle' } | { type: 'busy' } | { type: 'retry'; attempt: number; message: string; next: number }>>(`${this.baseURL}/session/status`, {
|
||||
params: this.getParams(),
|
||||
})
|
||||
}
|
||||
|
||||
getEventSourceURL() {
|
||||
const base = this.baseURL.startsWith('http')
|
||||
? this.baseURL
|
||||
: `${window.location.origin}${this.baseURL}`
|
||||
const url = new URL(`${base}/event`)
|
||||
if (this.directory) {
|
||||
url.searchParams.set('directory', this.directory)
|
||||
}
|
||||
return url.toString()
|
||||
text: input.text,
|
||||
...(input.files ? { files: input.files } : {}),
|
||||
...(input.agents ? { agents: input.agents } : {}),
|
||||
...(input.skills ? { skills: input.skills } : {}),
|
||||
...(input.delivery ? { delivery: input.delivery } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export const createOpenCodeClient = (baseURL: string, directory?: string) => {
|
||||
return new OpenCodeClient(baseURL, directory)
|
||||
export async function listSessionPage(input: SessionPageInput): Promise<SessionPage> {
|
||||
const { data, cursor } = await callOpenCode((api) =>
|
||||
api.session.list({
|
||||
directory: input.directory,
|
||||
parentID: 'null',
|
||||
limit: input.limit,
|
||||
order: input.order,
|
||||
search: input.search,
|
||||
cursor: input.cursor,
|
||||
}),
|
||||
)
|
||||
return { items: data, nextCursor: cursor.next ?? undefined }
|
||||
}
|
||||
|
||||
export async function getSession(sessionID: string): Promise<SessionInfo> {
|
||||
return callOpenCode((api) => api.session.get({ sessionID }))
|
||||
}
|
||||
|
||||
export async function createSession(input: CreateSessionInput): Promise<SessionInfo> {
|
||||
const model = input.model ? parseOpenCodeModelRef(input.model) : undefined
|
||||
return callOpenCode((api) =>
|
||||
api.session.create({
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.agent !== undefined ? { agent: input.agent } : {}),
|
||||
...(model ? { model } : {}),
|
||||
location: { directory: input.directory },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export async function deleteSession(sessionID: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.remove({ sessionID }))
|
||||
}
|
||||
|
||||
export async function renameSession(sessionID: string, title: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.update({ sessionID, title }))
|
||||
}
|
||||
|
||||
export async function forkSession(sessionID: string, before?: string): Promise<SessionInfo> {
|
||||
return callOpenCode((api) =>
|
||||
api.session.fork({
|
||||
sessionID,
|
||||
...(before ? { before } : {}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export async function switchSessionModel(sessionID: string, model: ModelRef): Promise<void> {
|
||||
await callOpenCode((api) => api.session.switchModel({ sessionID, model }))
|
||||
}
|
||||
|
||||
export async function switchSessionAgent(sessionID: string, agent: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.switchAgent({ sessionID, agent }))
|
||||
}
|
||||
|
||||
export async function sendPrompt(input: SendPromptInput): Promise<SessionInboxUser> {
|
||||
return callOpenCode((api) =>
|
||||
api.session.prompt({
|
||||
sessionID: input.sessionID,
|
||||
...buildPromptFields(input),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export async function runCommand(input: RunCommandInput): Promise<void> {
|
||||
await callOpenCode((api) =>
|
||||
api.session.command({
|
||||
sessionID: input.sessionID,
|
||||
name: input.name,
|
||||
...buildPromptFields(input),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export async function runShell(sessionID: string, command: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.shell({ sessionID, command }))
|
||||
}
|
||||
|
||||
export async function interruptSession(sessionID: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.interrupt({ sessionID }))
|
||||
}
|
||||
|
||||
export async function stageRevert(sessionID: string, messageID: string): Promise<SessionRevert> {
|
||||
return callOpenCode((api) => api.session.revert.stage({ sessionID, messageID }))
|
||||
}
|
||||
|
||||
export async function commitRevert(sessionID: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.revert.commit({ sessionID }))
|
||||
}
|
||||
|
||||
export async function clearRevert(sessionID: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.revert.clear({ sessionID }))
|
||||
}
|
||||
|
||||
export async function compactSession(sessionID: string): Promise<SessionInboxCompaction> {
|
||||
return callOpenCode((api) => api.session.compact({ sessionID }))
|
||||
}
|
||||
|
||||
export async function activateSkill(sessionID: string, id: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.skill({ sessionID, id }))
|
||||
}
|
||||
|
||||
export async function listActiveSessions(): Promise<ActiveSessions> {
|
||||
return callOpenCode((api) => api.session.active())
|
||||
}
|
||||
|
||||
export async function listAgents(directory?: string): Promise<AgentInfo[]> {
|
||||
const { data } = await callOpenCode((api) => api.agent.list(openCodeLocation(directory)))
|
||||
return data
|
||||
}
|
||||
|
||||
export async function listCommands(directory?: string): Promise<CommandInfo[]> {
|
||||
const { data } = await callOpenCode((api) => api.command.list(openCodeLocation(directory)))
|
||||
return data
|
||||
}
|
||||
|
||||
export async function listPendingPermissions(directory: string): Promise<PermissionRequest[]> {
|
||||
const { data } = await callOpenCode((api) => api.permission.request.list(openCodeLocation(directory)))
|
||||
return data
|
||||
}
|
||||
|
||||
export async function replyPermission(
|
||||
sessionID: string,
|
||||
requestID: string,
|
||||
decision: 'once' | 'always' | 'reject',
|
||||
message?: string,
|
||||
): Promise<void> {
|
||||
await callOpenCode((api) =>
|
||||
api.permission.reply({
|
||||
sessionID,
|
||||
requestID,
|
||||
decision,
|
||||
...(message ? { message } : {}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export async function listPendingForms(directory: string): Promise<FormInfo[]> {
|
||||
const { data } = await callOpenCode((api) => api.form.list(openCodeLocation(directory)))
|
||||
return data
|
||||
}
|
||||
|
||||
export async function replyForm(sessionID: string, formID: string, answer: FormAnswer): Promise<void> {
|
||||
await callOpenCode((api) => api.session.form.reply({ sessionID, formID, answer }))
|
||||
}
|
||||
|
||||
export async function cancelForm(sessionID: string, formID: string): Promise<void> {
|
||||
await callOpenCode((api) => api.session.form.cancel({ sessionID, formID }))
|
||||
}
|
||||
|
||||
export async function findFiles(input: FindFilesInput): Promise<string[]> {
|
||||
const { data } = await callOpenCode((api) =>
|
||||
api.file.find({
|
||||
...openCodeLocation(input.directory),
|
||||
query: input.query,
|
||||
type: 'file',
|
||||
limit: input.limit,
|
||||
}),
|
||||
)
|
||||
return data.map((entry) => entry.path)
|
||||
}
|
||||
|
||||
export async function listSessionMessages(
|
||||
sessionID: string,
|
||||
input: SessionMessagesInput = {},
|
||||
): Promise<SessionMessagesPage> {
|
||||
const { data, cursor } = await callOpenCode((api) =>
|
||||
api.message.list({
|
||||
sessionID,
|
||||
...(input.limit === undefined ? {} : { limit: input.limit }),
|
||||
...(input.cursor === undefined ? { order: 'desc' as const } : { cursor: input.cursor }),
|
||||
}),
|
||||
)
|
||||
return { messages: [...data].reverse(), nextCursor: cursor.next ?? undefined }
|
||||
}
|
||||
|
||||
export async function readSessionSnapshot(sessionID: string): Promise<SessionSnapshot> {
|
||||
const [page, pending, active] = await Promise.all([
|
||||
listSessionMessages(sessionID),
|
||||
callOpenCode((api) => api.session.inbox.list({ sessionID })),
|
||||
listActiveSessions(),
|
||||
])
|
||||
return {
|
||||
messages: page.messages,
|
||||
nextCursor: page.nextCursor,
|
||||
pending,
|
||||
status: active[sessionID] ? 'busy' : 'idle',
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ClientError, createOpenCodeApi, openCodeErrorStatus, type OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
|
||||
const openCodeApi = createOpenCodeApi({
|
||||
baseUrl: new URL(OPENCODE_API_ENDPOINT, window.location.origin).toString(),
|
||||
fetch: (input, init) => fetch(input, { ...init, credentials: 'include' }),
|
||||
})
|
||||
|
||||
function toFetchError(error: unknown): FetchError {
|
||||
if (error instanceof FetchError) {
|
||||
return error
|
||||
}
|
||||
|
||||
if (error instanceof ClientError) {
|
||||
const status = (error.cause as { status?: number } | undefined)?.status
|
||||
return new FetchError(error.message, status, error.reason)
|
||||
}
|
||||
|
||||
const status = openCodeErrorStatus(error)
|
||||
if (error instanceof Error) {
|
||||
return new FetchError(error.message, status ?? 0, error.name)
|
||||
}
|
||||
|
||||
return new FetchError('Request failed', status ?? 0)
|
||||
}
|
||||
|
||||
export async function callOpenCode<T>(operation: (api: OpenCodeApi) => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await operation(openCodeApi)
|
||||
} catch (error) {
|
||||
throw toFetchError(error)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { getProvidersWithModels } from './providers'
|
||||
import { getOpenCodeConfigModel, getProviders, getProvidersWithModels, providerCredentialsApi } from './providers'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const { mockGetOpenCodeConfig, mockFetchWrapper } = vi.hoisted(() => ({
|
||||
const { mockGetOpenCodeConfig, mockFetchWrapper, mockProviderList, mockModelList, mockConfigGet } = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
mockFetchWrapper: vi.fn(),
|
||||
mockProviderList: vi.fn(),
|
||||
mockModelList: vi.fn(),
|
||||
mockConfigGet: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./settings', () => ({
|
||||
@@ -17,6 +21,15 @@ vi.mock('./fetchWrapper', () => ({
|
||||
fetchWrapper: mockFetchWrapper,
|
||||
}))
|
||||
|
||||
vi.mock('./opencodeApi', () => ({
|
||||
callOpenCode: (operation: (api: unknown) => Promise<unknown>) =>
|
||||
operation({
|
||||
provider: { list: mockProviderList },
|
||||
model: { list: mockModelList },
|
||||
config: { get: mockConfigGet },
|
||||
}),
|
||||
}))
|
||||
|
||||
const config = makeOpenCodeConfigFile({
|
||||
content: {
|
||||
provider: {
|
||||
@@ -30,10 +43,166 @@ const config = makeOpenCodeConfigFile({
|
||||
},
|
||||
})
|
||||
|
||||
function makeAnthropicModel(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'claude-sonnet-4',
|
||||
modelID: 'claude-sonnet-4-20250514',
|
||||
providerID: 'anthropic',
|
||||
name: 'Claude Sonnet 4',
|
||||
capabilities: { tools: true, input: ['text', 'image'], output: ['text'] },
|
||||
variants: [{ id: 'thinking', settings: { reasoning: 'high' } }],
|
||||
time: { released: Date.UTC(2025, 4, 22) },
|
||||
cost: [{ input: 3, output: 15, cache: { read: 0.3, write: 3.75 } }],
|
||||
status: 'active',
|
||||
enabled: true,
|
||||
limit: { context: 200000, output: 64000 },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('getProviders', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockProviderList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
|
||||
mockModelList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
|
||||
})
|
||||
|
||||
it('maps V2 providers and models into the UI shape', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{ id: 'anthropic', name: 'Anthropic', activation: 'enabled', package: '@opencode/ai/providers/anthropic' },
|
||||
],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{
|
||||
id: 'claude-sonnet-4',
|
||||
modelID: 'claude-sonnet-4-20250514',
|
||||
providerID: 'anthropic',
|
||||
name: 'Claude Sonnet 4',
|
||||
capabilities: { tools: true, input: ['text', 'image'], output: ['text'] },
|
||||
variants: [{ id: 'thinking', settings: { reasoning: 'high' } }],
|
||||
time: { released: Date.UTC(2025, 4, 22) },
|
||||
cost: [{ input: 3, output: 15, cache: { read: 0.3, write: 3.75 } }],
|
||||
status: 'active',
|
||||
enabled: true,
|
||||
limit: { context: 200000, output: 64000 },
|
||||
},
|
||||
{
|
||||
id: 'claude-legacy',
|
||||
modelID: 'claude-legacy',
|
||||
providerID: 'anthropic',
|
||||
name: 'Claude Legacy',
|
||||
capabilities: { tools: false, input: ['text'], output: ['text'] },
|
||||
variants: [],
|
||||
time: { released: 0 },
|
||||
cost: [],
|
||||
status: 'deprecated',
|
||||
enabled: true,
|
||||
limit: { context: 1, output: 1 },
|
||||
},
|
||||
],
|
||||
})
|
||||
const result = await getProviders('/repo')
|
||||
|
||||
expect(result.connected).toEqual(['anthropic'])
|
||||
expect(result.providers).toHaveLength(1)
|
||||
expect(result.providers[0].models['claude-sonnet-4']).toMatchObject({
|
||||
key: 'claude-sonnet-4',
|
||||
id: 'claude-sonnet-4-20250514',
|
||||
name: 'Claude Sonnet 4',
|
||||
limit: { context: 200000, output: 64000 },
|
||||
variants: { thinking: { reasoning: 'high' } },
|
||||
})
|
||||
expect(result.providers[0].models['claude-legacy']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('excludes disabled models and disabled providers from the picker', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' },
|
||||
{ id: 'disabled-provider', name: 'Disabled', activation: 'disabled' },
|
||||
],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
makeAnthropicModel(),
|
||||
makeAnthropicModel({ id: 'claude-disabled', modelID: 'claude-disabled', enabled: false }),
|
||||
makeAnthropicModel({ id: 'claude-off-provider', modelID: 'claude-off-provider', providerID: 'disabled-provider' }),
|
||||
],
|
||||
})
|
||||
|
||||
const result = await getProviders('/repo')
|
||||
|
||||
expect(result.connected).toEqual(['anthropic'])
|
||||
expect(result.providers.map((provider) => provider.id)).toEqual(['anthropic'])
|
||||
expect(Object.keys(result.providers[0].models)).toEqual(['claude-sonnet-4'])
|
||||
})
|
||||
|
||||
it('degrades to an empty result when the upstream call fails', async () => {
|
||||
mockProviderList.mockRejectedValue(new Error('upstream down'))
|
||||
|
||||
await expect(getProviders('/repo')).resolves.toEqual({
|
||||
providers: [],
|
||||
connected: [],
|
||||
models: [],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getOpenCodeConfigModel', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('reads a string config model for the directory', async () => {
|
||||
mockConfigGet.mockResolvedValue([{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } }])
|
||||
|
||||
await expect(getOpenCodeConfigModel('/repo')).resolves.toBe('anthropic/claude-sonnet-4')
|
||||
expect(mockConfigGet).toHaveBeenCalledWith({ location: { directory: '/repo' } })
|
||||
})
|
||||
|
||||
it('formats an object config model as provider/model', async () => {
|
||||
mockConfigGet.mockResolvedValue([
|
||||
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } } },
|
||||
])
|
||||
|
||||
await expect(getOpenCodeConfigModel()).resolves.toBe('openai/gpt-4o')
|
||||
expect(mockConfigGet).toHaveBeenCalledWith(undefined)
|
||||
})
|
||||
|
||||
it('uses the last document that sets a model', async () => {
|
||||
mockConfigGet.mockResolvedValue([
|
||||
{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } },
|
||||
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o' } } },
|
||||
{ type: 'document', info: {} },
|
||||
])
|
||||
|
||||
await expect(getOpenCodeConfigModel('/repo')).resolves.toBe('openai/gpt-4o')
|
||||
})
|
||||
|
||||
it('returns null when no document sets a model', async () => {
|
||||
mockConfigGet.mockResolvedValue([{ type: 'document', info: {} }])
|
||||
|
||||
await expect(getOpenCodeConfigModel('/repo')).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the config read fails', async () => {
|
||||
mockConfigGet.mockRejectedValue(new Error('upstream down'))
|
||||
|
||||
await expect(getOpenCodeConfigModel('/repo')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getProvidersWithModels', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockFetchWrapper.mockResolvedValue({ all: [], connected: [], default: {} })
|
||||
mockProviderList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
|
||||
mockModelList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
|
||||
})
|
||||
|
||||
it('uses the supplied config instead of re-reading it', async () => {
|
||||
@@ -59,4 +228,160 @@ describe('getProvidersWithModels', () => {
|
||||
|
||||
expect(providers).toEqual([])
|
||||
})
|
||||
|
||||
it('merges configured providers from both provider and providers keys', async () => {
|
||||
const configWithProviders = makeOpenCodeConfigFile({
|
||||
content: {
|
||||
provider: {
|
||||
openai: { name: 'OpenAI', models: { 'gpt-4o': { name: 'GPT-4o' } } },
|
||||
},
|
||||
providers: {
|
||||
anthropic: { name: 'Anthropic', models: { 'claude-sonnet-4': { name: 'Claude Sonnet 4' } } },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const providers = await getProvidersWithModels(undefined, configWithProviders)
|
||||
|
||||
expect(providers.map((provider) => provider.id).sort()).toEqual(['anthropic', 'openai'])
|
||||
})
|
||||
|
||||
it('retains the resolved model catalog for a settings-only provider override', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
makeAnthropicModel(),
|
||||
makeAnthropicModel({
|
||||
id: 'claude-opus-4',
|
||||
modelID: 'claude-opus-4-20250514',
|
||||
name: 'Claude Opus 4',
|
||||
}),
|
||||
],
|
||||
})
|
||||
const configWithSettings = makeOpenCodeConfigFile({
|
||||
content: { providers: { anthropic: { settings: { apiKey: 'test' } } } },
|
||||
})
|
||||
|
||||
const providers = await getProvidersWithModels(undefined, configWithSettings)
|
||||
|
||||
const anthropic = providers.find((provider) => provider.id === 'anthropic')
|
||||
expect(anthropic?.source).toBe('configured')
|
||||
expect(anthropic?.models.map((model) => model.key).sort()).toEqual(['claude-opus-4', 'claude-sonnet-4'])
|
||||
})
|
||||
|
||||
it('retains every resolved model and its metadata when a partial model override exists', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
makeAnthropicModel(),
|
||||
makeAnthropicModel({
|
||||
id: 'claude-opus-4',
|
||||
modelID: 'claude-opus-4-20250514',
|
||||
name: 'Claude Opus 4',
|
||||
}),
|
||||
],
|
||||
})
|
||||
const configWithOverride = makeOpenCodeConfigFile({
|
||||
content: { providers: { anthropic: { models: { 'claude-sonnet-4': { limit: { context: 1 } } } } } },
|
||||
})
|
||||
|
||||
const providers = await getProvidersWithModels(undefined, configWithOverride)
|
||||
|
||||
const anthropic = providers.find((provider) => provider.id === 'anthropic')
|
||||
expect(anthropic?.models.map((model) => model.key).sort()).toEqual(['claude-opus-4', 'claude-sonnet-4'])
|
||||
const sonnet = anthropic?.models.find((model) => model.key === 'claude-sonnet-4')
|
||||
expect(sonnet?.limit).toEqual({ context: 200000, output: 64000 })
|
||||
expect(sonnet?.variants).toEqual({ thinking: { reasoning: 'high' } })
|
||||
})
|
||||
|
||||
it('appends config-only model entries that the resolved catalog omits', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [makeAnthropicModel()],
|
||||
})
|
||||
const configWithExtraModel = makeOpenCodeConfigFile({
|
||||
content: { providers: { anthropic: { models: { 'claude-custom': { name: 'Claude Custom' } } } } },
|
||||
})
|
||||
|
||||
const providers = await getProvidersWithModels(undefined, configWithExtraModel)
|
||||
|
||||
const anthropic = providers.find((provider) => provider.id === 'anthropic')
|
||||
expect(anthropic?.models.map((model) => model.key).sort()).toEqual(['claude-custom', 'claude-sonnet-4'])
|
||||
expect(anthropic?.models.find((model) => model.key === 'claude-custom')?.name).toBe('Claude Custom')
|
||||
})
|
||||
})
|
||||
|
||||
describe('providerCredentialsApi', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('lists provider ids with credentials from the Manager response', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ providers: ['anthropic', 'openai'] })
|
||||
|
||||
await expect(providerCredentialsApi.list()).resolves.toEqual(['anthropic', 'openai'])
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/credentials`)
|
||||
})
|
||||
|
||||
it('reports credential status from the Manager response', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ hasCredentials: true })
|
||||
|
||||
await expect(providerCredentialsApi.getStatus('anthropic')).resolves.toBe(true)
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/anthropic/credentials/status`
|
||||
)
|
||||
})
|
||||
|
||||
it('posts the api key to the provider credential route', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ success: true })
|
||||
|
||||
await providerCredentialsApi.set('anthropic', 'sk-ant-test')
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/anthropic/credentials`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ apiKey: 'sk-ant-test' }),
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('posts the key method form answer alongside the api key', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ success: true })
|
||||
|
||||
await providerCredentialsApi.set('azure', 'az-test', { resourceName: 'my-models' })
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/azure/credentials`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ apiKey: 'az-test', answer: { resourceName: 'my-models' } }),
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('deletes credentials through the provider credential route', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ success: true })
|
||||
|
||||
await providerCredentialsApi.delete('anthropic')
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/anthropic/credentials`,
|
||||
{ method: 'DELETE' }
|
||||
)
|
||||
})
|
||||
})
|
||||
+106
-184
@@ -1,95 +1,21 @@
|
||||
import { API_BASE_URL } from "@/config";
|
||||
import { settingsApi } from "./settings";
|
||||
import { fetchWrapper } from "./fetchWrapper";
|
||||
import { callOpenCode } from "./opencodeApi";
|
||||
import { openCodeLocation, type ConfigEntry, type FormAnswer, type ModelInfo } from "@opencode-manager/shared/opencode";
|
||||
import type { CredentialListResponse, CredentialStatusResponse } from "@opencode-manager/shared/schemas";
|
||||
import type { OpenCodeConfigFile } from "./types/settings";
|
||||
|
||||
export type ProviderSource = "configured" | "local" | "builtin";
|
||||
|
||||
export interface OpenCodeModel {
|
||||
id: string;
|
||||
providerID: string;
|
||||
name: string;
|
||||
api: {
|
||||
id: string;
|
||||
url?: string;
|
||||
npm: string;
|
||||
};
|
||||
status: "active" | "deprecated";
|
||||
headers: Record<string, string>;
|
||||
options: Record<string, unknown>;
|
||||
cost: {
|
||||
input: number;
|
||||
output: number;
|
||||
cache?: {
|
||||
read: number;
|
||||
write: number;
|
||||
};
|
||||
};
|
||||
limit: {
|
||||
context: number;
|
||||
output: number;
|
||||
};
|
||||
capabilities: {
|
||||
temperature: boolean;
|
||||
reasoning: boolean;
|
||||
attachment: boolean;
|
||||
toolcall: boolean;
|
||||
input: {
|
||||
text: boolean;
|
||||
audio: boolean;
|
||||
image: boolean;
|
||||
video: boolean;
|
||||
pdf: boolean;
|
||||
};
|
||||
output: {
|
||||
text: boolean;
|
||||
audio: boolean;
|
||||
image: boolean;
|
||||
video: boolean;
|
||||
pdf: boolean;
|
||||
};
|
||||
};
|
||||
variants?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export interface OpenCodeProvider {
|
||||
id: string;
|
||||
source: "custom" | "builtin";
|
||||
name: string;
|
||||
env: string[];
|
||||
options: Record<string, unknown>;
|
||||
models: Record<string, OpenCodeModel>;
|
||||
}
|
||||
|
||||
export interface Model {
|
||||
id: string;
|
||||
key?: string;
|
||||
name: string;
|
||||
release_date?: string;
|
||||
attachment?: boolean;
|
||||
reasoning?: boolean;
|
||||
temperature?: boolean;
|
||||
tool_call?: boolean;
|
||||
cost?: {
|
||||
input: number;
|
||||
output: number;
|
||||
cache_read?: number;
|
||||
cache_write?: number;
|
||||
};
|
||||
limit?: {
|
||||
context: number;
|
||||
output: number;
|
||||
};
|
||||
modalities?: {
|
||||
input: ("text" | "audio" | "image" | "video" | "pdf")[];
|
||||
output: ("text" | "audio" | "image" | "video" | "pdf")[];
|
||||
};
|
||||
experimental?: boolean;
|
||||
status?: "alpha" | "beta";
|
||||
options?: Record<string, unknown>;
|
||||
provider?: {
|
||||
npm: string;
|
||||
};
|
||||
variants?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
@@ -97,11 +23,8 @@ export interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
api?: string;
|
||||
env: string[];
|
||||
npm?: string;
|
||||
models: Record<string, Model>;
|
||||
options?: Record<string, unknown>;
|
||||
source?: ProviderSource;
|
||||
isConnected?: boolean;
|
||||
}
|
||||
|
||||
@@ -109,7 +32,6 @@ export interface ProviderWithModels {
|
||||
id: string;
|
||||
name: string;
|
||||
api?: string;
|
||||
env: string[];
|
||||
npm?: string;
|
||||
models: Model[];
|
||||
source: ProviderSource;
|
||||
@@ -156,86 +78,73 @@ function classifyProviderSource(providerId: string, isFromConfig: boolean): Prov
|
||||
return "configured";
|
||||
}
|
||||
|
||||
|
||||
interface OpenCodeProviderResponse {
|
||||
all: OpenCodeProvider[];
|
||||
connected: string[];
|
||||
default: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface ProvidersResult {
|
||||
providers: Provider[];
|
||||
connected: string[];
|
||||
default: Record<string, string>;
|
||||
models: ModelInfo[];
|
||||
}
|
||||
|
||||
async function getProvidersFromOpenCodeServer(directory?: string): Promise<ProvidersResult> {
|
||||
try {
|
||||
const response = await fetchWrapper<OpenCodeProviderResponse>(`${API_BASE_URL}/api/opencode/provider`, {
|
||||
params: { directory },
|
||||
});
|
||||
|
||||
if (response?.all && Array.isArray(response.all)) {
|
||||
const connectedSet = new Set(response.connected || []);
|
||||
|
||||
const providers = response.all.map((openCodeProvider: OpenCodeProvider) => {
|
||||
const models: Record<string, Model> = {};
|
||||
|
||||
Object.entries(openCodeProvider.models).forEach(([modelId, openCodeModel]) => {
|
||||
models[modelId] = {
|
||||
id: openCodeModel.api.id || modelId,
|
||||
key: modelId,
|
||||
name: openCodeModel.name,
|
||||
attachment: openCodeModel.capabilities.attachment,
|
||||
reasoning: openCodeModel.capabilities.reasoning,
|
||||
temperature: openCodeModel.capabilities.temperature,
|
||||
tool_call: openCodeModel.capabilities.toolcall,
|
||||
cost: {
|
||||
input: openCodeModel.cost.input,
|
||||
output: openCodeModel.cost.output,
|
||||
cache_read: openCodeModel.cost.cache?.read ?? 0,
|
||||
cache_write: openCodeModel.cost.cache?.write ?? 0,
|
||||
},
|
||||
limit: {
|
||||
context: openCodeModel.limit.context,
|
||||
output: openCodeModel.limit.output,
|
||||
},
|
||||
modalities: {
|
||||
input: Object.keys(openCodeModel.capabilities.input).filter(
|
||||
(key) => openCodeModel.capabilities.input[key as keyof typeof openCodeModel.capabilities.input]
|
||||
) as ("text" | "audio" | "image" | "video" | "pdf")[],
|
||||
output: Object.keys(openCodeModel.capabilities.output).filter(
|
||||
(key) => openCodeModel.capabilities.output[key as keyof typeof openCodeModel.capabilities.output]
|
||||
) as ("text" | "audio" | "image" | "video" | "pdf")[],
|
||||
},
|
||||
provider: {
|
||||
npm: openCodeModel.api.npm,
|
||||
},
|
||||
variants: openCodeModel.variants,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
id: openCodeProvider.id,
|
||||
name: openCodeProvider.name,
|
||||
env: openCodeProvider.env,
|
||||
models,
|
||||
options: openCodeProvider.options,
|
||||
isConnected: connectedSet.has(openCodeProvider.id),
|
||||
};
|
||||
});
|
||||
|
||||
return { providers, connected: response.connected || [], default: response.default || {} };
|
||||
}
|
||||
} catch {
|
||||
// Silently return empty providers on failure - graceful degradation
|
||||
}
|
||||
|
||||
return { providers: [], connected: [], default: {} };
|
||||
function mapModelInfo(model: ModelInfo): Model {
|
||||
return {
|
||||
id: model.modelID,
|
||||
key: model.id,
|
||||
name: model.name,
|
||||
limit: {
|
||||
context: model.limit.context,
|
||||
output: model.limit.output,
|
||||
},
|
||||
variants: Object.fromEntries(model.variants.map((variant) => [variant.id, variant.settings ?? {}])),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getProviders(directory?: string): Promise<ProvidersResult> {
|
||||
return await getProvidersFromOpenCodeServer(directory);
|
||||
try {
|
||||
const location = openCodeLocation(directory);
|
||||
const [providerResult, modelResult] = await callOpenCode((api) =>
|
||||
Promise.all([api.provider.list(location), api.model.list(location)]),
|
||||
);
|
||||
|
||||
const activeProviders = providerResult.data.filter((provider) => provider.activation !== "disabled");
|
||||
const connected = activeProviders.map((provider) => provider.id);
|
||||
const connectedSet = new Set(connected);
|
||||
|
||||
const providers = activeProviders.map((provider) => {
|
||||
const models: Record<string, Model> = {};
|
||||
for (const model of modelResult.data) {
|
||||
if (model.providerID !== provider.id || model.status === "deprecated" || !model.enabled) continue;
|
||||
models[model.id] = mapModelInfo(model);
|
||||
}
|
||||
return {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
models,
|
||||
isConnected: connectedSet.has(provider.id),
|
||||
};
|
||||
});
|
||||
|
||||
return { providers, connected, models: modelResult.data };
|
||||
} catch {
|
||||
return { providers: [], connected: [], models: [] };
|
||||
}
|
||||
}
|
||||
|
||||
type ConfigDocumentModel = Extract<ConfigEntry, { type: "document" }>["info"]["model"];
|
||||
|
||||
function formatConfigModel(model: NonNullable<ConfigDocumentModel>): string {
|
||||
return typeof model === "string" ? model : `${model.providerID}/${model.model}`;
|
||||
}
|
||||
|
||||
export async function getOpenCodeConfigModel(directory?: string): Promise<string | null> {
|
||||
try {
|
||||
const entries = await callOpenCode((api) => api.config.get(openCodeLocation(directory)));
|
||||
const model = entries.reduce<ConfigDocumentModel>(
|
||||
(current, entry) => (entry.type === "document" && entry.info.model ? entry.info.model : current),
|
||||
undefined,
|
||||
);
|
||||
return model ? formatConfigModel(model) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getOpenCodeModelState(): Promise<OpenCodeModelState> {
|
||||
@@ -269,12 +178,15 @@ export async function toggleOpenCodeFavoriteModel(model: ModelSelection): Promis
|
||||
async function getConfiguredProviders(connectedIds: Set<string>, config?: OpenCodeConfigFile): Promise<ProviderWithModels[]> {
|
||||
try {
|
||||
const resolvedConfig = config ?? await settingsApi.getOpenCodeConfig();
|
||||
if (!resolvedConfig.content.provider) return [];
|
||||
const configured = {
|
||||
...(resolvedConfig.content.providers as Record<string, ConfigProvider> | undefined),
|
||||
...(resolvedConfig.content.provider as Record<string, ConfigProvider> | undefined),
|
||||
};
|
||||
if (Object.keys(configured).length === 0) return [];
|
||||
|
||||
const configProviders = resolvedConfig.content.provider as Record<string, ConfigProvider>;
|
||||
const result: ProviderWithModels[] = [];
|
||||
|
||||
for (const [providerId, providerConfig] of Object.entries(configProviders)) {
|
||||
for (const [providerId, providerConfig] of Object.entries(configured)) {
|
||||
if (!providerConfig || typeof providerConfig !== "object") continue;
|
||||
|
||||
const source = classifyProviderSource(providerId, true);
|
||||
@@ -300,7 +212,6 @@ async function getConfiguredProviders(connectedIds: Set<string>, config?: OpenCo
|
||||
id: providerId,
|
||||
name: providerConfig.name || providerId,
|
||||
api: providerConfig.api || providerConfig.options?.baseURL,
|
||||
env: [],
|
||||
npm: providerConfig.npm,
|
||||
models,
|
||||
source,
|
||||
@@ -316,34 +227,45 @@ async function getConfiguredProviders(connectedIds: Set<string>, config?: OpenCo
|
||||
}
|
||||
|
||||
export async function getProvidersWithModels(directory?: string, config?: OpenCodeConfigFile): Promise<ProviderWithModels[]> {
|
||||
const { providers: builtinProviders, connected } = await getProviders(directory);
|
||||
const { providers: resolvedProviders, connected } = await getProviders(directory);
|
||||
const connectedIds = new Set(connected);
|
||||
|
||||
const configuredProviders = await getConfiguredProviders(connectedIds, config);
|
||||
const configuredIds = new Set(configuredProviders.map((p) => p.id));
|
||||
const configuredById = new Map(configuredProviders.map((provider) => [provider.id, provider]));
|
||||
const resolvedIds = new Set(resolvedProviders.map((provider) => provider.id));
|
||||
|
||||
const builtinResult: ProviderWithModels[] = builtinProviders
|
||||
.filter((provider) => !configuredIds.has(provider.id))
|
||||
.map((provider) => {
|
||||
const models = Object.entries(provider.models || {}).map(([id, model]) => ({
|
||||
...model,
|
||||
id: model.id || id,
|
||||
key: id,
|
||||
name: model.name || id,
|
||||
}));
|
||||
return {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
api: provider.api,
|
||||
env: provider.env || [],
|
||||
npm: provider.npm,
|
||||
models,
|
||||
source: "builtin" as ProviderSource,
|
||||
isConnected: provider.isConnected ?? false,
|
||||
};
|
||||
});
|
||||
const mergedProviders: ProviderWithModels[] = resolvedProviders.map((provider) => {
|
||||
const configured = configuredById.get(provider.id);
|
||||
const resolvedModels = Object.entries(provider.models || {}).map(([id, model]) => ({
|
||||
...model,
|
||||
id: model.id || id,
|
||||
key: id,
|
||||
name: model.name || id,
|
||||
}));
|
||||
const resolvedModelIdentifiers = new Set(
|
||||
resolvedModels.flatMap((model) => [model.key, model.id]).filter((value): value is string => Boolean(value)),
|
||||
);
|
||||
const configuredOnlyModels = configured
|
||||
? configured.models.filter(
|
||||
(model) =>
|
||||
!resolvedModelIdentifiers.has(model.key ?? "") && !resolvedModelIdentifiers.has(model.id),
|
||||
)
|
||||
: [];
|
||||
|
||||
const allProviders = [...configuredProviders, ...builtinResult];
|
||||
return {
|
||||
id: provider.id,
|
||||
name: provider.name || configured?.name || provider.id,
|
||||
api: provider.api ?? configured?.api,
|
||||
npm: provider.npm ?? configured?.npm,
|
||||
models: [...resolvedModels, ...configuredOnlyModels],
|
||||
source: configured ? configured.source : "builtin",
|
||||
isConnected: provider.isConnected ?? false,
|
||||
};
|
||||
});
|
||||
|
||||
const configOnlyProviders = configuredProviders.filter((provider) => !resolvedIds.has(provider.id));
|
||||
|
||||
const allProviders = [...mergedProviders, ...configOnlyProviders];
|
||||
|
||||
allProviders.sort((a, b) => {
|
||||
if (a.isConnected !== b.isConnected) {
|
||||
@@ -379,22 +301,22 @@ export function formatProviderName(
|
||||
|
||||
export const providerCredentialsApi = {
|
||||
list: async (): Promise<string[]> => {
|
||||
const { providers } = await fetchWrapper<{ providers: string[] }>(`${API_BASE_URL}/api/providers/credentials`);
|
||||
const { providers } = await fetchWrapper<CredentialListResponse>(`${API_BASE_URL}/api/providers/credentials`);
|
||||
return providers;
|
||||
},
|
||||
|
||||
getStatus: async (providerId: string): Promise<boolean> => {
|
||||
const { hasCredentials } = await fetchWrapper<{ hasCredentials: boolean }>(
|
||||
const { hasCredentials } = await fetchWrapper<CredentialStatusResponse>(
|
||||
`${API_BASE_URL}/api/providers/${providerId}/credentials/status`
|
||||
);
|
||||
return hasCredentials;
|
||||
},
|
||||
|
||||
set: async (providerId: string, apiKey: string): Promise<void> => {
|
||||
set: async (providerId: string, apiKey: string, answer?: FormAnswer): Promise<void> => {
|
||||
await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ apiKey }),
|
||||
body: JSON.stringify({ apiKey, answer }),
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
@@ -40,41 +40,30 @@ export async function getRepo(id: number): Promise<Repo> {
|
||||
|
||||
export type RepoSibling = Repo & {
|
||||
currentBranch?: string
|
||||
workspaceId?: string
|
||||
workspaceType?: string
|
||||
workspaceName?: string
|
||||
worktreeStrategy?: string
|
||||
}
|
||||
|
||||
export function workspaceLabel(workspace: RepoSibling): string {
|
||||
return (
|
||||
workspace.currentBranch ||
|
||||
workspace.branch ||
|
||||
workspace.workspaceName ||
|
||||
workspace.workspaceId ||
|
||||
'workspace'
|
||||
)
|
||||
return workspace.currentBranch || workspace.branch || workspace.localPath || 'workspace'
|
||||
}
|
||||
|
||||
export interface RepoWorkspace {
|
||||
id: string
|
||||
type: string
|
||||
name?: string | null
|
||||
branch?: string | null
|
||||
directory?: string | null
|
||||
projectID?: string
|
||||
export interface RepoWorktree {
|
||||
directory: string
|
||||
}
|
||||
|
||||
export async function getRepoSiblings(id: number): Promise<RepoSibling[]> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/siblings`)
|
||||
}
|
||||
|
||||
export async function deleteRepoWorkspace(repoId: number, workspaceId: string): Promise<void> {
|
||||
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/workspaces/${workspaceId}`, {
|
||||
export async function deleteRepoWorkspace(repoId: number, directory: string): Promise<void> {
|
||||
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function createRepoWorkspace(repoId: number): Promise<RepoWorkspace> {
|
||||
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
@@ -13,9 +13,10 @@ import type {
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillResponse,
|
||||
OpenCodeDirectoryFileInfo,
|
||||
OpenCodeRestartResponse,
|
||||
} from './types/settings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
|
||||
const DEFAULT_USER_ID = 'default'
|
||||
|
||||
@@ -85,7 +86,7 @@ export const settingsApi = {
|
||||
})
|
||||
},
|
||||
|
||||
restartOpenCodeServer: async (): Promise<{ success: boolean; message: string; details?: string }> => {
|
||||
restartOpenCodeServer: async (): Promise<OpenCodeRestartResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-restart`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -96,23 +97,6 @@ export const settingsApi = {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-active-sessions`)
|
||||
},
|
||||
|
||||
reloadOpenCodeConfig: async (): Promise<{ success: boolean; message: string; details?: string }> => {
|
||||
try {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-reload`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof FetchError && error.statusCode === 404) {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-restart`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
throw error
|
||||
}
|
||||
},
|
||||
|
||||
rollbackOpenCodeConfig: async (): Promise<{ success: boolean; message: string; fallback?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-rollback`, {
|
||||
method: 'POST',
|
||||
@@ -190,7 +174,7 @@ export const settingsApi = {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md/default`)
|
||||
},
|
||||
|
||||
updateAgentsMd: async (content: string): Promise<{ success: boolean }> => {
|
||||
updateAgentsMd: async (content: string): Promise<{ success: boolean; restartRequired?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -333,7 +317,7 @@ export interface VersionInfo {
|
||||
|
||||
export interface OpenCodeServerAuthStatus {
|
||||
isSet: boolean
|
||||
source: 'db' | 'env' | 'none'
|
||||
source: 'db' | 'env' | 'managed'
|
||||
}
|
||||
|
||||
export async function getOpenCodeServerAuth(): Promise<OpenCodeServerAuthStatus> {
|
||||
|
||||
+2
-234
@@ -17,243 +17,11 @@ export interface Repo {
|
||||
isLocal?: boolean
|
||||
}
|
||||
|
||||
import type { components } from './opencode-types'
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export type Message = components['schemas']['Message']
|
||||
export type Part = components['schemas']['Part']
|
||||
export type Session = components['schemas']['Session']
|
||||
export type PermissionRequest = components['schemas']['PermissionRequest']
|
||||
export type Session = SessionInfo
|
||||
export type PermissionResponse = 'once' | 'always' | 'reject'
|
||||
|
||||
export type QuestionOption = components['schemas']['QuestionOption']
|
||||
export type QuestionInfo = components['schemas']['QuestionInfo']
|
||||
export type QuestionRequest = components['schemas']['QuestionRequest']
|
||||
export type QuestionAnswer = components['schemas']['QuestionAnswer']
|
||||
|
||||
export type MessageWithParts = {
|
||||
info: Message
|
||||
parts: Part[]
|
||||
}
|
||||
|
||||
export type MessageListResponse = MessageWithParts[]
|
||||
|
||||
export interface SSEMessagePartUpdatedEvent {
|
||||
type: 'message.part.updated' | 'messagev2.part.updated'
|
||||
properties: {
|
||||
part: Part
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEMessagePartDeltaEvent {
|
||||
type: 'message.part.delta'
|
||||
properties: {
|
||||
sessionID: string
|
||||
messageID: string
|
||||
partID: string
|
||||
field: string
|
||||
delta: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEMessageUpdatedEvent {
|
||||
type: 'message.updated' | 'messagev2.updated'
|
||||
properties: {
|
||||
info: Message
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEMessageRemovedEvent {
|
||||
type: 'message.removed' | 'messagev2.removed'
|
||||
properties: {
|
||||
sessionID: string
|
||||
messageID: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEMessagePartRemovedEvent {
|
||||
type: 'message.part.removed' | 'messagev2.part.removed'
|
||||
properties: {
|
||||
sessionID: string
|
||||
messageID: string
|
||||
partID: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionUpdatedEvent {
|
||||
type: 'session.updated'
|
||||
properties: {
|
||||
info: Session
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionCreatedEvent {
|
||||
type: 'session.created'
|
||||
properties: {
|
||||
sessionID: string
|
||||
info: Session
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionDeletedEvent {
|
||||
type: 'session.deleted'
|
||||
properties: {
|
||||
sessionID: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionCompactedEvent {
|
||||
type: 'session.compacted'
|
||||
properties: {
|
||||
sessionID: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSETodoUpdatedEvent {
|
||||
type: 'todo.updated'
|
||||
properties: {
|
||||
sessionID: string
|
||||
todos: components['schemas']['Todo'][]
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEPermissionAskedEvent {
|
||||
type: 'permission.asked'
|
||||
properties: PermissionRequest
|
||||
directory?: string
|
||||
}
|
||||
|
||||
export interface SSEPermissionRepliedEvent {
|
||||
type: 'permission.replied'
|
||||
properties: {
|
||||
sessionID: string
|
||||
permissionID: string
|
||||
response: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEQuestionAskedEvent {
|
||||
type: 'question.asked'
|
||||
properties: QuestionRequest
|
||||
directory?: string
|
||||
}
|
||||
|
||||
export interface SSEQuestionRepliedEvent {
|
||||
type: 'question.replied'
|
||||
properties: {
|
||||
sessionID: string
|
||||
requestID: string
|
||||
answers: QuestionAnswer[]
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEQuestionRejectedEvent {
|
||||
type: 'question.rejected'
|
||||
properties: {
|
||||
sessionID: string
|
||||
requestID: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEInstallationUpdatedEvent {
|
||||
type: 'installation.updated'
|
||||
properties: {
|
||||
version: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSEInstallationUpdateAvailableEvent {
|
||||
type: 'installation.update-available'
|
||||
properties: {
|
||||
version: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionIdleEvent {
|
||||
type: 'session.idle'
|
||||
properties: {
|
||||
sessionID: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionStatusEvent {
|
||||
type: 'session.status'
|
||||
properties: {
|
||||
sessionID: string
|
||||
status: {
|
||||
type: 'idle'
|
||||
} | {
|
||||
type: 'busy'
|
||||
} | {
|
||||
type: 'compact'
|
||||
} | {
|
||||
type: 'retry'
|
||||
attempt: number
|
||||
message: string
|
||||
next: number
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionErrorEvent {
|
||||
type: 'session.error'
|
||||
properties: {
|
||||
sessionID?: string
|
||||
error?: components['schemas']['ProviderAuthError']
|
||||
| components['schemas']['UnknownError']
|
||||
| components['schemas']['MessageOutputLengthError']
|
||||
| components['schemas']['MessageAbortedError']
|
||||
| components['schemas']['APIError']
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSELspUpdatedEvent {
|
||||
type: 'lsp.updated'
|
||||
properties: Record<string, never>
|
||||
}
|
||||
|
||||
export interface SSEVcsBranchUpdatedEvent {
|
||||
type: 'vcs.branch.updated'
|
||||
directory?: string
|
||||
properties: {
|
||||
branch?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESSHHostKeyRequestEvent {
|
||||
type: 'ssh.host-key-request'
|
||||
properties: SSHHostKeyRequest
|
||||
}
|
||||
|
||||
export type SSEEvent =
|
||||
| SSEMessagePartUpdatedEvent
|
||||
| SSEMessagePartDeltaEvent
|
||||
| SSEMessageUpdatedEvent
|
||||
| SSEMessageRemovedEvent
|
||||
| SSEMessagePartRemovedEvent
|
||||
| SSESessionCreatedEvent
|
||||
| SSESessionUpdatedEvent
|
||||
| SSESessionDeletedEvent
|
||||
| SSESessionCompactedEvent
|
||||
| SSESessionIdleEvent
|
||||
| SSESessionStatusEvent
|
||||
| SSESessionErrorEvent
|
||||
| SSETodoUpdatedEvent
|
||||
| SSEPermissionAskedEvent
|
||||
| SSEPermissionRepliedEvent
|
||||
| SSEQuestionAskedEvent
|
||||
| SSEQuestionRepliedEvent
|
||||
| SSEQuestionRejectedEvent
|
||||
| SSEInstallationUpdatedEvent
|
||||
| SSEInstallationUpdateAvailableEvent
|
||||
| SSELspUpdatedEvent
|
||||
| SSEVcsBranchUpdatedEvent
|
||||
| SSESSHHostKeyRequestEvent
|
||||
|
||||
export type ContentPart =
|
||||
| { type: 'text', content: string }
|
||||
| { type: 'file', path: string, name: string }
|
||||
| { type: 'image', id: string, filename: string, mime: string, dataUrl: string }
|
||||
|
||||
export interface FileAttachmentInfo {
|
||||
path: string
|
||||
name: string
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
DEFAULT_USER_PREFERENCES,
|
||||
DEFAULT_LEADER_KEY,
|
||||
BLOCKED_SERVER_ENV_KEYS,
|
||||
DEFAULT_SERVER_ENV_VARS,
|
||||
selectPreferredOpenCodeConfigSourceName,
|
||||
type TTSConfig,
|
||||
type STTConfig,
|
||||
@@ -27,7 +26,7 @@ import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
import { saveFile } from '@/lib/download'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS }
|
||||
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
|
||||
|
||||
export function getOpenCodeConfigSources(config: OpenCodeConfigFile): OpenCodeConfigSourceFile[] {
|
||||
@@ -91,7 +90,6 @@ export interface UserPreferences {
|
||||
repoOrder?: number[]
|
||||
repoSortMode?: 'recent' | 'manual' | 'name'
|
||||
serverEnvVars?: Array<{ key: string; value: string }>
|
||||
disabledDefaultServerEnvVars?: string[]
|
||||
sandbox?: SandboxPreferences
|
||||
}
|
||||
|
||||
@@ -109,6 +107,11 @@ export interface OpenCodeConfigSaveResponse extends OpenCodeConfigFile {
|
||||
restartRequired?: boolean
|
||||
}
|
||||
|
||||
export interface OpenCodeRestartResponse {
|
||||
success: boolean
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface OpenCodeImportStatus {
|
||||
configSourcePath: string | null
|
||||
configSourcePaths: string[]
|
||||
|
||||
Reference in new issue
Block a user