mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add assistant schedules feature with routes and tests
This commit is contained in:
1 parent
f0c87ffa5d
commit
18cbcacd11
7 files changed
+422
-3
No files matched your search
@@ -13,6 +13,7 @@ import { createTTSRoutes, cleanupExpiredCache } from './routes/tts';
|
||||
import { createSTTRoutes } from './routes/stt'
|
||||
import { createFileRoutes } from './routes/files'
|
||||
import { createScheduleRoutes } from './routes/schedules'
|
||||
import { createAssistantScheduleRoutes } from './routes/assistant-schedules'
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
@@ -264,6 +265,7 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
|
||||
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
|
||||
app.route('/api/assistant/schedules', createAssistantScheduleRoutes(db, scheduleService))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { Hono } from 'hono'
|
||||
import { timingSafeEqual } from 'crypto'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
CreateScheduleJobRequestSchema,
|
||||
UpdateScheduleJobRequestSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ensureAssistantRepo, getAssistantSchedulerToken } from '../services/assistant-mode'
|
||||
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||
import { handleServiceError, parseId } from '../utils/route-helpers'
|
||||
|
||||
function parseRunListLimit(value: string | undefined): number {
|
||||
if (value === undefined) {
|
||||
return 20
|
||||
}
|
||||
|
||||
const parsed = parseId(value, 'limit', ScheduleServiceError)
|
||||
if (parsed < 1) {
|
||||
throw new ScheduleServiceError('Limit must be greater than 0', 400)
|
||||
}
|
||||
|
||||
return Math.min(parsed, 100)
|
||||
}
|
||||
|
||||
async function requireAssistantScheduleToken(c: { req: { header: (name: string) => string | undefined }; json: (body: { error: string }, status: 401 | 403) => Response }) {
|
||||
const expectedToken = await getAssistantSchedulerToken()
|
||||
if (!expectedToken) {
|
||||
return c.json({ error: 'Assistant scheduler token is not initialized' }, 403)
|
||||
}
|
||||
|
||||
const authorization = c.req.header('authorization')
|
||||
const actualToken = authorization?.startsWith('Bearer ') ? authorization.slice('Bearer '.length).trim() : ''
|
||||
const expected = Buffer.from(expectedToken)
|
||||
const actual = Buffer.from(actualToken)
|
||||
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function createAssistantScheduleRoutes(db: Database, scheduleService: ScheduleService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.use('*', async (c, next) => {
|
||||
const response = await requireAssistantScheduleToken(c)
|
||||
if (response) return response
|
||||
await next()
|
||||
})
|
||||
|
||||
app.get('/', (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
return c.json({ jobs: scheduleService.listJobs(assistantRepo.id), repo: assistantRepo })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list assistant schedules', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
const body = await c.req.json()
|
||||
const input = CreateScheduleJobRequestSchema.parse(body)
|
||||
const job = scheduleService.createJob(assistantRepo.id, input)
|
||||
return c.json({ job, repo: assistantRepo }, 201)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to create assistant schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId', (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const job = scheduleService.getJob(assistantRepo.id, jobId)
|
||||
if (!job) {
|
||||
return c.json({ error: 'Schedule not found' }, 404)
|
||||
}
|
||||
return c.json({ job, repo: assistantRepo })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to get assistant schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/:jobId', async (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const body = await c.req.json()
|
||||
const input = UpdateScheduleJobRequestSchema.parse(body)
|
||||
const job = scheduleService.updateJob(assistantRepo.id, jobId, input)
|
||||
return c.json({ job, repo: assistantRepo })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to update assistant schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId', (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
scheduleService.deleteJob(assistantRepo.id, jobId)
|
||||
return c.json({ success: true, repo: assistantRepo })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to delete assistant schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:jobId/run', async (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const run = await scheduleService.runJob(assistantRepo.id, jobId, 'manual')
|
||||
return c.json({ run, repo: assistantRepo })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to run assistant schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId/runs', (c) => {
|
||||
try {
|
||||
const assistantRepo = ensureAssistantRepo(db)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const limit = parseRunListLimit(c.req.query('limit'))
|
||||
return c.json({ runs: scheduleService.listRuns(assistantRepo.id, jobId, limit), repo: assistantRepo })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list assistant schedule runs', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -422,7 +422,7 @@ app.get('/', async (c) => {
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const options = AssistantModeInitRequestSchema.parse(body)
|
||||
|
||||
const status = await ensureAssistantMode(repo, options)
|
||||
const status = await ensureAssistantMode(repo, options, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to initialize assistant mode:', error)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import path from 'path'
|
||||
import { randomBytes } from 'crypto'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import type {
|
||||
AssistantModeStatus,
|
||||
@@ -13,11 +15,14 @@ import {
|
||||
} from './file-operations'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { createRepo, getRepoByLocalPath } from '../db/queries'
|
||||
|
||||
const ASSISTANT_MODE_DIR = 'assistant'
|
||||
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
|
||||
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
|
||||
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
|
||||
const ASSISTANT_SCHEDULER_SKILL_PATH = path.join('.opencode', 'skills', 'scheduler', 'SKILL.md')
|
||||
const ASSISTANT_SCHEDULER_TOKEN_PATH = path.join('.opencode', 'scheduler-token')
|
||||
|
||||
export function getAssistantModeDirectory(): string {
|
||||
const reposPath = getReposPath()
|
||||
@@ -63,6 +68,75 @@ The agent MAY self-edit the following files within this workspace:
|
||||
2. Update AGENTS.md when learning durable preferences
|
||||
3. Maintain version control awareness
|
||||
4. Document significant changes in commit messages
|
||||
|
||||
## Scheduler
|
||||
|
||||
Use the scheduler skill when the user wants recurring scheduled work in the Assistant repository.
|
||||
`
|
||||
}
|
||||
|
||||
export function buildAssistantSchedulerSkill(): string {
|
||||
return `---
|
||||
name: scheduler
|
||||
description: Configure recurring schedules for the Assistant repository. Use when the user asks the Assistant to create, update, pause, resume, or run a scheduled recurring job.
|
||||
---
|
||||
|
||||
# Scheduler Skill
|
||||
|
||||
Use this skill when configuring recurring work for the Assistant repository.
|
||||
|
||||
## Scope
|
||||
|
||||
- Manage only schedules for the Assistant repository directory.
|
||||
- Use the assistant schedule API below. It maps every operation to the Assistant repo and cannot target other repositories.
|
||||
- Do not create a separate scheduler store or schedule metadata layer.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Clarify the schedule name, recurring cadence, timezone, prompt, enabled state, and optional agent or model.
|
||||
2. Confirm the final schedule configuration before creating or updating it.
|
||||
3. Read the bearer token from \`.opencode/scheduler-token\`.
|
||||
4. Use the assistant schedule API for every list, create, update, delete, run, and run-history request.
|
||||
5. Prefer cron schedules for wall-clock times and interval schedules for simple repeated checks.
|
||||
6. After changes, list the assistant schedules and report the updated state to the user.
|
||||
|
||||
## API Shape
|
||||
|
||||
- List schedules: \`GET /api/assistant/schedules\`
|
||||
- Create schedule: \`POST /api/assistant/schedules\`
|
||||
- Update schedule: \`PATCH /api/assistant/schedules/:jobId\`
|
||||
- Delete schedule: \`DELETE /api/assistant/schedules/:jobId\`
|
||||
- Run schedule now: \`POST /api/assistant/schedules/:jobId/run\`
|
||||
|
||||
Send \`Authorization: Bearer <token>\` with every request.
|
||||
|
||||
## Schedule Payloads
|
||||
|
||||
Interval schedules use:
|
||||
|
||||
\`\`\`json
|
||||
{
|
||||
"name": "Morning repo review",
|
||||
"description": "Daily repository review",
|
||||
"enabled": true,
|
||||
"scheduleMode": "interval",
|
||||
"intervalMinutes": 1440,
|
||||
"prompt": "Review this repository and summarize useful follow-ups."
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
Cron schedules use:
|
||||
|
||||
\`\`\`json
|
||||
{
|
||||
"name": "Weekday repo review",
|
||||
"enabled": true,
|
||||
"scheduleMode": "cron",
|
||||
"cronExpression": "0 9 * * 1-5",
|
||||
"timezone": "UTC",
|
||||
"prompt": "Review this repository and summarize useful follow-ups."
|
||||
}
|
||||
\`\`\`
|
||||
`
|
||||
}
|
||||
|
||||
@@ -80,6 +154,9 @@ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
},
|
||||
skills: {
|
||||
paths: ['.opencode/skills'],
|
||||
},
|
||||
}
|
||||
|
||||
const result = OpenCodeConfigSchema.safeParse(config)
|
||||
@@ -90,19 +167,82 @@ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
|
||||
return config
|
||||
}
|
||||
|
||||
export function ensureAssistantRepo(db: Database): Repo {
|
||||
const existing = getRepoByLocalPath(db, ASSISTANT_MODE_DIR)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
|
||||
return createRepo(db, {
|
||||
localPath: ASSISTANT_MODE_DIR,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
}
|
||||
|
||||
export async function ensureAssistantSchedulerToken(assistantDir: string): Promise<string> {
|
||||
const tokenPath = path.join(assistantDir, ASSISTANT_SCHEDULER_TOKEN_PATH)
|
||||
const tokenExists = await fileExists(tokenPath)
|
||||
if (tokenExists) {
|
||||
return (await readFileContent(tokenPath)).trim()
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString('hex')
|
||||
await writeFileContent(tokenPath, token)
|
||||
return token
|
||||
}
|
||||
|
||||
export async function getAssistantSchedulerToken(): Promise<string | null> {
|
||||
const tokenPath = path.join(getAssistantModeDirectory(), ASSISTANT_SCHEDULER_TOKEN_PATH)
|
||||
if (!await fileExists(tokenPath)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (await readFileContent(tokenPath)).trim()
|
||||
}
|
||||
|
||||
async function ensureSchedulerSkillPathInOpenCodeConfig(opencodeJsonPath: string): Promise<void> {
|
||||
let config: OpenCodeConfigInput
|
||||
try {
|
||||
const content = await readFileContent(opencodeJsonPath)
|
||||
config = OpenCodeConfigSchema.parse(JSON.parse(content))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
const existingPaths = config.skills?.paths ?? []
|
||||
if (existingPaths.includes('.opencode/skills')) return
|
||||
|
||||
const updatedConfig = {
|
||||
...config,
|
||||
skills: {
|
||||
...config.skills,
|
||||
paths: [...existingPaths, '.opencode/skills'],
|
||||
},
|
||||
}
|
||||
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(updatedConfig, null, 2))
|
||||
}
|
||||
|
||||
export async function ensureAssistantMode(
|
||||
repo: Repo,
|
||||
options?: AssistantModeInitRequest
|
||||
options?: AssistantModeInitRequest,
|
||||
db?: Database,
|
||||
): Promise<AssistantModeStatus> {
|
||||
const assistantDir = getAssistantModeDirectory()
|
||||
const assistantRepo = db ? ensureAssistantRepo(db) : repo
|
||||
|
||||
await ensureDirectoryExists(assistantDir)
|
||||
|
||||
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
|
||||
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
|
||||
const schedulerSkillPath = path.join(assistantDir, ASSISTANT_SCHEDULER_SKILL_PATH)
|
||||
|
||||
const agentsMdExists = await fileExists(agentsMdPath)
|
||||
const opencodeJsonExists = await fileExists(opencodeJsonPath)
|
||||
const schedulerSkillExists = await fileExists(schedulerSkillPath)
|
||||
|
||||
const overwriteAgentsMd = options?.overwriteAgentsMd ?? false
|
||||
const overwriteOpenCodeConfig = options?.overwriteOpenCodeConfig ?? false
|
||||
@@ -117,10 +257,18 @@ export async function ensureAssistantMode(
|
||||
if (!opencodeJsonExists || overwriteOpenCodeConfig || hasLegacyOpenCodeConfig) {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(config, null, 2))
|
||||
} else {
|
||||
await ensureSchedulerSkillPathInOpenCodeConfig(opencodeJsonPath)
|
||||
}
|
||||
|
||||
if (!schedulerSkillExists) {
|
||||
await writeFileContent(schedulerSkillPath, buildAssistantSchedulerSkill())
|
||||
}
|
||||
|
||||
await ensureAssistantSchedulerToken(assistantDir)
|
||||
|
||||
return {
|
||||
repoId: repo.id,
|
||||
repoId: assistantRepo.id,
|
||||
directory: assistantDir,
|
||||
relativePath: ASSISTANT_MODE_RELATIVE_PATH,
|
||||
files: {
|
||||
|
||||
Reference in new issue
Block a user