opencode-agent-plus 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +161 -2
- package/package.json +27 -4
- package/src/frontmatter.ts +150 -0
- package/src/index.ts +106 -0
- package/src/safecommands.ts +147 -0
- package/src/tui.tsx +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Anoosh Ahmadi
|
|
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,162 @@
|
|
|
1
|
-
#
|
|
1
|
+
# opencode-agent-plus
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Per-agent reminders, request settings and safe-command auto-allow for [OpenCode](https://opencode.ai) v2.
|
|
4
|
+
|
|
5
|
+
Set `chat_template_kwargs` (like `enable_thinking`), sampling settings (`temperature`, `top_p`, `top_k`, `min_p`,
|
|
6
|
+
penalties) and a system reminder for each OpenCode agent. Works with llama.cpp, LiteLLM and other OpenAI-compatible
|
|
7
|
+
servers, and with thinking models like Qwen.
|
|
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
|
+
|
|
12
|
+
OpenCode v2 drops request settings such as `temperature` for OpenAI-compatible providers, and has no per-agent
|
|
13
|
+
reminder. agent-plus reads extra keys from the agent's `.md` file and applies them to every model request.
|
|
14
|
+
|
|
15
|
+
Tested with OpenCode 2.0.28 and llama.cpp behind LiteLLM.
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
Add it to the `plugin` list in `opencode.json`:
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"plugin": ["opencode-agent-plus"]
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Or, from GitHub: `"plugin": ["github:Anooshiravan/opencode-agent-plus"]`.
|
|
30
|
+
Agents: follow [AGENTS.md](AGENTS.md).
|
|
31
|
+
|
|
32
|
+
## Example
|
|
33
|
+
|
|
34
|
+
```markdown
|
|
35
|
+
---
|
|
36
|
+
description: Writing and editing text
|
|
37
|
+
mode: primary
|
|
38
|
+
model: litellm/my-model
|
|
39
|
+
temperature: 1.0
|
|
40
|
+
enable_thinking: false
|
|
41
|
+
reminder: |
|
|
42
|
+
- Keep replies short, simple words
|
|
43
|
+
- If unclear, say so — don't guess
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
You help the user write and edit text.
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Keys
|
|
50
|
+
|
|
51
|
+
| Key | Value | Effect |
|
|
52
|
+
| --- | --- | --- |
|
|
53
|
+
| `reminder` | text, one line or a `\|` block | Added as the last message of every model request |
|
|
54
|
+
| `reminder_file` | path, relative to the agent's `.md` file | Like `reminder`, read from a file |
|
|
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 |
|
|
57
|
+
| `temperature` | number | Request body |
|
|
58
|
+
| `top_p` | number | Request body |
|
|
59
|
+
| `top_k` | whole number | Request body |
|
|
60
|
+
| `min_p` | number | Request body |
|
|
61
|
+
| `presence_penalty` | number | Request body |
|
|
62
|
+
| `repeat_penalty` | number | Request body |
|
|
63
|
+
| `max_completion_tokens` | whole number | Request body |
|
|
64
|
+
| `reasoning_budget_tokens` | whole number | Request body (llama.cpp) |
|
|
65
|
+
| `reasoning_effort` | `none`, `minimal`, `low`, `medium`, `high` or `xhigh` | Request body |
|
|
66
|
+
| `enable_thinking` | `true` or `false` | Request body, under `chat_template_kwargs` |
|
|
67
|
+
|
|
68
|
+
Names are sent as written. A setting with a wrong value is not sent.
|
|
69
|
+
|
|
70
|
+
## Reminders
|
|
71
|
+
|
|
72
|
+
### Why
|
|
73
|
+
|
|
74
|
+
The system prompt sits at the start of the conversation. As the conversation grows with messages and tool output, the
|
|
75
|
+
model pays less attention to that early text and drifts: longer answers, extra work, guessing. Models weigh recent text
|
|
76
|
+
most, so a short reminder at the end puts the rules right where the model starts writing. Small local models benefit
|
|
77
|
+
the most.
|
|
78
|
+
|
|
79
|
+
### How
|
|
80
|
+
|
|
81
|
+
Before every model request, agent-plus adds one message at the end of the conversation with, in this order:
|
|
82
|
+
|
|
83
|
+
1. the agent's `reminder`
|
|
84
|
+
2. the agent's `reminder_file`
|
|
85
|
+
3. `reminder.txt` in the project folder, for every agent
|
|
86
|
+
|
|
87
|
+
The text is wrapped in `<system-reminder>` tags with a note that it is not from the user. Without this, the model may
|
|
88
|
+
take the reminder as your message and reply to it ("Understood. Short replies...") instead of answering you.
|
|
89
|
+
|
|
90
|
+
The message is only added to the outgoing request, **NOT saved in the chat history**. Every request has exactly one
|
|
91
|
+
reminder at the end, so reminders never pile up.
|
|
92
|
+
|
|
93
|
+
### Prompt cache
|
|
94
|
+
|
|
95
|
+
The impact on the server's prompt cache (KV cache) is small and does not grow with the conversation:
|
|
96
|
+
|
|
97
|
+
- Request 1 is `history + reminder`; the model writes its reply after the reminder.
|
|
98
|
+
- Request 2 is `history + reply + new message + reminder`.
|
|
99
|
+
|
|
100
|
+
The cache matches up to the end of `history`, where the old reminder was. The server then processes the model's last
|
|
101
|
+
reply again, plus the new message and the new reminder, which are new anyway. The extra cost per request is the length
|
|
102
|
+
of the last reply (one answer or one tool call), never the whole conversation. Servers that can reuse shifted cache
|
|
103
|
+
chunks, like llama.cpp with `--cache-reuse`, may recover part of it.
|
|
104
|
+
|
|
105
|
+
## Warnings
|
|
106
|
+
|
|
107
|
+
At start, a toast lists problems in agent files:
|
|
108
|
+
|
|
109
|
+
- misspelled keys, like `temprature → temperature`
|
|
110
|
+
- wrong values, like `top_k: must be a whole number`
|
|
111
|
+
- a `reminder_file` that is missing or empty
|
|
112
|
+
|
|
113
|
+
Unknown keys that don't look like a misspelling are left alone, so other plugins can add their own keys.
|
|
114
|
+
With no problems, the toast says "agent-plus is loaded".
|
|
115
|
+
|
|
116
|
+
## Sidebar
|
|
117
|
+
|
|
118
|
+
The session sidebar shows an "Agent-plus" section with the settings of the session's agent. It updates when you
|
|
119
|
+
switch agents or save an agent file.
|
|
120
|
+
|
|
121
|
+
## Wake the server
|
|
122
|
+
|
|
123
|
+
`on_error_command` runs a shell command when a model request fails with a connection error (the server is off or
|
|
124
|
+
unreachable), then asks OpenCode to retry after a short delay. HTTP errors (like 500 or 429) never trigger it.
|
|
125
|
+
|
|
126
|
+
```yaml
|
|
127
|
+
---
|
|
128
|
+
on_error_command: |
|
|
129
|
+
server-on
|
|
130
|
+
curl -sf http://litellm:4000/health
|
|
131
|
+
---
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
It fires once per outage per session: after a request gets through, the next connection error can run it again.
|
|
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
|
+
|
|
154
|
+
## Notes
|
|
155
|
+
|
|
156
|
+
- Use `max_completion_tokens`, not `max_tokens`: OpenCode already sends `max_completion_tokens`, and servers use that one.
|
|
157
|
+
- Do not give `reminder_file` a `.md` name: OpenCode loads every `.md` in the agent folder as an agent.
|
|
158
|
+
- `enable_thinking` and `reasoning_budget_tokens` need a server that supports them, like llama.cpp.
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-agent-plus",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
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
|
+
"license": "MIT",
|
|
6
|
+
"author": "Anoosh Ahmadi",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Anooshiravan/opencode-agent-plus.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"opencode", "opencode-plugin", "opencode-agent", "agent", "agents", "frontmatter",
|
|
13
|
+
"llama.cpp", "llama-cpp", "litellm", "openai-compatible", "local-llm",
|
|
14
|
+
"chat_template_kwargs", "chat-template-kwargs", "enable_thinking", "thinking", "reasoning",
|
|
15
|
+
"temperature", "sampling", "top_p", "top_k", "min_p",
|
|
16
|
+
"system-reminder", "reminder", "qwen"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./src/index.ts",
|
|
21
|
+
"./tui": "./src/tui.tsx"
|
|
22
|
+
},
|
|
23
|
+
"files": ["src"],
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@opentui/core": ">=0.5.8",
|
|
26
|
+
"@opentui/solid": ">=0.5.8",
|
|
27
|
+
"solid-js": ">=1.9.0"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
|
|
5
|
+
// Shared by the server half (index.ts) and the TUI half (tui.tsx).
|
|
6
|
+
// Same rule as opencode: OPENCODE_CONFIG_DIR, else $XDG_CONFIG_HOME/opencode, else ~/.config/opencode (also on Windows).
|
|
7
|
+
const GLOBAL_DIR =
|
|
8
|
+
process.env.OPENCODE_CONFIG_DIR ||
|
|
9
|
+
path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "opencode")
|
|
10
|
+
export const BODY = [
|
|
11
|
+
"temperature",
|
|
12
|
+
"top_p",
|
|
13
|
+
"top_k",
|
|
14
|
+
"min_p",
|
|
15
|
+
"presence_penalty",
|
|
16
|
+
"repeat_penalty",
|
|
17
|
+
"max_completion_tokens",
|
|
18
|
+
"reasoning_budget_tokens",
|
|
19
|
+
"reasoning_effort",
|
|
20
|
+
]
|
|
21
|
+
export const TEMPLATE_KWARGS = ["enable_thinking"]
|
|
22
|
+
const WHOLE_NUMBERS = ["top_k", "max_completion_tokens", "reasoning_budget_tokens"]
|
|
23
|
+
// Settings sent as text, with the values they accept.
|
|
24
|
+
const CHOICES: Record<string, string[]> = {
|
|
25
|
+
reasoning_effort: ["none", "minimal", "low", "medium", "high", "xhigh"],
|
|
26
|
+
}
|
|
27
|
+
const OPENCODE_KEYS = [
|
|
28
|
+
"description",
|
|
29
|
+
"mode",
|
|
30
|
+
"model",
|
|
31
|
+
"system",
|
|
32
|
+
"permissions",
|
|
33
|
+
"steps",
|
|
34
|
+
"hidden",
|
|
35
|
+
"color",
|
|
36
|
+
"disabled",
|
|
37
|
+
"request",
|
|
38
|
+
]
|
|
39
|
+
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "reminder_file", "on_error_command", "safe_commands", ...BODY, ...TEMPLATE_KWARGS])
|
|
40
|
+
|
|
41
|
+
export const read = (file: string) => readFile(file, "utf8").catch(() => "")
|
|
42
|
+
|
|
43
|
+
// Agent folders in lookup order: the project's .opencode first, then the global folder; `agent` or `agents`.
|
|
44
|
+
function agentFolders(directory: string) {
|
|
45
|
+
return [path.join(directory, ".opencode"), GLOBAL_DIR].flatMap((base) =>
|
|
46
|
+
["agent", "agents"].map((folder) => path.join(base, folder)),
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Finds the agent's .md file.
|
|
51
|
+
export async function agentFile(directory: string, agent: string) {
|
|
52
|
+
for (const folder of agentFolders(directory)) {
|
|
53
|
+
const file = path.join(folder, `${agent}.md`)
|
|
54
|
+
const text = await read(file)
|
|
55
|
+
if (text) return { file, text }
|
|
56
|
+
}
|
|
57
|
+
return { file: "", text: "" }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Lists every agent .md file, including subfolders (`team/reviewer.md` is agent `team/reviewer`).
|
|
61
|
+
export async function allAgentFiles(directory: string) {
|
|
62
|
+
const files: string[] = []
|
|
63
|
+
for (const folder of agentFolders(directory)) {
|
|
64
|
+
const names = await readdir(folder, { recursive: true }).catch(() => [] as string[])
|
|
65
|
+
files.push(...names.filter((n) => n.endsWith(".md")).map((n) => path.join(folder, n)))
|
|
66
|
+
}
|
|
67
|
+
return files
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Reads top-level `key: value` pairs as strings; `|` blocks are supported.
|
|
71
|
+
export function frontmatter(text: string): Record<string, string> {
|
|
72
|
+
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
73
|
+
if (!match) return {}
|
|
74
|
+
const lines = match[1].split(/\r?\n/)
|
|
75
|
+
const result: Record<string, string> = {}
|
|
76
|
+
for (let i = 0; i < lines.length; i++) {
|
|
77
|
+
const key = lines[i].match(/^([\w-]+):\s*(.*)$/)
|
|
78
|
+
if (!key) continue
|
|
79
|
+
const value = key[2].trim()
|
|
80
|
+
if (!value.startsWith("|")) {
|
|
81
|
+
result[key[1]] = value.replace(/^(["'])(.*)\1$/, "$2")
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
const block: string[] = []
|
|
85
|
+
while (i + 1 < lines.length && (!lines[i + 1].trim() || /^\s/.test(lines[i + 1]))) block.push(lines[++i])
|
|
86
|
+
const indent = Math.min(...block.filter((l) => l.trim()).map((l) => l.match(/^\s*/)![0].length))
|
|
87
|
+
result[key[1]] = block.map((l) => l.slice(indent)).join("\n").trim()
|
|
88
|
+
}
|
|
89
|
+
return result
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Number of single-letter edits to turn `a` into `b`.
|
|
93
|
+
function distance(a: string, b: string) {
|
|
94
|
+
let row = Array.from({ length: b.length + 1 }, (_, j) => j)
|
|
95
|
+
for (let i = 1; i <= a.length; i++) {
|
|
96
|
+
const next = [i]
|
|
97
|
+
for (let j = 1; j <= b.length; j++)
|
|
98
|
+
next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
|
|
99
|
+
row = next
|
|
100
|
+
}
|
|
101
|
+
return row[b.length]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Unknown keys that look like a misspelled known key, as "wrong → right".
|
|
105
|
+
// Other unknown keys are left alone: they may belong to another plugin.
|
|
106
|
+
export function misspelledKeys(keys: Record<string, string>) {
|
|
107
|
+
return Object.keys(keys).flatMap((key) => {
|
|
108
|
+
if (KNOWN.has(key)) return []
|
|
109
|
+
const match = [...KNOWN].find((known) => {
|
|
110
|
+
const d = distance(key, known)
|
|
111
|
+
return d <= 2 && d < known.length / 3
|
|
112
|
+
})
|
|
113
|
+
return match ? [`${key} → ${match}`] : []
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Converts a request setting to its JSON value, or gives an error text when the value is wrong.
|
|
118
|
+
export function requestValue(key: string, value: string): { value: number | boolean | string } | { error: string } {
|
|
119
|
+
if (TEMPLATE_KWARGS.includes(key)) {
|
|
120
|
+
if (value === "true" || value === "false") return { value: value === "true" }
|
|
121
|
+
return { error: `${key}: must be true or false` }
|
|
122
|
+
}
|
|
123
|
+
if (key in CHOICES) {
|
|
124
|
+
if (CHOICES[key].includes(value)) return { value }
|
|
125
|
+
return { error: `${key}: must be one of ${CHOICES[key].join(", ")}` }
|
|
126
|
+
}
|
|
127
|
+
const number = Number(value)
|
|
128
|
+
if (value === "" || Number.isNaN(number)) return { error: `${key}: must be a number` }
|
|
129
|
+
if (WHOLE_NUMBERS.includes(key) && !Number.isInteger(number)) return { error: `${key}: must be a whole number` }
|
|
130
|
+
return { value: number }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Everything wrong in an agent file: misspelled keys, wrong values and a missing reminder_file.
|
|
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
|
+
: []
|
|
139
|
+
const wrong = [...BODY, ...TEMPLATE_KWARGS]
|
|
140
|
+
.filter((k) => k in keys)
|
|
141
|
+
.flatMap((k) => {
|
|
142
|
+
const result = requestValue(k, keys[k])
|
|
143
|
+
return "error" in result ? [result.error] : []
|
|
144
|
+
})
|
|
145
|
+
const missing =
|
|
146
|
+
keys.reminder_file && !(await read(path.resolve(path.dirname(file), keys.reminder_file)))
|
|
147
|
+
? [`reminder_file: ${keys.reminder_file} not found or empty`]
|
|
148
|
+
: []
|
|
149
|
+
return [...misspelledKeys(keys), ...wrong, ...missing, ...safeCommands]
|
|
150
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { spawn } from "node:child_process"
|
|
3
|
+
import { appendFileSync, existsSync } from "node:fs"
|
|
4
|
+
import { agentFile, BODY, frontmatter, problems, read, requestValue, TEMPLATE_KWARGS } from "./frontmatter"
|
|
5
|
+
import { isSafe } from "./safecommands"
|
|
6
|
+
|
|
7
|
+
// Runs a shell command (single or multi-line) and waits for it to finish.
|
|
8
|
+
// zsh so ~/.zshenv functions and aliases (like server-on) are available; falls back to sh.
|
|
9
|
+
function runShell(command: string) {
|
|
10
|
+
const shell = existsSync("/bin/zsh") ? "/bin/zsh" : "/bin/sh"
|
|
11
|
+
return new Promise<void>((resolve) => {
|
|
12
|
+
const child = spawn(shell, ["-c", command], { stdio: "ignore" })
|
|
13
|
+
child.on("close", () => resolve())
|
|
14
|
+
child.on("error", () => resolve())
|
|
15
|
+
})
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Server half: adds the agent's reminders to every model request and its settings to the request body.
|
|
19
|
+
// The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
|
|
20
|
+
// Settings with a wrong value are not sent. Problems are logged once per agent; tui.tsx also shows them as a toast.
|
|
21
|
+
export default {
|
|
22
|
+
id: "agent-plus",
|
|
23
|
+
async setup(ctx: any) {
|
|
24
|
+
const directory = ctx.location.directory
|
|
25
|
+
const warned = new Set<string>()
|
|
26
|
+
|
|
27
|
+
async function settings(agent: string) {
|
|
28
|
+
const { file, text } = await agentFile(directory, agent)
|
|
29
|
+
const keys = frontmatter(text)
|
|
30
|
+
if (!warned.has(file)) {
|
|
31
|
+
warned.add(file)
|
|
32
|
+
const found = await problems(file, keys)
|
|
33
|
+
if (found.length) console.warn(`agent-plus: problems in ${file}: ${found.join(", ")}`)
|
|
34
|
+
}
|
|
35
|
+
return { file, keys }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Debug line, written when AGENT_PLUS_DEBUG points to a log file.
|
|
39
|
+
const debug = (line: string) => {
|
|
40
|
+
const file = process.env.AGENT_PLUS_DEBUG
|
|
41
|
+
if (file) try { appendFileSync(file, `${new Date().toISOString()} ${line}\n`) } catch {}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// `on_error_command`: when a request fails because the server is unreachable,
|
|
45
|
+
// run the agent's command (e.g. wake it up) and ask for a quick retry.
|
|
46
|
+
const woken = new Set<string>()
|
|
47
|
+
await ctx.session.hook("retry", async (event: any) => {
|
|
48
|
+
debug(`retry fired session=${event.sessionID} attempt=${event.attempt} error=${JSON.stringify(event.error)}`)
|
|
49
|
+
const { keys } = await settings(event.agent)
|
|
50
|
+
const command = keys.on_error_command
|
|
51
|
+
if (!command) return
|
|
52
|
+
// Only connection failures: a real HTTP answer has a status code.
|
|
53
|
+
if (event.error?.status) return
|
|
54
|
+
if (woken.has(event.sessionID)) return
|
|
55
|
+
woken.add(event.sessionID)
|
|
56
|
+
await runShell(command)
|
|
57
|
+
event.decision = { retry: true, delay: 1_000 }
|
|
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
|
+
|
|
70
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
71
|
+
// A request got through: allow on_error_command to fire again next time.
|
|
72
|
+
woken.delete(event.sessionID)
|
|
73
|
+
const { file, keys } = await settings(event.agent)
|
|
74
|
+
const parts = [
|
|
75
|
+
keys.reminder ?? "",
|
|
76
|
+
keys.reminder_file ? await read(path.resolve(path.dirname(file), keys.reminder_file)) : "",
|
|
77
|
+
await read(path.join(directory, "reminder.txt")),
|
|
78
|
+
]
|
|
79
|
+
const text = parts.map((t) => t.trim()).filter(Boolean).join("\n\n")
|
|
80
|
+
if (!text) return
|
|
81
|
+
// Wrapped so the model does not take the reminder as a user message and reply to it.
|
|
82
|
+
const wrapped = `<system-reminder>\nAutomatic note, not from the user. Do not reply to it.\n\n${text}\n</system-reminder>`
|
|
83
|
+
// Plugins cannot import opencode's Message class (@opencode/ai), so borrow it from an existing message.
|
|
84
|
+
const Message = event.messages[0].constructor
|
|
85
|
+
event.messages.push(new Message({ role: "user", content: [{ type: "text", text: wrapped }] }))
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
await ctx.session.hook("http.request", async (event: any) => {
|
|
89
|
+
const { keys } = await settings(event.agent)
|
|
90
|
+
const pick = (names: string[]) =>
|
|
91
|
+
Object.fromEntries(
|
|
92
|
+
names.flatMap((k) => {
|
|
93
|
+
if (!(k in keys)) return []
|
|
94
|
+
const result = requestValue(k, keys[k])
|
|
95
|
+
return "value" in result ? [[k, result.value]] : []
|
|
96
|
+
}),
|
|
97
|
+
)
|
|
98
|
+
const extra = pick(BODY)
|
|
99
|
+
const kwargs = pick(TEMPLATE_KWARGS)
|
|
100
|
+
if (!Object.keys(extra).length && !Object.keys(kwargs).length) return
|
|
101
|
+
const body = await event.request.clone().json()
|
|
102
|
+
if (Object.keys(kwargs).length) extra.chat_template_kwargs = { ...body.chat_template_kwargs, ...kwargs }
|
|
103
|
+
event.request = new Request(event.request, { body: JSON.stringify({ ...body, ...extra }) })
|
|
104
|
+
})
|
|
105
|
+
},
|
|
106
|
+
}
|
|
@@ -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
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/solid */
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
import { createMemo, createResource, createSignal, For, Show } from "solid-js"
|
|
4
|
+
import { agentFile, allAgentFiles, BODY, frontmatter, problems, read, requestValue } from "./frontmatter"
|
|
5
|
+
|
|
6
|
+
// At start, shows a warning toast for every agent .md file with problems, or a "loaded" toast when there are none.
|
|
7
|
+
// Adds an "Agent-plus" section to the sidebar with the agent-plus settings of the session's agent.
|
|
8
|
+
// The sidebar reads the agent file again when the session's agent changes or opencode reports an agent file change.
|
|
9
|
+
function sidebarLines(keys: Record<string, string>) {
|
|
10
|
+
const lines = BODY.filter((k) => k in keys && "value" in requestValue(k, keys[k])).map((k) => `${k}: ${keys[k]}`)
|
|
11
|
+
if (keys.enable_thinking === "true" || keys.enable_thinking === "false")
|
|
12
|
+
lines.push(`thinking: ${keys.enable_thinking === "true" ? "on" : "off"}`)
|
|
13
|
+
lines.push(`safe_commands: ${keys.safe_commands === "none" ? "off" : "on"}`)
|
|
14
|
+
if (keys.reminder || keys.reminder_file) lines.push("reminder: on")
|
|
15
|
+
if (keys.on_error_command)
|
|
16
|
+
lines.push(`on_error_command: ${keys.on_error_command.split("\n")[0].trim()}${keys.on_error_command.includes("\n") ? " …" : ""}`)
|
|
17
|
+
return lines
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export default {
|
|
21
|
+
id: "agent-plus",
|
|
22
|
+
async setup(ctx: any) {
|
|
23
|
+
const directory = ctx.location?.directory ?? process.cwd()
|
|
24
|
+
let warned = false
|
|
25
|
+
for (const file of await allAgentFiles(directory)) {
|
|
26
|
+
const found = await problems(file, frontmatter(await read(file)))
|
|
27
|
+
if (!found.length) continue
|
|
28
|
+
warned = true
|
|
29
|
+
ctx.ui.toast.show({
|
|
30
|
+
title: "agent-plus",
|
|
31
|
+
message: `Problems in ${path.basename(file)}:\n${found.join("\n")}`,
|
|
32
|
+
variant: "warning",
|
|
33
|
+
duration: 7000,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
if (!warned) ctx.ui.toast.show({ message: "agent-plus is loaded", variant: "info" })
|
|
37
|
+
|
|
38
|
+
const [agentsVersion, setAgentsVersion] = createSignal(0)
|
|
39
|
+
const stop = ctx.data.on("agent.updated", () => setAgentsVersion((v) => v + 1))
|
|
40
|
+
|
|
41
|
+
ctx.ui.slot({
|
|
42
|
+
append: "sidebar.content",
|
|
43
|
+
render: (props: { sessionID: string }) => {
|
|
44
|
+
const theme = ctx.theme
|
|
45
|
+
const agent = createMemo(() => ctx.data.session.get(props.sessionID)?.agent)
|
|
46
|
+
const [lines] = createResource(
|
|
47
|
+
() => agent() && { agent: agent()!, version: agentsVersion() },
|
|
48
|
+
async ({ agent }) => sidebarLines(frontmatter((await agentFile(directory, agent)).text)),
|
|
49
|
+
)
|
|
50
|
+
return (
|
|
51
|
+
<Show when={lines()?.length}>
|
|
52
|
+
<box>
|
|
53
|
+
<text fg={theme.text.base}>
|
|
54
|
+
<b>Agent-plus</b>
|
|
55
|
+
</text>
|
|
56
|
+
<For each={lines() ?? []}>{(line) => <text fg={theme.text.muted}>{line}</text>}</For>
|
|
57
|
+
</box>
|
|
58
|
+
</Show>
|
|
59
|
+
)
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
return stop
|
|
63
|
+
},
|
|
64
|
+
}
|