opencode-agent-plus 0.4.0 → 0.5.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 +88 -10
- package/package.json +31 -7
- package/src/antirepetition.test.ts +18 -0
- package/src/autogreenlight.ts +73 -0
- package/src/clockwork.ts +67 -0
- package/src/context.ts +55 -0
- package/src/frontmatter.test.ts +27 -0
- package/src/frontmatter.ts +35 -20
- package/src/httprequest.ts +21 -0
- package/src/index.ts +40 -79
- package/src/log.ts +23 -0
- package/src/{greenlight.ts → manualgreenlight.ts} +10 -11
- package/src/misplacedtag.test.ts +47 -0
- package/src/misplacedtag.ts +116 -0
- package/src/onerrorcommand.ts +39 -0
- package/src/pondering.ts +111 -0
- package/src/presets.ts +39 -0
- package/src/repetition.ts +203 -0
- package/src/safetoolcall.test.ts +36 -0
- package/src/{safecommands.ts → safetoolcall.ts} +1 -1
- package/src/tui.tsx +74 -10
- package/src/antiloop.ts +0 -66
- package/src/antirep/detect.ts +0 -57
- package/src/antirep/index.ts +0 -29
- package/src/antirep/stream.ts +0 -94
package/README.md
CHANGED
|
@@ -18,17 +18,47 @@ Tested with OpenCode 2.2.0 and llama.cpp behind LiteLLM.
|
|
|
18
18
|
|
|
19
19
|
## Install
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
Copy the files into the global plugins folder (plugins there load automatically):
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
rsync -a --exclude=.git <REPO_DIR>/ ~/.config/opencode/plugins/opencode-agent-plus/
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Or add it to the `plugins` list in `opencode.json`:
|
|
22
28
|
|
|
23
29
|
```json
|
|
24
30
|
{
|
|
25
|
-
"
|
|
31
|
+
"plugins": ["opencode-agent-plus"]
|
|
26
32
|
}
|
|
27
33
|
```
|
|
28
34
|
|
|
29
|
-
Or, from GitHub: `"
|
|
35
|
+
Or, from GitHub: `"plugins": ["github:Anooshiravan/opencode-agent-plus"]`.
|
|
30
36
|
Agents: follow [AGENTS.md](AGENTS.md).
|
|
31
37
|
|
|
38
|
+
To update an already-installed plugin, copy all files to the plugin folder:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
rsync -a --exclude=.git <REPO_DIR>/ ~/.config/opencode/plugins/opencode-agent-plus/
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Offline package
|
|
45
|
+
|
|
46
|
+
The plugin has no build step and no own dependencies (the `peerDependencies` are provided by OpenCode itself). To move it to a machine with no internet:
|
|
47
|
+
|
|
48
|
+
1. Package the files:
|
|
49
|
+
|
|
50
|
+
Name the package `opencode-agent-plus-<version_number>.tgz`, where `<version_number>` is the `version` in `package.json`:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
tar czf opencode-agent-plus-<version_number>.tgz -C <REPO_DIR> --exclude=.git --exclude=node_modules --exclude=local --exclude=screenshot.png .
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
2. On the offline machine, extract into `~/.config/opencode/plugins/opencode-agent-plus/`.
|
|
57
|
+
|
|
58
|
+
3. Restart: `opencode service restart`.
|
|
59
|
+
|
|
60
|
+
No `opencode.json` entry is needed; plugins in that folder load automatically.
|
|
61
|
+
|
|
32
62
|
## Example
|
|
33
63
|
|
|
34
64
|
```markdown
|
|
@@ -50,16 +80,21 @@ You help the user write and edit text.
|
|
|
50
80
|
|
|
51
81
|
| Key | Value | Effect |
|
|
52
82
|
| --- | --- | --- |
|
|
53
|
-
| `reminder` | text
|
|
54
|
-
| `reminder_file` | path, relative to the agent's `.md` file | Like `reminder`, read from a file |
|
|
83
|
+
| `reminder` | `concise`, `ultra-concise`, `creative`, `off`, or text (one line or a `\|` block) | Preset or custom reminder, added as the last message of every model request |
|
|
55
84
|
| `on_error_command` | shell command, one line or a `\|` block | Run when a request fails with a connection error (server off), then retry |
|
|
56
85
|
| `safe_commands` | `none` (default: on) | Turn safe-command auto-allow off for this agent |
|
|
86
|
+
| `anti_repetition` | `on` or `off` (default: off) | Stop the reply when the model repeats the same text |
|
|
87
|
+
| `max_same_tool` | whole number | Max times the same tool call may repeat in a row |
|
|
88
|
+
| `manual_green_light` | `on` or `off` (default: off) | Tools run only when your message ends with an approval word |
|
|
89
|
+
| `manual_green_light_words` | comma-separated words | The approval words for `manual_green_light` |
|
|
90
|
+
| `auto_green_light` | `on` or `off` (default: off) | The model checks itself before the first tool call of each turn |
|
|
57
91
|
| `temperature` | number | Request body |
|
|
58
92
|
| `top_p` | number | Request body |
|
|
59
93
|
| `top_k` | whole number | Request body |
|
|
60
94
|
| `min_p` | number | Request body |
|
|
61
95
|
| `presence_penalty` | number | Request body |
|
|
62
|
-
| `repeat_penalty` | number | Request body |
|
|
96
|
+
| `repeat_penalty` | number | Request body (llama.cpp) |
|
|
97
|
+
| `repetition_penalty` | number | Request body (vLLM, HF) |
|
|
63
98
|
| `max_completion_tokens` | whole number | Request body |
|
|
64
99
|
| `reasoning_budget_tokens` | whole number | Request body (llama.cpp) |
|
|
65
100
|
| `reasoning_effort` | `none`, `minimal`, `low`, `medium`, `high` or `xhigh` | Request body |
|
|
@@ -81,8 +116,11 @@ the most.
|
|
|
81
116
|
Before every model request, agent-plus adds one message at the end of the conversation with, in this order:
|
|
82
117
|
|
|
83
118
|
1. the agent's `reminder`
|
|
84
|
-
2. the
|
|
85
|
-
|
|
119
|
+
2. the `reminder` from `AGENTS.md` in the project folder, for every agent
|
|
120
|
+
|
|
121
|
+
`reminder` takes a preset name (`concise`, `ultra-concise`, `creative`, `off`) for wording held in
|
|
122
|
+
the plugin, or your own text (more than 3 words). A short unknown value means
|
|
123
|
+
`off`.
|
|
86
124
|
|
|
87
125
|
The text is wrapped in `<system-reminder>` tags with a note that it is not from the user. Without this, the model may
|
|
88
126
|
take the reminder as your message and reply to it ("Understood. Short replies...") instead of answering you.
|
|
@@ -108,7 +146,6 @@ At start, a toast lists problems in agent files:
|
|
|
108
146
|
|
|
109
147
|
- misspelled keys, like `temprature → temperature`
|
|
110
148
|
- wrong values, like `top_k: must be a whole number`
|
|
111
|
-
- a `reminder_file` that is missing or empty
|
|
112
149
|
|
|
113
150
|
Unknown keys that don't look like a misspelling are left alone, so other plugins can add their own keys.
|
|
114
151
|
With no problems, the toast says "agent-plus is loaded".
|
|
@@ -151,10 +188,51 @@ Known unsafe flags are refused, e.g. `find -exec`, `env <cmd>`, `rg --pre`, `sor
|
|
|
151
188
|
|
|
152
189
|
Turn it off for one agent with `safe_commands: none` in its frontmatter.
|
|
153
190
|
|
|
191
|
+
## Anti-repetition
|
|
192
|
+
|
|
193
|
+
With `anti_repetition: on`, agent-plus watches the model's reply as it streams. When the same stretch of text
|
|
194
|
+
repeats 5 or more times, the reply is cut and the session is interrupted, instead of filling up with garbage.
|
|
195
|
+
|
|
196
|
+
## Anti-loop
|
|
197
|
+
|
|
198
|
+
With `max_same_tool: 5`, the same tool call (same tool, same arguments) may repeat at most 5 times in a row.
|
|
199
|
+
The 6th is denied with a message telling the model to stop. The count resets when you send a new message.
|
|
200
|
+
|
|
201
|
+
## Pondering
|
|
202
|
+
|
|
203
|
+
With `pondering: on`, when the session goes idle the plugin runs one quiet
|
|
204
|
+
thinking request in it (opencode's transient generate: same conversation, not
|
|
205
|
+
saved to history). The model ponders where the conversation is going. The
|
|
206
|
+
result rides into your next message as a `<pondering>` block, which the model
|
|
207
|
+
uses silently — like the reminder, it never replies to it.
|
|
208
|
+
|
|
209
|
+
## Misplaced tag filter
|
|
210
|
+
|
|
211
|
+
With `misplaced_tag_filter: on`, tag signs (`<`, `>`, `|`) that leak into the
|
|
212
|
+
thinking or message text are swapped for safe look-alikes, so they cannot break
|
|
213
|
+
the next turn. Tool calls are not touched. When a message was changed, a short
|
|
214
|
+
note is added so you do not copy broken code from it.
|
|
215
|
+
|
|
216
|
+
## Green light
|
|
217
|
+
|
|
218
|
+
With `manual_green_light: on`, tool calls are denied unless your latest message ends with an approval word (in its last
|
|
219
|
+
3 words), like "run the tests, go". Deny messages tell you to approve or answer without tools. The `read` tool
|
|
220
|
+
is always allowed. Set your own words with `manual_green_light_words: yes, do, go`.
|
|
221
|
+
|
|
222
|
+
With `auto_green_light: on`, the model checks itself before the first tool call of each turn: it must allow the call
|
|
223
|
+
and state its plan, or explain why it cannot. The check fires once per turn and is not saved in the chat history.
|
|
224
|
+
|
|
225
|
+
## Clockwork
|
|
226
|
+
|
|
227
|
+
With `clockwork: on`, the agent runs hands-off. Every permission ask is denied,
|
|
228
|
+
and after each finished turn the plugin runs one quiet thinking request (like
|
|
229
|
+
pondering) to write a fresh "keep going" message, then sends it. The session
|
|
230
|
+
keeps working on its own until you stop it. Only agents with `clockwork: on` are
|
|
231
|
+
affected.
|
|
232
|
+
|
|
154
233
|
## Notes
|
|
155
234
|
|
|
156
235
|
- 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
236
|
- `enable_thinking` and `reasoning_budget_tokens` need a server that supports them, like llama.cpp.
|
|
159
237
|
|
|
160
238
|
## License
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-agent-plus",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
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",
|
|
@@ -9,21 +9,45 @@
|
|
|
9
9
|
"url": "git+https://github.com/Anooshiravan/opencode-agent-plus.git"
|
|
10
10
|
},
|
|
11
11
|
"keywords": [
|
|
12
|
-
"opencode",
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
12
|
+
"opencode",
|
|
13
|
+
"opencode-plugin",
|
|
14
|
+
"opencode-agent",
|
|
15
|
+
"agent",
|
|
16
|
+
"agents",
|
|
17
|
+
"frontmatter",
|
|
18
|
+
"llama.cpp",
|
|
19
|
+
"llama-cpp",
|
|
20
|
+
"litellm",
|
|
21
|
+
"openai-compatible",
|
|
22
|
+
"local-llm",
|
|
23
|
+
"chat_template_kwargs",
|
|
24
|
+
"chat-template-kwargs",
|
|
25
|
+
"enable_thinking",
|
|
26
|
+
"thinking",
|
|
27
|
+
"reasoning",
|
|
28
|
+
"temperature",
|
|
29
|
+
"sampling",
|
|
30
|
+
"top_p",
|
|
31
|
+
"top_k",
|
|
32
|
+
"min_p",
|
|
33
|
+
"system-reminder",
|
|
34
|
+
"reminder",
|
|
35
|
+
"qwen"
|
|
17
36
|
],
|
|
18
37
|
"type": "module",
|
|
19
38
|
"exports": {
|
|
20
39
|
".": "./src/index.ts",
|
|
21
40
|
"./tui": "./src/tui.tsx"
|
|
22
41
|
},
|
|
23
|
-
"files": [
|
|
42
|
+
"files": [
|
|
43
|
+
"src"
|
|
44
|
+
],
|
|
24
45
|
"peerDependencies": {
|
|
25
46
|
"@opentui/core": ">=0.7.0",
|
|
26
47
|
"@opentui/solid": ">=0.7.0",
|
|
27
48
|
"solid-js": ">=1.9.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"tsx": "^4.23.15"
|
|
28
52
|
}
|
|
29
53
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { findRepetition } from "./repetition"
|
|
3
|
+
|
|
4
|
+
test("flags a repeated block, ignores normal text", () => {
|
|
5
|
+
expect(findRepetition("parameter=".repeat(10))?.times).toBeGreaterThanOrEqual(5)
|
|
6
|
+
expect(findRepetition("the quick brown fox jumps over the lazy dog")).toBeUndefined()
|
|
7
|
+
expect(findRepetition("ok " .repeat(4))).toBeUndefined() // below min total
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
test("empty and short input", () => {
|
|
11
|
+
expect(findRepetition("")).toBeUndefined()
|
|
12
|
+
expect(findRepetition("a")).toBeUndefined()
|
|
13
|
+
expect(findRepetition("aaaaa")).toBeUndefined() // repeats but below min total
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test("repetition only at the start is still found", () => {
|
|
17
|
+
expect(findRepetition("xy".repeat(30) + " done")).toBeDefined()
|
|
18
|
+
})
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Auto green light: with `auto_green_light: on`, the first tool call of each
|
|
2
|
+
// turn is judged by a hidden request (same session, not saved to history, like
|
|
3
|
+
// pondering). The model answers ALLOW or DISALLOW for the planned call.
|
|
4
|
+
// ALLOW -> the tool runs; the main model never sees the check.
|
|
5
|
+
// DISALLOW -> the tool is denied with the model's reason.
|
|
6
|
+
// One check per turn; a new user message re-arms it.
|
|
7
|
+
import { realUserTexts } from "./context"
|
|
8
|
+
import { log } from "./log"
|
|
9
|
+
|
|
10
|
+
export interface AutoGreenLightOptions {
|
|
11
|
+
/** Reads the agent's frontmatter keys. */
|
|
12
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// The hidden prompt. It runs in the same session, so the model sees the real
|
|
16
|
+
// conversation and the tool call it is about to make.
|
|
17
|
+
function judgePrompt(action: string, resources: string[]) {
|
|
18
|
+
return [
|
|
19
|
+
"SYSTEM CHECK, not from the user. Do not reply to the user.",
|
|
20
|
+
`The agent is about to call the tool "${action}"${resources.length ? ` on: ${resources.join(", ")}` : ""}.`,
|
|
21
|
+
"You need to make judgment:",
|
|
22
|
+
"- Does the agent understand perfectly what the user intended?",
|
|
23
|
+
"- Is the user question clear and unambiguous?",
|
|
24
|
+
"- Is the tool call relevant to the question?",
|
|
25
|
+
"- In case of doubt, did the model ask relevant questions?",
|
|
26
|
+
"- Is the agent activity free of all assumptions or guesswork?",
|
|
27
|
+
'If all the above checks are positive, answer: {"allow": true}',
|
|
28
|
+
'Otherwise answer: {"allow": false, "reason": "why"}',
|
|
29
|
+
"Answer with the JSON only, nothing else.",
|
|
30
|
+
].join("\n")
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function autoGreenLight(ctx: any, options: AutoGreenLightOptions) {
|
|
34
|
+
const lastUser = new Map<string, string>() // session -> latest real user message
|
|
35
|
+
const checked = new Map<string, string>() // session -> message the check ran for
|
|
36
|
+
|
|
37
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
38
|
+
const texts = realUserTexts(event.messages)
|
|
39
|
+
lastUser.set(String(event.sessionID), texts[texts.length - 1] ?? "")
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
43
|
+
if (!event.agent) return
|
|
44
|
+
const { keys } = await options.settings(event.agent)
|
|
45
|
+
if (keys.auto_green_light !== "on") return
|
|
46
|
+
// Reading files is always allowed; only acting needs the check.
|
|
47
|
+
if (event.action === "read") return
|
|
48
|
+
const sessionID = String(event.sessionID)
|
|
49
|
+
const text = lastUser.get(sessionID) ?? ""
|
|
50
|
+
if (checked.get(sessionID) === text) return // already judged this turn
|
|
51
|
+
checked.set(sessionID, text)
|
|
52
|
+
try {
|
|
53
|
+
const { text: answer } = await ctx.session.generate({
|
|
54
|
+
sessionID,
|
|
55
|
+
prompt: judgePrompt(event.action, event.resources ?? []),
|
|
56
|
+
})
|
|
57
|
+
log(`autogreenlight: raw answer session=${sessionID} answer=${JSON.stringify(answer)}`)
|
|
58
|
+
let verdict: { allow?: boolean; reason?: string } = {}
|
|
59
|
+
try {
|
|
60
|
+
verdict = JSON.parse(String(answer).replace(/^```json?\s*|\s*```$/g, "").trim())
|
|
61
|
+
} catch {
|
|
62
|
+
log(`autogreenlight: bad verdict session=${sessionID} answer=${JSON.stringify(String(answer).slice(0, 200))}`)
|
|
63
|
+
}
|
|
64
|
+
log(`autogreenlight: allow=${verdict.allow} action=${event.action} session=${sessionID}`)
|
|
65
|
+
if (verdict.allow) return // tool runs; the check is not in history
|
|
66
|
+
event.effect = "deny"
|
|
67
|
+
event.message = `Auto green light: you disallowed this tool call. Reason: ${verdict.reason || "no reason given"}. Explain to the user why you cannot act, or ask them.`
|
|
68
|
+
} catch (error) {
|
|
69
|
+
log(`autogreenlight: judge failed session=${sessionID} error=${String(error)}`)
|
|
70
|
+
// Doubtful = asked: let the normal permission flow handle it.
|
|
71
|
+
}
|
|
72
|
+
})
|
|
73
|
+
}
|
package/src/clockwork.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// `clockwork: on` — hands-off loop. Denies every permission ask, and after the
|
|
2
|
+
// agent finishes a turn it asks the LLM endpoint to write a fresh proactive
|
|
3
|
+
// message, then sends it so the agent keeps going. Only agents with
|
|
4
|
+
// `clockwork: on` are affected.
|
|
5
|
+
import { log } from "./log"
|
|
6
|
+
|
|
7
|
+
const FALLBACK =
|
|
8
|
+
"Work autonomously. Decide for yourself, pick the option that best fits " +
|
|
9
|
+
"the task and the surrounding code, and keep going. If the situation is " +
|
|
10
|
+
"ambiguous, trust your feeling. Use all available tools to solve the task."
|
|
11
|
+
|
|
12
|
+
const META =
|
|
13
|
+
"You are nudging an autonomous coding agent that just stopped. Write ONE " +
|
|
14
|
+
"short imperative sentence telling it what to do next to keep making " +
|
|
15
|
+
"progress. Do not greet, do not ask questions, do not repeat prior work. " +
|
|
16
|
+
"Reply with that one sentence only."
|
|
17
|
+
|
|
18
|
+
export async function clockwork(ctx: any, { settings }: { settings: (agent: string) => Promise<{ keys: Record<string, string> }> }) {
|
|
19
|
+
const shared = ((globalThis as any).__agentPlusClockwork ??= { running: new Set<string>(), denied: new Set<string>() })
|
|
20
|
+
const running = shared.running as Set<string> // a keep-going prompt is in flight
|
|
21
|
+
const denied = shared.denied as Set<string> // this turn had a denied ask
|
|
22
|
+
|
|
23
|
+
// Deny every permission ask for clockwork agents.
|
|
24
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
25
|
+
if (!event.agent) return
|
|
26
|
+
const { keys } = await settings(event.agent)
|
|
27
|
+
if (keys.clockwork !== "on") return
|
|
28
|
+
if (event.effect !== "ask") return
|
|
29
|
+
event.effect = "deny"
|
|
30
|
+
event.message = "Clockwork: permission denied. Pick a different approach."
|
|
31
|
+
denied.add(String(event.sessionID))
|
|
32
|
+
log(`clockwork: denied ask session=${event.sessionID} action=${event.action}`)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// After each finished turn, ask the endpoint for a fresh nudge and send it.
|
|
36
|
+
const controller = new AbortController()
|
|
37
|
+
log(`clockwork: listener started`)
|
|
38
|
+
void (async () => {
|
|
39
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
40
|
+
if (event.id === shared.lastEvent) continue
|
|
41
|
+
shared.lastEvent = event.id
|
|
42
|
+
if (event.type !== "session.execution.succeeded") continue
|
|
43
|
+
const sessionID: string | undefined = event.data?.sessionID
|
|
44
|
+
if (!sessionID || running.has(sessionID)) continue
|
|
45
|
+
try {
|
|
46
|
+
const session = await ctx.session.get({ sessionID })
|
|
47
|
+
const { keys } = await settings(session.agent)
|
|
48
|
+
if (keys.clockwork !== "on") continue
|
|
49
|
+
running.add(sessionID)
|
|
50
|
+
const wasDenied = denied.delete(sessionID)
|
|
51
|
+
|
|
52
|
+
const { text: next } = await ctx.session.generate({ sessionID, prompt: META })
|
|
53
|
+
const text = String(next).trim() || FALLBACK
|
|
54
|
+
|
|
55
|
+
const final = wasDenied ? `Request is rejected. ${text}` : text
|
|
56
|
+
log(`clockwork: continuing session=${sessionID} denied=${wasDenied} text=${final}`)
|
|
57
|
+
await ctx.session.prompt({ sessionID, text: final, delivery: "steer" })
|
|
58
|
+
} catch (error) {
|
|
59
|
+
log(`clockwork: prompt failed session=${sessionID} error=${String(error)}`)
|
|
60
|
+
} finally {
|
|
61
|
+
running.delete(sessionID)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
})().catch((error) => log(`clockwork: listener died error=${String(error)}`))
|
|
65
|
+
|
|
66
|
+
return () => controller.abort()
|
|
67
|
+
}
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Owns the `context` hook: appends hidden blocks (like <system-reminder>)
|
|
2
|
+
// to the messages of every model request.
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import { frontmatter, read } from "./frontmatter"
|
|
5
|
+
import { reminderPreset } from "./presets"
|
|
6
|
+
|
|
7
|
+
// Appends `text` wrapped in <tag> as a user message the model must not reply to.
|
|
8
|
+
// Plugins cannot import opencode's Message class (@opencode/ai), so borrow it from an existing message.
|
|
9
|
+
export function appendBlock(event: any, tag: string, text: string, header = "Automatic note, not from the user. Do not reply to it.") {
|
|
10
|
+
const wrapped = `<${tag}>\n${header}\n\n${text}\n</${tag}>`
|
|
11
|
+
const Message = event.messages[0].constructor
|
|
12
|
+
const block = new Message({ role: "user", content: [{ type: "text", text: wrapped }] })
|
|
13
|
+
// NEVER change this order: the throwaway block must stay AFTER the user's
|
|
14
|
+
// last message, never before it.
|
|
15
|
+
//
|
|
16
|
+
// Why: the inference server we use, Strata, caches the conversation with
|
|
17
|
+
// checkpoints so the next request only reads the new text. Strata saves a
|
|
18
|
+
// checkpoint at the start of the last turn and reuses it next time.
|
|
19
|
+
//
|
|
20
|
+
// Strata has a flag, --tail-role-token, meant for a throwaway turn the
|
|
21
|
+
// server itself appends (a reasoning-effort note): it tells the engine to
|
|
22
|
+
// put the checkpoint BEFORE that turn, so the changing text never poisons
|
|
23
|
+
// the cache. With our reminder injected before the user message, the engine
|
|
24
|
+
// treated it as that throwaway turn and moved the checkpoint before it -
|
|
25
|
+
// but unlike the effort note, our block pushes the real user message and
|
|
26
|
+
// reply past the checkpoint, so every turn re-read them (reuse stuck, prefill
|
|
27
|
+
// growing each turn).
|
|
28
|
+
//
|
|
29
|
+
// With the block appended after the user message, the checkpoint covers the
|
|
30
|
+
// whole conversation and only the throwaway block itself is re-read.
|
|
31
|
+
event.messages.push(block)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Real user messages only: skips injections wrapped in <system-reminder>
|
|
35
|
+
// (ours and other plugins').
|
|
36
|
+
export function realUserTexts(messages: any[]): string[] {
|
|
37
|
+
const texts: string[] = []
|
|
38
|
+
for (const m of messages) {
|
|
39
|
+
if (m.role !== "user") continue
|
|
40
|
+
const parts = m.content ?? m.parts ?? []
|
|
41
|
+
const text = parts.map((p: any) => p.text ?? "").join("")
|
|
42
|
+
if (text.trimStart().startsWith("<system-reminder>")) continue
|
|
43
|
+
texts.push(text)
|
|
44
|
+
}
|
|
45
|
+
return texts
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The reminder text for a request: the agent file's `reminder:` first,
|
|
49
|
+
// then AGENTS.md's, then off ("").
|
|
50
|
+
export async function reminderText(directory: string, keys: Record<string, string>) {
|
|
51
|
+
const own = reminderPreset(keys.reminder)
|
|
52
|
+
if (own !== null) return own
|
|
53
|
+
const agents = frontmatter(await read(path.join(directory, "AGENTS.md")))
|
|
54
|
+
return reminderPreset(agents.reminder) ?? ""
|
|
55
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { frontmatter, problems, requestValue } from "./frontmatter"
|
|
3
|
+
|
|
4
|
+
test("parses keys and | blocks", () => {
|
|
5
|
+
const keys = frontmatter("---\ntemperature: 1\nreminder: |\n a\n b\n---\nbody")
|
|
6
|
+
expect(keys.temperature).toBe("1")
|
|
7
|
+
expect(keys.reminder).toBe("a\nb")
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
test("validates request values", () => {
|
|
11
|
+
expect(requestValue("top_k", "5")).toEqual({ value: 5 })
|
|
12
|
+
expect(requestValue("top_k", "1.5")).toEqual({ error: "top_k: must be a whole number" })
|
|
13
|
+
expect(requestValue("enable_thinking", "true")).toEqual({ value: true })
|
|
14
|
+
expect(requestValue("reasoning_effort", "bad")).toEqual({ error: "reasoning_effort: must be one of none, minimal, low, medium, high, xhigh" })
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
test("no frontmatter, empty, and unknown keys", () => {
|
|
18
|
+
expect(frontmatter("no dashes here")).toEqual({})
|
|
19
|
+
expect(frontmatter("---\n---\n")).toEqual({})
|
|
20
|
+
expect(frontmatter("---\nsomekey: v\n---").somekey).toBe("v")
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test("reports misspelled keys and wrong values", async () => {
|
|
24
|
+
const found = await problems("f", { temprature: "1", max_word_repeat: "maybe" })
|
|
25
|
+
expect(found).toContain("temprature → temperature")
|
|
26
|
+
expect(found).toContain("max_word_repeat: must be on or off")
|
|
27
|
+
})
|
package/src/frontmatter.ts
CHANGED
|
@@ -9,17 +9,18 @@ const GLOBAL_DIR =
|
|
|
9
9
|
path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "opencode")
|
|
10
10
|
export const BODY = [
|
|
11
11
|
"temperature",
|
|
12
|
-
"top_p",
|
|
13
|
-
"top_k",
|
|
14
|
-
"min_p",
|
|
15
|
-
"presence_penalty",
|
|
16
|
-
"repeat_penalty",
|
|
17
12
|
"max_completion_tokens",
|
|
18
13
|
"reasoning_budget_tokens",
|
|
19
14
|
"reasoning_effort",
|
|
20
15
|
]
|
|
21
16
|
export const TEMPLATE_KWARGS = ["enable_thinking"]
|
|
22
17
|
const WHOLE_NUMBERS = ["top_k", "max_completion_tokens", "reasoning_budget_tokens"]
|
|
18
|
+
// Safe value ranges for the sampling settings.
|
|
19
|
+
const RANGES: Record<string, [number, number]> = {
|
|
20
|
+
temperature: [0.2, 1.4],
|
|
21
|
+
max_completion_tokens: [1024, 32768],
|
|
22
|
+
reasoning_budget_tokens: [1024, 8192],
|
|
23
|
+
}
|
|
23
24
|
// Settings sent as text, with the values they accept.
|
|
24
25
|
const CHOICES: Record<string, string[]> = {
|
|
25
26
|
reasoning_effort: ["none", "minimal", "low", "medium", "high", "xhigh"],
|
|
@@ -36,7 +37,7 @@ const OPENCODE_KEYS = [
|
|
|
36
37
|
"disabled",
|
|
37
38
|
"request",
|
|
38
39
|
]
|
|
39
|
-
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "
|
|
40
|
+
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "on_error_command", "safe_commands", "max_word_repeat", "max_tool_repeat", "manual_green_light", "manual_green_light_words", "auto_green_light", "pondering", "misplaced_tag_filter", "clockwork", ...BODY, ...TEMPLATE_KWARGS])
|
|
40
41
|
|
|
41
42
|
export const read = (file: string) => readFile(file, "utf8").catch(() => "")
|
|
42
43
|
|
|
@@ -127,26 +128,44 @@ export function requestValue(key: string, value: string): { value: number | bool
|
|
|
127
128
|
const number = Number(value)
|
|
128
129
|
if (value === "" || Number.isNaN(number)) return { error: `${key}: must be a number` }
|
|
129
130
|
if (WHOLE_NUMBERS.includes(key) && !Number.isInteger(number)) return { error: `${key}: must be a whole number` }
|
|
131
|
+
const range = RANGES[key]
|
|
132
|
+
if (range && (number < range[0] || number > range[1])) return { error: `${key}: must be between ${range[0]} and ${range[1]}` }
|
|
130
133
|
return { value: number }
|
|
131
134
|
}
|
|
132
135
|
|
|
133
|
-
// Everything wrong in an agent file: misspelled keys
|
|
136
|
+
// Everything wrong in an agent file: misspelled keys and wrong values.
|
|
134
137
|
export async function problems(file: string, keys: Record<string, string>) {
|
|
135
138
|
const safeCommands =
|
|
136
139
|
keys.safe_commands && !["allow", "none"].includes(keys.safe_commands)
|
|
137
140
|
? [`safe_commands: must be allow or none`]
|
|
138
141
|
: []
|
|
139
|
-
const
|
|
140
|
-
keys.
|
|
141
|
-
? [`
|
|
142
|
+
const maxWordRepeat =
|
|
143
|
+
keys.max_word_repeat && !["on", "off"].includes(keys.max_word_repeat)
|
|
144
|
+
? [`max_word_repeat: must be on or off`]
|
|
142
145
|
: []
|
|
143
|
-
const
|
|
144
|
-
keys.
|
|
145
|
-
? [`
|
|
146
|
+
const maxToolRepeat =
|
|
147
|
+
keys.max_tool_repeat && !/^\d+$/.test(keys.max_tool_repeat)
|
|
148
|
+
? [`max_tool_repeat: must be a whole number`]
|
|
146
149
|
: []
|
|
147
150
|
const greenLight =
|
|
148
|
-
keys.
|
|
149
|
-
? [`
|
|
151
|
+
keys.manual_green_light && !["on", "off"].includes(keys.manual_green_light)
|
|
152
|
+
? [`manual_green_light: must be on or off`]
|
|
153
|
+
: []
|
|
154
|
+
const autoGreenLight =
|
|
155
|
+
keys.auto_green_light && !["on", "off"].includes(keys.auto_green_light)
|
|
156
|
+
? [`auto_green_light: must be on or off`]
|
|
157
|
+
: []
|
|
158
|
+
const pondering =
|
|
159
|
+
keys.pondering && !["on", "off"].includes(keys.pondering)
|
|
160
|
+
? [`pondering: must be on or off`]
|
|
161
|
+
: []
|
|
162
|
+
const misplacedTagFilter =
|
|
163
|
+
keys.misplaced_tag_filter && !["on", "off"].includes(keys.misplaced_tag_filter)
|
|
164
|
+
? [`misplaced_tag_filter: must be on or off`]
|
|
165
|
+
: []
|
|
166
|
+
const clockwork =
|
|
167
|
+
keys.clockwork && !["on", "off"].includes(keys.clockwork)
|
|
168
|
+
? [`clockwork: must be on or off`]
|
|
150
169
|
: []
|
|
151
170
|
const wrong = [...BODY, ...TEMPLATE_KWARGS]
|
|
152
171
|
.filter((k) => k in keys)
|
|
@@ -154,9 +173,5 @@ export async function problems(file: string, keys: Record<string, string>) {
|
|
|
154
173
|
const result = requestValue(k, keys[k])
|
|
155
174
|
return "error" in result ? [result.error] : []
|
|
156
175
|
})
|
|
157
|
-
|
|
158
|
-
keys.reminder_file && !(await read(path.resolve(path.dirname(file), keys.reminder_file)))
|
|
159
|
-
? [`reminder_file: ${keys.reminder_file} not found or empty`]
|
|
160
|
-
: []
|
|
161
|
-
return [...misspelledKeys(keys), ...wrong, ...missing, ...safeCommands, ...antiRepetition, ...maxSameTool, ...greenLight]
|
|
176
|
+
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering, ...misplacedTagFilter, ...clockwork]
|
|
162
177
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Request settings: adds the agent's sampling settings to the model request.
|
|
2
|
+
// Supported keys are listed in frontmatter.ts; a setting with a wrong value is not sent.
|
|
3
|
+
import { BODY, requestValue } from "./frontmatter"
|
|
4
|
+
import { log } from "./log"
|
|
5
|
+
|
|
6
|
+
export interface HttpRequestOptions {
|
|
7
|
+
/** Reads the agent's frontmatter keys. */
|
|
8
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function httpRequest(event: any, options: HttpRequestOptions) {
|
|
12
|
+
const { keys } = await options.settings(event.agent)
|
|
13
|
+
const extra: Record<string, number | string> = {}
|
|
14
|
+
for (const k of BODY) {
|
|
15
|
+
if (!(k in keys)) continue
|
|
16
|
+
const result = requestValue(k, keys[k])
|
|
17
|
+
if ("value" in result) extra[k] = result.value as number | string
|
|
18
|
+
}
|
|
19
|
+
log(`httprequest: agent=${event.agent} extra=${JSON.stringify(extra)}`)
|
|
20
|
+
event.options = { ...event.options, ...extra }
|
|
21
|
+
}
|