mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +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
@@ -160,7 +160,7 @@ function buildLegacyAssistantAgentPrompt(): string {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildAssistantDefaultAgentMdFromPrompt(prompt: string): string {
|
||||
function buildAssistantDefaultAgentMdFromPrompt(prompt: string, shellPermissionKey: 'bash' | 'shell'): string {
|
||||
const permission = buildAssistantAgentPermission()
|
||||
|
||||
return `---
|
||||
@@ -172,7 +172,7 @@ permission:
|
||||
glob: ${permission.glob}
|
||||
grep: ${permission.grep}
|
||||
list: ${permission.list}
|
||||
bash: ${permission.bash}
|
||||
${shellPermissionKey}: ${permission.shell}
|
||||
external_directory: ${permission.external_directory}
|
||||
---
|
||||
|
||||
@@ -181,7 +181,7 @@ ${prompt}
|
||||
}
|
||||
|
||||
function buildLegacyAssistantDefaultAgentMd(): string {
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildLegacyAssistantAgentPrompt())
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildLegacyAssistantAgentPrompt(), 'bash')
|
||||
}
|
||||
|
||||
function buildPreviousAssistantAgentsMd(): string {
|
||||
@@ -296,24 +296,24 @@ function buildAssistantAgentPrompt(): string {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildAssistantAgentPermission(): { read: 'allow'; edit: 'allow'; glob: 'allow'; grep: 'allow'; list: 'allow'; bash: 'allow'; external_directory: 'ask' } {
|
||||
function buildAssistantAgentPermission(): { read: 'allow'; edit: 'allow'; glob: 'allow'; grep: 'allow'; list: 'allow'; shell: 'allow'; external_directory: 'ask' } {
|
||||
return {
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
bash: 'allow',
|
||||
shell: 'allow',
|
||||
external_directory: 'ask',
|
||||
}
|
||||
}
|
||||
|
||||
function buildPreviousAssistantDefaultAgentMd(): string {
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildPreviousAssistantAgentPrompt())
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildPreviousAssistantAgentPrompt(), 'bash')
|
||||
}
|
||||
|
||||
export function buildAssistantDefaultAgentMd(): string {
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildAssistantAgentPrompt())
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildAssistantAgentPrompt(), 'shell')
|
||||
}
|
||||
|
||||
export function buildSchedulesSkill(): string {
|
||||
@@ -691,9 +691,9 @@ Returns the updated settings object with the same structure as GET.
|
||||
|
||||
### POST /assistant/reload
|
||||
|
||||
Reload the assistant workspace by disposing the current OpenCode instance. Use this after editing \`.opencode/agents/assistant.md\` or \`opencode.json\` so changes take effect on the next message.
|
||||
Reload the OpenCode configuration without restarting the server, rebuilding every loaded location. OpenCode re-reads \`opencode.json\`/\`opencode.jsonc\`, agents, commands, skills, plugins, and \`AGENTS.md\`; running sessions, including this one, keep running. Use this after editing \`.opencode/agents/assistant.md\` or other workspace files so changes take effect on the next message. Returns \`400\` with \`validationIssues\` when the OpenCode configuration is invalid.
|
||||
|
||||
**Note:** Always confirm with the user before reloading, as it re-bootstraps the workspace.
|
||||
**Note:** Always confirm with the user before reloading.
|
||||
|
||||
**Rate Limiting:** 5 requests per minute per token. Returns \`429 Too Many Requests\` with \`Retry-After\` header when exceeded.
|
||||
|
||||
@@ -715,11 +715,11 @@ Reload the assistant workspace by disposing the current OpenCode instance. Use t
|
||||
|
||||
## OpenCode Configuration
|
||||
|
||||
The global configuration files on disk are the source of truth. Use the \`ocm\` tool's \`request\` action with the endpoints below to read or change them; never edit the files directly. Global sources merge in order: \`config.json\`, \`opencode.json\`, then \`opencode.jsonc\`.
|
||||
The global configuration files on disk are the source of truth. Use the \`ocm\` tool's \`request\` action with the endpoints below to read or change them; never edit the files directly. Global sources merge in order: \`opencode.json\`, then \`opencode.jsonc\`.
|
||||
|
||||
### GET /opencode-config
|
||||
|
||||
Read the merged persisted global configuration and its source files. Returns \`404\` when no source exists. This is not the running instance configuration: project overrides and expanded environment values are not included. \`GET /opencode-config/effective\` reads the running server's effective global configuration separately; never copy that response into a save.
|
||||
Read the merged persisted global configuration and its source files. Returns \`404\` when no source exists. This is not the running instance configuration: project overrides and expanded environment values are not included. \`GET /opencode-config/effective\` reads the running server's configuration separately as \`entries\`: the configuration documents and discovery directories in precedence order, lowest first, each shaped as \`{ type: 'document', path, info }\` or \`{ type: 'directory', path }\`. Its \`info\` values are expanded for the running server; never copy this response into a save.
|
||||
|
||||
**Response (\`OpenCodeConfigFile\`):**
|
||||
\`\`\`ts
|
||||
@@ -748,13 +748,13 @@ Read the merged persisted global configuration and its source files. Returns \`4
|
||||
|
||||
### PUT /opencode-config
|
||||
|
||||
Read the merged persisted configuration first, change only the keys the user asked for, and send the complete object back with its revision. Only changed fields are patched into the preferred existing source: JSONC, JSON, then legacy config.json. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved. Removing a field removes only its override in the write target; a lower-priority value can reappear.
|
||||
Read the merged persisted configuration first, change only the keys the user asked for, and send the complete object back with its revision. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved. Removing a field removes only its override in the write target; a lower-priority value can reappear.
|
||||
|
||||
For a raw edit, send a string with the exact source name from \`sources\`. Never send merged JSON as raw source text. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content.
|
||||
|
||||
**Request Body:**
|
||||
\`\`\`ts
|
||||
{ content: object | string, expectedRevision: string, source?: "config.json" | "opencode.json" | "opencode.jsonc" }
|
||||
{ content: object | string, expectedRevision: string, source?: "opencode.json" | "opencode.jsonc" }
|
||||
\`\`\`
|
||||
|
||||
**Example:**
|
||||
@@ -775,17 +775,21 @@ For a raw edit, send a string with the exact source name from \`sources\`. Never
|
||||
\`\`\`
|
||||
|
||||
**Response:**
|
||||
Returns the refreshed merged configuration and source files. Adds \`restartRequired: true\` for semantic configuration changes, except changes limited to \`mcp\`, which are saved without it; to make an MCP change take effect immediately, tell the user to reconnect or reload the server from Settings → MCP. Comment-only changes do not require a restart. Saving never silently drops unsupported fields.
|
||||
Returns the refreshed merged configuration and source files. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. Changes limited to \`mcp\` are saved without a reload; to make an MCP change take effect immediately, tell the user to reconnect the server from Settings → MCP. Comment-only changes do nothing. Saving never silently drops unsupported fields.
|
||||
|
||||
The response adds \`restartRequired: true\` only when the automatic reload failed, for example because the OpenCode server is unavailable.
|
||||
|
||||
Returns \`400\` for invalid configuration and \`409\` for a stale revision.
|
||||
|
||||
When the response contains \`restartRequired: true\`, tell the user to restart the OpenCode server from Settings. Never attempt the restart yourself: it would terminate your own session.
|
||||
|
||||
Only changes to how the OpenCode process is launched need a user restart from Settings: server environment variables, Git credentials and identity, sandbox enforcement, rotating the manager token, the server password, and installing or upgrading the OpenCode version. You cannot make these changes through this API.
|
||||
|
||||
## Safety
|
||||
|
||||
- The settings PATCH endpoint rejects any attempt to modify credentials, API keys, or other sensitive settings; guide the user to the full UI for Git, TTS, and STT credentials
|
||||
- PUT /opencode-config patches changed global settings, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
|
||||
- The settings PATCH endpoint does NOT trigger OpenCode reload or restart
|
||||
- The settings PATCH endpoint does NOT trigger an OpenCode reload or restart
|
||||
`
|
||||
}
|
||||
|
||||
@@ -866,7 +870,6 @@ List all repos available to OpenCode Manager. The repos are returned in the orde
|
||||
export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
|
||||
const config: OpenCodeConfigInput = {
|
||||
default_agent: ASSISTANT_DEFAULT_AGENT_NAME,
|
||||
instructions: ['AGENTS.md'],
|
||||
permission: buildAssistantAgentPermission(),
|
||||
agent: {
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: 'primary' },
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { getAuthPath } from '@opencode-manager/shared/config/env'
|
||||
import { logger } from '../utils/logger'
|
||||
import { AuthCredentialsSchema } from '../../../shared/src/schemas/auth'
|
||||
import type { z } from 'zod'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
|
||||
type AuthCredentials = z.infer<typeof AuthCredentialsSchema>
|
||||
|
||||
export class AuthService {
|
||||
private authPath = getAuthPath()
|
||||
|
||||
private migrateEntry(entry: Record<string, unknown>): Record<string, unknown> {
|
||||
if (entry.type === 'apiKey' && typeof entry.apiKey === 'string') {
|
||||
return {
|
||||
type: 'api',
|
||||
key: entry.apiKey,
|
||||
}
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
async getAll(): Promise<AuthCredentials> {
|
||||
try {
|
||||
const data = await fs.readFile(this.authPath, 'utf-8')
|
||||
const parsed = JSON.parse(data) as Record<string, Record<string, unknown>>
|
||||
|
||||
let needsMigration = false
|
||||
const migrated: Record<string, Record<string, unknown>> = {}
|
||||
|
||||
for (const [key, entry] of Object.entries(parsed)) {
|
||||
const migratedEntry = this.migrateEntry(entry)
|
||||
if (migratedEntry !== entry) {
|
||||
needsMigration = true
|
||||
}
|
||||
migrated[key] = migratedEntry
|
||||
}
|
||||
|
||||
if (needsMigration) {
|
||||
await fs.writeFile(this.authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 })
|
||||
logger.info('Migrated auth.json to new schema format')
|
||||
}
|
||||
|
||||
return AuthCredentialsSchema.parse(migrated)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return {}
|
||||
}
|
||||
logger.error('Failed to read auth.json:', error)
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
async set(providerId: string, apiKey: string): Promise<void> {
|
||||
const auth = await this.getAll()
|
||||
auth[providerId] = {
|
||||
type: 'api',
|
||||
key: apiKey,
|
||||
}
|
||||
|
||||
await mkdirSafe(path.dirname(this.authPath))
|
||||
await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2), { mode: 0o600 })
|
||||
|
||||
logger.info(`Set credentials for provider: ${providerId}`)
|
||||
}
|
||||
|
||||
async delete(providerId: string): Promise<void> {
|
||||
const auth = await this.getAll()
|
||||
delete auth[providerId]
|
||||
|
||||
await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2), { mode: 0o600 })
|
||||
logger.info(`Deleted credentials for provider: ${providerId}`)
|
||||
}
|
||||
|
||||
async list(): Promise<string[]> {
|
||||
const auth = await this.getAll()
|
||||
return Object.keys(auth)
|
||||
}
|
||||
|
||||
async has(providerId: string): Promise<boolean> {
|
||||
const auth = await this.getAll()
|
||||
return !!auth[providerId]
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +1,46 @@
|
||||
export interface McpOAuthFlowState {
|
||||
export interface McpOAuthFlow {
|
||||
state: string
|
||||
serverName: string
|
||||
serverUrl: string
|
||||
codeVerifier: string
|
||||
clientId: string
|
||||
clientSecret?: string
|
||||
callbackUrl: string
|
||||
tokenEndpoint: string
|
||||
timestamp: number
|
||||
integrationID: string
|
||||
attemptID: string
|
||||
callbackPort: number
|
||||
directory?: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export type McpOAuthFlowResult =
|
||||
| { status: 'pending' }
|
||||
| { status: 'completed'; serverName: string }
|
||||
| { status: 'failed'; error: string }
|
||||
|
||||
const flowStore = new Map<string, McpOAuthFlowState>()
|
||||
const resultStore = new Map<string, McpOAuthFlowResult & { timestamp: number }>()
|
||||
const STATE_TTL_MS = 10 * 60 * 1000
|
||||
const RESULT_TTL_MS = 5 * 60 * 1000
|
||||
const flowStore = new Map<string, McpOAuthFlow>()
|
||||
const attemptStore = new Map<string, McpOAuthFlow>()
|
||||
const FLOW_TTL_MS = 10 * 60 * 1000
|
||||
const CLEANUP_INTERVAL_MS = 60 * 1000
|
||||
|
||||
setInterval(() => {
|
||||
const now = Date.now()
|
||||
for (const [key, value] of flowStore) {
|
||||
if (now - value.timestamp > STATE_TTL_MS) {
|
||||
for (const [key, flow] of flowStore) {
|
||||
if (now - flow.timestamp > FLOW_TTL_MS) {
|
||||
flowStore.delete(key)
|
||||
}
|
||||
}
|
||||
for (const [key, value] of resultStore) {
|
||||
if (now - value.timestamp > RESULT_TTL_MS) {
|
||||
resultStore.delete(key)
|
||||
for (const [key, flow] of attemptStore) {
|
||||
if (now - flow.timestamp > FLOW_TTL_MS) {
|
||||
attemptStore.delete(key)
|
||||
}
|
||||
}
|
||||
}, CLEANUP_INTERVAL_MS)
|
||||
|
||||
export function storeMcpOAuthFlow(state: string, data: Omit<McpOAuthFlowState, 'timestamp'>): void {
|
||||
flowStore.set(state, { ...data, timestamp: Date.now() })
|
||||
resultStore.set(state, { status: 'pending', timestamp: Date.now() })
|
||||
export function storeMcpOAuthFlow(flow: Omit<McpOAuthFlow, 'timestamp'>): void {
|
||||
const entry = { ...flow, timestamp: Date.now() }
|
||||
flowStore.set(flow.state, entry)
|
||||
attemptStore.set(flow.attemptID, entry)
|
||||
}
|
||||
|
||||
export function consumeMcpOAuthFlow(state: string): McpOAuthFlowState | undefined {
|
||||
const data = flowStore.get(state)
|
||||
if (data) {
|
||||
export function consumeMcpOAuthFlow(state: string): McpOAuthFlow | undefined {
|
||||
const flow = flowStore.get(state)
|
||||
if (flow) {
|
||||
flowStore.delete(state)
|
||||
}
|
||||
return data
|
||||
return flow
|
||||
}
|
||||
|
||||
export function deleteMcpOAuthFlow(state: string): void {
|
||||
flowStore.delete(state)
|
||||
}
|
||||
|
||||
export function markMcpOAuthFlowCompleted(state: string, serverName: string): void {
|
||||
resultStore.set(state, { status: 'completed', serverName, timestamp: Date.now() })
|
||||
}
|
||||
|
||||
export function markMcpOAuthFlowFailed(state: string, error: string): void {
|
||||
resultStore.set(state, { status: 'failed', error, timestamp: Date.now() })
|
||||
}
|
||||
|
||||
export function getMcpOAuthFlowResult(state: string): McpOAuthFlowResult | undefined {
|
||||
const entry = resultStore.get(state)
|
||||
if (!entry) return undefined
|
||||
if (entry.status === 'completed') return { status: entry.status, serverName: entry.serverName }
|
||||
if (entry.status === 'failed') return { status: entry.status, error: entry.error }
|
||||
return { status: entry.status }
|
||||
export function getMcpOAuthFlowByAttempt(attemptID: string): McpOAuthFlow | undefined {
|
||||
return attemptStore.get(attemptID)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
import {
|
||||
getPermissionLabel,
|
||||
getPermissionDetail,
|
||||
getQuestionText,
|
||||
getFormText,
|
||||
} from "@opencode-manager/shared/notifications";
|
||||
import { SettingsService } from "./settings";
|
||||
import { sseAggregator, type SSEEvent } from "./sse-aggregator";
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import type { Repo } from "../types/repo";
|
||||
import { getReposPath } from "@opencode-manager/shared/config/env";
|
||||
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils";
|
||||
import { sessionIDFromEvent } from "@opencode-manager/shared/opencode";
|
||||
import { resolveProjectId } from "./project-id-resolver";
|
||||
import path from "path";
|
||||
|
||||
@@ -36,28 +37,28 @@ const EVENT_CONFIG: Record<
|
||||
string,
|
||||
{
|
||||
preferencesKey: keyof typeof DEFAULT_NOTIFICATION_PREFERENCES.events;
|
||||
titleFn: (props: Record<string, unknown>) => string;
|
||||
bodyFn: (props: Record<string, unknown>) => string;
|
||||
titleFn: (data: Record<string, unknown>) => string;
|
||||
bodyFn: (data: Record<string, unknown>) => string;
|
||||
}
|
||||
> = {
|
||||
[NotificationEventType.PERMISSION_ASKED]: {
|
||||
preferencesKey: "permissionAsked",
|
||||
titleFn: (props) =>
|
||||
titleFn: (data) =>
|
||||
getPermissionLabel(
|
||||
typeof props.permission === "string" ? props.permission : ""
|
||||
typeof data.action === "string" ? data.action : ""
|
||||
),
|
||||
bodyFn: (props) => getPermissionDetail(props).primary || "Approval required",
|
||||
bodyFn: (data) => getPermissionDetail(data).primary || "Approval required",
|
||||
},
|
||||
[NotificationEventType.QUESTION_ASKED]: {
|
||||
[NotificationEventType.FORM_CREATED]: {
|
||||
preferencesKey: "questionAsked",
|
||||
titleFn: () => "Question",
|
||||
bodyFn: (props) => getQuestionText(props) || "A question needs your answer",
|
||||
bodyFn: (data) => getFormText(data.form as { title?: unknown }) || "A question needs your answer",
|
||||
},
|
||||
[NotificationEventType.SESSION_ERROR]: {
|
||||
[NotificationEventType.SESSION_FAILED]: {
|
||||
preferencesKey: "sessionError",
|
||||
titleFn: () => "Error",
|
||||
bodyFn: (props) => {
|
||||
const error = props.error as { message?: string } | undefined;
|
||||
bodyFn: (data) => {
|
||||
const error = data.error as { message?: string } | undefined;
|
||||
return error?.message ?? "A session encountered an error";
|
||||
},
|
||||
},
|
||||
@@ -70,6 +71,13 @@ const EVENT_CONFIG: Record<
|
||||
|
||||
const MAX_BODY_LENGTH = 140;
|
||||
|
||||
function resolveEventSessionId(event: SSEEvent): string | undefined {
|
||||
if (event.type === NotificationEventType.FORM_CREATED) {
|
||||
return event.data.form.sessionID;
|
||||
}
|
||||
return sessionIDFromEvent(event);
|
||||
}
|
||||
|
||||
export function buildNotificationUrl(
|
||||
repo: Pick<Repo, "id"> | null,
|
||||
sessionId: string | undefined
|
||||
@@ -81,7 +89,7 @@ export function buildNotificationUrl(
|
||||
}
|
||||
|
||||
export function buildEventNotificationPayload(
|
||||
event: SSEEvent,
|
||||
event: Pick<SSEEvent, "type" | "data">,
|
||||
context: {
|
||||
repoName?: string;
|
||||
repoId?: number;
|
||||
@@ -93,9 +101,9 @@ export function buildEventNotificationPayload(
|
||||
const config = EVENT_CONFIG[event.type];
|
||||
if (!config) return null;
|
||||
|
||||
const title = config.titleFn(event.properties);
|
||||
const title = config.titleFn(event.data);
|
||||
|
||||
const detail = config.bodyFn(event.properties);
|
||||
const detail = config.bodyFn(event.data);
|
||||
const rawBody = context.repoName
|
||||
? `${context.repoName} · ${detail}`
|
||||
: detail;
|
||||
@@ -292,7 +300,7 @@ export class NotificationService {
|
||||
const config = EVENT_CONFIG[event.type];
|
||||
if (!config) return;
|
||||
|
||||
const sessionId = event.properties.sessionID as string | undefined;
|
||||
const sessionId = resolveEventSessionId(event);
|
||||
if (sessionId && sseAggregator.isSessionBeingViewed(sessionId)) return;
|
||||
if (sessionId && sseAggregator.isSubagentSession(sessionId)) return;
|
||||
|
||||
|
||||
@@ -13,19 +13,28 @@ import {
|
||||
withOpenCodeConfigLock,
|
||||
} from './opencode-config-file'
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
import { reloadOpenCodeConfig } from './opencode-restart'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import type { SettingsService } from './settings'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export type OpenCodeReloadOutcome = 'reloaded' | 'restart_pending'
|
||||
|
||||
export type ApplyOpenCodeConfigResult =
|
||||
| { status: 'restart_pending'; config: OpenCodeConfigFile }
|
||||
| { status: 'applied'; config: OpenCodeConfigFile }
|
||||
| { status: 'reloaded'; config: OpenCodeConfigFile }
|
||||
| { status: 'restart_pending'; config: OpenCodeConfigFile }
|
||||
|
||||
export interface ApplyOpenCodeConfigInput {
|
||||
content: Record<string, unknown> | string
|
||||
source?: OpenCodeConfigSourceName
|
||||
expectedRevision?: string
|
||||
settingsService: SettingsService
|
||||
openCodeClient: OpenCodeClient
|
||||
}
|
||||
|
||||
const MCP_CONFIG_KEY = 'mcp'
|
||||
|
||||
export async function captureLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
|
||||
const previous = await readOpenCodeConfigFile()
|
||||
if (previous?.isValid) {
|
||||
@@ -66,26 +75,33 @@ export function toOpenCodeConfigApplyResponse(
|
||||
}
|
||||
}
|
||||
|
||||
function requiresOpenCodeRestart(previous: OpenCodeConfigFile | null, next: OpenCodeConfigFile): boolean {
|
||||
export async function reloadOpenCodeOrMarkRestartPending(openCodeClient: OpenCodeClient): Promise<OpenCodeReloadOutcome> {
|
||||
try {
|
||||
await reloadOpenCodeConfig(openCodeClient)
|
||||
return 'reloaded'
|
||||
} catch (error) {
|
||||
logger.warn('OpenCode configuration reload failed, marking a server restart as pending:', error)
|
||||
opencodeServerManager.markRestartPending()
|
||||
return 'restart_pending'
|
||||
}
|
||||
}
|
||||
|
||||
function listChangedTopLevelKeys(previous: Record<string, unknown>, next: Record<string, unknown>): string[] {
|
||||
const keys = new Set([...Object.keys(previous), ...Object.keys(next)])
|
||||
return [...keys].filter((key) => !isDeepStrictEqual(previous[key], next[key]))
|
||||
}
|
||||
|
||||
function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenCodeConfigFile): boolean {
|
||||
if (previous?.isValid !== next.isValid) {
|
||||
return true
|
||||
}
|
||||
|
||||
const previousContent = previous?.content ?? {}
|
||||
const keys = new Set([...Object.keys(previousContent), ...Object.keys(next.content)])
|
||||
for (const key of keys) {
|
||||
if (!isDeepStrictEqual(previousContent[key], next.content[key]) && key !== 'mcp') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).some((key) => key !== MCP_CONFIG_KEY)
|
||||
}
|
||||
|
||||
export async function applyOpenCodeConfigUpdate(
|
||||
input: ApplyOpenCodeConfigInput,
|
||||
): Promise<ApplyOpenCodeConfigResult> {
|
||||
return withOpenCodeConfigLock(async () => {
|
||||
const { reloadRequired, config } = await withOpenCodeConfigLock(async () => {
|
||||
const { content, source, expectedRevision, settingsService } = input
|
||||
|
||||
const snapshot = await readOpenCodeConfigSnapshot()
|
||||
@@ -103,11 +119,12 @@ export async function applyOpenCodeConfigUpdate(
|
||||
}
|
||||
}
|
||||
|
||||
if (requiresOpenCodeRestart(previous, next)) {
|
||||
opencodeServerManager.markRestartPending()
|
||||
return { status: 'restart_pending', config: next }
|
||||
}
|
||||
|
||||
return { status: 'applied', config: next }
|
||||
return { reloadRequired: requiresOpenCodeReload(previous, next), config: next }
|
||||
})
|
||||
|
||||
if (!reloadRequired) {
|
||||
return { status: 'applied', config }
|
||||
}
|
||||
|
||||
return { status: await reloadOpenCodeOrMarkRestartPending(input.openCodeClient), config }
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import { createHash } from 'crypto'
|
||||
import { readFile, readdir, rm, stat } from 'fs/promises'
|
||||
import { readFile, readdir, rename, rm, stat } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import { applyEdits, modify, type JSONPath } from 'jsonc-parser'
|
||||
import type { ZodIssue } from 'zod'
|
||||
import { getConfigPath, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
|
||||
import { getConfigPath, getOpenCodeConfigHome, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
|
||||
LEGACY_OPENCODE_CONFIG_SOURCE_NAME,
|
||||
OPENCODE_CONFIG_SOURCE_NAMES,
|
||||
isOpenCodeConfigSourceName,
|
||||
selectPreferredOpenCodeConfigSourceName,
|
||||
@@ -28,6 +29,10 @@ export const OPENCODE_CONFIG_SEED = JSON.stringify({ $schema: 'https://opencode.
|
||||
|
||||
export const HEALTH_WATCH_MAX_ENTRIES = 20
|
||||
|
||||
const OPENCODE_CONFIG_ARCHIVE_DIR_NAME = 'opencode-configs-archive'
|
||||
|
||||
export type OpenCodeConfigRestorableSourceName = OpenCodeConfigSourceName | typeof LEGACY_OPENCODE_CONFIG_SOURCE_NAME
|
||||
|
||||
const OPENCODE_CONFIG_SOURCE_ORDER: readonly OpenCodeConfigSourceName[] = OPENCODE_CONFIG_SOURCE_NAMES
|
||||
|
||||
const OPENCODE_CONFIG_SNAPSHOT_VERSION = 1
|
||||
@@ -99,7 +104,7 @@ export interface OpenCodeConfigSnapshot {
|
||||
}
|
||||
|
||||
interface OpenCodeConfigSourceFileState {
|
||||
name: OpenCodeConfigSourceName
|
||||
name: OpenCodeConfigRestorableSourceName
|
||||
rawContent: string | null
|
||||
}
|
||||
|
||||
@@ -110,7 +115,7 @@ interface PreparedOpenCodeConfigSourceFileState extends OpenCodeConfigSourceFile
|
||||
}
|
||||
|
||||
interface AppliedOpenCodeConfigSourceFileState {
|
||||
name: OpenCodeConfigSourceName
|
||||
name: OpenCodeConfigRestorableSourceName
|
||||
previousRawContent: string | null
|
||||
previousMode: number | undefined
|
||||
}
|
||||
@@ -121,7 +126,7 @@ interface OpenCodeConfigPathOperation {
|
||||
}
|
||||
|
||||
interface OpenCodeConfigSnapshotEnvelopeSource {
|
||||
name: OpenCodeConfigSourceName
|
||||
name: OpenCodeConfigRestorableSourceName
|
||||
rawContent: string
|
||||
}
|
||||
|
||||
@@ -135,7 +140,7 @@ function getOpenCodeConfigDirectory(): string {
|
||||
return getConfigPath()
|
||||
}
|
||||
|
||||
function getOpenCodeConfigSourcePath(name: OpenCodeConfigSourceName): string {
|
||||
function getOpenCodeConfigSourcePath(name: OpenCodeConfigRestorableSourceName): string {
|
||||
return path.join(getOpenCodeConfigDirectory(), name)
|
||||
}
|
||||
|
||||
@@ -453,7 +458,7 @@ export async function updateOpenCodeConfigFile(
|
||||
}
|
||||
|
||||
export function serializeOpenCodeConfigSourceSnapshot(
|
||||
entries: ReadonlyArray<{ name: OpenCodeConfigSourceName; rawContent: string }>,
|
||||
entries: ReadonlyArray<{ name: OpenCodeConfigRestorableSourceName; rawContent: string }>,
|
||||
): string {
|
||||
const envelope: OpenCodeConfigSnapshotEnvelope = {
|
||||
marker: OPENCODE_CONFIG_SNAPSHOT_MARKER,
|
||||
@@ -479,7 +484,15 @@ function isSnapshotEnvelopeCandidate(parsed: Record<string, unknown>): boolean {
|
||||
return hasOwn(parsed, 'marker') || (hasOwn(parsed, 'sources') && hasOwn(parsed, 'version'))
|
||||
}
|
||||
|
||||
function parseOpenCodeConfigSnapshot(snapshot: string): Map<OpenCodeConfigSourceName, string> {
|
||||
function isRestorableOpenCodeConfigSourceName(value: string): value is OpenCodeConfigRestorableSourceName {
|
||||
return isOpenCodeConfigSourceName(value) || value === LEGACY_OPENCODE_CONFIG_SOURCE_NAME
|
||||
}
|
||||
|
||||
export function toOpenCodeConfigRestorableSourceName(value: string): OpenCodeConfigRestorableSourceName | null {
|
||||
return isRestorableOpenCodeConfigSourceName(value) ? value : null
|
||||
}
|
||||
|
||||
function parseOpenCodeConfigSnapshot(snapshot: string): Map<OpenCodeConfigRestorableSourceName, string> {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = parseJsonc(snapshot)
|
||||
@@ -498,12 +511,12 @@ function parseOpenCodeConfigSnapshot(snapshot: string): Map<OpenCodeConfigSource
|
||||
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot sources')
|
||||
}
|
||||
|
||||
const sources = new Map<OpenCodeConfigSourceName, string>()
|
||||
const sources = new Map<OpenCodeConfigRestorableSourceName, string>()
|
||||
for (const entry of parsed.sources) {
|
||||
if (!isPlainObject(entry)) {
|
||||
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot source')
|
||||
}
|
||||
if (typeof entry.name !== 'string' || !isOpenCodeConfigSourceName(entry.name)) {
|
||||
if (typeof entry.name !== 'string' || !isRestorableOpenCodeConfigSourceName(entry.name)) {
|
||||
throw new OpenCodeConfigSnapshotError(`Invalid OpenCode config snapshot source name: ${String(entry.name)}`)
|
||||
}
|
||||
if (typeof entry.rawContent !== 'string') {
|
||||
@@ -550,7 +563,7 @@ async function applyOpenCodeConfigSourceFileStates(
|
||||
states: OpenCodeConfigSourceFileState[],
|
||||
current: OpenCodeConfigSnapshot,
|
||||
): Promise<void> {
|
||||
const previousByName = new Map<OpenCodeConfigSourceName, string | null>(
|
||||
const previousByName = new Map<string, string | null>(
|
||||
current.sources.map((source) => [source.name, source.rawContent]),
|
||||
)
|
||||
const prepared: PreparedOpenCodeConfigSourceFileState[] = []
|
||||
@@ -590,10 +603,14 @@ async function applyOpenCodeConfigSourceFileStates(
|
||||
export async function restoreOpenCodeConfigSnapshot(snapshot: string): Promise<OpenCodeConfigFile | null> {
|
||||
const desired = parseOpenCodeConfigSnapshot(snapshot)
|
||||
const current = await readOpenCodeConfigSnapshot()
|
||||
const currentNames = new Set(current.sources.map((source) => source.name))
|
||||
const currentNames = new Set<string>(current.sources.map((source) => source.name))
|
||||
|
||||
const restorableOrder: readonly OpenCodeConfigRestorableSourceName[] = [
|
||||
...OPENCODE_CONFIG_SOURCE_ORDER,
|
||||
LEGACY_OPENCODE_CONFIG_SOURCE_NAME,
|
||||
]
|
||||
const states: OpenCodeConfigSourceFileState[] = []
|
||||
for (const name of OPENCODE_CONFIG_SOURCE_ORDER) {
|
||||
for (const name of restorableOrder) {
|
||||
if (desired.has(name)) {
|
||||
states.push({ name, rawContent: desired.get(name) ?? '' })
|
||||
} else if (currentNames.has(name)) {
|
||||
@@ -602,9 +619,69 @@ export async function restoreOpenCodeConfigSnapshot(snapshot: string): Promise<O
|
||||
}
|
||||
|
||||
await applyOpenCodeConfigSourceFileStates(states, current)
|
||||
await foldLegacyConfigJsonSource()
|
||||
return readOpenCodeConfigFile()
|
||||
}
|
||||
|
||||
async function archiveLegacyConfigJsonSource(rawContent: string): Promise<string> {
|
||||
const archiveDirectory = path.join(getOpenCodeConfigHome(), OPENCODE_CONFIG_ARCHIVE_DIR_NAME)
|
||||
await ensureDirectoryExists(archiveDirectory)
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const archivePath = path.join(archiveDirectory, `${LEGACY_OPENCODE_CONFIG_SOURCE_NAME}.${timestamp}`)
|
||||
await writeFileAtomic(archivePath, rawContent, { mode: 0o600 })
|
||||
return archivePath
|
||||
}
|
||||
|
||||
export async function foldLegacyConfigJsonSource(): Promise<boolean> {
|
||||
const legacyPath = getOpenCodeConfigSourcePath(LEGACY_OPENCODE_CONFIG_SOURCE_NAME)
|
||||
|
||||
let rawContent: string
|
||||
try {
|
||||
rawContent = await readFile(legacyPath, 'utf8')
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
logger.warn(`Failed to read legacy OpenCode config ${legacyPath}:`, error)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const legacyContent = parseJsonc(rawContent)
|
||||
if (!isPlainObject(legacyContent)) {
|
||||
logger.warn(`Leaving legacy OpenCode config ${legacyPath} in place: its root is not an object`)
|
||||
return false
|
||||
}
|
||||
|
||||
const [lowestPrecedenceSource] = (await readOpenCodeConfigSnapshot()).sources
|
||||
if (lowestPrecedenceSource && !lowestPrecedenceSource.isValid) {
|
||||
logger.warn(`Leaving legacy OpenCode config ${legacyPath} in place: ${lowestPrecedenceSource.path} is invalid`)
|
||||
return false
|
||||
}
|
||||
|
||||
const archivePath = await archiveLegacyConfigJsonSource(rawContent)
|
||||
if (!lowestPrecedenceSource) {
|
||||
const promotedPath = getOpenCodeConfigSourcePath('opencode.json')
|
||||
await rename(legacyPath, promotedPath)
|
||||
logger.info(`Folded legacy OpenCode config ${legacyPath} into ${promotedPath} and archived it to ${archivePath}`)
|
||||
return true
|
||||
}
|
||||
|
||||
const operations = collectOpenCodeConfigPathOperations(legacyContent, lowestPrecedenceSource.content)
|
||||
.filter((operation) => operation.value !== undefined && !hasOpenCodeConfigPath(lowestPrecedenceSource.content, operation.path))
|
||||
if (operations.length > 0) {
|
||||
const updatedText = applyOpenCodeConfigPathOperations(lowestPrecedenceSource.rawContent, operations)
|
||||
OpenCodeConfigSchema.parse(parseJsonc(updatedText))
|
||||
await writeFileAtomic(lowestPrecedenceSource.path, updatedText, { mode: await existingFileMode(lowestPrecedenceSource.path) })
|
||||
}
|
||||
await rm(legacyPath, { force: true })
|
||||
logger.info(`Folded legacy OpenCode config ${legacyPath} into ${lowestPrecedenceSource.path} and archived it to ${archivePath}`)
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to fold legacy OpenCode config ${legacyPath}:`, error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function pruneHealthWatchDirectory(dirPath: string): Promise<void> {
|
||||
try {
|
||||
const entries = await readdir(dirPath, { withFileTypes: true })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export function buildGhEnvPluginSource(): string {
|
||||
export function buildGhEnvPluginSource(id: string): string {
|
||||
return `const TTL_MS = 5000
|
||||
let cache = new Map()
|
||||
|
||||
@@ -26,13 +26,13 @@ async function fetchGhEnv(cwd) {
|
||||
}
|
||||
}
|
||||
|
||||
export default async function () {
|
||||
return {
|
||||
'shell.env': async (input, output) => {
|
||||
const env = await fetchGhEnv(input.cwd)
|
||||
Object.assign(output.env, env)
|
||||
},
|
||||
}
|
||||
export default {
|
||||
id: '${id}',
|
||||
async setup(ctx) {
|
||||
await ctx.shell.hook('create.before', async (event) => {
|
||||
Object.assign(event.env, await fetchGhEnv(event.cwd))
|
||||
})
|
||||
},
|
||||
}
|
||||
`
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function getOpenCodeHome(): string {
|
||||
return process.env.HOME ?? '/home/node'
|
||||
}
|
||||
@@ -6,11 +6,17 @@ import { Database as SQLiteDatabase } from 'bun:sqlite'
|
||||
import { getConfigPath, getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
|
||||
LEGACY_OPENCODE_CONFIG_SOURCE_NAME,
|
||||
OPENCODE_CONFIG_SOURCE_NAMES,
|
||||
isOpenCodeConfigSourceName,
|
||||
selectPreferredOpenCodeConfigSourceName,
|
||||
} from '@opencode-manager/shared'
|
||||
import { parseOpenCodeConfigContent, restoreOpenCodeConfigSnapshot, serializeOpenCodeConfigSourceSnapshot, withOpenCodeConfigLock } from './opencode-config-file'
|
||||
import {
|
||||
parseOpenCodeConfigContent,
|
||||
restoreOpenCodeConfigSnapshot,
|
||||
serializeOpenCodeConfigSourceSnapshot,
|
||||
toOpenCodeConfigRestorableSourceName,
|
||||
withOpenCodeConfigLock,
|
||||
} from './opencode-config-file'
|
||||
import { captureLastKnownGoodOpenCodeConfig } from './opencode-config-apply'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent } from './file-operations'
|
||||
import type { SettingsService } from './settings'
|
||||
@@ -68,7 +74,7 @@ function getExistingConfigSourcePaths(): string[] {
|
||||
if (explicitPath && existsSync(path.resolve(explicitPath))) {
|
||||
return [path.resolve(explicitPath)]
|
||||
}
|
||||
return OPENCODE_CONFIG_SOURCE_NAMES
|
||||
return [...OPENCODE_CONFIG_SOURCE_NAMES, LEGACY_OPENCODE_CONFIG_SOURCE_NAME]
|
||||
.map(name => path.join(os.homedir(), '.config', 'opencode', name))
|
||||
.filter(candidate => existsSync(candidate))
|
||||
}
|
||||
@@ -181,7 +187,7 @@ async function importOpenCodeConfigFromSources(sourcePaths: string[], settingsSe
|
||||
const configDir = getConfigPath()
|
||||
const sources = await Promise.all(sourcePaths.map(async sourcePath => {
|
||||
const basename = path.basename(sourcePath)
|
||||
const name = isOpenCodeConfigSourceName(basename) ? basename : DEFAULT_OPENCODE_CONFIG_SOURCE_NAME
|
||||
const name = toOpenCodeConfigRestorableSourceName(basename) ?? DEFAULT_OPENCODE_CONFIG_SOURCE_NAME
|
||||
const rawContent = await readFileContent(sourcePath)
|
||||
if (!parseOpenCodeConfigContent(rawContent).isValid) {
|
||||
throw new Error('Importable OpenCode config is invalid')
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { spawnSync } from 'child_process'
|
||||
import { createWriteStream, promises as fs, readdirSync } from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { Readable } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import type { ReadableStream as WebReadableStream } from 'stream/web'
|
||||
import {
|
||||
buildOpenCodeReleaseAsset,
|
||||
compareOpenCodeVersions,
|
||||
describeUnsupportedOpenCodeVersion,
|
||||
isStableOpenCodeVersion,
|
||||
isSupportedOpenCodeVersion,
|
||||
normalizeOpenCodeVersion,
|
||||
parseOpenCodeVersionOutput,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
import { getOpenCodeHome } from './opencode-home'
|
||||
|
||||
const OPENCODE_REGISTRY_URL = 'https://registry.npmjs.org/@opencode/cli'
|
||||
const OPENCODE_VERSION_CACHE_TTL_MS = 5 * 60 * 1000
|
||||
const OPENCODE_MUSL_LOADER_PREFIX = 'ld-musl-'
|
||||
|
||||
export class OpenCodeInstallError extends Error {
|
||||
readonly swapStarted: boolean
|
||||
|
||||
constructor(message: string, swapStarted: boolean, options?: ErrorOptions) {
|
||||
super(message, options)
|
||||
this.name = 'OpenCodeInstallError'
|
||||
this.swapStarted = swapStarted
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenCodeInstallTarget {
|
||||
platform: NodeJS.Platform
|
||||
arch: string
|
||||
musl: boolean
|
||||
}
|
||||
|
||||
export interface OpenCodeRelease {
|
||||
version: string
|
||||
publishedAt: string | null
|
||||
}
|
||||
|
||||
export interface InstallOpenCodeOptions {
|
||||
fetch?: typeof fetch
|
||||
homeDirectory?: string
|
||||
target?: OpenCodeInstallTarget
|
||||
}
|
||||
|
||||
export interface OpenCodeRegistryOptions {
|
||||
fetch?: typeof fetch
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface OpenCodeRegistry {
|
||||
versions?: Record<string, unknown>
|
||||
time?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface CachedOpenCodeReleases {
|
||||
releases: OpenCodeRelease[]
|
||||
fetchedAt: number
|
||||
}
|
||||
|
||||
let cachedOpenCodeReleases: CachedOpenCodeReleases | null = null
|
||||
|
||||
export function resolveOpenCodeBinaryPath(homeDirectory: string): string {
|
||||
return path.join(homeDirectory, '.opencode', 'bin', 'opencode')
|
||||
}
|
||||
|
||||
export function resolveOpenCodeInstallTarget(): OpenCodeInstallTarget {
|
||||
return {
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
musl: process.platform === 'linux' && hasMuslLoader(),
|
||||
}
|
||||
}
|
||||
|
||||
function hasMuslLoader(): boolean {
|
||||
try {
|
||||
return readdirSync('/lib').some((entry) => entry.startsWith(OPENCODE_MUSL_LOADER_PREFIX))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isInstallableOpenCodeVersion(version: string): boolean {
|
||||
return isStableOpenCodeVersion(version) && isSupportedOpenCodeVersion(version)
|
||||
}
|
||||
|
||||
async function fetchOpenCodeRegistryJson<T>(fetchFn: typeof fetch, url: string): Promise<T> {
|
||||
const response = await fetchFn(url)
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch OpenCode releases: registry responded with HTTP ${response.status}`)
|
||||
}
|
||||
return await response.json() as T
|
||||
}
|
||||
|
||||
export function clearOpenCodeVersionCache(): void {
|
||||
cachedOpenCodeReleases = null
|
||||
}
|
||||
|
||||
export async function listOpenCodeVersions(options: OpenCodeRegistryOptions = {}): Promise<OpenCodeRelease[]> {
|
||||
const now = (options.now ?? Date.now)()
|
||||
if (cachedOpenCodeReleases && now - cachedOpenCodeReleases.fetchedAt < OPENCODE_VERSION_CACHE_TTL_MS) {
|
||||
return cachedOpenCodeReleases.releases
|
||||
}
|
||||
|
||||
const registry = await fetchOpenCodeRegistryJson<OpenCodeRegistry>(options.fetch ?? fetch, OPENCODE_REGISTRY_URL)
|
||||
const publishedTimes = registry.time ?? {}
|
||||
const releases = Object.keys(registry.versions ?? {})
|
||||
.filter(isInstallableOpenCodeVersion)
|
||||
.map((version) => ({
|
||||
version,
|
||||
publishedAt: typeof publishedTimes[version] === 'string' ? publishedTimes[version] as string : null,
|
||||
}))
|
||||
.sort((left, right) => compareOpenCodeVersions(right.version, left.version))
|
||||
|
||||
cachedOpenCodeReleases = { releases, fetchedAt: now }
|
||||
return releases
|
||||
}
|
||||
|
||||
async function downloadToFile(response: Response, filePath: string): Promise<void> {
|
||||
if (!response.body) throw new Error('OpenCode download returned an empty body')
|
||||
await pipeline(Readable.fromWeb(response.body as WebReadableStream<Uint8Array>), createWriteStream(filePath))
|
||||
}
|
||||
|
||||
export async function installOpenCodeVersion(
|
||||
version: string,
|
||||
options: InstallOpenCodeOptions = {},
|
||||
): Promise<string> {
|
||||
const requestedVersion = normalizeOpenCodeVersion(version)
|
||||
if (!isInstallableOpenCodeVersion(requestedVersion)) {
|
||||
throw new OpenCodeInstallError(`${describeUnsupportedOpenCodeVersion(version)}; refusing to install it`, false)
|
||||
}
|
||||
|
||||
const fetchFn = options.fetch ?? fetch
|
||||
const homeDirectory = options.homeDirectory ?? getOpenCodeHome()
|
||||
const asset = buildOpenCodeReleaseAsset(requestedVersion, options.target ?? resolveOpenCodeInstallTarget())
|
||||
const binaryPath = resolveOpenCodeBinaryPath(homeDirectory)
|
||||
const stagingDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'opencode-install-'))
|
||||
|
||||
let swapStarted = false
|
||||
|
||||
try {
|
||||
const archivePath = path.join(stagingDirectory, asset.archive === 'zip' ? 'opencode.zip' : 'opencode.tar.gz')
|
||||
const response = await fetchFn(asset.url)
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download OpenCode ${requestedVersion} from ${asset.url}: HTTP ${response.status}`)
|
||||
}
|
||||
await downloadToFile(response, archivePath)
|
||||
|
||||
const extraction = asset.archive === 'zip'
|
||||
? spawnSync('unzip', ['-o', archivePath, '-d', stagingDirectory], { encoding: 'utf8' })
|
||||
: spawnSync('tar', ['-xzf', archivePath, '-C', stagingDirectory], { encoding: 'utf8' })
|
||||
if (extraction.error) {
|
||||
throw new Error(`Failed to extract the OpenCode ${requestedVersion} archive: ${extraction.error.message}`)
|
||||
}
|
||||
if (extraction.status !== 0) {
|
||||
throw new Error(`Failed to extract the OpenCode ${requestedVersion} archive: ${extraction.stderr || extraction.stdout}`)
|
||||
}
|
||||
|
||||
const stagedBinaryPath = path.join(stagingDirectory, 'opencode')
|
||||
await fs.chmod(stagedBinaryPath, 0o755)
|
||||
|
||||
const probe = spawnSync(stagedBinaryPath, ['--version'], { encoding: 'utf8' })
|
||||
const detectedVersion = parseOpenCodeVersionOutput(`${probe.stdout ?? ''}${probe.stderr ?? ''}`)
|
||||
if (detectedVersion !== requestedVersion) {
|
||||
throw new Error(`Downloaded OpenCode binary reports ${detectedVersion ?? 'no version'}; expected ${requestedVersion}`)
|
||||
}
|
||||
|
||||
const binDirectory = path.dirname(binaryPath)
|
||||
await mkdirSafe(binDirectory)
|
||||
const pendingPath = path.join(binDirectory, `.opencode.ocm-tmp-${process.pid}-${Date.now()}`)
|
||||
swapStarted = true
|
||||
try {
|
||||
await fs.copyFile(stagedBinaryPath, pendingPath)
|
||||
await fs.chmod(pendingPath, 0o755)
|
||||
await fs.rename(pendingPath, binaryPath)
|
||||
} catch (error) {
|
||||
await fs.rm(pendingPath, { force: true }).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
|
||||
return binaryPath
|
||||
} catch (error) {
|
||||
if (error instanceof OpenCodeInstallError) throw error
|
||||
throw new OpenCodeInstallError(error instanceof Error ? error.message : String(error), swapStarted, { cause: error })
|
||||
} finally {
|
||||
await fs.rm(stagingDirectory, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
},
|
||||
})
|
||||
})
|
||||
},
|
||||
}
|
||||
`
|
||||
}
|
||||
@@ -1,20 +1,11 @@
|
||||
import type { ModelInfo, ModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { formatOpenCodeModelRef, openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
interface OpenCodeConfigResponse {
|
||||
model?: string
|
||||
}
|
||||
|
||||
interface OpenCodeProviderResponse {
|
||||
providers?: Array<{
|
||||
id: string
|
||||
models?: Record<string, unknown>
|
||||
}>
|
||||
default?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface ResolvedOpenCodeModel {
|
||||
providerID: string
|
||||
modelID: string
|
||||
id: string
|
||||
variant?: string
|
||||
model: string
|
||||
}
|
||||
|
||||
@@ -27,94 +18,52 @@ function normalizeModelCandidate(model: string | null | undefined): string | nul
|
||||
return normalized ? normalized : null
|
||||
}
|
||||
|
||||
function parseModel(model: string): ResolvedOpenCodeModel | null {
|
||||
const [providerID, ...modelParts] = model.split('/')
|
||||
const modelID = modelParts.join('/')
|
||||
|
||||
if (!providerID || !modelID) {
|
||||
return null
|
||||
}
|
||||
|
||||
function toResolvedModel(ref: ModelRef): ResolvedOpenCodeModel {
|
||||
return {
|
||||
providerID,
|
||||
modelID,
|
||||
model: `${providerID}/${modelID}`,
|
||||
providerID: ref.providerID,
|
||||
id: ref.id,
|
||||
...(ref.variant ? { variant: ref.variant } : {}),
|
||||
model: formatOpenCodeModelRef(ref),
|
||||
}
|
||||
}
|
||||
|
||||
function buildAvailableModels(response: OpenCodeProviderResponse): Set<string> {
|
||||
const availableModels = new Set<string>()
|
||||
|
||||
for (const provider of response.providers ?? []) {
|
||||
for (const modelID of Object.keys(provider.models ?? {})) {
|
||||
availableModels.add(`${provider.id}/${modelID}`)
|
||||
}
|
||||
}
|
||||
|
||||
return availableModels
|
||||
}
|
||||
|
||||
function uniqueCandidates(candidates: Array<string | null | undefined>): string[] {
|
||||
const normalizedCandidates = candidates
|
||||
.map(normalizeModelCandidate)
|
||||
.filter((candidate): candidate is string => candidate !== null)
|
||||
|
||||
return [...new Set(normalizedCandidates)]
|
||||
}
|
||||
|
||||
async function fetchOpenCodeConfig(client: OpenCodeClient, directory?: string): Promise<OpenCodeConfigResponse> {
|
||||
return client.getJson<OpenCodeConfigResponse>('/config', { directory })
|
||||
}
|
||||
|
||||
async function fetchOpenCodeProviders(client: OpenCodeClient, directory?: string): Promise<OpenCodeProviderResponse> {
|
||||
return client.getJson<OpenCodeProviderResponse>('/config/providers', { directory })
|
||||
function findAvailable(models: ModelInfo[], ref: ModelRef): ModelInfo | undefined {
|
||||
return models.find((model) => model.providerID === ref.providerID && model.id === ref.id)
|
||||
}
|
||||
|
||||
export async function resolveOpenCodeModel(
|
||||
client: OpenCodeClient,
|
||||
directory: string | undefined,
|
||||
directory: string,
|
||||
options?: {
|
||||
preferredModel?: string | null
|
||||
},
|
||||
): Promise<ResolvedOpenCodeModel> {
|
||||
const [config, providersResponse] = await Promise.all([
|
||||
fetchOpenCodeConfig(client, directory),
|
||||
fetchOpenCodeProviders(client, directory),
|
||||
const location = openCodeLocation(directory)
|
||||
const [modelsResponse, defaultResponse] = await Promise.all([
|
||||
client.api.model.list(location),
|
||||
client.api.model.default(location),
|
||||
])
|
||||
const models = modelsResponse.data
|
||||
|
||||
const availableModels = buildAvailableModels(providersResponse)
|
||||
const defaultModels = providersResponse.default ?? {}
|
||||
const candidates = uniqueCandidates([options?.preferredModel, config.model])
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (availableModels.has(candidate)) {
|
||||
const parsedCandidate = parseModel(candidate)
|
||||
if (parsedCandidate) {
|
||||
return parsedCandidate
|
||||
}
|
||||
const preferred = normalizeModelCandidate(options?.preferredModel)
|
||||
if (preferred) {
|
||||
const parsedPreferred = parseOpenCodeModelRef(preferred)
|
||||
if (parsedPreferred && findAvailable(models, parsedPreferred)) {
|
||||
return toResolvedModel(parsedPreferred)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [providerID, modelID] of Object.entries(defaultModels)) {
|
||||
const model = `${providerID}/${modelID}`
|
||||
if (availableModels.has(model)) {
|
||||
return {
|
||||
providerID,
|
||||
modelID,
|
||||
model,
|
||||
}
|
||||
const defaultModel = defaultResponse.data
|
||||
if (defaultModel) {
|
||||
const defaultRef: ModelRef = { providerID: defaultModel.providerID, id: defaultModel.id }
|
||||
if (findAvailable(models, defaultRef)) {
|
||||
return toResolvedModel(defaultRef)
|
||||
}
|
||||
}
|
||||
|
||||
for (const provider of providersResponse.providers ?? []) {
|
||||
const firstModelID = Object.keys(provider.models ?? {})[0]
|
||||
if (firstModelID) {
|
||||
return {
|
||||
providerID: provider.id,
|
||||
modelID: firstModelID,
|
||||
model: `${provider.id}/${firstModelID}`,
|
||||
}
|
||||
}
|
||||
const fallback = models.find((model) => model.enabled)
|
||||
if (fallback) {
|
||||
return toResolvedModel({ providerID: fallback.providerID, id: fallback.id })
|
||||
}
|
||||
|
||||
throw new Error('No configured OpenCode models are available')
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import { lstat, realpath } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { OPENCODE_CONFIG_SOURCE_NAMES } from '@opencode-manager/shared'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { existingFileMode, mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import { withOpenCodeConfigLock } from './opencode-config-file'
|
||||
import { getOpenCodeHome } from './opencode-home'
|
||||
import { getOpenCodePluginDir } from './opencode/plugin-registry'
|
||||
import {
|
||||
isRecord,
|
||||
@@ -16,10 +18,6 @@ const PLUGIN_CONFIG_BACKUP_SUFFIX = '.ocm-sandbox-backup'
|
||||
const QUARANTINE_CONFLICT_SUFFIX = '.ocm-conflict'
|
||||
const QUARANTINE_MANIFEST_FILENAME = '.ocm-quarantine-manifest.json'
|
||||
|
||||
export function getOpenCodePluginDiscoveryHome(): string {
|
||||
return process.env.HOME ?? '/home/node'
|
||||
}
|
||||
|
||||
type QuarantineManifestEntry = {
|
||||
original: string
|
||||
order: number
|
||||
@@ -31,17 +29,17 @@ type QuarantineManifest = {
|
||||
}
|
||||
|
||||
function getPluginDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
const home = getOpenCodeHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'plugin'),
|
||||
getOpenCodePluginDir(configHome),
|
||||
path.join(configHome, 'opencode', 'plugins'),
|
||||
path.join(home, '.opencode', 'plugin'),
|
||||
path.join(home, '.opencode', 'plugins'),
|
||||
]
|
||||
}
|
||||
|
||||
function getToolDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
const home = getOpenCodeHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'tool'),
|
||||
path.join(configHome, 'opencode', 'tools'),
|
||||
@@ -51,13 +49,10 @@ function getToolDirs(configHome: string): string[] {
|
||||
}
|
||||
|
||||
function getNativeOpenCodeConfigPaths(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
const home = getOpenCodeHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'opencode.json'),
|
||||
path.join(configHome, 'opencode', 'opencode.jsonc'),
|
||||
path.join(configHome, 'opencode', 'config.json'),
|
||||
path.join(home, '.opencode', 'opencode.json'),
|
||||
path.join(home, '.opencode', 'opencode.jsonc'),
|
||||
...OPENCODE_CONFIG_SOURCE_NAMES.map((name) => path.join(configHome, 'opencode', name)),
|
||||
...OPENCODE_CONFIG_SOURCE_NAMES.map((name) => path.join(home, '.opencode', name)),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -79,7 +74,7 @@ function getManagedConfigPaths(): string[] {
|
||||
dirs.push(override)
|
||||
}
|
||||
return [...new Set(dirs)].flatMap((dir) =>
|
||||
['opencode.json', 'opencode.jsonc'].map((file) => path.join(dir, file)),
|
||||
OPENCODE_CONFIG_SOURCE_NAMES.map((file) => path.join(dir, file)),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { OpenCodeRestartCoordinator, type ActiveSessionsProvider, type ResumableSession } from './opencode-restart-coordinator'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
function createFakeActiveSessionsProvider(overrides: Partial<ActiveSessionsProvider> = {}): ActiveSessionsProvider {
|
||||
return {
|
||||
getActiveSessions: vi.fn(() => ({})),
|
||||
isSubagentSession: vi.fn(() => false),
|
||||
getScheduledSessionIds: vi.fn(() => new Set<string>()),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('OpenCodeRestartCoordinator', () => {
|
||||
let client: OpenCodeClient
|
||||
let activeSessions: ActiveSessionsProvider
|
||||
let coordinator: OpenCodeRestartCoordinator
|
||||
|
||||
beforeEach(() => {
|
||||
client = createStubOpenCodeClient()
|
||||
activeSessions = createFakeActiveSessionsProvider()
|
||||
coordinator = new OpenCodeRestartCoordinator(client, activeSessions)
|
||||
})
|
||||
|
||||
describe('captureResumableSessions', () => {
|
||||
it('excludes subagent sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 'sub1'],
|
||||
'/b': ['s2'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub1')
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns empty array when no active sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('filters out only subagent sessions, keeps all others', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/x': ['a1', 'a2', 'sub_x'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id.startsWith('sub_'))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([
|
||||
{ sessionID: 'a1', directory: '/x' },
|
||||
{ sessionID: 'a2', directory: '/x' },
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes scheduled sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 'sched1'],
|
||||
})
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([{ sessionID: 's1', directory: '/a' }])
|
||||
})
|
||||
|
||||
it('excludes both subagent and scheduled sessions simultaneously', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/p': ['manual', 'sub', 'sched'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub')
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched']))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([{ sessionID: 'manual', directory: '/p' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('runWithResume', () => {
|
||||
it('aborts captured sessions, restarts, then resumes when healthy', async () => {
|
||||
const events: string[] = []
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockImplementation(async (opts) => {
|
||||
events.push(`forward:${opts.path}`)
|
||||
return new Response(null, { status: 200 })
|
||||
})
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1'],
|
||||
'/b': ['s2'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => {
|
||||
events.push('restart')
|
||||
return true
|
||||
})
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Assert interleaved ordering: aborts → restart → resumes
|
||||
expect(events).toEqual([
|
||||
'forward:/session/s1/abort',
|
||||
'forward:/session/s2/abort',
|
||||
'restart',
|
||||
'forward:/session/s1/prompt_async',
|
||||
'forward:/session/s2/prompt_async',
|
||||
])
|
||||
|
||||
// Aborts called first for both sessions
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/abort',
|
||||
directory: '/b',
|
||||
})
|
||||
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
|
||||
// Forward was called 4 times: 2 aborts (calls 1-2) + 2 resumes (calls 3-4)
|
||||
expect(forward).toHaveBeenCalledTimes(4)
|
||||
expect(forward).toHaveBeenNthCalledWith(3, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/prompt_async',
|
||||
directory: '/a',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(4, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/prompt_async',
|
||||
directory: '/b',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['s1', 's2'] })
|
||||
})
|
||||
|
||||
it('does NOT resume when restart returns unhealthy', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => false)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Aborts still happen
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
|
||||
// No prompt_async calls
|
||||
const promptAsyncCalls = forward.mock.calls.filter(
|
||||
(call: unknown[]) => (call[0] as { path: string }).path.includes('prompt_async'),
|
||||
)
|
||||
expect(promptAsyncCalls).toHaveLength(0)
|
||||
|
||||
expect(result).toEqual({ healthy: false, resumedSessionIDs: [] })
|
||||
})
|
||||
|
||||
it('with no active sessions performs restart only', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
expect(forward).not.toHaveBeenCalled()
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: [] })
|
||||
})
|
||||
|
||||
it('does not abort or resume scheduled sessions', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['manual1', 'sched1'],
|
||||
})
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Only manual1 should be aborted and resumed — 2 forward calls total
|
||||
expect(forward).toHaveBeenCalledTimes(2)
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/manual1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/manual1/prompt_async',
|
||||
directory: '/a',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['manual1'] })
|
||||
})
|
||||
|
||||
it('is best-effort: per-session errors are swallowed and other sessions still processed', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
// Aborts all succeed, but resume for s2 fails
|
||||
forward
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s1
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s2
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s3
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s1
|
||||
.mockRejectedValueOnce(new Error('connection refused')) // resume s2 fails
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s3
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 's2', 's3'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
expect(result.healthy).toBe(true)
|
||||
expect(result.resumedSessionIDs).toEqual(['s1', 's3'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('abortSessions', () => {
|
||||
it('does not throw when forward rejects and continues processing remaining sessions', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward
|
||||
.mockRejectedValueOnce(new Error('timeout'))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
|
||||
await expect(
|
||||
coordinator.abortSessions([
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
]),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
expect(forward).toHaveBeenCalledTimes(2)
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/abort',
|
||||
directory: '/b',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('resumeSessions', () => {
|
||||
it('only includes sessions with ok response', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 404 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
|
||||
const sessions: ResumableSession[] = [
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
{ sessionID: 's3', directory: '/c' },
|
||||
]
|
||||
|
||||
const result = await coordinator.resumeSessions(sessions)
|
||||
|
||||
expect(result).toEqual(['s1', 's3'])
|
||||
})
|
||||
|
||||
it('does not throw when forward rejects', async () => {
|
||||
vi.mocked(client.forward).mockRejectedValue(new Error('timeout'))
|
||||
|
||||
const result = await coordinator.resumeSessions([{ sessionID: 's1', directory: '/a' }])
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,89 +0,0 @@
|
||||
import { logger } from '../utils/logger'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
export interface ActiveSessionsProvider {
|
||||
getActiveSessions(): Record<string, string[]>
|
||||
isSubagentSession(sessionId: string): boolean
|
||||
getScheduledSessionIds(): Set<string>
|
||||
}
|
||||
|
||||
export interface ResumableSession {
|
||||
sessionID: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
export interface RestartWithResumeResult {
|
||||
healthy: boolean
|
||||
resumedSessionIDs: string[]
|
||||
}
|
||||
|
||||
export class OpenCodeRestartCoordinator {
|
||||
constructor(
|
||||
private readonly client: OpenCodeClient,
|
||||
private readonly activeSessions: ActiveSessionsProvider,
|
||||
) {}
|
||||
|
||||
captureResumableSessions(): ResumableSession[] {
|
||||
const active = this.activeSessions.getActiveSessions()
|
||||
const scheduled = this.activeSessions.getScheduledSessionIds()
|
||||
const sessions: ResumableSession[] = []
|
||||
|
||||
for (const [directory, sessionIDs] of Object.entries(active)) {
|
||||
for (const sessionID of sessionIDs) {
|
||||
if (!this.activeSessions.isSubagentSession(sessionID) && !scheduled.has(sessionID)) {
|
||||
sessions.push({ sessionID, directory })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sessions
|
||||
}
|
||||
|
||||
async abortSessions(sessions: ResumableSession[]): Promise<void> {
|
||||
await Promise.allSettled(
|
||||
sessions.map(async (s) => {
|
||||
try {
|
||||
await this.client.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${s.sessionID}/abort`,
|
||||
directory: s.directory,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to abort session ${s.sessionID}: ${error}`)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async resumeSessions(sessions: ResumableSession[]): Promise<string[]> {
|
||||
const results = await Promise.allSettled(
|
||||
sessions.map(async (s) => {
|
||||
try {
|
||||
const response = await this.client.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${s.sessionID}/prompt_async`,
|
||||
directory: s.directory,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
return response.ok ? s.sessionID : null
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to resume session ${s.sessionID}: ${error}`)
|
||||
return null
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return results
|
||||
.map((result) => (result.status === 'fulfilled' ? result.value : null))
|
||||
.filter((sessionID): sessionID is string => sessionID !== null)
|
||||
}
|
||||
|
||||
async runWithResume(restart: () => Promise<boolean>): Promise<RestartWithResumeResult> {
|
||||
const sessions = this.captureResumableSessions()
|
||||
await this.abortSessions(sessions)
|
||||
const healthy = await restart()
|
||||
const resumedSessionIDs = healthy ? await this.resumeSessions(sessions) : []
|
||||
return { healthy, resumedSessionIDs }
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,27 @@
|
||||
import { opencodeServerManager, ConfigReloadError } from './opencode-single-server'
|
||||
import { readOpenCodeConfigFile } from './opencode-config-file'
|
||||
import { sseAggregator } from './sse-aggregator'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import type { OpenCodeOperationReason, OpenCodeSupervisor } from './opencode-supervisor'
|
||||
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
|
||||
|
||||
let restartCoordinator: OpenCodeRestartCoordinator | null = null
|
||||
|
||||
/**
|
||||
* Registers the process-wide restart coordinator so every restart path can
|
||||
* abort and resume in-flight sessions consistently. Passing null disables
|
||||
* resume (used by tests and pre-initialization paths).
|
||||
*/
|
||||
export function setOpenCodeRestartCoordinator(coordinator: OpenCodeRestartCoordinator | null): void {
|
||||
restartCoordinator = coordinator
|
||||
export interface ActiveSessionsSource {
|
||||
getActiveSessions(): Record<string, string[]>
|
||||
isSubagentSession(sessionId: string): boolean
|
||||
getScheduledSessionIds(): Set<string>
|
||||
}
|
||||
|
||||
export function getOpenCodeRestartCoordinator(): OpenCodeRestartCoordinator | null {
|
||||
return restartCoordinator
|
||||
export interface ActiveUserSession {
|
||||
sessionID: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
export function listActiveUserSessions(source: ActiveSessionsSource = sseAggregator): ActiveUserSession[] {
|
||||
const scheduled = source.getScheduledSessionIds()
|
||||
return Object.entries(source.getActiveSessions()).flatMap(([directory, sessionIDs]) =>
|
||||
sessionIDs
|
||||
.filter((sessionID) => !source.isSubagentSession(sessionID) && !scheduled.has(sessionID))
|
||||
.map((sessionID) => ({ sessionID, directory })),
|
||||
)
|
||||
}
|
||||
|
||||
function restartFailureError(): Error {
|
||||
@@ -23,55 +29,26 @@ function restartFailureError(): Error {
|
||||
return new Error(startupError ?? 'OpenCode server restart did not complete successfully')
|
||||
}
|
||||
|
||||
async function performRestart(supervisor: OpenCodeSupervisor | undefined, reason: OpenCodeOperationReason): Promise<boolean> {
|
||||
async function restartServer(supervisor: OpenCodeSupervisor | undefined, reason: OpenCodeOperationReason): Promise<boolean> {
|
||||
if (supervisor) {
|
||||
return (await supervisor.restart(reason)).healthy
|
||||
}
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
return healthy
|
||||
return opencodeServerManager.checkHealth()
|
||||
}
|
||||
|
||||
/**
|
||||
* The single entry point for restarting the OpenCode server. Every restart
|
||||
* trigger (manual restart, version upgrade/install, workspace config change,
|
||||
* restart-sensitive config saves) routes through here so that interrupted user
|
||||
* sessions are aborted and resumed uniformly when a coordinator is registered.
|
||||
* A full process restart drops in-flight sessions; resuming re-issues a
|
||||
* "continue" prompt once the server is healthy again.
|
||||
*/
|
||||
export async function restartOpenCode(
|
||||
supervisor?: OpenCodeSupervisor,
|
||||
reason: OpenCodeOperationReason = 'settings_restart',
|
||||
): Promise<{ resumedSessionIDs: string[] }> {
|
||||
if (restartCoordinator) {
|
||||
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor, reason))
|
||||
if (!result.healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
return { resumedSessionIDs: result.resumedSessionIDs }
|
||||
): Promise<void> {
|
||||
const healthy = await restartServer(supervisor, reason)
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
if (supervisor) {
|
||||
const status = await supervisor.restart(reason)
|
||||
if (!status.healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
} else {
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
}
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
|
||||
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
|
||||
export async function assertValidOpenCodeConfig(): Promise<void> {
|
||||
const config = await readOpenCodeConfigFile()
|
||||
if (!config) {
|
||||
throw new ConfigReloadError('No OpenCode global configuration files found')
|
||||
@@ -79,5 +56,9 @@ export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Pro
|
||||
if (!config.isValid) {
|
||||
throw new ConfigReloadError('OpenCode global configuration is invalid', config.validationIssues)
|
||||
}
|
||||
return restartOpenCode(supervisor, 'settings_reload')
|
||||
}
|
||||
|
||||
export async function reloadOpenCodeConfig(openCodeClient: OpenCodeClient): Promise<void> {
|
||||
await assertValidOpenCodeConfig()
|
||||
await openCodeClient.api.location.reload()
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
|
||||
import {
|
||||
SANDBOX_FORWARDED_ENV_NAMES,
|
||||
SANDBOX_SHELL_ENV_HOST_SHELL,
|
||||
SANDBOX_SHELL_ENV_WORKDIR,
|
||||
} from './sandbox/shell-shim'
|
||||
|
||||
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
|
||||
|
||||
export function buildSandboxPluginSource(shellShimPath: string): string {
|
||||
export function buildSandboxPluginSource(id: string, shellShimPath: string, serviceSettingsPath: string): string {
|
||||
return `import { existsSync } from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
|
||||
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
|
||||
var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)}
|
||||
var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)}
|
||||
var ENV_HOST_SHELL = ${JSON.stringify(SANDBOX_SHELL_ENV_HOST_SHELL)}
|
||||
var FORWARDED_ENV_NAMES = ${JSON.stringify(SANDBOX_FORWARDED_ENV_NAMES)}
|
||||
var SERVICE_SETTINGS_PATH = path.resolve(${JSON.stringify(serviceSettingsPath)})
|
||||
var SERVICE_SETTINGS_DIRECTORY = path.dirname(SERVICE_SETTINGS_PATH)
|
||||
var SERVICE_SETTINGS_DENIED = 'OpenCode Manager denies access to its service settings file (service.json), which holds the OpenCode server password.'
|
||||
|
||||
function isEnforced() {
|
||||
return process.env.OCM_SANDBOX_ENFORCED === 'true'
|
||||
@@ -25,6 +27,59 @@ function unavailable(reason) {
|
||||
return new Error(SANDBOX_UNAVAILABLE_PREFIX + reason)
|
||||
}
|
||||
|
||||
function isWithin(directory, target) {
|
||||
var relative = path.relative(directory, target)
|
||||
return relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function globDirectory(resource) {
|
||||
var trimmed = resource
|
||||
while (trimmed.length > 0 && trimmed.charAt(trimmed.length - 1) === '*') {
|
||||
trimmed = trimmed.slice(0, -1)
|
||||
}
|
||||
while (trimmed.length > 1 && (trimmed.charAt(trimmed.length - 1) === '/' || trimmed.charAt(trimmed.length - 1) === path.sep)) {
|
||||
trimmed = trimmed.slice(0, -1)
|
||||
}
|
||||
return trimmed.length === 0 ? path.parse(SERVICE_SETTINGS_PATH).root : trimmed
|
||||
}
|
||||
|
||||
function resourceResolvesToServiceSettings(resource) {
|
||||
return typeof resource === 'string' && resource.length > 0 && path.resolve(resource) === SERVICE_SETTINGS_PATH
|
||||
}
|
||||
|
||||
function externalDirectoryTargetsServiceSettings(resource) {
|
||||
if (typeof resource !== 'string' || resource.length === 0) return false
|
||||
return isWithin(path.resolve(globDirectory(resource)), SERVICE_SETTINGS_DIRECTORY)
|
||||
}
|
||||
|
||||
function absolutePathTargetsServiceSettings(value) {
|
||||
if (typeof value !== 'string' || value.length === 0 || !path.isAbsolute(value)) return false
|
||||
var resolved = path.resolve(value)
|
||||
return resolved === SERVICE_SETTINGS_PATH || isWithin(resolved, SERVICE_SETTINGS_DIRECTORY)
|
||||
}
|
||||
|
||||
function metadataTargetsServiceSettings(metadata) {
|
||||
if (metadata === null || typeof metadata !== 'object') return false
|
||||
return absolutePathTargetsServiceSettings(metadata.path)
|
||||
|| (metadata.root !== metadata.path && absolutePathTargetsServiceSettings(metadata.root))
|
||||
}
|
||||
|
||||
function deniesServiceSettings(event) {
|
||||
if (event.action === 'grep' || event.action === 'glob') {
|
||||
return metadataTargetsServiceSettings(event.metadata)
|
||||
}
|
||||
if (!Array.isArray(event.resources)) return false
|
||||
for (var index = 0; index < event.resources.length; index += 1) {
|
||||
var resource = event.resources[index]
|
||||
if (event.action === 'external_directory') {
|
||||
if (externalDirectoryTargetsServiceSettings(resource)) return true
|
||||
} else if (resourceResolvesToServiceSettings(resource)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function lockAccessor(target, key, value) {
|
||||
try {
|
||||
Object.defineProperty(target, key, {
|
||||
@@ -86,46 +141,44 @@ async function planSandboxShell(cwd) {
|
||||
return plan
|
||||
}
|
||||
|
||||
export default async function () {
|
||||
var hostShell
|
||||
|
||||
return {
|
||||
config: async (cfg) => {
|
||||
if (!isEnforced()) return
|
||||
var configured = cfg.shell
|
||||
if (typeof configured === 'string' && configured.length > 0 && configured !== SHELL_SHIM_PATH) {
|
||||
hostShell = configured
|
||||
}
|
||||
lockAccessor(cfg, 'shell', SHELL_SHIM_PATH)
|
||||
},
|
||||
'shell.env': async (input, output) => {
|
||||
if (!isEnforced() || typeof input.callID !== 'string' || input.callID.length === 0) {
|
||||
if (hostShell !== undefined) {
|
||||
output.env[ENV_HOST_SHELL] = hostShell
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!existsSync(SHELL_SHIM_PATH)) {
|
||||
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
|
||||
}
|
||||
var plan = await planSandboxShell(input.cwd)
|
||||
if (plan.env !== null && typeof plan.env === 'object') {
|
||||
for (var name of FORWARDED_ENV_NAMES) {
|
||||
if (typeof plan.env[name] === 'string') {
|
||||
output.env[name] = plan.env[name]
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!lockAccessor(output.env, ENV_WORKDIR, plan.workdir)) {
|
||||
throw unavailable('sandbox enforcement could not pin the sandbox working directory; aborting before the command runs on the host')
|
||||
}
|
||||
},
|
||||
'tool.execute.after': async (input, output) => {
|
||||
if (!isEnforced() || input.tool !== 'bash') return
|
||||
if (output.metadata === null || typeof output.metadata !== 'object') return
|
||||
output.metadata.sandbox = true
|
||||
},
|
||||
async function pinSandboxShell(event) {
|
||||
if (!existsSync(SHELL_SHIM_PATH)) {
|
||||
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
|
||||
}
|
||||
var plan = await planSandboxShell(event.cwd)
|
||||
if (plan.env !== null && typeof plan.env === 'object') {
|
||||
for (var name of FORWARDED_ENV_NAMES) {
|
||||
if (typeof plan.env[name] === 'string') {
|
||||
event.env[name] = plan.env[name]
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!lockAccessor(event, 'shell', SHELL_SHIM_PATH)) {
|
||||
throw unavailable('sandbox enforcement could not pin the sandbox shell; aborting before the command runs on the host')
|
||||
}
|
||||
if (!lockAccessor(event.env, ENV_WORKDIR, plan.workdir)) {
|
||||
throw unavailable('sandbox enforcement could not pin the sandbox working directory; aborting before the command runs on the host')
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
id: '${id}',
|
||||
async setup(ctx) {
|
||||
await ctx.permission.hook('evaluate', (event) => {
|
||||
if (!isEnforced() || !deniesServiceSettings(event)) return
|
||||
event.effect = 'deny'
|
||||
event.message = SERVICE_SETTINGS_DENIED
|
||||
})
|
||||
await ctx.shell.hook('create.before', async (event) => {
|
||||
if (!isEnforced()) return
|
||||
await pinSandboxShell(event)
|
||||
})
|
||||
await ctx.tool.hook('execute.after', (event) => {
|
||||
if (!isEnforced() || event.tool !== 'shell' || event.status !== 'completed') return
|
||||
if (event.result === null || typeof event.result !== 'object') return
|
||||
event.result = { ...event.result, metadata: { ...(event.result.metadata ?? {}), sandbox: true } }
|
||||
})
|
||||
},
|
||||
}
|
||||
`
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import { getConfigPath } from '@opencode-manager/shared/config/env'
|
||||
import { writeFileAtomic } from '../utils/fs-safe'
|
||||
|
||||
const OPENCODE_APP_DIRECTORY = 'opencode'
|
||||
const OPENCODE_SERVICE_FILENAME = 'service.json'
|
||||
|
||||
export const OPENCODE_SERVICE_SERVE_ARGS = ['serve', '--service'] as const
|
||||
|
||||
export type OpenCodeServiceEnv = {
|
||||
XDG_CONFIG_HOME: string
|
||||
XDG_STATE_HOME: string
|
||||
}
|
||||
|
||||
export function getOpenCodeServiceSettingsPath(): string {
|
||||
return path.join(getConfigPath(), OPENCODE_SERVICE_FILENAME)
|
||||
}
|
||||
|
||||
export function getOpenCodeServiceRegistrationPath(env: OpenCodeServiceEnv): string {
|
||||
return path.join(env.XDG_STATE_HOME, OPENCODE_APP_DIRECTORY, OPENCODE_SERVICE_FILENAME)
|
||||
}
|
||||
|
||||
export async function writeOpenCodeServiceSettings(configDirectory: string, password: string): Promise<void> {
|
||||
await writeFileAtomic(path.join(configDirectory, OPENCODE_SERVICE_FILENAME), `${JSON.stringify({ password }, null, 2)}\n`, { mode: 0o600 })
|
||||
}
|
||||
|
||||
export async function prepareOpenCodeServiceLaunch(env: OpenCodeServiceEnv, password: string): Promise<void> {
|
||||
await fs.rm(getOpenCodeServiceRegistrationPath(env), { force: true })
|
||||
await writeOpenCodeServiceSettings(getConfigPath(), password)
|
||||
}
|
||||
@@ -15,7 +15,14 @@ import {
|
||||
parseSSHHost
|
||||
} from '../utils/ssh-key-manager'
|
||||
import { decryptSecret } from '../utils/crypto'
|
||||
import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@opencode-manager/shared'
|
||||
import { BLOCKED_SERVER_ENV_KEYS } from '@opencode-manager/shared'
|
||||
import {
|
||||
OPENCODE_PINNED_VERSION,
|
||||
describeUnsupportedOpenCodeVersion,
|
||||
isSupportedOpenCodeVersion,
|
||||
parseOpenCodeVersionOutput,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { resolveOpenCodeBinaryPath } from './opencode-installer'
|
||||
import { SettingsService } from './settings'
|
||||
import {
|
||||
getWorkspacePath,
|
||||
@@ -27,37 +34,31 @@ import {
|
||||
ENV,
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import {
|
||||
readOpenCodeConfigFile,
|
||||
} from './opencode-config-file'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { installManagedPlugins } from './opencode/plugin-registry'
|
||||
import { getOpenCodePluginDiscoveryHome, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
|
||||
import { getOpenCodeHome } from './opencode-home'
|
||||
import { restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
|
||||
import { resolveProcessIdentityProvider } from './opencode/process-identity'
|
||||
import { SandboxRuntimeService } from './sandbox/runtime'
|
||||
import { CredentialProvider } from './credential-provider'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import { createProcessLogForwarder } from '../utils/log-buffer'
|
||||
import { OPENCODE_SERVICE_SERVE_ARGS, prepareOpenCodeServiceLaunch } from './opencode-service-mode'
|
||||
|
||||
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
|
||||
const PROCESS_EXIT_GRACE_MS = 2000
|
||||
const STARTUP_HEALTH_TIMEOUT_MS = 30000
|
||||
const PROCESS_SIGTERM_GRACE_MS = 10000
|
||||
const PROCESS_SIGKILL_CONFIRM_MS = 2000
|
||||
const PROCESS_EXIT_POLL_MS = 50
|
||||
const CHILD_STATE_MARKER_REFRESH_MS = 60000
|
||||
const DEPRECATED_PLUGIN_PACKAGES = ['opencode-openai-codex-auth', 'opencode-copilot-auth']
|
||||
|
||||
type StartupValidationIssue = {
|
||||
path: string
|
||||
message: string
|
||||
}
|
||||
|
||||
type OpenCodePluginOptions = Record<string, unknown>
|
||||
type OpenCodePluginSpec = string | [string, OpenCodePluginOptions]
|
||||
|
||||
export class ConfigReloadError extends Error {
|
||||
validationIssues: StartupValidationIssue[]
|
||||
|
||||
@@ -82,51 +83,12 @@ export class OpenCodeOperationBusyError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
function parseStartupValidationIssues(stderrOutput: string): StartupValidationIssue[] {
|
||||
const match = stderrOutput.match(/ZodError:\s*(\[[\s\S]*?\])(?:\n\s+at |$)/)
|
||||
if (!match?.[1]) {
|
||||
return []
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]) as Array<{ path?: unknown; message?: unknown }>
|
||||
return parsed
|
||||
.map((issue) => ({
|
||||
path: Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : 'root',
|
||||
message: typeof issue.message === 'string' ? issue.message : 'Invalid value',
|
||||
}))
|
||||
.filter((issue) => issue.message)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function formatStartupError(stderrOutput: string, fallback: string): string {
|
||||
const validationIssues = parseStartupValidationIssues(stderrOutput)
|
||||
if (validationIssues.length === 0) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const summary = validationIssues
|
||||
.slice(0, 8)
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
|
||||
const remainder = validationIssues.length > 8
|
||||
? ` (${validationIssues.length - 8} more issue${validationIssues.length - 8 === 1 ? '' : 's'})`
|
||||
: ''
|
||||
|
||||
return `OpenCode config validation failed: ${summary}${remainder}`
|
||||
}
|
||||
|
||||
// Helper getters to ensure values are computed at runtime (not module load time)
|
||||
// This allows proper mocking in tests
|
||||
const getOpenCodeServerDirectory = () => getWorkspacePath()
|
||||
const getOpenCodeConfigPath = () => getOpenCodeConfigFilePath()
|
||||
const getOpenCodeServerPort = () => ENV.OPENCODE.PORT
|
||||
const getOpenCodeServerHost = () => ENV.OPENCODE.HOST
|
||||
const getOpenCodeServerPublicUrl = () => ENV.OPENCODE.PUBLIC_URL
|
||||
const getOpenCodeServerUsername = () => ENV.OPENCODE.SERVER_USERNAME
|
||||
|
||||
function resolveManagerMicrosandboxEnv(): Record<string, string> {
|
||||
const env: Record<string, string> = {
|
||||
@@ -266,7 +228,7 @@ async function removeChildStateMarker(): Promise<void> {
|
||||
export function resolveOpenCodeExecutable(): string | null {
|
||||
const candidates = [
|
||||
process.env.OPENCODE_BIN,
|
||||
path.join(getOpenCodePluginDiscoveryHome(), '.opencode', 'bin', 'opencode'),
|
||||
resolveOpenCodeBinaryPath(getOpenCodeHome()),
|
||||
'/usr/local/bin/opencode',
|
||||
'/opt/opencode/bin/opencode',
|
||||
].filter((candidate): candidate is string => typeof candidate === 'string' && candidate.length > 0)
|
||||
@@ -364,7 +326,7 @@ class OpenCodeServerManager {
|
||||
return this.opInProgress
|
||||
}
|
||||
|
||||
async start(retryAfterPluginInstall = true, allowNested = false): Promise<void> {
|
||||
async start(allowNested = false): Promise<void> {
|
||||
const acquired = this.acquireOp()
|
||||
if (!acquired && !allowNested) {
|
||||
throw new OpenCodeOperationBusyError()
|
||||
@@ -395,9 +357,9 @@ class OpenCodeServerManager {
|
||||
)
|
||||
}
|
||||
try {
|
||||
await this.terminateAttestedPredecessor(PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminateAttestedPredecessor()
|
||||
if (existingProcesses.length > 0) {
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminatePortOwners(existingProcesses)
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
this.failNonRecoverable(
|
||||
@@ -424,13 +386,6 @@ class OpenCodeServerManager {
|
||||
|
||||
const password = this.getResolvedPassword()
|
||||
const openCodeServerHost = getOpenCodeServerHost()
|
||||
const isExposed = openCodeServerHost !== '127.0.0.1' && openCodeServerHost !== 'localhost'
|
||||
if (isExposed && !password) {
|
||||
const msg = `OPENCODE_HOST=${openCodeServerHost} exposes the OpenCode server externally but no password is configured. Set OPENCODE_SERVER_PASSWORD env var or configure a password via Settings → OpenCode → Server Auth.`
|
||||
this.lastStartupError = msg
|
||||
logger.error(msg)
|
||||
throw new Error(msg)
|
||||
}
|
||||
|
||||
let credentialProvider: CredentialProvider | null = null
|
||||
let gitIdentityEnv: Record<string, string> = {}
|
||||
@@ -441,11 +396,7 @@ class OpenCodeServerManager {
|
||||
const settingsService = new SettingsService(this.db)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitCredentials = credentialProvider.getGitCredentials()
|
||||
const disabledDefaultEnvVars = new Set(settings.preferences.disabledDefaultServerEnvVars || [])
|
||||
const rawEnvVars = [
|
||||
...DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultEnvVars.has(envVar.key)),
|
||||
...(settings.preferences.serverEnvVars || []),
|
||||
]
|
||||
const rawEnvVars = settings.preferences.serverEnvVars || []
|
||||
if (rawEnvVars.length > 0) {
|
||||
userEnvVars = Object.fromEntries(
|
||||
rawEnvVars
|
||||
@@ -494,10 +445,10 @@ class OpenCodeServerManager {
|
||||
}
|
||||
let replacingExistingServer = false
|
||||
if (sandboxEnforced) {
|
||||
await this.terminateAttestedPredecessor(PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminateAttestedPredecessor()
|
||||
if (existingProcesses.length > 0) {
|
||||
logger.warn('Sandbox enforcement enabled: killing existing OpenCode server to guarantee a sandboxed startup')
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminatePortOwners(existingProcesses)
|
||||
replacingExistingServer = true
|
||||
}
|
||||
} else if (existingProcesses.length > 0) {
|
||||
@@ -506,7 +457,7 @@ class OpenCodeServerManager {
|
||||
if (healthy) {
|
||||
if (isDevelopment) {
|
||||
logger.warn('Development mode: Killing existing server for hot reload')
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminatePortOwners(existingProcesses)
|
||||
replacingExistingServer = true
|
||||
} else {
|
||||
const childState = await readChildStateMarker()
|
||||
@@ -522,17 +473,17 @@ class OpenCodeServerManager {
|
||||
return
|
||||
}
|
||||
logger.warn(`Existing OpenCode server on port ${openCodeServerPort} is not attested as a matching unenforced child; terminating it to guarantee consistent sandbox enforcement`)
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminatePortOwners(existingProcesses)
|
||||
replacingExistingServer = true
|
||||
}
|
||||
} else {
|
||||
logger.warn('Killing unhealthy OpenCode server')
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
await this.terminatePortOwners(existingProcesses)
|
||||
replacingExistingServer = true
|
||||
}
|
||||
}
|
||||
|
||||
await this.reconcileExitedChildMarker(PROCESS_EXIT_GRACE_MS)
|
||||
await this.reconcileExitedChildMarker()
|
||||
|
||||
const openCodeServerDirectory = getOpenCodeServerDirectory()
|
||||
const openCodeConfigPath = getOpenCodeConfigPath()
|
||||
@@ -587,7 +538,12 @@ class OpenCodeServerManager {
|
||||
|
||||
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
|
||||
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
await this.fetchVersion()
|
||||
if (this.version && !this.isVersionSupported()) {
|
||||
this.failNonRecoverable(
|
||||
`${describeUnsupportedOpenCodeVersion(this.version)}. Install a supported version from Settings → OpenCode.`,
|
||||
)
|
||||
}
|
||||
await this.resetAgentTmpDirectory()
|
||||
const pluginConfigHome = getOpenCodeConfigHome()
|
||||
try {
|
||||
@@ -606,9 +562,6 @@ class OpenCodeServerManager {
|
||||
}
|
||||
logger.warn('Failed to install a generated OpenCode plugin (sandboxing is disabled):', error)
|
||||
}
|
||||
const configuredPlugins = await this.getConfiguredPlugins()
|
||||
await this.installConfiguredPlugins(configuredPlugins)
|
||||
const configuredPluginCount = configuredPlugins.length
|
||||
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
|
||||
|
||||
let stderrOutput = ''
|
||||
@@ -616,49 +569,56 @@ class OpenCodeServerManager {
|
||||
const microsandboxEnv = resolveManagerMicrosandboxEnv()
|
||||
|
||||
const cleanEnv = { ...process.env }
|
||||
delete cleanEnv.OPENCODE_PASSWORD
|
||||
delete cleanEnv.OPENCODE_SERVER_PASSWORD
|
||||
delete cleanEnv.OPENCODE_RUN_ID
|
||||
delete cleanEnv.OPENCODE_PROCESS_ROLE
|
||||
delete cleanEnv.OPENCODE_PID
|
||||
delete cleanEnv.OPENCODE
|
||||
delete cleanEnv.OPENCODE_PURE
|
||||
delete cleanEnv.OPENCODE_CONFIG
|
||||
delete cleanEnv.OPENCODE_CONFIG_DIR
|
||||
delete cleanEnv.OPENCODE_CONFIG_CONTENT
|
||||
delete userEnvVars.OPENCODE_CONFIG
|
||||
delete userEnvVars.OPENCODE_CONFIG_DIR
|
||||
delete userEnvVars.OPENCODE_CONFIG_CONTENT
|
||||
|
||||
const serverEnv = {
|
||||
...cleanEnv,
|
||||
...userEnvVars,
|
||||
...microsandboxEnv,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
...(this.db
|
||||
? {
|
||||
OCM_INTERNAL_API_URL: `http://localhost:${ENV.SERVER.PORT}/api/internal`,
|
||||
OCM_INTERNAL_TOKEN: getOrCreateInternalToken(this.db),
|
||||
}
|
||||
: {}),
|
||||
OCM_SANDBOX_ENFORCED: sandboxEnforced ? 'true' : 'false',
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
XDG_DATA_HOME: getOpenCodeStateHome(),
|
||||
XDG_STATE_HOME: getOpenCodeStateHome(),
|
||||
XDG_CONFIG_HOME: getOpenCodeConfigHome(),
|
||||
TMPDIR: getOpenCodeTmpHome(),
|
||||
}
|
||||
|
||||
try {
|
||||
await prepareOpenCodeServiceLaunch(serverEnv, password)
|
||||
} catch (error) {
|
||||
const message = `Failed to prepare the OpenCode service settings: ${error instanceof Error ? error.message : String(error)}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
this.serverProcess = spawn(
|
||||
openCodeExecutable,
|
||||
['serve', '--port', openCodeServerPort.toString(), '--hostname', openCodeServerHost],
|
||||
[...OPENCODE_SERVICE_SERVE_ARGS, '--port', openCodeServerPort.toString(), '--hostname', openCodeServerHost],
|
||||
{
|
||||
cwd: openCodeServerDirectory,
|
||||
detached: !isDevelopment,
|
||||
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...cleanEnv,
|
||||
...userEnvVars,
|
||||
...microsandboxEnv,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
...(this.db
|
||||
? {
|
||||
OCM_INTERNAL_API_URL: `http://localhost:${ENV.SERVER.PORT}/api/internal`,
|
||||
OCM_INTERNAL_TOKEN: getOrCreateInternalToken(this.db),
|
||||
}
|
||||
: {}),
|
||||
OCM_SANDBOX_ENFORCED: sandboxEnforced ? 'true' : 'false',
|
||||
OPENCODE_PURE: 'false',
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
XDG_DATA_HOME: getOpenCodeStateHome(),
|
||||
XDG_STATE_HOME: getOpenCodeStateHome(),
|
||||
XDG_CONFIG_HOME: getOpenCodeConfigHome(),
|
||||
TMPDIR: getOpenCodeTmpHome(),
|
||||
...(getOpenCodeServerPublicUrl() ? { OPENCODE_PUBLIC_URL: getOpenCodeServerPublicUrl() } : {}),
|
||||
...(password
|
||||
? {
|
||||
OPENCODE_SERVER_PASSWORD: password,
|
||||
OPENCODE_SERVER_USERNAME: getOpenCodeServerUsername(),
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
env: serverEnv,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -690,8 +650,7 @@ class OpenCodeServerManager {
|
||||
this.stopChildStateMarkerRefresh()
|
||||
}
|
||||
if (code !== null && code !== 0) {
|
||||
const fallback = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
|
||||
this.lastStartupError = formatStartupError(stderrOutput, fallback)
|
||||
this.lastStartupError = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
|
||||
logger.error('OpenCode server process exited:', this.lastStartupError)
|
||||
} else if (signal) {
|
||||
this.lastStartupError = `Server terminated by signal ${signal}`
|
||||
@@ -740,18 +699,9 @@ class OpenCodeServerManager {
|
||||
|
||||
logger.info(`OpenCode server started with PID ${this.serverPid}`)
|
||||
|
||||
const healthTimeoutMs = configuredPluginCount > 0 ? 120000 : 30000
|
||||
const healthy = await this.waitForHealth(healthTimeoutMs)
|
||||
const healthy = await this.waitForHealth(STARTUP_HEALTH_TIMEOUT_MS)
|
||||
if (!healthy) {
|
||||
const fallback = `Server failed to become healthy after ${Math.round(healthTimeoutMs / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
|
||||
this.lastStartupError = formatStartupError(stderrOutput, fallback)
|
||||
if (configuredPluginCount > 0 && retryAfterPluginInstall) {
|
||||
logger.warn(`OpenCode server did not become healthy after installing ${configuredPluginCount} configured plugin(s); restarting once`)
|
||||
await this.stop(true)
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
await this.start(false, true)
|
||||
return
|
||||
}
|
||||
this.lastStartupError = `Server failed to become healthy after ${Math.round(STARTUP_HEALTH_TIMEOUT_MS / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
|
||||
throw new Error('OpenCode server failed to become healthy')
|
||||
}
|
||||
|
||||
@@ -785,10 +735,6 @@ class OpenCodeServerManager {
|
||||
await this.fetchVersion()
|
||||
if (this.version) {
|
||||
logger.info(`OpenCode version: ${this.version}`)
|
||||
if (!this.isVersionSupported()) {
|
||||
logger.warn(`OpenCode version ${this.version} is below minimum required version ${MIN_OPENCODE_VERSION}`)
|
||||
logger.warn('Some features like MCP management may not work correctly')
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.releaseOp(acquired)
|
||||
@@ -803,7 +749,7 @@ class OpenCodeServerManager {
|
||||
|
||||
try {
|
||||
if (!this.serverPid) {
|
||||
await this.reconcileExitedChildMarker(PROCESS_EXIT_GRACE_MS)
|
||||
await this.reconcileExitedChildMarker()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -840,7 +786,6 @@ class OpenCodeServerManager {
|
||||
await this.terminateAndConfirm(
|
||||
pid,
|
||||
groupTarget,
|
||||
PROCESS_EXIT_GRACE_MS,
|
||||
'OpenCode server',
|
||||
'retained live processes after SIGTERM and SIGKILL; refusing to complete the stop while host-executed processes may survive',
|
||||
)
|
||||
@@ -876,141 +821,6 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeOpencodeBinDirectory(): Promise<void> {
|
||||
const binDir = path.join(getOpenCodeStateHome(), 'opencode', 'bin')
|
||||
|
||||
const packageJsonPath = path.join(binDir, 'package.json')
|
||||
|
||||
try {
|
||||
await mkdirSafe(binDir)
|
||||
|
||||
const packageJsonExists = await fs.access(packageJsonPath)
|
||||
.then(() => true)
|
||||
.catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return false
|
||||
throw error
|
||||
})
|
||||
|
||||
if (!packageJsonExists) {
|
||||
try {
|
||||
execSync('bun init -y', {
|
||||
cwd: binDir,
|
||||
stdio: 'inherit',
|
||||
timeout: 30000
|
||||
})
|
||||
logger.info('OpenCode bin directory initialized successfully')
|
||||
} catch (error) {
|
||||
logger.error('bun init failed:', error)
|
||||
throw new Error(`bun init failed: ${error}`)
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize OpenCode bin directory:', error)
|
||||
}
|
||||
}
|
||||
|
||||
private isPathPluginSpec(spec: string): boolean {
|
||||
return spec.startsWith('file://') || spec.startsWith('.') || path.isAbsolute(spec)
|
||||
}
|
||||
|
||||
private getPluginInstallSpec(spec: string): string {
|
||||
if (spec.startsWith('@')) {
|
||||
const slashIndex = spec.indexOf('/')
|
||||
return slashIndex !== -1 && spec.indexOf('@', slashIndex + 1) === -1 ? `${spec}@latest` : spec
|
||||
}
|
||||
return spec.includes('@') ? spec : `${spec}@latest`
|
||||
}
|
||||
|
||||
private getPluginPackageName(spec: string): string {
|
||||
if (spec.startsWith('@')) {
|
||||
const slashIndex = spec.indexOf('/')
|
||||
if (slashIndex === -1) return spec
|
||||
const versionIndex = spec.indexOf('@', slashIndex + 1)
|
||||
return versionIndex === -1 ? spec : spec.slice(0, versionIndex)
|
||||
}
|
||||
const versionIndex = spec.indexOf('@')
|
||||
return versionIndex === -1 ? spec : spec.slice(0, versionIndex)
|
||||
}
|
||||
|
||||
private sanitizeNpmCacheSegment(spec: string): string {
|
||||
if (process.platform !== 'win32') return spec
|
||||
return Array.from(spec, (char) => /[<>:"|?*]/.test(char) || char.charCodeAt(0) < 32 ? '_' : char).join('')
|
||||
}
|
||||
|
||||
private getPluginSpecifier(plugin: OpenCodePluginSpec): string {
|
||||
return Array.isArray(plugin) ? plugin[0] : plugin
|
||||
}
|
||||
|
||||
private isOpenCodePluginSpec(plugin: unknown): plugin is OpenCodePluginSpec {
|
||||
if (typeof plugin === 'string') return plugin.trim().length > 0
|
||||
if (!Array.isArray(plugin) || plugin.length !== 2 || typeof plugin[0] !== 'string' || plugin[0].trim().length === 0) return false
|
||||
const options = plugin[1]
|
||||
return options !== null && typeof options === 'object' && !Array.isArray(options)
|
||||
}
|
||||
|
||||
private async getConfiguredPlugins(): Promise<OpenCodePluginSpec[]> {
|
||||
try {
|
||||
const file = await readOpenCodeConfigFile()
|
||||
const plugin = file?.content.plugin
|
||||
if (!Array.isArray(plugin)) return []
|
||||
return plugin
|
||||
.filter((entry): entry is OpenCodePluginSpec => this.isOpenCodePluginSpec(entry))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private async installConfiguredPlugins(plugins: OpenCodePluginSpec[]): Promise<void> {
|
||||
const npmPlugins = plugins
|
||||
.map((plugin) => this.getPluginSpecifier(plugin))
|
||||
.filter((plugin) => !this.isPathPluginSpec(plugin) && !DEPRECATED_PLUGIN_PACKAGES.some((pkg) => plugin.includes(pkg)))
|
||||
if (npmPlugins.length === 0) return
|
||||
|
||||
const cacheHome = process.env.XDG_CACHE_HOME || path.join(process.env.HOME || '/home/node', '.cache')
|
||||
logger.info(`Pre-installing ${npmPlugins.length} configured OpenCode plugin(s)`)
|
||||
|
||||
for (const plugin of npmPlugins) {
|
||||
const installSpec = this.getPluginInstallSpec(plugin)
|
||||
const packageName = this.getPluginPackageName(plugin)
|
||||
const installDir = path.join(cacheHome, 'opencode', 'packages', this.sanitizeNpmCacheSegment(installSpec))
|
||||
const packageJsonPath = path.join(installDir, 'node_modules', packageName, 'package.json')
|
||||
|
||||
try {
|
||||
await fs.access(packageJsonPath)
|
||||
logger.info(`OpenCode plugin already installed: ${plugin}`)
|
||||
continue
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as NodeJS.ErrnoException).code : ''
|
||||
if (errorCode !== 'ENOENT') {
|
||||
logger.warn(`Could not check OpenCode plugin install state for ${plugin}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
await mkdirSafe(installDir)
|
||||
if (!await fs.access(path.join(installDir, 'package.json')).then(() => true).catch(() => false)) {
|
||||
const init = spawnSync('bun', ['init', '-y'], { cwd: installDir, encoding: 'utf8', timeout: 30000 })
|
||||
if (init.status !== 0) {
|
||||
logger.warn(`Failed to initialize OpenCode plugin cache for ${plugin}: ${init.stderr || init.stdout}`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const result = spawnSync('bun', ['add', '--ignore-scripts', installSpec], { cwd: installDir, encoding: 'utf8', timeout: PLUGIN_INSTALL_TIMEOUT_MS })
|
||||
if (result.status === 0) {
|
||||
logger.info(`Installed OpenCode plugin: ${plugin}`)
|
||||
continue
|
||||
}
|
||||
|
||||
if (result.error) {
|
||||
logger.warn(`Failed to install OpenCode plugin ${plugin}: ${result.error.message}`)
|
||||
continue
|
||||
}
|
||||
|
||||
logger.warn(`Failed to install OpenCode plugin ${plugin}: ${result.stderr || result.stdout}`)
|
||||
}
|
||||
}
|
||||
|
||||
async restart(): Promise<void> {
|
||||
const acquired = this.acquireOp()
|
||||
if (!acquired) {
|
||||
@@ -1020,7 +830,7 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
logger.info('Restarting OpenCode server (full process restart)')
|
||||
await this.stop(true)
|
||||
await this.start(false, true)
|
||||
await this.start(true)
|
||||
} finally {
|
||||
this.releaseOp(acquired)
|
||||
}
|
||||
@@ -1035,12 +845,12 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
getMinVersion(): string {
|
||||
return MIN_OPENCODE_VERSION
|
||||
return OPENCODE_PINNED_VERSION
|
||||
}
|
||||
|
||||
isVersionSupported(): boolean {
|
||||
if (!this.version) return false
|
||||
return compareVersions(this.version, MIN_OPENCODE_VERSION) >= 0
|
||||
return isSupportedOpenCodeVersion(this.version)
|
||||
}
|
||||
|
||||
getLastStartupError(): string | null {
|
||||
@@ -1085,22 +895,15 @@ class OpenCodeServerManager {
|
||||
advanceDurableRestartGeneration(this.db)
|
||||
}
|
||||
|
||||
async reinitializeBinDirectory(): Promise<void> {
|
||||
logger.info('Reinitializing OpenCode bin directory')
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
if (!this.openCodeClient) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const response = await this.openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/global/health',
|
||||
await this.openCodeClient.api.server.info({
|
||||
signal: AbortSignal.timeout(ENV.TIMEOUTS.HEALTH_CHECK_TIMEOUT_MS),
|
||||
})
|
||||
return response.ok
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
@@ -1110,9 +913,9 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
const executable = resolveOpenCodeExecutable() ?? 'opencode'
|
||||
const result = spawnSync(executable, ['--version'], { encoding: 'utf8' })
|
||||
const match = `${result.stdout ?? ''}${result.stderr ?? ''}`.match(/(\d+\.\d+\.\d+)/)
|
||||
if (match && match[1]) {
|
||||
this.version = match[1]
|
||||
const version = parseOpenCodeVersionOutput(`${result.stdout ?? ''}${result.stderr ?? ''}`)
|
||||
if (version) {
|
||||
this.version = version
|
||||
return this.version
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -1160,15 +963,14 @@ class OpenCodeServerManager {
|
||||
private async terminateAndConfirm(
|
||||
pid: number,
|
||||
groupTarget: number | null,
|
||||
graceMs: number,
|
||||
context: string,
|
||||
failurePhrase: string,
|
||||
): Promise<void> {
|
||||
this.signalProcessOrGroup(pid, groupTarget, 'SIGTERM')
|
||||
const exited = await this.waitForProcessOrGroupExit(pid, groupTarget, graceMs)
|
||||
const exited = await this.waitForProcessOrGroupExit(pid, groupTarget, PROCESS_SIGTERM_GRACE_MS)
|
||||
if (exited) return
|
||||
this.signalProcessOrGroup(pid, groupTarget, 'SIGKILL')
|
||||
const killed = await this.waitForProcessOrGroupExit(pid, groupTarget, graceMs)
|
||||
const killed = await this.waitForProcessOrGroupExit(pid, groupTarget, PROCESS_SIGKILL_CONFIRM_MS)
|
||||
if (!killed) {
|
||||
const message = `${context} (PID ${pid}${groupTarget !== null ? `, process group ${groupTarget}` : ''}) ${failurePhrase}`
|
||||
this.lastStartupError = message
|
||||
@@ -1177,7 +979,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async terminatePortOwners(processes: Array<{pid: number}>, graceMs: number): Promise<void> {
|
||||
private async terminatePortOwners(processes: Array<{pid: number}>): Promise<void> {
|
||||
const targets = processes.map((proc) => {
|
||||
const pgid = readProcessGroupId(proc.pid)
|
||||
return { pid: proc.pid, groupTarget: pgid !== null && pgid === proc.pid ? proc.pid : null }
|
||||
@@ -1187,7 +989,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
const survivors: number[] = []
|
||||
for (const target of targets) {
|
||||
const exited = await this.waitForProcessOrGroupExit(target.pid, target.groupTarget, graceMs)
|
||||
const exited = await this.waitForProcessOrGroupExit(target.pid, target.groupTarget, PROCESS_SIGKILL_CONFIRM_MS)
|
||||
if (!exited) {
|
||||
survivors.push(target.pid)
|
||||
}
|
||||
@@ -1229,7 +1031,7 @@ class OpenCodeServerManager {
|
||||
return { pid, groupTarget, pidAttested, groupAttested }
|
||||
}
|
||||
|
||||
private async terminateAttestedPredecessor(graceMs: number): Promise<void> {
|
||||
private async terminateAttestedPredecessor(): Promise<void> {
|
||||
const marker = await readChildStateMarker()
|
||||
if (marker === null) return
|
||||
const target = this.resolveAttestedProcessTarget(marker)
|
||||
@@ -1249,13 +1051,12 @@ class OpenCodeServerManager {
|
||||
await this.terminateAndConfirm(
|
||||
target.pid,
|
||||
target.groupTarget,
|
||||
graceMs,
|
||||
'Previous OpenCode server process',
|
||||
'retained live processes after SIGTERM and SIGKILL; refusing to start an enforced server while host-executed processes may survive',
|
||||
)
|
||||
}
|
||||
|
||||
private async reconcileExitedChildMarker(graceMs: number): Promise<void> {
|
||||
private async reconcileExitedChildMarker(): Promise<void> {
|
||||
this.isHealthy = false
|
||||
this.stopChildStateMarkerRefresh()
|
||||
const marker = await readChildStateMarker()
|
||||
@@ -1268,7 +1069,6 @@ class OpenCodeServerManager {
|
||||
await this.terminateAndConfirm(
|
||||
target.pid,
|
||||
target.groupTarget,
|
||||
graceMs,
|
||||
'OpenCode server',
|
||||
'retained live processes after SIGTERM and SIGKILL; refusing to complete the stop while host-executed processes may survive',
|
||||
)
|
||||
@@ -1290,7 +1090,6 @@ class OpenCodeServerManager {
|
||||
await this.terminateAndConfirm(
|
||||
target.pid,
|
||||
target.groupTarget,
|
||||
graceMs,
|
||||
'Previous OpenCode server process group',
|
||||
'retained live processes after SIGTERM and SIGKILL; refusing to replace the child state marker while host-executed processes may survive',
|
||||
)
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { buildOpenCodeBasicAuth } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export type OpenCodePasswordResolver = () => string | Promise<string>
|
||||
|
||||
export function getOpenCodeBasicAuthHeader(): string | null
|
||||
export function getOpenCodeBasicAuthHeader(password: string): string | null
|
||||
export function getOpenCodeBasicAuthHeader(passwordResolver: OpenCodePasswordResolver): Promise<string | null>
|
||||
export function getOpenCodeBasicAuthHeader(source?: string | OpenCodePasswordResolver): string | null | Promise<string | null> {
|
||||
export function getOpenCodeBasicAuthHeader(password: string): string
|
||||
export function getOpenCodeBasicAuthHeader(passwordResolver: OpenCodePasswordResolver): Promise<string>
|
||||
export function getOpenCodeBasicAuthHeader(source: string | OpenCodePasswordResolver): string | Promise<string> {
|
||||
if (typeof source === 'function') {
|
||||
return Promise.resolve(source()).then((password) => getOpenCodeBasicAuthHeader(password))
|
||||
return Promise.resolve(source()).then((password) => buildOpenCodeBasicAuth(password))
|
||||
}
|
||||
|
||||
const password = source ?? ENV.OPENCODE.SERVER_PASSWORD
|
||||
const username = ENV.OPENCODE.SERVER_USERNAME
|
||||
if (!password) return null
|
||||
const token = Buffer.from(`${username}:${password}`).toString('base64')
|
||||
return `Basic ${token}`
|
||||
return buildOpenCodeBasicAuth(source)
|
||||
}
|
||||
@@ -1,41 +1,12 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './upstream'
|
||||
|
||||
export interface ForwardRequest {
|
||||
method: string
|
||||
path: string
|
||||
body?: string
|
||||
headers?: Record<string, string>
|
||||
directory?: string
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface JsonRequestOptions {
|
||||
directory?: string
|
||||
headers?: Record<string, string>
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export class UpstreamError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
public readonly bodyText: string,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `OpenCode upstream returned ${status}`)
|
||||
this.name = 'UpstreamError'
|
||||
}
|
||||
}
|
||||
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream'
|
||||
|
||||
export interface OpenCodeClient {
|
||||
forward(req: ForwardRequest): Promise<Response>
|
||||
readonly api: OpenCodeApi
|
||||
forwardRaw(request: Request): Promise<Response>
|
||||
getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T>
|
||||
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
|
||||
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
|
||||
deleteProviderAuth(providerId: string): Promise<boolean>
|
||||
}
|
||||
|
||||
export type OpenCodeClientHost = string | (() => string)
|
||||
@@ -48,7 +19,14 @@ export interface FetchOpenCodeClientConfig {
|
||||
}
|
||||
|
||||
export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
constructor(private readonly config: FetchOpenCodeClientConfig) {}
|
||||
readonly api: OpenCodeApi
|
||||
|
||||
constructor(private readonly config: FetchOpenCodeClientConfig) {
|
||||
this.api = createOpenCodeApi({
|
||||
baseUrl: this.resolveBaseUrl(),
|
||||
fetch: ((input, init) => this.fetchWithResolvedAuth(input, init)) as typeof fetch,
|
||||
})
|
||||
}
|
||||
|
||||
private get fetchFn(): typeof fetch {
|
||||
return this.config.fetchFn ?? fetch
|
||||
@@ -63,17 +41,25 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
return this.config.basicAuth ?? ''
|
||||
}
|
||||
|
||||
return await getOpenCodeBasicAuthHeader(this.config.passwordResolver) ?? ''
|
||||
return await getOpenCodeBasicAuthHeader(this.config.passwordResolver)
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.resolveBaseUrl() + req.path)
|
||||
private async fetchWithResolvedAuth(input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> {
|
||||
const headers = new Headers(withDefaultOpenCodeDirectory(Object.fromEntries(new Headers(init?.headers))))
|
||||
const basicAuth = await this.getBasicAuth()
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
if (basicAuth) {
|
||||
headers.set('Authorization', basicAuth)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { ...(req.headers ?? {}) }
|
||||
return this.fetchFn(input, { ...init, headers })
|
||||
}
|
||||
|
||||
private async request(req: { method: string; path: string; body?: string; headers?: Record<string, string> }): Promise<Response> {
|
||||
const url = new URL(this.resolveBaseUrl() + req.path)
|
||||
|
||||
const headers: Record<string, string> = withDefaultOpenCodeDirectory({ ...(req.headers ?? {}) })
|
||||
|
||||
const basicAuth = await this.getBasicAuth()
|
||||
|
||||
if (basicAuth) {
|
||||
@@ -85,7 +71,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
method: req.method,
|
||||
headers,
|
||||
body: req.body,
|
||||
signal: req.signal,
|
||||
})
|
||||
|
||||
const filteredHeaders: Record<string, string> = {}
|
||||
@@ -120,10 +105,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
}
|
||||
}
|
||||
|
||||
async forward(req: ForwardRequest): Promise<Response> {
|
||||
return this.request(req)
|
||||
}
|
||||
|
||||
async forwardRaw(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
|
||||
@@ -151,88 +132,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
async getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T> {
|
||||
const response = await this.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
directory: opts?.directory,
|
||||
headers: opts?.headers,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(opts?.headers ?? {}),
|
||||
}
|
||||
|
||||
const response = await this.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: JSON.stringify(body),
|
||||
headers,
|
||||
directory: opts?.directory,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async setProviderAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'PUT',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Set OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to set OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async deleteProviderAuth(providerId: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'DELETE',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to delete OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(
|
||||
@@ -243,7 +142,7 @@ export function createOpenCodeClient(
|
||||
const baseUrl: OpenCodeClientHost = () => getOpenCodeUpstreamBaseUrl(resolveConfiguredHost())
|
||||
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
const basicAuth = password ? getOpenCodeBasicAuthHeader(password) : null
|
||||
|
||||
return new FetchOpenCodeClient({ baseUrl, basicAuth, passwordResolver })
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { isIntegrationNotFoundError, type OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export const INTEGRATION_READY_POLL_INTERVAL_MS = 100
|
||||
export const INTEGRATION_READY_TIMEOUT_MS = 2000
|
||||
|
||||
export type IntegrationTarget = Parameters<OpenCodeApi['integration']['get']>[0]
|
||||
|
||||
type IntegrationReader = Pick<OpenCodeApi, 'integration'>
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
async function isIntegrationAvailable(api: IntegrationReader, target: IntegrationTarget): Promise<boolean | undefined> {
|
||||
try {
|
||||
await api.integration.get(target)
|
||||
return true
|
||||
} catch (error) {
|
||||
return isIntegrationNotFoundError(error) ? false : undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForIntegration(api: IntegrationReader, target: IntegrationTarget): Promise<boolean> {
|
||||
const deadline = Date.now() + INTEGRATION_READY_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
await delay(INTEGRATION_READY_POLL_INTERVAL_MS)
|
||||
const available = await isIntegrationAvailable(api, target)
|
||||
if (available !== false) return available === true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export async function runWhenIntegrationReady<T>(
|
||||
api: IntegrationReader,
|
||||
target: IntegrationTarget,
|
||||
action: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await action()
|
||||
} catch (error) {
|
||||
if (!isIntegrationNotFoundError(error)) throw error
|
||||
if (!(await waitForIntegration(api, target))) throw error
|
||||
return await action()
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,53 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin'
|
||||
import { buildManagerToolPluginSource } from '../opencode-manager-tool-plugin'
|
||||
import { buildSandboxPluginSource } from '../opencode-sandbox-plugin'
|
||||
import { getOpenCodeServiceSettingsPath } from '../opencode-service-mode'
|
||||
import { ensureSandboxShellShim } from '../sandbox/shell-shim'
|
||||
|
||||
const MANAGED_OPENCODE_PLUGIN_IDS = {
|
||||
ghEnv: 'ocm.gh-env',
|
||||
manager: 'ocm.manager',
|
||||
sandbox: 'ocm.sandbox',
|
||||
} as const
|
||||
|
||||
type ManagedOpenCodePlugin = {
|
||||
id: string
|
||||
filename: string
|
||||
buildSource: (context: { shellShimPath: string }) => string
|
||||
buildSource: (context: { id: string; shellShimPath: string; serviceSettingsPath: string }) => string
|
||||
}
|
||||
|
||||
const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [
|
||||
{ filename: 'ocm-gh-env.js', buildSource: () => buildGhEnvPluginSource() },
|
||||
{ filename: 'ocm-manager.js', buildSource: () => buildManagerToolPluginSource() },
|
||||
{ filename: 'ocm-sandbox.js', buildSource: ({ shellShimPath }) => buildSandboxPluginSource(shellShimPath) },
|
||||
{
|
||||
id: MANAGED_OPENCODE_PLUGIN_IDS.ghEnv,
|
||||
filename: 'ocm-gh-env.js',
|
||||
buildSource: ({ id }) => buildGhEnvPluginSource(id),
|
||||
},
|
||||
{
|
||||
id: MANAGED_OPENCODE_PLUGIN_IDS.manager,
|
||||
filename: 'ocm-manager.js',
|
||||
buildSource: ({ id }) => buildManagerToolPluginSource(id),
|
||||
},
|
||||
{
|
||||
id: MANAGED_OPENCODE_PLUGIN_IDS.sandbox,
|
||||
filename: 'ocm-sandbox.js',
|
||||
buildSource: ({ id, shellShimPath, serviceSettingsPath }) => buildSandboxPluginSource(id, shellShimPath, serviceSettingsPath),
|
||||
},
|
||||
]
|
||||
|
||||
export function getOpenCodePluginDir(configHome: string): string {
|
||||
return join(configHome, 'opencode', 'plugin')
|
||||
return join(configHome, 'opencode', 'plugins')
|
||||
}
|
||||
|
||||
export async function installManagedPlugins(configHome: string): Promise<void> {
|
||||
const shellShimPath = await ensureSandboxShellShim(configHome)
|
||||
const serviceSettingsPath = getOpenCodeServiceSettingsPath()
|
||||
const dir = getOpenCodePluginDir(configHome)
|
||||
const legacyDir = join(configHome, 'opencode', 'plugin')
|
||||
for (const plugin of MANAGED_OPENCODE_PLUGINS) {
|
||||
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource({ shellShimPath }))
|
||||
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource({ id: plugin.id, shellShimPath, serviceSettingsPath }))
|
||||
await fs.rm(join(legacyDir, plugin.filename), { force: true })
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { ENV, getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
export const OPENCODE_DIRECTORY_HEADER = 'x-opencode-directory'
|
||||
|
||||
function formatOpenCodeHostForUrl(host: string): string {
|
||||
if (host.startsWith('[') && host.endsWith(']')) return host
|
||||
@@ -10,3 +12,8 @@ export function getOpenCodeUpstreamBaseUrl(hostOverride?: string | (() => string
|
||||
const normalizedHost = configuredHost === '0.0.0.0' ? '127.0.0.1' : configuredHost
|
||||
return `http://${formatOpenCodeHostForUrl(normalizedHost)}:${ENV.OPENCODE.PORT}`
|
||||
}
|
||||
|
||||
export function withDefaultOpenCodeDirectory(headers: Record<string, string>): Record<string, string> {
|
||||
const hasDirectory = Object.keys(headers).some((key) => key.toLowerCase() === OPENCODE_DIRECTORY_HEADER)
|
||||
return hasDirectory ? headers : { ...headers, [OPENCODE_DIRECTORY_HEADER]: encodeURIComponent(getWorkspacePath()) }
|
||||
}
|
||||
@@ -16,9 +16,10 @@ import { getErrorMessage } from '../utils/error-utils'
|
||||
import { sseAggregator } from './sse-aggregator'
|
||||
import { resolveProjectId, isGitMainCheckout } from './project-id-resolver'
|
||||
import { listRepos } from '../db/queries'
|
||||
import { listActiveScheduleRunWorkspaces } from '../db/schedules'
|
||||
import { listActiveScheduleRunWorktreePaths } from '../db/schedules'
|
||||
import { SettingsService } from './settings'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { canonicalPathSync, mkdirSafe } from '../utils/fs-safe'
|
||||
|
||||
const GIT_CLONE_TIMEOUT = 300000
|
||||
@@ -1162,12 +1163,17 @@ export function isRepoInUse(db: Database, repoId: number): boolean {
|
||||
return sseAggregator.getActiveDirectories().includes(repo.fullPath)
|
||||
}
|
||||
|
||||
export async function resolveRepoProjectId(openCodeClient: OpenCodeClient, directory: string): Promise<string> {
|
||||
const { project } = await openCodeClient.api.location.get(openCodeLocation(directory))
|
||||
return project.id
|
||||
}
|
||||
|
||||
export async function getSiblingRepos(
|
||||
database: Database,
|
||||
repoId: number,
|
||||
gitEnv: Record<string, string>,
|
||||
openCodeClient?: OpenCodeClient,
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined }>> {
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined; worktreeStrategy?: string }>> {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings()
|
||||
const allRepos = listRepos(database, settings.preferences.repoOrder)
|
||||
@@ -1200,88 +1206,60 @@ export async function getSiblingRepos(
|
||||
if (!openCodeClient) return repoSiblings
|
||||
|
||||
try {
|
||||
const workspaces = await openCodeClient.getJson<Array<{
|
||||
id: string
|
||||
type: string
|
||||
name: string | null
|
||||
branch: string | null
|
||||
directory: string | null
|
||||
projectID: string
|
||||
}>>('/experimental/workspace', { directory: target.fullPath })
|
||||
const projectID = await resolveRepoProjectId(openCodeClient, target.fullPath)
|
||||
const worktrees = await openCodeClient.api.worktree.list({ projectID })
|
||||
|
||||
// Normalize paths so a workspace pointing at a real repo directory can never
|
||||
// be exposed as deletable. Deleting an OpenCode workspace recursively removes
|
||||
// its directory, so the current repo directory and all known managed repo
|
||||
// directories must be excluded regardless of trailing slashes or symlinks.
|
||||
// Workspaces that are git main checkouts (not linked worktrees) are also
|
||||
// excluded so the project's origin/main repository can never be surfaced
|
||||
// as deletable.
|
||||
const knownDirectories = new Set(repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))))
|
||||
const targetDirectory = canonicalPathSync(path.resolve(target.fullPath))
|
||||
const reposRoot = canonicalPathSync(path.resolve(getReposPath()))
|
||||
const scheduleWorktreeRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
|
||||
|
||||
// Schedule runs may create their isolated worktree via the OpenCode workspace
|
||||
// API, which places it outside getScheduleWorktreesPath(). Exclude any live
|
||||
// run's workspace/worktree so an in-progress run is never surfaced as a
|
||||
// deletable Sibling during the window it exists.
|
||||
const activeRuns = listActiveScheduleRunWorkspaces(database)
|
||||
const activeRunWorkspaceIds = new Set(activeRuns.map((run) => run.workspaceId).filter((id): id is string => id !== null))
|
||||
const activeRunDirectories = new Set(
|
||||
activeRuns.map((run) => run.worktreePath).filter((p): p is string => p !== null).map((p) => canonicalPathSync(path.resolve(p))),
|
||||
listActiveScheduleRunWorktreePaths(database).map((p) => canonicalPathSync(path.resolve(p))),
|
||||
)
|
||||
|
||||
const candidates = workspaces.filter((workspace) => {
|
||||
if (workspace.projectID !== targetProjectId) return false
|
||||
if (!workspace.directory) return false
|
||||
|
||||
const workspaceDirectory = canonicalPathSync(path.resolve(workspace.directory))
|
||||
if (workspaceDirectory === targetDirectory) return false
|
||||
if (workspaceDirectory === reposRoot) return false
|
||||
if (workspaceDirectory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
|
||||
if (activeRunWorkspaceIds.has(workspace.id)) return false
|
||||
if (activeRunDirectories.has(workspaceDirectory)) return false
|
||||
if (knownDirectories.has(workspaceDirectory)) return false
|
||||
|
||||
const candidates = worktrees.filter((worktree) => {
|
||||
const directory = canonicalPathSync(path.resolve(worktree.directory))
|
||||
if (directory === targetDirectory) return false
|
||||
if (directory === reposRoot) return false
|
||||
if (directory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
|
||||
if (activeRunDirectories.has(directory)) return false
|
||||
if (knownDirectories.has(directory)) return false
|
||||
return true
|
||||
})
|
||||
|
||||
const mainChecks = await Promise.all(
|
||||
candidates.map((workspace) => isGitMainCheckout(workspace.directory!).catch(() => false)),
|
||||
candidates.map((worktree) => isGitMainCheckout(worktree.directory).catch(() => false)),
|
||||
)
|
||||
|
||||
const uniqueWorkspaces = new Map<string, typeof candidates[number]>()
|
||||
const uniqueWorktrees = new Map<string, typeof candidates[number]>()
|
||||
candidates
|
||||
.filter((_, index) => !mainChecks[index])
|
||||
.forEach((workspace) => {
|
||||
const directory = canonicalPathSync(path.resolve(workspace.directory!))
|
||||
if (!uniqueWorkspaces.has(directory)) {
|
||||
uniqueWorkspaces.set(directory, workspace)
|
||||
.forEach((worktree) => {
|
||||
const directory = canonicalPathSync(path.resolve(worktree.directory))
|
||||
if (!uniqueWorktrees.has(directory)) {
|
||||
uniqueWorktrees.set(directory, worktree)
|
||||
}
|
||||
})
|
||||
|
||||
const workspaceSiblings = Array.from(uniqueWorkspaces.values())
|
||||
.map((workspace) => ({
|
||||
id: -1,
|
||||
repoUrl: target.repoUrl,
|
||||
localPath: workspace.name ?? workspace.id,
|
||||
fullPath: workspace.directory!,
|
||||
sourcePath: workspace.directory!,
|
||||
branch: workspace.branch ?? undefined,
|
||||
defaultBranch: target.defaultBranch,
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
isWorktree: true,
|
||||
isLocal: true,
|
||||
currentBranch: workspace.branch ?? undefined,
|
||||
workspaceId: workspace.id,
|
||||
workspaceType: workspace.type,
|
||||
workspaceName: workspace.name ?? undefined,
|
||||
}))
|
||||
const worktreeSiblings = Array.from(uniqueWorktrees.values()).map((worktree) => ({
|
||||
id: -1,
|
||||
repoUrl: target.repoUrl,
|
||||
localPath: path.basename(worktree.directory),
|
||||
fullPath: worktree.directory,
|
||||
sourcePath: worktree.directory,
|
||||
branch: undefined,
|
||||
defaultBranch: target.defaultBranch,
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
isWorktree: true,
|
||||
isLocal: true,
|
||||
currentBranch: undefined,
|
||||
worktreeStrategy: worktree.strategy,
|
||||
}))
|
||||
|
||||
return [...repoSiblings, ...workspaceSiblings]
|
||||
return [...repoSiblings, ...worktreeSiblings]
|
||||
} catch (error) {
|
||||
logger.warn('Failed to list OpenCode workspaces:', error)
|
||||
logger.warn('Failed to list OpenCode worktrees:', error)
|
||||
return repoSiblings
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import path from 'path'
|
||||
import { existsSync } from 'fs'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
import {
|
||||
@@ -15,8 +14,6 @@ export const SANDBOX_SHELL_FILENAME = 'ocm-sandbox-shell'
|
||||
|
||||
export const SANDBOX_SHELL_ENV_WORKDIR = 'OCM_SANDBOX_WORKDIR'
|
||||
|
||||
export const SANDBOX_SHELL_ENV_HOST_SHELL = 'OCM_SANDBOX_HOST_SHELL'
|
||||
|
||||
/**
|
||||
* Upper bound on `http.<host>.extraheader` pairs forwarded into the microVM.
|
||||
* The shim enumerates a fixed set of variable names rather than expanding
|
||||
@@ -73,21 +70,6 @@ export function sandboxShellShimPath(configHome: string): string {
|
||||
return path.join(configHome, 'ocm', SANDBOX_SHELL_FILENAME)
|
||||
}
|
||||
|
||||
export function resolveShimHostShell(): string {
|
||||
const configured = process.env.SHELL?.trim()
|
||||
if (
|
||||
configured !== undefined &&
|
||||
configured !== '' &&
|
||||
path.isAbsolute(configured) &&
|
||||
path.basename(configured) !== SANDBOX_SHELL_FILENAME &&
|
||||
existsSync(configured)
|
||||
) {
|
||||
return configured
|
||||
}
|
||||
if (existsSync('/bin/bash')) return '/bin/bash'
|
||||
return '/bin/sh'
|
||||
}
|
||||
|
||||
export function buildSandboxShellShimScript(): string {
|
||||
const timeoutSeconds = Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)
|
||||
const execArgs = [
|
||||
@@ -107,22 +89,22 @@ export function buildSandboxShellShimScript(): string {
|
||||
(name) => ` if [ -n "\${${name}+x}" ]; then set -- "$@" -e "${name}=$${name}"; fi`,
|
||||
).join('\n')
|
||||
return `#!/bin/sh
|
||||
if [ -n "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then
|
||||
ocm_argc=$#
|
||||
set -- "$@" ${execArgs}
|
||||
${forwardEnv}
|
||||
set -- "$@" -- sh
|
||||
ocm_i=0
|
||||
while [ "$ocm_i" -lt "$ocm_argc" ]; do
|
||||
ocm_arg=$1
|
||||
shift
|
||||
set -- "$@" "$ocm_arg"
|
||||
ocm_i=$((ocm_i + 1))
|
||||
done
|
||||
exec "$@"
|
||||
if [ -z "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then
|
||||
echo 'ocm-sandbox-shell: sandbox working directory missing; refusing to run on the host' >&2
|
||||
exit 126
|
||||
fi
|
||||
OCM_SANDBOX_DEFAULT_SHELL=${quoteForShell(resolveShimHostShell())}
|
||||
exec "\${${SANDBOX_SHELL_ENV_HOST_SHELL}:-$OCM_SANDBOX_DEFAULT_SHELL}" "$@"
|
||||
ocm_argc=$#
|
||||
set -- "$@" ${execArgs}
|
||||
${forwardEnv}
|
||||
set -- "$@" -- sh
|
||||
ocm_i=0
|
||||
while [ "$ocm_i" -lt "$ocm_argc" ]; do
|
||||
ocm_arg=$1
|
||||
shift
|
||||
set -- "$@" "$ocm_arg"
|
||||
ocm_i=$((ocm_i + 1))
|
||||
done
|
||||
exec "$@"
|
||||
`
|
||||
}
|
||||
|
||||
|
||||
@@ -7,21 +7,17 @@ import type { Repo } from '../types/repo'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import type { SettingsService } from './settings'
|
||||
import type { CredentialProvider } from './credential-provider'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { resolveGitIdentity, createGitIdentityEnv } from '../utils/git-auth'
|
||||
import { isSSHUrl } from '@opencode-manager/shared/utils'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSyncSafe } from '../utils/fs-safe'
|
||||
import { resolveSandboxWorkDirectory } from './sandbox/command'
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
|
||||
export interface ScheduleWorktreeContext {
|
||||
directory: string
|
||||
worktreePath: string
|
||||
runBranch: string
|
||||
workspaceId: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,19 +31,12 @@ export function buildRepoEnvForRepo(repo: { id?: number; fullPath: string }): Re
|
||||
}
|
||||
}
|
||||
|
||||
interface OpenCodeWorkspace {
|
||||
id: string
|
||||
directory: string
|
||||
branch: string | null
|
||||
}
|
||||
|
||||
export class ScheduleWorktreeManager {
|
||||
constructor(
|
||||
private readonly gitAuthService: GitAuthService,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly credentialProvider: CredentialProvider,
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
) {}
|
||||
|
||||
async prepare(
|
||||
@@ -82,44 +71,6 @@ export class ScheduleWorktreeManager {
|
||||
|
||||
const runBranch = `schedule/${job.id}/run-${runId}`
|
||||
|
||||
// Attempt OpenCode workspace API; fall back to raw git worktree on failure
|
||||
let createdWorkspace: OpenCodeWorkspace | null = null
|
||||
try {
|
||||
createdWorkspace = await this.openCodeClient.postJson<OpenCodeWorkspace>(
|
||||
'/experimental/workspace',
|
||||
{ type: 'worktree', branch: null },
|
||||
{ directory: repo.fullPath },
|
||||
)
|
||||
|
||||
const workspaceDirectory = await this.resolveWorkspaceDirectory(createdWorkspace.directory)
|
||||
|
||||
// Re-point the workspace to our run branch and base
|
||||
await executeCommand(['git', '-C', workspaceDirectory, 'checkout', '-B', runBranch, baseRef], { env })
|
||||
|
||||
if (!existsSync(workspaceDirectory)) {
|
||||
throw new Error(`OpenCode workspace directory was not created at: ${workspaceDirectory}`)
|
||||
}
|
||||
|
||||
return {
|
||||
directory: workspaceDirectory,
|
||||
worktreePath: workspaceDirectory,
|
||||
runBranch,
|
||||
workspaceId: createdWorkspace.id,
|
||||
}
|
||||
} catch (apiError) {
|
||||
logger.warn(`OpenCode workspace API failed, falling back to raw git worktree: ${apiError}`)
|
||||
// Best-effort cleanup of created workspace if checkout/setup failed after API success
|
||||
if (createdWorkspace) {
|
||||
this.openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(createdWorkspace.id)}`,
|
||||
directory: repo.fullPath,
|
||||
}).catch(() => {})
|
||||
}
|
||||
// Fall through to raw git path
|
||||
}
|
||||
|
||||
// Fallback: raw git worktree
|
||||
const worktreePath = path.join(getScheduleWorktreesPath(), `job-${job.id}-run-${runId}`)
|
||||
mkdirSyncSafe(path.dirname(worktreePath))
|
||||
await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef)
|
||||
@@ -128,7 +79,7 @@ export class ScheduleWorktreeManager {
|
||||
throw new Error(`Worktree directory was not created at: ${worktreePath}`)
|
||||
}
|
||||
|
||||
return { directory: worktreePath, worktreePath, runBranch, workspaceId: null }
|
||||
return { directory: worktreePath, worktreePath, runBranch }
|
||||
} finally {
|
||||
if (sshSetup) {
|
||||
await this.gitAuthService.cleanupSSHKey()
|
||||
@@ -139,7 +90,7 @@ export class ScheduleWorktreeManager {
|
||||
async finalize(
|
||||
repo: Repo,
|
||||
job: { id: number; name: string; prompt: string },
|
||||
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string; workspaceId?: string | null },
|
||||
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string },
|
||||
): Promise<{ commitHash: string | null }> {
|
||||
if (!run.worktreePath) {
|
||||
return { commitHash: null }
|
||||
@@ -178,33 +129,12 @@ export class ScheduleWorktreeManager {
|
||||
logger.error(`Failed to finalize schedule run ${run.id} in worktree ${run.worktreePath}:`, error)
|
||||
throw error
|
||||
} finally {
|
||||
// Teardown: delete the worktree/workspace
|
||||
try {
|
||||
await this.deleteWorkspaceOrFallback(repo, run, env)
|
||||
} catch (error) {
|
||||
await removeWorktree(repo.fullPath, run.worktreePath, env).catch((error) => {
|
||||
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
|
||||
// Best-effort fallback
|
||||
await removeWorktree(repo.fullPath, run.worktreePath, env).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
// Branch reconciliation: ensure the run branch survives teardown
|
||||
if (run.runBranch) {
|
||||
try {
|
||||
if (!commitHash) {
|
||||
// No changes: remove the empty run branch
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => {})
|
||||
} else if (run.workspaceId) {
|
||||
// Only the workspace API teardown can remove the run branch; the raw
|
||||
// git fallback leaves it intact, so verify/restore only matters here.
|
||||
try {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'rev-parse', '--verify', `refs/heads/${run.runBranch}`], { env, silent: true })
|
||||
} catch {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', run.runBranch, commitHash], { env })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort
|
||||
}
|
||||
if (run.runBranch && !commitHash) {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => undefined)
|
||||
}
|
||||
|
||||
if (sshSetup) {
|
||||
@@ -221,24 +151,16 @@ export class ScheduleWorktreeManager {
|
||||
*/
|
||||
async pruneRunArtifacts(
|
||||
repo: Repo,
|
||||
artifacts: { runBranch: string | null; worktreePath: string | null; workspaceId?: string | null }[],
|
||||
artifacts: { runBranch: string | null; worktreePath: string | null }[],
|
||||
): Promise<void> {
|
||||
if (artifacts.length === 0) return
|
||||
|
||||
const env = await this.buildGitEnv(repo, false, true)
|
||||
|
||||
// Workspace/worktree removals are independent per artifact, so run them
|
||||
// concurrently; failures are swallowed per artifact so one bad entry does
|
||||
// not block the rest.
|
||||
await Promise.all(
|
||||
artifacts.map(async (artifact) => {
|
||||
try {
|
||||
await this.deleteWorkspaceOrFallback(repo, artifact, env)
|
||||
} catch {
|
||||
if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env).catch(() => {})
|
||||
}
|
||||
}
|
||||
if (!artifact.worktreePath) return
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env).catch(() => undefined)
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -248,33 +170,6 @@ export class ScheduleWorktreeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a run's worktree, preferring the OpenCode workspace API when a
|
||||
* workspaceId is present and falling back to a raw `git worktree remove` when
|
||||
* the API is unavailable or returns a non-ok response.
|
||||
*/
|
||||
private async deleteWorkspaceOrFallback(
|
||||
repo: Repo,
|
||||
artifact: { workspaceId?: string | null; worktreePath: string | null },
|
||||
env: Record<string, string> | undefined,
|
||||
): Promise<void> {
|
||||
if (artifact.workspaceId) {
|
||||
const response = await this.openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(artifact.workspaceId)}`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
if (!response.ok) {
|
||||
logger.warn(`OpenCode workspace DELETE returned ${response.status}, falling back to raw removeWorktree`)
|
||||
if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
|
||||
}
|
||||
}
|
||||
} else if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a user-supplied base branch name to a verified git ref, preferring
|
||||
* the remote-tracking branch for freshness. Returns null when neither the
|
||||
@@ -293,17 +188,6 @@ export class ScheduleWorktreeManager {
|
||||
return null
|
||||
}
|
||||
|
||||
private async resolveWorkspaceDirectory(directory: string): Promise<string> {
|
||||
if (!opencodeServerManager.isSandboxEnforced()) {
|
||||
return directory
|
||||
}
|
||||
const workDirectory = await resolveSandboxWorkDirectory(directory)
|
||||
if (workDirectory === null) {
|
||||
throw new Error(`OpenCode workspace directory is outside the sandboxed project roots: ${directory}`)
|
||||
}
|
||||
return workDirectory
|
||||
}
|
||||
|
||||
private async buildGitEnv(repo: Repo, sshSetup: boolean, silent: boolean): Promise<Record<string, string>> {
|
||||
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
|
||||
const sshEnv = sshSetup ? this.gitAuthService.getSSHEnvironment() : {}
|
||||
|
||||
+160
-274
@@ -7,6 +7,7 @@ import {
|
||||
type ScheduleRunTriggerSource,
|
||||
type UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import { assistantText, openCodeLocation, sessionIDFromEvent, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { ScheduleJobWithRepo } from '../db/schedules'
|
||||
@@ -59,41 +60,6 @@ class ScheduleServiceError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
interface SessionResponse {
|
||||
id: string
|
||||
}
|
||||
|
||||
interface SessionMessagePart {
|
||||
type?: string
|
||||
text?: string
|
||||
}
|
||||
|
||||
interface SessionMessage {
|
||||
info?: {
|
||||
id?: string
|
||||
sessionID?: string
|
||||
role?: string
|
||||
time?: {
|
||||
created?: number
|
||||
completed?: number
|
||||
}
|
||||
error?: {
|
||||
name?: string
|
||||
data?: {
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
}
|
||||
parts?: SessionMessagePart[]
|
||||
}
|
||||
|
||||
interface SessionStatus {
|
||||
type: 'idle' | 'retry' | 'busy'
|
||||
attempt?: number
|
||||
message?: string
|
||||
next?: number
|
||||
}
|
||||
|
||||
const SESSION_STOPPED_ERROR = 'The session stopped without producing an assistant response. This usually means OpenCode restarted mid-run or the session was interrupted. Open the linked session to inspect any partial output and rerun if needed.'
|
||||
|
||||
interface SessionSignal {
|
||||
@@ -116,73 +82,7 @@ function buildSessionTitle(job: ScheduleJob): string {
|
||||
return `Scheduled: ${job.name}`
|
||||
}
|
||||
|
||||
type SkillInfo = {
|
||||
name: string
|
||||
description: string
|
||||
location: string
|
||||
content: string
|
||||
}
|
||||
|
||||
async function fetchSkillContent(slugs: string[], repoPath: string, openCodeClient: OpenCodeClient): Promise<string[]> {
|
||||
try {
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/skill',
|
||||
directory: repoPath,
|
||||
})
|
||||
if (!response.ok) {
|
||||
logger.warn(`Failed to fetch skills from OpenCode (${response.status}), falling back to name-only injection`)
|
||||
return []
|
||||
}
|
||||
const skills = await response.json() as SkillInfo[]
|
||||
|
||||
const skillBlocks = slugs
|
||||
.map((slug) => {
|
||||
const skill = skills.find((s) => s.name === slug || s.name.endsWith(`/${slug}`) || s.name.endsWith(`-${slug}`))
|
||||
if (!skill) {
|
||||
logger.warn(`Skill "${slug}" not found in OpenCode skill list`)
|
||||
return null
|
||||
}
|
||||
return [
|
||||
`<skill_content name="${skill.name}">`,
|
||||
`# Skill: ${skill.name}`,
|
||||
'',
|
||||
skill.content.trim(),
|
||||
'</skill_content>',
|
||||
].join('\n')
|
||||
})
|
||||
.filter((block): block is string => block !== null)
|
||||
|
||||
const foundCount = skillBlocks.length
|
||||
if (foundCount < slugs.length) {
|
||||
logger.warn(`Only ${foundCount} of ${slugs.length} requested skills were found`)
|
||||
}
|
||||
|
||||
return skillBlocks
|
||||
} catch (error) {
|
||||
logger.warn('Error fetching skills from OpenCode, falling back to name-only injection:', error)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function buildPromptWithSkills(
|
||||
prompt: string,
|
||||
skillMetadata: ScheduleJob['skillMetadata'],
|
||||
repoPath: string,
|
||||
openCodeClient: OpenCodeClient,
|
||||
): Promise<string> {
|
||||
if (!skillMetadata || !skillMetadata.skillSlugs || skillMetadata.skillSlugs.length === 0) return prompt
|
||||
|
||||
const skillBlocks = await fetchSkillContent(skillMetadata.skillSlugs, repoPath, openCodeClient)
|
||||
const notesLine = skillMetadata.notes ? `\nSkill notes: ${skillMetadata.notes}` : ''
|
||||
|
||||
if (skillBlocks.length === 0) {
|
||||
const skillList = skillMetadata.skillSlugs.join(', ')
|
||||
return `${prompt}\n\nFor this task, use the following skills: ${skillList}${notesLine}`
|
||||
}
|
||||
|
||||
return `${prompt}\n\nThe following skills have been loaded for this task:\n\n${skillBlocks.join('\n\n')}${notesLine}`
|
||||
}
|
||||
type SkillAttachment = { id: string }
|
||||
|
||||
function buildRunLog(input: {
|
||||
job: ScheduleJob
|
||||
@@ -247,64 +147,36 @@ function buildRunStartedLog(input: {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function extractAssistantMessageText(parts: SessionMessagePart[] | undefined): string {
|
||||
return (parts ?? [])
|
||||
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
||||
.map((part) => part.text?.replace(/<think>[\s\S]*?<\/think>\s*/g, '').trim() ?? '')
|
||||
.filter(Boolean)
|
||||
.join('\n\n')
|
||||
}
|
||||
|
||||
function getAssistantMessageState(messages: SessionMessage[]): {
|
||||
function getAssistantMessageState(messages: SessionMessageInfo[]): {
|
||||
responseText: string | null
|
||||
errorText: string | null
|
||||
completed: boolean
|
||||
} | null {
|
||||
const assistantMessage = [...messages]
|
||||
.reverse()
|
||||
.find((message) => message.info?.role === 'assistant')
|
||||
const assistantMessage = messages.find(
|
||||
(message): message is SessionMessageAssistant => message.type === 'assistant',
|
||||
)
|
||||
|
||||
if (!assistantMessage) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
responseText: extractAssistantMessageText(assistantMessage.parts) || null,
|
||||
errorText: assistantMessage.info?.error?.data?.message ?? assistantMessage.info?.error?.name ?? null,
|
||||
completed: Boolean(assistantMessage.info?.time?.completed),
|
||||
responseText: assistantText(assistantMessage.content, { stripThink: true }) || null,
|
||||
errorText: assistantMessage.error?.message ?? null,
|
||||
completed: Boolean(assistantMessage.time.completed),
|
||||
}
|
||||
}
|
||||
|
||||
function getSessionEventId(event: SSEEvent): string | null {
|
||||
const properties = event.properties as {
|
||||
sessionID?: string
|
||||
info?: { id?: string }
|
||||
}
|
||||
|
||||
return properties.sessionID ?? properties.info?.id ?? null
|
||||
}
|
||||
|
||||
function getSessionErrorText(event: SSEEvent): string | null {
|
||||
const properties = event.properties as {
|
||||
error?: {
|
||||
name?: string
|
||||
data?: {
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
if (event.type !== 'session.execution.failed') {
|
||||
return null
|
||||
}
|
||||
|
||||
return properties.error?.data?.message ?? properties.error?.name ?? null
|
||||
return event.data.error.message || null
|
||||
}
|
||||
|
||||
function getSessionStatusType(event: SSEEvent): string | null {
|
||||
const properties = event.properties as {
|
||||
status?: {
|
||||
type?: string
|
||||
}
|
||||
}
|
||||
|
||||
return properties.status?.type ?? null
|
||||
return event.type === 'session.status' ? event.data.status.type : null
|
||||
}
|
||||
|
||||
function createSessionMonitor(directory: string, sessionId: string): SessionMonitor {
|
||||
@@ -327,16 +199,25 @@ function createSessionMonitor(directory: string, sessionId: string): SessionMoni
|
||||
return
|
||||
}
|
||||
|
||||
if (getSessionEventId(event) !== sessionId) {
|
||||
if (sessionIDFromEvent(event) !== sessionId) {
|
||||
return
|
||||
}
|
||||
|
||||
if (event.type === 'session.error') {
|
||||
if (event.type === 'session.execution.failed') {
|
||||
push({ errorText: getSessionErrorText(event) ?? 'The session reported an unknown error.', disposed: false })
|
||||
return
|
||||
}
|
||||
|
||||
if (event.type === 'session.idle' || (event.type === 'session.status' && getSessionStatusType(event) === 'idle')) {
|
||||
if (event.type === 'session.execution.interrupted') {
|
||||
push({ errorText: 'The session execution was interrupted.', disposed: false })
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
event.type === 'session.idle'
|
||||
|| event.type === 'session.execution.succeeded'
|
||||
|| (event.type === 'session.status' && getSessionStatusType(event) === 'idle')
|
||||
) {
|
||||
push({ errorText: null, disposed: false })
|
||||
}
|
||||
})
|
||||
@@ -445,8 +326,9 @@ export class ScheduleService {
|
||||
return getScheduleJobById(this.db, repoId, jobId)
|
||||
}
|
||||
|
||||
createJob(repoId: number, input: CreateScheduleJobRequest): ScheduleJob {
|
||||
this.assertRepo(repoId)
|
||||
async createJob(repoId: number, input: CreateScheduleJobRequest): Promise<ScheduleJob> {
|
||||
const repo = this.assertRepo(repoId)
|
||||
await this.assertAgentAvailable(repo.fullPath, input.agentSlug?.trim() || null)
|
||||
|
||||
try {
|
||||
const job = createScheduleJob(this.db, repoId, buildCreateSchedulePersistenceInput(input))
|
||||
@@ -457,9 +339,12 @@ export class ScheduleService {
|
||||
}
|
||||
}
|
||||
|
||||
updateJob(repoId: number, jobId: number, input: UpdateScheduleJobRequest): ScheduleJob {
|
||||
this.assertRepo(repoId)
|
||||
async updateJob(repoId: number, jobId: number, input: UpdateScheduleJobRequest): Promise<ScheduleJob> {
|
||||
const repo = this.assertRepo(repoId)
|
||||
const existing = this.assertJob(repoId, jobId)
|
||||
if (input.agentSlug !== undefined) {
|
||||
await this.assertAgentAvailable(repo.fullPath, input.agentSlug?.trim() || null)
|
||||
}
|
||||
let job: ScheduleJob | null
|
||||
|
||||
try {
|
||||
@@ -570,7 +455,7 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
|
||||
}
|
||||
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath, workspaceId: run.workspaceId }])
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
|
||||
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
|
||||
if (!deleted) {
|
||||
throw new ScheduleServiceError('Run not found', 404)
|
||||
@@ -610,36 +495,32 @@ export class ScheduleService {
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, run.id, {
|
||||
worktreePath: wt.worktreePath,
|
||||
runBranch: wt.runBranch,
|
||||
workspaceId: wt.workspaceId,
|
||||
})
|
||||
}
|
||||
|
||||
const runJob = { ...job, agentSlug: await this.resolveRunAgent(runDirectory, job.agentSlug) }
|
||||
const model = await resolveOpenCodeModel(this.openCodeClient, runDirectory, {
|
||||
preferredModel: job.model,
|
||||
})
|
||||
const sessionTitle = buildSessionTitle(job)
|
||||
const sessionResponse = await this.openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: '/session',
|
||||
directory: runDirectory,
|
||||
body: JSON.stringify({
|
||||
let session: { id: string }
|
||||
try {
|
||||
session = await this.openCodeClient.api.session.create({
|
||||
title: sessionTitle,
|
||||
agent: job.agentSlug ?? undefined,
|
||||
permission: buildSchedulePermissionRuleset(job.permissionConfig),
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (!sessionResponse.ok) {
|
||||
throw new ScheduleServiceError('Failed to create OpenCode session', 502)
|
||||
agent: runJob.agentSlug ?? undefined,
|
||||
model: { providerID: model.providerID, id: model.id, variant: model.variant },
|
||||
...openCodeLocation(runDirectory),
|
||||
permissions: buildSchedulePermissionRuleset(job.permissionConfig),
|
||||
})
|
||||
} catch (error) {
|
||||
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to create OpenCode session', 502)
|
||||
}
|
||||
|
||||
const session = await sessionResponse.json() as SessionResponse
|
||||
const runWithSession = updateScheduleRunMetadata(this.db, repoId, jobId, run.id, {
|
||||
sessionId: session.id,
|
||||
sessionTitle,
|
||||
logText: buildRunStartedLog({
|
||||
job,
|
||||
job: runJob,
|
||||
triggerSource,
|
||||
sessionId: session.id,
|
||||
sessionTitle,
|
||||
@@ -654,12 +535,11 @@ export class ScheduleService {
|
||||
|
||||
void this.submitPromptAndMonitor({
|
||||
repoId,
|
||||
job,
|
||||
job: runJob,
|
||||
runId: run.id,
|
||||
sessionId: session.id,
|
||||
sessionTitle,
|
||||
triggerSource,
|
||||
model,
|
||||
sessionMonitor,
|
||||
directory: runDirectory,
|
||||
})
|
||||
@@ -718,31 +598,23 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError('Only running schedule runs can be cancelled', 409)
|
||||
}
|
||||
|
||||
const runDirectory = run.worktreePath ?? repo.fullPath
|
||||
|
||||
if (run.sessionId) {
|
||||
const messages = await this.listSessionMessages(runDirectory, run.sessionId)
|
||||
const assistantState = getAssistantMessageState(messages)
|
||||
const outcome = await this.readAssistantOutcome(run.sessionId)
|
||||
|
||||
if (assistantState?.completed || assistantState?.errorText) {
|
||||
if (outcome.kind === 'settled') {
|
||||
await this.finalizeRecoveredRun(job, run, {
|
||||
status: assistantState.errorText ? 'failed' : 'completed',
|
||||
responseText: assistantState.responseText,
|
||||
errorText: assistantState.errorText,
|
||||
status: outcome.errorText ? 'failed' : 'completed',
|
||||
responseText: outcome.responseText,
|
||||
errorText: outcome.errorText,
|
||||
}, repo)
|
||||
|
||||
return this.getRun(repoId, jobId, runId)
|
||||
}
|
||||
|
||||
const abortResponse = await this.openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${run.sessionId}/abort`,
|
||||
directory: runDirectory,
|
||||
})
|
||||
|
||||
if (!abortResponse.ok) {
|
||||
const errorText = await abortResponse.text()
|
||||
throw new ScheduleServiceError(errorText || 'Failed to cancel schedule run', 502)
|
||||
try {
|
||||
await this.openCodeClient.api.session.interrupt({ sessionID: run.sessionId })
|
||||
} catch (error) {
|
||||
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to cancel schedule run', 502)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -788,29 +660,20 @@ export class ScheduleService {
|
||||
sessionId: string
|
||||
sessionTitle: string
|
||||
triggerSource: ScheduleRunTriggerSource
|
||||
model: { providerID: string; modelID: string }
|
||||
sessionMonitor: SessionMonitor
|
||||
directory: string
|
||||
}): Promise<void> {
|
||||
const repo = this.assertRepo(input.repoId)
|
||||
|
||||
try {
|
||||
const promptResponse = await this.openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${input.sessionId}/prompt_async`,
|
||||
directory: input.directory,
|
||||
body: JSON.stringify({
|
||||
parts: [{ type: 'text', text: await buildPromptWithSkills(input.job.prompt, input.job.skillMetadata, input.directory, this.openCodeClient) }],
|
||||
model: input.model,
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
const skills = await this.resolveSkillAttachments(input.directory, input.job.skillMetadata)
|
||||
const notes = input.job.skillMetadata?.notes?.trim()
|
||||
await this.openCodeClient.api.session.prompt({
|
||||
sessionID: input.sessionId,
|
||||
text: notes ? `${input.job.prompt}\n\nSkill notes: ${notes}` : input.job.prompt,
|
||||
...(skills.length > 0 ? { skills } : {}),
|
||||
})
|
||||
|
||||
if (!promptResponse.ok) {
|
||||
const errorText = await promptResponse.text()
|
||||
throw new ScheduleServiceError(errorText || 'Failed to run scheduled prompt', 502)
|
||||
}
|
||||
|
||||
input.sessionMonitor.markSubmitted()
|
||||
|
||||
await this.monitorRunCompletion({
|
||||
@@ -821,7 +684,6 @@ export class ScheduleService {
|
||||
sessionId: input.sessionId,
|
||||
sessionTitle: input.sessionTitle,
|
||||
triggerSource: input.triggerSource,
|
||||
directory: input.directory,
|
||||
})
|
||||
return
|
||||
} catch (error) {
|
||||
@@ -869,34 +731,10 @@ export class ScheduleService {
|
||||
sessionId: string
|
||||
sessionTitle: string
|
||||
triggerSource: ScheduleRunTriggerSource
|
||||
directory: string
|
||||
initialSessionStatus?: SessionStatus
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const sessionStatus = input.initialSessionStatus
|
||||
if (sessionStatus && sessionStatus.type === 'idle') {
|
||||
const repo = this.assertRepo(input.repoId)
|
||||
const messages = await this.listSessionMessages(input.directory, input.sessionId)
|
||||
const assistantState = getAssistantMessageState(messages)
|
||||
if (assistantState?.completed || assistantState?.errorText) {
|
||||
await this.finalizeRecoveredRun(input.job, {
|
||||
id: input.runId,
|
||||
repoId: input.repoId,
|
||||
jobId: input.job.id,
|
||||
sessionId: input.sessionId,
|
||||
sessionTitle: input.sessionTitle,
|
||||
triggerSource: input.triggerSource,
|
||||
} as ScheduleRun, {
|
||||
status: assistantState.errorText ? 'failed' : 'completed',
|
||||
responseText: assistantState.responseText,
|
||||
errorText: assistantState.errorText,
|
||||
}, repo)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const repo = this.assertRepo(input.repoId)
|
||||
const currentAssistantState = await this.readSettledAssistantState(input.directory, input.sessionId)
|
||||
const currentAssistantState = await this.readSettledAssistantState(input.sessionId)
|
||||
if (currentAssistantState) {
|
||||
await this.finalizeRecoveredRun(input.job, {
|
||||
id: input.runId,
|
||||
@@ -913,7 +751,7 @@ export class ScheduleService {
|
||||
return
|
||||
}
|
||||
|
||||
const response = await this.waitForAssistantMessage(input.sessionId, input.sessionMonitor, input.directory)
|
||||
const response = await this.waitForAssistantMessage(input.sessionId, input.sessionMonitor)
|
||||
const currentRun = getScheduleRunById(this.db, input.repoId, input.job.id, input.runId)
|
||||
if (!currentRun || currentRun.status !== 'running') {
|
||||
return
|
||||
@@ -1011,22 +849,18 @@ export class ScheduleService {
|
||||
return
|
||||
}
|
||||
|
||||
const messages = await this.listSessionMessages(runDirectory, run.sessionId)
|
||||
const assistantState = getAssistantMessageState(messages)
|
||||
const outcome = await this.readAssistantOutcome(run.sessionId)
|
||||
|
||||
if (assistantState?.completed || assistantState?.errorText) {
|
||||
if (outcome.kind === 'settled') {
|
||||
await this.finalizeRecoveredRun(job, run, {
|
||||
status: assistantState.errorText ? 'failed' : 'completed',
|
||||
responseText: assistantState.responseText,
|
||||
errorText: assistantState.errorText,
|
||||
status: outcome.errorText ? 'failed' : 'completed',
|
||||
responseText: outcome.responseText,
|
||||
errorText: outcome.errorText,
|
||||
}, repo)
|
||||
return
|
||||
}
|
||||
|
||||
const sessionStatuses = await this.getSessionStatuses(runDirectory)
|
||||
const sessionStatus = run.sessionId ? sessionStatuses[run.sessionId] : undefined
|
||||
|
||||
if (sessionStatus && sessionStatus.type !== 'idle') {
|
||||
if (outcome.kind === 'busy') {
|
||||
const sessionMonitor = createSessionMonitor(runDirectory, run.sessionId)
|
||||
void this.monitorRunCompletion({
|
||||
sessionMonitor,
|
||||
@@ -1036,15 +870,13 @@ export class ScheduleService {
|
||||
sessionId: run.sessionId,
|
||||
sessionTitle: run.sessionTitle ?? buildSessionTitle(job),
|
||||
triggerSource: run.triggerSource,
|
||||
initialSessionStatus: sessionStatus,
|
||||
directory: runDirectory,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await this.finalizeRecoveredRun(job, run, {
|
||||
status: 'failed',
|
||||
responseText: assistantState?.responseText ?? null,
|
||||
responseText: outcome.responseText,
|
||||
errorText: 'This run was interrupted before completion, likely because OpenCode Manager restarted while it was in progress. Open the linked session to inspect the partial output and rerun if needed.',
|
||||
}, repo)
|
||||
} catch (error) {
|
||||
@@ -1109,12 +941,11 @@ export class ScheduleService {
|
||||
worktreePath: fresh.worktreePath,
|
||||
runBranch: fresh.runBranch,
|
||||
triggerSource: fresh.triggerSource,
|
||||
workspaceId: fresh.workspaceId,
|
||||
})
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash, workspaceId: null })
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash })
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, workspaceId: null })
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null })
|
||||
}
|
||||
} finally {
|
||||
ScheduleService.activeTeardowns.delete(key)
|
||||
@@ -1124,15 +955,14 @@ export class ScheduleService {
|
||||
/**
|
||||
* An assistant message completing is not the end of a run: a multi-step agent
|
||||
* settles one message per tool call. Only a session that has gone idle has
|
||||
* finished, and only then is the final message guaranteed to carry its parts.
|
||||
* finished, and only then is the final message guaranteed to carry its content.
|
||||
*/
|
||||
private async readAssistantOutcome(directory: string, sessionId: string): Promise<AssistantOutcome> {
|
||||
const sessionStatus = (await this.getSessionStatuses(directory))[sessionId]
|
||||
if (sessionStatus && sessionStatus.type !== 'idle') {
|
||||
private async readAssistantOutcome(sessionId: string): Promise<AssistantOutcome> {
|
||||
if (await this.isSessionActive(sessionId)) {
|
||||
return { kind: 'busy' }
|
||||
}
|
||||
|
||||
const assistantState = getAssistantMessageState(await this.listSessionMessages(directory, sessionId))
|
||||
const assistantState = getAssistantMessageState(await this.listSessionMessages(sessionId))
|
||||
if (assistantState?.completed || assistantState?.errorText) {
|
||||
return { kind: 'settled', responseText: assistantState.responseText, errorText: assistantState.errorText }
|
||||
}
|
||||
@@ -1141,10 +971,9 @@ export class ScheduleService {
|
||||
}
|
||||
|
||||
private async readSettledAssistantState(
|
||||
directory: string,
|
||||
sessionId: string,
|
||||
): Promise<{ responseText: string | null; errorText: string | null } | null> {
|
||||
const outcome = await this.readAssistantOutcome(directory, sessionId)
|
||||
const outcome = await this.readAssistantOutcome(sessionId)
|
||||
return outcome.kind === 'settled'
|
||||
? { responseText: outcome.responseText, errorText: outcome.errorText }
|
||||
: null
|
||||
@@ -1153,20 +982,19 @@ export class ScheduleService {
|
||||
private async waitForAssistantMessage(
|
||||
sessionId: string,
|
||||
sessionMonitor: SessionMonitor,
|
||||
directory: string,
|
||||
): Promise<{ responseText: string | null; errorText: string | null }> {
|
||||
for (;;) {
|
||||
const signal = await sessionMonitor.nextSignal()
|
||||
|
||||
if (signal.errorText || signal.disposed) {
|
||||
const messages = await this.listSessionMessages(directory, sessionId)
|
||||
const messages = await this.listSessionMessages(sessionId)
|
||||
return {
|
||||
responseText: getAssistantMessageState(messages)?.responseText ?? null,
|
||||
errorText: signal.errorText ?? SESSION_STOPPED_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
const outcome = await this.readAssistantOutcome(directory, sessionId)
|
||||
const outcome = await this.readAssistantOutcome(sessionId)
|
||||
|
||||
if (outcome.kind === 'busy') {
|
||||
continue
|
||||
@@ -1180,34 +1008,92 @@ export class ScheduleService {
|
||||
}
|
||||
}
|
||||
|
||||
private async listSessionMessages(directory: string, sessionId: string): Promise<SessionMessage[]> {
|
||||
const messagesResponse = await this.openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: `/session/${sessionId}/message`,
|
||||
directory,
|
||||
})
|
||||
|
||||
if (!messagesResponse.ok) {
|
||||
const errorText = await messagesResponse.text()
|
||||
throw new ScheduleServiceError(errorText || 'Failed to fetch session messages', 502)
|
||||
private async listSessionMessages(sessionId: string): Promise<SessionMessageInfo[]> {
|
||||
try {
|
||||
const response = await this.openCodeClient.api.message.list({
|
||||
sessionID: sessionId,
|
||||
order: 'desc',
|
||||
limit: 20,
|
||||
})
|
||||
return response.data
|
||||
} catch (error) {
|
||||
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to fetch session messages', 502)
|
||||
}
|
||||
|
||||
return await messagesResponse.json() as SessionMessage[]
|
||||
}
|
||||
|
||||
private async getSessionStatuses(directory: string): Promise<Record<string, SessionStatus>> {
|
||||
const response = await this.openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/session/status',
|
||||
directory,
|
||||
})
|
||||
private async isSessionActive(sessionId: string): Promise<boolean> {
|
||||
try {
|
||||
const active = await this.openCodeClient.api.session.active()
|
||||
return sessionId in active
|
||||
} catch (error) {
|
||||
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to fetch active sessions', 502)
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new ScheduleServiceError(errorText || 'Failed to fetch session statuses', 502)
|
||||
private async listAgentIds(directory: string): Promise<Set<string>> {
|
||||
try {
|
||||
const response = await this.openCodeClient.api.agent.list(openCodeLocation(directory))
|
||||
return new Set(response.data.map((agent) => agent.id))
|
||||
} catch (error) {
|
||||
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to list agents', 502)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenCode admits a prompt for a session whose agent does not exist at its location
|
||||
* but never delivers it, so a scheduled run falls back to the default agent when its agent is gone.
|
||||
*/
|
||||
private async resolveRunAgent(directory: string, agentSlug: string | null): Promise<string | null> {
|
||||
if (!agentSlug) {
|
||||
return null
|
||||
}
|
||||
|
||||
return await response.json() as Record<string, SessionStatus>
|
||||
if ((await this.listAgentIds(directory)).has(agentSlug)) {
|
||||
return agentSlug
|
||||
}
|
||||
|
||||
logger.warn(`Agent "${agentSlug}" is not available in ${directory}; running the schedule with the default agent`)
|
||||
return null
|
||||
}
|
||||
|
||||
private async assertAgentAvailable(directory: string, agentSlug: string | null): Promise<void> {
|
||||
if (!agentSlug) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!(await this.listAgentIds(directory)).has(agentSlug)) {
|
||||
throw new ScheduleServiceError(
|
||||
`Agent "${agentSlug}" is not available in ${directory}. Choose an agent defined for this repo in the schedule settings, or clear the agent to use the default.`,
|
||||
400,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveSkillAttachments(
|
||||
directory: string,
|
||||
skillMetadata: ScheduleJob['skillMetadata'],
|
||||
): Promise<SkillAttachment[]> {
|
||||
const slugs = skillMetadata?.skillSlugs ?? []
|
||||
if (slugs.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
let availableSkills: Set<string>
|
||||
try {
|
||||
const response = await this.openCodeClient.api.skill.list(openCodeLocation(directory))
|
||||
availableSkills = new Set(response.data.map((skill) => skill.id))
|
||||
} catch (error) {
|
||||
logger.warn('Failed to list skills for the scheduled run; continuing without skill attachments:', error)
|
||||
return []
|
||||
}
|
||||
|
||||
return slugs.flatMap((slug) => {
|
||||
if (!availableSkills.has(slug)) {
|
||||
logger.warn(`Skill "${slug}" is not available in this location; dropping it from the scheduled run`)
|
||||
return []
|
||||
}
|
||||
return [{ id: slug }]
|
||||
})
|
||||
}
|
||||
|
||||
private assertRepo(repoId: number) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { logger } from '../utils/logger'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { encryptSecret, decryptSecret } from '../utils/crypto'
|
||||
@@ -12,6 +13,11 @@ import {
|
||||
DEFAULT_USER_PREFERENCES,
|
||||
} from '../types/settings'
|
||||
|
||||
const CUSTOM_OPENCODE_SERVER_PASSWORD_KEY = 'opencode_server_password'
|
||||
const MANAGED_OPENCODE_SERVER_PASSWORD_KEY = 'opencode_server_managed_password'
|
||||
|
||||
export type OpenCodeServerPasswordSource = 'db' | 'env' | 'managed'
|
||||
|
||||
interface OpenCodeServerPasswordState {
|
||||
value: string
|
||||
createdAt: number
|
||||
@@ -124,26 +130,59 @@ export class SettingsService {
|
||||
logger.info('Saved last known good config')
|
||||
}
|
||||
|
||||
getOpenCodeServerPassword(): string {
|
||||
const row = this.db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string } | undefined
|
||||
private readSecret(key: string): string | null {
|
||||
const row = this.db.prepare('SELECT value FROM app_secrets WHERE key = ?').get(key) as { value: string } | undefined
|
||||
if (!row) {
|
||||
return ENV.OPENCODE.SERVER_PASSWORD
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return decryptSecret(row.value)
|
||||
} catch (error) {
|
||||
logger.error('Failed to decrypt opencode_server_password, falling back to env', error)
|
||||
return ENV.OPENCODE.SERVER_PASSWORD
|
||||
logger.error(`Failed to decrypt ${key}`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
hasStoredOpenCodeServerPassword(): boolean {
|
||||
const row = this.db.prepare('SELECT 1 FROM app_secrets WHERE key = ?').get('opencode_server_password')
|
||||
return Boolean(row)
|
||||
getOrCreateManagedOpenCodeServerPassword(): string {
|
||||
const existing = this.readSecret(MANAGED_OPENCODE_SERVER_PASSWORD_KEY)
|
||||
if (existing !== null) {
|
||||
return existing
|
||||
}
|
||||
|
||||
const password = randomBytes(32).toString('base64url')
|
||||
const now = Date.now()
|
||||
this.db.prepare(`
|
||||
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO NOTHING
|
||||
`).run(MANAGED_OPENCODE_SERVER_PASSWORD_KEY, encryptSecret(password), now, now)
|
||||
|
||||
const stored = this.readSecret(MANAGED_OPENCODE_SERVER_PASSWORD_KEY)
|
||||
if (stored === null) {
|
||||
throw new Error('Failed to persist the managed OpenCode server password')
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
getOpenCodeServerPassword(): string {
|
||||
const stored = this.readSecret(CUSTOM_OPENCODE_SERVER_PASSWORD_KEY)
|
||||
if (stored !== null) {
|
||||
return stored
|
||||
}
|
||||
if (ENV.OPENCODE.SERVER_PASSWORD) {
|
||||
return ENV.OPENCODE.SERVER_PASSWORD
|
||||
}
|
||||
return this.getOrCreateManagedOpenCodeServerPassword()
|
||||
}
|
||||
|
||||
getOpenCodeServerPasswordSource(): OpenCodeServerPasswordSource {
|
||||
if (this.readSecret(CUSTOM_OPENCODE_SERVER_PASSWORD_KEY) !== null) {
|
||||
return 'db'
|
||||
}
|
||||
return ENV.OPENCODE.SERVER_PASSWORD ? 'env' : 'managed'
|
||||
}
|
||||
|
||||
getStoredOpenCodeServerPasswordState(): OpenCodeServerPasswordState | null {
|
||||
const row = this.db.prepare('SELECT value, created_at, updated_at FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string; created_at: number; updated_at: number } | undefined
|
||||
const row = this.db.prepare('SELECT value, created_at, updated_at FROM app_secrets WHERE key = ?').get(CUSTOM_OPENCODE_SERVER_PASSWORD_KEY) as { value: string; created_at: number; updated_at: number } | undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -164,7 +203,7 @@ export class SettingsService {
|
||||
this.db.prepare(`
|
||||
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, created_at = excluded.created_at, updated_at = excluded.updated_at
|
||||
`).run('opencode_server_password', state.value, state.createdAt, state.updatedAt)
|
||||
`).run(CUSTOM_OPENCODE_SERVER_PASSWORD_KEY, state.value, state.createdAt, state.updatedAt)
|
||||
}
|
||||
|
||||
setOpenCodeServerPassword(password: string): void {
|
||||
@@ -173,10 +212,10 @@ export class SettingsService {
|
||||
this.db.prepare(`
|
||||
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
|
||||
`).run('opencode_server_password', encrypted, now, now)
|
||||
`).run(CUSTOM_OPENCODE_SERVER_PASSWORD_KEY, encrypted, now, now)
|
||||
}
|
||||
|
||||
clearOpenCodeServerPassword(): void {
|
||||
this.db.prepare('DELETE FROM app_secrets WHERE key = ?').run('opencode_server_password')
|
||||
this.db.prepare('DELETE FROM app_secrets WHERE key = ?').run(CUSTOM_OPENCODE_SERVER_PASSWORD_KEY)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest, InstallSkillUploadRequest, InstallSkillFromGithubRequest, InstallSkillResponse } from '@opencode-manager/shared'
|
||||
import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shared'
|
||||
import { getOpenCodeGlobalSkillsPath, getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env'
|
||||
import { openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { getRepoById, getRepoName, listRepos } from '../db/queries'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
|
||||
@@ -16,7 +17,7 @@ import { mkdirSafe } from '../utils/fs-safe'
|
||||
interface OpenCodeSkillInfo {
|
||||
name: string
|
||||
description: string
|
||||
location: string
|
||||
path: string
|
||||
content: string
|
||||
}
|
||||
|
||||
@@ -384,16 +385,13 @@ function buildSkillFileContent(name: string, description: string, body: string):
|
||||
|
||||
async function fetchOpenCodeSkills(openCodeClient: OpenCodeClient, directory: string): Promise<OpenCodeSkillInfo[]> {
|
||||
try {
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/skill',
|
||||
directory,
|
||||
})
|
||||
if (!response.ok) {
|
||||
logger.warn(`Failed to fetch skills from OpenCode (${response.status})`)
|
||||
return []
|
||||
}
|
||||
return await response.json() as OpenCodeSkillInfo[]
|
||||
const response = await openCodeClient.api.skill.list(openCodeLocation(directory))
|
||||
return response.data.map((skill) => ({
|
||||
name: skill.name,
|
||||
description: skill.description ?? '',
|
||||
path: skill.path,
|
||||
content: skill.content,
|
||||
}))
|
||||
} catch (error) {
|
||||
logger.warn('Error fetching skills from OpenCode:', error)
|
||||
return []
|
||||
@@ -433,7 +431,7 @@ function toSkillFileInfo(
|
||||
description: skill.description,
|
||||
body: skill.content,
|
||||
scope: classification.scope,
|
||||
location: skill.location,
|
||||
location: skill.path,
|
||||
repoId: classification.repo?.id,
|
||||
repoName: classification.repo ? getRepoName(classification.repo) : undefined,
|
||||
}
|
||||
@@ -502,8 +500,8 @@ export async function listManagedSkills(
|
||||
if (directory) {
|
||||
const skills = await fetchOpenCodeSkills(openCodeClient, directory)
|
||||
for (const skill of skills) {
|
||||
if (seenLocations.has(skill.location)) continue
|
||||
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos, directory)
|
||||
if (seenLocations.has(skill.path)) continue
|
||||
const classification = classifySkillLocation(skill.path, globalPrefix, allRepos, directory)
|
||||
if (!classification) continue
|
||||
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
|
||||
}
|
||||
@@ -532,8 +530,8 @@ export async function listManagedSkills(
|
||||
for (const dir of directories) {
|
||||
const skills = await fetchOpenCodeSkills(openCodeClient, dir)
|
||||
for (const skill of skills) {
|
||||
if (seenLocations.has(skill.location)) continue
|
||||
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos)
|
||||
if (seenLocations.has(skill.path)) continue
|
||||
const classification = classifySkillLocation(skill.path, globalPrefix, allRepos)
|
||||
if (!classification) continue
|
||||
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EventSource } from 'eventsource'
|
||||
import { logger } from '../utils/logger'
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
import type { SSEEventEnvelope, SSEEventPayload } from '@opencode-manager/shared'
|
||||
import { openCodeLocation, type OpenCodeApi, type V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './opencode/auth'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './opencode/upstream'
|
||||
import { encodeSSEFrame } from '../utils/sse-frame'
|
||||
@@ -19,10 +19,10 @@ interface SSEClient {
|
||||
activeSessionId: string | null
|
||||
}
|
||||
|
||||
export type SSEEvent = SSEEventPayload
|
||||
export type SSEEvent = V2Event
|
||||
|
||||
export interface PendingActionsFetcher {
|
||||
getJson<T>(path: string, opts?: { directory?: string; signal?: AbortSignal }): Promise<T>
|
||||
api: OpenCodeApi
|
||||
}
|
||||
|
||||
export interface ScheduledSessionRef {
|
||||
@@ -30,22 +30,14 @@ export interface ScheduledSessionRef {
|
||||
directory: string
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
id: string
|
||||
sessionID: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface PendingQuestion {
|
||||
id: string
|
||||
sessionID: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
type SessionStatusValue = { type: string } & Record<string, unknown>
|
||||
type SessionStatusMap = Record<string, SessionStatusValue>
|
||||
type ReplayEventType = 'permission.asked' | 'form.created' | 'session.status'
|
||||
|
||||
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
|
||||
const MULTILINE_PATTERN = /[\r\n]/
|
||||
|
||||
function serializeEnvelope(directory: string | null, payloadJson: string): string {
|
||||
return '{"directory":' + JSON.stringify(directory) + ',"payload":' + payloadJson + '}'
|
||||
}
|
||||
|
||||
class SSEAggregator {
|
||||
private static instance: SSEAggregator
|
||||
@@ -63,6 +55,7 @@ class SSEAggregator {
|
||||
private pendingActionsFetcher: PendingActionsFetcher | null = null
|
||||
private passwordResolver: OpenCodePasswordResolver | null = null
|
||||
private scheduledSessionsResolver: (() => ScheduledSessionRef[]) | null = null
|
||||
private replayEventCount = 0
|
||||
|
||||
private constructor() {}
|
||||
|
||||
@@ -198,125 +191,121 @@ class SSEAggregator {
|
||||
))
|
||||
}
|
||||
|
||||
private async replayPendingActionsForAllClients(): Promise<void> {
|
||||
const fetcher = this.pendingActionsFetcher
|
||||
if (!fetcher) return
|
||||
private async replayPendingActionsForDirectory(
|
||||
clientId: string,
|
||||
directory: string,
|
||||
fetcher: PendingActionsFetcher,
|
||||
): Promise<void> {
|
||||
const [permissionsResult, formsResult] = await Promise.allSettled([
|
||||
fetcher.api.permission.request.list(openCodeLocation(directory)),
|
||||
fetcher.api.form.list(openCodeLocation(directory)),
|
||||
])
|
||||
|
||||
const tasks: Promise<void>[] = []
|
||||
this.clients.forEach((client) => {
|
||||
const directories = Array.from(client.directories)
|
||||
if (directories.length === 0) return
|
||||
tasks.push(this.replayPendingActionsForClient(client.id, directories))
|
||||
})
|
||||
if (permissionsResult.status === 'rejected') {
|
||||
logger.warn(`replay: failed to fetch pending permissions for ${directory}: ${String(permissionsResult.reason)}`)
|
||||
} else {
|
||||
this.emitReplayEventsToClient(clientId, directory, permissionsResult.value.data.map(request =>
|
||||
this.buildReplayEvent('permission.asked', directory, request)
|
||||
))
|
||||
}
|
||||
|
||||
if (tasks.length === 0) return
|
||||
logger.info(`replay: replaying pending actions to ${tasks.length} client(s) after upstream reconnect`)
|
||||
await Promise.allSettled(tasks)
|
||||
if (formsResult.status === 'rejected') {
|
||||
logger.warn(`replay: failed to fetch pending forms for ${directory}: ${String(formsResult.reason)}`)
|
||||
} else {
|
||||
this.emitReplayEventsToClient(clientId, directory, formsResult.value.data.map(form =>
|
||||
this.buildReplayEvent('form.created', directory, { form })
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private emitReplayEventsToClient(clientId: string, directory: string, events: V2Event[]): void {
|
||||
if (events.length === 0) return
|
||||
|
||||
const client = this.clients.get(clientId)
|
||||
if (!client || !client.directories.has(directory)) return
|
||||
|
||||
for (const event of events) {
|
||||
try {
|
||||
client.callback('message', serializeEnvelope(directory, JSON.stringify(event)))
|
||||
} catch (error) {
|
||||
logger.error(`replay: failed to deliver ${event.type} to client ${clientId}:`, error)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`replay: sent ${events.length} pending action(s) for ${directory} to client ${clientId}`)
|
||||
}
|
||||
|
||||
private async replaySessionStatusesForTrackedDirectories(): Promise<void> {
|
||||
const fetcher = this.pendingActionsFetcher
|
||||
if (!fetcher) return
|
||||
|
||||
const scheduledByDirectory = this.getScheduledSessionsByDirectory()
|
||||
const directories = new Set<string>(scheduledByDirectory.keys())
|
||||
this.clients.forEach((client) => {
|
||||
client.directories.forEach(dir => directories.add(dir))
|
||||
})
|
||||
|
||||
if (directories.size === 0) return
|
||||
logger.info(`replay: replaying session statuses for ${directories.size} directory(ies) after upstream reconnect`)
|
||||
await Promise.allSettled(Array.from(directories).map(directory =>
|
||||
this.replaySessionStatusesForDirectory(directory, fetcher, scheduledByDirectory.get(directory))
|
||||
))
|
||||
}
|
||||
|
||||
private async replaySessionStatusesForDirectory(
|
||||
directory: string,
|
||||
fetcher: PendingActionsFetcher,
|
||||
scheduledSessionIDs?: Set<string>,
|
||||
): Promise<void> {
|
||||
let statuses: SessionStatusMap
|
||||
let running: Record<string, { type: string }>
|
||||
try {
|
||||
statuses = await fetcher.getJson<SessionStatusMap>('/session/status', { directory })
|
||||
running = await fetcher.api.session.active()
|
||||
} catch (error) {
|
||||
logger.warn(`replay: failed to fetch session statuses for ${directory}: ${String(error)}`)
|
||||
logger.warn(`replay: failed to fetch active sessions: ${String(error)}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (!statuses) return
|
||||
|
||||
const tracked = new Set(this.activeSessions.get(directory) ?? [])
|
||||
scheduledSessionIDs?.forEach(sessionID => tracked.add(sessionID))
|
||||
const nowActive = new Set<string>()
|
||||
const tracked = this.getTrackedSessions()
|
||||
const runningIDs = Object.keys(running ?? {})
|
||||
const runningSet = new Set(runningIDs)
|
||||
|
||||
let replayed = 0
|
||||
for (const [sessionID, status] of Object.entries(statuses)) {
|
||||
if (!sessionID || !status || status.type === 'idle') continue
|
||||
nowActive.add(sessionID)
|
||||
const data = JSON.stringify({ directory, payload: { type: 'session.status', properties: { sessionID, status } } })
|
||||
this.handleUpstreamMessage(data)
|
||||
|
||||
for (const [sessionID, directory] of tracked) {
|
||||
if (runningSet.has(sessionID)) continue
|
||||
this.deliverEvent(directory, this.buildReplayEvent('session.status', directory, { sessionID, status: { type: 'idle' } }))
|
||||
replayed++
|
||||
}
|
||||
|
||||
let cleared = 0
|
||||
for (const sessionID of tracked) {
|
||||
if (nowActive.has(sessionID)) continue
|
||||
const data = JSON.stringify({ directory, payload: { type: 'session.status', properties: { sessionID, status: { type: 'idle' } } } })
|
||||
this.handleUpstreamMessage(data)
|
||||
cleared++
|
||||
const runningDirectories = await Promise.all(runningIDs.map(async (sessionID) => ({
|
||||
sessionID,
|
||||
directory: tracked.get(sessionID) ?? await this.resolveSessionDirectory(fetcher, sessionID),
|
||||
})))
|
||||
|
||||
for (const { sessionID, directory } of runningDirectories) {
|
||||
if (!directory) continue
|
||||
this.deliverEvent(directory, this.buildReplayEvent('session.status', directory, { sessionID, status: { type: 'busy' } }))
|
||||
replayed++
|
||||
}
|
||||
|
||||
if (replayed > 0 || cleared > 0) {
|
||||
logger.info(`replay: re-emitted ${replayed} active and ${cleared} idle session status(es) for ${directory}`)
|
||||
if (replayed > 0) {
|
||||
logger.info(`replay: re-emitted ${replayed} session status(es) after upstream reconnect`)
|
||||
}
|
||||
}
|
||||
|
||||
private async replayPendingActionsForDirectory(
|
||||
clientId: string,
|
||||
directory: string,
|
||||
fetcher: PendingActionsFetcher,
|
||||
): Promise<void> {
|
||||
const [permissionsResult, questionsResult] = await Promise.allSettled([
|
||||
fetcher.getJson<PendingPermission[]>('/permission', { directory }),
|
||||
fetcher.getJson<PendingQuestion[]>('/question', { directory }),
|
||||
])
|
||||
|
||||
if (permissionsResult.status === 'rejected') {
|
||||
logger.warn(`replay: failed to fetch pending permissions for ${directory}: ${String(permissionsResult.reason)}`)
|
||||
} else {
|
||||
this.emitPendingEventsToClient(clientId, directory, 'permission.asked', permissionsResult.value)
|
||||
private getTrackedSessions(): Map<string, string> {
|
||||
const tracked = new Map<string, string>()
|
||||
this.activeSessions.forEach((sessionIDs, directory) => {
|
||||
sessionIDs.forEach(sessionID => tracked.set(sessionID, directory))
|
||||
})
|
||||
for (const ref of this.getScheduledSessions()) {
|
||||
tracked.set(ref.sessionID, ref.directory)
|
||||
}
|
||||
return tracked
|
||||
}
|
||||
|
||||
if (questionsResult.status === 'rejected') {
|
||||
logger.warn(`replay: failed to fetch pending questions for ${directory}: ${String(questionsResult.reason)}`)
|
||||
} else {
|
||||
this.emitPendingEventsToClient(clientId, directory, 'question.asked', questionsResult.value)
|
||||
private async resolveSessionDirectory(fetcher: PendingActionsFetcher, sessionID: string): Promise<string | null> {
|
||||
try {
|
||||
const session = await fetcher.api.session.get({ sessionID })
|
||||
return session.location.directory
|
||||
} catch (error) {
|
||||
logger.warn(`replay: failed to resolve directory for session ${sessionID}: ${String(error)}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private emitPendingEventsToClient(
|
||||
clientId: string,
|
||||
directory: string,
|
||||
type: 'permission.asked' | 'question.asked',
|
||||
items: Array<PendingPermission | PendingQuestion> | null,
|
||||
): void {
|
||||
if (!items || items.length === 0) return
|
||||
|
||||
const client = this.clients.get(clientId)
|
||||
if (!client || !client.directories.has(directory)) return
|
||||
|
||||
for (const item of items) {
|
||||
const payload = JSON.stringify({ directory, payload: { type, properties: item } })
|
||||
try {
|
||||
client.callback('message', payload)
|
||||
} catch (error) {
|
||||
logger.error(`replay: failed to deliver ${type} to client ${clientId}:`, error)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`replay: sent ${items.length} ${type} event(s) for ${directory} to client ${clientId}`)
|
||||
private buildReplayEvent(type: ReplayEventType, directory: string, data: unknown): V2Event {
|
||||
this.replayEventCount += 1
|
||||
return {
|
||||
id: `ocm_replay_${this.replayEventCount}`,
|
||||
created: Date.now(),
|
||||
type,
|
||||
location: { directory },
|
||||
data,
|
||||
} as V2Event
|
||||
}
|
||||
|
||||
private async connectUpstream(): Promise<void> {
|
||||
@@ -326,13 +315,13 @@ class SSEAggregator {
|
||||
this.upstream = null
|
||||
}
|
||||
|
||||
const url = `${getOpenCodeUpstreamBaseUrl()}/global/event`
|
||||
const url = `${getOpenCodeUpstreamBaseUrl()}/api/event`
|
||||
const wasConnectedBefore = this.everConnected
|
||||
logger.info(`SSE connecting to OpenCode global stream: ${url}`)
|
||||
|
||||
const authHeader = this.passwordResolver
|
||||
? await getOpenCodeBasicAuthHeader(this.passwordResolver)
|
||||
: getOpenCodeBasicAuthHeader()
|
||||
: null
|
||||
|
||||
if (!this.started) return
|
||||
|
||||
@@ -353,14 +342,7 @@ class SSEAggregator {
|
||||
this.upstream = es
|
||||
|
||||
es.onopen = () => {
|
||||
logger.info('SSE global stream connected')
|
||||
this.upstreamConnected = true
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.everConnected = true
|
||||
if (wasConnectedBefore) {
|
||||
void this.replayPendingActionsForAllClients()
|
||||
void this.replaySessionStatusesForTrackedDirectories()
|
||||
}
|
||||
this.handleUpstreamOpen(wasConnectedBefore)
|
||||
}
|
||||
|
||||
es.onerror = (event) => {
|
||||
@@ -380,6 +362,21 @@ class SSEAggregator {
|
||||
}
|
||||
}
|
||||
|
||||
private handleUpstreamOpen(wasConnectedBefore: boolean): void {
|
||||
logger.info('SSE global stream connected')
|
||||
this.upstreamConnected = true
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.everConnected = true
|
||||
this.broadcastResync()
|
||||
if (wasConnectedBefore) {
|
||||
void this.replaySessionStatusesForTrackedDirectories()
|
||||
}
|
||||
}
|
||||
|
||||
private broadcastResync(): void {
|
||||
this.broadcastToAll('resync', JSON.stringify({ timestamp: Date.now() }))
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (!this.started || this.reconnectTimeout) return
|
||||
this.reconnectTimeout = setTimeout(() => {
|
||||
@@ -395,82 +392,110 @@ class SSEAggregator {
|
||||
}
|
||||
|
||||
private handleUpstreamMessage(data: string): void {
|
||||
let envelope: SSEEventEnvelope
|
||||
let event: V2Event
|
||||
try {
|
||||
envelope = JSON.parse(data) as SSEEventEnvelope
|
||||
event = JSON.parse(data) as V2Event
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
if (!envelope.directory || !envelope.payload?.type) return
|
||||
if (!event?.type) return
|
||||
|
||||
const directory = envelope.directory
|
||||
const parsed = envelope.payload
|
||||
const payloadJson = MULTILINE_PATTERN.test(data) ? JSON.stringify(event) : data
|
||||
const directory = event.location?.directory
|
||||
|
||||
this.handleEvent(directory, parsed)
|
||||
try {
|
||||
if (directory) {
|
||||
this.deliverEvent(directory, event, payloadJson)
|
||||
} else {
|
||||
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`SSE failed to handle ${event.type} event:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
private deliverEvent(directory: string, event: SSEEvent, payloadJson?: string): void {
|
||||
this.handleEvent(directory, event)
|
||||
|
||||
this.eventListeners.forEach(listener => {
|
||||
try { listener(directory, parsed) } catch { /* ignore listener errors */ }
|
||||
try { listener(directory, event) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
|
||||
const subscriberIds = this.directoryClients.get(directory)
|
||||
if (subscriberIds && subscriberIds.size > 0) {
|
||||
let frame: Uint8Array | undefined
|
||||
const getFrame = (): Uint8Array => (frame ??= encodeSSEFrame('message', data))
|
||||
for (const clientId of subscriberIds) {
|
||||
const client = this.clients.get(clientId)
|
||||
if (!client) continue
|
||||
try {
|
||||
client.writeFrame(getFrame())
|
||||
} catch (error) {
|
||||
logger.error(`Failed to send to client ${client.id}:`, error)
|
||||
}
|
||||
if (!subscriberIds || subscriberIds.size === 0) return
|
||||
|
||||
this.writeEnvelopeToClients(subscriberIds, directory, payloadJson ?? JSON.stringify(event))
|
||||
}
|
||||
|
||||
private writeEnvelopeToClients(clientIds: Iterable<string>, directory: string | null, payloadJson: string): void {
|
||||
let frame: Uint8Array | null = null
|
||||
for (const clientId of clientIds) {
|
||||
const client = this.clients.get(clientId)
|
||||
if (!client) continue
|
||||
frame ??= encodeSSEFrame('message', serializeEnvelope(directory, payloadJson))
|
||||
try {
|
||||
client.writeFrame(frame)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to send to client ${client.id}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleEvent(directory: string, event: SSEEvent): void {
|
||||
const { type, properties } = event
|
||||
|
||||
if (type === 'session.status') {
|
||||
const sessionID = properties.sessionID as string
|
||||
const status = properties.status as { type: string }
|
||||
|
||||
if (!sessionID || !status) return
|
||||
|
||||
const isActive = status.type === 'busy' || status.type === 'retry' || status.type === 'compact'
|
||||
|
||||
if (isActive) {
|
||||
this.markSessionActive(directory, sessionID)
|
||||
} else if (status.type === 'idle') {
|
||||
this.markSessionIdle(directory, sessionID)
|
||||
}
|
||||
} else if (type === 'session.idle') {
|
||||
const sessionID = properties.sessionID as string
|
||||
if (sessionID) {
|
||||
this.markSessionIdle(directory, sessionID)
|
||||
}
|
||||
} else if (type === 'session.created' || type === 'session.updated') {
|
||||
const info = properties.info as { id?: string; parentID?: string } | undefined
|
||||
if (info?.id && info.parentID) {
|
||||
let sessions = this.subagentSessions.get(directory)
|
||||
if (!sessions) {
|
||||
sessions = new Set()
|
||||
this.subagentSessions.set(directory, sessions)
|
||||
switch (event.type) {
|
||||
case 'session.status': {
|
||||
const { sessionID, status } = event.data
|
||||
if (status.type === 'idle') {
|
||||
this.markSessionIdle(directory, sessionID)
|
||||
} else {
|
||||
this.markSessionActive(directory, sessionID)
|
||||
}
|
||||
sessions.add(info.id)
|
||||
return
|
||||
}
|
||||
} else if (type === 'session.deleted') {
|
||||
const info = properties.info as { id?: string } | undefined
|
||||
if (info?.id) {
|
||||
const sessions = this.subagentSessions.get(directory)
|
||||
if (sessions) {
|
||||
sessions.delete(info.id)
|
||||
if (sessions.size === 0) {
|
||||
this.subagentSessions.delete(directory)
|
||||
}
|
||||
case 'session.idle': {
|
||||
this.markSessionIdle(directory, event.data.sessionID)
|
||||
return
|
||||
}
|
||||
case 'session.execution.started': {
|
||||
this.markSessionActive(directory, event.data.sessionID)
|
||||
return
|
||||
}
|
||||
case 'session.execution.succeeded':
|
||||
case 'session.execution.failed':
|
||||
case 'session.execution.interrupted': {
|
||||
this.markSessionIdle(directory, event.data.sessionID)
|
||||
return
|
||||
}
|
||||
case 'session.created': {
|
||||
const { sessionID, parentID } = event.data
|
||||
if (parentID) {
|
||||
this.markSubagentSession(directory, sessionID)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'session.deleted': {
|
||||
this.unmarkSubagentSession(directory, event.data.sessionID)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private markSubagentSession(directory: string, sessionID: string): void {
|
||||
let sessions = this.subagentSessions.get(directory)
|
||||
if (!sessions) {
|
||||
sessions = new Set()
|
||||
this.subagentSessions.set(directory, sessions)
|
||||
}
|
||||
sessions.add(sessionID)
|
||||
}
|
||||
|
||||
private unmarkSubagentSession(directory: string, sessionID: string): void {
|
||||
const sessions = this.subagentSessions.get(directory)
|
||||
if (!sessions) return
|
||||
sessions.delete(sessionID)
|
||||
if (sessions.size === 0) {
|
||||
this.subagentSessions.delete(directory)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,19 +568,6 @@ class SSEAggregator {
|
||||
return this.scheduledSessionsResolver?.() ?? []
|
||||
}
|
||||
|
||||
private getScheduledSessionsByDirectory(): Map<string, Set<string>> {
|
||||
const byDirectory = new Map<string, Set<string>>()
|
||||
for (const ref of this.getScheduledSessions()) {
|
||||
let sessions = byDirectory.get(ref.directory)
|
||||
if (!sessions) {
|
||||
sessions = new Set()
|
||||
byDirectory.set(ref.directory, sessions)
|
||||
}
|
||||
sessions.add(ref.sessionID)
|
||||
}
|
||||
return byDirectory
|
||||
}
|
||||
|
||||
getActiveDirectories(): string[] {
|
||||
return Array.from(this.activeSessions.keys())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user