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:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

@@ -1,8 +1,9 @@
import { z } from 'zod'
import { ASSISTANT_NOTIFICATION_LIMITS } from '@opencode-manager/shared/schemas'
export const MANAGER_TOOL_NAME = 'ocm'
export const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
export const MANAGER_TOOL_ALLOWED_ROUTES = [
'GET /settings',
@@ -29,7 +30,34 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [
'POST /repos/*/schedules/*/runs/*/cancel',
] as const
export const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
const MANAGER_TOOL_ACTION_NAMES = ['send_notification', 'request'] as const
const ManagerToolNotificationParamsSchema = z
.object({
title: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX).describe('The notification title.'),
body: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.BODY_MAX).describe('The notification body.'),
url: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.URL_MAX).optional().describe('A deep link to open, such as /repos/my-repo.'),
tag: z.string().max(ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX).optional().describe('A deduplication key for replacing an earlier notification.'),
priority: z.enum(['normal', 'high']).optional().describe('Use high for something that should interrupt the user.'),
})
.strict()
.describe('Send a push notification to every device the user has registered.')
const ManagerToolRequestParamsSchema = z
.object({
method: z.enum(MANAGER_TOOL_ALLOWED_METHODS).describe('The HTTP method for the internal API route.'),
path: z.string().min(1).max(500).describe('The internal API route path, such as /settings or /repos/0/schedules. Query strings are allowed.'),
body: z.record(z.string(), z.unknown()).optional().describe('The JSON request body, for POST and PATCH routes.'),
})
.strict()
.describe('Call an allow-listed OpenCode Manager internal API route.')
const MANAGER_TOOL_ACTION_PARAMS_SCHEMAS: Record<(typeof MANAGER_TOOL_ACTION_NAMES)[number], z.ZodType> = {
send_notification: ManagerToolNotificationParamsSchema,
request: ManagerToolRequestParamsSchema,
}
export function parseAllowedRoute(route: string): { method: string; path: string } {
const separator = route.indexOf(' ')
@@ -47,10 +75,45 @@ function buildRouteMatchers(): { method: string; source: string }[] {
})
}
export function buildManagerToolPluginSource(): string {
return `import { z } from 'zod'
function requiredKeysOf(schema: z.ZodType): string[] {
const jsonSchema = z.toJSONSchema(schema) as { required?: string[] }
return jsonSchema.required ?? []
}
var REQUEST_TIMEOUT_MS = ${MANAGER_TOOL_REQUEST_TIMEOUT_MS}
function buildManagerToolInputJsonSchema(): Record<string, unknown> {
const jsonSchema: Record<string, unknown> = z.toJSONSchema(
z
.object({
action: z.enum(MANAGER_TOOL_ACTION_NAMES).describe('The OpenCode Manager action to perform.'),
params: z
.union([MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.send_notification, MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.request])
.describe('The parameters for the chosen action.'),
})
.strict(),
)
delete jsonSchema.$schema
return jsonSchema
}
function buildManagerToolActionRequiredKeys(): Record<string, string[]> {
return Object.fromEntries(MANAGER_TOOL_ACTION_NAMES.map((name) => [name, requiredKeysOf(MANAGER_TOOL_ACTION_PARAMS_SCHEMAS[name])]))
}
function buildManagerToolDescription(): string {
return [
'Perform an OpenCode Manager action.',
'The action runs inside OpenCode Manager itself, so it needs no token and no network access from the agent shell, and it works in sandboxed sessions and scheduled runs.',
'Actions:',
'- send_notification: send a push notification to every device the user has registered.',
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos, OpenCode workspaces, and schedules.',
'Allowed request routes:',
]
.concat(MANAGER_TOOL_ALLOWED_ROUTES.map((route) => `- ${route}`))
.join('\n')
}
export function buildManagerToolPluginSource(id: string): string {
return `var REQUEST_TIMEOUT_MS = ${MANAGER_TOOL_REQUEST_TIMEOUT_MS}
var ALLOWED_ROUTES = ${JSON.stringify(MANAGER_TOOL_ALLOWED_ROUTES)}
@@ -58,6 +121,14 @@ var ALLOWED_MATCHERS = ${JSON.stringify(buildRouteMatchers())}.map(function (mat
return { method: matcher.method, pattern: new RegExp(matcher.source) }
})
var ACTION_NAMES = ${JSON.stringify(MANAGER_TOOL_ACTION_NAMES)}
var ACTION_REQUIRED_KEYS = ${JSON.stringify(buildManagerToolActionRequiredKeys())}
var INPUT_SCHEMA = ${JSON.stringify(buildManagerToolInputJsonSchema(), null, 2)}
var DESCRIPTION = ${JSON.stringify(buildManagerToolDescription())}
function resolveRoute(path) {
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
@@ -90,10 +161,14 @@ function assertAllowedRoute(method, path) {
return resolved
}
async function requestInternalApi(method, path, body) {
async function requestInternalApi(method, path, body, signal) {
var resolved = resolveRoute(path)
var headers = { Authorization: 'Bearer ' + resolved.token }
var init = { method: method, headers: headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }
var init = {
method: method,
headers: headers,
signal: AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]),
}
if (body !== undefined) {
headers['content-type'] = 'application/json'
init.body = JSON.stringify(body)
@@ -111,8 +186,8 @@ async function requestInternalApi(method, path, body) {
return text
}
async function postInternalApi(routePath, body) {
var text = await requestInternalApi('POST', routePath, body)
async function postInternalApi(routePath, body, signal) {
var text = await requestInternalApi('POST', routePath, body, signal)
try {
return JSON.parse(text)
} catch (error) {
@@ -122,15 +197,8 @@ async function postInternalApi(routePath, body) {
var ACTIONS = {
send_notification: {
params: z.object({
title: z.string().min(1).max(${ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX}).describe('The notification title.'),
body: z.string().min(1).max(${ASSISTANT_NOTIFICATION_LIMITS.BODY_MAX}).describe('The notification body.'),
url: z.string().min(1).max(${ASSISTANT_NOTIFICATION_LIMITS.URL_MAX}).optional().describe('A deep link to open, such as /repos/my-repo.'),
tag: z.string().max(${ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX}).optional().describe('A deduplication key for replacing an earlier notification.'),
priority: z.enum(['normal', 'high']).optional().describe('Use high for something that should interrupt the user.'),
}).describe('Send a push notification to every device the user has registered.'),
run: async function (params) {
var result = await postInternalApi('/notifications/send', params)
run: async function (params, signal) {
var result = await postInternalApi('/notifications/send', params, signal)
if (result.noSubscriptions === true) {
return 'No devices are registered for push notifications, so nothing was delivered.'
}
@@ -138,47 +206,53 @@ var ACTIONS = {
},
},
request: {
params: z.object({
method: z.enum(${JSON.stringify(MANAGER_TOOL_ALLOWED_METHODS)}).describe('The HTTP method for the internal API route.'),
path: z.string().min(1).max(500).describe('The internal API route path, such as /settings or /repos/0/schedules. Query strings are allowed.'),
body: z.record(z.string(), z.unknown()).optional().describe('The JSON request body, for POST and PATCH routes.'),
}).describe('Call an allow-listed OpenCode Manager internal API route.'),
run: async function (params) {
run: async function (params, signal) {
assertAllowedRoute(params.method, params.path)
var text = await requestInternalApi(params.method, params.path, params.body)
var text = await requestInternalApi(params.method, params.path, params.body, signal)
return text || 'The request succeeded with an empty response body.'
},
},
}
var ACTION_NAMES = Object.keys(ACTIONS)
export default async function () {
return {
tool: {
${MANAGER_TOOL_NAME}: {
description: [
'Perform an OpenCode Manager action.',
'The action runs inside OpenCode Manager itself, so it needs no token and no network access from the agent shell, and it works in sandboxed sessions and scheduled runs.',
'Actions:',
'- send_notification: send a push notification to every device the user has registered.',
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos, OpenCode workspaces, and schedules.',
'Allowed request routes:',
].concat(ALLOWED_ROUTES.map(function (route) { return '- ' + route })).join('\\n'),
args: {
action: z.enum(ACTION_NAMES).describe('The OpenCode Manager action to perform.'),
params: z.union(ACTION_NAMES.map(function (name) { return ACTIONS[name].params })).describe('The parameters for the chosen action.'),
},
execute: async function (args) {
if (!Object.prototype.hasOwnProperty.call(ACTIONS, args.action)) {
throw new Error('Unknown OpenCode Manager action: ' + String(args.action) + '. Supported actions: ' + ACTION_NAMES.join(', ') + '.')
}
var action = ACTIONS[args.action]
return await action.run(action.params.parse(args.params))
},
},
},
function assertParams(actionName, params) {
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
throw new Error('Invalid parameters for OpenCode Manager action: ' + actionName + '.')
}
var required = ACTION_REQUIRED_KEYS[actionName]
for (var index = 0; index < required.length; index += 1) {
if (!Object.prototype.hasOwnProperty.call(params, required[index])) {
throw new Error(
'Invalid parameters for OpenCode Manager action: ' + actionName + '. Missing required parameter: ' + required[index] + '.',
)
}
}
}
async function runAction(input, signal) {
var actionName = input !== null && typeof input === 'object' ? input.action : undefined
if (!Object.prototype.hasOwnProperty.call(ACTIONS, actionName)) {
throw new Error('Unknown OpenCode Manager action: ' + String(actionName) + '. Supported actions: ' + ACTION_NAMES.join(', ') + '.')
}
var params = input.params
assertParams(actionName, params)
return await ACTIONS[actionName].run(params, signal)
}
export default {
id: '${id}',
async setup(ctx) {
await ctx.tool.transform(function (editor) {
editor.add({
name: ${JSON.stringify(MANAGER_TOOL_NAME)},
description: DESCRIPTION,
input: INPUT_SCHEMA,
options: { codemode: false },
execute: async function (input, context) {
return { content: await runAction(input, context.signal) }
},
})
})
},
}
`
}