opencode-agent-plus 0.3.2 → 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 +73 -10
- package/package.json +1 -1
- package/src/antirepetition.test.ts +18 -0
- package/src/autogreenlight.ts +73 -0
- package/src/context.ts +55 -0
- package/src/frontmatter.test.ts +27 -0
- package/src/frontmatter.ts +31 -29
- package/src/httprequest.ts +21 -0
- package/src/index.ts +39 -96
- package/src/log.ts +23 -0
- package/src/manualgreenlight.ts +47 -0
- package/src/onerrorcommand.ts +39 -0
- package/src/pondering.ts +111 -0
- package/src/presets.ts +45 -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 +72 -10
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,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.
|
|
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
|
+
})
|
package/src/frontmatter.ts
CHANGED
|
@@ -9,34 +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
|
-
"frequency_penalty",
|
|
17
|
-
"repetition_penalty",
|
|
18
|
-
"repeat_penalty",
|
|
19
|
-
"repeat_last_n",
|
|
20
|
-
"penalty_last_n",
|
|
21
|
-
"dry_multiplier",
|
|
22
|
-
"dry_allowed_length",
|
|
23
|
-
"dry_penalty_last_n",
|
|
24
|
-
"dry_base",
|
|
25
|
-
"mirostat",
|
|
26
|
-
"mirostat_tau",
|
|
27
|
-
"mirostat_eta",
|
|
28
|
-
"typical_p",
|
|
29
|
-
"xtc_threshold",
|
|
30
|
-
"xtc_probability",
|
|
31
|
-
"min_keep",
|
|
32
|
-
"ignore_eos",
|
|
33
|
-
"seed",
|
|
34
12
|
"max_completion_tokens",
|
|
35
13
|
"reasoning_budget_tokens",
|
|
36
14
|
"reasoning_effort",
|
|
37
15
|
]
|
|
38
16
|
export const TEMPLATE_KWARGS = ["enable_thinking"]
|
|
39
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
|
+
}
|
|
40
24
|
// Settings sent as text, with the values they accept.
|
|
41
25
|
const CHOICES: Record<string, string[]> = {
|
|
42
26
|
reasoning_effort: ["none", "minimal", "low", "medium", "high", "xhigh"],
|
|
@@ -53,7 +37,7 @@ const OPENCODE_KEYS = [
|
|
|
53
37
|
"disabled",
|
|
54
38
|
"request",
|
|
55
39
|
]
|
|
56
|
-
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", ...BODY, ...TEMPLATE_KWARGS])
|
|
57
41
|
|
|
58
42
|
export const read = (file: string) => readFile(file, "utf8").catch(() => "")
|
|
59
43
|
|
|
@@ -144,24 +128,42 @@ export function requestValue(key: string, value: string): { value: number | bool
|
|
|
144
128
|
const number = Number(value)
|
|
145
129
|
if (value === "" || Number.isNaN(number)) return { error: `${key}: must be a number` }
|
|
146
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]}` }
|
|
147
133
|
return { value: number }
|
|
148
134
|
}
|
|
149
135
|
|
|
150
|
-
// Everything wrong in an agent file: misspelled keys
|
|
136
|
+
// Everything wrong in an agent file: misspelled keys and wrong values.
|
|
151
137
|
export async function problems(file: string, keys: Record<string, string>) {
|
|
152
138
|
const safeCommands =
|
|
153
139
|
keys.safe_commands && !["allow", "none"].includes(keys.safe_commands)
|
|
154
140
|
? [`safe_commands: must be allow or none`]
|
|
155
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`]
|
|
145
|
+
: []
|
|
146
|
+
const maxToolRepeat =
|
|
147
|
+
keys.max_tool_repeat && !/^\d+$/.test(keys.max_tool_repeat)
|
|
148
|
+
? [`max_tool_repeat: must be a whole number`]
|
|
149
|
+
: []
|
|
150
|
+
const greenLight =
|
|
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
|
+
: []
|
|
156
162
|
const wrong = [...BODY, ...TEMPLATE_KWARGS]
|
|
157
163
|
.filter((k) => k in keys)
|
|
158
164
|
.flatMap((k) => {
|
|
159
165
|
const result = requestValue(k, keys[k])
|
|
160
166
|
return "error" in result ? [result.error] : []
|
|
161
167
|
})
|
|
162
|
-
|
|
163
|
-
keys.reminder_file && !(await read(path.resolve(path.dirname(file), keys.reminder_file)))
|
|
164
|
-
? [`reminder_file: ${keys.reminder_file} not found or empty`]
|
|
165
|
-
: []
|
|
166
|
-
return [...misspelledKeys(keys), ...wrong, ...missing, ...safeCommands]
|
|
168
|
+
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering]
|
|
167
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,19 +1,13 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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
|
-
}
|
|
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"
|
|
17
11
|
|
|
18
12
|
// Server half: adds the agent's reminders to every model request and its settings to the request body.
|
|
19
13
|
// The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
|
|
@@ -30,101 +24,50 @@ export default {
|
|
|
30
24
|
if (!warned.has(file)) {
|
|
31
25
|
warned.add(file)
|
|
32
26
|
const found = await problems(file, keys)
|
|
33
|
-
if (found.length)
|
|
27
|
+
if (found.length) log(`server: problems file=${file} found=${found.join("; ")}`)
|
|
34
28
|
}
|
|
35
29
|
return { file, keys }
|
|
36
30
|
}
|
|
37
31
|
|
|
38
|
-
|
|
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
|
-
}
|
|
32
|
+
log(`server: plugin loaded directory=${directory} pid=${process.pid} module=${import.meta.url}`)
|
|
43
33
|
|
|
44
|
-
// `on_error_command`:
|
|
45
|
-
|
|
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
|
-
})
|
|
34
|
+
// `on_error_command`: wake the server on a connection failure, then retry.
|
|
35
|
+
const allowWake = await onErrorCommand(ctx, { settings })
|
|
59
36
|
|
|
60
37
|
// Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands: none`.
|
|
61
38
|
// It skips the ask window for read-only tool calls and safe shell commands.
|
|
62
39
|
// Configured `deny` rules are final and never reach this hook; anything unsafe passes through unchanged.
|
|
63
|
-
// `max_same_tool: n` denies a tool after n calls in a row without another tool in between.
|
|
64
|
-
// Varied work resets the count; only a streak trips it.
|
|
65
|
-
const streaks = new Map<string, { action: string; count: number }>()
|
|
66
|
-
// Serialize per session: parallel calls in one batch must not interleave on the counter.
|
|
67
|
-
const queues = new Map<string, Promise<void>>()
|
|
68
40
|
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
69
|
-
if (!event.agent) return
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const max = Number(keys.max_same_tool)
|
|
74
|
-
if (Number.isInteger(max) && max >= 1 && event.action !== "task") {
|
|
75
|
-
const prev = streaks.get(key)
|
|
76
|
-
const count = prev && prev.action === event.action ? prev.count + 1 : 1
|
|
77
|
-
streaks.set(key, { action: event.action, count })
|
|
78
|
-
if (count > max) {
|
|
79
|
-
streaks.set(key, { action: event.action, count: 0 })
|
|
80
|
-
event.effect = "deny"
|
|
81
|
-
event.message = `You already used '${event.action}' more than the maximum allowed ${max} times in a row. You are probably stuck in a doom loop. Try something else or report the issue to user.`
|
|
82
|
-
return
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
if (event.effect !== "ask") return
|
|
86
|
-
if (keys.safe_commands === "none") return
|
|
87
|
-
if (isSafe(event.action, event.resources ?? [])) event.effect = "allow"
|
|
88
|
-
}
|
|
89
|
-
const run = (queues.get(key) ?? Promise.resolve()).then(work, work)
|
|
90
|
-
queues.set(key, run.then(() => {}).catch(() => {}))
|
|
91
|
-
await run
|
|
41
|
+
if (event.effect !== "ask" || !event.agent) return
|
|
42
|
+
const { keys } = await settings(event.agent)
|
|
43
|
+
if (keys.safe_commands === "none") return
|
|
44
|
+
if (isSafeToolCall(event.action, event.resources ?? [])) event.effect = "allow"
|
|
92
45
|
})
|
|
93
46
|
|
|
47
|
+
// `max_word_repeat: on` — interrupt the run when the model's text repeats itself.
|
|
48
|
+
await maxWordRepeat(ctx, { settings })
|
|
49
|
+
|
|
50
|
+
// `manual_green_light: on` — deny tools unless the user's latest message ends with a go-ahead word.
|
|
51
|
+
// Registered first so its deny wins and the anti-loop below does not count a denied call.
|
|
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 })
|
|
56
|
+
|
|
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 })
|
|
62
|
+
|
|
94
63
|
await ctx.session.hook("context", async (event: any) => {
|
|
95
64
|
// A request got through: allow on_error_command to fire again next time.
|
|
96
|
-
|
|
97
|
-
const { file, keys } = await settings(event.agent)
|
|
98
|
-
const parts = [
|
|
99
|
-
keys.reminder ?? "",
|
|
100
|
-
keys.reminder_file ? await read(path.resolve(path.dirname(file), keys.reminder_file)) : "",
|
|
101
|
-
await read(path.join(directory, "reminder.txt")),
|
|
102
|
-
]
|
|
103
|
-
const text = parts.map((t) => t.trim()).filter(Boolean).join("\n\n")
|
|
104
|
-
if (!text) return
|
|
105
|
-
// Wrapped so the model does not take the reminder as a user message and reply to it.
|
|
106
|
-
const wrapped = `<system-reminder>\nAutomatic note, not from the user. Do not reply to it.\n\n${text}\n</system-reminder>`
|
|
107
|
-
// Plugins cannot import opencode's Message class (@opencode/ai), so borrow it from an existing message.
|
|
108
|
-
const Message = event.messages[0].constructor
|
|
109
|
-
event.messages.push(new Message({ role: "user", content: [{ type: "text", text: wrapped }] }))
|
|
110
|
-
})
|
|
111
|
-
|
|
112
|
-
await ctx.session.hook("http.request", async (event: any) => {
|
|
65
|
+
allowWake(event.sessionID)
|
|
113
66
|
const { keys } = await settings(event.agent)
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const result = requestValue(k, keys[k])
|
|
119
|
-
return "value" in result ? [[k, result.value]] : []
|
|
120
|
-
}),
|
|
121
|
-
)
|
|
122
|
-
const extra = pick(BODY)
|
|
123
|
-
const kwargs = pick(TEMPLATE_KWARGS)
|
|
124
|
-
if (!Object.keys(extra).length && !Object.keys(kwargs).length) return
|
|
125
|
-
const body = await event.request.clone().json()
|
|
126
|
-
if (Object.keys(kwargs).length) extra.chat_template_kwargs = { ...body.chat_template_kwargs, ...kwargs }
|
|
127
|
-
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)
|
|
128
71
|
})
|
|
129
72
|
},
|
|
130
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
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Green light: with `manual_green_light: on`, every tool is denied unless the user's
|
|
2
|
+
// latest message ends with a green-light word (in its last 3 words), e.g.
|
|
3
|
+
// "fix the config, go". The agent must ask, the user must approve.
|
|
4
|
+
// Everything stays in memory; nothing is sent to the server.
|
|
5
|
+
import { realUserTexts } from "./context"
|
|
6
|
+
import { log } from "./log"
|
|
7
|
+
|
|
8
|
+
export interface ManualGreenLightOptions {
|
|
9
|
+
/** Reads the agent's frontmatter keys. */
|
|
10
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Words that mean "you may act", checked in the last 3 words of the message.
|
|
14
|
+
// Agents replace the list with `manual_green_light_words: yes, go, do`.
|
|
15
|
+
const DEFAULT_GREEN_LIGHT_WORDS = ["yes", "do", "go", "ok", "okay", "fine", "good", "fix", "try", "run"]
|
|
16
|
+
|
|
17
|
+
// Resolves `manual_green_light_words` to the effective word list and its match test.
|
|
18
|
+
function greenLightWords(words: string | undefined): { list: string[]; test: RegExp } {
|
|
19
|
+
const list = words?.split(",").map((w) => w.trim().toLowerCase()).filter(Boolean)
|
|
20
|
+
const safe = list?.length ? list : DEFAULT_GREEN_LIGHT_WORDS
|
|
21
|
+
return { list: safe, test: new RegExp(`\\b(${safe.map((w) => w.replace(/[^\w-]/g, "")).join("|")})\\b`, "i") }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function manualGreenLight(ctx: any, options: ManualGreenLightOptions) {
|
|
25
|
+
// Per session: the user's latest real message text.
|
|
26
|
+
const lastUser = new Map<string, string>()
|
|
27
|
+
|
|
28
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
29
|
+
const texts = realUserTexts(event.messages)
|
|
30
|
+
lastUser.set(String(event.sessionID), texts[texts.length - 1] ?? "")
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
34
|
+
if (!event.agent) return
|
|
35
|
+
const { keys } = await options.settings(event.agent)
|
|
36
|
+
if (keys.manual_green_light !== "on") return
|
|
37
|
+
// Reading files is always allowed; only acting needs the word.
|
|
38
|
+
if (event.action === "read") return
|
|
39
|
+
const text = lastUser.get(String(event.sessionID)) ?? ""
|
|
40
|
+
const tail = text.trim().split(/\s+/).slice(-3).join(" ")
|
|
41
|
+
const { list, test } = greenLightWords(keys.manual_green_light_words)
|
|
42
|
+
if (test.test(tail)) return
|
|
43
|
+
event.effect = "deny"
|
|
44
|
+
event.message = `Green light is on: tools run only when the user's message ends with a green-light word (${list.join(", ")}). Ask the user to approve, or answer without tools.`
|
|
45
|
+
log(`greenlight: denied action=${event.action} session=${String(event.sessionID)} tail=${JSON.stringify(tail)}`)
|
|
46
|
+
})
|
|
47
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// `on_error_command`: when a request fails because the server is unreachable,
|
|
2
|
+
// run the agent's command (e.g. wake it up) and ask for a quick retry.
|
|
3
|
+
import { spawn } from "node:child_process"
|
|
4
|
+
import { existsSync } from "node:fs"
|
|
5
|
+
import { log } from "./log"
|
|
6
|
+
|
|
7
|
+
export interface OnErrorCommandOptions {
|
|
8
|
+
/** Reads the agent's frontmatter keys. */
|
|
9
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Runs a shell command (single or multi-line) and waits for it to finish.
|
|
13
|
+
// zsh so ~/.zshenv functions and aliases (like server-on) are available; falls back to sh.
|
|
14
|
+
function runShell(command: string) {
|
|
15
|
+
const shell = existsSync("/bin/zsh") ? "/bin/zsh" : "/bin/sh"
|
|
16
|
+
return new Promise<void>((resolve) => {
|
|
17
|
+
const child = spawn(shell, ["-c", command], { stdio: "ignore" })
|
|
18
|
+
child.on("close", () => resolve())
|
|
19
|
+
child.on("error", () => resolve())
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function onErrorCommand(ctx: any, options: OnErrorCommandOptions) {
|
|
24
|
+
const woken = new Set<string>()
|
|
25
|
+
await ctx.session.hook("retry", async (event: any) => {
|
|
26
|
+
log(`onerrorcommand: retry fired session=${event.sessionID} attempt=${event.attempt} error=${JSON.stringify(event.error)}`)
|
|
27
|
+
const { keys } = await options.settings(event.agent)
|
|
28
|
+
const command = keys.on_error_command
|
|
29
|
+
if (!command) return
|
|
30
|
+
// Only connection failures: a real HTTP answer has a status code.
|
|
31
|
+
if (event.error?.status) return
|
|
32
|
+
if (woken.has(event.sessionID)) return
|
|
33
|
+
woken.add(event.sessionID)
|
|
34
|
+
await runShell(command)
|
|
35
|
+
event.decision = { retry: true, delay: 1_000 }
|
|
36
|
+
})
|
|
37
|
+
// Called from the context hook when a request got through: allow firing again.
|
|
38
|
+
return (sessionID: string) => woken.delete(sessionID)
|
|
39
|
+
}
|
package/src/pondering.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// `pondering: on` — when a session goes idle, run one transient generate
|
|
2
|
+
// request in it (opencode's own API: same context, not saved to history)
|
|
3
|
+
// asking the model to ponder where the conversation is going. The result is
|
|
4
|
+
// appended to the user's next message as a <pondering> block, used silently.
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
7
|
+
import { folder, log } from "./log"
|
|
8
|
+
import { appendBlock } from "./context"
|
|
9
|
+
|
|
10
|
+
// Small file the TUI sidebar watches to show pondering: busy/idle.
|
|
11
|
+
// Content is a JSON map: { sessionID: "busy" | "idle" }.
|
|
12
|
+
const statusFile = path.join(folder, "pondering.status")
|
|
13
|
+
function setStatus(sessionID: string, state: "busy" | "idle", note = "") {
|
|
14
|
+
try {
|
|
15
|
+
const map = JSON.parse(readFileSync(statusFile, "utf8")) as Record<string, { state: string; note: string }>
|
|
16
|
+
map[sessionID] = { state, note }
|
|
17
|
+
writeFileSync(statusFile, JSON.stringify(map))
|
|
18
|
+
} catch {
|
|
19
|
+
writeFileSync(statusFile, JSON.stringify({ [sessionID]: { state, note } }))
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const NOTE = [
|
|
24
|
+
"This is a pondering request (like a chess engine's permanent brain) to think ahead and improve future replies.",
|
|
25
|
+
"Read your last reply only. If there is nothing useful to note (a greeting, a yes/no answer), reply with exactly: SKIP",
|
|
26
|
+
"Otherwise write a short note, one line per point, only what applies.",
|
|
27
|
+
"1. Claims you did not verify: quote each one, if any.",
|
|
28
|
+
"2. Anything left unfinished.",
|
|
29
|
+
"3. What the user will likely ask next.",
|
|
30
|
+
"4. One thing to check first, and how.",
|
|
31
|
+
"5. Did you understand the user's intent, or miss something?",
|
|
32
|
+
"6. Anything you are stuck on, or want to ask the user.",
|
|
33
|
+
"7. Any other useful note.",
|
|
34
|
+
].join("\n")
|
|
35
|
+
|
|
36
|
+
export async function pondering(ctx: any, { settings }: { settings: (agent: string) => Promise<{ keys: Record<string, string> }> }) {
|
|
37
|
+
const shared = ((globalThis as any).__agentPlusPondering ??= { busy: new Set<string>(), done: new Set<string>() })
|
|
38
|
+
shared.ready ??= new Map<string, string>() // backfill when an older load created the object
|
|
39
|
+
const busy = shared.busy as Set<string> // a ponder is running for this session
|
|
40
|
+
const done = shared.done as Set<string> // this session already pondered this turn
|
|
41
|
+
const ready = shared.ready as Map<string, string> // shared: any copy's hook can inject the note
|
|
42
|
+
|
|
43
|
+
const controller = new AbortController()
|
|
44
|
+
log(`pondering: listener started`)
|
|
45
|
+
void (async () => {
|
|
46
|
+
// Events arrive as { type, data: {...} }; the session ID is in data.
|
|
47
|
+
// session.idle is never emitted by the server; the real "run finished"
|
|
48
|
+
// event is session.execution.succeeded (payload { sessionID }).
|
|
49
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
50
|
+
const sessionID: string | undefined = event.data?.sessionID
|
|
51
|
+
// Every plugin copy sees every event. Handle each event exactly once,
|
|
52
|
+
// in the first copy that gets to it; the rest skip.
|
|
53
|
+
if (event.id === shared.lastEvent) continue
|
|
54
|
+
shared.lastEvent = event.id
|
|
55
|
+
if (event.type === "session.inbox.enqueued") {
|
|
56
|
+
// The NOTE we sent via session.generate arrives as a user message.
|
|
57
|
+
// Ignore it so it does not clear `done` and re-arm pondering.
|
|
58
|
+
if (event.data?.item?.payload?.text === NOTE) {
|
|
59
|
+
log(`pondering: swallowed own NOTE session=${sessionID}`)
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
log(`pondering: enqueued session=${sessionID}`)
|
|
63
|
+
done.delete(sessionID) // the user sent a message, so done is cleared and the session can ponder again
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
if (event.type !== "session.execution.succeeded") continue
|
|
67
|
+
log(`pondering: event type=${event.type} session=${sessionID}`)
|
|
68
|
+
if (!sessionID || busy.has(sessionID) || done.has(sessionID)) continue
|
|
69
|
+
busy.add(sessionID) // claim now, before any await, so the other copies skip
|
|
70
|
+
try {
|
|
71
|
+
const session = await ctx.session.get({ sessionID })
|
|
72
|
+
const { keys } = await settings(session.agent)
|
|
73
|
+
if (keys.pondering !== "on") {
|
|
74
|
+
busy.delete(sessionID)
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
log(`pondering: start session=${sessionID} agent=${session.agent}`)
|
|
78
|
+
setStatus(sessionID, "busy")
|
|
79
|
+
const { text } = await ctx.session.generate({ sessionID, prompt: NOTE })
|
|
80
|
+
let trimmed = String(text).trim()
|
|
81
|
+
if (trimmed === "SKIP") trimmed = "" // the model found nothing worth noting
|
|
82
|
+
setStatus(sessionID, "idle", trimmed) // sidebar shows the raw note (troubleshooting)
|
|
83
|
+
if (trimmed) {
|
|
84
|
+
ready.set(sessionID, trimmed)
|
|
85
|
+
log(`pondering: done session=${sessionID} chars=${trimmed.length} text=${trimmed}`)
|
|
86
|
+
} else {
|
|
87
|
+
log(`pondering: discarded session=${sessionID} text=${trimmed}`)
|
|
88
|
+
}
|
|
89
|
+
busy.delete(sessionID)
|
|
90
|
+
done.add(sessionID) // one ponder per user message
|
|
91
|
+
} catch (error) {
|
|
92
|
+
setStatus(sessionID, "idle")
|
|
93
|
+
busy.delete(sessionID)
|
|
94
|
+
done.add(sessionID) // even a failed ponder counts for this turn
|
|
95
|
+
log(`pondering: failed session=${sessionID} error=${String(error)}`)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
})().catch((error) => log(`pondering: listener died error=${String(error)}`))
|
|
99
|
+
|
|
100
|
+
// Inject the stored pondering into the next real model request of the session
|
|
101
|
+
// (generate uses its own hook, so this only runs for real turns).
|
|
102
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
103
|
+
const text = ready.get(event.sessionID)
|
|
104
|
+
if (!text) return
|
|
105
|
+
ready.delete(event.sessionID)
|
|
106
|
+
setStatus(event.sessionID, "idle") // the sidebar note is consumed with this message
|
|
107
|
+
appendBlock(event, "pondering", text, "Automatic pondering note, not from the user. The assistant pondered during idle time; these are its notes. Do not reply to it, but use it silently when answering.")
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
return () => controller.abort()
|
|
111
|
+
}
|
package/src/presets.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Preset texts for `reminder:` values. Reading order: the agent file's
|
|
2
|
+
// `reminder:` first, then AGENTS.md's. A value that is a preset name gets
|
|
3
|
+
// the plugin's text; long text is used as written; a short unknown value
|
|
4
|
+
// means off (logged, never an error).
|
|
5
|
+
import { log } from "./log"
|
|
6
|
+
|
|
7
|
+
const PRESETS: Record<string, string> = {
|
|
8
|
+
concise: [
|
|
9
|
+
'You are "Concise" agents, a helpful assistant.',
|
|
10
|
+
"Be concise in chat: short simple answers covering only the requested task. When request is unclear, say it so instead of guessing.",
|
|
11
|
+
"Always answer in plain simple English, no jargon.",
|
|
12
|
+
"Do NOT over-explain. Do not add details that are not asked. You are required to be short and quickly readable, NOT complete and comprehensive.",
|
|
13
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
14
|
+
"Never use chained shell commands (; or &&). Run one command per call; chaining causes permission and execution issues.",
|
|
15
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
16
|
+
].join("\n"),
|
|
17
|
+
"ultra-concise": [
|
|
18
|
+
'You are "Concise" agents, a helpful assistant.',
|
|
19
|
+
"Answer in one or two sentences. Only the requested fact or action, nothing else.",
|
|
20
|
+
"Plain simple English, no jargon, no headings, no lists.",
|
|
21
|
+
"Do not explain, summarize, or add details that are not asked.",
|
|
22
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
23
|
+
"NEVER use chained shell commands (; or &&). Run one command per call; chaining causes permission and execution issues.",
|
|
24
|
+
"NEVER ask 'want me to?' or 'shall I?' or offer to do something. When the user wants an action, just do it. Only ask questions that are technical and block you from proceeding.",
|
|
25
|
+
"NEVER ask 'what do you want?' or tell the user what to do. NEVER push the user to act. Say nothing to the user except precise technical content.",
|
|
26
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
27
|
+
].join("\n"),
|
|
28
|
+
creative: [
|
|
29
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
30
|
+
"Keep the user's meaning, facts and voice. Change only what the user asks for. When asked to write or rewrite, give the full text. Use plain, clear language unless the user asks for another style.",
|
|
31
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
32
|
+
].join("\n"),
|
|
33
|
+
off: "",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Resolves one `reminder:` value to its text ("" = off).
|
|
37
|
+
// Returns null when the value is not set, so the caller reads the next source.
|
|
38
|
+
export function reminderPreset(value: string | undefined) {
|
|
39
|
+
const text = value?.trim() ?? ""
|
|
40
|
+
if (!text) return null
|
|
41
|
+
if (text in PRESETS) return PRESETS[text]
|
|
42
|
+
if (text.split(/\s+/).length > 3) return text
|
|
43
|
+
log(`presets: unknown value=${text} -> off`)
|
|
44
|
+
return ""
|
|
45
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// Repetition guards: stop the model when it repeats itself.
|
|
2
|
+
// `max_word_repeat` — interrupt the reply when its text repeats back-to-back.
|
|
3
|
+
// `max_tool_repeat` — deny a tool after it is called the same way N times in a row.
|
|
4
|
+
import { log } from "./log"
|
|
5
|
+
import { realUserTexts } from "./context"
|
|
6
|
+
|
|
7
|
+
export interface RepetitionOptions {
|
|
8
|
+
/** Reads the agent's frontmatter keys. */
|
|
9
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// --- max_word_repeat: text repetition ---
|
|
13
|
+
|
|
14
|
+
export interface RepetitionHit {
|
|
15
|
+
/** The repeated piece, e.g. "parameter=". */
|
|
16
|
+
unit: string
|
|
17
|
+
/** How many times it appeared back-to-back. */
|
|
18
|
+
times: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DetectOptions {
|
|
22
|
+
/** Longest repeated piece to look for. Default 64 characters. */
|
|
23
|
+
maxUnit?: number
|
|
24
|
+
/** Minimum back-to-back repeats to call it repetition. Default 5. */
|
|
25
|
+
minTimes?: number
|
|
26
|
+
/** Minimum total characters (unit x times) to call it repetition. Default 40. */
|
|
27
|
+
minTotal?: number
|
|
28
|
+
/** Only the last this-many characters are examined. Default 4096. */
|
|
29
|
+
window?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Looks at the tail of `text` for a block of length `unit` repeated `minTimes`
|
|
33
|
+
// or more times in a row. Returns the longest/most repeated block found.
|
|
34
|
+
export function findRepetition(text: string, options: DetectOptions = {}): RepetitionHit | undefined {
|
|
35
|
+
const maxUnit = options.maxUnit ?? 64
|
|
36
|
+
const minTimes = options.minTimes ?? 5
|
|
37
|
+
const minTotal = options.minTotal ?? 40
|
|
38
|
+
const window = options.window ?? 4096
|
|
39
|
+
|
|
40
|
+
const tail = text.length > window ? text.slice(-window) : text
|
|
41
|
+
let best: RepetitionHit | undefined
|
|
42
|
+
|
|
43
|
+
for (let unit = 1; unit <= maxUnit; unit++) {
|
|
44
|
+
const limit = tail.length - unit * minTimes
|
|
45
|
+
if (limit < 0) break
|
|
46
|
+
for (let start = 0; start <= limit; start++) {
|
|
47
|
+
const block = tail.slice(start, start + unit)
|
|
48
|
+
let times = 1
|
|
49
|
+
let at = start + unit
|
|
50
|
+
while (at + unit <= tail.length && tail.startsWith(block, at)) {
|
|
51
|
+
times++
|
|
52
|
+
at += unit
|
|
53
|
+
}
|
|
54
|
+
if (times >= minTimes && times * unit >= minTotal) {
|
|
55
|
+
const hit = { unit: block, times }
|
|
56
|
+
if (!best || times * unit > best.times * best.unit.length) best = hit
|
|
57
|
+
}
|
|
58
|
+
if (times > 1) start = at - unit
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return best
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Pulls model words out of protocol text: every `"content":"..."` value,
|
|
65
|
+
// with JSON escapes decoded. Unfinished tail (partial value) stays in `rest`.
|
|
66
|
+
export function extractText(chunk: string): { text: string; rest: string } {
|
|
67
|
+
let text = ""
|
|
68
|
+
let i = 0
|
|
69
|
+
for (;;) {
|
|
70
|
+
const key = chunk.indexOf('"content":"', i)
|
|
71
|
+
if (key < 0) return { text, rest: chunk.slice(i) }
|
|
72
|
+
let j = key + '"content":"'.length
|
|
73
|
+
let value = ""
|
|
74
|
+
let closed = false
|
|
75
|
+
while (j < chunk.length) {
|
|
76
|
+
const c = chunk[j]
|
|
77
|
+
if (c === "\\") {
|
|
78
|
+
if (j + 1 >= chunk.length) break
|
|
79
|
+
const next = chunk[j + 1]
|
|
80
|
+
value += next === "n" ? "\n" : next === "t" ? "\t" : next
|
|
81
|
+
j += 2
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
if (c === '"') {
|
|
85
|
+
closed = true
|
|
86
|
+
j++
|
|
87
|
+
break
|
|
88
|
+
}
|
|
89
|
+
value += c
|
|
90
|
+
j++
|
|
91
|
+
}
|
|
92
|
+
if (!closed) return { text, rest: chunk.slice(key) }
|
|
93
|
+
text += value
|
|
94
|
+
i = j
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface ScanOptions {
|
|
99
|
+
/** Called at most once, on the first repetition found. */
|
|
100
|
+
onHit: (hit: RepetitionHit) => void
|
|
101
|
+
/** Scan when at least this many new characters arrived since last scan. Default 256. */
|
|
102
|
+
scanEvery?: number
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Wraps a model reply stream so the model's words can be scanned as they
|
|
106
|
+
// arrive. When the scanner says stop, onHit fires once; the stream keeps
|
|
107
|
+
// flowing (opencode's interrupt ends the run, not us).
|
|
108
|
+
export function scanResponse(response: Response, options: ScanOptions): Response {
|
|
109
|
+
if (!response.body) return response
|
|
110
|
+
const scanEvery = options.scanEvery ?? 256
|
|
111
|
+
const decoder = new TextDecoder()
|
|
112
|
+
let pending = ""
|
|
113
|
+
let words = ""
|
|
114
|
+
let sinceScan = 0
|
|
115
|
+
let fired = false
|
|
116
|
+
|
|
117
|
+
const check = (final: boolean) => {
|
|
118
|
+
if (fired) return
|
|
119
|
+
const hit = findRepetition(words)
|
|
120
|
+
if (!hit) return
|
|
121
|
+
fired = true
|
|
122
|
+
log(`repetition: hit unit=${JSON.stringify(hit.unit)} times=${hit.times} final=${final}`)
|
|
123
|
+
options.onHit(hit)
|
|
124
|
+
throw new Error(`agent-plus: anti-repetition stopped the reply ("${hit.unit}" repeated ${hit.times} times)`)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const checker = new TransformStream<Uint8Array, Uint8Array>({
|
|
128
|
+
transform(chunk, controller) {
|
|
129
|
+
if (sinceScan === 0 && words === "" && pending === "") log(`repetition: first chunk bytes=${chunk.byteLength}`)
|
|
130
|
+
if (fired) throw new Error("agent-plus: anti-repetition stopped the reply")
|
|
131
|
+
controller.enqueue(chunk)
|
|
132
|
+
const { text, rest } = extractText(pending + decoder.decode(chunk, { stream: true }))
|
|
133
|
+
pending = rest
|
|
134
|
+
if (!text) return
|
|
135
|
+
words += text
|
|
136
|
+
sinceScan += text.length
|
|
137
|
+
check(false)
|
|
138
|
+
},
|
|
139
|
+
flush() {
|
|
140
|
+
log(`repetition: stream end words=${words.length} fired=${fired}`)
|
|
141
|
+
check(true)
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
return new Response(response.body.pipeThrough(checker), {
|
|
146
|
+
status: response.status,
|
|
147
|
+
statusText: response.statusText,
|
|
148
|
+
headers: response.headers,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function maxWordRepeat(ctx: any, options: RepetitionOptions) {
|
|
153
|
+
return ctx.session.hook("http.response", async (event: any) => {
|
|
154
|
+
const { keys } = await options.settings(event.agent)
|
|
155
|
+
if (keys.max_word_repeat !== "on") return
|
|
156
|
+
log(`repetition: http.response fired session=${event.sessionID} agent=${event.agent}`)
|
|
157
|
+
const sessionID = event.sessionID
|
|
158
|
+
const stop = (hit: RepetitionHit) => {
|
|
159
|
+
log(`repetition: interrupt session=${sessionID} unit=${JSON.stringify(hit.unit)} times=${hit.times}`)
|
|
160
|
+
ctx.session.interrupt({ sessionID }).catch(() => {})
|
|
161
|
+
}
|
|
162
|
+
event.response = scanResponse(event.response, { onHit: stop })
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// --- max_tool_repeat: same tool call repeated ---
|
|
167
|
+
|
|
168
|
+
function countUserTurns(messages: any[]): number {
|
|
169
|
+
return realUserTexts(messages).length
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function maxToolRepeat(ctx: any, options: RepetitionOptions) {
|
|
173
|
+
const streaks = new Map<string, { call: string; count: number }>()
|
|
174
|
+
const turns = new Map<string, number>()
|
|
175
|
+
|
|
176
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
177
|
+
const key = String(event.sessionID)
|
|
178
|
+
const turn = countUserTurns(event.messages)
|
|
179
|
+
if (turns.get(key) !== turn) {
|
|
180
|
+
turns.set(key, turn)
|
|
181
|
+
streaks.delete(key)
|
|
182
|
+
}
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
186
|
+
if (!event.agent) return
|
|
187
|
+
if (event.effect === "deny") return
|
|
188
|
+
const { keys } = await options.settings(event.agent)
|
|
189
|
+
const max = Number(keys.max_tool_repeat)
|
|
190
|
+
if (!Number.isInteger(max) || max < 1 || event.action === "task") return
|
|
191
|
+
const key = String(event.sessionID)
|
|
192
|
+
// Same tool AND same arguments: only then it is a repeat.
|
|
193
|
+
const call = `${event.action}\u0000${(event.resources ?? []).join("\u0000")}`
|
|
194
|
+
const prev = streaks.get(key)
|
|
195
|
+
const count = prev && prev.call === call ? prev.count + 1 : 1
|
|
196
|
+
streaks.set(key, { call, count })
|
|
197
|
+
if (count <= max) return
|
|
198
|
+
streaks.set(key, { call, count: 0 })
|
|
199
|
+
event.effect = "deny"
|
|
200
|
+
event.message = `You already used '${event.action}' the same way ${max} times in a row in this message. You are probably stuck in a doom loop. Try something else or report the issue to the user.`
|
|
201
|
+
log(`repetition: tool denied action=${event.action} session=${key} count=${count} max=${max}`)
|
|
202
|
+
})
|
|
203
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { isSafeToolCall } from "./safetoolcall"
|
|
3
|
+
|
|
4
|
+
const safe = (cmd: string) => isSafeToolCall("shell", [cmd])
|
|
5
|
+
|
|
6
|
+
test("read-only tools are safe", () => {
|
|
7
|
+
for (const a of ["read", "glob", "grep", "websearch"]) expect(isSafeToolCall(a, [])).toBe(true)
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
test("safe shell commands", () => {
|
|
11
|
+
for (const c of ["ls", "cat f", "git status", "git log --oneline", "docker compose ps", "npm ls", "node --version", "psql -c 'select 1'"])
|
|
12
|
+
expect(safe(c)).toBe(true)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
test("unsafe commands and flags", () => {
|
|
16
|
+
for (const c of ["rm -rf /", "git branch -D x", "find . -exec rm {} ;", "sort -o out f", "git log --output=f", "node script.js", "env rm x", "ssh -o ProxyCommand=x host"])
|
|
17
|
+
expect(safe(c)).toBe(false)
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
test("compound commands need every part safe", () => {
|
|
21
|
+
expect(isSafeToolCall("shell", ["ls", "cat f"])).toBe(true)
|
|
22
|
+
expect(isSafeToolCall("shell", ["ls", "rm x"])).toBe(false)
|
|
23
|
+
expect(safe("echo $(whoami)")).toBe(false)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test("corner cases", () => {
|
|
27
|
+
expect(isSafeToolCall("shell", [])).toBe(false) // no resources
|
|
28
|
+
expect(safe("")).toBe(false) // empty command
|
|
29
|
+
expect(safe("ls; rm x")).toBe(false) // semicolon hides a write
|
|
30
|
+
expect(safe("cat `whoami`")).toBe(false) // backtick substitution
|
|
31
|
+
expect(safe("git status --output=f")).toBe(false) // git write flag
|
|
32
|
+
expect(safe("docker compose down")).toBe(false) // not a read subcommand
|
|
33
|
+
expect(safe("sqlite3 db '.dump'")).toBe(false) // not a read-only dot
|
|
34
|
+
expect(safe("ssh host")).toBe(false) // bare ssh is a shell
|
|
35
|
+
expect(safe("ssh host ls")).toBe(true) // remote read command
|
|
36
|
+
})
|
|
@@ -139,7 +139,7 @@ function safeSsh(args: string[]): boolean {
|
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
// Is this permission event safe to allow? `action` and `resources` come from the hook event.
|
|
142
|
-
export function
|
|
142
|
+
export function isSafeToolCall(action: string, resources: readonly string[]): boolean {
|
|
143
143
|
if (SAFE_ACTIONS.has(action)) return true
|
|
144
144
|
if (action !== "shell") return false
|
|
145
145
|
// The scanner splits compound commands into several resources: every part must be safe.
|
package/src/tui.tsx
CHANGED
|
@@ -1,19 +1,39 @@
|
|
|
1
1
|
/** @jsxImportSource @opentui/solid */
|
|
2
2
|
import path from "node:path"
|
|
3
|
-
import {
|
|
3
|
+
import { readFileSync, unwatchFile, watchFile } from "node:fs"
|
|
4
|
+
import { createEffect, createMemo, createResource, createSignal, For, Show } from "solid-js"
|
|
4
5
|
import { agentFile, allAgentFiles, BODY, frontmatter, problems, read, requestValue } from "./frontmatter"
|
|
6
|
+
import { folder, log } from "./log"
|
|
7
|
+
import { reminderPreset } from "./presets"
|
|
5
8
|
|
|
6
9
|
// At start, shows a warning toast for every agent .md file with problems, or a "loaded" toast when there are none.
|
|
7
10
|
// Adds an "Agent-plus" section to the sidebar with the agent-plus settings of the session's agent.
|
|
8
11
|
// The sidebar reads the agent file again when the session's agent changes or opencode reports an agent file change.
|
|
12
|
+
const onOff = (v: string | undefined, on = "on") => (v === on ? "on" : "off")
|
|
13
|
+
|
|
9
14
|
function sidebarLines(keys: Record<string, string>) {
|
|
10
|
-
const lines
|
|
15
|
+
const lines: string[] = []
|
|
16
|
+
const reminder = reminderPreset(keys.reminder ?? "")
|
|
17
|
+
lines.push(reminder ? `reminder: ${keys.reminder}` : "reminder: off")
|
|
18
|
+
lines.push(`safe_commands: ${keys.safe_commands === "none" ? "off" : "on"}`)
|
|
19
|
+
lines.push(`max_word_repeat: ${onOff(keys.max_word_repeat)}`)
|
|
20
|
+
lines.push(`max_tool_repeat: ${keys.max_tool_repeat || "off"}`)
|
|
21
|
+
lines.push(
|
|
22
|
+
`on_error_command: ${keys.on_error_command ? keys.on_error_command.split("\n")[0].trim() + (keys.on_error_command.includes("\n") ? " …" : "") : "off"}`,
|
|
23
|
+
)
|
|
24
|
+
lines.push(`manual_green_light: ${onOff(keys.manual_green_light)}`)
|
|
25
|
+
lines.push(`auto_green_light: ${onOff(keys.auto_green_light)}`)
|
|
26
|
+
lines.push(`pondering: ${onOff(keys.pondering)}`)
|
|
27
|
+
if ("reasoning_effort" in keys && "value" in requestValue("reasoning_effort", keys.reasoning_effort))
|
|
28
|
+
lines.push(`reasoning_effort: ${keys.reasoning_effort}`)
|
|
29
|
+
for (const k of BODY) {
|
|
30
|
+
if (k === "reasoning_effort" || !(k in keys)) continue
|
|
31
|
+
const result = requestValue(k, keys[k])
|
|
32
|
+
if ("value" in result) lines.push(`${k}: ${keys[k]}`)
|
|
33
|
+
else lines.push(`${k}: ${keys[k]} (ERR: out of range!)`)
|
|
34
|
+
}
|
|
11
35
|
if (keys.enable_thinking === "true" || keys.enable_thinking === "false")
|
|
12
36
|
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
37
|
return lines
|
|
18
38
|
}
|
|
19
39
|
|
|
@@ -21,11 +41,13 @@ export default {
|
|
|
21
41
|
id: "agent-plus",
|
|
22
42
|
async setup(ctx: any) {
|
|
23
43
|
const directory = ctx.location?.directory ?? process.cwd()
|
|
44
|
+
log(`tui: setup directory=${directory} toast=${typeof ctx.ui?.toast?.show}`)
|
|
24
45
|
let warned = false
|
|
25
46
|
for (const file of await allAgentFiles(directory)) {
|
|
26
47
|
const found = await problems(file, frontmatter(await read(file)))
|
|
27
48
|
if (!found.length) continue
|
|
28
49
|
warned = true
|
|
50
|
+
log(`tui: toast warning file=${file} problems=${found.join("; ")}`)
|
|
29
51
|
ctx.ui.toast.show({
|
|
30
52
|
title: "agent-plus",
|
|
31
53
|
message: `Problems in ${path.basename(file)}:\n${found.join("\n")}`,
|
|
@@ -33,11 +55,26 @@ export default {
|
|
|
33
55
|
duration: 7000,
|
|
34
56
|
})
|
|
35
57
|
}
|
|
36
|
-
if (!warned)
|
|
58
|
+
if (!warned) {
|
|
59
|
+
log("tui: toast loaded")
|
|
60
|
+
ctx.ui.toast.show({ message: "agent-plus is loaded", variant: "info" })
|
|
61
|
+
}
|
|
37
62
|
|
|
38
63
|
const [agentsVersion, setAgentsVersion] = createSignal(0)
|
|
39
64
|
const stop = ctx.data.on("agent.updated", () => setAgentsVersion((v) => v + 1))
|
|
40
65
|
|
|
66
|
+
// Live pondering state written by the server plugin: { sessionID: "busy" | "idle" }
|
|
67
|
+
const statusFile = path.join(folder, "pondering.status")
|
|
68
|
+
const [statuses, setStatuses] = createSignal<Record<string, string>>({})
|
|
69
|
+
const readStatus = () => {
|
|
70
|
+
try {
|
|
71
|
+
setStatuses(JSON.parse(readFileSync(statusFile, "utf8")))
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
watchFile(statusFile, { interval: 300 }, readStatus)
|
|
75
|
+
const [frame, setFrame] = createSignal(0) // spinner frame counter
|
|
76
|
+
const timer = setInterval(() => setFrame((f) => f + 1), 80)
|
|
77
|
+
|
|
41
78
|
ctx.ui.slot({
|
|
42
79
|
append: "sidebar.content",
|
|
43
80
|
render: (props: { sessionID: string }) => {
|
|
@@ -47,18 +84,43 @@ export default {
|
|
|
47
84
|
() => agent() && { agent: agent()!, version: agentsVersion() },
|
|
48
85
|
async ({ agent }) => sidebarLines(frontmatter((await agentFile(directory, agent)).text)),
|
|
49
86
|
)
|
|
87
|
+
// Live line: spinner while pondering, "on (idle)" when enabled and done, "off" when disabled.
|
|
88
|
+
const shown = createMemo(() => {
|
|
89
|
+
const ls = lines() ?? []
|
|
90
|
+
if (!ls.includes("pondering: on")) return ls
|
|
91
|
+
const st = statuses()[props.sessionID]
|
|
92
|
+
const busy = st?.state === "busy"
|
|
93
|
+
const text = busy ? `pondering: ${"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"[frame() % 10]}` : "pondering: on (idle)"
|
|
94
|
+
const out = ls.map((l) => (l === "pondering: on" ? text : l))
|
|
95
|
+
if (!busy && st?.note) out.push("", "Pondering:", ...String(st.note).split("\n"))
|
|
96
|
+
return out
|
|
97
|
+
})
|
|
50
98
|
return (
|
|
51
|
-
<Show when={
|
|
99
|
+
<Show when={shown().length}>
|
|
52
100
|
<box>
|
|
53
101
|
<text fg={theme.text.base}>
|
|
54
102
|
<b>Agent-plus</b>
|
|
55
103
|
</text>
|
|
56
|
-
<For each={
|
|
104
|
+
<For each={shown()}>
|
|
105
|
+
{(line) =>
|
|
106
|
+
line === "Pondering:" ? (
|
|
107
|
+
<text fg={theme.text.base}>
|
|
108
|
+
<b>Pondering:</b>
|
|
109
|
+
</text>
|
|
110
|
+
) : (
|
|
111
|
+
<text fg={theme.text.muted}>{line}</text>
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
</For>
|
|
57
115
|
</box>
|
|
58
116
|
</Show>
|
|
59
117
|
)
|
|
60
118
|
},
|
|
61
119
|
})
|
|
62
|
-
return
|
|
120
|
+
return () => {
|
|
121
|
+
clearInterval(timer)
|
|
122
|
+
unwatchFile(statusFile, readStatus)
|
|
123
|
+
stop()
|
|
124
|
+
}
|
|
63
125
|
},
|
|
64
126
|
}
|