opencode-agent-plus 0.4.0 → 0.4.2

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
@@ -18,17 +18,47 @@ Tested with OpenCode 2.2.0 and llama.cpp behind LiteLLM.
18
18
 
19
19
  ## Install
20
20
 
21
- Add it to the `plugin` list in `opencode.json`:
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
- "plugin": ["opencode-agent-plus"]
31
+ "plugins": ["opencode-agent-plus"]
26
32
  }
27
33
  ```
28
34
 
29
- Or, from GitHub: `"plugin": ["github:Anooshiravan/opencode-agent-plus"]`.
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, 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 |
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 agent's `reminder_file`
85
- 3. `reminder.txt` in the project folder, for every agent
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,36 @@ 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
+ ## Green light
210
+
211
+ With `manual_green_light: on`, tool calls are denied unless your latest message ends with an approval word (in its last
212
+ 3 words), like "run the tests, go". Deny messages tell you to approve or answer without tools. The `read` tool
213
+ is always allowed. Set your own words with `manual_green_light_words: yes, do, go`.
214
+
215
+ With `auto_green_light: on`, the model checks itself before the first tool call of each turn: it must allow the call
216
+ and state its plan, or explain why it cannot. The check fires once per turn and is not saved in the chat history.
217
+
154
218
  ## Notes
155
219
 
156
220
  - 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
221
  - `enable_thinking` and `reasoning_budget_tokens` need a server that supports them, like llama.cpp.
159
222
 
160
223
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-agent-plus",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",
@@ -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/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
+ })
@@ -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", "reminder_file", "on_error_command", "safe_commands", "anti_repetition", "max_same_tool", "green_light", "green_light_words", ...BODY, ...TEMPLATE_KWARGS])
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", ...BODY, ...TEMPLATE_KWARGS])
40
41
 
41
42
  export const read = (file: string) => readFile(file, "utf8").catch(() => "")
42
43
 
@@ -127,26 +128,36 @@ 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, wrong values and a missing reminder_file.
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 antiRepetition =
140
- keys.anti_repetition && !["on", "off"].includes(keys.anti_repetition)
141
- ? [`anti_repetition: must be on or off`]
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 maxSameTool =
144
- keys.max_same_tool && !/^\d+$/.test(keys.max_same_tool)
145
- ? [`max_same_tool: must be a whole number`]
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.green_light && !["on", "off"].includes(keys.green_light)
149
- ? [`green_light: must be on or off`]
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`]
150
161
  : []
151
162
  const wrong = [...BODY, ...TEMPLATE_KWARGS]
152
163
  .filter((k) => k in keys)
@@ -154,9 +165,5 @@ export async function problems(file: string, keys: Record<string, string>) {
154
165
  const result = requestValue(k, keys[k])
155
166
  return "error" in result ? [result.error] : []
156
167
  })
157
- const missing =
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]
168
+ return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering]
162
169
  }
@@ -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
+ }
package/src/index.ts CHANGED
@@ -1,22 +1,13 @@
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
- import { antiRepetition } from "./antirep"
7
- import { antiLoop } from "./antiloop"
8
- import { greenLight } from "./greenlight"
9
-
10
- // Runs a shell command (single or multi-line) and waits for it to finish.
11
- // zsh so ~/.zshenv functions and aliases (like server-on) are available; falls back to sh.
12
- function runShell(command: string) {
13
- const shell = existsSync("/bin/zsh") ? "/bin/zsh" : "/bin/sh"
14
- return new Promise<void>((resolve) => {
15
- const child = spawn(shell, ["-c", command], { stdio: "ignore" })
16
- child.on("close", () => resolve())
17
- child.on("error", () => resolve())
18
- })
19
- }
1
+ import { agentFile, frontmatter, problems } from "./frontmatter"
2
+ import { appendBlock, reminderText } from "./context"
3
+ import { log } from "./log"
4
+ import { isSafeToolCall } from "./safetoolcall"
5
+ import { maxWordRepeat, maxToolRepeat } from "./repetition"
6
+ import { manualGreenLight } from "./manualgreenlight"
7
+ import { autoGreenLight } from "./autogreenlight"
8
+ import { onErrorCommand } from "./onerrorcommand"
9
+ import { httpRequest } from "./httprequest"
10
+ import { pondering } from "./pondering"
20
11
 
21
12
  // Server half: adds the agent's reminders to every model request and its settings to the request body.
22
13
  // The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
@@ -33,33 +24,15 @@ export default {
33
24
  if (!warned.has(file)) {
34
25
  warned.add(file)
35
26
  const found = await problems(file, keys)
36
- if (found.length) console.warn(`agent-plus: problems in ${file}: ${found.join(", ")}`)
27
+ if (found.length) log(`server: problems file=${file} found=${found.join("; ")}`)
37
28
  }
38
29
  return { file, keys }
39
30
  }
40
31
 
41
- // Debug line, written when AGENT_PLUS_DEBUG points to a log file.
42
- const debug = (line: string) => {
43
- const file = process.env.AGENT_PLUS_DEBUG
44
- if (file) try { appendFileSync(file, `${new Date().toISOString()} ${line}\n`) } catch {}
45
- }
46
- debug(`plugin loaded directory=${directory}`)
32
+ log(`server: plugin loaded directory=${directory} pid=${process.pid} module=${import.meta.url}`)
47
33
 
