Add cron-based scheduling with prompt templates integration (#164)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-21 23:33:03 -04:00
1 parent cbd0ee2958
commit 1e863c5fc5
63 files changed
+7797 -64

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
import { Hono, type Context } from 'hono'
import type { Database } from 'bun:sqlite'
import {
CreatePromptTemplateRequestSchema,
UpdatePromptTemplateRequestSchema,
} from '@opencode-manager/shared/schemas'
import { PromptTemplateService, PromptTemplateServiceError } from '../services/prompt-templates'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
function parseId(value: string | undefined): number {
const parsed = Number.parseInt(value ?? '', 10)
if (Number.isNaN(parsed)) throw new PromptTemplateServiceError('Invalid id', 400)
return parsed
}
function handleTemplateError(c: Context, error: unknown, fallback: string) {
if (error instanceof PromptTemplateServiceError) {
return c.json({ error: error.message }, error.statusCode as 400 | 404 | 500)
}
logger.error(fallback, error)
return c.json({ error: getErrorMessage(error) }, 500)
}
export function createPromptTemplateRoutes(database: Database) {
const app = new Hono()
const service = new PromptTemplateService(database)
app.get('/', (c) => {
try {
return c.json({ templates: service.list() })
} catch (error) {
return handleTemplateError(c, error, 'Failed to list templates')
}
})
app.post('/', async (c) => {
try {
const body = await c.req.json()
const input = CreatePromptTemplateRequestSchema.parse(body)
const template = service.create(input)
return c.json({ template }, 201)
} catch (error) {
return handleTemplateError(c, error, 'Failed to create template')
}
})
app.get('/:id', (c) => {
try {
const id = parseId(c.req.param('id'))
return c.json({ template: service.getById(id) })
} catch (error) {
return handleTemplateError(c, error, 'Failed to get template')
}
})
app.patch('/:id', async (c) => {
try {
const id = parseId(c.req.param('id'))
const body = await c.req.json()
const input = UpdatePromptTemplateRequestSchema.parse(body)
const template = service.update(id, input)
return c.json({ template })
} catch (error) {
return handleTemplateError(c, error, 'Failed to update template')
}
})
app.delete('/:id', (c) => {
try {
const id = parseId(c.req.param('id'))
service.delete(id)
return c.body(null, 204)
} catch (error) {
return handleTemplateError(c, error, 'Failed to delete template')
}
})
return app
}
+2
View File
@@ -13,6 +13,7 @@ import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
import { createRepoGitRoutes } from './repo-git'
import { createScheduleRoutes } from './schedules'
import type { GitAuthService } from '../services/git-auth'
import path from 'path'
@@ -20,6 +21,7 @@ export function createRepoRoutes(database: Database, gitAuthService: GitAuthServ
const app = new Hono()
app.route('/', createRepoGitRoutes(database, gitAuthService))
app.route('/:id/schedules', createScheduleRoutes(database))
app.post('/', async (c) => {
try {
+154
View File
@@ -0,0 +1,154 @@
import { Hono, type Context } from 'hono'
import type { Database } from 'bun:sqlite'
import {
CreateScheduleJobRequestSchema,
UpdateScheduleJobRequestSchema,
} from '@opencode-manager/shared/schemas'
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
function parseId(value: string | undefined, label: string): number {
if (!value) {
throw new ScheduleServiceError(`Missing ${label}`, 400)
}
const parsed = Number.parseInt(value, 10)
if (Number.isNaN(parsed)) {
throw new ScheduleServiceError(`Invalid ${label}`, 400)
}
return parsed
}
function parseRunListLimit(value: string | undefined): number {
if (value === undefined) {
return 20
}
const parsed = parseId(value, 'limit')
if (parsed < 1) {
throw new ScheduleServiceError('Limit must be greater than 0', 400)
}
return Math.min(parsed, 100)
}
export function createScheduleRoutes(database: Database) {
const app = new Hono()
const scheduleService = new ScheduleService(database)
app.get('/', (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
return c.json({ jobs: scheduleService.listJobs(repoId) })
} catch (error) {
return handleScheduleError(c, error, 'Failed to list schedules')
}
})
app.post('/', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const body = await c.req.json()
const input = CreateScheduleJobRequestSchema.parse(body)
const job = scheduleService.createJob(repoId, input)
return c.json({ job }, 201)
} catch (error) {
return handleScheduleError(c, error, 'Failed to create schedule')
}
})
app.get('/:jobId', (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
const job = scheduleService.getJob(repoId, jobId)
if (!job) {
return c.json({ error: 'Schedule not found' }, 404)
}
return c.json({ job })
} catch (error) {
return handleScheduleError(c, error, 'Failed to get schedule')
}
})
app.patch('/:jobId', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
const body = await c.req.json()
const input = UpdateScheduleJobRequestSchema.parse(body)
const job = scheduleService.updateJob(repoId, jobId, input)
return c.json({ job })
} catch (error) {
return handleScheduleError(c, error, 'Failed to update schedule')
}
})
app.delete('/:jobId', (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
scheduleService.deleteJob(repoId, jobId)
return c.json({ success: true })
} catch (error) {
return handleScheduleError(c, error, 'Failed to delete schedule')
}
})
app.post('/:jobId/run', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
const run = await scheduleService.runJob(repoId, jobId, 'manual')
return c.json({ run })
} catch (error) {
return handleScheduleError(c, error, 'Failed to run schedule')
}
})
app.get('/:jobId/runs', (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
const limit = parseRunListLimit(c.req.query('limit'))
return c.json({ runs: scheduleService.listRuns(repoId, jobId, limit) })
} catch (error) {
return handleScheduleError(c, error, 'Failed to list schedule runs')
}
})
app.get('/:jobId/runs/:runId', (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
const runId = parseId(c.req.param('runId'), 'run id')
return c.json({ run: scheduleService.getRun(repoId, jobId, runId) })
} catch (error) {
return handleScheduleError(c, error, 'Failed to get schedule run')
}
})
app.post('/:jobId/runs/:runId/cancel', async (c) => {
try {
const repoId = parseId(c.req.param('id'), 'repo id')
const jobId = parseId(c.req.param('jobId'), 'schedule id')
const runId = parseId(c.req.param('runId'), 'run id')
const run = await scheduleService.cancelRun(repoId, jobId, runId)
return c.json({ run })
} catch (error) {
return handleScheduleError(c, error, 'Failed to cancel schedule run')
}
})
return app
}
function handleScheduleError(c: Context, error: unknown, fallbackMessage: string) {
if (error instanceof ScheduleServiceError) {
return c.json({ error: error.message }, error.status as 400 | 404 | 409 | 500 | 502)
}
logger.error(fallbackMessage + ':', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
+100 -27
View File
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
import { z } from 'zod'
import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { resolveOpenCodeModel } from '../services/opencode-models'
const TitleRequestSchema = z.object({
text: z.string().min(1).max(5000),
@@ -9,12 +10,101 @@ const TitleRequestSchema = z.object({
})
const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}`
const TITLE_POLL_INTERVAL_MS = 1_000
const TITLE_POLL_TIMEOUT_MS = 30_000
interface PromptResponse {
parts?: Array<{ type?: string; text?: string }>
}
interface SessionMessage {
info?: {
role?: string
time?: {
completed?: number
}
error?: {
name?: string
data?: {
message?: string
}
}
}
parts?: Array<{ type?: string; text?: string }>
}
function buildUrl(path: string, directory?: string): string {
const url = `${OPENCODE_SERVER_URL}${path}`
return directory ? `${url}${url.includes('?') ? '&' : '?'}directory=${encodeURIComponent(directory)}` : url
}
function parsePromptResponse(responseText: string): PromptResponse | null {
if (!responseText.trim()) {
return null
}
try {
return JSON.parse(responseText) as PromptResponse
} catch {
return null
}
}
function extractText(parts: Array<{ type?: string; text?: string }> | 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')
}
function extractTitle(result: PromptResponse | SessionMessage): string {
const text = extractText(result.parts)
const title = text
.split('\n')
.map((line) => line.trim())
.find((line) => line.length > 0) || ''
if (title.length > 100) {
return title.substring(0, 97) + '...'
}
return title
}
async function waitForTitleResponse(sessionID: string, directory: string): Promise<SessionMessage> {
const startedAt = Date.now()
while (Date.now() - startedAt < TITLE_POLL_TIMEOUT_MS) {
const messagesResponse = await fetch(buildUrl(`/session/${sessionID}/message`, directory))
if (!messagesResponse.ok) {
const errorText = await messagesResponse.text()
throw new Error(errorText || 'Failed to fetch title generation messages')
}
const messages = await messagesResponse.json() as SessionMessage[]
const assistantMessage = [...messages]
.reverse()
.find((message) => message.info?.role === 'assistant')
if (assistantMessage) {
const errorText = assistantMessage.info?.error?.data?.message ?? assistantMessage.info?.error?.name
if (errorText) {
throw new Error(errorText)
}
if (assistantMessage.info?.time?.completed) {
return assistantMessage
}
}
await Bun.sleep(TITLE_POLL_INTERVAL_MS)
}
throw new Error('Timed out waiting for title generation')
}
const TITLE_PROMPT = `You are a title generator. You output ONLY a thread title. Nothing else.
<task>
@@ -63,15 +153,9 @@ export function createTitleRoutes() {
logger.info('Generating session title via LLM', { sessionID, textLength: text.length })
const configResponse = await fetch(buildUrl('/config', directory))
if (!configResponse.ok) {
logger.error('Failed to fetch OpenCode config')
return c.json({ error: 'Failed to fetch config' }, 500)
}
const config = await configResponse.json() as { model?: string; small_model?: string }
const modelStr = config.small_model || (config.model ?? "")
const [providerID, modelID] = modelStr.split('/')
const model = await resolveOpenCodeModel(directory || undefined, {
preferSmallModel: true,
})
const titleSessionResponse = await fetch(buildUrl('/session', directory), {
method: 'POST',
@@ -98,7 +182,10 @@ export function createTitleRoutes() {
text: `${TITLE_PROMPT}\n\nGenerate a title for this conversation:\n<user_message>\n${text.substring(0, 2000)}\n</user_message>`
}
],
model: { providerID, modelID }
model: {
providerID: model.providerID,
modelID: model.modelID,
}
})
})
@@ -108,23 +195,9 @@ export function createTitleRoutes() {
return c.json({ error: 'LLM request failed' }, 500)
}
const result = await promptResponse.json() as { parts?: Array<{ type: string; text?: string }> }
let title = ''
if (result.parts) {
const textPart = result.parts.find((p: { type: string }) => p.type === 'text')
if (textPart && 'text' in textPart) {
title = (textPart.text as string)
.replace(/<think>[\s\S]*?<\/think>\s*/g, '')
.split('\n')
.map((line: string) => line.trim())
.find((line: string) => line.length > 0) || ''
}
}
if (title && title.length > 100) {
title = title.substring(0, 97) + '...'
}
const promptBody = await promptResponse.text()
const promptResult = parsePromptResponse(promptBody)
const title = extractTitle(promptResult ?? await waitForTitleResponse(titleSessionID, directory))
if (title) {
const updateResponse = await fetch(buildUrl(`/session/${sessionID}`, directory), {