Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
123 changes: 123 additions & 0 deletions packages/opencode/src/tool/automate-manage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { Effect, Schema } from "effect"
import { ActiveRunStillRunningError, Automation } from "@/automation"
import { AutomationScheduler } from "@/automation/scheduler"
import * as Tool from "./tool"

const Action = Schema.Literals(["list", "pause", "resume", "delete"])

export const AutomateManageParameters = Schema.Struct({
action: Action.annotate({
description:
'Management action for an existing PawWork Automation: "list", "pause", "resume", or "delete".',
}),
id: Schema.optional(Schema.String).annotate({
description:
"Exact automation id from automate_manage list or an automate creation result. Required for pause, resume, and delete; omit for list.",
}),
})

type Parameters = Schema.Schema.Type<typeof AutomateManageParameters>
type Metadata = {
automationDefinitions?: Automation.Definition[]
automationDefinition?: Automation.Definition
automationTombstone?: Automation.Tombstone
stoppedRun?: Automation.Run
}

function schedule(definition: Automation.Definition) {
if (definition.kind === "oneshot") return new Date(definition.fireAt).toISOString()
if (definition.rhythm.kind === "cron") return definition.rhythm.expression
return `every ${definition.rhythm.everyMs}ms`
}

function item(definition: Automation.Definition) {
return {
id: definition.id,
title: definition.title,
kind: definition.kind,
paused: definition.paused,
schedule: schedule(definition),
timezone: definition.timezone,
context: definition.context,
nextFireAt: definition.kind === "recurring" ? definition.nextFireAt : undefined,
}
}

function requireID(params: Parameters) {
if (params.id) return params.id
throw new Error(`automate_manage action "${params.action}" requires an exact automation id.`)
}
Comment thread
Astro-Han marked this conversation as resolved.
Resolved

function readableAutomationError(error: unknown, id: string) {
if (error instanceof ActiveRunStillRunningError) {
return new Error(
`Cannot delete automation ${id}: active_run_still_running (${error.runID}). Try again after the active run finishes.`,
{ cause: error },
)
}
return error
}

export function createAutomateManageDefinition(
automation: Automation.Interface,
): Tool.DefWithoutID<typeof AutomateManageParameters, Metadata> {
return {
description: [
"Manage existing PawWork Automations from the conversation. Use this when the user asks to show scheduled tasks, list reminders, pause an automation, resume an automation, or delete/remove/cancel an automation. Never use OS schedulers (crontab, cron, at, launchd, schtasks) to manage PawWork Automations.",
"Use action list first when the user has not provided an exact automation id. Pause and resume are reversible and do not need confirmation. Delete is destructive and must ask the user for confirmation before removing anything.",
].join("\n\n"),
parameters: AutomateManageParameters,
execute: (params, ctx) =>
Effect.gen(function* () {
const scheduler = AutomationScheduler.current()
yield* Effect.promise(() => scheduler.settleOwner())

if (params.action === "list") {
const items = yield* automation.list()
return {
title: "Automations",
metadata: { automationDefinitions: items },
output: JSON.stringify({ items: items.map(item) }, null, 2),
}
}

const id = requireID(params)
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
const previous = yield* automation.get(id)
if (params.action === "pause" || params.action === "resume") {
const definition = yield* automation.update(id, { paused: params.action === "pause" })
if (definition.revision !== previous.revision) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
yield* automation.publishDefinitionUpdated(definition)
}
return {
title: params.action === "pause" ? "Automation paused" : "Automation resumed",
metadata: { automationDefinition: definition },
output: JSON.stringify(item(definition), null, 2),
}
}

yield* ctx.ask({
permission: "automate_manage",
patterns: [id],
always: [],
metadata: { action: "delete", id, title: previous.title },
})
const removed = yield* automation.remove(id).pipe(Effect.mapError((error) => readableAutomationError(error, id)))
yield* Effect.sync(() => scheduler.cancel(removed.tombstone.id))
if (removed.stoppedRun) yield* automation.publishRunUpdated(removed.stoppedRun)
yield* automation.publishDefinitionDeleted(removed.tombstone)
return {
title: "Automation deleted",
metadata: { automationTombstone: removed.tombstone, stoppedRun: removed.stoppedRun },
output: JSON.stringify(removed.tombstone, null, 2),
}
}),
}
}

