mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
refactor(core): introduce Permission.Policy algebra for rule composition (#65907)
This commit is contained in:
parent
553c14178e
commit
ca9e8f2ce9
21 changed files with 339 additions and 134 deletions
|
|
@ -11,7 +11,7 @@ import type { SessionMessage } from "../session/message.js"
|
|||
import type { SessionSchema } from "../session/schema.js"
|
||||
import { Tool } from "../tool.js"
|
||||
import { McpTool } from "../tool/mcp.js"
|
||||
import { Wildcard } from "../util/wildcard.js"
|
||||
|
||||
import { type Invocation, matchesAuthor } from "./author.js"
|
||||
import type { AutomationEvent } from "./event.js"
|
||||
|
||||
|
|
@ -102,13 +102,13 @@ export const authorize = Effect.fnUntraced(function* (
|
|||
if (invocation && !matchesAuthor(session, agent.info, invocation))
|
||||
return yield* Effect.fail("Create the automation with the session's current agent")
|
||||
const actions = (yield* resolveCapabilities(scanned)).actions
|
||||
const rules = Permission.merge(agent.info?.permissions ?? [], session.permissions ?? [])
|
||||
const policy = Permission.Policy.fromRules(agent.info?.permissions ?? [], session.permissions ?? [])
|
||||
// A rule scoped to some resources (`vault:*: ask`) must prompt too, not only the catch-all `*`.
|
||||
const request = (item: string) => ({
|
||||
action: item,
|
||||
resources: Array.dedupe([
|
||||
"*",
|
||||
...scopedRules(rules, item).flatMap((rule) => (rule.effect === "ask" ? [rule.resource] : [])),
|
||||
...Permission.Policy.scopedRules(policy, item).flatMap((rule) => (rule.effect === "ask" ? [rule.resource] : [])),
|
||||
]),
|
||||
...(invocation ?? { sessionID: session.id, agent: agent.id }),
|
||||
})
|
||||
|
|
@ -129,11 +129,6 @@ export const authorize = Effect.fnUntraced(function* (
|
|||
)
|
||||
})
|
||||
|
||||
/** Rules for `action` that name specific resources rather than `*`, in order. */
|
||||
function scopedRules(rules: Permission.Ruleset, action: string) {
|
||||
return rules.filter((rule) => rule.resource !== "*" && Wildcard.match(action, rule.action))
|
||||
}
|
||||
|
||||
const bunFileReadMembers = new Set([
|
||||
"name",
|
||||
"type",
|
||||
|
|
@ -203,12 +198,12 @@ export const run = Effect.fnUntraced(
|
|||
if (Result.isFailure(resolved)) return { ok: false as const, error: resolved.failure, invalid: true }
|
||||
|
||||
const actions = ["execute", ...resolved.success.actions]
|
||||
const rules = Permission.merge(agent.info.permissions, session.permissions ?? [])
|
||||
const policy = Permission.Policy.fromRules(agent.info.permissions, session.permissions ?? [])
|
||||
// Unattended rules come after the configured ones and the last match wins, so restate every scoped rule after the
|
||||
// grant: the approval stands in for the catch-all `*` only, and a scoped `ask` still needs a person.
|
||||
const unattended: Permission.Ruleset = actions.flatMap((item) => [
|
||||
{ action: item, resource: "*", effect: "allow" as const },
|
||||
...scopedRules(rules, item),
|
||||
...Permission.Policy.scopedRules(policy, item),
|
||||
])
|
||||
|
||||
// A deny added to config after creation still wins.
|
||||
|
|
@ -231,7 +226,7 @@ export const run = Effect.fnUntraced(
|
|||
code: action.code,
|
||||
tools: scanned.success.tools,
|
||||
bindings: { ...bindings, input: bindings },
|
||||
permissions: rules,
|
||||
policy,
|
||||
limits: CODE_LIMITS,
|
||||
services: yield* CodeModeTool.services,
|
||||
context: {
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ export const authorize = Effect.fnUntraced(function* (
|
|||
program,
|
||||
target,
|
||||
once: true,
|
||||
rules: Effect.succeed(Permission.merge(agent.info?.permissions ?? [], owner.permissions ?? [])),
|
||||
policy: Effect.succeed(Permission.Policy.fromRules(agent.info?.permissions ?? [], owner.permissions ?? [])),
|
||||
}).pipe(Effect.mapError((error) => error.message))
|
||||
// No save patterns: approval applies only to the command stored in this automation.
|
||||
yield* Effect.forEach(
|
||||
|
|
|
|||
|
|
@ -10,10 +10,11 @@ import { Agent } from "./agent.js"
|
|||
import { SessionErrors } from "./session/error.js"
|
||||
import { SessionSchema } from "./session/schema.js"
|
||||
import { SessionStore } from "./session/store.js"
|
||||
import { Wildcard } from "./util/wildcard.js"
|
||||
import { PermissionPolicy } from "./permission/policy.js"
|
||||
import { PermissionSaved } from "./permission/saved.js"
|
||||
import { PluginHooks } from "./plugin/hooks.js"
|
||||
|
||||
export * as Policy from "./permission/policy.js"
|
||||
const PermissionEffect = Permission.Effect
|
||||
export { PermissionEffect as Effect }
|
||||
export { Rule, Ruleset } from "@opencode/schema/permission"
|
||||
|
|
@ -91,38 +92,15 @@ export class NotFoundError extends Schema.TaggedError<NotFoundError>()("Permissi
|
|||
|
||||
export type Error = BlockedError | CorrectedError
|
||||
|
||||
/** Actions whose resources are file paths. */
|
||||
export const pathActions = ["external_directory", "read", "edit"] as const
|
||||
|
||||
/** macOS volumes ignore case by default, so `.OPENCODE/x` opens `.opencode/x`; rules for file paths must match it too. */
|
||||
export function ignoresCase(action: string) {
|
||||
return process.platform === "darwin" && pathActions.some((item) => item === action)
|
||||
}
|
||||
export { ignoresCase, pathActions } from "./permission/policy.js"
|
||||
|
||||
export function evaluate(action: string, resource: string, ...rulesets: Permission.Ruleset[]): Permission.Rule {
|
||||
const ignoreCase = ignoresCase(action)
|
||||
return (
|
||||
rulesets
|
||||
.flat()
|
||||
.findLast(
|
||||
(rule) => Wildcard.match(action, rule.action) && Wildcard.match(resource, rule.resource, ignoreCase),
|
||||
) ?? {
|
||||
action,
|
||||
resource: "*",
|
||||
effect: "ask",
|
||||
}
|
||||
)
|
||||
return PermissionPolicy.evaluate(PermissionPolicy.fromRules(...rulesets), action, resource)
|
||||
}
|
||||
|
||||
/** True when every resource for `action` is denied; trailing narrow denies preserve a blanket deny while any `allow` or `ask` keeps the action reachable. */
|
||||
export function isActionDenied(action: string, ...rulesets: Permission.Ruleset[]): boolean {
|
||||
return rulesets
|
||||
.flat()
|
||||
.filter((rule) => Wildcard.match(action, rule.action))
|
||||
.reduce((denied, rule) => {
|
||||
if (rule.resource === "*") return rule.effect === "deny"
|
||||
return rule.effect === "deny" ? denied : false
|
||||
}, false)
|
||||
return PermissionPolicy.isActionDenied(PermissionPolicy.fromRules(...rulesets), action)
|
||||
}
|
||||
|
||||
export function merge(...rulesets: Permission.Ruleset[]): Permission.Ruleset {
|
||||
|
|
@ -184,13 +162,15 @@ const layer = Layer.effect(
|
|||
}).pipe(Effect.uninterruptible)
|
||||
yield* Effect.addFinalizer(() => close)
|
||||
|
||||
const savedRules = Effect.fnUntraced(function* () {
|
||||
return (yield* saved.list({ projectID: location.project.id })).map(
|
||||
(item): Permission.Rule => ({
|
||||
action: item.action,
|
||||
resource: item.resource,
|
||||
effect: "allow",
|
||||
}),
|
||||
const savedPolicy = Effect.fnUntraced(function* () {
|
||||
return PermissionPolicy.fromRules(
|
||||
(yield* saved.list({ projectID: location.project.id })).map(
|
||||
(item): Permission.Rule => ({
|
||||
action: item.action,
|
||||
resource: item.resource,
|
||||
effect: "allow",
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
|
|
@ -198,17 +178,9 @@ const layer = Layer.effect(
|
|||
const session = yield* sessions.get(sessionID)
|
||||
if (!session) return yield* new SessionErrors.NotFoundError({ sessionID })
|
||||
const agent = yield* agents.resolve(agentID ?? session.agent)
|
||||
return merge(agent?.permissions ?? missingAgentPermissions, session.permissions ?? [])
|
||||
return PermissionPolicy.fromRules(agent?.permissions ?? missingAgentPermissions, session.permissions ?? [])
|
||||
})
|
||||
|
||||
function denied(input: Pick<Request, "action" | "resources">, rules: Permission.Ruleset) {
|
||||
return input.resources.some((resource) => evaluate(input.action, resource, rules).effect === "deny")
|
||||
}
|
||||
|
||||
function relevant(input: AssertInput, rules: Permission.Ruleset) {
|
||||
return rules.filter((rule) => Wildcard.match(input.action, rule.action))
|
||||
}
|
||||
|
||||
const nested: Interface["nested"] = (call, parent) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => void parents.set(call, parent)),
|
||||
|
|
@ -221,11 +193,11 @@ const layer = Layer.effect(
|
|||
}
|
||||
|
||||
const evaluateInput = Effect.fnUntraced(function* (input: AssertInput) {
|
||||
const rules = yield* configured(input.sessionID, input.agent)
|
||||
if (denied(input, rules)) return { effect: "deny" as const, rules }
|
||||
const all = [...rules, ...(yield* savedRules())]
|
||||
const effects = input.resources.map((resource) => evaluate(input.action, resource, all).effect)
|
||||
const effect: Permission.Effect = effects.includes("ask") ? "ask" : "allow"
|
||||
const base = yield* configured(input.sessionID, input.agent)
|
||||
if (PermissionPolicy.evaluateAll(base, input.action, input.resources) === "deny")
|
||||
return { effect: "deny" as const, policy: base }
|
||||
const effective = PermissionPolicy.fallback(base, yield* savedPolicy())
|
||||
const effect = PermissionPolicy.evaluateAll(effective, input.action, input.resources)
|
||||
const event = yield* hooks.trigger("permission", "evaluate", {
|
||||
sessionID: input.sessionID,
|
||||
agent: input.agent,
|
||||
|
|
@ -237,14 +209,14 @@ const layer = Layer.effect(
|
|||
})
|
||||
const unattended = yield* Unattended
|
||||
if (event.effect !== "ask" || unattended === undefined)
|
||||
return { effect: event.effect, message: event.message, rules: all }
|
||||
const settled = [...all, ...unattended]
|
||||
const allowed = input.resources.every((resource) => evaluate(input.action, resource, settled).effect === "allow")
|
||||
if (allowed) return { effect: "allow" as const, rules: all }
|
||||
return { effect: event.effect, message: event.message, policy: effective }
|
||||
const settled = PermissionPolicy.override(effective, unattended)
|
||||
if (PermissionPolicy.evaluateAll(settled, input.action, input.resources) === "allow")
|
||||
return { effect: "allow" as const, policy: effective }
|
||||
return {
|
||||
effect: "deny" as const,
|
||||
message: `Permission ${input.action} needs approval, and nobody is present to give it`,
|
||||
rules: all,
|
||||
policy: effective,
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -300,7 +272,7 @@ const layer = Layer.effect(
|
|||
Effect.gen(function* () {
|
||||
if (result.effect === "deny") {
|
||||
return yield* new BlockedError({
|
||||
rules: relevant(input, result.rules),
|
||||
rules: PermissionPolicy.relevant(result.policy, input.action),
|
||||
permission: input.action,
|
||||
resources: input.resources,
|
||||
reason: result.message,
|
||||
|
|
@ -330,7 +302,7 @@ const layer = Layer.effect(
|
|||
const result = yield* evaluateInput(input)
|
||||
if (result.effect !== "deny") return
|
||||
return yield* new BlockedError({
|
||||
rules: relevant(input, result.rules),
|
||||
rules: PermissionPolicy.relevant(result.policy, input.action),
|
||||
permission: input.action,
|
||||
resources: input.resources,
|
||||
reason: result.message,
|
||||
|
|
|
|||
166
packages/core/src/permission/policy.ts
Normal file
166
packages/core/src/permission/policy.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
export * as PermissionPolicy from "./policy.js"
|
||||
|
||||
import type { Permission } from "@opencode/schema/permission"
|
||||
import { Wildcard } from "../util/wildcard.js"
|
||||
|
||||
/** Actions whose resources are file paths. */
|
||||
export const pathActions = ["external_directory", "read", "edit"] as const
|
||||
|
||||
/** macOS volumes ignore case by default, so `.OPENCODE/x` opens `.opencode/x`; rules for file paths must match it too. */
|
||||
export function ignoresCase(action: string) {
|
||||
return process.platform === "darwin" && pathActions.some((item) => item === action)
|
||||
}
|
||||
|
||||
export interface Deny {
|
||||
readonly action: string
|
||||
readonly resource: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Composable permission policy separating three distinct semantics:
|
||||
* - `override`: ordered last-match-wins layers (defaults -> agent -> session)
|
||||
* - `restrict`: monotone deny-wins restrictions (cannot be undone by `fallback`)
|
||||
* - `fallback`: ask-settling layers (e.g. saved approvals), never overrides `deny` or `allow`
|
||||
*/
|
||||
export type Policy =
|
||||
| { readonly _tag: "rules"; readonly rules: Permission.Ruleset }
|
||||
| { readonly _tag: "override"; readonly base: Policy; readonly next: Permission.Ruleset }
|
||||
| { readonly _tag: "restrict"; readonly base: Policy; readonly denies: ReadonlyArray<Deny> }
|
||||
| { readonly _tag: "fallback"; readonly base: Policy; readonly secondary: Policy }
|
||||
|
||||
export const empty: Policy = { _tag: "rules", rules: [] }
|
||||
|
||||
export function fromRules(...rulesets: Permission.Ruleset[]): Policy {
|
||||
return { _tag: "rules", rules: rulesets.flat() }
|
||||
}
|
||||
|
||||
/** Last-match-wins layer on top of `base`. */
|
||||
export function override(base: Policy, ...rulesets: Permission.Ruleset[]): Policy {
|
||||
const next = rulesets.flat()
|
||||
if (next.length === 0) return base
|
||||
if (base._tag === "rules") return { _tag: "rules", rules: [...base.rules, ...next] }
|
||||
return { _tag: "override", base, next }
|
||||
}
|
||||
|
||||
/** Monotone deny layer: matching `denies` always yield `deny` and cannot be undone by `fallback`. */
|
||||
export function restrict(base: Policy, denies: ReadonlyArray<Deny>): Policy {
|
||||
if (denies.length === 0) return base
|
||||
return { _tag: "restrict", base, denies }
|
||||
}
|
||||
|
||||
/** Settles `ask` results using `secondary`; `deny` and `allow` from `base` are preserved unchanged. */
|
||||
export function fallback(base: Policy, secondary: Policy): Policy {
|
||||
return { _tag: "fallback", base, secondary }
|
||||
}
|
||||
|
||||
function matchLast(rules: Permission.Ruleset, action: string, resource: string): Permission.Rule | undefined {
|
||||
const ignoreCase = ignoresCase(action)
|
||||
return rules.findLast(
|
||||
(rule) => Wildcard.match(action, rule.action) && Wildcard.match(resource, rule.resource, ignoreCase),
|
||||
)
|
||||
}
|
||||
|
||||
function evaluateOption(policy: Policy, action: string, resource: string): Permission.Rule | undefined {
|
||||
switch (policy._tag) {
|
||||
case "rules":
|
||||
return matchLast(policy.rules, action, resource)
|
||||
case "override":
|
||||
return matchLast(policy.next, action, resource) ?? evaluateOption(policy.base, action, resource)
|
||||
case "restrict": {
|
||||
const ignoreCase = ignoresCase(action)
|
||||
const denied = policy.denies.findLast(
|
||||
(rule) => Wildcard.match(action, rule.action) && Wildcard.match(resource, rule.resource, ignoreCase),
|
||||
)
|
||||
if (denied) return { action: denied.action, resource: denied.resource, effect: "deny" }
|
||||
return evaluateOption(policy.base, action, resource)
|
||||
}
|
||||
case "fallback": {
|
||||
const primary = evaluateOption(policy.base, action, resource)
|
||||
if (primary !== undefined && primary.effect !== "ask") return primary
|
||||
return evaluateOption(policy.secondary, action, resource) ?? primary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluate(policy: Policy, action: string, resource: string): Permission.Rule {
|
||||
return evaluateOption(policy, action, resource) ?? { action, resource: "*", effect: "ask" }
|
||||
}
|
||||
|
||||
/** Combines resource evaluations under the effect lattice (`deny > ask > allow`). */
|
||||
export function evaluateAll(policy: Policy, action: string, resources: ReadonlyArray<string>): Permission.Effect {
|
||||
const effects = resources.map((resource) => evaluate(policy, action, resource).effect)
|
||||
if (effects.includes("deny")) return "deny"
|
||||
if (effects.includes("ask")) return "ask"
|
||||
return "allow"
|
||||
}
|
||||
|
||||
function reduceActionDenied(initial: boolean, rules: Permission.Ruleset, action: string): boolean {
|
||||
return rules.reduce((denied, rule) => {
|
||||
if (!Wildcard.match(action, rule.action)) return denied
|
||||
if (rule.resource === "*") return rule.effect === "deny"
|
||||
return rule.effect === "deny" ? denied : false
|
||||
}, initial)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sound whole-action denial check: true only when every resource for `action` is guaranteed `deny`.
|
||||
* Narrow denies never undo a blanket deny and never wholly deny an otherwise reachable action.
|
||||
*/
|
||||
export function isActionDenied(policy: Policy, action: string): boolean {
|
||||
switch (policy._tag) {
|
||||
case "rules":
|
||||
return reduceActionDenied(false, policy.rules, action)
|
||||
case "override":
|
||||
return reduceActionDenied(isActionDenied(policy.base, action), policy.next, action)
|
||||
case "restrict":
|
||||
return (
|
||||
policy.denies.some((rule) => Wildcard.match(action, rule.action) && rule.resource === "*") ||
|
||||
isActionDenied(policy.base, action)
|
||||
)
|
||||
case "fallback":
|
||||
return isActionDenied(policy.base, action)
|
||||
}
|
||||
}
|
||||
|
||||
/** True when any rule in `policy` can deny `action`. */
|
||||
export function hasDeny(policy: Policy, action: string): boolean {
|
||||
switch (policy._tag) {
|
||||
case "rules":
|
||||
return policy.rules.some((rule) => rule.effect === "deny" && Wildcard.match(action, rule.action))
|
||||
case "override":
|
||||
return (
|
||||
policy.next.some((rule) => rule.effect === "deny" && Wildcard.match(action, rule.action)) ||
|
||||
hasDeny(policy.base, action)
|
||||
)
|
||||
case "restrict":
|
||||
return policy.denies.some((rule) => Wildcard.match(action, rule.action)) || hasDeny(policy.base, action)
|
||||
case "fallback":
|
||||
return hasDeny(policy.base, action) || hasDeny(policy.secondary, action)
|
||||
}
|
||||
}
|
||||
|
||||
/** All rules matching `action` in evaluation order (for diagnostics and `BlockedError`). */
|
||||
export function relevant(policy: Policy, action: string): Permission.Ruleset {
|
||||
switch (policy._tag) {
|
||||
case "rules":
|
||||
return policy.rules.filter((rule) => Wildcard.match(action, rule.action))
|
||||
case "override":
|
||||
return [...relevant(policy.base, action), ...policy.next.filter((rule) => Wildcard.match(action, rule.action))]
|
||||
case "restrict":
|
||||
return [
|
||||
...relevant(policy.base, action),
|
||||
...policy.denies.flatMap((rule) =>
|
||||
Wildcard.match(action, rule.action)
|
||||
? [{ action: rule.action, resource: rule.resource, effect: "deny" as const }]
|
||||
: [],
|
||||
),
|
||||
]
|
||||
case "fallback":
|
||||
return [...relevant(policy.base, action), ...relevant(policy.secondary, action)]
|
||||
}
|
||||
}
|
||||
|
||||
/** Resource-scoped rules (`resource !== "*"`) matching `action`, in evaluation order. */
|
||||
export function scopedRules(policy: Policy, action: string): Permission.Ruleset {
|
||||
return relevant(policy, action).filter((rule) => rule.resource !== "*")
|
||||
}
|
||||
|
|
@ -164,7 +164,7 @@ const layer = Layer.effect(
|
|||
const agent = yield* agents.select(session.agent)
|
||||
if (!agent.info) return yield* new AgentNotFoundError({ sessionID: session.id, agent: session.agent ?? agent.id })
|
||||
// Session permissions narrow discovery the same way they narrow the tool snapshot.
|
||||
const permissions = Permission.merge(agent.info.permissions, session.permissions ?? [])
|
||||
const policy = Permission.Policy.fromRules(agent.info.permissions, session.permissions ?? [])
|
||||
const [selected, hasWebSearch, fullCodeMode, opencodeApi] = yield* Effect.all(
|
||||
[
|
||||
models.select(session, model.available).pipe(Effect.orElseSucceed(() => undefined)),
|
||||
|
|
@ -176,7 +176,7 @@ const layer = Layer.effect(
|
|||
)
|
||||
const fallbackRef = session.model ?? agent.info.model
|
||||
const policyModel = selected?.info ?? (fallbackRef && Model.Info.default(fallbackRef.providerID, fallbackRef.id))
|
||||
const tools = yield* registry.snapshot(permissions, {
|
||||
const tools = yield* registry.snapshot(policy, {
|
||||
services,
|
||||
api: Context.make(CodeModeApi.Service, opencodeApi ? api : CodeModeApi.disabled).pipe(
|
||||
Context.add(Location.Service, location),
|
||||
|
|
@ -185,7 +185,7 @@ const layer = Layer.effect(
|
|||
tools: modelTools({
|
||||
model: policyModel,
|
||||
websearch: hasWebSearch,
|
||||
fullCodeMode: fullCodeMode && Tool.codeModeAvailable(permissions),
|
||||
fullCodeMode: fullCodeMode && Tool.codeModeAvailable(policy),
|
||||
}),
|
||||
})
|
||||
const cwd = yield* sessionCwd.current(session.id)
|
||||
|
|
@ -194,7 +194,7 @@ const layer = Layer.effect(
|
|||
builtins: builtins.load({ cwd: cwd && SessionCwd.describe(cwd, environment.id) }),
|
||||
cwd: cwdInstructions.load(cwd, session.id),
|
||||
discovery: discovery.load(),
|
||||
skills: skillInstructions.load(permissions),
|
||||
skills: skillInstructions.load(policy),
|
||||
references: referenceInstructions.load(),
|
||||
mcp: mcpInstructions.load(tools),
|
||||
machines: machineInstructions.load(),
|
||||
|
|
|
|||
|
|
@ -2,8 +2,7 @@ export * as ShellPermissions from "./permissions.js"
|
|||
|
||||
import { Effect, Result, Schema } from "effect"
|
||||
import { FileAccess } from "../file-access.js"
|
||||
import type { Permission } from "../permission.js"
|
||||
import { Wildcard } from "../util/wildcard.js"
|
||||
import { PermissionPolicy } from "../permission/policy.js"
|
||||
import { ShellParse } from "./parse.js"
|
||||
|
||||
export class UnverifiableError extends Schema.TaggedError<UnverifiableError>()("ShellPermissions.UnverifiableError", {
|
||||
|
|
@ -21,8 +20,8 @@ export const requests = Effect.fnUntraced(function* <E>(
|
|||
readonly program: string
|
||||
readonly target: FileAccess.Target
|
||||
readonly once?: boolean
|
||||
/** The agent's and session's rules, read only for a command the scanner can't analyze. */
|
||||
readonly rules: Effect.Effect<Permission.Ruleset, E>
|
||||
/** The agent's and session's policy, read only for a command the scanner can't analyze. */
|
||||
readonly policy: Effect.Effect<PermissionPolicy.Policy, E>
|
||||
},
|
||||
) {
|
||||
const scanned = yield* Effect.result(
|
||||
|
|
@ -32,7 +31,7 @@ export const requests = Effect.fnUntraced(function* <E>(
|
|||
)
|
||||
if (Result.isFailure(scanned)) {
|
||||
// A deny pattern can't be matched against subcommands the scanner couldn't find.
|
||||
if ((yield* input.rules).some((rule) => rule.effect === "deny" && Wildcard.match("shell", rule.action)))
|
||||
if (PermissionPolicy.hasDeny(yield* input.policy, "shell"))
|
||||
return yield* new UnverifiableError({ reason: scanned.failure.reason })
|
||||
// An unanalyzed command may reach any directory, so only rules allowing every directory settle it, and approval
|
||||
// is never saved as a pattern.
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import path from "path"
|
|||
import { Context, Effect, Layer, Types } from "effect"
|
||||
import { Skill } from "@opencode/schema/skill"
|
||||
import { Bus } from "./bus.js"
|
||||
import { Permission } from "./permission.js"
|
||||
import { PermissionPolicy } from "./permission/policy.js"
|
||||
import { State } from "./state.js"
|
||||
|
||||
export const DirectorySource = Skill.DirectorySource
|
||||
|
|
@ -30,8 +30,8 @@ export type Name = Skill.Name
|
|||
|
||||
export { Event } from "@opencode/schema/skill"
|
||||
|
||||
export const available = (skills: ReadonlyArray<Info>, permissions: Permission.Ruleset) =>
|
||||
skills.filter((skill) => Permission.evaluate("skill", skill.id, permissions).effect !== "deny")
|
||||
export const available = (skills: ReadonlyArray<Info>, policy: PermissionPolicy.Policy) =>
|
||||
skills.filter((skill) => PermissionPolicy.evaluate(policy, "skill", skill.id).effect !== "deny")
|
||||
|
||||
export const uri = (id: string, file?: string) => (file ? `skill://${id}/${file}` : `skill://${id}`)
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ export * as SkillInstructions from "./instructions.js"
|
|||
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { Context, Effect, Layer, Schema } from "effect"
|
||||
import { Permission } from "../permission.js"
|
||||
import type { PermissionPolicy } from "../permission/policy.js"
|
||||
import { Skill } from "../skill.js"
|
||||
import { Instructions } from "../instructions/index.js"
|
||||
|
||||
|
|
@ -46,8 +46,8 @@ const update = Instructions.listUpdate<Summary>({
|
|||
})
|
||||
|
||||
export interface Interface {
|
||||
/** Lists skills the given ruleset does not deny; callers pass the merged agent and Session permissions. */
|
||||
readonly load: (permissions: Permission.Ruleset) => Effect.Effect<Instructions.List>
|
||||
/** Lists skills the given policy does not deny; callers pass the session's effective permission policy. */
|
||||
readonly load: (policy: PermissionPolicy.Policy) => Effect.Effect<Instructions.List>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/SkillInstructions") {}
|
||||
|
|
@ -58,8 +58,8 @@ const layer = Layer.effect(
|
|||
const skills = yield* Skill.Service
|
||||
|
||||
return Service.of({
|
||||
load: Effect.fn("SkillInstructions.load")(function* (permissions) {
|
||||
const available = Skill.available(yield* skills.list(), permissions)
|
||||
load: Effect.fn("SkillInstructions.load")(function* (policy) {
|
||||
const available = Skill.available(yield* skills.list(), policy)
|
||||
.flatMap((skill) =>
|
||||
skill.description === undefined || skill.autoinvoke === false
|
||||
? []
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { CodeModeTool } from "./codemode/tool.js"
|
|||
import { Flag } from "./flag.js"
|
||||
import { Image } from "./image.js"
|
||||
import { Permission } from "./permission.js"
|
||||
import { PermissionPolicy } from "./permission/policy.js"
|
||||
import { PluginHooks } from "./plugin/hooks.js"
|
||||
import { SessionMessage } from "./session/message.js"
|
||||
import { SessionSchema } from "./session/schema.js"
|
||||
|
|
@ -78,7 +79,7 @@ export interface SnapshotOptions {
|
|||
export interface Interface extends State.Transformable<Editor> {
|
||||
readonly list: () => Effect.Effect<ReadonlyArray<RegisteredTool>>
|
||||
readonly codeModeTools: (paths: ReadonlyArray<string>) => Effect.Effect<ReadonlyMap<string, RegisteredTool>>
|
||||
readonly snapshot: (permissions?: Permission.Ruleset, options?: SnapshotOptions) => Effect.Effect<Snapshot>
|
||||
readonly snapshot: (policy?: PermissionPolicy.Policy, options?: SnapshotOptions) => Effect.Effect<Snapshot>
|
||||
/**
|
||||
* Runs a Code Mode program with no model step over only the Code Mode tools named in `tools` (still subject to
|
||||
* whole-tool permission filtering and each tool's own executor policy).
|
||||
|
|
@ -90,7 +91,7 @@ export interface CheckInput {
|
|||
readonly code: string
|
||||
readonly tools: ReadonlyArray<string>
|
||||
readonly bindings: Readonly<Record<string, CodeMode.DataValue>>
|
||||
readonly permissions: Permission.Ruleset
|
||||
readonly policy: PermissionPolicy.Policy
|
||||
readonly limits: CodeMode.ExecutionLimits
|
||||
readonly services?: Context.Context<CodeModeTool.Services>
|
||||
readonly context: Omit<Tool.Context, "id">
|
||||
|
|
@ -308,9 +309,9 @@ const layer = Layer.effect(
|
|||
codeModeTools: (paths) => Effect.sync(() => new Map(codeModeTools(state.get().tools, paths))),
|
||||
snapshot: Effect.fn("Tool.snapshot")((permissions, options) =>
|
||||
Effect.gen(function* () {
|
||||
const rules = permissions ?? []
|
||||
const policy = permissions ?? PermissionPolicy.empty
|
||||
// Without Code Mode its tools would be unreachable, so expose them as direct tools instead.
|
||||
const codeModeEnabled = codeModeAvailable(rules)
|
||||
const codeModeEnabled = codeModeAvailable(policy)
|
||||
const full = codeModeEnabled && options?.services !== undefined && (yield* flags.enabled("full_codemode"))
|
||||
const data = state.get()
|
||||
if (catalogData !== data) {
|
||||
|
|
@ -323,7 +324,7 @@ const layer = Layer.effect(
|
|||
const codemodeEntries: Array<[string, Tool.Info]> = []
|
||||
for (const [name, tool] of data.tools) {
|
||||
if (hidden?.has(name)) continue
|
||||
if (Permission.isActionDenied(tool.options?.permission ?? name, rules)) continue
|
||||
if (PermissionPolicy.isActionDenied(policy, tool.options?.permission ?? name)) continue
|
||||
if (codeModeEnabled && defaultCodeMode(tool) && !keepDirect?.has(name)) {
|
||||
codemodeEntries.push([name, tool])
|
||||
continue
|
||||
|
|
@ -422,7 +423,7 @@ const layer = Layer.effect(
|
|||
}),
|
||||
),
|
||||
check: Effect.fn("Tool.check")(function* (input) {
|
||||
if (Permission.isActionDenied("execute", input.permissions)) {
|
||||
if (PermissionPolicy.isActionDenied(input.policy, "execute")) {
|
||||
return {
|
||||
ok: false,
|
||||
error: { kind: "ExecutionFailure", message: "Code Mode is disabled for this agent" },
|
||||
|
|
@ -432,7 +433,7 @@ const layer = Layer.effect(
|
|||
const data = state.get()
|
||||
const tools = new Map(
|
||||
codeModeTools(data.tools, input.tools)
|
||||
.filter(([, tool]) => !Permission.isActionDenied(tool.options?.permission ?? tool.id, input.permissions))
|
||||
.filter(([, tool]) => !PermissionPolicy.isActionDenied(input.policy, tool.options?.permission ?? tool.id))
|
||||
.map(([, tool]) => [tool.id, tool] as const),
|
||||
)
|
||||
const callSeq = yield* Ref.make(0)
|
||||
|
|
@ -496,8 +497,9 @@ function* codeModeTools(registered: Data["tools"], paths: ReadonlyArray<string>)
|
|||
}
|
||||
}
|
||||
|
||||
/** Whether the rules leave Code Mode's `execute` reachable, as `snapshot` decides it. */
|
||||
export const codeModeAvailable = (rules: Permission.Ruleset) => !Permission.isActionDenied("execute", rules)
|
||||
/** Whether the policy leaves Code Mode's `execute` reachable, as `snapshot` decides it. */
|
||||
export const codeModeAvailable = (policy: PermissionPolicy.Policy) =>
|
||||
!PermissionPolicy.isActionDenied(policy, "execute")
|
||||
|
||||
const CATALOG_CACHE_LIMIT = 5
|
||||
|
||||
|
|
|
|||
|
|
@ -345,10 +345,10 @@ export const Plugin = {
|
|||
command: invocation.command,
|
||||
program: invocation.shell,
|
||||
target,
|
||||
rules: Effect.gen(function* () {
|
||||
policy: Effect.gen(function* () {
|
||||
const session = yield* sessions.get(context.sessionID)
|
||||
const agent = yield* agents.resolve(context.agent)
|
||||
return Permission.merge(agent?.permissions ?? [], session.permissions ?? [])
|
||||
return Permission.Policy.fromRules(agent?.permissions ?? [], session.permissions ?? [])
|
||||
}),
|
||||
})
|
||||
yield* Effect.forEach(
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { CodeModeCatalog } from "@opencode/core/codemode/catalog"
|
|||
import { Config } from "@opencode/core/config"
|
||||
import { Image } from "@opencode/core/image"
|
||||
import { Permission } from "@opencode/core/permission"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { toSessionError } from "@opencode/core/session/to-session-error"
|
||||
import type { SessionError } from "@opencode/schema/session-error"
|
||||
|
|
@ -29,7 +30,9 @@ export const toolNodeReplacements = (
|
|||
]
|
||||
|
||||
export const toolDefinitions = (registry: Tool.Interface, permissions?: Permission.Ruleset) =>
|
||||
registry.snapshot(permissions).pipe(Effect.map((toolSet) => toolSet.definitions))
|
||||
registry
|
||||
.snapshot(permissions ? PermissionPolicy.fromRules(permissions) : undefined)
|
||||
.pipe(Effect.map((toolSet) => toolSet.definitions))
|
||||
|
||||
export const codeModeListings = (catalog: CodeModeCatalog.Inventory) =>
|
||||
CodeModeCatalog.summarize(catalog, { budget: Infinity }).namespaces.flatMap((namespace) => namespace.entries)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
|||
import { Location } from "@opencode/core/location"
|
||||
import { Mcp } from "@opencode/core/mcp/index"
|
||||
import { McpInstructions } from "@opencode/core/mcp/instructions"
|
||||
import { Permission } from "@opencode/core/permission"
|
||||
import type { Permission } from "@opencode/core/permission"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { McpTool } from "@opencode/core/tool/mcp"
|
||||
|
|
@ -39,7 +40,7 @@ const load = (permissions: Permission.Ruleset = []) =>
|
|||
const registry = yield* Tool.Service
|
||||
const service = yield* McpInstructions.Service
|
||||
yield* mcpTools.flush
|
||||
return yield* service.load(yield* registry.snapshot(permissions))
|
||||
return yield* service.load(yield* registry.snapshot(PermissionPolicy.fromRules(permissions)))
|
||||
})
|
||||
|
||||
describe("McpInstructions", () => {
|
||||
|
|
|
|||
|
|
@ -147,6 +147,42 @@ describe("Permission.isActionDenied", () => {
|
|||
expect(Permission.isActionDenied(item.action, item.rules)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
test("composes override, restrict, and fallback with distinct precedence laws", () => {
|
||||
const base = Permission.Policy.fromRules([
|
||||
rule("read", "*", "ask"),
|
||||
rule("read", ".env", "deny"),
|
||||
rule("read", "README.md", "allow"),
|
||||
])
|
||||
const withSaved = Permission.Policy.fallback(base, Permission.Policy.fromRules([rule("read", "*", "allow")]))
|
||||
|
||||
// fallback settles ask, never overrides deny or allow
|
||||
expect(Permission.Policy.evaluate(withSaved, "read", "src/index.ts").effect).toBe("allow")
|
||||
expect(Permission.Policy.evaluate(withSaved, "read", ".env").effect).toBe("deny")
|
||||
expect(Permission.Policy.evaluate(withSaved, "read", "README.md").effect).toBe("allow")
|
||||
|
||||
// evaluateAll follows the deny > ask > allow lattice
|
||||
expect(Permission.Policy.evaluateAll(base, "read", ["README.md", "src/index.ts"])).toBe("ask")
|
||||
expect(Permission.Policy.evaluateAll(base, "read", ["README.md", ".env"])).toBe("deny")
|
||||
expect(Permission.Policy.evaluateAll(withSaved, "read", ["README.md", "src/index.ts"])).toBe("allow")
|
||||
|
||||
// restrict is monotone: cannot be undone by fallback, and narrow restricts never unmask a blanket deny
|
||||
const restricted = Permission.Policy.fallback(
|
||||
Permission.Policy.restrict(Permission.Policy.fromRules([rule("skill", "*", "allow")]), [
|
||||
{ action: "skill", resource: "browser" },
|
||||
]),
|
||||
Permission.Policy.fromRules([rule("skill", "*", "allow")]),
|
||||
)
|
||||
expect(Permission.Policy.evaluate(restricted, "skill", "browser").effect).toBe("deny")
|
||||
expect(Permission.Policy.evaluate(restricted, "skill", "other").effect).toBe("allow")
|
||||
expect(Permission.Policy.isActionDenied(restricted, "skill")).toBe(false)
|
||||
expect(Permission.Policy.hasDeny(restricted, "skill")).toBe(true)
|
||||
|
||||
const blanketRestricted = Permission.Policy.restrict(Permission.Policy.fromRules([rule("skill", "*", "deny")]), [
|
||||
{ action: "skill", resource: "browser" },
|
||||
])
|
||||
expect(Permission.Policy.isActionDenied(blanketRestricted, "skill")).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("Permission", () => {
|
||||
|
|
|
|||
|
|
@ -409,10 +409,9 @@ const layer = Layer.unwrap(
|
|||
load: () => Effect.succeed(Instructions.empty),
|
||||
})
|
||||
const skillInstructions = Layer.mock(SkillInstructions.Service, {
|
||||
load: (permissions) => {
|
||||
load: (policy) => {
|
||||
// `setup` tags each agent's ruleset with a `skill` rule naming that agent.
|
||||
const baseline = permissions
|
||||
.filter((rule) => rule.action === "skill")
|
||||
const baseline = Permission.Policy.relevant(policy, "skill")
|
||||
.map((rule) => state.skillBaselines.get(Agent.ID.make(rule.resource)))
|
||||
.findLast((text) => text !== undefined)
|
||||
return Effect.succeed(
|
||||
|
|
@ -2097,9 +2096,7 @@ describe("SessionRunnerLLM", () => {
|
|||
expect(userTexts(last)).toEqual(["First", "Fourth"])
|
||||
expect(last.system.map((part) => part.text).join("\n")).not.toContain("Entered mode")
|
||||
// Clients still see every message; only the model context hides the stale update.
|
||||
expect((yield* s.messages).filter((message) => message.type === "system")).toMatchObject([
|
||||
{ text: "Entered mode" },
|
||||
])
|
||||
expect((yield* s.messages).filter((message) => message.type === "system")).toMatchObject([{ text: "Entered mode" }])
|
||||
})
|
||||
|
||||
scenario("uses the selected model family prompt when the agent does not override it", function* (s) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import { Deferred, Effect, Fiber, Layer, Stream } from "effect"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
|
|
@ -58,7 +59,7 @@ describe("Skill", () => {
|
|||
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))
|
||||
const guidance = yield* instructions.load(PermissionPolicy.empty).pipe(Effect.flatMap(readInitial))
|
||||
expect(guidance.text).toContain("<id>team:review</id>")
|
||||
expect(guidance.text).not.toContain("deploy")
|
||||
|
||||
|
|
@ -218,7 +219,7 @@ describe("Skill", () => {
|
|||
}),
|
||||
)
|
||||
const agent = yield* agents.get(Agent.ID.make("reviewer"))
|
||||
expect(Skill.available([info("deploy", "Deploy")], agent!.permissions)).toEqual([])
|
||||
expect(Skill.available([info("deploy", "Deploy")], PermissionPolicy.fromRules(agent!.permissions))).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { describe, expect } from "bun:test"
|
|||
import { Effect, Layer } from "effect"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { SkillInstructions } from "@opencode/core/skill/instructions"
|
||||
|
|
@ -53,7 +54,9 @@ describe("SkillInstructions", () => {
|
|||
let skills = [hidden, denied, manual, effect]
|
||||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
const initialized = yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))
|
||||
const initialized = yield* instructions
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap(readInitial))
|
||||
|
||||
expect(initialized.text).toBe(
|
||||
[
|
||||
|
|
@ -74,7 +77,7 @@ describe("SkillInstructions", () => {
|
|||
skills = []
|
||||
expect(
|
||||
yield* instructions
|
||||
.load(agent.permissions)
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap((context) => readUpdate(context, initialized))),
|
||||
).toMatchObject({ text: "Skill guidance is no longer available. Do not use any previously listed skill." })
|
||||
}).pipe(Effect.provide(layer(() => skills)))
|
||||
|
|
@ -92,11 +95,13 @@ describe("SkillInstructions", () => {
|
|||
let skills = [effect]
|
||||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
const initialized = yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))
|
||||
const initialized = yield* instructions
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap(readInitial))
|
||||
|
||||
skills = [effect, debugging]
|
||||
const added = yield* instructions
|
||||
.load(agent.permissions)
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap((context) => readUpdate(context, initialized)))
|
||||
expect(added.text).toBe(
|
||||
[
|
||||
|
|
@ -111,7 +116,7 @@ describe("SkillInstructions", () => {
|
|||
|
||||
skills = [debugging]
|
||||
const removed = yield* instructions
|
||||
.load(agent.permissions)
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap((context) => readUpdate(context, added)))
|
||||
expect(removed.text).toBe("The following skill IDs are no longer available and must not be used: effect.")
|
||||
}).pipe(Effect.provide(layer(() => skills)))
|
||||
|
|
@ -122,11 +127,13 @@ describe("SkillInstructions", () => {
|
|||
let skills = [effect]
|
||||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
const initialized = yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))
|
||||
const initialized = yield* instructions
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap(readInitial))
|
||||
|
||||
skills = [Skill.Info.make({ ...effect, description: "Build applications with Effect v4" })]
|
||||
const changed = yield* instructions
|
||||
.load(agent.permissions)
|
||||
.load(PermissionPolicy.fromRules(agent.permissions))
|
||||
.pipe(Effect.flatMap((context) => readUpdate(context, initialized)))
|
||||
expect(changed.text).toBe(
|
||||
[
|
||||
|
|
@ -148,7 +155,10 @@ describe("SkillInstructions", () => {
|
|||
})
|
||||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
expect((yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))).text).toBe("")
|
||||
expect(
|
||||
(yield* instructions.load(PermissionPolicy.fromRules(agent.permissions)).pipe(Effect.flatMap(readInitial)))
|
||||
.text,
|
||||
).toBe("")
|
||||
}).pipe(Effect.provide(layer(() => [effect])))
|
||||
})
|
||||
|
||||
|
|
@ -162,7 +172,10 @@ describe("SkillInstructions", () => {
|
|||
})
|
||||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
expect((yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))).text).toBe("")
|
||||
expect(
|
||||
(yield* instructions.load(PermissionPolicy.fromRules(agent.permissions)).pipe(Effect.flatMap(readInitial)))
|
||||
.text,
|
||||
).toBe("")
|
||||
}).pipe(Effect.provide(layer(() => [effect])))
|
||||
})
|
||||
|
||||
|
|
@ -177,7 +190,8 @@ describe("SkillInstructions", () => {
|
|||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
expect(
|
||||
(yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))).text,
|
||||
(yield* instructions.load(PermissionPolicy.fromRules(agent.permissions)).pipe(Effect.flatMap(readInitial)))
|
||||
.text,
|
||||
).toContain("<name>Effect</name>")
|
||||
}).pipe(Effect.provide(layer(() => [effect])))
|
||||
})
|
||||
|
|
@ -193,7 +207,10 @@ describe("SkillInstructions", () => {
|
|||
})
|
||||
return Effect.gen(function* () {
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
expect((yield* instructions.load(agent.permissions).pipe(Effect.flatMap(readInitial))).text).toBe("")
|
||||
expect(
|
||||
(yield* instructions.load(PermissionPolicy.fromRules(agent.permissions)).pipe(Effect.flatMap(readInitial)))
|
||||
.text,
|
||||
).toBe("")
|
||||
}).pipe(Effect.provide(layer(() => [effect])))
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { Agent } from "@opencode/core/agent"
|
|||
import { Automation } from "@opencode/core/automation"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { Project } from "@opencode/core/project"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
|
|
@ -135,7 +136,7 @@ const run = (registry: Tool.Interface, name: string, input: unknown, session = s
|
|||
|
||||
/** Calls a tool directly, as a model does when Code Mode is denied, and returns the text it reads. */
|
||||
const direct = (registry: Tool.Interface, name: string, input: unknown) =>
|
||||
registry.snapshot([{ action: "execute", resource: "*", effect: "deny" }]).pipe(
|
||||
registry.snapshot(PermissionPolicy.fromRules([{ action: "execute", resource: "*", effect: "deny" }])).pipe(
|
||||
Effect.flatMap((tools) =>
|
||||
tools.execute({
|
||||
sessionID,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
|||
import { Mcp } from "@opencode/core/mcp/index"
|
||||
import { McpClient } from "@opencode/core/mcp/client"
|
||||
import type { Permission } from "@opencode/core/permission"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { McpEventTools } from "@opencode/core/tool/plugin/mcp-events"
|
||||
|
|
@ -43,7 +44,7 @@ const setup = Effect.fnUntraced(function* () {
|
|||
)
|
||||
const registry = yield* Tool.Service
|
||||
const list = (input: Record<string, unknown>) =>
|
||||
registry.snapshot([{ action: "execute", resource: "*", effect: "deny" }]).pipe(
|
||||
registry.snapshot(PermissionPolicy.fromRules([{ action: "execute", resource: "*", effect: "deny" }])).pipe(
|
||||
Effect.flatMap((tools) =>
|
||||
tools.execute({
|
||||
sessionID: Session.ID.make("ses_mcp_events"),
|
||||
|
|
|
|||
|
|
@ -660,7 +660,9 @@ describe("Tool", () => {
|
|||
(yield* snapshot.execute({ ...call("acme.tools.echo"), definitions: withoutExecute }).pipe(Effect.flip))
|
||||
.message,
|
||||
).toContain('No tool named "acme.tools.echo"')
|
||||
const denied = yield* service.snapshot([{ action: "acme_tools_echo", resource: "*", effect: "deny" }])
|
||||
const denied = yield* service.snapshot(
|
||||
Permission.Policy.fromRules([{ action: "acme_tools_echo", resource: "*", effect: "deny" }]),
|
||||
)
|
||||
expect((yield* denied.execute(call("acme.tools.echo")).pipe(Effect.flip)).message).toContain(
|
||||
'No tool named "acme.tools.echo"',
|
||||
)
|
||||
|
|
@ -789,7 +791,9 @@ describe("Tool", () => {
|
|||
expect(available.definitions.map((tool) => tool.name)).toEqual(["execute"])
|
||||
expect(available.codeModeCatalog?.tools).toEqual([])
|
||||
|
||||
const denied = yield* service.snapshot([{ action: "execute", resource: "*", effect: "deny" }])
|
||||
const denied = yield* service.snapshot(
|
||||
Permission.Policy.fromRules([{ action: "execute", resource: "*", effect: "deny" }]),
|
||||
)
|
||||
expect(denied.definitions).toEqual([])
|
||||
expect(denied.codeModeCatalog).toBeUndefined()
|
||||
}),
|
||||
|
|
@ -907,7 +911,7 @@ describe("Tool", () => {
|
|||
code: 'return await tools.shell({ command: "build", background: true })',
|
||||
tools: ["shell"],
|
||||
bindings: {},
|
||||
permissions: [],
|
||||
policy: Permission.Policy.empty,
|
||||
limits: {},
|
||||
context: { sessionID, ...identity, progress: () => Effect.void },
|
||||
}),
|
||||
|
|
@ -917,7 +921,7 @@ describe("Tool", () => {
|
|||
code: 'return await tools.glob({ pattern: "*" })',
|
||||
tools: ["glob"],
|
||||
bindings: {},
|
||||
permissions: [],
|
||||
policy: Permission.Policy.empty,
|
||||
limits: {},
|
||||
context: { sessionID, ...identity, progress: () => Effect.void },
|
||||
}),
|
||||
|
|
@ -944,9 +948,12 @@ describe("Tool", () => {
|
|||
).toBe("ls:true:false")
|
||||
|
||||
// When execute is denied, Code Mode tools fall back to their direct form while hidden tools stay hidden.
|
||||
const denied = yield* service.snapshot([{ action: "execute", resource: "*", effect: "deny" }], {
|
||||
tools: { hidden: new Set(["glob"]) },
|
||||
})
|
||||
const denied = yield* service.snapshot(
|
||||
Permission.Policy.fromRules([{ action: "execute", resource: "*", effect: "deny" }]),
|
||||
{
|
||||
tools: { hidden: new Set(["glob"]) },
|
||||
},
|
||||
)
|
||||
expect(denied.codeModeCatalog).toBeUndefined()
|
||||
expect(denied.definitions.map((tool) => tool.name)).toEqual([
|
||||
"legacy_pin",
|
||||
|
|
@ -999,7 +1006,7 @@ describe("Tool", () => {
|
|||
t5: make(),
|
||||
t6: make(),
|
||||
})
|
||||
const deny = (action: string): Permission.Ruleset => [{ action, resource: "*", effect: "deny" }]
|
||||
const deny = (action: string) => Permission.Policy.fromRules([{ action, resource: "*", effect: "deny" }])
|
||||
|
||||
const s1 = yield* service.snapshot(deny("t1"))
|
||||
const s2 = yield* service.snapshot(deny("t2"))
|
||||
|
|
@ -1037,14 +1044,16 @@ describe("Tool", () => {
|
|||
const service = yield* Tool.Service
|
||||
yield* transform(service, { lookup: make() }, { namespace: "mcp" })
|
||||
yield* transform(service, { bash: make() }, { codemode: false })
|
||||
const denyExecute: Permission.Ruleset = [{ action: "execute", resource: "*", effect: "deny" }]
|
||||
const denyExecute = Permission.Policy.fromRules([{ action: "execute", resource: "*", effect: "deny" }])
|
||||
|
||||
const snapshot = yield* service.snapshot(denyExecute)
|
||||
expect(snapshot.definitions.map((tool) => tool.name)).toEqual(["bash", "mcp_lookup"])
|
||||
expect(snapshot.codeModeCatalog).toBeUndefined()
|
||||
expect((yield* snapshot.execute(call("mcp_lookup"))).output).toEqual({ text: "mcp_lookup" })
|
||||
|
||||
const hidden = yield* service.snapshot([...denyExecute, { action: "mcp_lookup", resource: "*", effect: "deny" }])
|
||||
const hidden = yield* service.snapshot(
|
||||
Permission.Policy.override(denyExecute, [{ action: "mcp_lookup", resource: "*", effect: "deny" }]),
|
||||
)
|
||||
expect(hidden.definitions.map((tool) => tool.name)).toEqual(["bash"])
|
||||
expect(yield* hidden.execute(call("mcp_lookup")).pipe(Effect.flip)).toBeInstanceOf(Tool.Error)
|
||||
}),
|
||||
|
|
@ -1054,14 +1063,16 @@ describe("Tool", () => {
|
|||
Effect.gen(function* () {
|
||||
const service = yield* Tool.Service
|
||||
yield* transform(service, { move: make(), rename: make() }, { namespace: "opencode.session" })
|
||||
const deny: Permission.Ruleset = [{ action: "opencode_session_move", resource: "*", effect: "deny" }]
|
||||
const deny = Permission.Policy.fromRules([{ action: "opencode_session_move", resource: "*", effect: "deny" }])
|
||||
|
||||
const codeMode = yield* service.snapshot(deny)
|
||||
const paths = codeModeListings(codeMode.codeModeCatalog!).map((entry) => entry.path)
|
||||
expect(paths).toContain("opencode.session.rename")
|
||||
expect(paths).not.toContain("opencode.session.move")
|
||||
|
||||
const direct = yield* service.snapshot([...deny, { action: "execute", resource: "*", effect: "deny" }])
|
||||
const direct = yield* service.snapshot(
|
||||
Permission.Policy.override(deny, [{ action: "execute", resource: "*", effect: "deny" }]),
|
||||
)
|
||||
expect(direct.definitions.map((tool) => tool.name)).toEqual(["opencode_session_rename"])
|
||||
}),
|
||||
)
|
||||
|
|
@ -1332,7 +1343,7 @@ describe("Tool", () => {
|
|||
code: 'return await tools.echo({ text: "constant" })',
|
||||
tools,
|
||||
bindings: {},
|
||||
permissions: [],
|
||||
policy: Permission.Policy.empty,
|
||||
limits: {},
|
||||
context: { sessionID, ...identity, progress: () => Effect.void },
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1766,7 +1766,7 @@ describe("ShellTool", () => {
|
|||
code,
|
||||
tools: ["shell"],
|
||||
bindings: {},
|
||||
permissions: [{ action: "*", resource: "*", effect: "allow" }],
|
||||
policy: Permission.Policy.fromRules([{ action: "*", resource: "*", effect: "allow" }]),
|
||||
limits: { timeoutMs: 30_000, maxOutputBytes: 32 * 1024 },
|
||||
context: {
|
||||
sessionID,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { LayerNode } from "@opencode/util/effect/layer-node"
|
|||
import { Bus } from "@opencode/core/bus"
|
||||
import { Location } from "@opencode/core/location"
|
||||
import { LocationServiceMap } from "@opencode/core/location-services"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { SdkPlugins } from "@opencode/core/plugin/sdk"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
|
|
@ -260,7 +261,9 @@ test("controls arbitrary tools through scoped SDK overlays", async () => {
|
|||
expect.objectContaining({ name: "lookup", description: "Look up a value" }),
|
||||
)
|
||||
expect(
|
||||
(yield* registry.snapshot([{ action: "simulate_lookup", resource: "*", effect: "deny" }])).definitions,
|
||||
(yield* registry.snapshot(
|
||||
PermissionPolicy.fromRules([{ action: "simulate_lookup", resource: "*", effect: "deny" }]),
|
||||
)).definitions,
|
||||
).not.toContainEqual(expect.objectContaining({ name: "lookup" }))
|
||||
const secondaryToolSet = yield* Tool.Service.use((secondaryRegistry) => secondaryRegistry.snapshot()).pipe(
|
||||
Effect.provide(secondary),
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue