Add assistant schedules feature with routes and tests

This commit is contained in:
Chris Scott committed 2026-04-30 04:51:36 +00:00
1 parent f0c87ffa5d
commit 18cbcacd11
7 files changed
+422 -3

No files matched your search

+2
View File
@@ -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)
+133
View File
@@ -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
}
+1 -1
View File
@@ -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)
+150 -2
View File
@@ -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: {
@@ -0,0 +1,120 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
const assistantRepo = {
id: 99,
repoUrl: undefined,
localPath: 'assistant',
fullPath: '/tmp/test-workspace/repos/assistant',
branch: undefined,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 1,
lastAccessedAt: 1,
isLocal: true,
}
const scheduleService = {
listJobs: vi.fn(),
createJob: vi.fn(),
getJob: vi.fn(),
updateJob: vi.fn(),
deleteJob: vi.fn(),
runJob: vi.fn(),
listRuns: vi.fn(),
}
vi.mock('../../src/services/assistant-mode', () => ({
ensureAssistantRepo: vi.fn(() => assistantRepo),
getAssistantSchedulerToken: vi.fn(() => Promise.resolve('test-token')),
}))
vi.mock('../../src/utils/logger', () => ({
logger: {
error: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
},
}))
import { createAssistantScheduleRoutes } from '../../src/routes/assistant-schedules'
describe('Assistant Schedule Routes', () => {
let app: Hono
beforeEach(() => {
vi.clearAllMocks()
app = new Hono()
app.route('/assistant/schedules', createAssistantScheduleRoutes({} as Database, scheduleService as never))
})
it('rejects requests without the assistant scheduler token', async () => {
const response = await app.request('/assistant/schedules')
const body = await response.json() as { error: string }
expect(response.status).toBe(401)
expect(body.error).toBe('Unauthorized')
expect(scheduleService.listJobs).not.toHaveBeenCalled()
})
it('lists schedules for the assistant repo only', async () => {
scheduleService.listJobs.mockReturnValue([{ id: 7, name: 'Reminder' }])
const response = await app.request('/assistant/schedules', {
headers: { Authorization: 'Bearer test-token' },
})
const body = await response.json() as { jobs: Array<{ id: number }>; repo: { id: number } }
expect(response.status).toBe(200)
expect(body.jobs).toHaveLength(1)
expect(body.repo.id).toBe(assistantRepo.id)
expect(scheduleService.listJobs).toHaveBeenCalledWith(assistantRepo.id)
})
it('creates schedules for the assistant repo only', async () => {
scheduleService.createJob.mockReturnValue({ id: 8, name: 'Hourly reminder' })
const response = await app.request('/assistant/schedules', {
method: 'POST',
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Hourly reminder',
enabled: true,
scheduleMode: 'interval',
intervalMinutes: 60,
prompt: 'Remind me to check the release queue.',
}),
})
expect(response.status).toBe(201)
expect(scheduleService.createJob).toHaveBeenCalledWith(assistantRepo.id, expect.objectContaining({ name: 'Hourly reminder' }))
})
it('updates and deletes schedules for the assistant repo only', async () => {
scheduleService.updateJob.mockReturnValue({ id: 8, name: 'Updated reminder' })
scheduleService.deleteJob.mockReturnValue(undefined)
const updateResponse = await app.request('/assistant/schedules/8', {
method: 'PATCH',
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Updated reminder' }),
})
const deleteResponse = await app.request('/assistant/schedules/8', {
method: 'DELETE',
headers: { Authorization: 'Bearer test-token' },
})
expect(updateResponse.status).toBe(200)
expect(deleteResponse.status).toBe(200)
expect(scheduleService.updateJob).toHaveBeenCalledWith(assistantRepo.id, 8, expect.objectContaining({ name: 'Updated reminder' }))
expect(scheduleService.deleteJob).toHaveBeenCalledWith(assistantRepo.id, 8)
})
})
@@ -81,6 +81,11 @@ describe('buildAssistantOpenCodeConfig', () => {
expect(config.instructions).toEqual(['AGENTS.md'])
})
it('includes the assistant skills path', () => {
const config = buildAssistantOpenCodeConfig()
expect(config.skills?.paths).toEqual(['.opencode/skills'])
})
it('has permission rules for the assistant workspace', () => {
const config = buildAssistantOpenCodeConfig()
expect(config.permission).toEqual({
@@ -110,6 +115,10 @@ describe('ensureAssistantMode', () => {
expect(result.relativePath).toBe('repos/assistant')
expect(result.files.agentsMd.exists).toBe(true)
expect(result.files.opencodeJson.exists).toBe(true)
expect(writeFile).toHaveBeenCalledWith(
expect.stringContaining(path.join('.opencode', 'skills', 'scheduler', 'SKILL.md')),
expect.any(Buffer),
)
})
it('does not overwrite existing customized files by default', async () => {
+7
View File
@@ -63,6 +63,13 @@ export function AssistantRedirect() {
const assistantDirectory = assistantMode?.directory
const assistantFileBasePath = assistantDirectory?.split('/').filter(Boolean).at(-1)
useEffect(() => {
if (assistantMode) {
queryClient.invalidateQueries({ queryKey: ["repos"] })
queryClient.invalidateQueries({ queryKey: ["all-schedules"] })
}
}, [assistantMode, queryClient])
useSSE(opcodeUrl, assistantDirectory)
const createSessionMutation = useCreateSession(opcodeUrl, assistantDirectory, (session) => {