export const AutomateManageTool = Tool.define(
"automate_manage",
Effect.gen(function* () {
const automation = yield* Automation.Service
return createAutomateManageDefinition(automation)
}),
)
4 changes: 4 additions & 0 deletions packages/opencode/src/tool/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { ApplyPatchTool } from "./apply_patch"
import { EnterWorktreeTool } from "./enter-worktree"
import { ExitWorktreeTool } from "./exit-worktree"
import { AutomateTool } from "./automate"
import { AutomateManageTool } from "./automate-manage"
import { Automation } from "@/automation"
import { Permission } from "../permission"
import { Glob } from "../util/glob"
Expand Down Expand Up @@ -164,6 +165,7 @@ export namespace ToolRegistry {
const enterWorktree = yield* EnterWorktreeTool
const exitWorktree = yield* ExitWorktreeTool
const automate = yield* AutomateTool
const automateManage = yield* AutomateManageTool
const browserNavigate = yield* BrowserNavigateTool
const browserSnapshot = yield* BrowserSnapshotTool
const browserClick = yield* BrowserClickTool
Expand Down Expand Up @@ -336,6 +338,7 @@ export namespace ToolRegistry {
enterWorktree: Tool.init(enterWorktree),
exitWorktree: Tool.init(exitWorktree),
automate: Tool.init(automate),
automateManage: Tool.init(automateManage),
toolInfo: Tool.init(toolInfoInfo),
browserNavigate: Tool.init(browserNavigate),
browserSnapshot: Tool.init(browserSnapshot),
Expand Down Expand Up @@ -371,6 +374,7 @@ export namespace ToolRegistry {
...(lspEnabled ? [tool.lsp] : []),
...(Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE && Flag.OPENCODE_CLIENT === "cli" ? [tool.plan] : []),
tool.automate,
tool.automateManage,
tool.enterWorktree,
tool.exitWorktree,
// Desktop-only: the embedded browser lives in the desktop app's
Expand Down
8 changes: 8 additions & 0 deletions packages/opencode/src/tool/tool-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Parameters as ExitWorktreeParameters } from "./exit-worktree"
import ExitWorktreeDescription from "./exit-worktree.txt"
import { Parameters as LspParameters } from "./lsp"
import LspDescription from "./lsp.txt"
import { AutomateManageParameters } from "./automate-manage"
import { Parameters as BrowserNavigateParameters } from "./browser-navigate"
import BrowserNavigateDescription from "./browser-navigate.txt"
import { Parameters as BrowserSnapshotParameters } from "./browser-snapshot"
Expand Down Expand Up @@ -65,6 +66,13 @@ const DEFERRED: DeferredEntry[] = [
description: LspDescription,
parameters: LspParameters as unknown as Tool.Def["parameters"],
},
{
id: "automate_manage",
card: "List, pause, resume, or delete existing PawWork Automations by exact id.",
description:
"Manage existing PawWork Automations from the conversation. Use this when the user asks to show scheduled tasks, list reminders, pause an automation, resume an automation, or delete/remove/cancel an automation. Delete asks the user for confirmation; pause and resume are reversible.",
parameters: AutomateManageParameters as unknown as Tool.Def["parameters"],
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
id: "browser_navigate",
card: "Open a URL in the embedded browser tab.",
Expand Down
196 changes: 196 additions & 0 deletions packages/opencode/test/tool/automate-manage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import { afterEach, describe, expect, test } from "bun:test"
import { Effect, ManagedRuntime, Schema } from "effect"
import { Automation } from "../../src/automation"
import { AutomationScheduler } from "../../src/automation/scheduler"
import { Instance } from "../../src/project/instance"
import { ProjectID } from "../../src/project/schema"
import { MessageID, SessionID } from "../../src/session/schema"
import { AutomateManageParameters, createAutomateManageDefinition } from "../../src/tool/automate-manage"
import { Flock } from "../../src/util/flock"
import { tmpdir } from "../fixture/fixture"
import { fakeAutomationProvider } from "../fake/provider"

const { providerID, modelID } = fakeAutomationProvider()
const runtime = ManagedRuntime.make(Automation.defaultLayer)
const automation = await runtime.runPromise(Effect.gen(function* () {
return yield* Automation.Service
}))

function recurring(projectID: ProjectID, title: string): Automation.CreateInput {
return {
kind: "recurring",
title,
prompt: `Run ${title}.`,
context: "fresh",
where: { projectID },
timezone: "UTC",
model: { providerID, modelID },
rhythm: { kind: "cron", expression: "0 9 * * *" },
stop: { kind: "never" },
}
}

function installScheduler(cancelled: string[] = []) {
AutomationScheduler.install({
stop: () => undefined,
settleOwner: async () => undefined,
reschedule: () => undefined,
cancel: (automationID) => cancelled.push(automationID),
computeNextFireAt: () => null,
})
}

function tool() {
return createAutomateManageDefinition(automation)
}

function toolContext(asks: unknown[] = []) {
return {
sessionID: SessionID.descending(),
messageID: MessageID.ascending(),
agent: "build",
abort: new AbortController().signal,
messages: [],
metadata: () => Effect.void,
ask: (input: unknown) => Effect.sync(() => { asks.push(input) }),
}
}

afterEach(async () => {
AutomationScheduler.stopProcess({ stopRuns: false })
await Instance.disposeAll()
})

describe("automate_manage tool", () => {
test("schema keeps the model-facing management surface flat and exact-id based", () => {
const decoded = Schema.decodeUnknownSync(AutomateManageParameters)({
action: "pause",
id: "aut_123",
paused: true,
where: { projectID: "spoofed" },
})

expect(decoded).toEqual({ action: "pause", id: "aut_123" })
})

test("lists current-scope automations with ids and schedules", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
installScheduler()
const created = Automation.create(recurring(Instance.project.id, "Daily repo brief"), { now: 100 })

const result = await Effect.runPromise(tool().execute({ action: "list" }, toolContext()))
const output = JSON.parse(result.output)

expect(result.title).toBe("Automations")
expect(output.items).toEqual([
expect.objectContaining({
id: created.id,
title: "Daily repo brief",
paused: false,
schedule: "0 9 * * *",
timezone: "UTC",
}),
])
},
})
})

test("pause and resume update by exact id without asking for confirmation", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
installScheduler()
const asks: unknown[] = []
const created = Automation.create(recurring(Instance.project.id, "Daily repo brief"), { now: 100 })

const paused = await Effect.runPromise(tool().execute({ action: "pause", id: created.id }, toolContext(asks)))
expect(paused.title).toBe("Automation paused")
expect(paused.metadata.automationDefinition).toMatchObject({ id: created.id, paused: true, revision: 2 })
expect(Automation.get(created.id).paused).toBe(true)

const resumed = await Effect.runPromise(tool().execute({ action: "resume", id: created.id }, toolContext(asks)))
expect(resumed.title).toBe("Automation resumed")
expect(resumed.metadata.automationDefinition).toMatchObject({ id: created.id, paused: false, revision: 3 })
expect(Automation.get(created.id).paused).toBe(false)
expect(asks).toEqual([])
},
})
})

