fix(core): refuse plugin automation creates before configured permissions load (#66109)

This commit is contained in:
victor 2026-11-24 15:34:36 +01:00 • committed by GitHub
parent a44675ecee
commit af54caef70
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 156 additions and 126 deletions

View file

@ -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" })

View file

@ -88,10 +88,17 @@ export const FromPlugin = Context.Reference<Plugin.Interface | undefined>("@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.",
)
})
/**

View file

@ -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))

View file

@ -269,6 +269,7 @@ const layer = Layer.effect(
activate,
close,
awaitActivation: ready.await,
activated: Effect.sync(() => pending.size === 0),
hold,
list,
gui,

View file

@ -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 })),

View file

@ -14,6 +14,8 @@ export interface Interface {
readonly close: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>
/** Wait for announced updates and activation to settle; failures remain in the inventory. */
readonly awaitActivation: Effect.Effect<void>
/** Whether activation has settled, without waiting for it. */
readonly activated: Effect.Effect<boolean>
/** Keep readiness pending while preparing an update. Run the returned Effect to release it. */
readonly hold: () => Effect.Effect<Effect.Effect<void>>
}

View file

@ -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<unknown>> = []
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* () {

View file

@ -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 () => {