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

@@ -0,0 +1,58 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 7,
name: 'schedules',
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS schedule_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
interval_minutes INTEGER,
agent_slug TEXT,
prompt TEXT NOT NULL,
model TEXT,
skill_metadata TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
last_run_at INTEGER,
next_run_at INTEGER
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
db.run(`
CREATE TABLE IF NOT EXISTS schedule_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
trigger_source TEXT NOT NULL,
status TEXT NOT NULL,
started_at INTEGER NOT NULL,
finished_at INTEGER,
created_at INTEGER NOT NULL,
session_id TEXT,
session_title TEXT,
log_text TEXT,
response_text TEXT,
error_text TEXT
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
},
down(db) {
db.run('DROP TABLE IF EXISTS schedule_runs')
db.run('DROP TABLE IF EXISTS schedule_jobs')
},
}
export default migration
@@ -0,0 +1,129 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
notnull: number
dflt_value: string | null
}
const migration: Migration = {
version: 8,
name: 'schedule-cron-support',
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
const existingColumns = new Set(tableInfo.map((column) => column.name))
const intervalMinutesColumn = tableInfo.find((column) => column.name === 'interval_minutes')
const scheduleModeColumn = tableInfo.find((column) => column.name === 'schedule_mode')
const hasCronColumns = existingColumns.has('schedule_mode') && existingColumns.has('cron_expression') && existingColumns.has('timezone')
const scheduleModeDefault = scheduleModeColumn?.dflt_value?.replaceAll("'", '')
if (intervalMinutesColumn?.notnull === 0 && hasCronColumns && scheduleModeDefault === 'interval') {
return
}
db.run(`
CREATE TABLE schedule_jobs_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
interval_minutes INTEGER,
schedule_mode TEXT NOT NULL DEFAULT 'interval',
cron_expression TEXT,
timezone TEXT,
agent_slug TEXT,
prompt TEXT NOT NULL,
model TEXT,
skill_metadata TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
last_run_at INTEGER,
next_run_at INTEGER
)
`)
db.run(`
INSERT INTO schedule_jobs_new (
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
agent_slug, prompt, model, skill_metadata, created_at, updated_at, last_run_at, next_run_at
)
SELECT
id,
repo_id,
name,
description,
enabled,
interval_minutes,
${existingColumns.has('schedule_mode') ? "COALESCE(schedule_mode, 'interval')" : "'interval'"},
${existingColumns.has('cron_expression') ? 'cron_expression' : 'NULL'},
${existingColumns.has('timezone') ? 'timezone' : 'NULL'},
agent_slug,
prompt,
model,
skill_metadata,
created_at,
updated_at,
last_run_at,
next_run_at
FROM schedule_jobs
`)
db.run('DROP TABLE schedule_jobs')
db.run('ALTER TABLE schedule_jobs_new RENAME TO schedule_jobs')
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
},
down(db) {
db.run(`
CREATE TABLE schedule_jobs_old (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
interval_minutes INTEGER NOT NULL,
agent_slug TEXT,
prompt TEXT NOT NULL,
model TEXT,
skill_metadata TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
last_run_at INTEGER,
next_run_at INTEGER
)
`)
db.run(`
INSERT INTO schedule_jobs_old (
id, repo_id, name, description, enabled, interval_minutes, agent_slug, prompt, model, skill_metadata,
created_at, updated_at, last_run_at, next_run_at
)
SELECT
id,
repo_id,
name,
description,
enabled,
COALESCE(interval_minutes, 60),
agent_slug,
prompt,
model,
skill_metadata,
created_at,
updated_at,
last_run_at,
next_run_at
FROM schedule_jobs
`)
db.run('DROP TABLE schedule_jobs')
db.run('ALTER TABLE schedule_jobs_old RENAME TO schedule_jobs')
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
},
}
export default migration
@@ -0,0 +1,315 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 10,
name: '010-prompt-templates',
up(db) {
db.run(`
CREATE TABLE prompt_templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
category TEXT NOT NULL,
cadence_hint TEXT NOT NULL,
suggested_name TEXT NOT NULL,
suggested_description TEXT NOT NULL DEFAULT '',
description TEXT NOT NULL DEFAULT '',
prompt TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
const now = Date.now()
const insert = db.prepare(`
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
insert.run(
'Repo Health Report',
'Health',
'Weekly',
'Weekly repo health report',
'Summarize code health, risk areas, and the next highest-leverage follow-ups.',
'A broad weekly review of project health, risks, and recommended next actions.',
[
'Review this repository and prepare a concise weekly health report.',
'',
'Focus on:',
'- overall code health and maintainability signals',
'- risky or stale areas in the codebase',
'- flaky, fragile, or untested workflows',
'- notable recent drift in tooling, scripts, or structure',
'',
'Do not modify files or create commits.',
'',
'Return the result in these sections:',
'1. Overall Status',
'2. Key Risks',
'3. What Changed or Drifted',
'4. Recommended Next Actions',
].join('\n'),
now,
now,
)
insert.run(
'Dependency Watchlist',
'Maintenance',
'Weekly',
'Dependency watchlist',
'Review dependency health, upgrade pressure, and risky package drift.',
'Surfaces outdated, risky, or inconsistent dependencies and upgrade priorities.',
[
'Audit this repository for dependency risk and upgrade pressure.',
'',
'Inspect package manifests, lockfiles, build tooling, runtime dependencies, and obvious version drift.',
'',
'Focus on:',
'- outdated or inconsistent package versions',
'- packages that look risky, abandoned, duplicated, or unnecessary',
'- tooling mismatches that could cause local vs CI drift',
'- high-priority upgrades to tackle next',
'',
'Do not change files.',
'',
'Return:',
'1. Highest Priority Upgrades',
'2. Risky or Inconsistent Dependencies',
'3. Tooling Drift',
'4. Suggested Upgrade Order',
].join('\n'),
now,
now,
)
insert.run(
'Release Readiness Review',
'Release',
'Before release',
'Release readiness review',
'Check whether the repo looks ready to ship and what could block release confidence.',
'A pre-release checkpoint for blockers, missing validation, and confidence gaps.',
[
'Review this repository for release readiness.',
'',
'Focus on anything that would reduce confidence in shipping soon, including:',
'- missing validation, tests, or smoke coverage',
'- fragile configuration or deployment assumptions',
'- unfinished, ambiguous, or risky recent work',
'- docs or scripts that appear stale relative to the implementation',
'',
'Do not edit files.',
'',
'Return:',
'1. Release Confidence',
'2. Blockers',
'3. Follow-ups Before Shipping',
'4. Nice-to-have Cleanup After Release',
].join('\n'),
now,
now,
)
insert.run(
'Test Stability Audit',
'Quality',
'Weekly',
'Test stability audit',
'Find flaky areas, missing coverage signals, and brittle testing patterns.',
'Looks at test quality, slow paths, brittle coverage, and likely flaky areas.',
[
'Inspect this repository for test stability and coverage risk.',
'',
'Focus on:',
'- flaky or brittle test patterns',
'- important product areas with weak or missing coverage',
'- slow or overcomplicated test flows',
'- test setup/config problems that could cause false confidence',
'',
'Do not modify files.',
'',
'Return:',
'1. Confidence Gaps',
'2. Flaky or Fragile Areas',
'3. Coverage Priorities',
'4. Suggested Test Improvements',
].join('\n'),
now,
now,
)
insert.run(
'Docs Drift Review',
'Docs',
'Biweekly',
'Docs drift review',
'Check whether README, setup steps, and docs still match the current repo.',
'Finds README/setup/documentation drift relative to the actual codebase.',
[
'Review this repository for documentation drift.',
'',
'Compare README files, setup instructions, scripts, and other repo docs against the actual implementation and project structure.',
'',
'Focus on:',
'- stale setup or run instructions',
'- missing documentation for important workflows',
'- docs that no longer match the codebase structure or tooling',
'- confusing or duplicated documentation',
'',
'Do not edit files.',
'',
'Return:',
'1. Docs That Look Stale',
'2. Missing Documentation',
'3. Confusing or Conflicting Guidance',
'4. Suggested Documentation Updates',
].join('\n'),
now,
now,
)
insert.run(
'Tech Debt Triage',
'Planning',
'Weekly',
'Tech debt triage',
'Identify the most expensive sources of drag and rank cleanup opportunities.',
'Ranks the most valuable cleanup and refactor opportunities in the repo.',
[
'Review this repository and identify the most important technical debt to address next.',
'',
'Focus on debt that creates drag for delivery, reliability, or maintainability, such as:',
'- duplicated logic or tangled ownership',
'- brittle architecture seams',
'- outdated patterns or confusing abstractions',
'- hotspots that are hard to safely change',
'',
'Do not make changes.',
'',
'Return:',
'1. Top Technical Debt Items',
'2. Why Each Item Matters',
'3. Cost vs Impact',
'4. Recommended Cleanup Order',
].join('\n'),
now,
now,
)
insert.run(
'Security and Config Review',
'Security',
'Weekly',
'Security and config review',
'Inspect obvious security, secrets, and environment/config handling risks.',
'Looks for obvious secrets, auth, and configuration handling issues.',
[
'Inspect this repository for obvious security and configuration handling risks.',
'',
'Focus on:',
'- secrets or credentials handling problems',
'- risky defaults in environment or auth configuration',
'- places where permission checks or trust assumptions look weak',
'- config sprawl that could cause unsafe deployments',
'',
'Stay read-only. Do not modify files.',
'',
'Return:',
'1. High-Risk Findings',
'2. Medium-Risk Findings',
'3. Configuration Concerns',
'4. Recommended Fixes',
].join('\n'),
now,
now,
)
insert.run(
'CI and Ops Review',
'Operations',
'Weekly',
'CI and ops review',
'Check CI, scripts, and operational workflows for fragility or drift.',
'Surfaces friction or fragility in CI, automation, and repo operations.',
[
'Review this repository for CI, automation, and operational workflow issues.',
'',
'Focus on:',
'- brittle build or test assumptions',
'- scripts that look stale, redundant, or inconsistent',
'- automation that appears slow, noisy, or easy to break',
'- workflow gaps that could hurt developer reliability',
'',
'Do not edit files.',
'',
'Return:',
'1. Operational Risks',
'2. CI or Automation Drift',
'3. Reliability Improvements',
'4. Highest-Leverage Next Steps',
].join('\n'),
now,
now,
)
insert.run(
'Onboarding Brief',
'Knowledge',
'Monthly',
'Onboarding brief refresh',
'Produce a concise orientation summary for someone new to the repo.',
'Creates a concise orientation guide for engineers who are new to the repo.',
[
'Prepare an onboarding brief for an engineer who is new to this repository.',
'',
'Focus on:',
'- the repo structure and major areas of responsibility',
'- the core development workflows and important commands',
'- risky or confusing areas worth knowing early',
'- where a new engineer should start reading or exploring',
'',
'Do not modify files.',
'',
'Return:',
'1. What This Repo Does',
'2. Important Areas to Know',
'3. Local Workflow Cheatsheet',
'4. Common Pitfalls and First Reading List',
].join('\n'),
now,
now,
)
insert.run(
'Memory Candidate Review',
'Knowledge',
'Biweekly',
'Memory candidate review',
'Identify stable conventions, decisions, and context worth preserving as memory.',
'Great for repos using durable memory or team conventions that should be captured.',
[
'Review this repository and identify durable knowledge worth preserving as long-lived memory.',
'',
'Focus on conventions, architectural decisions, recurring workflows, and stable context that future sessions should know.',
'',
'Do not create or update memory directly. Just recommend candidates.',
'',
'Return:',
'1. Candidate Conventions',
'2. Candidate Decisions',
'3. Candidate Context',
'4. Why Each Item Should Be Preserved',
].join('\n'),
now,
now,
)
},
down(db) {
db.run('DROP TABLE IF EXISTS prompt_templates')
},
}
export default migration
+6
View File
@@ -5,7 +5,10 @@ import migration003 from './003-repos-add-columns'
import migration004 from './004-repos-indexes'
import migration005 from './005-repos-local-path-prefix'
import migration006 from './006-git-token-to-credentials'
import migration007 from './007-schedules'
import migration008 from './008-schedule-cron-support'
import migration009 from './009-repo-source-path'
import migration010 from './009-prompt-templates'
export const allMigrations: Migration[] = [
migration001,
@@ -14,5 +17,8 @@ export const allMigrations: Migration[] = [
migration004,
migration005,
migration006,
migration007,
migration008,
migration009,
migration010,
]
+82
View File
@@ -0,0 +1,82 @@
import type { Database } from 'bun:sqlite'
import {
PromptTemplateSchema,
type PromptTemplate,
type CreatePromptTemplateRequest,
type UpdatePromptTemplateRequest,
} from '@opencode-manager/shared/schemas'
interface PromptTemplateRow {
id: number
title: string
category: string
cadence_hint: string
suggested_name: string
suggested_description: string
description: string
prompt: string
created_at: number
updated_at: number
}
function rowToPromptTemplate(row: PromptTemplateRow): PromptTemplate {
return PromptTemplateSchema.parse({
id: row.id,
title: row.title,
category: row.category,
cadenceHint: row.cadence_hint,
suggestedName: row.suggested_name,
suggestedDescription: row.suggested_description,
description: row.description,
prompt: row.prompt,
createdAt: row.created_at,
updatedAt: row.updated_at,
})
}
export function listPromptTemplates(db: Database): PromptTemplate[] {
const rows = db.prepare('SELECT * FROM prompt_templates ORDER BY id ASC').all() as PromptTemplateRow[]
return rows.map(rowToPromptTemplate)
}
export function getPromptTemplateById(db: Database, id: number): PromptTemplate | null {
const row = db.prepare('SELECT * FROM prompt_templates WHERE id = ?').get(id) as PromptTemplateRow | null
return row ? rowToPromptTemplate(row) : null
}
export function createPromptTemplate(db: Database, data: CreatePromptTemplateRequest): PromptTemplate {
const now = Date.now()
const result = db.prepare(`
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(data.title, data.category, data.cadenceHint, data.suggestedName, data.suggestedDescription, data.description, data.prompt, now, now)
return getPromptTemplateById(db, result.lastInsertRowid as number)!
}
export function updatePromptTemplate(db: Database, id: number, data: UpdatePromptTemplateRequest): PromptTemplate | null {
const existing = getPromptTemplateById(db, id)
if (!existing) return null
const now = Date.now()
db.prepare(`
UPDATE prompt_templates SET
title = ?, category = ?, cadence_hint = ?, suggested_name = ?,
suggested_description = ?, description = ?, prompt = ?, updated_at = ?
WHERE id = ?
`).run(
data.title ?? existing.title,
data.category ?? existing.category,
data.cadenceHint ?? existing.cadenceHint,
data.suggestedName ?? existing.suggestedName,
data.suggestedDescription ?? existing.suggestedDescription,
data.description ?? existing.description,
data.prompt ?? existing.prompt,
now,
id,
)
return getPromptTemplateById(db, id)
}
export function deletePromptTemplate(db: Database, id: number): boolean {
const result = db.prepare('DELETE FROM prompt_templates WHERE id = ?').run(id)
return result.changes > 0
}
+386
View File
@@ -0,0 +1,386 @@
import type { Database } from 'bun:sqlite'
import {
ScheduleJobSchema,
ScheduleRunSchema,
ScheduleSkillMetadataSchema,
type ScheduleJob,
type ScheduleMode,
type ScheduleRun,
type ScheduleRunStatus,
type ScheduleRunTriggerSource,
} from '@opencode-manager/shared/schemas'
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
interface ScheduleJobRow {
id: number
repo_id: number
name: string
description: string | null
enabled: number
schedule_mode: ScheduleMode | null
interval_minutes: number | null
cron_expression: string | null
timezone: string | null
agent_slug: string | null
prompt: string
model: string | null
skill_metadata: string | null
created_at: number
updated_at: number
last_run_at: number | null
next_run_at: number | null
}
interface ScheduleRunRow {
id: number
job_id: number
repo_id: number
trigger_source: string
status: string
started_at: number
finished_at: number | null
created_at: number
session_id: string | null
session_title: string | null
log_text: string | null
response_text: string | null
error_text: string | null
}
function parseSkillMetadata(raw: string | null) {
if (!raw) {
return null
}
try {
const parsed = JSON.parse(raw)
const result = ScheduleSkillMetadataSchema.safeParse(parsed)
return result.success ? result.data : null
} catch {
return null
}
}
function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
return ScheduleJobSchema.parse({
id: row.id,
repoId: row.repo_id,
name: row.name,
description: row.description,
enabled: Boolean(row.enabled),
scheduleMode: row.schedule_mode ?? 'interval',
intervalMinutes: row.interval_minutes,
cronExpression: row.cron_expression,
timezone: row.timezone,
agentSlug: row.agent_slug,
prompt: row.prompt,
model: row.model,
skillMetadata: parseSkillMetadata(row.skill_metadata),
createdAt: row.created_at,
updatedAt: row.updated_at,
lastRunAt: row.last_run_at,
nextRunAt: row.next_run_at,
})
}
function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
return ScheduleRunSchema.parse({
id: row.id,
jobId: row.job_id,
repoId: row.repo_id,
triggerSource: row.trigger_source,
status: row.status,
startedAt: row.started_at,
finishedAt: row.finished_at,
createdAt: row.created_at,
sessionId: row.session_id,
sessionTitle: row.session_title,
logText: row.log_text,
responseText: row.response_text,
errorText: row.error_text,
})
}
function serializeSkillMetadata(skillMetadata: ScheduleJobPersistenceInput['skillMetadata']): string | null {
if (!skillMetadata) {
return null
}
return JSON.stringify(skillMetadata)
}
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
const rows = stmt.all(repoId) as ScheduleJobRow[]
return rows.map(rowToScheduleJob)
}
export function listDueScheduleJobs(db: Database, now: number, limit: number = 20): ScheduleJob[] {
const stmt = db.prepare(`
SELECT * FROM schedule_jobs
WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ?
ORDER BY next_run_at ASC
LIMIT ?
`)
const rows = stmt.all(now, limit) as ScheduleJobRow[]
return rows.map(rowToScheduleJob)
}
export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
const rows = stmt.all() as ScheduleJobRow[]
return rows.map(rowToScheduleJob)
}
export function getScheduleJobById(db: Database, repoId: number, jobId: number): ScheduleJob | null {
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
const row = stmt.get(repoId, jobId) as ScheduleJobRow | undefined
return row ? rowToScheduleJob(row) : null
}
export function createScheduleJob(db: Database, repoId: number, input: ScheduleJobPersistenceInput): ScheduleJob {
const now = Date.now()
const stmt = db.prepare(`
INSERT INTO schedule_jobs (
repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
created_at, updated_at, last_run_at, next_run_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
const result = stmt.run(
repoId,
input.name,
input.description ?? null,
input.enabled ? 1 : 0,
input.scheduleMode,
input.intervalMinutes,
input.cronExpression,
input.timezone,
input.agentSlug ?? null,
input.prompt,
input.model ?? null,
serializeSkillMetadata(input.skillMetadata),
now,
now,
null,
input.nextRunAt,
)
const job = getScheduleJobById(db, repoId, Number(result.lastInsertRowid))
if (!job) {
throw new Error('Failed to load created schedule job')
}
return job
}
export function updateScheduleJob(db: Database, repoId: number, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
const existing = getScheduleJobById(db, repoId, jobId)
if (!existing) {
return null
}
const now = Date.now()
const stmt = db.prepare(`
UPDATE schedule_jobs
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?, agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, updated_at = ?, next_run_at = ?
WHERE repo_id = ? AND id = ?
`)
stmt.run(
input.name,
input.description,
input.enabled ? 1 : 0,
input.scheduleMode,
input.intervalMinutes,
input.cronExpression,
input.timezone,
input.agentSlug,
input.prompt,
input.model,
serializeSkillMetadata(input.skillMetadata),
now,
input.nextRunAt,
repoId,
jobId,
)
return getScheduleJobById(db, repoId, jobId)
}
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
const result = stmt.run(repoId, jobId)
return result.changes > 0
}
export function reserveScheduleJobNextRun(db: Database, repoId: number, jobId: number, nextRunAt: number): void {
const stmt = db.prepare('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(nextRunAt, Date.now(), repoId, jobId)
}
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
}
export function createScheduleRun(
db: Database,
input: {
jobId: number
repoId: number
triggerSource: ScheduleRunTriggerSource
status: ScheduleRunStatus
startedAt: number
createdAt: number
},
): ScheduleRun {
const stmt = db.prepare(`
INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at)
VALUES (?, ?, ?, ?, ?, ?)
`)
const result = stmt.run(
input.jobId,
input.repoId,
input.triggerSource,
input.status,
input.startedAt,
input.createdAt,
)
const run = getScheduleRunById(db, input.repoId, input.jobId, Number(result.lastInsertRowid))
if (!run) {
throw new Error('Failed to load created schedule run')
}
return run
}
export function updateScheduleRun(
db: Database,
repoId: number,
jobId: number,
runId: number,
input: {
status: ScheduleRunStatus
finishedAt: number
sessionId?: string | null
sessionTitle?: string | null
logText?: string | null
responseText?: string | null
errorText?: string | null
},
): ScheduleRun | null {
const stmt = db.prepare(`
UPDATE schedule_runs
SET status = ?, finished_at = ?, session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
WHERE repo_id = ? AND job_id = ? AND id = ?
`)
stmt.run(
input.status,
input.finishedAt,
input.sessionId ?? null,
input.sessionTitle ?? null,
input.logText ?? null,
input.responseText ?? null,
input.errorText ?? null,
repoId,
jobId,
runId,
)
return getScheduleRunById(db, repoId, jobId, runId)
}
export function updateScheduleRunMetadata(
db: Database,
repoId: number,
jobId: number,
runId: number,
input: {
sessionId?: string | null
sessionTitle?: string | null
logText?: string | null
responseText?: string | null
errorText?: string | null
},
): ScheduleRun | null {
const existing = getScheduleRunById(db, repoId, jobId, runId)
if (!existing) {
return null
}
const stmt = db.prepare(`
UPDATE schedule_runs
SET session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
WHERE repo_id = ? AND job_id = ? AND id = ?
`)
stmt.run(
input.sessionId === undefined ? existing.sessionId : input.sessionId,
input.sessionTitle === undefined ? existing.sessionTitle : input.sessionTitle,
input.logText === undefined ? existing.logText : input.logText,
input.responseText === undefined ? existing.responseText : input.responseText,
input.errorText === undefined ? existing.errorText : input.errorText,
repoId,
jobId,
runId,
)
return getScheduleRunById(db, repoId, jobId, runId)
}
export function getScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): ScheduleRun | null {
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
const row = stmt.get(repoId, jobId, runId) as ScheduleRunRow | undefined
return row ? rowToScheduleRun(row) : null
}
export function getRunningScheduleRunByJob(db: Database, repoId: number, jobId: number): ScheduleRun | null {
const stmt = db.prepare(`
SELECT * FROM schedule_runs
WHERE repo_id = ? AND job_id = ? AND status = 'running'
ORDER BY started_at DESC
LIMIT 1
`)
const row = stmt.get(repoId, jobId) as ScheduleRunRow | undefined
return row ? rowToScheduleRun(row) : null
}
export function listRunningScheduleRuns(db: Database, limit: number = 100): ScheduleRun[] {
const stmt = db.prepare(`
SELECT * FROM schedule_runs
WHERE status = 'running'
ORDER BY started_at ASC
LIMIT ?
`)
const rows = stmt.all(limit) as ScheduleRunRow[]
return rows.map(rowToScheduleRun)
}
export function listScheduleRunsByJob(db: Database, repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
const stmt = db.prepare(`
SELECT
id,
job_id,
repo_id,
trigger_source,
status,
started_at,
finished_at,
created_at,
session_id,
session_title,
NULL AS log_text,
NULL AS response_text,
error_text
FROM schedule_runs
WHERE repo_id = ? AND job_id = ?
ORDER BY started_at DESC
LIMIT ?
`)
const rows = stmt.all(repoId, jobId, limit) as ScheduleRunRow[]
return rows.map(rowToScheduleRun)
}
+11 -1
View File
@@ -37,12 +37,14 @@ import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
import { NotificationService } from './services/notification'
import { ScheduleRunner, ScheduleService } from './services/schedules'
import { logger } from './utils/logger'
import {
@@ -81,6 +83,7 @@ const requireAuth = createAuthMiddleware(auth)
import { DEFAULT_AGENTS_MD } from './constants'
let ipcServer: IPCServer | undefined
let scheduleRunnerInstance: ScheduleRunner | undefined
const gitAuthService = new GitAuthService()
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
@@ -312,6 +315,10 @@ try {
await opencodeServerManager.start()
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
const scheduleService = new ScheduleService(db)
scheduleRunnerInstance = new ScheduleRunner(scheduleService)
await scheduleRunnerInstance.start()
await syncAdminFromEnv(auth, db)
} catch (error) {
logger.error('Failed to initialize workspace:', error)
@@ -340,13 +347,13 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
app.route('/api/auth', createAuthRoutes(auth))
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
protectedApi.route('/health', createHealthRoutes(db))
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService))
protectedApi.route('/settings', createSettingsRoutes(db))
protectedApi.route('/files', createFileRoutes())
@@ -359,6 +366,7 @@ protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
protectedApi.route('/memory', createMemoryRoutes(db))
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
app.route('/api', protectedApi)
@@ -461,6 +469,8 @@ const shutdown = async (signal: string) => {
await ipcServer.dispose()
logger.info('Git IPC server stopped')
}
scheduleRunnerInstance?.stop()
logger.info('Schedule runner stopped')
await opencodeServerManager.stop()
logger.info('OpenCode server stopped')
} catch (error) {
+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), {
+158
View File
@@ -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')
}
+45
View File
@@ -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)
}
}
+156
View File
@@ -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