mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Add cron-based scheduling with prompt templates integration (#164)
This commit is contained in:
1 parent
cbd0ee2958
commit
1e863c5fc5
63 files changed
+7797
-64
No files matched your search
@@ -0,0 +1,158 @@
|
||||
import { proxyToOpenCodeWithDirectory } from './proxy'
|
||||
|
||||
interface OpenCodeConfigResponse {
|
||||
model?: string
|
||||
small_model?: string
|
||||
}
|
||||
|
||||
interface OpenCodeProviderResponse {
|
||||
providers?: Array<{
|
||||
id: string
|
||||
models?: Record<string, unknown>
|
||||
}>
|
||||
default?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface ResolvedOpenCodeModel {
|
||||
providerID: string
|
||||
modelID: string
|
||||
model: string
|
||||
}
|
||||
|
||||
function normalizeModelCandidate(model: string | null | undefined): string | null {
|
||||
if (!model) {
|
||||
return null
|
||||
}
|
||||
|
||||
const normalized = model.trim()
|
||||
return normalized ? normalized : null
|
||||
}
|
||||
|
||||
function parseModel(model: string): ResolvedOpenCodeModel | null {
|
||||
const [providerID, ...modelParts] = model.split('/')
|
||||
const modelID = modelParts.join('/')
|
||||
|
||||
if (!providerID || !modelID) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
providerID,
|
||||
modelID,
|
||||
model: `${providerID}/${modelID}`,
|
||||
}
|
||||
}
|
||||
|
||||
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(directory?: string): Promise<OpenCodeConfigResponse> {
|
||||
const response = await proxyToOpenCodeWithDirectory('/config', 'GET', directory)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(errorText || 'Failed to fetch OpenCode config')
|
||||
}
|
||||
|
||||
return await response.json() as OpenCodeConfigResponse
|
||||
}
|
||||
|
||||
async function fetchOpenCodeProviders(directory?: string): Promise<OpenCodeProviderResponse> {
|
||||
const response = await proxyToOpenCodeWithDirectory('/config/providers', 'GET', directory)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(errorText || 'Failed to fetch OpenCode providers')
|
||||
}
|
||||
|
||||
return await response.json() as OpenCodeProviderResponse
|
||||
}
|
||||
|
||||
export async function resolveOpenCodeModel(
|
||||
directory: string | undefined,
|
||||
options?: {
|
||||
preferredModel?: string | null
|
||||
preferSmallModel?: boolean
|
||||
},
|
||||
): Promise<ResolvedOpenCodeModel> {
|
||||
const [config, providersResponse] = await Promise.all([
|
||||
fetchOpenCodeConfig(directory),
|
||||
fetchOpenCodeProviders(directory),
|
||||
])
|
||||
|
||||
const availableModels = buildAvailableModels(providersResponse)
|
||||
const defaultModels = providersResponse.default ?? {}
|
||||
const configCandidates = options?.preferSmallModel
|
||||
? [config.small_model, config.model]
|
||||
: [config.model, config.small_model]
|
||||
const candidates = uniqueCandidates([options?.preferredModel, ...configCandidates])
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (availableModels.has(candidate)) {
|
||||
const parsedCandidate = parseModel(candidate)
|
||||
if (parsedCandidate) {
|
||||
return parsedCandidate
|
||||
}
|
||||
}
|
||||
|
||||
const parsedCandidate = parseModel(candidate)
|
||||
if (!parsedCandidate) {
|
||||
continue
|
||||
}
|
||||
|
||||
const providerDefaultModel = defaultModels[parsedCandidate.providerID]
|
||||
if (!providerDefaultModel) {
|
||||
continue
|
||||
}
|
||||
|
||||
const providerDefault = `${parsedCandidate.providerID}/${providerDefaultModel}`
|
||||
if (availableModels.has(providerDefault)) {
|
||||
return {
|
||||
providerID: parsedCandidate.providerID,
|
||||
modelID: providerDefaultModel,
|
||||
model: providerDefault,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [providerID, modelID] of Object.entries(defaultModels)) {
|
||||
const model = `${providerID}/${modelID}`
|
||||
if (availableModels.has(model)) {
|
||||
return {
|
||||
providerID,
|
||||
modelID,
|
||||
model,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('No configured OpenCode models are available')
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { CreatePromptTemplateRequest, UpdatePromptTemplateRequest } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
listPromptTemplates,
|
||||
getPromptTemplateById,
|
||||
createPromptTemplate,
|
||||
updatePromptTemplate,
|
||||
deletePromptTemplate,
|
||||
} from '../db/prompt-templates'
|
||||
|
||||
export class PromptTemplateServiceError extends Error {
|
||||
constructor(message: string, public statusCode: number = 500) {
|
||||
super(message)
|
||||
this.name = 'PromptTemplateServiceError'
|
||||
}
|
||||
}
|
||||
|
||||
export class PromptTemplateService {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
list() {
|
||||
return listPromptTemplates(this.db)
|
||||
}
|
||||
|
||||
getById(id: number) {
|
||||
const template = getPromptTemplateById(this.db, id)
|
||||
if (!template) throw new PromptTemplateServiceError('Template not found', 404)
|
||||
return template
|
||||
}
|
||||
|
||||
create(data: CreatePromptTemplateRequest) {
|
||||
return createPromptTemplate(this.db, data)
|
||||
}
|
||||
|
||||
update(id: number, data: UpdatePromptTemplateRequest) {
|
||||
const template = updatePromptTemplate(this.db, id, data)
|
||||
if (!template) throw new PromptTemplateServiceError('Template not found', 404)
|
||||
return template
|
||||
}
|
||||
|
||||
delete(id: number) {
|
||||
const deleted = deletePromptTemplate(this.db, id)
|
||||
if (!deleted) throw new PromptTemplateServiceError('Template not found', 404)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { Cron } from 'croner'
|
||||
import type {
|
||||
CreateScheduleJobRequest,
|
||||
ScheduleJob,
|
||||
ScheduleMode,
|
||||
ScheduleSkillMetadata,
|
||||
UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
|
||||
const DEFAULT_CRON_TIMEZONE = 'UTC'
|
||||
|
||||
export interface ScheduleJobPersistenceInput {
|
||||
name: string
|
||||
description: string | null
|
||||
enabled: boolean
|
||||
scheduleMode: ScheduleMode
|
||||
intervalMinutes: number | null
|
||||
cronExpression: string | null
|
||||
timezone: string | null
|
||||
agentSlug: string | null
|
||||
prompt: string
|
||||
model: string | null
|
||||
skillMetadata: ScheduleSkillMetadata | null | undefined
|
||||
nextRunAt: number | null
|
||||
}
|
||||
|
||||
function validateTimeZone(timezone: string): string {
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-US', { timeZone: timezone })
|
||||
return timezone
|
||||
} catch {
|
||||
throw new Error(`Invalid timezone: ${timezone}`)
|
||||
}
|
||||
}
|
||||
|
||||
function getCronNextRunAt(cronExpression: string, timezone: string, currentDate: number): number {
|
||||
const cron = new Cron(cronExpression, { timezone })
|
||||
const next = cron.nextRun(new Date(currentDate))
|
||||
if (!next) {
|
||||
throw new Error(`Cron expression "${cronExpression}" has no upcoming run`)
|
||||
}
|
||||
return next.getTime()
|
||||
}
|
||||
|
||||
function normalizeCronConfig(cronExpression: string, timezone: string | null | undefined, currentDate: number) {
|
||||
const normalizedTimezone = validateTimeZone(timezone?.trim() || DEFAULT_CRON_TIMEZONE)
|
||||
const normalizedCronExpression = cronExpression.trim()
|
||||
const nextRunAt = getCronNextRunAt(normalizedCronExpression, normalizedTimezone, currentDate)
|
||||
|
||||
return {
|
||||
scheduleMode: 'cron' as const,
|
||||
intervalMinutes: null,
|
||||
cronExpression: normalizedCronExpression,
|
||||
timezone: normalizedTimezone,
|
||||
nextRunAt,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeIntervalConfig(intervalMinutes: number, currentDate: number) {
|
||||
return {
|
||||
scheduleMode: 'interval' as const,
|
||||
intervalMinutes,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
nextRunAt: currentDate + intervalMinutes * 60_000,
|
||||
}
|
||||
}
|
||||
|
||||
export function computeNextRunAtForJob(job: ScheduleJob, currentDate: number): number | null {
|
||||
if (!job.enabled) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (job.scheduleMode === 'cron') {
|
||||
if (!job.cronExpression) {
|
||||
throw new Error('Cron expression is required for cron schedules')
|
||||
}
|
||||
|
||||
return getCronNextRunAt(job.cronExpression, job.timezone || DEFAULT_CRON_TIMEZONE, currentDate)
|
||||
}
|
||||
|
||||
if (!job.intervalMinutes) {
|
||||
throw new Error('Interval minutes are required for interval schedules')
|
||||
}
|
||||
|
||||
return currentDate + job.intervalMinutes * 60_000
|
||||
}
|
||||
|
||||
export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequest, currentDate: number = Date.now()): ScheduleJobPersistenceInput {
|
||||
const base = {
|
||||
name: input.name.trim(),
|
||||
description: input.description?.trim() || null,
|
||||
enabled: input.enabled !== false,
|
||||
agentSlug: input.agentSlug?.trim() || null,
|
||||
prompt: input.prompt.trim(),
|
||||
model: input.model?.trim() || null,
|
||||
skillMetadata: input.skillMetadata,
|
||||
}
|
||||
|
||||
const scheduleConfig = input.scheduleMode === 'cron'
|
||||
? normalizeCronConfig(input.cronExpression, input.timezone, currentDate)
|
||||
: normalizeIntervalConfig(input.intervalMinutes, currentDate)
|
||||
|
||||
return {
|
||||
...base,
|
||||
...scheduleConfig,
|
||||
nextRunAt: base.enabled ? scheduleConfig.nextRunAt : null,
|
||||
}
|
||||
}
|
||||
|
||||
export function buildUpdatedSchedulePersistenceInput(
|
||||
existing: ScheduleJob,
|
||||
input: UpdateScheduleJobRequest,
|
||||
currentDate: number = Date.now(),
|
||||
): ScheduleJobPersistenceInput {
|
||||
const enabled = input.enabled ?? existing.enabled
|
||||
const scheduleMode = input.scheduleMode ?? existing.scheduleMode
|
||||
|
||||
const scheduleConfig = scheduleMode === 'cron'
|
||||
? normalizeCronConfig(
|
||||
input.cronExpression ?? existing.cronExpression ?? '',
|
||||
input.timezone ?? existing.timezone ?? DEFAULT_CRON_TIMEZONE,
|
||||
currentDate,
|
||||
)
|
||||
: normalizeIntervalConfig(
|
||||
input.intervalMinutes ?? existing.intervalMinutes ?? 60,
|
||||
currentDate,
|
||||
)
|
||||
|
||||
const scheduleChanged =
|
||||
input.scheduleMode !== undefined ||
|
||||
input.intervalMinutes !== undefined ||
|
||||
input.cronExpression !== undefined ||
|
||||
input.timezone !== undefined
|
||||
|
||||
const nextRunAt = enabled
|
||||
? scheduleChanged || input.enabled !== undefined || existing.nextRunAt === null
|
||||
? scheduleConfig.nextRunAt
|
||||
: existing.nextRunAt
|
||||
: null
|
||||
|
||||
return {
|
||||
name: input.name?.trim() || existing.name,
|
||||
description: input.description === undefined ? existing.description : (input.description?.trim() || null),
|
||||
enabled,
|
||||
scheduleMode: scheduleConfig.scheduleMode,
|
||||
intervalMinutes: scheduleConfig.intervalMinutes,
|
||||
cronExpression: scheduleConfig.cronExpression,
|
||||
timezone: scheduleConfig.timezone,
|
||||
agentSlug: input.agentSlug === undefined ? existing.agentSlug : (input.agentSlug?.trim() || null),
|
||||
prompt: input.prompt?.trim() || existing.prompt,
|
||||
model: input.model === undefined ? existing.model : (input.model?.trim() || null),
|
||||
skillMetadata: input.skillMetadata === undefined ? existing.skillMetadata : input.skillMetadata,
|
||||
nextRunAt,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user