From af54caef70f9bc1d700d9bfd5b4f2f7471deadd8 Mon Sep 17 00:00:00 2001 From: victor Date: Tue, 24 Nov 2026 15:34:36 +0100 Subject: [PATCH] fix(core): refuse plugin automation creates before configured permissions load (#66109) --- packages/core/src/automation.ts | 2 +- packages/core/src/automation/code.ts | 11 +- packages/core/src/automation/shell.ts | 3 +- packages/core/src/plugin.ts | 1 + packages/core/src/plugin/host.ts | 5 +- packages/core/src/plugin/service.ts | 2 + packages/core/test/plugin/automation.test.ts | 165 ++++++++----------- packages/sdk/test/instances.test.ts | 93 ++++++++--- 8 files changed, 156 insertions(+), 126 deletions(-) diff --git a/packages/core/src/automation.ts b/packages/core/src/automation.ts index 7d74291a682..466cc45415c 100644 --- a/packages/core/src/automation.ts +++ b/packages/core/src/automation.ts @@ -272,7 +272,7 @@ const layer = Layer.effect( */ const subagent = (owner: SessionSchema.Info, id: Agent.ID, invocation?: Invocation) => Effect.gen(function* () { - yield* AutomationCode.awaitPlugins + yield* AutomationCode.awaitPlugins.pipe(Effect.mapError((reason) => new InvalidError({ reason }))) const location = yield* Location.Service if (location.project.id !== owner.projectID) return yield* new InvalidError({ reason: "The creating session's location is no longer in its project" }) diff --git a/packages/core/src/automation/code.ts b/packages/core/src/automation/code.ts index ea25fe4f2da..4a676fadd9d 100644 --- a/packages/core/src/automation/code.ts +++ b/packages/core/src/automation/code.ts @@ -88,10 +88,17 @@ export const FromPlugin = Context.Reference("@open defaultValue: () => undefined, }) -/** Wait unless this registry's activation could be waiting on the calling plugin's setup. */ +/** + * Waits for this registry's plugins. A create from a plugin in this same registry is refused instead while it activates: + * its activation may be waiting on that plugin's setup, and configured permissions are applied by plugins that load later. + */ export const awaitPlugins = Effect.gen(function* () { const plugins = yield* Plugin.Service - if ((yield* FromPlugin) !== plugins) yield* plugins.awaitActivation + if ((yield* FromPlugin) !== plugins) return yield* plugins.awaitActivation + if (yield* plugins.activated) return + return yield* Effect.fail( + "Plugins in this location are still loading, so configured permissions are not applied yet. Create this automation after plugin setup, for example from an event handler.", + ) }) /** diff --git a/packages/core/src/automation/shell.ts b/packages/core/src/automation/shell.ts index 0cc2e800ec2..7c03ac79b2c 100644 --- a/packages/core/src/automation/shell.ts +++ b/packages/core/src/automation/shell.ts @@ -12,6 +12,7 @@ import { Shell } from "../shell.js" import { ShellPermissions } from "../shell/permissions.js" import { ShellSelect } from "../shell/select.js" import { type Invocation, matchesAuthor } from "./author.js" +import { AutomationCode } from "./code.js" export const authorize = Effect.fnUntraced(function* ( owner: SessionSchema.Info, @@ -20,7 +21,7 @@ export const authorize = Effect.fnUntraced(function* ( action: Automation.ShellAction, invocation?: Invocation, ) { - if (invocation) yield* Plugin.awaitActivation + if (invocation || (yield* AutomationCode.FromPlugin)) yield* AutomationCode.awaitPlugins const agents = yield* Agent.Service const agent = yield* agents.select(owner.agent) if (invocation && !matchesAuthor(owner, agent.info, invocation)) diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index f3c5e902d3b..afa58bc1502 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -269,6 +269,7 @@ const layer = Layer.effect( activate, close, awaitActivation: ready.await, + activated: Effect.sync(() => pending.size === 0), hold, list, gui, diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index 507b249cf01..33b77dbe8d1 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -327,8 +327,9 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p automation: { // A plugin has no UI listener to answer an interactive ask, so asks settle unattended, as they do over HTTP. // A JavaScript plugin can pass any shape, so validate it against the type-side schema before storing it. - // Its own registry may be waiting on this setup, so use what's loaded there now. The instance's selector - // can serve its own Sessions while booting. Other registries still have to finish activating. + // Its own registry may be waiting on this setup, so creates that need permissions are refused there until it + // finishes activating. The instance's selector can serve its own Sessions while booting. Other registries still + // have to finish activating. create: (input) => Schema.decodeUnknownEffect(Schema.toType(Automation.CreateInput))(input).pipe( Effect.mapError((error) => new Automation.InvalidError({ reason: error.message })), diff --git a/packages/core/src/plugin/service.ts b/packages/core/src/plugin/service.ts index d647969c8ab..41dc98517d2 100644 --- a/packages/core/src/plugin/service.ts +++ b/packages/core/src/plugin/service.ts @@ -14,6 +14,8 @@ export interface Interface { readonly close: (exit: Exit.Exit) => Effect.Effect /** Wait for announced updates and activation to settle; failures remain in the inventory. */ readonly awaitActivation: Effect.Effect + /** Whether activation has settled, without waiting for it. */ + readonly activated: Effect.Effect /** Keep readiness pending while preparing an update. Run the returned Effect to release it. */ readonly hold: () => Effect.Effect> } diff --git a/packages/core/test/plugin/automation.test.ts b/packages/core/test/plugin/automation.test.ts index d14d7f000e1..33ae9c2c44e 100644 --- a/packages/core/test/plugin/automation.test.ts +++ b/packages/core/test/plugin/automation.test.ts @@ -67,109 +67,74 @@ it.live("Effect plugins cannot store an automation with an invalid target", () = }), ) -it.live("a plugin can create a code automation while its Location activates", () => - Effect.gen(function* () { - const automations = yield* Automation.Service - const location = yield* Location.Service - const locations = yield* LocationServiceMap.Service - const loaded: string[] = [] +const setupActions = { + code: { type: "code", code: "return" }, + subagent: { type: "prompt", prompt: "Triage the inbox.", to: { subagent: Agent.ID.make("general") } }, +} as const - // Activate the Location's own plugins, the ones a create in that Location waits for. - yield* Effect.gen(function* () { - const plugins = yield* Plugin.Service - yield* plugins.awaitActivation - yield* plugins.activate([ - { - id: "test.automation.effect", - revision: "1", - effect: (ctx) => - Effect.gen(function* () { - const session = yield* ctx.session.create({ title: "Effect code automation" }) - yield* ctx.experimental.automation.create({ - sessionID: session.id, - name: "effect code", - trigger: { type: "cron", cron: "0 * * * *" }, - action: { type: "code", code: "return" }, - }) - loaded.push("effect") - }).pipe(Effect.orDie), - }, - { - revision: "1", - ...PluginPromise.fromPromise({ - id: "test.automation.promise", - async setup(ctx) { - const session = await ctx.session.create({ title: "Promise code automation" }) - await ctx.experimental.automation.create({ - sessionID: session.id, - name: "promise code", - trigger: { type: "cron", cron: "0 * * * *" }, - action: { type: "code", code: "return" }, - }) - loaded.push("promise") - }, - }), - }, - { id: "test.automation.after", revision: "1", effect: () => Effect.sync(() => loaded.push("after")) }, - ]) - }).pipe(Effect.provide(locations.get(LocationServiceMap.canonical({ directory: location.directory })))) +for (const kind of ["code", "subagent"] as const) { + it.live(`a plugin's ${kind} automation is refused while its Location activates and created after`, () => + Effect.gen(function* () { + const automations = yield* Automation.Service + const location = yield* Location.Service + const locations = yield* LocationServiceMap.Service + const loaded: string[] = [] + const later: Array<() => Promise> = [] + const input = (name: string) => + ({ name, trigger: { type: "every", every: "1 hour" }, action: setupActions[kind] }) as const - expect(loaded).toEqual(["effect", "promise", "after"]) - expect((yield* automations.list()).map((item) => item.name)).toEqual( - expect.arrayContaining(["effect code", "promise code"]), - ) - }), -) + // Activate the Location's own plugins. Their permissions are not all applied yet, so creates that need them fail. + yield* Effect.gen(function* () { + const plugins = yield* Plugin.Service + yield* plugins.awaitActivation + yield* plugins.activate([ + { ...AgentPlugin.Plugin, revision: "1" }, + { + id: "test.automation.effect", + revision: "1", + effect: (ctx) => + Effect.gen(function* () { + const session = yield* ctx.session.create({ title: `Effect ${kind} automation` }) + const create = ctx.experimental.automation.create({ ...input("effect"), sessionID: session.id }) + loaded.push( + yield* create.pipe( + Effect.match({ + onFailure: (error) => + String(error).includes("still loading") ? "effect refused" : String(error), + onSuccess: () => "effect created", + }), + ), + ) + later.push(() => Effect.runPromise(create)) + }).pipe(Effect.orDie), + }, + { + revision: "1", + ...PluginPromise.fromPromise({ + id: "test.automation.promise", + async setup(ctx) { + const session = await ctx.session.create({ title: `Promise ${kind} automation` }) + const create = () => ctx.experimental.automation.create({ ...input("promise"), sessionID: session.id }) + await create().then( + () => loaded.push("promise created"), + (error: unknown) => + loaded.push(String(error).includes("still loading") ? "promise refused" : String(error)), + ) + later.push(create) + }, + }), + }, + { id: "test.automation.after", revision: "1", effect: () => Effect.sync(() => loaded.push("after")) }, + ]) + }).pipe(Effect.provide(locations.get(LocationServiceMap.canonical({ directory: location.directory })))) -it.live("a plugin can create a subagent prompt automation while its Location activates", () => - Effect.gen(function* () { - const automations = yield* Automation.Service - const location = yield* Location.Service - const locations = yield* LocationServiceMap.Service - const loaded: string[] = [] - const triage = { - name: "triage", - trigger: { type: "every", every: "1 hour" }, - action: { type: "prompt", prompt: "Triage the inbox.", to: { subagent: Agent.ID.make("general") } }, - } as const - - // Activate the Location's own plugins, the ones a create in that Location waits for. - yield* Effect.gen(function* () { - const plugins = yield* Plugin.Service - yield* plugins.awaitActivation - yield* plugins.activate([ - { ...AgentPlugin.Plugin, revision: "1" }, - { - id: "test.automation.effect", - revision: "1", - effect: (ctx) => - Effect.gen(function* () { - const session = yield* ctx.session.create({ title: "Effect subagent automation" }) - yield* ctx.experimental.automation.create({ ...triage, sessionID: session.id, name: "effect triage" }) - loaded.push("effect") - }).pipe(Effect.orDie), - }, - { - revision: "1", - ...PluginPromise.fromPromise({ - id: "test.automation.promise", - async setup(ctx) { - const session = await ctx.session.create({ title: "Promise subagent automation" }) - await ctx.experimental.automation.create({ ...triage, sessionID: session.id, name: "promise triage" }) - loaded.push("promise") - }, - }), - }, - { id: "test.automation.after", revision: "1", effect: () => Effect.sync(() => loaded.push("after")) }, - ]) - }).pipe(Effect.provide(locations.get(LocationServiceMap.canonical({ directory: location.directory })))) - - expect(loaded).toEqual(["effect", "promise", "after"]) - expect((yield* automations.list()).map((item) => item.name)).toEqual( - expect.arrayContaining(["effect triage", "promise triage"]), - ) - }), -) + expect(loaded).toEqual(["effect refused", "promise refused", "after"]) + expect((yield* automations.list()).map((item) => item.name)).toEqual([]) + yield* Effect.promise(() => Promise.all(later.map((create) => create()))) + expect((yield* automations.list()).map((item) => item.name).toSorted()).toEqual(["effect", "promise"]) + }), + ) +} it.live("a plugin's create for another Location waits for that Location's plugins", () => Effect.gen(function* () { diff --git a/packages/sdk/test/instances.test.ts b/packages/sdk/test/instances.test.ts index 653b73c4aa0..20573e96a23 100644 --- a/packages/sdk/test/instances.test.ts +++ b/packages/sdk/test/instances.test.ts @@ -145,10 +145,11 @@ test("Promise instances are lazy, share by key and Location, and stay isolated b expect(cleanups.toSorted()).toEqual(setups.toSorted()) }, 20_000) -test("a cold instance plugin can create a shell automation for its Session during setup", async () => { +test("a cold instance plugin creates a shell automation for its Session after setup, not during it", async () => { await using directory = await tmpdir("opencode-instance-shell-automation-") const sessionID = Session.ID.create() - const created: string[] = [] + const refused: string[] = [] + let create: () => Promise<{ name: string }> = () => Promise.reject(new Error("setup did not run")) await using opencode = await OpenCode.create({ ...hostOptions(directory.path), instances: { @@ -158,13 +159,14 @@ test("a cold instance plugin can create a shell automation for its Session durin { id: "shell-automation", async setup(ctx) { - const automation = await ctx.experimental.automation.create({ - sessionID, - name: "hourly", - trigger: { type: "every", every: "1 hour" }, - action: { type: "shell", command: "echo ok" }, - }) - created.push(automation.name) + create = () => + ctx.experimental.automation.create({ + sessionID, + name: "hourly", + trigger: { type: "every", every: "1 hour" }, + action: { type: "shell", command: "echo ok" }, + }) + await create().catch((error: unknown) => refused.push(String(error))) }, }, ], @@ -173,7 +175,55 @@ test("a cold instance plugin can create a shell automation for its Session durin }) await opencode.sessions.create({ id: sessionID, location: { directory: directory.path } }) expect(await opencode.permission.list({ sessionID })).toEqual([]) - expect(created).toEqual(["hourly"]) + expect(refused).toEqual([expect.stringContaining("still loading")]) + expect((await create()).name).toBe("hourly") +}) + +test.each([ + { kind: "shell", deny: "shell", action: { type: "shell", command: "true" } }, + { kind: "code", deny: "execute", action: { type: "code", code: "return" } }, + { kind: "subagent", deny: "subagent", action: { type: "prompt", prompt: "Check in.", to: { subagent: "general" } } }, +] as const)("a cold instance plugin cannot create a $kind automation that config denies", async (input) => { + await using directory = await tmpdir("opencode-instance-denied-automation-") + const sessionID = Session.ID.create() + const outcome: { created?: string; error?: string; stored?: number } = {} + const options = hostOptions(directory.path) + await using opencode = await OpenCode.create({ + ...options, + config: { + ...options.config, + content: JSON.stringify({ permissions: [{ action: input.deny, resource: "*", effect: "deny" }] }), + }, + instances: { + key: () => "one", + configure: () => ({ + plugins: [ + { + id: "denied-automation", + async setup(ctx) { + await ctx.experimental.automation + .create({ + sessionID, + name: "hourly", + trigger: { type: "every", every: "1 hour" }, + action: input.action, + }) + .then( + (automation) => (outcome.created = automation.name), + (error: unknown) => (outcome.error = String(error)), + ) + outcome.stored = (await ctx.experimental.automation.list({ directory: ctx.location.directory })).length + }, + }, + ], + }), + }, + }) + await opencode.sessions.create({ id: sessionID, location: { directory: directory.path } }) + expect(await opencode.permission.list({ sessionID })).toEqual([]) + expect(outcome.created).toBeUndefined() + expect(outcome.error).toBeDefined() + expect(outcome.stored).toBe(0) }) test("an instance plugin's code automation waits for the host's tool registry in the same Location", async () => { @@ -250,10 +300,11 @@ test("an instance plugin's code automation waits for the host's tool registry in } }) -test("a cold instance plugin can create a subagent prompt automation for its Session during setup", async () => { +test("a cold instance plugin creates a subagent prompt automation for its Session after setup, not during it", async () => { await using directory = await tmpdir("opencode-instance-subagent-automation-") const sessionID = Session.ID.create() - const created: string[] = [] + const refused: string[] = [] + let create: () => Promise<{ name: string }> = () => Promise.reject(new Error("setup did not run")) const options = hostOptions(directory.path) await using opencode = await OpenCode.create({ ...options, @@ -269,13 +320,14 @@ test("a cold instance plugin can create a subagent prompt automation for its Ses { id: "subagent-automation", async setup(ctx) { - const automation = await ctx.experimental.automation.create({ - sessionID, - name: "triage", - trigger: { type: "every", every: "1 hour" }, - action: { type: "prompt", prompt: "Triage the inbox.", to: { subagent: "general" } }, - }) - created.push(automation.name) + create = () => + ctx.experimental.automation.create({ + sessionID, + name: "triage", + trigger: { type: "every", every: "1 hour" }, + action: { type: "prompt", prompt: "Triage the inbox.", to: { subagent: "general" } }, + }) + await create().catch((error: unknown) => refused.push(String(error))) }, }, ], @@ -284,7 +336,8 @@ test("a cold instance plugin can create a subagent prompt automation for its Ses }) await opencode.sessions.create({ id: sessionID, location: { directory: directory.path } }) expect(await opencode.permission.list({ sessionID })).toEqual([]) - expect(created).toEqual(["triage"]) + expect(refused).toEqual([expect.stringContaining("still loading")]) + expect((await create()).name).toBe("triage") }) test("a throwing fork hook still returns the saved fork", async () => {