Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- Automation definitions and runs persisted before PR5.5 lack the now-required
-- `model` field on AutomationDefinition. Since automations are still gated
-- behind the env-flagged `automate` tool and no UI entry exists yet, any rows
-- in these tables are pre-release dev/QA data. Drop them so the new schema
-- parses cleanly without per-row backfill.
DELETE FROM `automation_run`;--> statement-breakpoint
DELETE FROM `automation_definition`;
61 changes: 61 additions & 0 deletions packages/opencode/src/automation/cron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { DateTime } from "luxon"

export type CronSchedule = {
minutes: Set<number>
hours: Set<number>
days: Set<number>
months: Set<number>
weekdays: Set<number>
dayRestricted: boolean
weekdayRestricted: boolean
}

function cronValues(field: string, min: number, max: number, options?: { sundayAlias?: boolean }) {
const values = new Set<number>()
for (const item of field.split(",")) {
const [base, stepRaw] = item.split("/")
if (!base || item.split("/").length > 2) throw new Error(`Invalid cron field: ${item}`)
const step = stepRaw === undefined ? 1 : Number(stepRaw)
if (!Number.isInteger(step) || step <= 0) throw new Error(`Invalid cron step: ${item}`)
const range = base === "*" ? [min, max] : base.split("-").map(Number)
if (range.length === 0 || range.length > 2 || range.some((value) => !Number.isInteger(value))) {
throw new Error(`Invalid cron field: ${item}`)
}
const start = range[0]
const end = base === "*" || (range.length === 1 && stepRaw !== undefined) ? max : range.length === 1 ? range[0] : range[1]
if (start < min || end > max || start > end) throw new Error(`Invalid cron range: ${item}`)
for (let value = start; value <= end; value += step) {
values.add(options?.sundayAlias && value === 7 ? 0 : value)
}
}
return values
}

export function parseCronSchedule(expression: string): CronSchedule {
const fields = expression.trim().split(/\s+/)
if (fields.length !== 5) throw new Error(`Invalid cron expression: ${expression}`)
const [minuteField, hourField, dayField, monthField, weekdayField] = fields
return {
minutes: cronValues(minuteField, 0, 59),
hours: cronValues(hourField, 0, 23),
days: cronValues(dayField, 1, 31),
months: cronValues(monthField, 1, 12),
weekdays: cronValues(weekdayField, 0, 7, { sundayAlias: true }),
dayRestricted: dayField !== "*",
weekdayRestricted: weekdayField !== "*",
}
}

export function cronMatches(schedule: CronSchedule, time: DateTime) {
const weekday = time.weekday === 7 ? 0 : time.weekday
const dayMatches = schedule.days.has(time.day)
const weekdayMatches = schedule.weekdays.has(weekday)
const calendarMatches =
schedule.dayRestricted && schedule.weekdayRestricted ? dayMatches || weekdayMatches : dayMatches && weekdayMatches
return (
schedule.minutes.has(time.minute) &&
schedule.hours.has(time.hour) &&
schedule.months.has(time.month) &&
calendarMatches
)
}
75 changes: 75 additions & 0 deletions packages/opencode/src/automation/derived.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { DateTime } from "luxon"
import type { Automation } from "."
import { type CronSchedule, parseCronSchedule } from "./cron"

const CRON_LOOKAHEAD_MINUTES = 527_040 * 5
const NEXT_FIRES_PREVIEW = 5

type RecurringDefinition = Extract<Automation.Definition, { kind: "recurring" }>

const PLUS_ONE_MONTH = { months: 1 }
const PLUS_ONE_DAY = { days: 1 }
const PLUS_ONE_HOUR = { hours: 1 }
const PLUS_ONE_MINUTE = { minutes: 1 }

function nextCronFires(definition: RecurringDefinition, from: number, count: number): number[] {
if (definition.rhythm.kind !== "cron" || count <= 0) return []
let schedule: CronSchedule
try {
schedule = parseCronSchedule(definition.rhythm.expression)
} catch {
return []
}
const fires: number[] = []
const maxTimestamp = from + CRON_LOOKAHEAD_MINUTES * 60 * 1000
let cursor = DateTime.fromMillis(from, { zone: definition.timezone }).plus(PLUS_ONE_MINUTE).startOf("minute")
while (cursor.toMillis() < maxTimestamp && fires.length < count) {
if (!schedule.months.has(cursor.month)) {
cursor = cursor.plus(PLUS_ONE_MONTH).startOf("month")
continue
}
const weekday = cursor.weekday === 7 ? 0 : cursor.weekday
const dayMatches = schedule.days.has(cursor.day)
const weekdayMatches = schedule.weekdays.has(weekday)
const calendarMatches =
schedule.dayRestricted && schedule.weekdayRestricted ? dayMatches || weekdayMatches : dayMatches && weekdayMatches
if (!calendarMatches) {
cursor = cursor.plus(PLUS_ONE_DAY).startOf("day")
continue
}
if (!schedule.hours.has(cursor.hour)) {
cursor = cursor.plus(PLUS_ONE_HOUR).startOf("hour")
continue
}
if (schedule.minutes.has(cursor.minute)) fires.push(cursor.toMillis())
cursor = cursor.plus(PLUS_ONE_MINUTE)
}
return fires
}
Comment thread
Astro-Han marked this conversation as resolved.
Resolved

