opencode-agent-plus 0.1.0 → 0.2.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/README.md CHANGED
@@ -1,11 +1,14 @@
1
1
  # opencode-agent-plus
2
2
 
3
- Per-agent reminders and request settings for [OpenCode](https://opencode.ai) v2, set in the agent's frontmatter.
3
+ Per-agent reminders, request settings and safe-command auto-allow for [OpenCode](https://opencode.ai) v2.
4
4
 
5
5
  Set `chat_template_kwargs` (like `enable_thinking`), sampling settings (`temperature`, `top_p`, `top_k`, `min_p`,
6
6
  penalties) and a system reminder for each OpenCode agent. Works with llama.cpp, LiteLLM and other OpenAI-compatible
7
7
  servers, and with thinking models like Qwen.
8
8
 
9
+ Auto-allows read-only tool calls and safe shell commands (`ls`, `cat`, `git status`, `docker compose ps`, …), so
10
+ with `shell: ask` in your permissions you get no prompt window for them — everything else still asks.
11
+
9
12
  OpenCode v2 drops request settings such as `temperature` for OpenAI-compatible providers, and has no per-agent
10
13
  reminder. agent-plus reads extra keys from the agent's `.md` file and applies them to every model request.
11
14
 
@@ -50,6 +53,7 @@ You help the user write and edit text.
50
53
  | `reminder` | text, one line or a `\|` block | Added as the last message of every model request |
51
54
  | `reminder_file` | path, relative to the agent's `.md` file | Like `reminder`, read from a file |
52
55
  | `on_error_command` | shell command, one line or a `\|` block | Run when a request fails with a connection error (server off), then retry |
56
+ | `safe_commands` | `none` (default: on) | Turn safe-command auto-allow off for this agent |
53
57
  | `temperature` | number | Request body |
54
58
  | `top_p` | number | Request body |
55
59
  | `top_k` | whole number | Request body |
@@ -129,6 +133,24 @@ on_error_command: |
129
133
 
130
134
  It fires once per outage per session: after a request gets through, the next connection error can run it again.
131
135
 
136
+ ## Safe commands
137
+
138
+ With `shell: ask` in your `permissions`, every shell command would prompt. agent-plus skips the prompt for calls
139
+ that can only read:
140
+
141
+ - Tools: `read`, `glob`, `grep`, `websearch`
142
+ - Commands: `ls`, `cat`, `head`, `tail`, `wc`, `find`, `grep`, `rg`, `sort`, `diff`, `pwd`, `echo`, `du`, `df`,
143
+ `git status/log/diff/show/branch`, `docker ps/logs/inspect`, `docker compose ps/logs`, `npm ls/view/outdated`,
144
+ `node --version`, `psql`/`sqlite3` with read-only queries, and `ssh host <safe command>`
145
+ - Anything with `;`, `|`, `&&`, `$( )` or redirections is checked **per part**: all parts must be safe
146
+
147
+ It never overrides a configured `deny`, and only turns `ask` into `allow`. Doubtful = asked.
148
+
149
+ Known unsafe flags are refused, e.g. `find -exec`, `env <cmd>`, `rg --pre`, `sort -o`, `git branch -D`,
150
+ `git log --output=`, `ssh -o ProxyCommand=`.
151
+
152
+ Turn it off for one agent with `safe_commands: none` in its frontmatter.
153
+
132
154
  ## Notes
133
155
 
134
156
  - Use `max_completion_tokens`, not `max_tokens`: OpenCode already sends `max_completion_tokens`, and servers use that one.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-agent-plus",
3
- "version": "0.1.0",
4
- "description": "OpenCode plugin: per-agent chat_template_kwargs (enable_thinking), sampling settings (temperature, top_p, top_k, min_p) and system reminders from agent frontmatter. For llama.cpp, LiteLLM and OpenAI-compatible providers.",
3
+ "version": "0.2.0",
4
+ "description": "OpenCode plugin: safe-command auto-allow (no prompt for read-only calls), per-agent chat_template_kwargs (enable_thinking), sampling settings and system reminders from agent frontmatter. For llama.cpp, LiteLLM and OpenAI-compatible providers.",
5
5
  "license": "MIT",
6
6
  "author": "Anoosh Ahmadi",
7
7
  "repository": {
@@ -36,7 +36,7 @@ const OPENCODE_KEYS = [
36
36
  "disabled",
37
37
  "request",
38
38
  ]
39
- const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "reminder_file", "on_error_command", ...BODY, ...TEMPLATE_KWARGS])
39
+ const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "reminder_file", "on_error_command", "safe_commands", ...BODY, ...TEMPLATE_KWARGS])
40
40
 
