Repository navigation
feat(tool): add automate_manage lifecycle actions #1278
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
5d5ac5e
feat(tool): add automate manage actions
Astro-Han 8393bf4
feat(tool): defer automate manage activation
Astro-Han d80c076
fix(permission): respect once-only approval prompts
Astro-Han 4f54cc7
fix(tool): report missing automation ids through Effect
Astro-Han c3b97aa
fix(tool): clarify automate_manage activation contract
Astro-Han d58cf06
test(session): cover automate_manage model activation
Astro-Han ad4c3c9
fix(tool): report stale automation ids clearly
Astro-Han b14ca66
fix(tool): avoid scheduler settle in automate_manage
Astro-Han 76a9642
test(tool): pin automate_manage model contract
Astro-Han a95a8ee
fix(tool): report delete race automation ids clearly
Astro-Han d3bb3d1
fix(tool): rely on automation delete events for scheduling
Astro-Han cbe32b3
fix(tool): report update race automation ids clearly
Astro-Han b7db39a
test(session): clarify automate_manage activation request count
Astro-Han fedb1dd
chore: merge dev into automate_manage branch
Astro-Han File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.`) | ||
| } | ||
|
|
||
| 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) | ||
|
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) { | ||
|
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) | ||
| }), | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| }, | ||
| }) | ||
| }) | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.