48
- // `on_error_command`: when a request fails because the server is unreachable,
49
- // run the agent's command (e.g. wake it up) and ask for a quick retry.
50
- const woken = new Set<string>()
51
- await ctx.session.hook("retry", async (event: any) => {
52
- debug(`retry fired session=${event.sessionID} attempt=${event.attempt} error=${JSON.stringify(event.error)}`)
53
- const { keys } = await settings(event.agent)
54
- const command = keys.on_error_command
55
- if (!command) return
56
- // Only connection failures: a real HTTP answer has a status code.
57
- if (event.error?.status) return
58
- if (woken.has(event.sessionID)) return
59
- woken.add(event.sessionID)
60
- await runShell(command)
61
- event.decision = { retry: true, delay: 1_000 }
62
- })
34
+ // `on_error_command`: wake the server on a connection failure, then retry.
35
+ const allowWake = await onErrorCommand(ctx, { settings })
63
36
 
64
37
  // Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands: none`.
65
38
  // It skips the ask window for read-only tool calls and safe shell commands.
@@ -68,53 +41,33 @@ export default {
68
41
  if (event.effect !== "ask" || !event.agent) return
69
42
  const { keys } = await settings(event.agent)
70
43
  if (keys.safe_commands === "none") return
71
- if (isSafe(event.action, event.resources ?? [])) event.effect = "allow"
44
+ if (isSafeToolCall(event.action, event.resources ?? [])) event.effect = "allow"
72
45
  })
73
46
 
74
- // `anti_repetition: on` — interrupt the run when the model's text repeats itself.
75
- await antiRepetition(ctx, { settings, debug })
47
+ // `max_word_repeat: on` — interrupt the run when the model's text repeats itself.
48
+ await maxWordRepeat(ctx, { settings })
76
49
 
77
- // `green_light: on` — deny tools unless the user's latest message ends with a go-ahead word.
50
+ // `manual_green_light: on` — deny tools unless the user's latest message ends with a go-ahead word.
78
51
  // Registered first so its deny wins and the anti-loop below does not count a denied call.
79
- await greenLight(ctx, { settings, debug })
52
+ await manualGreenLight(ctx, { settings })
53
+
54
+ // `auto_green_light: on` — the model checks itself before the first tool call of each turn.
55
+ await autoGreenLight(ctx, { settings })
80
56
 
81
- // `max_same_tool: n` — deny a tool after n calls in a row within one user message.
82
- await antiLoop(ctx, { settings, debug })
57
+ // `max_tool_repeat: n` — deny a tool after n calls in a row within one user message.
58
+ await maxToolRepeat(ctx, { settings })
59
+
60
+ // `pondering: on` — think during idle time; the result rides into the next user message.
61
+ await pondering(ctx, { settings })
83
62
 
84
63
  await ctx.session.hook("context", async (event: any) => {
85
64
  // A request got through: allow on_error_command to fire again next time.
86
- woken.delete(event.sessionID)
87
- const { file, keys } = await settings(event.agent)
88
- const parts = [
89
- keys.reminder ?? "",
90
- keys.reminder_file ? await read(path.resolve(path.dirname(file), keys.reminder_file)) : "",
91
- await read(path.join(directory, "reminder.txt")),
92
- ]
93
- const text = parts.map((t) => t.trim()).filter(Boolean).join("\n\n")
94
- if (!text) return
95
- // Wrapped so the model does not take the reminder as a user message and reply to it.
96
- const wrapped = `<system-reminder>\nAutomatic note, not from the user. Do not reply to it.\n\n${text}\n</system-reminder>`
97
- // Plugins cannot import opencode's Message class (@opencode/ai), so borrow it from an existing message.
98
- const Message = event.messages[0].constructor
99
- event.messages.push(new Message({ role: "user", content: [{ type: "text", text: wrapped }] }))
100
- })
101
-
102
- await ctx.session.hook("http.request", async (event: any) => {
65
+ allowWake(event.sessionID)
103
66
  const { keys } = await settings(event.agent)
104
- const pick = (names: string[]) =>
105
- Object.fromEntries(
106
- names.flatMap((k) => {
107
- if (!(k in keys)) return []
108
- const result = requestValue(k, keys[k])
109
- return "value" in result ? [[k, result.value]] : []
110
- }),
111
- )
112
- const extra = pick(BODY)
113
- const kwargs = pick(TEMPLATE_KWARGS)
114
- if (!Object.keys(extra).length && !Object.keys(kwargs).length) return
115
- const body = await event.request.clone().json()
116
- if (Object.keys(kwargs).length) extra.chat_template_kwargs = { ...body.chat_template_kwargs, ...kwargs }
117
- event.request = new Request(event.request, { body: JSON.stringify({ ...body, ...extra }) })
67
+ await httpRequest(event, { settings })
68
+ const text = await reminderText(directory, keys)
69
+ if (!text) return
70
+ appendBlock(event, "system-reminder", text)
118
71
  })
119
72
  },
120
73
  }
package/src/log.ts ADDED
@@ -0,0 +1,23 @@
1
+ // The plugin's single log function. Lines are appended to `debug.log`
2
+ // next to the plugin's folder. Debug lines are on only while a `debug`
3
+ // file exists in the plugin's folder (touch/rm, no restart needed).
4
+ import path from "node:path"
5
+ import { appendFileSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs"
6
+ import { fileURLToPath } from "node:url"
7
+
8
+ export const folder = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
9
+ const marker = path.join(folder, "debug")
10
+ const file = path.join(folder, "debug.log")
11
+ const MAX_BYTES = 500_000 // cheap size check per line; on pass, rewrite with the last KEEP_LINES
12
+ const KEEP_LINES = 2000
13
+
14
+ export function log(line: string) {
15
+ if (!existsSync(marker)) return
16
+ try {
17
+ if (existsSync(file) && statSync(file).size > MAX_BYTES) {
18
+ const lines = readFileSync(file, "utf8").split("\n")
19
+ writeFileSync(file, lines.slice(-KEEP_LINES).join("\n"))
20
+ }
21
+ appendFileSync(file, `${new Date().toISOString()} ${line}\n`)
22
+ } catch {}
23
+ }