41
41
  export const read = (file: string) => readFile(file, "utf8").catch(() => "")
42
42
 
@@ -132,6 +132,10 @@ export function requestValue(key: string, value: string): { value: number | bool
132
132
 
133
133
  // Everything wrong in an agent file: misspelled keys, wrong values and a missing reminder_file.
134
134
  export async function problems(file: string, keys: Record<string, string>) {
135
+ const safeCommands =
136
+ keys.safe_commands && !["allow", "none"].includes(keys.safe_commands)
137
+ ? [`safe_commands: must be allow or none`]
138
+ : []
135
139
  const wrong = [...BODY, ...TEMPLATE_KWARGS]
136
140
  .filter((k) => k in keys)
137
141
  .flatMap((k) => {
@@ -142,5 +146,5 @@ export async function problems(file: string, keys: Record<string, string>) {
142
146
  keys.reminder_file && !(await read(path.resolve(path.dirname(file), keys.reminder_file)))
143
147
  ? [`reminder_file: ${keys.reminder_file} not found or empty`]
144
148
  : []
145
- return [...misspelledKeys(keys), ...wrong, ...missing]
149
+ return [...misspelledKeys(keys), ...wrong, ...missing, ...safeCommands]
146
150
  }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ import path from "node:path"
2
2
  import { spawn } from "node:child_process"
3
3
  import { appendFileSync, existsSync } from "node:fs"
4
4
  import { agentFile, BODY, frontmatter, problems, read, requestValue, TEMPLATE_KWARGS } from "./frontmatter"
5
+ import { isSafe } from "./safecommands"
5
6
 
6
7
  // Runs a shell command (single or multi-line) and waits for it to finish.
7
8
  // zsh so ~/.zshenv functions and aliases (like server-on) are available; falls back to sh.
@@ -56,6 +57,16 @@ export default {
56
57
  event.decision = { retry: true, delay: 1_000 }
57
58
  })
58
59
 
60
+ // Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands: none`.
61
+ // It skips the ask window for read-only tool calls and safe shell commands.
62
+ // Configured `deny` rules are final and never reach this hook; anything unsafe passes through unchanged.
63
+ await ctx.permission.hook("evaluate", async (event: any) => {
64
+ if (event.effect !== "ask" || !event.agent) return
65
+ const { keys } = await settings(event.agent)
66
+ if (keys.safe_commands === "none") return
67
+ if (isSafe(event.action, event.resources ?? [])) event.effect = "allow"
68
+ })
69
+
59
70
  await ctx.session.hook("context", async (event: any) => {
60
71
  // A request got through: allow on_error_command to fire again next time.
61
72
  woken.delete(event.sessionID)
@@ -0,0 +1,147 @@
1
+ // Safe-command checks for the `safe_commands: allow` frontmatter key.
2
+ // The permission hook (index.ts) asks: is this action + resource list read-only enough
3
+ // to skip the ask window? Anything doubtful stays on the normal path (config rules, prompt).
4
+
5
+ // Read-only tool actions that need no further checks.
6
+ const SAFE_ACTIONS = new Set(["read", "glob", "grep", "websearch"])
7
+
8
+ // Single commands that only read. Two-word commands (git, docker, ssh) are checked separately below.
9
+ const SAFE_COMMANDS = new Set([
10
+ "ls", "cat", "head", "tail", "wc", "find", "grep", "rg", "sort", "uniq", "diff",
11
+ "pwd", "echo", "whoami", "uname", "date", "du", "df", "file", "which", "type",
12
+ "tree", "stat", "env", "printenv", "basename", "dirname", "realpath",
13
+ ])
14
+
15
+ const GIT_SUBS = new Set(["status", "log", "diff", "show", "branch", "remote", "ls-files", "blame", "describe"])
16
+ const DOCKER_SUBS = new Set(["ps", "logs", "inspect", "images", "version", "top", "port"])
17
+ const COMPOSE_SUBS = new Set(["ps", "logs", "config", "images", "top", "port", "version"])
18
+ const NPM_SUBS = new Set(["ls", "list", "view", "outdated", "ping", "help"])
19
+ // First words of a database query that only read.
20
+ const SQL_STARTS = /^(select|with|explain|show|pragma)\b/i
21
+ const SQLITE_DOTS = new Set([".tables", ".schema", ".headers"])
22
+
23
+ // ssh flags that run code, tunnel traffic or change the connection: never safe.
24
+ const SSH_UNSAFE_FLAGS = new Set(["-o", "-J", "-L", "-R", "-D", "-W", "-F", "-E", "ssh_proxycommand"])
25
+
26
+ // Characters that mean the string is more than one simple command, or hides a substitution.
27
+ const UNSAFE_CHARS = /[$`;&|<>\n\r]/
28
+
29
+ // Splits one command into words, keeping quoted parts together.
30
+ function words(command: string): string[] | undefined {
31
+ const out: string[] = []
32
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g
33
+ let match: RegExpExecArray | null
34
+ while ((match = re.exec(command))) out.push(match[1] ?? match[2] ?? match[3])
35
+ return out.length ? out : undefined
36
+ }
37
+
38
+ // Reads inside quotes are not shell syntax: strip them before the unsafe-character check.
39
+ function unquoted(command: string): string {
40
+ return command.replace(/"[^"]*"|'[^']*'/g, " ")
41
+ }
42
+
43
+ // Checks one simple command (already split by the scanner from compounds).
44
+ function safeCommand(command: string): boolean {
45
+ if (UNSAFE_CHARS.test(unquoted(command))) return false
46
+ const parts = words(command)
47
+ if (!parts) return false
48
+ const [name, ...rest] = parts
49
+
50
+ // env runs whatever follows: check that command instead.
51
+ if (name === "env") {
52
+ const rest2 = rest.filter((r) => !r.includes("="))
53
+ return rest2.length > 0 && safeCommand(rest2.join(" "))
54
+ }
55
+
56
+ // These read-only tools can also run code or write files with certain flags.
57
+ const DANGEROUS_FLAGS: Record<string, string[]> = {
58
+ find: ["-exec", "-execdir", "-ok", "-delete", "-fprint", "-fprintf", "-fls"],
59
+ rg: ["--pre", "--hostname-bin"],
60
+ sort: ["-o", "--output"],
61
+ grep: ["--exclude-from"], // reads any file: keep it simple and refuse
62
+ }
63
+ if (DANGEROUS_FLAGS[name]) {
64
+ if (rest.some((r) => DANGEROUS_FLAGS[name].some((f) => r === f || r.startsWith(f + "=")))) return false
65
+ if (name === "grep") return true
66
+ return true
67
+ }
68
+
69
+ if (SAFE_COMMANDS.has(name)) return true
70
+
71
+ if (name === "git") {
72
+ const sub = rest.find((r) => !r.startsWith("-"))
73
+ if (sub === undefined || !GIT_SUBS.has(sub)) return false
74
+ // git branch can delete (-d -D -m -M -c -C) and git log/diff/show can write files (--output).
75
+ if (sub === "branch" && rest.some((r) => /^-(d|D|m|M|c|C)$/.test(r) || r.startsWith("--delete") || r.startsWith("--move"))) return false
76
+ if (rest.some((r) => r === "--output" || r.startsWith("--output="))) return false
77
+ return true
78
+ }
79
+
80
+ if (name === "docker") {
81
+ const sub = rest.find((r) => !r.startsWith("-"))
82
+ if (sub === "compose") {
83
+ const next = rest.slice(rest.indexOf(sub) + 1).find((r) => !r.startsWith("-"))
84
+ return next !== undefined && COMPOSE_SUBS.has(next)
85
+ }
86
+ return sub !== undefined && DOCKER_SUBS.has(sub)
87
+ }
88
+
89
+ if (name === "npm") {
90
+ const sub = rest.find((r) => !r.startsWith("-"))
91
+ return sub !== undefined && NPM_SUBS.has(sub)
92
+ }
93
+
94
+ // node only with plain info flags; node <script> or -e runs code.
95
+ if (name === "node") return rest.length > 0 && rest.every((r) => ["-v", "--version", "--help"].includes(r))
96
+
97
+ // psql / sqlite3: every quoted query must start with a read-only keyword and hold one statement.
98
+ if (name === "psql" || name === "sqlite3") return safeQueries(command)
99
+
100
+ // ssh [flags] host <cmd>: the remote command must itself be safe; a bare ssh is a shell.
101
+ if (name === "ssh") return safeSsh(rest)
102
+
103
+ return false
104
+ }
105
+
106
+ // psql / sqlite3: each quoted part must be one read-only statement; an unquoted .dot also counts.
107
+ function safeQueries(command: string): boolean {
108
+ const quoted = [...command.matchAll(/"([^"]*)"|'([^']*)'/g)].map((m) => m[1] ?? m[2])
109
+ if (!quoted.length) return SQLITE_DOTS.has(command.trim().split(/\s+/).pop()?.toLowerCase() ?? "")
110
+ return quoted.every((q) => {
111
+ const text = q.trim()
112
+ if (!text) return false
113
+ if (text.includes(";") && text.replace(/;+$/, "").includes(";")) return false // only one statement
114
+ const body = text.replace(/;+$/, "").trim()
115
+ return SQLITE_DOTS.has(body.toLowerCase()) || SQL_STARTS.test(body)
116
+ })
117
+ }
118
+
119
+ function safeSsh(args: string[]): boolean {
120
+ const rest: string[] = []
121
+ for (let i = 0; i < args.length; i++) {
122
+ const arg = args[i]
123
+ if (arg.startsWith("-")) {
124
+ // "-L 8080:host:80" style: the value is the next word; the flag itself decides.
125
+ const flag = arg.split("=")[0].toLowerCase()
126
+ if (SSH_UNSAFE_FLAGS.has(flag)) return false
127
+ if (/^-[jklmobic]$/.test(flag) && !arg.includes("=")) i++ // skip this flag's value
128
+ continue
129
+ }
130
+ if (!rest.length) {
131
+ rest.push(arg) // host
132
+ continue
133
+ }
134
+ rest.push(arg)
135
+ }
136
+ // rest[0] is the host; the rest is the remote command, checked like a local one.
137
+ if (rest.length < 2) return false
138
+ return safeCommand(rest.slice(1).join(" "))
139
+ }
140
+
141
+ // Is this permission event safe to allow? `action` and `resources` come from the hook event.
142
+ export function isSafe(action: string, resources: readonly string[]): boolean {
143
+ if (SAFE_ACTIONS.has(action)) return true
144
+ if (action !== "shell") return false
145
+ // The scanner splits compound commands into several resources: every part must be safe.
146
+ return resources.length > 0 && resources.every(safeCommand)
147
+ }
package/src/tui.tsx CHANGED
@@ -10,6 +10,7 @@ function sidebarLines(keys: Record<string, string>) {
10
10
  const lines = BODY.filter((k) => k in keys && "value" in requestValue(k, keys[k])).map((k) => `${k}: ${keys[k]}`)
11
11
  if (keys.enable_thinking === "true" || keys.enable_thinking === "false")
12
12
  lines.push(`thinking: ${keys.enable_thinking === "true" ? "on" : "off"}`)
13
+ lines.push(`safe_commands: ${keys.safe_commands === "none" ? "off" : "on"}`)
13
14
  if (keys.reminder || keys.reminder_file) lines.push("reminder: on")
14
15
  if (keys.on_error_command)
15
16
  lines.push(`on_error_command: ${keys.on_error_command.split("\n")[0].trim()}${keys.on_error_command.includes("\n") ? " …" : ""}`)