function nextIntervalFires(definition: RecurringDefinition, from: number, count: number): number[] {
if (definition.rhythm.kind !== "interval" || count <= 0) return []
const fires: number[] = []
let cursor = from + definition.rhythm.everyMs
for (let index = 0; index < count; index++) {
fires.push(cursor)
cursor += definition.rhythm.everyMs
}
return fires
}

export function computeDerivedFields(
definition: RecurringDefinition,
from: number,
completedRunCount: number,
): { nextFireAt: number | null; nextFires: number[] } {
if (definition.paused) return { nextFireAt: null, nextFires: [] }
if (definition.stop.kind === "condition") return { nextFireAt: null, nextFires: [] }
const remaining =
definition.stop.kind === "count" ? Math.max(0, definition.stop.count - completedRunCount) : NEXT_FIRES_PREVIEW
if (remaining <= 0) return { nextFireAt: null, nextFires: [] }
const count = Math.min(NEXT_FIRES_PREVIEW, remaining)
const fires =
definition.rhythm.kind === "cron" ? nextCronFires(definition, from, count) : nextIntervalFires(definition, from, count)
return { nextFireAt: fires[0] ?? null, nextFires: fires }
}
12 changes: 10 additions & 2 deletions packages/opencode/src/automation/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,18 @@ export const automationDefinitionFixture = Automation.Definition.parse({
updatedAt: 1_800_000_030_000,
timezone: "UTC",
normalizationWarnings: [],
model: Automation.Model.parse({ providerID: "anthropic", modelID: "claude-sonnet-4-6" }),
variant: "high",
rhythm: { kind: "interval", everyMs: 3_600_000 },
stop: { kind: "never" },
nextFireAt: null,
nextFires: [],
nextFireAt: 1_800_003_600_000,
nextFires: [
1_800_003_600_000,
1_800_007_200_000,
1_800_010_800_000,
1_800_014_400_000,
1_800_018_000_000,
],
failureStreak: 0,
})

Expand Down
92 changes: 88 additions & 4 deletions packages/opencode/src/automation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import { Identifier } from "@/id/id"
import { Instance } from "@/project/instance"
import { ProjectID } from "@/project/schema"
import { PermissionID } from "@/permission/schema"
import { ModelID, ProviderID } from "@/provider/schema"
import { SessionID } from "@/session/schema"
import { and, Database, desc, eq, gte, inArray, lt, NotFoundError, or, sql } from "@/storage/db"
import { Flock } from "@/util/flock"
import type { AutomationRunAttendance, AutomationRunBlocker } from "./run-context"
import { AutomationDefinitionTable, AutomationRunTable } from "./automation.sql"
import { computeDerivedFields } from "./derived"

export const AutomationID = {
Definition: {
Expand Down Expand Up @@ -38,11 +40,17 @@ export namespace Automation {
.meta({
ref: "AutomationWhere",
})
export const Model = z
.object({ providerID: ProviderID.zod, modelID: ModelID.zod })
.strict()
.meta({ ref: "AutomationModel" })
export type Model = z.infer<typeof Model>
export const ValidationErrorDetail = z
.object({ field: z.string(), message: z.string() })
.strict()
.meta({ ref: "AutomationValidationErrorDetail" })
export type ValidationErrorDetail = z.infer<typeof ValidationErrorDetail>
export type ValidationErrorDetailType = ValidationErrorDetail
export const ValidationErrorResponse = z
.object({ error: z.literal("invalid_automation"), details: z.array(ValidationErrorDetail) })
.strict()
Expand Down Expand Up @@ -75,6 +83,8 @@ export namespace Automation {
context: Context,
where: Where,
timezone: z.string().min(1),
model: Model,
variant: z.string().min(1).optional(),
}

export const CreateInput = z
Expand All @@ -96,6 +106,8 @@ export namespace Automation {
fireAt: z.number().int().nonnegative().optional(),
rhythm: Rhythm.optional(),
stop: Stop.optional(),
model: Model.optional(),
variant: z.string().min(1).nullable().optional(),
})
.strict()
.meta({ ref: "AutomationUpdateInput" })
Expand All @@ -115,6 +127,8 @@ export namespace Automation {
sourceSessionID: SessionID.zod.optional(),
automationSessionID: SessionID.zod.optional(),
normalizationWarnings: z.array(z.string()),
model: Model,
variant: z.string().min(1).optional(),
}

export const Definition = z
Expand Down Expand Up @@ -263,6 +277,8 @@ export namespace Automation {
"context",
"where",
"timezone",
"model",
"variant",
])
const ONESHOT_CREATE_FIELDS = new Set([...COMMON_CREATE_FIELDS, "fireAt"])
const RECURRING_CREATE_FIELDS = new Set([...COMMON_CREATE_FIELDS, "rhythm", "stop"])
Expand All @@ -276,6 +292,8 @@ export namespace Automation {
"fireAt",
"rhythm",
"stop",
"model",
"variant",
])

