GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(plugin): let plugins create, list and delete automations (#65747) · yusha/opencode@26f4041

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • core
      • src
        • automation.ts
        • automation
          • code.ts
          • shell.ts
        • plugin
          • host.ts
      • test
        • automation.test.ts
        • plugin
          • automation.test.ts
          • fixture.ts
          • host.ts
    • plugin/src
      • effect
        • plugin.ts
      • promise
        • adapter.ts
        • plugin.ts
    • server/src/handlers
      • automation.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/automation.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/automation.ts
+50-11Lines changed: 50 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ import { KVTable } from "./kv/sql.js"
5656
import { Location } from "./location.js"
5757
import { LocationServiceMap } from "./location-service-map.js"
5858
import { Permission } from "./permission.js"
59-
import { Plugin } from "./plugin.js"
59+
import { Plugin } from "./plugin/service.js"
6060
import { Project } from "./project.js"
6161
import { Session } from "./session.js"
6262
import { SessionExecution } from "./session/execution.js"
@@ -93,18 +93,22 @@ export class DisabledError extends Schema.TaggedError<DisabledError>()("Automati
9393
export interface ListInput {
9494
readonly sessionID?: SessionSchema.ID
9595
readonly projectID?: ProjectID
96+
/** Only automations in the project that owns this absolute directory, or that ran in it. */
97+
readonly directory?: string
9698
}
9799

98100
export interface Interface {
99101
readonly create: (
100102
input: CreateInput,
101103
invocation?: Invocation,
102104
) => Effect.Effect<Info, InvalidError | DisabledError | Session.NotFoundError | Permission.Error>
103-
readonly list: (input?: ListInput) => Effect.Effect<Info[]>
104-
readonly get: (id: ID) => Effect.Effect<Info, NotFoundError>
105-
readonly pause: (id: ID) => Effect.Effect<Info, NotFoundError>
106-
readonly resume: (id: ID) => Effect.Effect<Info, NotFoundError>
107-
readonly remove: (id: ID) => Effect.Effect<void, NotFoundError>
105+
/** Oldest first, leaving out automations whose directory has automations off. */
106+
readonly list: (input?: ListInput) => Effect.Effect<Info[], InvalidError | DisabledError | Session.NotFoundError>
107+
/** These fail with DisabledError when the automation's directory has automations off. */
108+
readonly get: (id: ID) => Effect.Effect<Info, NotFoundError | DisabledError>
109+
readonly pause: (id: ID) => Effect.Effect<Info, NotFoundError | DisabledError>
110+
readonly resume: (id: ID) => Effect.Effect<Info, NotFoundError | DisabledError>
111+
readonly remove: (id: ID) => Effect.Effect<void, NotFoundError | DisabledError>
108112
/** Whether automations are enabled in the config of `directory`. */
109113
readonly enabled: (directory: string) => Effect.Effect<boolean, FileSystem.DirectoryNotFoundError>
110114
/** Runs every automation that is due now, at most once each. */
@@ -305,6 +309,21 @@ const layer = Layer.effect(
305309
}
306310
}).pipe(inDirectory(directory))
307311

312+
// An automation whose folder is gone stays manageable, so it can be inspected and deleted.
313+
const visible = (directory: string) =>
314+
settings(directory).pipe(
315+
Effect.map((value) => value.enabled),
316+
Effect.catchTag("FileSystem.DirectoryNotFoundError", () => Effect.succeed(true)),
317+
)
318+
319+
/** The row of an automation callers may manage: it exists and its directory has automations on. */
320+
const findVisible = (id: ID) =>
321+
Effect.gen(function* () {
322+
const row = yield* find(id)
323+
if (!(yield* visible(row.directory))) return yield* new DisabledError()
324+
return row
325+
})
326+
308327
const find = (id: ID) =>
309328
db
310329
.select()
@@ -1162,6 +1181,19 @@ const layer = Layer.effect(
11621181
return toInfo(row)
11631182
}),
11641183
list: Effect.fn("Automation.list")(function* (input) {
1184+
if (input?.sessionID !== undefined) {
1185+
const session = yield* sessions.get(input.sessionID)
1186+
if (!(yield* visible(session.location.directory))) return yield* new DisabledError()
1187+
}
1188+
const directory = input?.directory
1189+
if (directory !== undefined && !path.isAbsolute(directory))
1190+
return yield* new InvalidError({ reason: `Directory must be an absolute path: ${directory}` })
1191+
if (directory !== undefined && !(yield* visible(directory))) return yield* new DisabledError()
1192+
// Reading ownership must not record a Project for a folder that was only asked about.
1193+
const owner =
1194+
directory === undefined
1195+
? undefined
1196+
: (yield* projects.resolve(AbsolutePath.make(directory), { persist: false })).id
11651197
const rows = yield* db
11661198
.select()
11671199
.from(AutomationTable)
@@ -1174,13 +1206,20 @@ const layer = Layer.effect(
11741206
.orderBy(asc(AutomationTable.time_created), asc(AutomationTable.id))
11751207
.all()
11761208
.pipe(Effect.orDie)
1177-
return rows.map(toInfo)
1209+
// A deleted folder may no longer resolve to its Project, so also match automations that ran there.
1210+
const matching = rows.filter(
1211+
(row) => directory === undefined || row.project_id === owner || row.directory === directory,
1212+
)
1213+
const shown = new Set(
1214+
yield* Effect.filter(new Set(matching.map((row) => row.directory)), (item) => visible(item)),
1215+
)
1216+
return matching.filter((row) => shown.has(row.directory)).map(toInfo)
11781217
}),
11791218
get: Effect.fn("Automation.get")(function* (id) {
1180-
return toInfo(yield* find(id))
1219+
return toInfo(yield* findVisible(id))
11811220
}),
11821221
pause: Effect.fn("Automation.pause")(function* (id) {
1183-
const row = yield* find(id)
1222+
const row = yield* findVisible(id)
11841223
if (row.status !== "active") return toInfo(row)
11851224
yield* db
11861225
.update(AutomationTable)
@@ -1192,7 +1231,7 @@ const layer = Layer.effect(
11921231
return toInfo(yield* find(id))
11931232
}),
11941233
resume: Effect.fn("Automation.resume")(function* (id) {
1195-
const row = yield* find(id)
1234+
const row = yield* findVisible(id)
11961235
if (row.status !== "paused") return toInfo(row)
11971236
const now = yield* Clock.currentTimeMillis
11981237
// 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(
12161255
return toInfo(yield* find(id))
12171256
}),
12181257
remove: Effect.fn("Automation.remove")(function* (id) {
1219-
yield* find(id)
1258+
yield* findVisible(id)
12201259
yield* db.delete(AutomationTable).where(eq(AutomationTable.id, id)).run().pipe(Effect.orDie)
12211260
yield* FiberMap.remove(watches, id)
12221261
}),
Collapse file

‎packages/core/src/automation/code.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/automation/code.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Array, Effect, Option, Result, Schema } from "effect"
66
import { Agent } from "../agent.js"
77
import { CodeModeTool } from "../codemode/tool.js"
88
import { Permission } from "../permission.js"
9-
import { Plugin } from "../plugin.js"
9+
import { Plugin } from "../plugin/service.js"
1010
import type { SessionMessage } from "../session/message.js"
1111
import type { SessionSchema } from "../session/schema.js"
1212
import { Tool } from "../tool.js"
Collapse file

‎packages/core/src/automation/shell.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/automation/shell.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Agent } from "../agent.js"
66
import { Environment } from "../environment/index.js"
77
import { FileAccess } from "../file-access.js"
88
import { Permission } from "../permission.js"
9-
import { Plugin } from "../plugin.js"
9+
import { Plugin } from "../plugin/service.js"
1010
import type { SessionSchema } from "../session/schema.js"
1111
import { Shell } from "../shell.js"
1212
import { ShellPermissions } from "../shell/permissions.js"
Collapse file

