mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
feat(core): enforce skill integration policies
This commit is contained in:
@@ -13,7 +13,9 @@ export const Plugin = define({
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const config = yield* Config.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const reload = State.batch(Effect.all([ctx.provider.reload(), ctx.mcp.reload()], { discard: true }))
|
||||
const reload = State.batch(
|
||||
Effect.all([ctx.provider.reload(), ctx.mcp.reload(), ctx.skill.reload()], { discard: true }),
|
||||
)
|
||||
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, reload)
|
||||
yield* managed.changes().pipe(
|
||||
Stream.runForEach(() => reload),
|
||||
@@ -37,6 +39,12 @@ export const Plugin = define({
|
||||
if (ManagedPolicy.decision(current, "integration.use", `mcp:${name}`) === "deny") servers.remove(name)
|
||||
}
|
||||
})
|
||||
yield* ctx.skill.transform((skills) => {
|
||||
const current = policies()
|
||||
for (const skill of skills.list()) {
|
||||
if (ManagedPolicy.decision(current, "integration.use", `skill:${skill.id}`) === "deny") skills.remove(skill.id)
|
||||
}
|
||||
})
|
||||
yield* ctx.permission.hook("evaluate", (event) =>
|
||||
Effect.sync(() => {
|
||||
const current = policies()
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
import { ConfigPolicyPlugin } from "@opencode/core/config/plugin/policy"
|
||||
import { Mcp } from "@opencode/core/mcp/index"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { ID } from "@opencode/schema/event"
|
||||
import { Effect, Stream } from "effect"
|
||||
import { host } from "../plugin/host"
|
||||
|
||||
// Exercise the real policy plugin against a live MCP catalog without unrelated provider/permission setup.
|
||||
export const registerIntegrationPolicy = Effect.fn(function* (
|
||||
mcp: Mcp.Interface,
|
||||
events: Stream.Stream<{ readonly type: string }, unknown> = Stream.never,
|
||||
) {
|
||||
// Exercise the real policy plugin against supplied catalogs without unrelated provider/permission setup.
|
||||
export const registerIntegrationPolicy = Effect.fn(function* (input: {
|
||||
mcp?: Mcp.Interface
|
||||
skill?: Skill.Interface
|
||||
events?: Stream.Stream<{ readonly type: string }, unknown>
|
||||
}) {
|
||||
yield* ConfigPolicyPlugin.Plugin.effect(
|
||||
host({
|
||||
event: {
|
||||
subscribe: () =>
|
||||
events.pipe(
|
||||
(input.events ?? Stream.never).pipe(
|
||||
Stream.filter((event) => event.type === "config.updated"),
|
||||
Stream.map(() => ({ id: ID.create(), created: Date.now(), type: "config.updated" as const, data: {} })),
|
||||
),
|
||||
@@ -26,8 +28,13 @@ export const registerIntegrationPolicy = Effect.fn(function* (
|
||||
},
|
||||
mcp: {
|
||||
list: () => Effect.die("unused mcp.list"),
|
||||
transform: (callback) => mcp.transform(callback),
|
||||
reload: mcp.reload,
|
||||
transform: (callback) => input.mcp?.transform(callback) ?? Effect.succeed({ dispose: Effect.void }),
|
||||
reload: () => input.mcp?.reload() ?? Effect.void,
|
||||
},
|
||||
skill: {
|
||||
list: () => Effect.die("unused skill.list"),
|
||||
transform: (callback) => input.skill?.transform(callback) ?? Effect.succeed({ dispose: Effect.void }),
|
||||
reload: () => input.skill?.reload() ?? Effect.void,
|
||||
},
|
||||
permission: {
|
||||
hook: () => Effect.succeed({ dispose: Effect.void }),
|
||||
|
||||
@@ -289,7 +289,7 @@ function resourceMcpLayer(
|
||||
yield* State.batch(
|
||||
Effect.gen(function* () {
|
||||
yield* ConfigMcpPlugin.register(bus.subscribe())
|
||||
yield* registerIntegrationPolicy(mcp, bus.subscribe())
|
||||
yield* registerIntegrationPolicy({ mcp, events: bus.subscribe() })
|
||||
}),
|
||||
)
|
||||
}),
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import type { FileSystem } from "@opencode/core/filesystem"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer, LayerMap } from "effect"
|
||||
import { Duration, Effect, Layer, LayerMap } from "effect"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { makeGlobalNode } from "@opencode/util/effect/app-node"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { Image } from "@opencode/core/image"
|
||||
import { Location } from "@opencode/core/location"
|
||||
import { LocationServiceMap } from "@opencode/core/location-service-map"
|
||||
@@ -26,6 +28,7 @@ import { Skill } from "@opencode/core/skill"
|
||||
import { Event } from "@opencode/schema/event"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { globalProjectNode } from "./lib/project"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
|
||||
const info = Skill.Info.make({
|
||||
@@ -39,25 +42,51 @@ const locations = makeGlobalNode({
|
||||
service: LocationServiceMap.Service,
|
||||
layer: Layer.effect(
|
||||
LocationServiceMap.Service,
|
||||
LayerMap.make(
|
||||
(_ref: Location.Ref) =>
|
||||
// These tests need skill activation and prompt preparation from the same location services.
|
||||
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
|
||||
Layer.mergeAll(
|
||||
LayerNode.compile(LayerNode.group([PluginHooks.node, Image.node])),
|
||||
Layer.mock(Skill.Service, {
|
||||
get: (id) => Effect.succeed(id === info.id ? info : undefined),
|
||||
list: () => Effect.succeed([info]),
|
||||
}),
|
||||
Layer.mock(Plugin.Service, { awaitActivation: Effect.void }),
|
||||
) as unknown as Layer.Layer<LocationServices, FileSystem.DirectoryNotFoundError>,
|
||||
),
|
||||
Effect.gen(function* () {
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
return yield* LayerMap.make(
|
||||
(_ref: Location.Ref) =>
|
||||
// These tests need skill activation and prompt preparation from the same location services.
|
||||
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
|
||||
Layer.mergeAll(
|
||||
Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
yield* skills.transform((editor) => editor.add(info))
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(
|
||||
LayerNode.compile(
|
||||
LayerNode.group([PluginHooks.node, Image.node, Skill.node, Config.node, ManagedPolicy.node]),
|
||||
{
|
||||
replacements: [
|
||||
Config.node.replace(Config.testLayer()),
|
||||
ManagedPolicy.node.replace(Layer.succeed(ManagedPolicy.Service, managed)),
|
||||
],
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
Layer.mock(Plugin.Service, { awaitActivation: Effect.void }),
|
||||
) as unknown as Layer.Layer<LocationServices, FileSystem.DirectoryNotFoundError>,
|
||||
{ idleTimeToLive: Duration.infinity },
|
||||
)
|
||||
}),
|
||||
),
|
||||
deps: [],
|
||||
deps: [ManagedPolicy.node],
|
||||
})
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]),
|
||||
LayerNode.group([
|
||||
Database.node,
|
||||
Bus.node,
|
||||
SessionProjector.node,
|
||||
SessionStore.node,
|
||||
Session.node,
|
||||
ManagedPolicy.node,
|
||||
LocationServiceMap.node,
|
||||
]),
|
||||
[
|
||||
LocationServiceMap.node.replace(locations),
|
||||
Project.node.replace(globalProjectNode),
|
||||
@@ -67,6 +96,30 @@ const it = testEffect(
|
||||
)
|
||||
|
||||
describe("Session.skill", () => {
|
||||
it.effect("refuses blocked skill mentions and standalone activation without writing their content", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:effect", effect: "deny" }] })
|
||||
expect(
|
||||
yield* sessions.skill({ sessionID: session.id, skill: info.id, resume: false }).pipe(Effect.flip),
|
||||
).toMatchObject({ _tag: "Session.SkillNotFoundError", skill: info.id })
|
||||
expect(
|
||||
yield* sessions
|
||||
.prompt({
|
||||
sessionID: session.id,
|
||||
text: "@effect",
|
||||
skills: [{ id: info.id, mention: { start: 0, end: 7, text: "@effect" } }],
|
||||
resume: false,
|
||||
})
|
||||
.pipe(Effect.flip),
|
||||
).toMatchObject({ _tag: "Session.SkillNotFoundError", skill: info.id })
|
||||
expect(yield* sessions.messages({ sessionID: session.id })).toEqual([])
|
||||
expect(yield* sessions.inbox(session.id)).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("materializes mentioned skills on their owning prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
@@ -144,6 +197,8 @@ describe("Session.skill", () => {
|
||||
const bus = yield* Bus.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
const id = SessionMessage.ID.make("msg_caller_skill")
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
yield* Skill.Service.use((skills) => skills.list()).pipe(Effect.provide(locations.get(session.location)))
|
||||
const events: Event.Payload[] = []
|
||||
yield* bus.listen((event) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Deferred, Effect, Fiber, Stream } from "effect"
|
||||
import { Deferred, Effect, Fiber, Layer, Schedule, Stream } from "effect"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { Document, Event } from "@opencode/schema/config"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { SkillInstructions } from "@opencode/core/skill/instructions"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { readInitial } from "./lib/instructions"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
|
||||
const it = testEffect(AppNodeBuilder.build(LayerNode.group([Skill.node, Agent.node, Bus.node])))
|
||||
const configLayer = Config.testLayer()
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Skill.node, SkillInstructions.node, Agent.node, Bus.node, ManagedPolicy.node]),
|
||||
[Config.node.replace(configLayer)],
|
||||
).pipe(Layer.provideMerge(configLayer)),
|
||||
)
|
||||
|
||||
const info = (id: string, description: string) =>
|
||||
Skill.Info.make({
|
||||
@@ -20,6 +32,93 @@ const info = (id: string, description: string) =>
|
||||
})
|
||||
|
||||
describe("Skill", () => {
|
||||
it.live("hides and refuses denied skills while organization policy overrides local allows", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const config = yield* Config.Test
|
||||
yield* skills.transform((editor) => {
|
||||
editor.add(info("team:review", "Review"))
|
||||
editor.add(info("deploy", "Deploy"))
|
||||
})
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: {
|
||||
experimental: { policies: [{ action: "integration.use", resource: "skill:*", effect: "allow" }] },
|
||||
},
|
||||
}),
|
||||
])
|
||||
yield* managed.set({
|
||||
statements: [
|
||||
{ action: "integration.use", resource: "*", effect: "deny" },
|
||||
{ action: "integration.use", resource: "skill:team:review", effect: "allow" },
|
||||
],
|
||||
})
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
expect(yield* skills.list()).toEqual([info("team:review", "Review")])
|
||||
expect(yield* skills.get(Skill.ID.make("deploy"))).toBeUndefined()
|
||||
expect(yield* skills.get(Skill.ID.make("team:review"))).toEqual(info("team:review", "Review"))
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
const guidance = yield* instructions.load([]).pipe(Effect.flatMap(readInitial))
|
||||
expect(guidance.text).toContain("<id>team:review</id>")
|
||||
expect(guidance.text).not.toContain("deploy")
|
||||
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:team:review", effect: "deny" }] })
|
||||
yield* waitUntil(skills.get(Skill.ID.make("team:review")).pipe(Effect.map((skill) => skill === undefined)))
|
||||
expect(yield* skills.get(Skill.ID.make("team:review"))).toBeUndefined()
|
||||
expect(yield* skills.list()).toEqual([info("deploy", "Deploy")])
|
||||
yield* managed.set({ statements: [] })
|
||||
yield* waitUntil(skills.list().pipe(Effect.map((skills) => skills.length === 2)))
|
||||
expect(yield* skills.list()).toHaveLength(2)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("applies configuration precedence to skills without changing their registered values", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const config = yield* Config.Test
|
||||
yield* skills.transform((editor) => editor.add(info("review", "Review")))
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: { experimental: { policies: [{ action: "integration.use", resource: "skill:*", effect: "deny" }] } },
|
||||
}),
|
||||
new Document({
|
||||
type: "document",
|
||||
info: {
|
||||
experimental: { policies: [{ action: "integration.use", resource: "skill:review", effect: "allow" }] },
|
||||
},
|
||||
}),
|
||||
])
|
||||
const bus = yield* Bus.Service
|
||||
yield* registerIntegrationPolicy({ skill: skills, events: bus.subscribe() })
|
||||
expect(yield* skills.list()).toEqual([])
|
||||
expect(yield* skills.get(Skill.ID.make("review"))).toBeUndefined()
|
||||
yield* config.setEntries([])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* waitUntil(skills.get(Skill.ID.make("review")).pipe(Effect.map((skill) => skill !== undefined)))
|
||||
expect(yield* skills.get(Skill.ID.make("review"))).toEqual(info("review", "Review"))
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("publishes catalog updates when managed policy changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const bus = yield* Bus.Service
|
||||
yield* skills.transform((editor) => editor.add(info("review", "Review")))
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
const updated = yield* Deferred.make<Skill.Info[]>()
|
||||
yield* bus.subscribe(Skill.Event.Updated).pipe(
|
||||
Stream.runForEach(() => skills.list().pipe(Effect.flatMap((values) => Deferred.succeed(updated, values)))),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:review", effect: "deny" }] })
|
||||
expect(yield* Deferred.await(updated).pipe(Effect.timeout("1 second"))).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("reads the current editor entry by ID", () =>
|
||||
Effect.gen(function* () {
|
||||
const skill = yield* Skill.Service
|
||||
@@ -123,3 +222,12 @@ describe("Skill", () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
const waitUntil = (condition: Effect.Effect<boolean>) =>
|
||||
condition.pipe(
|
||||
Effect.filterOrFail(
|
||||
(ready) => ready,
|
||||
() => new Error("Skill policy was not applied"),
|
||||
),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
|
||||
@@ -8,6 +8,8 @@ import { Permission } from "@opencode/core/permission"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { SkillTool } from "@opencode/core/tool/plugin/skill"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
@@ -18,6 +20,7 @@ import { permissionLayer } from "./lib/permission"
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
|
||||
const skillToolNode = makeLocationNode({
|
||||
name: "test/skill-tool-plugin",
|
||||
@@ -28,6 +31,42 @@ const skillToolNode = makeLocationNode({
|
||||
const sessionID = Session.ID.make("ses_skill_tool_test")
|
||||
|
||||
describe("SkillTool", () => {
|
||||
it.effect("refuses a policy-blocked skill before authorization or content preparation", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const tools = yield* Tool.Service
|
||||
// This path does not exist; an attempted content scan would fail the test.
|
||||
yield* skills.transform((editor) =>
|
||||
editor.add(
|
||||
Skill.Info.make({
|
||||
id: Skill.ID.make("private"),
|
||||
name: Skill.Name.make("Private"),
|
||||
path: AbsolutePath.make("/unavailable/private/SKILL.md"),
|
||||
content: "Private instructions",
|
||||
}),
|
||||
),
|
||||
)
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:private", effect: "deny" }] })
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
expect(
|
||||
yield* executeTool(tools, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id: "call-policy-denied-skill", name: "skill", input: { id: "private" } },
|
||||
}),
|
||||
).toEqual({ status: "error", error: { type: "tool.execution", message: "Unable to load skill private" } })
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AppNodeBuilder.build(LayerNode.group([Tool.node, skillToolNode, Skill.node, Config.node, ManagedPolicy.node]), [
|
||||
Config.node.replace(Config.testLayer()),
|
||||
Permission.node.replace(permissionLayer({ assert: () => Effect.die("Blocked skill reached authorization") })),
|
||||
Image.node.replace(imagePassthrough),
|
||||
]),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("lists available skills, authorizes the selected ID, and loads model-facing content", () =>
|
||||
Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
|
||||
@@ -6,7 +6,7 @@ Status: **Implemented.**
|
||||
|
||||
Policies control whether an operation on a named resource is allowed. Statements are authored in configuration files or delivered by the connected OpenCode Console, and applied by a terminal plugin.
|
||||
|
||||
Two consumers exist:
|
||||
The supported actions are:
|
||||
|
||||
```text
|
||||
action: provider.use
|
||||
@@ -14,6 +14,10 @@ resource: provider ID, such as openai or company-ai
|
||||
|
||||
action: tool.use
|
||||
resource: <permission action>:<resource>, such as shell:sudo * or edit:*.env
|
||||
|
||||
action: integration.use
|
||||
resource: mcp:<server ID>, plugin:<unversioned package or absolute local path>,
|
||||
hosted:<integration ID>, or skill:<skill ID>
|
||||
```
|
||||
|
||||
Provider configuration and provider policy remain separate:
|
||||
@@ -260,6 +264,25 @@ tool.use / shell:git status -> unchanged: the agent's rules decide allow or
|
||||
- A statement `deny` overrides `allow` and `ask`, including saved "Allow always" approvals.
|
||||
- A statement `allow` never grants; it only cancels an earlier, broader statement `deny`.
|
||||
|
||||
## Skill Integration Policy
|
||||
|
||||
Skills use their OpenCode IDs, including a namespace when present. Denied skills are absent from the client catalog and model guidance, and cannot be loaded by the skill tool, a prompt mention, or standalone activation.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"experimental": {
|
||||
"policies": [
|
||||
{ "action": "integration.use", "resource": "skill:*", "effect": "deny" },
|
||||
{ "action": "integration.use", "resource": "skill:team:review", "effect": "allow" },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The protected terminal config policy plugin filters `skill:<id>` through `ctx.skill.transform`, following the provider and MCP catalog pattern. The skill domain does not interpret policy statements. Config and managed policy changes reload the catalog and publish an update after the transformed values are visible. Removing a restriction restores the registered skill without reinstallation. A global integrations allow list also excludes skills unless it explicitly allows their IDs. Skill policy does not remove content already stored in session history or sandbox plugin filesystem access.
|
||||
|
||||
Plugin hooks are governed by the existing plugin integration resource: blocking an external plugin prevents its import or unloads its active generation, including its hooks. There is no separate hook resource; required built-in policy and Console authentication plugins remain protected.
|
||||
|
||||
## Interaction With Provider Configuration
|
||||
|
||||
```jsonc
|
||||
|
||||
Reference in New Issue
Block a user