From 26f4041911bbfbb101fbb5ae64409ca59e61020a Mon Sep 17 00:00:00 2001 From: victor Date: Mon, 23 Nov 2026 10:24:49 +0100 Subject: [PATCH] feat(plugin): let plugins create, list and delete automations (#65747) --- packages/core/src/automation.ts | 61 +++++++++++--- packages/core/src/automation/code.ts | 2 +- packages/core/src/automation/shell.ts | 2 +- packages/core/src/plugin/host.ts | 9 +++ packages/core/test/automation.test.ts | 42 +++++++++- packages/core/test/plugin/automation.test.ts | 70 +++++++++++++++++ packages/core/test/plugin/fixture.ts | 2 + packages/core/test/plugin/host.ts | 5 ++ packages/plugin/src/effect/plugin.ts | 2 + packages/plugin/src/promise/adapter.ts | 5 ++ packages/plugin/src/promise/plugin.ts | 2 + packages/server/src/handlers/automation.ts | 83 +++++--------------- 12 files changed, 207 insertions(+), 78 deletions(-) create mode 100644 packages/core/test/plugin/automation.test.ts diff --git a/packages/core/src/automation.ts b/packages/core/src/automation.ts index c048b0d91b3..80478042224 100644 --- a/packages/core/src/automation.ts +++ b/packages/core/src/automation.ts @@ -56,7 +56,7 @@ import { KVTable } from "./kv/sql.js" import { Location } from "./location.js" import { LocationServiceMap } from "./location-service-map.js" import { Permission } from "./permission.js" -import { Plugin } from "./plugin.js" +import { Plugin } from "./plugin/service.js" import { Project } from "./project.js" import { Session } from "./session.js" import { SessionExecution } from "./session/execution.js" @@ -93,6 +93,8 @@ export class DisabledError extends Schema.TaggedError()("Automati export interface ListInput { readonly sessionID?: SessionSchema.ID readonly projectID?: ProjectID + /** Only automations in the project that owns this absolute directory, or that ran in it. */ + readonly directory?: string } export interface Interface { @@ -100,11 +102,13 @@ export interface Interface { input: CreateInput, invocation?: Invocation, ) => Effect.Effect - readonly list: (input?: ListInput) => Effect.Effect - readonly get: (id: ID) => Effect.Effect - readonly pause: (id: ID) => Effect.Effect - readonly resume: (id: ID) => Effect.Effect - readonly remove: (id: ID) => Effect.Effect + /** Oldest first, leaving out automations whose directory has automations off. */ + readonly list: (input?: ListInput) => Effect.Effect + /** These fail with DisabledError when the automation's directory has automations off. */ + readonly get: (id: ID) => Effect.Effect + readonly pause: (id: ID) => Effect.Effect + readonly resume: (id: ID) => Effect.Effect + readonly remove: (id: ID) => Effect.Effect /** Whether automations are enabled in the config of `directory`. */ readonly enabled: (directory: string) => Effect.Effect /** Runs every automation that is due now, at most once each. */ @@ -305,6 +309,21 @@ const layer = Layer.effect( } }).pipe(inDirectory(directory)) + // An automation whose folder is gone stays manageable, so it can be inspected and deleted. + const visible = (directory: string) => + settings(directory).pipe( + Effect.map((value) => value.enabled), + Effect.catchTag("FileSystem.DirectoryNotFoundError", () => Effect.succeed(true)), + ) + + /** The row of an automation callers may manage: it exists and its directory has automations on. */ + const findVisible = (id: ID) => + Effect.gen(function* () { + const row = yield* find(id) + if (!(yield* visible(row.directory))) return yield* new DisabledError() + return row + }) + const find = (id: ID) => db .select() @@ -1162,6 +1181,19 @@ const layer = Layer.effect( return toInfo(row) }), list: Effect.fn("Automation.list")(function* (input) { + if (input?.sessionID !== undefined) { + const session = yield* sessions.get(input.sessionID) + if (!(yield* visible(session.location.directory))) return yield* new DisabledError() + } + const directory = input?.directory + if (directory !== undefined && !path.isAbsolute(directory)) + return yield* new InvalidError({ reason: `Directory must be an absolute path: ${directory}` }) + if (directory !== undefined && !(yield* visible(directory))) return yield* new DisabledError() + // Reading ownership must not record a Project for a folder that was only asked about. + const owner = + directory === undefined + ? undefined + : (yield* projects.resolve(AbsolutePath.make(directory), { persist: false })).id const rows = yield* db .select() .from(AutomationTable) @@ -1174,13 +1206,20 @@ const layer = Layer.effect( .orderBy(asc(AutomationTable.time_created), asc(AutomationTable.id)) .all() .pipe(Effect.orDie) - return rows.map(toInfo) + // A deleted folder may no longer resolve to its Project, so also match automations that ran there. + const matching = rows.filter( + (row) => directory === undefined || row.project_id === owner || row.directory === directory, + ) + const shown = new Set( + yield* Effect.filter(new Set(matching.map((row) => row.directory)), (item) => visible(item)), + ) + return matching.filter((row) => shown.has(row.directory)).map(toInfo) }), get: Effect.fn("Automation.get")(function* (id) { - return toInfo(yield* find(id)) + return toInfo(yield* findVisible(id)) }), pause: Effect.fn("Automation.pause")(function* (id) { - const row = yield* find(id) + const row = yield* findVisible(id) if (row.status !== "active") return toInfo(row) yield* db .update(AutomationTable) @@ -1192,7 +1231,7 @@ const layer = Layer.effect( return toInfo(yield* find(id)) }), resume: Effect.fn("Automation.resume")(function* (id) { - const row = yield* find(id) + const row = yield* findVisible(id) if (row.status !== "paused") return toInfo(row) const now = yield* Clock.currentTimeMillis // An `at` that fell due while paused runs once, late, unless it has expired; a repeating automation resumes at @@ -1216,7 +1255,7 @@ const layer = Layer.effect( return toInfo(yield* find(id)) }), remove: Effect.fn("Automation.remove")(function* (id) { - yield* find(id) + yield* findVisible(id) yield* db.delete(AutomationTable).where(eq(AutomationTable.id, id)).run().pipe(Effect.orDie) yield* FiberMap.remove(watches, id) }), diff --git a/packages/core/src/automation/code.ts b/packages/core/src/automation/code.ts index 173955a99af..3f27be86311 100644 --- a/packages/core/src/automation/code.ts +++ b/packages/core/src/automation/code.ts @@ -6,7 +6,7 @@ import { Array, Effect, Option, Result, Schema } from "effect" import { Agent } from "../agent.js" import { CodeModeTool } from "../codemode/tool.js" import { Permission } from "../permission.js" -import { Plugin } from "../plugin.js" +import { Plugin } from "../plugin/service.js" import type { SessionMessage } from "../session/message.js" import type { SessionSchema } from "../session/schema.js" import { Tool } from "../tool.js" diff --git a/packages/core/src/automation/shell.ts b/packages/core/src/automation/shell.ts index 1a9dde14348..d1ae10e727d 100644 --- a/packages/core/src/automation/shell.ts +++ b/packages/core/src/automation/shell.ts @@ -6,7 +6,7 @@ import { Agent } from "../agent.js" import { Environment } from "../environment/index.js" import { FileAccess } from "../file-access.js" import { Permission } from "../permission.js" -import { Plugin } from "../plugin.js" +import { Plugin } from "../plugin/service.js" import type { SessionSchema } from "../session/schema.js" import { Shell } from "../shell.js" import { ShellPermissions } from "../shell/permissions.js" diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index ac321a74f22..4dcfa6f325e 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -10,6 +10,7 @@ import { Effect, Schema, Stream } from "effect" import { Agent } from "../agent.js" import { Artifact } from "../artifact.js" import { AISDK } from "../aisdk.js" +import { Automation } from "../automation.js" import { Command } from "../command.js" import { Credential } from "../credential.js" import { Bus } from "../bus.js" @@ -54,6 +55,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick automations.create(input).pipe(Effect.provideService(Permission.Unattended, [])), + list: (input) => automations.list(input), + delete: (input) => automations.remove(input.automationID), + }, }, generate: { text: generateText, @@ -635,6 +643,7 @@ export const requirements = LayerNode.group([ Agent.node, Artifact.node, AISDK.node, + Automation.node, Provider.node, Model.node, Command.node, diff --git a/packages/core/test/automation.test.ts b/packages/core/test/automation.test.ts index 6905656560d..a1f7606b85c 100644 --- a/packages/core/test/automation.test.ts +++ b/packages/core/test/automation.test.ts @@ -401,7 +401,9 @@ describe("Automation", () => { expect((yield* automations.list({ projectID: (yield* creator).projectID })).map((item) => item.id)).toEqual([ automation.id, ]) - expect((yield* automations.list({ sessionID: otherID })).map((item) => item.id)).toEqual([]) + expect(yield* Effect.flip(automations.list({ sessionID: otherID }))).toMatchObject({ + _tag: "Session.NotFoundError", + }) expect((yield* automations.pause(automation.id)).status).toBe("paused") yield* TestClock.adjust("150 seconds") @@ -877,6 +879,36 @@ describe("Automation", () => { }), ) + it.effect("hides and refuses automations while their location has automations off", () => + Effect.gen(function* () { + const automations = yield* setup(toggleDirectory) + toggle.on = true + const { id } = yield* automations.create({ + sessionID, + name: "poll", + trigger: every("1 minute"), + action: prompt("poll"), + }) + expect((yield* automations.list({ directory: toggleDirectory })).map((item) => item.id)).toEqual([id]) + expect(yield* Effect.flip(automations.list({ directory: "relative" }))).toMatchObject({ + _tag: "Automation.InvalidError", + }) + + toggle.on = false + expect(yield* automations.list()).toEqual([]) + expect(yield* Effect.flip(automations.list({ directory: toggleDirectory }))).toMatchObject({ + _tag: "Automation.DisabledError", + }) + expect(yield* Effect.flip(automations.list({ sessionID }))).toMatchObject({ _tag: "Automation.DisabledError" }) + expect(yield* Effect.flip(automations.pause(id))).toMatchObject({ _tag: "Automation.DisabledError" }) + expect(yield* Effect.flip(automations.remove(id))).toMatchObject({ _tag: "Automation.DisabledError" }) + + toggle.on = true + yield* automations.remove(id) + expect(yield* automations.list()).toEqual([]) + }), + ) + it.effect("rechecks hourly while automations are disabled in its location, then catches up when enabled", () => Effect.gen(function* () { const automations = yield* setup(toggleDirectory) @@ -891,7 +923,13 @@ describe("Automation", () => { const before = toggle.reads yield* TestClock.adjust("1 minute") yield* automations.tick - expect(yield* automations.get(id)).toMatchObject({ status: "active", runCount: 0, lastOutcome: "disabled" }) + // Callers can't read an automation while its location has automations off, so read the row. + const { db } = yield* Database.Service + expect( + yield* db.select().from(AutomationTable).where(eq(AutomationTable.id, id)).get().pipe(Effect.orDie), + ).toMatchObject({ status: "active", run_count: 0, last_outcome: "disabled" }) + expect(yield* Effect.flip(automations.get(id))).toMatchObject({ _tag: "Automation.DisabledError" }) + expect(yield* automations.list()).toEqual([]) expect(yield* pendingIDs).toEqual([]) const reads = toggle.reads expect(reads).toBeGreaterThan(before) diff --git a/packages/core/test/plugin/automation.test.ts b/packages/core/test/plugin/automation.test.ts new file mode 100644 index 00000000000..a1dd9325ec1 --- /dev/null +++ b/packages/core/test/plugin/automation.test.ts @@ -0,0 +1,70 @@ +import { expect } from "bun:test" +import { Automation } from "@opencode/core/automation" +import { Plugin } from "@opencode/core/plugin" +import { PluginHost } from "@opencode/core/plugin/host" +import { PluginPromise } from "@opencode/core/plugin/promise" +import { Effect } from "effect" +import { testEffect } from "../lib/effect" +import { PluginTestLayer } from "./fixture" + +const it = testEffect(PluginTestLayer) + +it.live("Effect plugins can create, list and delete automations", () => + Effect.gen(function* () { + const plugins = yield* Plugin.Service + const automations = yield* Automation.Service + const context = yield* PluginHost.make(plugins, "test") + const session = yield* context.session.create({ title: "Effect automation target" }) + + const created = yield* context.experimental.automation.create({ + directory: context.location.directory, + name: "effect inbox", + trigger: { type: "cron", cron: "0 * * * *", tz: "Europe/Madrid" }, + action: { type: "prompt", prompt: "Clean up the inboxes now.", to: { session: session.id } }, + }) + + expect(created).toMatchObject({ + name: "effect inbox", + status: "active", + trigger: { type: "cron", cron: "0 * * * *" }, + action: { type: "prompt", prompt: "Clean up the inboxes now.", to: { session: session.id } }, + }) + const listed = yield* context.experimental.automation.list({ directory: context.location.directory }) + expect(listed.map((item) => item.id)).toContain(created.id) + + yield* context.experimental.automation.delete({ automationID: created.id }) + expect((yield* automations.list()).map((item) => item.id)).not.toContain(created.id) + }), +) + +it.live("Promise plugins can create, list and delete automations", () => + Effect.gen(function* () { + const plugins = yield* Plugin.Service + const automations = yield* Automation.Service + const context = yield* PluginHost.make(plugins, "test") + const session = yield* context.session.create({ title: "Promise automation target" }) + const ids: string[] = [] + + yield* PluginPromise.fromPromise({ + id: "test.automation", + async setup(ctx) { + const created = await ctx.experimental.automation.create({ + directory: ctx.location.directory, + name: "promise inbox", + trigger: { type: "cron", cron: "0 9 * * *" }, + action: { type: "prompt", prompt: "Check the balance now.", to: { session: session.id } }, + }) + ids.push(created.id) + expect(created).toMatchObject({ name: "promise inbox", action: { to: { session: session.id } } }) + expect( + (await ctx.experimental.automation.list({ directory: ctx.location.directory })).map((item) => item.id), + ).toContain(created.id) + await ctx.experimental.automation.delete({ automationID: created.id }) + await expect(ctx.experimental.automation.delete({ automationID: created.id })).rejects.toThrow() + }, + }).effect(context) + + expect(ids).toHaveLength(1) + expect((yield* automations.list()).map((item) => item.id)).not.toContain(ids[0]) + }), +) diff --git a/packages/core/test/plugin/fixture.ts b/packages/core/test/plugin/fixture.ts index 81063500f62..795485572ee 100644 --- a/packages/core/test/plugin/fixture.ts +++ b/packages/core/test/plugin/fixture.ts @@ -3,6 +3,7 @@ import { App } from "@opencode/core/app" import { Artifact } from "@opencode/core/artifact" import { BlobStore } from "@opencode/core/blob-store" import { AISDK } from "@opencode/core/aisdk" +import { Automation } from "@opencode/core/automation" import { Command } from "@opencode/core/command" import { Config } from "@opencode/core/config" import { Credential } from "@opencode/core/credential" @@ -128,6 +129,7 @@ export const makePluginTestLayer = ( Agent.node, Artifact.node, AISDK.node, + Automation.node, BlobStore.node, Provider.node, Model.node, diff --git a/packages/core/test/plugin/host.ts b/packages/core/test/plugin/host.ts index bc436ab7d24..aa2ed44a257 100644 --- a/packages/core/test/plugin/host.ts +++ b/packages/core/test/plugin/host.ts @@ -81,6 +81,11 @@ export function host(overrides: Overrides = {}): Plugin.Context { transform: () => Effect.die("unused experimental.artifact.transform"), reload: () => Effect.die("unused experimental.artifact.reload"), }, + automation: { + create: () => Effect.die("unused experimental.automation.create"), + list: () => Effect.die("unused experimental.automation.list"), + delete: () => Effect.die("unused experimental.automation.delete"), + }, }, generate: overrides.generate ?? { text: () => Effect.die("unused generate.text"), diff --git a/packages/plugin/src/effect/plugin.ts b/packages/plugin/src/effect/plugin.ts index 61971725229..a08d1cb8455 100644 --- a/packages/plugin/src/effect/plugin.ts +++ b/packages/plugin/src/effect/plugin.ts @@ -38,6 +38,8 @@ export interface Context { /** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */ readonly generate: Omit, "video"> readonly artifact: ExperimentalArtifactDomain + /** Create, list and delete automations. Creation fails while automations are off where they would run. */ + readonly automation: Pick["automation"], "create" | "list" | "delete"> } readonly integration: IntegrationDomain readonly mcp: MCPDomain diff --git a/packages/plugin/src/promise/adapter.ts b/packages/plugin/src/promise/adapter.ts index 49b0342ab75..d4ef8244402 100644 --- a/packages/plugin/src/promise/adapter.ts +++ b/packages/plugin/src/promise/adapter.ts @@ -405,6 +405,11 @@ export function fromPromise(plugin: Plugin) { }), ), }, + automation: { + create: adaptApiMethod(ExperimentalEndpoints["automation.create"], host.experimental.automation.create), + list: adaptApiMethod(ExperimentalEndpoints["automation.list"], host.experimental.automation.list), + delete: adaptApiMethod(ExperimentalEndpoints["automation.delete"], host.experimental.automation.delete), + }, }, generate: { text: adaptApiMethod(GenerateEndpoints["generate.text"], host.generate.text), diff --git a/packages/plugin/src/promise/plugin.ts b/packages/plugin/src/promise/plugin.ts index cce3aa8ed28..6e3882c516c 100644 --- a/packages/plugin/src/promise/plugin.ts +++ b/packages/plugin/src/promise/plugin.ts @@ -38,6 +38,8 @@ export interface Context { /** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */ readonly generate: Omit readonly artifact: ExperimentalArtifactDomain + /** Create, list and delete automations. Creation fails while automations are off where they would run. */ + readonly automation: Pick } readonly integration: IntegrationDomain readonly mcp: MCPDomain diff --git a/packages/server/src/handlers/automation.ts b/packages/server/src/handlers/automation.ts index 80b9856a7a9..90c204a821e 100644 --- a/packages/server/src/handlers/automation.ts +++ b/packages/server/src/handlers/automation.ts @@ -1,35 +1,14 @@ import { Automation } from "@opencode/core/automation" import { Permission } from "@opencode/core/permission" -import { Project } from "@opencode/core/project" -import { Session } from "@opencode/core/session" -import { AbsolutePath } from "@opencode/core/schema" import { AutomationNotFoundError, ForbiddenError, InvalidRequestError } from "@opencode/protocol/errors" import type { CreatePayload, ListQuery } from "@opencode/protocol/groups/automation" import { Effect } from "effect" -import path from "node:path" import { HttpApiSchema } from "effect/http-api" import { missingSession } from "./session-error" /** `automation.*` in the `server.experimental` group. Every route requires automations to be enabled where it runs. */ export const makeAutomation = Effect.gen(function* () { const automations = yield* Automation.Service - const sessions = yield* Session.Service - const projects = yield* Project.Service - - const enabled = (directory: string) => - automations.enabled(directory).pipe( - // An automation whose folder is gone stays manageable, so it can be inspected and deleted. - Effect.catchTag("FileSystem.DirectoryNotFoundError", () => Effect.succeed(true)), - ) - const allowed = (directory: string) => - enabled(directory).pipe(Effect.flatMap((on) => (on ? Effect.void : Effect.fail(disabled())))) - - const find = (id: Automation.ID) => - Effect.gen(function* () { - const info = yield* automations.get(id).pipe(Effect.mapError(missingAutomation)) - yield* allowed(info.directory) - return info - }) return { create: (payload: CreatePayload) => @@ -47,53 +26,31 @@ export const makeAutomation = Effect.gen(function* () { }), ), list: (query: ListQuery) => - Effect.gen(function* () { - const session = - query.sessionID === undefined - ? undefined - : yield* sessions.get(query.sessionID).pipe(Effect.mapError(missingSession)) - if (session !== undefined) yield* allowed(session.location.directory) - const directory = query.directory - if (directory !== undefined && !path.isAbsolute(directory)) - return yield* new InvalidRequestError({ - message: `Directory must be an absolute path: ${directory}`, - kind: "automation", - }) - if (directory !== undefined) yield* allowed(directory) - // Reading ownership must not record a Project for a folder that was only asked about. - const projectID = - directory === undefined - ? undefined - : (yield* projects.resolve(AbsolutePath.make(directory), { persist: false })).id - const rows = yield* automations.list({ sessionID: query.sessionID }) - // A deleted folder may no longer resolve to its Project, so also match automations that ran there. - const matching = rows.filter( - (row) => directory === undefined || row.projectID === projectID || row.directory === directory, - ) - // Each automation is shown only where the flag allows it, the same as `get`. - const directories = new Set(matching.map((row) => row.directory)) - const visible = new Set(yield* Effect.filter(directories, enabled)) - return { data: matching.filter((row) => visible.has(row.directory)) } - }), - get: (id: Automation.ID) => find(id).pipe(Effect.map((data) => ({ data }))), - pause: (id: Automation.ID) => - find(id).pipe( - Effect.andThen(automations.pause(id).pipe(Effect.mapError(missingAutomation))), + automations.list(query).pipe( Effect.map((data) => ({ data })), + Effect.catchTags({ + "Automation.InvalidError": (error) => + Effect.fail(new InvalidRequestError({ message: error.message, kind: "automation" })), + "Automation.DisabledError": () => Effect.fail(disabled()), + "Session.NotFoundError": (error) => Effect.fail(missingSession(error)), + }), ), - resume: (id: Automation.ID) => - find(id).pipe( - Effect.andThen(automations.resume(id).pipe(Effect.mapError(missingAutomation))), - Effect.map((data) => ({ data })), - ), - remove: (id: Automation.ID) => - find(id).pipe( - Effect.andThen(automations.remove(id).pipe(Effect.mapError(missingAutomation))), - Effect.as(HttpApiSchema.NoContent.make()), - ), + get: (id: Automation.ID) => managed(automations.get(id).pipe(Effect.map((data) => ({ data })))), + pause: (id: Automation.ID) => managed(automations.pause(id).pipe(Effect.map((data) => ({ data })))), + resume: (id: Automation.ID) => managed(automations.resume(id).pipe(Effect.map((data) => ({ data })))), + remove: (id: Automation.ID) => managed(automations.remove(id).pipe(Effect.as(HttpApiSchema.NoContent.make()))), } }) +function managed(effect: Effect.Effect) { + return effect.pipe( + Effect.catchTags({ + "Automation.NotFoundError": (error) => Effect.fail(missingAutomation(error)), + "Automation.DisabledError": () => Effect.fail(disabled()), + }), + ) +} + function missingAutomation(error: { readonly automationID: Automation.ID }) { return new AutomationNotFoundError({ automationID: error.automationID,