‎packages/core/src/plugin/host.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/plugin/host.ts
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { Effect, Schema, Stream } from "effect"
1010
import { Agent } from "../agent.js"
1111
import { Artifact } from "../artifact.js"
1212
import { AISDK } from "../aisdk.js"
13+
import { Automation } from "../automation.js"
1314
import { Command } from "../command.js"
1415
import { Credential } from "../credential.js"
1516
import { Bus } from "../bus.js"
@@ -54,6 +55,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interfa
5455
const app = yield* App.Service
5556
const agents = yield* Agent.Service
5657
const artifacts = yield* Artifact.Service
58+
const automations = yield* Automation.Service
5759
const aisdk = yield* AISDK.Service
5860
const providers = yield* Provider.Service
5961
const models = yield* Model.Service
@@ -317,6 +319,12 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interfa
317319
})
318320
}),
319321
},
322+
automation: {
323+
// A plugin has no UI listener to answer an interactive ask, so asks settle unattended, as they do over HTTP.
324+
create: (input) => automations.create(input).pipe(Effect.provideService(Permission.Unattended, [])),
325+
list: (input) => automations.list(input),
326+
delete: (input) => automations.remove(input.automationID),
327+
},
320328
},
321329
generate: {
322330
text: generateText,
@@ -635,6 +643,7 @@ export const requirements = LayerNode.group([
635643
Agent.node,
636644
Artifact.node,
637645
AISDK.node,
646+
Automation.node,
638647
Provider.node,
639648
Model.node,
640649
Command.node,
Collapse file

‎packages/core/test/automation.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/automation.test.ts
+40-2Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,9 @@ describe("Automation", () => {
401401
expect((yield* automations.list({ projectID: (yield* creator).projectID })).map((item) => item.id)).toEqual([
402402
automation.id,
403403
])
404-
expect((yield* automations.list({ sessionID: otherID })).map((item) => item.id)).toEqual([])
404+
expect(yield* Effect.flip(automations.list({ sessionID: otherID }))).toMatchObject({
405+
_tag: "Session.NotFoundError",
406+
})
405407

406408
expect((yield* automations.pause(automation.id)).status).toBe("paused")
407409
yield* TestClock.adjust("150 seconds")
@@ -877,6 +879,36 @@ describe("Automation", () => {
877879
}),
878880
)
879881

882+
it.effect("hides and refuses automations while their location has automations off", () =>
883+
Effect.gen(function* () {
884+
const automations = yield* setup(toggleDirectory)
885+
toggle.on = true
886+
const { id } = yield* automations.create({
887+
sessionID,
888+
name: "poll",
889+
trigger: every("1 minute"),
890+
action: prompt("poll"),
891+
})
892+
expect((yield* automations.list({ directory: toggleDirectory })).map((item) => item.id)).toEqual([id])
893+
expect(yield* Effect.flip(automations.list({ directory: "relative" }))).toMatchObject({
894+
_tag: "Automation.InvalidError",
895+
})
896+
897+
toggle.on = false
898+
expect(yield* automations.list()).toEqual([])
899+
expect(yield* Effect.flip(automations.list({ directory: toggleDirectory }))).toMatchObject({
900+
_tag: "Automation.DisabledError",
901+
})
902+
expect(yield* Effect.flip(automations.list({ sessionID }))).toMatchObject({ _tag: "Automation.DisabledError" })
903+
expect(yield* Effect.flip(automations.pause(id))).toMatchObject({ _tag: "Automation.DisabledError" })
904+
expect(yield* Effect.flip(automations.remove(id))).toMatchObject({ _tag: "Automation.DisabledError" })
905+
906+
toggle.on = true
907+
yield* automations.remove(id)
908+
expect(yield* automations.list()).toEqual([])
909+
}),
910+
)
911+
880912
it.effect("rechecks hourly while automations are disabled in its location, then catches up when enabled", () =>
881913
Effect.gen(function* () {
882914
const automations = yield* setup(toggleDirectory)
@@ -891,7 +923,13 @@ describe("Automation", () => {
891923
const before = toggle.reads
892924
yield* TestClock.adjust("1 minute")
893925
yield* automations.tick
894-
expect(yield* automations.get(id)).toMatchObject({ status: "active", runCount: 0, lastOutcome: "disabled" })
926+
// Callers can't read an automation while its location has automations off, so read the row.
927+
const { db } = yield* Database.Service
928+
expect(
929+
yield* db.select().from(AutomationTable).where(eq(AutomationTable.id, id)).get().pipe(Effect.orDie),
930+
).toMatchObject({ status: "active", run_count: 0, last_outcome: "disabled" })
931+
expect(yield* Effect.flip(automations.get(id))).toMatchObject({ _tag: "Automation.DisabledError" })
932+
expect(yield* automations.list()).toEqual([])
895933
expect(yield* pendingIDs).toEqual([])
896934
const reads = toggle.reads
897935
expect(reads).toBeGreaterThan(before)
Collapse file

‎packages/core/test/plugin/automation.test.ts‎

Copy file name to clipboard
+70Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { expect } from "bun:test"
2+
import { Automation } from "@opencode/core/automation"
3+
import { Plugin } from "@opencode/core/plugin"
4+
import { PluginHost } from "@opencode/core/plugin/host"
5+
import { PluginPromise } from "@opencode/core/plugin/promise"
6+
import { Effect } from "effect"
7+
import { testEffect } from "../lib/effect"
8+
import { PluginTestLayer } from "./fixture"
9+
10+
const it = testEffect(PluginTestLayer)
11+
12+
it.live("Effect plugins can create, list and delete automations", () =>
13+
Effect.gen(function* () {
14+
const plugins = yield* Plugin.Service
15+
const automations = yield* Automation.Service
16+
const context = yield* PluginHost.make(plugins, "test")
17+
const session = yield* context.session.create({ title: "Effect automation target" })
18+
19+
const created = yield* context.experimental.automation.create({
20+
directory: context.location.directory,
21+
name: "effect inbox",
22+
trigger: { type: "cron", cron: "0 * * * *", tz: "Europe/Madrid" },
23+
action: { type: "prompt", prompt: "Clean up the inboxes now.", to: { session: session.id } },
24+
})
25+
26+
expect(created).toMatchObject({
27+
name: "effect inbox",
28+
status: "active",
29+
trigger: { type: "cron", cron: "0 * * * *" },
30+
action: { type: "prompt", prompt: "Clean up the inboxes now.", to: { session: session.id } },
31+
})
32+
const listed = yield* context.experimental.automation.list({ directory: context.location.directory })
33+
expect(listed.map((item) => item.id)).toContain(created.id)
34+
35+
yield* context.experimental.automation.delete({ automationID: created.id })
36+
expect((yield* automations.list()).map((item) => item.id)).not.toContain(created.id)
37+
}),
38+
)
39+
40+
it.live("Promise plugins can create, list and delete automations", () =>
41+
Effect.gen(function* () {
42+
const plugins = yield* Plugin.Service
43+
const automations = yield* Automation.Service
44+
const context = yield* PluginHost.make(plugins, "test")
45+
const session = yield* context.session.create({ title: "Promise automation target" })
46+
const ids: string[] = []
47+
48+
yield* PluginPromise.fromPromise({
49+
id: "test.automation",
50+
async setup(ctx) {
51+
const created = await ctx.experimental.automation.create({
52+
directory: ctx.location.directory,
53+
name: "promise inbox",
54+
trigger: { type: "cron", cron: "0 9 * * *" },
55+
action: { type: "prompt", prompt: "Check the balance now.", to: { session: session.id } },
56+
})
57+
ids.push(created.id)
58+
expect(created).toMatchObject({ name: "promise inbox", action: { to: { session: session.id } } })
59+
expect(
60+
(await ctx.experimental.automation.list({ directory: ctx.location.directory })).map((item) => item.id),
61+
).toContain(created.id)
62+
await ctx.experimental.automation.delete({ automationID: created.id })
63+
await expect(ctx.experimental.automation.delete({ automationID: created.id })).rejects.toThrow()
64+
},
65+
}).effect(context)
66+
67+
expect(ids).toHaveLength(1)
68+
expect((yield* automations.list()).map((item) => item.id)).not.toContain(ids[0])
69+
}),
70+
)
Collapse file

‎packages/core/test/plugin/fixture.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/plugin/fixture.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { App } from "@opencode/core/app"
33
import { Artifact } from "@opencode/core/artifact"
44
import { BlobStore } from "@opencode/core/blob-store"
55
import { AISDK } from "@opencode/core/aisdk"
6+
import { Automation } from "@opencode/core/automation"
67
import { Command } from "@opencode/core/command"
78
import { Config } from "@opencode/core/config"
89
import { Credential } from "@opencode/core/credential"
@@ -128,6 +129,7 @@ export const makePluginTestLayer = (
128129
Agent.node,
129130
Artifact.node,
130131
AISDK.node,
132+
Automation.node,
131133
BlobStore.node,
132134
Provider.node,
133135
Model.node,
Collapse file

‎packages/core/test/plugin/host.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/plugin/host.ts
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,11 @@ export function host(overrides: Overrides = {}): Plugin.Context {
8181
transform: () => Effect.die("unused experimental.artifact.transform"),
8282
reload: () => Effect.die("unused experimental.artifact.reload"),
8383
},
84+
automation: {
85+
create: () => Effect.die("unused experimental.automation.create"),
86+
list: () => Effect.die("unused experimental.automation.list"),
87+
delete: () => Effect.die("unused experimental.automation.delete"),
88+
},
8489
},
8590
generate: overrides.generate ?? {
8691
text: () => Effect.die("unused generate.text"),
Collapse file

‎packages/plugin/src/effect/plugin.ts‎

Copy file name to clipboardExpand all lines: packages/plugin/src/effect/plugin.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ export interface Context {
3838
/** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */
3939
readonly generate: Omit<ExperimentalGenerateApi<unknown>, "video">
4040
readonly artifact: ExperimentalArtifactDomain
41+
/** Create, list and delete automations. Creation fails while automations are off where they would run. */
42+
readonly automation: Pick<ExperimentalApi<unknown>["automation"], "create" | "list" | "delete">
4143
}
4244
readonly integration: IntegrationDomain
4345
readonly mcp: MCPDomain
Collapse file

‎packages/plugin/src/promise/adapter.ts‎

Copy file name to clipboardExpand all lines: packages/plugin/src/promise/adapter.ts
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,11 @@ export function fromPromise(plugin: Plugin) {
405405
}),
406406
),
407407
},
408+
automation: {
409+
create: adaptApiMethod(ExperimentalEndpoints["automation.create"], host.experimental.automation.create),
410+
list: adaptApiMethod(ExperimentalEndpoints["automation.list"], host.experimental.automation.list),
411+
delete: adaptApiMethod(ExperimentalEndpoints["automation.delete"], host.experimental.automation.delete),
412+
},
408413
},
409414
generate: {
410415
text: adaptApiMethod(GenerateEndpoints["generate.text"], host.generate.text),

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.