function addDetail(details: ValidationErrorDetail[], field: string, message: string) {
Expand Down Expand Up @@ -443,6 +461,9 @@ export namespace Automation {
if (input.where.worktree && Instance.project.vcs !== "git") {
addDetail(details, "where.worktree", "unsupported_where_worktree_not_git")
}
if (input.kind === "recurring" && input.stop.kind === "condition") {
addDetail(details, "stop", "unsupported_stop_condition")
}
details.push(...validateScheduleFields(input))
return details
}
Expand All @@ -467,6 +488,9 @@ export namespace Automation {
if (patch.rhythm?.kind === "cron" && !isValidCronExpression(patch.rhythm.expression)) {
addDetail(details, "rhythm.expression", "invalid_cron_expression")
}
if (patch.stop?.kind === "condition") {
addDetail(details, "stop", "unsupported_stop_condition")
}
return details
}

Expand All @@ -487,9 +511,11 @@ export namespace Automation {
updatedAt: now,
timezone: input.timezone,
normalizationWarnings: [],
model: input.model,
...(input.variant ? { variant: input.variant } : {}),
...(options?.sourceSessionID ? { sourceSessionID: options.sourceSessionID } : {}),
}
const definition: Definition =
let definition: Definition =
input.kind === "oneshot"
? { kind: "oneshot", ...base, fireAt: input.fireAt }
: {
Expand All @@ -501,6 +527,10 @@ export namespace Automation {
nextFires: [],
failureStreak: 0,
}
if (definition.kind === "recurring") {
const derived = computeDerivedFields(definition, now, 0)
definition = { ...definition, nextFireAt: derived.nextFireAt, nextFires: derived.nextFires }
}
writeDefinition(definition)
return definition
}
Expand Down Expand Up @@ -645,17 +675,71 @@ export namespace Automation {
const updateDetails = validateUpdateInput(previous, patch, now)
if (updateDetails.length) throw new ValidationError(updateDetails)
if (!hasChanges(previous, patch)) return previous
const next = Definition.parse({
...previous,
...patch,
const merged: Record<string, unknown> = { ...previous, ...patch }
if (patch.variant === null) delete merged.variant
let next = Definition.parse({
...merged,
revision: previous.revision + 1,
updatedAt: now,
})
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
const details = validateCreateInput(next)
if (details.length) throw new ValidationError(details)
if (next.kind === "recurring" && previous.kind === "recurring") {
const scheduleChanged =
!isSameValue(previous.rhythm, next.rhythm) ||
!isSameValue(previous.stop, next.stop) ||
previous.timezone !== next.timezone ||
previous.paused !== next.paused
if (scheduleChanged) {
const derived = computeDerivedFields(next, now, completedRunCount(next.id))
next = { ...next, nextFireAt: derived.nextFireAt, nextFires: derived.nextFires }
}
}
return replaceDefinition(previous, next)
}

export function recordRunOutcome(run: Run, options?: { now?: number }): Definition | undefined {
if (run.state !== "succeeded" && run.state !== "failed" && run.state !== "stopped") return undefined
const previous = getOptional(run.automationID)
if (!previous || previous.kind !== "recurring") return undefined
const now = options?.now ?? Date.now()
const failureStreak =
run.state === "succeeded" ? 0 : run.state === "failed" ? previous.failureStreak + 1 : previous.failureStreak
const derived =
run.state === "stopped"
? { nextFireAt: previous.nextFireAt, nextFires: previous.nextFires }
: computeDerivedFields(previous, now, completedRunCount(previous.id))
if (
previous.failureStreak === failureStreak &&
previous.nextFireAt === derived.nextFireAt &&
sameArray(previous.nextFires, derived.nextFires)
) {
return undefined
}
const next = Definition.parse({
...previous,
failureStreak,
nextFireAt: derived.nextFireAt,
nextFires: derived.nextFires,
revision: previous.revision + 1,
updatedAt: now,
})
try {
return replaceDefinition(previous, next)
} catch (error) {
if (error instanceof ConflictError) return undefined
throw error
}
}

function sameArray(left: readonly number[], right: readonly number[]) {
if (left.length !== right.length) return false
for (let index = 0; index < left.length; index++) {
if (left[index] !== right[index]) return false
}
return true
}

export async function remove(id: string): Promise<{ tombstone: Tombstone; stoppedRun?: Run }> {
const previous = get(id)
const stoppedRun = stopActiveRun(id)
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/automation/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ export const sessionPromptExecutor: Automation.RunExecutor = async ({ definition
const message = await SessionPrompt.promptWithAutomationContext(
{
sessionID,
model: definition.model,
...(definition.variant ? { variant: definition.variant } : {}),
parts: [{ type: "text", text: definition.prompt }],
},
scoped,
Expand Down
Loading
Loading