test("delete asks once, cancels the scheduler, and removes the automation", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
const cancelled: string[] = []
const asks: unknown[] = []
installScheduler(cancelled)
const created = Automation.create(recurring(Instance.project.id, "Daily repo brief"), { now: 100 })

const result = await Effect.runPromise(tool().execute({ action: "delete", id: created.id }, toolContext(asks)))

expect(result.title).toBe("Automation deleted")
expect(result.metadata.automationTombstone).toEqual({ id: created.id, deleted: true, revision: 2 })
expect(JSON.parse(result.output)).toEqual({ id: created.id, deleted: true, revision: 2 })
expect(cancelled).toEqual([created.id])
expect(asks).toEqual([
{
permission: "automate_manage",
patterns: [created.id],
always: [],
metadata: { action: "delete", id: created.id, title: "Daily repo brief" },
},
])
expect(Automation.list()).toEqual([])
},
})
})

test("non-list actions require an exact automation id", async () => {
installScheduler()
await expect(Effect.runPromise(tool().execute({ action: "pause" }, toolContext()))).rejects.toThrow(
'automate_manage action "pause" requires an exact automation id.',
)
})

test("delete preserves the automation when a live active run is still running", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
installScheduler()
const created = Automation.create(recurring(Instance.project.id, "Daily repo brief"), { now: 100 })
const active = Automation.runNow(created.id, { now: 200 })
await using _lease = await Flock.acquire(`automation-run:${Instance.directory}:${active.id}`)

await expect(
Effect.runPromise(tool().execute({ action: "delete", id: created.id }, toolContext())),
).rejects.toThrow(`Cannot delete automation ${created.id}: active_run_still_running (${active.id})`)

expect(Automation.get(created.id).id).toBe(created.id)
},
})
})

test("delete stops before removal when the confirmation is denied", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
installScheduler()
const created = Automation.create(recurring(Instance.project.id, "Daily repo brief"), { now: 100 })
const ctx = { ...toolContext(), ask: () => Effect.die(new Error("denied")) }

await expect(Effect.runPromise(tool().execute({ action: "delete", id: created.id }, ctx))).rejects.toThrow(
"denied",
)

expect(Automation.get(created.id).id).toBe(created.id)
},
})
})
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading
Loading