opencode-agent-plus 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -30
- package/package.json +4 -2
- package/src/clockwork.ts +60 -2
- package/src/context.ts +3 -9
- package/src/frontmatter.test.ts +2 -4
- package/src/frontmatter.ts +102 -10
- package/src/httprequest.ts +8 -1
- package/src/index.ts +14 -4
- package/src/presets.ts +6 -20
- package/src/probe.ts +156 -0
- package/src/repetition.ts +2 -2
- package/src/tooloverrides.ts +48 -0
- package/src/tui.tsx +269 -19
- package/src/verifier.ts +99 -0
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Per-agent reminders, request settings and safe-command auto-allow for [OpenCode](https://opencode.ai) v2.
|
|
4
4
|
|
|
5
|
-
Set `chat_template_kwargs` (like `enable_thinking`), sampling settings (`temperature`, `top_p`, `
|
|
5
|
+
Set `chat_template_kwargs` (like `enable_thinking`), sampling settings (`temperature`, `top_p`, `min_p`,
|
|
6
6
|
penalties) and a system reminder for each OpenCode agent. Works with llama.cpp, LiteLLM and other OpenAI-compatible
|
|
7
7
|
servers, and with thinking models like Qwen.
|
|
8
8
|
|
|
@@ -12,8 +12,6 @@ with `shell: ask` in your permissions you get no prompt window for them — ever
|
|
|
12
12
|
OpenCode v2 drops request settings such as `temperature` for OpenAI-compatible providers, and has no per-agent
|
|
13
13
|
reminder. agent-plus reads extra keys from the agent's `.md` file and applies them to every model request.
|
|
14
14
|
|
|
15
|
-
Tested with OpenCode 2.2.0 and llama.cpp behind LiteLLM.
|
|
16
|
-
|
|
17
15
|

|
|
18
16
|
|
|
19
17
|
## Install
|
|
@@ -80,28 +78,40 @@ You help the user write and edit text.
|
|
|
80
78
|
|
|
81
79
|
| Key | Value | Effect |
|
|
82
80
|
| --- | --- | --- |
|
|
83
|
-
| `reminder` | `concise`, `
|
|
81
|
+
| `reminder` | `concise`, `off`, or text (one line or a `\|` block) | Preset or custom reminder, added as the last message of every model request |
|
|
84
82
|
| `on_error_command` | shell command, one line or a `\|` block | Run when a request fails with a connection error (server off), then retry |
|
|
85
|
-
| `safe_commands` | `
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
83
|
+
| `safe_commands` | `off` (default: on) | Turn safe-command auto-allow off for this agent |
|
|
84
|
+
| `max_word_repeat` | `on` or `off` (default: off) | Stop the reply when the model repeats the same text |
|
|
85
|
+
| `max_tool_repeat` | whole number | Max times the same tool call may repeat in a row |
|
|
88
86
|
| `manual_green_light` | `on` or `off` (default: off) | Tools run only when your message ends with an approval word |
|
|
89
87
|
| `manual_green_light_words` | comma-separated words | The approval words for `manual_green_light` |
|
|
90
88
|
| `auto_green_light` | `on` or `off` (default: off) | The model checks itself before the first tool call of each turn |
|
|
91
|
-
| `temperature` | number | Request body |
|
|
92
|
-
| `top_p` | number | Request body |
|
|
93
|
-
| `top_k` | whole number | Request body |
|
|
94
|
-
| `min_p` | number | Request body |
|
|
95
|
-
| `presence_penalty` | number | Request body |
|
|
96
|
-
| `repeat_penalty` | number | Request body (llama.cpp) |
|
|
97
|
-
| `repetition_penalty` | number | Request body (vLLM, HF) |
|
|
89
|
+
| `temperature` | number from `0` to `1` | Request body |
|
|
98
90
|
| `max_completion_tokens` | whole number | Request body |
|
|
99
|
-
| `reasoning_budget_tokens` | whole number | Request body
|
|
100
|
-
| `reasoning_effort` | `
|
|
91
|
+
| `reasoning_budget_tokens` | whole number | Request body |
|
|
92
|
+
| `reasoning_effort` | `low`, `medium`, `high` or `xhigh` | Request body |
|
|
101
93
|
| `enable_thinking` | `true` or `false` | Request body, under `chat_template_kwargs` |
|
|
94
|
+
| `tools_override` | path to a JSON file (relative to the agent file) | Replace tool descriptions with your own |
|
|
95
|
+
| `pondering` | `on` or `off` (default: off) | Run a quiet thinking request when the session goes idle |
|
|
96
|
+
| `misplaced_tag_filter` | `on` or `off` (default: off) | Replace leaked tag signs in thinking/message text |
|
|
97
|
+
| `show_settings_on_sidebar` | `on` or `off` (default: on) | Show this agent's settings in the TUI sidebar |
|
|
98
|
+
| `clockwork` | `on` or `off` (default: off) | Run the agent hands-off with auto-continue |
|
|
102
99
|
|
|
103
100
|
Names are sent as written. A setting with a wrong value is not sent.
|
|
104
101
|
|
|
102
|
+
## Settings menu
|
|
103
|
+
|
|
104
|
+
Type `/agent-plus` in the chat input to open a settings menu for the current agent. Every key from the table above
|
|
105
|
+
has a row:
|
|
106
|
+
|
|
107
|
+
- Toggles (`on` / `off`) flip with **space**.
|
|
108
|
+
- Choice rows (`reasoning_effort`, `temperature`, …) offer the valid values in a picker.
|
|
109
|
+
- `reminder` offers the presets, `edit…` for your own text, and `off`.
|
|
110
|
+
- Every row has a `default (…)` option that removes the key from the file, so the model default applies.
|
|
111
|
+
|
|
112
|
+
Choices are written straight into the agent's `.md` frontmatter (agent-plus keys are kept first, in menu order), so
|
|
113
|
+
the sidebar and the file always match.
|
|
114
|
+
|
|
105
115
|
## Reminders
|
|
106
116
|
|
|
107
117
|
### Why
|
|
@@ -113,12 +123,9 @@ the most.
|
|
|
113
123
|
|
|
114
124
|
### How
|
|
115
125
|
|
|
116
|
-
Before every model request, agent-plus adds one message at the end of the conversation with
|
|
117
|
-
|
|
118
|
-
1. the agent's `reminder`
|
|
119
|
-
2. the `reminder` from `AGENTS.md` in the project folder, for every agent
|
|
126
|
+
Before every model request, agent-plus adds one message at the end of the conversation with the agent's `reminder`.
|
|
120
127
|
|
|
121
|
-
`reminder` takes a preset name (`concise`, `
|
|
128
|
+
`reminder` takes a preset name (`concise`, `off`) for wording held in
|
|
122
129
|
the plugin, or your own text (more than 3 words). A short unknown value means
|
|
123
130
|
`off`.
|
|
124
131
|
|
|
@@ -145,7 +152,7 @@ chunks, like llama.cpp with `--cache-reuse`, may recover part of it.
|
|
|
145
152
|
At start, a toast lists problems in agent files:
|
|
146
153
|
|
|
147
154
|
- misspelled keys, like `temprature → temperature`
|
|
148
|
-
- wrong values, like `
|
|
155
|
+
- wrong values, like `max_completion_tokens: must be a whole number`
|
|
149
156
|
|
|
150
157
|
Unknown keys that don't look like a misspelling are left alone, so other plugins can add their own keys.
|
|
151
158
|
With no problems, the toast says "agent-plus is loaded".
|
|
@@ -186,16 +193,16 @@ It never overrides a configured `deny`, and only turns `ask` into `allow`. Doubt
|
|
|
186
193
|
Known unsafe flags are refused, e.g. `find -exec`, `env <cmd>`, `rg --pre`, `sort -o`, `git branch -D`,
|
|
187
194
|
`git log --output=`, `ssh -o ProxyCommand=`.
|
|
188
195
|
|
|
189
|
-
Turn it off for one agent with `safe_commands:
|
|
196
|
+
Turn it off for one agent with `safe_commands: off` in its frontmatter.
|
|
190
197
|
|
|
191
198
|
## Anti-repetition
|
|
192
199
|
|
|
193
|
-
With `
|
|
200
|
+
With `max_word_repeat: on`, agent-plus watches the model's reply as it streams. When the same stretch of text
|
|
194
201
|
repeats 5 or more times, the reply is cut and the session is interrupted, instead of filling up with garbage.
|
|
195
202
|
|
|
196
203
|
## Anti-loop
|
|
197
204
|
|
|
198
|
-
With `
|
|
205
|
+
With `max_tool_repeat: 5`, the same tool call (same tool, same arguments) may repeat at most 5 times in a row.
|
|
199
206
|
The 6th is denied with a message telling the model to stop. The count resets when you send a new message.
|
|
200
207
|
|
|
201
208
|
## Pondering
|
|
@@ -222,13 +229,37 @@ is always allowed. Set your own words with `manual_green_light_words: yes, do, g
|
|
|
222
229
|
With `auto_green_light: on`, the model checks itself before the first tool call of each turn: it must allow the call
|
|
223
230
|
and state its plan, or explain why it cannot. The check fires once per turn and is not saved in the chat history.
|
|
224
231
|
|
|
232
|
+
## Tool overrides
|
|
233
|
+
|
|
234
|
+
With `tools_override: <file>.json` (relative to the agent file), tool
|
|
235
|
+
descriptions are replaced with the ones from that file. The file maps tool
|
|
236
|
+
names to replacement descriptions:
|
|
237
|
+
|
|
238
|
+
```json
|
|
239
|
+
{
|
|
240
|
+
"bash": "Run a shell command.",
|
|
241
|
+
"read": "Read a file."
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Tools not listed keep their original description. The file is re-read only when
|
|
246
|
+
it changes on disk, so the prompt cache stays warm.
|
|
247
|
+
|
|
225
248
|
## Clockwork
|
|
226
249
|
|
|
227
|
-
With `clockwork: on`, the agent runs hands-off. Every permission ask is denied
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
250
|
+
With `clockwork: on`, the agent runs hands-off. Every permission ask is denied.
|
|
251
|
+
After each finished turn a judge request reads the plan and the work so far and
|
|
252
|
+
replies with one word:
|
|
253
|
+
|
|
254
|
+
- `CONTINUE` — the plugin sends a fresh "keep going" message. Every 7–10 turns
|
|
255
|
+
it instead nudges the agent to re-read its plan document (PLAN.md, TODO.md,
|
|
256
|
+
etc.) and list remaining work.
|
|
257
|
+
- `WAIT` — the agent is waiting on a background job, so the plugin waits 30s
|
|
258
|
+
and judges again.
|
|
259
|
+
- `DONE` — the plugin sends a wrap-up message. The next `DONE` sends a final
|
|
260
|
+
"JOB COMPLETED" line and stops the loop.
|
|
261
|
+
|
|
262
|
+
Only agents with `clockwork: on` are affected.
|
|
232
263
|
|
|
233
264
|
## Notes
|
|
234
265
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-agent-plus",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "OpenCode plugin: safe-command auto-allow (no prompt for read-only calls), per-agent chat_template_kwargs (enable_thinking), sampling settings and system reminders from agent frontmatter. For llama.cpp, LiteLLM and OpenAI-compatible providers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Anoosh Ahmadi",
|
|
@@ -28,13 +28,15 @@
|
|
|
28
28
|
"temperature",
|
|
29
29
|
"sampling",
|
|
30
30
|
"top_p",
|
|
31
|
-
"top_k",
|
|
32
31
|
"min_p",
|
|
33
32
|
"system-reminder",
|
|
34
33
|
"reminder",
|
|
35
34
|
"qwen"
|
|
36
35
|
],
|
|
37
36
|
"type": "module",
|
|
37
|
+
"scripts": {
|
|
38
|
+
"test": "bun test ./src"
|
|
39
|
+
},
|
|
38
40
|
"exports": {
|
|
39
41
|
".": "./src/index.ts",
|
|
40
42
|
"./tui": "./src/tui.tsx"
|
package/src/clockwork.ts
CHANGED
|
@@ -15,10 +15,34 @@ const META =
|
|
|
15
15
|
"progress. Do not greet, do not ask questions, do not repeat prior work. " +
|
|
16
16
|
"Reply with that one sentence only."
|
|
17
17
|
|
|
18
|
+
const PLAN_META =
|
|
19
|
+
"You are nudging an autonomous coding agent that just stopped. Write ONE " +
|
|
20
|
+
"short imperative sentence telling it to read the project's plan document " +
|
|
21
|
+
"(PLAN.md, TODO.md, DESIGN.md or similar) and list the work that is still " +
|
|
22
|
+
"left. Do not greet, do not ask questions. Reply with that one sentence only."
|
|
23
|
+
|
|
24
|
+
const JUDGE_META =
|
|
25
|
+
"Review the plan and the work done so far. Reply with ONE word: DONE, WAIT, " +
|
|
26
|
+
"or CONTINUE. Say DONE if every plan item is complete and the acting agent is " +
|
|
27
|
+
"asking to conclude. Say WAIT if the agent is waiting for a background job or " +
|
|
28
|
+
"long task to finish. Otherwise say CONTINUE."
|
|
29
|
+
|
|
30
|
+
const WAIT_MS = 30_000
|
|
31
|
+
|
|
32
|
+
const WRAPUP = "Wrap up now: summarize what was done and stop."
|
|
33
|
+
|
|
34
|
+
const COMPLETED = "==================== CLOCKWORK: JOB COMPLETED ===================="
|
|
35
|
+
|
|
36
|
+
const nextTarget = () => 7 + Math.floor(Math.random() * 4) // 7, 8, 9 or 10
|
|
37
|
+
|
|
18
38
|
export async function clockwork(ctx: any, { settings }: { settings: (agent: string) => Promise<{ keys: Record<string, string> }> }) {
|
|
19
|
-
const shared = ((globalThis as any).__agentPlusClockwork ??= { running: new Set<string>(), denied: new Set<string>() })
|
|
39
|
+
const shared = ((globalThis as any).__agentPlusClockwork ??= { running: new Set<string>(), denied: new Set<string>(), stopped: new Set<string>(), wrapped: new Set<string>(), turns: new Map<string, number>(), targets: new Map<string, number>() })
|
|
20
40
|
const running = shared.running as Set<string> // a keep-going prompt is in flight
|
|
21
41
|
const denied = shared.denied as Set<string> // this turn had a denied ask
|
|
42
|
+
const stopped = shared.stopped as Set<string> // the judge said the work is done
|
|
43
|
+
const wrapped = shared.wrapped as Set<string> // already sent the wrap-up message
|
|
44
|
+
const turns = shared.turns as Map<string, number> // turns since last plan check
|
|
45
|
+
const targets = shared.targets as Map<string, number> // when the next plan check fires
|
|
22
46
|
|
|
23
47
|
// Deny every permission ask for clockwork agents.
|
|
24
48
|
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
@@ -46,10 +70,44 @@ export async function clockwork(ctx: any, { settings }: { settings: (agent: stri
|
|
|
46
70
|
const session = await ctx.session.get({ sessionID })
|
|
47
71
|
const { keys } = await settings(session.agent)
|
|
48
72
|
if (keys.clockwork !== "on") continue
|
|
73
|
+
if (stopped.has(sessionID)) continue
|
|
49
74
|
running.add(sessionID)
|
|
50
75
|
const wasDenied = denied.delete(sessionID)
|
|
51
76
|
|
|
52
|
-
|
|
77
|
+
// Judge: is the work finished, or waiting on a job? Read-only, nothing saved.
|
|
78
|
+
// Empty reply means no verdict, so retry once. WAIT means pause and re-judge.
|
|
79
|
+
let verdict: unknown
|
|
80
|
+
for (;;) {
|
|
81
|
+
verdict = (await ctx.session.generate({ sessionID, prompt: JUDGE_META })).text
|
|
82
|
+
if (!String(verdict).trim()) {
|
|
83
|
+
log(`clockwork: judge empty, retrying session=${sessionID}`)
|
|
84
|
+
verdict = (await ctx.session.generate({ sessionID, prompt: JUDGE_META })).text
|
|
85
|
+
}
|
|
86
|
+
log(`clockwork: judge session=${sessionID} reply=${String(verdict).trim()}`)
|
|
87
|
+
if (!/\bWAIT\b/i.test(String(verdict))) break
|
|
88
|
+
log(`clockwork: waiting session=${sessionID} ${WAIT_MS}ms`)
|
|
89
|
+
await new Promise((r) => setTimeout(r, WAIT_MS))
|
|
90
|
+
}
|
|
91
|
+
if (/\bDONE\b/i.test(String(verdict))) {
|
|
92
|
+
if (!wrapped.has(sessionID)) {
|
|
93
|
+
wrapped.add(sessionID)
|
|
94
|
+
log(`clockwork: wrap-up session=${sessionID}`)
|
|
95
|
+
await ctx.session.prompt({ sessionID, text: WRAPUP, delivery: "steer" })
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
stopped.add(sessionID)
|
|
99
|
+
log(`clockwork: finished session=${sessionID} verdict=${String(verdict).trim()}`)
|
|
100
|
+
await ctx.session.prompt({ sessionID, text: COMPLETED, delivery: "steer" })
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const count = (turns.get(sessionID) ?? 0) + 1
|
|
105
|
+
const target = targets.get(sessionID) ?? nextTarget()
|
|
106
|
+
const checkPlan = count >= target
|
|
107
|
+
turns.set(sessionID, checkPlan ? 0 : count)
|
|
108
|
+
if (checkPlan) targets.set(sessionID, nextTarget())
|
|
109
|
+
|
|
110
|
+
const { text: next } = await ctx.session.generate({ sessionID, prompt: checkPlan ? PLAN_META : META })
|
|
53
111
|
const text = String(next).trim() || FALLBACK
|
|
54
112
|
|
|
55
113
|
const final = wasDenied ? `Request is rejected. ${text}` : text
|
package/src/context.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
// Owns the `context` hook: appends hidden blocks (like <system-reminder>)
|
|
2
2
|
// to the messages of every model request.
|
|
3
|
-
import path from "node:path"
|
|
4
|
-
import { frontmatter, read } from "./frontmatter"
|
|
5
3
|
import { reminderPreset } from "./presets"
|
|
6
4
|
|
|
7
5
|
// Appends `text` wrapped in <tag> as a user message the model must not reply to.
|
|
@@ -45,11 +43,7 @@ export function realUserTexts(messages: any[]): string[] {
|
|
|
45
43
|
return texts
|
|
46
44
|
}
|
|
47
45
|
|
|
48
|
-
// The reminder text for a request: the agent file's `reminder
|
|
49
|
-
|
|
50
|
-
|
|
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) ?? ""
|
|
46
|
+
// The reminder text for a request: the agent file's `reminder:`, or off ("").
|
|
47
|
+
export async function reminderText(keys: Record<string, string>) {
|
|
48
|
+
return reminderPreset(keys.reminder) ?? ""
|
|
55
49
|
}
|
package/src/frontmatter.test.ts
CHANGED
|
@@ -8,10 +8,8 @@ test("parses keys and | blocks", () => {
|
|
|
8
8
|
})
|
|
9
9
|
|
|
10
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
11
|
expect(requestValue("enable_thinking", "true")).toEqual({ value: true })
|
|
14
|
-
expect(requestValue("reasoning_effort", "bad")).toEqual({ error: "reasoning_effort: must be one of
|
|
12
|
+
expect(requestValue("reasoning_effort", "bad")).toEqual({ error: "reasoning_effort: must be one of low, medium, high, xhigh" })
|
|
15
13
|
})
|
|
16
14
|
|
|
17
15
|
test("no frontmatter, empty, and unknown keys", () => {
|
|
@@ -21,7 +19,7 @@ test("no frontmatter, empty, and unknown keys", () => {
|
|
|
21
19
|
})
|
|
22
20
|
|
|
23
21
|
test("reports misspelled keys and wrong values", async () => {
|
|
24
|
-
const found = await problems(
|
|
22
|
+
const found = await problems({ temprature: "1", max_word_repeat: "maybe" })
|
|
25
23
|
expect(found).toContain("temprature → temperature")
|
|
26
24
|
expect(found).toContain("max_word_repeat: must be on or off")
|
|
27
25
|
})
|
package/src/frontmatter.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readdir, readFile } from "node:fs/promises"
|
|
1
|
+
import { readdir, readFile, writeFile } from "node:fs/promises"
|
|
2
2
|
import { homedir } from "node:os"
|
|
3
3
|
import path from "node:path"
|
|
4
4
|
|
|
@@ -14,16 +14,16 @@ export const BODY = [
|
|
|
14
14
|
"reasoning_effort",
|
|
15
15
|
]
|
|
16
16
|
export const TEMPLATE_KWARGS = ["enable_thinking"]
|
|
17
|
-
const WHOLE_NUMBERS = ["
|
|
17
|
+
const WHOLE_NUMBERS = ["max_completion_tokens", "reasoning_budget_tokens"]
|
|
18
18
|
// Safe value ranges for the sampling settings.
|
|
19
19
|
const RANGES: Record<string, [number, number]> = {
|
|
20
|
-
temperature: [0
|
|
20
|
+
temperature: [0, 1],
|
|
21
21
|
max_completion_tokens: [1024, 32768],
|
|
22
22
|
reasoning_budget_tokens: [1024, 8192],
|
|
23
23
|
}
|
|
24
24
|
// Settings sent as text, with the values they accept.
|
|
25
25
|
const CHOICES: Record<string, string[]> = {
|
|
26
|
-
reasoning_effort: ["
|
|
26
|
+
reasoning_effort: ["low", "medium", "high", "xhigh"],
|
|
27
27
|
}
|
|
28
28
|
const OPENCODE_KEYS = [
|
|
29
29
|
"description",
|
|
@@ -37,7 +37,7 @@ const OPENCODE_KEYS = [
|
|
|
37
37
|
"disabled",
|
|
38
38
|
"request",
|
|
39
39
|
]
|
|
40
|
-
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "on_error_command", "safe_commands", "max_word_repeat", "max_tool_repeat", "manual_green_light", "manual_green_light_words", "auto_green_light", "pondering", "misplaced_tag_filter", "clockwork", ...BODY, ...TEMPLATE_KWARGS])
|
|
40
|
+
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "on_error_command", "safe_commands", "max_word_repeat", "max_tool_repeat", "manual_green_light", "manual_green_light_words", "auto_green_light", "pondering", "misplaced_tag_filter", "clockwork", "verifier", "verifier_max_nags", "tools_override", "show_settings_on_sidebar", ...BODY, ...TEMPLATE_KWARGS])
|
|
41
41
|
|
|
42
42
|
export const read = (file: string) => readFile(file, "utf8").catch(() => "")
|
|
43
43
|
|
|
@@ -90,6 +90,90 @@ export function frontmatter(text: string): Record<string, string> {
|
|
|
90
90
|
return result
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
// Rewrites one top-level `key: value` in the frontmatter, adding it when missing.
|
|
94
|
+
// A previous `|` block value is replaced by the new single line.
|
|
95
|
+
// The menu order of agent-plus settings; setFrontmatter keeps these keys
|
|
96
|
+
// first in the frontmatter, in this order. Other keys keep their order below.
|
|
97
|
+
const SETTING_ORDER = [
|
|
98
|
+
"reminder",
|
|
99
|
+
"safe_commands",
|
|
100
|
+
"verifier",
|
|
101
|
+
"verifier_max_nags",
|
|
102
|
+
"pondering",
|
|
103
|
+
"clockwork",
|
|
104
|
+
"tools_override",
|
|
105
|
+
"on_error_command",
|
|
106
|
+
"manual_green_light",
|
|
107
|
+
"manual_green_light_words",
|
|
108
|
+
"auto_green_light",
|
|
109
|
+
"max_word_repeat",
|
|
110
|
+
"max_tool_repeat",
|
|
111
|
+
"misplaced_tag_filter",
|
|
112
|
+
"reasoning_effort",
|
|
113
|
+
"temperature",
|
|
114
|
+
"show_settings_on_sidebar",
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
// Groups top-level key lines (with their block continuations) and returns
|
|
118
|
+
// them with the SETTING_ORDER keys first, in order, then the rest as-is.
|
|
119
|
+
function reorder(lines: string[]) {
|
|
120
|
+
const entries: { key: string; lines: string[] }[] = []
|
|
121
|
+
for (const l of lines) {
|
|
122
|
+
const m = l.match(/^(\w[\w-]*):/)
|
|
123
|
+
if (m) entries.push({ key: m[1], lines: [l] })
|
|
124
|
+
else if (entries.length) entries[entries.length - 1].lines.push(l)
|
|
125
|
+
}
|
|
126
|
+
const known = SETTING_ORDER.filter((k) => entries.some((e) => e.key === k)).flatMap((k) => entries.filter((e) => e.key === k).flatMap((e) => e.lines))
|
|
127
|
+
const rest = entries.filter((e) => !SETTING_ORDER.includes(e.key)).flatMap((e) => e.lines)
|
|
128
|
+
return [...known, ...rest]
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function setFrontmatter(text: string, key: string, value: string) {
|
|
132
|
+
const safe = /^[\w ./:,[\]{}-]*$/
|
|
133
|
+
const quote = safe.test(value) ? value : !value.includes("'") ? `'${value}'` : JSON.stringify(value)
|
|
134
|
+
const line = `${key}: ${quote}`
|
|
135
|
+
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
136
|
+
if (!match) return `---\n${line}\n---\n${text}`
|
|
137
|
+
const lines = match[1].split(/\r?\n/)
|
|
138
|
+
const i = lines.findIndex((l) => new RegExp(`^${key}:`).test(l))
|
|
139
|
+
if (i < 0) lines.push(line)
|
|
140
|
+
else {
|
|
141
|
+
const block = /\|\s*$/.test(lines[i])
|
|
142
|
+
lines[i] = line
|
|
143
|
+
if (block) while (i + 1 < lines.length && (!lines[i + 1].trim() || /^\s/.test(lines[i + 1]))) lines.splice(i + 1, 1)
|
|
144
|
+
}
|
|
145
|
+
return `---\n${reorder(lines).join("\n")}\n---${text.slice(match[0].length)}`
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Removes one top-level key from the frontmatter (including a `|` block value).
|
|
149
|
+
export function removeFrontmatter(text: string, key: string) {
|
|
150
|
+
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
151
|
+
if (!match) return text
|
|
152
|
+
const lines = match[1].split(/\r?\n/)
|
|
153
|
+
const i = lines.findIndex((l) => new RegExp(`^${key}:`).test(l))
|
|
154
|
+
if (i < 0) return text
|
|
155
|
+
const block = /\|\s*$/.test(lines[i])
|
|
156
|
+
lines.splice(i, 1)
|
|
157
|
+
if (block) while (i < lines.length && (!lines[i].trim() || /^\s/.test(lines[i]))) lines.splice(i, 1)
|
|
158
|
+
return `---\n${lines.join("\n")}\n---${text.slice(match[0].length)}`
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Sets one agent-plus setting in the agent's .md file; false when the file is not found.
|
|
162
|
+
export async function writeAgentSetting(directory: string, agent: string, key: string, value: string) {
|
|
163
|
+
const { file, text } = await agentFile(directory, agent)
|
|
164
|
+
if (!file) return false
|
|
165
|
+
await writeFile(file, setFrontmatter(text, key, value), "utf8")
|
|
166
|
+
return true
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Removes one agent-plus setting from the agent's .md file.
|
|
170
|
+
export async function removeAgentSetting(directory: string, agent: string, key: string) {
|
|
171
|
+
const { file, text } = await agentFile(directory, agent)
|
|
172
|
+
if (!file) return false
|
|
173
|
+
await writeFile(file, removeFrontmatter(text, key), "utf8")
|
|
174
|
+
return true
|
|
175
|
+
}
|
|
176
|
+
|
|
93
177
|
// Number of single-letter edits to turn `a` into `b`.
|
|
94
178
|
function distance(a: string, b: string) {
|
|
95
179
|
let row = Array.from({ length: b.length + 1 }, (_, j) => j)
|
|
@@ -104,7 +188,7 @@ function distance(a: string, b: string) {
|
|
|
104
188
|
|
|
105
189
|
// Unknown keys that look like a misspelled known key, as "wrong → right".
|
|
106
190
|
// Other unknown keys are left alone: they may belong to another plugin.
|
|
107
|
-
|
|
191
|
+
function misspelledKeys(keys: Record<string, string>) {
|
|
108
192
|
return Object.keys(keys).flatMap((key) => {
|
|
109
193
|
if (KNOWN.has(key)) return []
|
|
110
194
|
const match = [...KNOWN].find((known) => {
|
|
@@ -134,10 +218,10 @@ export function requestValue(key: string, value: string): { value: number | bool
|
|
|
134
218
|
}
|
|
135
219
|
|
|
136
220
|
// Everything wrong in an agent file: misspelled keys and wrong values.
|
|
137
|
-
export async function problems(
|
|
221
|
+
export async function problems(keys: Record<string, string>) {
|
|
138
222
|
const safeCommands =
|
|
139
|
-
keys.safe_commands && !["allow", "
|
|
140
|
-
? [`safe_commands: must be allow or
|
|
223
|
+
keys.safe_commands && !["allow", "off"].includes(keys.safe_commands)
|
|
224
|
+
? [`safe_commands: must be allow or off`]
|
|
141
225
|
: []
|
|
142
226
|
const maxWordRepeat =
|
|
143
227
|
keys.max_word_repeat && !["on", "off"].includes(keys.max_word_repeat)
|
|
@@ -167,11 +251,19 @@ export async function problems(file: string, keys: Record<string, string>) {
|
|
|
167
251
|
keys.clockwork && !["on", "off"].includes(keys.clockwork)
|
|
168
252
|
? [`clockwork: must be on or off`]
|
|
169
253
|
: []
|
|
254
|
+
const showSettings =
|
|
255
|
+
keys.show_settings_on_sidebar && !["on", "off"].includes(keys.show_settings_on_sidebar)
|
|
256
|
+
? [`show_settings_on_sidebar: must be on or off`]
|
|
257
|
+
: []
|
|
258
|
+
const toolOverrides =
|
|
259
|
+
keys.tools_override !== undefined && !keys.tools_override.trim()
|
|
260
|
+
? [`tools_override: must name a JSON file`]
|
|
261
|
+
: []
|
|
170
262
|
const wrong = [...BODY, ...TEMPLATE_KWARGS]
|
|
171
263
|
.filter((k) => k in keys)
|
|
172
264
|
.flatMap((k) => {
|
|
173
265
|
const result = requestValue(k, keys[k])
|
|
174
266
|
return "error" in result ? [result.error] : []
|
|
175
267
|
})
|
|
176
|
-
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering, ...misplacedTagFilter, ...clockwork]
|
|
268
|
+
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering, ...misplacedTagFilter, ...clockwork, ...toolOverrides, ...showSettings]
|
|
177
269
|
}
|
package/src/httprequest.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Request settings: adds the agent's sampling settings to the model request.
|
|
2
2
|
// Supported keys are listed in frontmatter.ts; a setting with a wrong value is not sent.
|
|
3
|
-
import { BODY, requestValue } from "./frontmatter"
|
|
3
|
+
import { BODY, TEMPLATE_KWARGS, requestValue } from "./frontmatter"
|
|
4
4
|
import { log } from "./log"
|
|
5
5
|
|
|
6
6
|
export interface HttpRequestOptions {
|
|
@@ -16,6 +16,13 @@ export async function httpRequest(event: any, options: HttpRequestOptions) {
|
|
|
16
16
|
const result = requestValue(k, keys[k])
|
|
17
17
|
if ("value" in result) extra[k] = result.value as number | string
|
|
18
18
|
}
|
|
19
|
+
const kwargs: Record<string, boolean> = {}
|
|
20
|
+
for (const k of TEMPLATE_KWARGS) {
|
|
21
|
+
if (!(k in keys)) continue
|
|
22
|
+
const result = requestValue(k, keys[k])
|
|
23
|
+
if ("value" in result) kwargs[k] = result.value as boolean
|
|
24
|
+
}
|
|
25
|
+
if (Object.keys(kwargs).length) extra.chat_template_kwargs = kwargs as any
|
|
19
26
|
log(`httprequest: agent=${event.agent} extra=${JSON.stringify(extra)}`)
|
|
20
27
|
event.options = { ...event.options, ...extra }
|
|
21
28
|
}
|
package/src/index.ts
CHANGED
|
@@ -10,6 +10,9 @@ import { httpRequest } from "./httprequest"
|
|
|
10
10
|
import { pondering } from "./pondering"
|
|
11
11
|
import { misplacedTagFilter } from "./misplacedtag"
|
|
12
12
|
import { clockwork } from "./clockwork"
|
|
13
|
+
import { verifier } from "./verifier"
|
|
14
|
+
import { toolOverrides } from "./tooloverrides"
|
|
15
|
+
import { probe } from "./probe"
|
|
13
16
|
|
|
14
17
|
// Server half: adds the agent's reminders to every model request and its settings to the request body.
|
|
15
18
|
// The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
|
|
@@ -25,7 +28,7 @@ export default {
|
|
|
25
28
|
const keys = frontmatter(text)
|
|
26
29
|
if (!warned.has(file)) {
|
|
27
30
|
warned.add(file)
|
|
28
|
-
const found = await problems(
|
|
31
|
+
const found = await problems(keys)
|
|
29
32
|
if (found.length) log(`server: problems file=${file} found=${found.join("; ")}`)
|
|
30
33
|
}
|
|
31
34
|
return { file, keys }
|
|
@@ -36,13 +39,13 @@ export default {
|
|
|
36
39
|
// `on_error_command`: wake the server on a connection failure, then retry.
|
|
37
40
|
const allowWake = await onErrorCommand(ctx, { settings })
|
|
38
41
|
|
|
39
|
-
// Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands:
|
|
42
|
+
// Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands: off`.
|
|
40
43
|
// It skips the ask window for read-only tool calls and safe shell commands.
|
|
41
44
|
// Configured `deny` rules are final and never reach this hook; anything unsafe passes through unchanged.
|
|
42
45
|
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
43
46
|
if (event.effect !== "ask" || !event.agent) return
|
|
44
47
|
const { keys } = await settings(event.agent)
|
|
45
|
-
if (keys.safe_commands === "
|
|
48
|
+
if (keys.safe_commands === "off") return
|
|
46
49
|
if (isSafeToolCall(event.action, event.resources ?? [])) event.effect = "allow"
|
|
47
50
|
})
|
|
48
51
|
|
|
@@ -68,12 +71,19 @@ export default {
|
|
|
68
71
|
// `clockwork: on` — deny all asks and keep the agent going on its own.
|
|
69
72
|
await clockwork(ctx, { settings })
|
|
70
73
|
|
|
74
|
+
// `verifier: on` — check each finished message and ask the agent to correct it.
|
|
75
|
+
await verifier(ctx, { settings })
|
|
76
|
+
|
|
77
|
+
// Answers the TUI's `reasoning_effort` format probe (probe.request → probe.status).
|
|
78
|
+
await probe(ctx)
|
|
79
|
+
|
|
71
80
|
await ctx.session.hook("context", async (event: any) => {
|
|
72
81
|
// A request got through: allow on_error_command to fire again next time.
|
|
73
82
|
allowWake(event.sessionID)
|
|
74
83
|
const { keys } = await settings(event.agent)
|
|
75
84
|
await httpRequest(event, { settings })
|
|
76
|
-
|
|
85
|
+
await toolOverrides(event, { settings })
|
|
86
|
+
const text = await reminderText(keys)
|
|
77
87
|
if (!text) return
|
|
78
88
|
appendBlock(event, "system-reminder", text)
|
|
79
89
|
})
|
package/src/presets.ts
CHANGED
|
@@ -1,32 +1,18 @@
|
|
|
1
|
-
// Preset texts for `reminder:` values
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// means off (logged, never an error).
|
|
1
|
+
// Preset texts for `reminder:` values, set in the agent file.
|
|
2
|
+
// A value that is a preset name gets the plugin's text; long text is used
|
|
3
|
+
// as written; a short unknown value means off (logged, never an error).
|
|
5
4
|
import { log } from "./log"
|
|
6
5
|
|
|
7
6
|
const PRESETS: Record<string, string> = {
|
|
8
7
|
concise: [
|
|
9
8
|
"Be concise and straight to the point. Cut the crap and jargon, and talk plain English. Do only what the user asked, and nothing else.",
|
|
10
9
|
].join("\n"),
|
|
11
|
-
"ultra-concise": [
|
|
12
|
-
'You are "Concise" agents, a helpful assistant.',
|
|
13
|
-
"Answer in one or two sentences. Only the requested fact or action, nothing else.",
|
|
14
|
-
"Plain simple English, no jargon, no headings, no lists.",
|
|
15
|
-
"Do not explain, summarize, or add details that are not asked.",
|
|
16
|
-
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
17
|
-
"NEVER use chained shell commands (; or &&). Run one command per call; chaining causes permission and execution issues.",
|
|
18
|
-
"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.",
|
|
19
|
-
"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.",
|
|
20
|
-
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
21
|
-
].join("\n"),
|
|
22
|
-
creative: [
|
|
23
|
-
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
24
|
-
"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.",
|
|
25
|
-
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
26
|
-
].join("\n"),
|
|
27
10
|
off: "",
|
|
28
11
|
}
|
|
29
12
|
|
|
13
|
+
// Preset names (without "off"), for pickers.
|
|
14
|
+
export const reminderPresets = Object.keys(PRESETS).filter((k) => k !== "off")
|
|
15
|
+
|
|
30
16
|
// Resolves one `reminder:` value to its text ("" = off).
|
|
31
17
|
// Returns null when the value is not set, so the caller reads the next source.
|
|
32
18
|
export function reminderPreset(value: string | undefined) {
|
package/src/probe.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// `reasoning_effort` format probe. The TUI writes `probe.request` next to this plugin's
|
|
2
|
+
// files ({ agent, model }); this module answers with `probe.status` listing the
|
|
3
|
+
// reasoning_effort values the model's server really supports: { model, levels } or { model, note }.
|
|
4
|
+
// llama.cpp answers exactly via GET /props (chat_template_caps.reasoning_effort_levels);
|
|
5
|
+
// other servers are probed with one tiny request per candidate value — an error naming
|
|
6
|
+
// reasoning_effort means the value is rejected. Servers that ignore unknown values cannot be
|
|
7
|
+
// detected; they report every candidate as supported.
|
|
8
|
+
// The plugin also loads in TUI processes, so several processes watch probe.request; the first
|
|
9
|
+
// one atomically renames the file (claim) and only it answers.
|
|
10
|
+
import path from "node:path"
|
|
11
|
+
import { watchFile, unwatchFile, readFileSync, writeFileSync, renameSync, existsSync, rmSync, readdirSync, statSync } from "node:fs"
|
|
12
|
+
import { folder, log } from "./log"
|
|
13
|
+
|
|
14
|
+
const requestFile = path.join(folder, "probe.request")
|
|
15
|
+
const statusFile = path.join(folder, "probe.status")
|
|
16
|
+
// Endpoints seen in model requests, persisted so probes work right after a server restart.
|
|
17
|
+
// Contains auth headers, like opencode's own config file.
|
|
18
|
+
const endpointsFile = path.join(folder, "probe.endpoints")
|
|
19
|
+
const CANDIDATES = ["low", "medium", "high", "xhigh"]
|
|
20
|
+
|
|
21
|
+
type Endpoint = { url: string; headers: Record<string, string> }
|
|
22
|
+
// Last seen endpoint per model id form, from the http.request hook (final URL and headers, auth included).
|
|
23
|
+
const endpoints = new Map<string, Endpoint>()
|
|
24
|
+
// Successful probes, so repeated opens are instant.
|
|
25
|
+
const probed = new Map<string, string[]>()
|
|
26
|
+
|
|
27
|
+
function modelKeys(ref: any): string[] {
|
|
28
|
+
const modelID = String(ref?.modelID ?? ref?.id ?? (typeof ref === "string" ? ref : "") ?? "")
|
|
29
|
+
return [modelID, ref?.providerID && modelID ? `${ref.providerID}/${modelID}` : ""].filter(Boolean)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function probeEndpoint(endpoint: Endpoint, model: string): Promise<string[] | null> {
|
|
33
|
+
const root = (() => {
|
|
34
|
+
try {
|
|
35
|
+
return new URL(endpoint.url).origin
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
})()
|
|
40
|
+
if (root) {
|
|
41
|
+
// llama.cpp: exact answer in one request.
|
|
42
|
+
try {
|
|
43
|
+
const res = await fetch(`${root}/props`, { signal: AbortSignal.timeout(3000) })
|
|
44
|
+
log(`probe: /props -> HTTP ${res.status}`)
|
|
45
|
+
if (res.ok) {
|
|
46
|
+
const levels = (await res.json())?.chat_template_caps?.reasoning_effort_levels
|
|
47
|
+
if (Array.isArray(levels) && levels.length) return CANDIDATES.filter((c) => levels.includes(c))
|
|
48
|
+
}
|
|
49
|
+
} catch (e) {
|
|
50
|
+
log(`probe: /props error ${String(e)}`)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// Fallback: one tiny request per candidate, in parallel; only an error naming reasoning_effort counts as a rejection.
|
|
54
|
+
const modelID = model.includes("/") ? model.slice(model.lastIndexOf("/") + 1) : model
|
|
55
|
+
const results = await Promise.all(
|
|
56
|
+
CANDIDATES.map(async (level): Promise<string | null> => {
|
|
57
|
+
try {
|
|
58
|
+
const res = await fetch(endpoint.url, {
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: { "content-type": "application/json", ...endpoint.headers },
|
|
61
|
+
body: JSON.stringify({ model: modelID, messages: [{ role: "user", content: "x" }], reasoning_effort: level, max_tokens: 1 }),
|
|
62
|
+
signal: AbortSignal.timeout(8000),
|
|
63
|
+
})
|
|
64
|
+
if (res.ok) return level
|
|
65
|
+
const text = await res.text().catch(() => "")
|
|
66
|
+
log(`probe: ${level} -> HTTP ${res.status} ${text.slice(0, 200).replace(/\s+/g, " ")}`)
|
|
67
|
+
return /reasoning/i.test(text) ? null : level // an error about something else proves nothing
|
|
68
|
+
} catch (e) {
|
|
69
|
+
log(`probe: ${level} fetch error ${String(e)}`)
|
|
70
|
+
return level // connection trouble proves nothing
|
|
71
|
+
}
|
|
72
|
+
}),
|
|
73
|
+
)
|
|
74
|
+
const supported = CANDIDATES.filter((_, i) => results[i] !== null)
|
|
75
|
+
return supported.length ? supported : null
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function probe(ctx: any) {
|
|
79
|
+
// The final outbound request: URL and headers as opencode actually sends them (auth included).
|
|
80
|
+
await ctx.session.hook("http.request", async (event: any) => {
|
|
81
|
+
const url = event.request?.url
|
|
82
|
+
if (!url || !url.includes("/chat/completions")) return
|
|
83
|
+
const headers: Record<string, string> = {}
|
|
84
|
+
try {
|
|
85
|
+
event.request.headers.forEach((v: string, k: string) => (headers[k] = v))
|
|
86
|
+
} catch {}
|
|
87
|
+
const endpoint = { url: String(url), headers }
|
|
88
|
+
for (const id of modelKeys(event.model)) endpoints.set(id, endpoint)
|
|
89
|
+
try {
|
|
90
|
+
writeFileSync(endpointsFile, JSON.stringify(Object.fromEntries(endpoints)))
|
|
91
|
+
} catch {}
|
|
92
|
+
})
|
|
93
|
+
// Restore persisted endpoints (this process may not have seen a request for this model yet).
|
|
94
|
+
try {
|
|
95
|
+
for (const [id, e] of Object.entries(JSON.parse(readFileSync(endpointsFile, "utf8")))) {
|
|
96
|
+
if (e && typeof (e as Endpoint).url === "string") endpoints.set(id, e as Endpoint)
|
|
97
|
+
}
|
|
98
|
+
} catch {}
|
|
99
|
+
// Remove claim files left behind by a process that died mid-probe (older than 30 s).
|
|
100
|
+
try {
|
|
101
|
+
for (const f of readdirSync(folder)) {
|
|
102
|
+
if (!f.startsWith("probe.request.claimed.")) continue
|
|
103
|
+
const p = path.join(folder, f)
|
|
104
|
+
try {
|
|
105
|
+
if (Date.now() - statSync(p).mtimeMs > 30_000) rmSync(p)
|
|
106
|
+
} catch {}
|
|
107
|
+
}
|
|
108
|
+
} catch {}
|
|
109
|
+
const onRequest = async () => {
|
|
110
|
+
// Claim the request: only the process that renames the file answers.
|
|
111
|
+
const claim = `${requestFile}.claimed.${process.pid}`
|
|
112
|
+
try {
|
|
113
|
+
renameSync(requestFile, claim)
|
|
114
|
+
} catch {
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
let body: { agent?: string; model?: string }
|
|
118
|
+
try {
|
|
119
|
+
body = JSON.parse(readFileSync(claim, "utf8"))
|
|
120
|
+
} catch {
|
|
121
|
+
return
|
|
122
|
+
} finally {
|
|
123
|
+
try {
|
|
124
|
+
if (existsSync(claim)) rmSync(claim)
|
|
125
|
+
} catch {}
|
|
126
|
+
}
|
|
127
|
+
if (!body?.model) return
|
|
128
|
+
const model = String(body.model)
|
|
129
|
+
const write = (result: { model: string; levels?: string[]; note?: string }) => {
|
|
130
|
+
try {
|
|
131
|
+
writeFileSync(statusFile, JSON.stringify({ ...result, at: Date.now() }))
|
|
132
|
+
} catch {}
|
|
133
|
+
}
|
|
134
|
+
if (probed.has(model)) {
|
|
135
|
+
write({ model, levels: probed.get(model)! })
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
const endpoint = endpoints.get(model) ?? endpoints.get(model.slice(model.lastIndexOf("/") + 1))
|
|
139
|
+
if (!endpoint) {
|
|
140
|
+
log(`probe: no endpoint for ${model}; have [${[...endpoints.keys()].join(", ")}]`)
|
|
141
|
+
write({ model, note: "no request to this model yet — send one message first" })
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
log(`probe: start model=${model} url=${endpoint.url}`)
|
|
145
|
+
const levels = await probeEndpoint(endpoint, model).catch((e) => {
|
|
146
|
+
log(`probe: probe threw ${String(e?.stack ?? e)}`)
|
|
147
|
+
return null
|
|
148
|
+
})
|
|
149
|
+
if (levels) probed.set(model, levels) // cache successes only, so a failure retries next time
|
|
150
|
+
log(`probe: done model=${model} levels=${levels ? levels.join(",") : "null"}`)
|
|
151
|
+
if (levels) write({ model, levels })
|
|
152
|
+
else write({ model, note: "probe failed" })
|
|
153
|
+
}
|
|
154
|
+
watchFile(requestFile, { interval: 200 }, () => void onRequest())
|
|
155
|
+
return () => unwatchFile(requestFile, onRequest)
|
|
156
|
+
}
|
package/src/repetition.ts
CHANGED
|
@@ -63,7 +63,7 @@ export function findRepetition(text: string, options: DetectOptions = {}): Repet
|
|
|
63
63
|
|
|
64
64
|
// Pulls model words out of protocol text: every `"content":"..."` value,
|
|
65
65
|
// with JSON escapes decoded. Unfinished tail (partial value) stays in `rest`.
|
|
66
|
-
|
|
66
|
+
function extractText(chunk: string): { text: string; rest: string } {
|
|
67
67
|
let text = ""
|
|
68
68
|
let i = 0
|
|
69
69
|
for (;;) {
|
|
@@ -105,7 +105,7 @@ interface ScanOptions {
|
|
|
105
105
|
// Wraps a model reply stream so the model's words can be scanned as they
|
|
106
106
|
// arrive. When the scanner says stop, onHit fires once; the stream keeps
|
|
107
107
|
// flowing (opencode's interrupt ends the run, not us).
|
|
108
|
-
|
|
108
|
+
function scanResponse(response: Response, options: ScanOptions): Response {
|
|
109
109
|
if (!response.body) return response
|
|
110
110
|
const scanEvery = options.scanEvery ?? 256
|
|
111
111
|
const decoder = new TextDecoder()
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Owns the `tools_override` setting: replaces tool descriptions with shorter
|
|
2
|
+
// ones from a JSON file named in the agent frontmatter (always next to the
|
|
3
|
+
// agent file). Off unless the key is set.
|
|
4
|
+
// Replacements are byte-stable (same file, same output every request), so the
|
|
5
|
+
// provider prompt cache is rebuilt once and then keeps hitting.
|
|
6
|
+
import { readFile, stat } from "node:fs/promises"
|
|
7
|
+
import path from "node:path"
|
|
8
|
+
import { log } from "./log"
|
|
9
|
+
|
|
10
|
+
// Parsed JSON per file, re-read only when the file changes on disk.
|
|
11
|
+
const cache = new Map<string, { mtimeMs: number; map: Record<string, string> }>()
|
|
12
|
+
|
|
13
|
+
async function load(file: string): Promise<Record<string, string> | undefined> {
|
|
14
|
+
const info = await stat(file).catch(() => undefined)
|
|
15
|
+
if (!info) return undefined
|
|
16
|
+
const hit = cache.get(file)
|
|
17
|
+
if (hit && hit.mtimeMs === info.mtimeMs) return hit.map
|
|
18
|
+
let map: Record<string, string>
|
|
19
|
+
try {
|
|
20
|
+
map = JSON.parse(await readFile(file, "utf8"))
|
|
21
|
+
} catch (e) {
|
|
22
|
+
log(`tools_override: bad JSON ${file}: ${e}`)
|
|
23
|
+
return undefined
|
|
24
|
+
}
|
|
25
|
+
cache.set(file, { mtimeMs: info.mtimeMs, map })
|
|
26
|
+
log(`tools_override: loaded ${file} tools=${Object.keys(map).join(",")}`)
|
|
27
|
+
return map
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Swap in the short descriptions for the tools listed in the file.
|
|
31
|
+
// Tools not listed (e.g. skill) keep their original description.
|
|
32
|
+
export async function toolOverrides(event: any, opts: { settings: (agent: string) => Promise<{ file: string; keys: Record<string, string> }> }) {
|
|
33
|
+
const { keys, file } = await opts.settings(event.agent)
|
|
34
|
+
if (!keys.tools_override || !file) return
|
|
35
|
+
const map = await load(path.join(path.dirname(file), keys.tools_override))
|
|
36
|
+
if (!map) {
|
|
37
|
+
log(`tools_override: file not found: ${keys.tools_override}`)
|
|
38
|
+
return
|
|
39
|
+
}
|
|
40
|
+
for (const [name, description] of Object.entries(map)) {
|
|
41
|
+
const tool = event.tools[name]
|
|
42
|
+
if (!tool) {
|
|
43
|
+
log(`tools_override: tool not sent to model, key does nothing: ${name}`)
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
if (typeof description === "string") tool.description = description
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/tui.tsx
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/** @jsxImportSource @opentui/solid */
|
|
2
2
|
import path from "node:path"
|
|
3
|
-
import { readFileSync, unwatchFile, watchFile } from "node:fs"
|
|
3
|
+
import { readFileSync, unwatchFile, watchFile, writeFileSync } from "node:fs"
|
|
4
4
|
import { createEffect, createMemo, createResource, createSignal, For, Show } from "solid-js"
|
|
5
|
-
import { agentFile, allAgentFiles, BODY, frontmatter, problems, read, requestValue } from "./frontmatter"
|
|
5
|
+
import { agentFile, allAgentFiles, BODY, frontmatter, problems, read, removeAgentSetting, requestValue, writeAgentSetting } from "./frontmatter"
|
|
6
6
|
import { folder, log } from "./log"
|
|
7
|
-
import { reminderPreset } from "./presets"
|
|
7
|
+
import { reminderPreset, reminderPresets } from "./presets"
|
|
8
8
|
|
|
9
9
|
// At start, shows a warning toast for every agent .md file with problems, or a "loaded" toast when there are none.
|
|
10
10
|
// Adds an "Agent-plus" section to the sidebar with the agent-plus settings of the session's agent.
|
|
@@ -13,19 +13,26 @@ const onOff = (v: string | undefined, on = "on") => (v === on ? "on" : "off")
|
|
|
13
13
|
|
|
14
14
|
function sidebarLines(keys: Record<string, string>) {
|
|
15
15
|
const lines: string[] = []
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
lines.push(
|
|
22
|
-
|
|
23
|
-
)
|
|
24
|
-
lines.push(`
|
|
25
|
-
lines.push(`
|
|
26
|
-
lines.push(`
|
|
27
|
-
|
|
28
|
-
|
|
16
|
+
if ("reminder" in keys) {
|
|
17
|
+
const reminder = reminderPreset(keys.reminder ?? "")
|
|
18
|
+
const reminderLabel = !reminder ? "off" : (keys.reminder?.trim().split(/\s+/).length ?? 0) <= 3 ? keys.reminder!.trim() : "user-defined"
|
|
19
|
+
lines.push(`reminder: ${reminderLabel}`)
|
|
20
|
+
}
|
|
21
|
+
if ("safe_commands" in keys) lines.push(`safe_commands: ${keys.safe_commands === "off" ? "off" : "on"}`)
|
|
22
|
+
if ("verifier" in keys) lines.push(`verifier: ${onOff(keys.verifier)}`)
|
|
23
|
+
if ("verifier_max_nags" in keys) lines.push(`verifier_max_nags: ${keys.verifier_max_nags || "default"}`)
|
|
24
|
+
if ("pondering" in keys) lines.push(`pondering: ${onOff(keys.pondering)}`)
|
|
25
|
+
if ("clockwork" in keys) lines.push(`clockwork: ${onOff(keys.clockwork)}`)
|
|
26
|
+
if ("tools_override" in keys) lines.push(`tools_override: ${keys.tools_override ? "on" : "off"}`)
|
|
27
|
+
if ("on_error_command" in keys)
|
|
28
|
+
lines.push(
|
|
29
|
+
`on_error_command: ${keys.on_error_command ? keys.on_error_command.split("\n")[0].trim() + (keys.on_error_command.includes("\n") ? " …" : "") : "off"}`,
|
|
30
|
+
)
|
|
31
|
+
if ("manual_green_light" in keys) lines.push(`manual_green_light: ${onOff(keys.manual_green_light)}`)
|
|
32
|
+
if ("auto_green_light" in keys) lines.push(`auto_green_light: ${onOff(keys.auto_green_light)}`)
|
|
33
|
+
if ("max_word_repeat" in keys) lines.push(`max_word_repeat: ${onOff(keys.max_word_repeat)}`)
|
|
34
|
+
if ("max_tool_repeat" in keys) lines.push(`max_tool_repeat: ${keys.max_tool_repeat || "off"}`)
|
|
35
|
+
if ("misplaced_tag_filter" in keys) lines.push(`misplaced_tag_filter: ${onOff(keys.misplaced_tag_filter)}`)
|
|
29
36
|
if ("reasoning_effort" in keys && "value" in requestValue("reasoning_effort", keys.reasoning_effort))
|
|
30
37
|
lines.push(`reasoning_effort: ${keys.reasoning_effort}`)
|
|
31
38
|
for (const k of BODY) {
|
|
@@ -39,6 +46,28 @@ function sidebarLines(keys: Record<string, string>) {
|
|
|
39
46
|
return lines
|
|
40
47
|
}
|
|
41
48
|
|
|
49
|
+
// The /agent-plus menu rows: toggles flip with space or enter; text rows open a prompt;
|
|
50
|
+
// reminder opens a preset / edit / off picker.
|
|
51
|
+
const ROWS: { key: string; kind: "toggle" | "text" | "reminder" | "choice"; on?: string; off?: string; values?: string[]; offLabel?: string; defaultLabel?: string }[] = [
|
|
52
|
+
{ key: "reminder", kind: "reminder", defaultLabel: "off" },
|
|
53
|
+
{ key: "safe_commands", kind: "toggle", on: "allow", off: "off", defaultLabel: "allow" },
|
|
54
|
+
{ key: "verifier", kind: "toggle", defaultLabel: "off" },
|
|
55
|
+
{ key: "verifier_max_nags", kind: "choice", values: ["1", "2", "3", "4"], offLabel: "default (1)" },
|
|
56
|
+
{ key: "pondering", kind: "toggle", defaultLabel: "off" },
|
|
57
|
+
{ key: "clockwork", kind: "toggle", defaultLabel: "off" },
|
|
58
|
+
{ key: "tools_override", kind: "text", defaultLabel: "off" },
|
|
59
|
+
{ key: "on_error_command", kind: "text", defaultLabel: "off" },
|
|
60
|
+
{ key: "manual_green_light", kind: "toggle", defaultLabel: "off" },
|
|
61
|
+
{ key: "manual_green_light_words", kind: "text", defaultLabel: "built-in list" },
|
|
62
|
+
{ key: "auto_green_light", kind: "toggle", defaultLabel: "off" },
|
|
63
|
+
{ key: "max_word_repeat", kind: "toggle", defaultLabel: "off" },
|
|
64
|
+
{ key: "max_tool_repeat", kind: "choice", values: ["1", "2", "3", "5", "8", "13", "21"], offLabel: "default (no limit)" },
|
|
65
|
+
{ key: "misplaced_tag_filter", kind: "toggle", defaultLabel: "off" },
|
|
66
|
+
{ key: "reasoning_effort", kind: "choice", values: ["low", "medium", "high", "xhigh"], offLabel: "default (model)" },
|
|
67
|
+
{ key: "temperature", kind: "choice", values: ["0", "0.2", "0.4", "0.6", "0.7", "0.8", "0.9", "1"], offLabel: "default (model)" },
|
|
68
|
+
{ key: "show_settings_on_sidebar", kind: "toggle", defaultLabel: "on" },
|
|
69
|
+
]
|
|
70
|
+
|
|
42
71
|
export default {
|
|
43
72
|
id: "agent-plus",
|
|
44
73
|
async setup(ctx: any) {
|
|
@@ -46,7 +75,7 @@ export default {
|
|
|
46
75
|
log(`tui: setup directory=${directory} toast=${typeof ctx.ui?.toast?.show}`)
|
|
47
76
|
let warned = false
|
|
48
77
|
for (const file of await allAgentFiles(directory)) {
|
|
49
|
-
const found = await problems(
|
|
78
|
+
const found = await problems(frontmatter(await read(file)))
|
|
50
79
|
if (!found.length) continue
|
|
51
80
|
warned = true
|
|
52
81
|
log(`tui: toast warning file=${file} problems=${found.join("; ")}`)
|
|
@@ -74,6 +103,45 @@ export default {
|
|
|
74
103
|
} catch {}
|
|
75
104
|
}
|
|
76
105
|
watchFile(statusFile, { interval: 300 }, readStatus)
|
|
106
|
+
// Live verifier verdict written by the server plugin: { sessionID: { verdict } }
|
|
107
|
+
const verifierFile = path.join(folder, "verifier.status")
|
|
108
|
+
const [verifierStatus, setVerifierStatus] = createSignal<Record<string, { verdict: string }>>({})
|
|
109
|
+
const readVerifier = () => {
|
|
110
|
+
try {
|
|
111
|
+
setVerifierStatus(JSON.parse(readFileSync(verifierFile, "utf8")))
|
|
112
|
+
} catch {}
|
|
113
|
+
}
|
|
114
|
+
watchFile(verifierFile, { interval: 300 }, readVerifier)
|
|
115
|
+
// reasoning_effort format probe: the TUI writes probe.request, the server plugin answers in probe.status.
|
|
116
|
+
const probeRequestFile = path.join(folder, "probe.request")
|
|
117
|
+
const probeStatusFile = path.join(folder, "probe.status")
|
|
118
|
+
const [probeStatus, setProbeStatus] = createSignal<{ model?: string; levels?: string[]; note?: string; at?: number }>({})
|
|
119
|
+
const readProbe = () => {
|
|
120
|
+
try {
|
|
121
|
+
setProbeStatus(JSON.parse(readFileSync(probeStatusFile, "utf8")))
|
|
122
|
+
} catch {}
|
|
123
|
+
}
|
|
124
|
+
watchFile(probeStatusFile, { interval: 150 }, readProbe)
|
|
125
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
|
|
126
|
+
async function probeReasoningEffort(agent: string): Promise<string[] | undefined> {
|
|
127
|
+
const current = ctx.ui.model.current?.()
|
|
128
|
+
const model = current ? `${current.providerID}/${current.modelID}` : undefined
|
|
129
|
+
if (!model) return undefined
|
|
130
|
+
const before = probeStatus().at
|
|
131
|
+
try {
|
|
132
|
+
writeFileSync(probeRequestFile, JSON.stringify({ agent, model }))
|
|
133
|
+
} catch {
|
|
134
|
+
return undefined
|
|
135
|
+
}
|
|
136
|
+
ctx.ui.toast.show({ title: "agent-plus", message: "Detecting supported values...", variant: "info", duration: 4000 })
|
|
137
|
+
const deadline = Date.now() + 10000
|
|
138
|
+
while (Date.now() < deadline) {
|
|
139
|
+
await sleep(150)
|
|
140
|
+
const s = probeStatus()
|
|
141
|
+
if (s.model === model && s.at !== before) return s.levels
|
|
142
|
+
}
|
|
143
|
+
return undefined
|
|
144
|
+
}
|
|
77
145
|
const [frame, setFrame] = createSignal(0) // spinner frame counter
|
|
78
146
|
const timer = setInterval(() => setFrame((f) => f + 1), 80)
|
|
79
147
|
|
|
@@ -84,11 +152,30 @@ export default {
|
|
|
84
152
|
const agent = createMemo(() => ctx.data.session.get(props.sessionID)?.agent)
|
|
85
153
|
const [lines] = createResource(
|
|
86
154
|
() => agent() && { agent: agent()!, version: agentsVersion() },
|
|
87
|
-
async ({ agent }) =>
|
|
155
|
+
async ({ agent }) => {
|
|
156
|
+
const keys = frontmatter((await agentFile(directory, agent)).text)
|
|
157
|
+
return keys.show_settings_on_sidebar === "off" ? null : sidebarLines(keys)
|
|
158
|
+
},
|
|
88
159
|
)
|
|
89
160
|
// Live line: spinner while pondering, "on (idle)" when enabled and done, "off" when disabled.
|
|
161
|
+
const cacheLine = createMemo(() => {
|
|
162
|
+
const msgs = ctx.data.session.message.list(props.sessionID) ?? []
|
|
163
|
+
const last = [...msgs].reverse().find((m: any) => m.type === "assistant" && m.tokens)
|
|
164
|
+
if (!last) return "cache: -"
|
|
165
|
+
const t = last.tokens
|
|
166
|
+
const total = t.input + t.cache.read
|
|
167
|
+
const pct = total > 0 ? ((t.cache.read / total) * 100).toFixed(1) : "0.0"
|
|
168
|
+
return `cache: ${pct}% (cached: ${t.cache.read} token · new: ${t.input} token)`
|
|
169
|
+
})
|
|
90
170
|
const shown = createMemo(() => {
|
|
91
|
-
const
|
|
171
|
+
const base = lines()
|
|
172
|
+
if (!base) return []
|
|
173
|
+
const ls = [...base, cacheLine()]
|
|
174
|
+
const sv = verifierStatus()[props.sessionID]
|
|
175
|
+
if (sv) {
|
|
176
|
+
const idx = ls.findIndex((l) => l === "verifier: on")
|
|
177
|
+
if (idx >= 0) ls[idx] = `verifier: on (last: ${sv.verdict})`
|
|
178
|
+
}
|
|
92
179
|
if (!ls.includes("pondering: on")) return ls
|
|
93
180
|
const st = statuses()[props.sessionID]
|
|
94
181
|
const busy = st?.state === "busy"
|
|
@@ -119,9 +206,172 @@ export default {
|
|
|
119
206
|
)
|
|
120
207
|
},
|
|
121
208
|
})
|
|
209
|
+
// /agent-plus: settings menu for the current session's agent; writes its .md frontmatter directly.
|
|
210
|
+
let reopening = false
|
|
211
|
+
let focusKey: string | undefined
|
|
212
|
+
const openSettings = async () => {
|
|
213
|
+
focusKey = undefined
|
|
214
|
+
const route = ctx.ui.router.current()
|
|
215
|
+
if (route.type !== "session") {
|
|
216
|
+
ctx.ui.toast.show({ title: "agent-plus", message: "Open a session first.", variant: "warning" })
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
const agent = ctx.data.session.get(route.sessionID)?.agent
|
|
220
|
+
if (!agent) return
|
|
221
|
+
log(`tui: settings open agent=${agent}`)
|
|
222
|
+
const flip = async (row: (typeof ROWS)[number]) => {
|
|
223
|
+
const { file, text } = await agentFile(directory, agent)
|
|
224
|
+
if (!file) return
|
|
225
|
+
const cur = frontmatter(text)[row.key]
|
|
226
|
+
const value = !cur || cur === (row.off ?? "off") ? (row.on ?? "on") : (row.off ?? "off")
|
|
227
|
+
await writeAgentSetting(directory, agent, row.key, value)
|
|
228
|
+
log(`tui: settings set agent=${agent} ${row.key}=${value}`)
|
|
229
|
+
}
|
|
230
|
+
while (true) {
|
|
231
|
+
reopening = false
|
|
232
|
+
const { file, text } = await agentFile(directory, agent)
|
|
233
|
+
if (!file) {
|
|
234
|
+
ctx.ui.toast.show({ title: "agent-plus", message: `No file found for agent "${agent}".`, variant: "warning" })
|
|
235
|
+
return
|
|
236
|
+
}
|
|
237
|
+
const keys = frontmatter(text)
|
|
238
|
+
const pick = await ctx.ui.dialog.select({
|
|
239
|
+
title: `agent-plus · ${agent}`,
|
|
240
|
+
current: focusKey,
|
|
241
|
+
options: ROWS.map((row) => ({
|
|
242
|
+
title: row.key,
|
|
243
|
+
value: row.key,
|
|
244
|
+
footer: keys[row.key] ? keys[row.key].split("\n")[0].slice(0, 40) : "default",
|
|
245
|
+
})),
|
|
246
|
+
actions: [
|
|
247
|
+
{
|
|
248
|
+
bind: "space",
|
|
249
|
+
title: "toggle",
|
|
250
|
+
onTrigger: (key: string) => {
|
|
251
|
+
const row = ROWS.find((r) => r.key === key)
|
|
252
|
+
if (!row || row.kind !== "toggle") return
|
|
253
|
+
void flip(row).then(() => {
|
|
254
|
+
focusKey = key
|
|
255
|
+
reopening = true
|
|
256
|
+
ctx.ui.dialog.clear() // closes this select; the loop below reopens it with fresh values
|
|
257
|
+
})
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
],
|
|
261
|
+
})
|
|
262
|
+
if (reopening) continue
|
|
263
|
+
if (!pick) return
|
|
264
|
+
focusKey = pick
|
|
265
|
+
const row = ROWS.find((r) => r.key === pick)
|
|
266
|
+
if (!row) continue
|
|
267
|
+
if (row.kind === "toggle") {
|
|
268
|
+
const on = row.on ?? "on"
|
|
269
|
+
const off = row.off ?? "off"
|
|
270
|
+
const cur = keys[row.key]
|
|
271
|
+
const choice = await ctx.ui.dialog.select({
|
|
272
|
+
title: row.key,
|
|
273
|
+
current: cur,
|
|
274
|
+
options: [
|
|
275
|
+
{ title: on, value: on, footer: cur === on ? "current" : "" },
|
|
276
|
+
{ title: off, value: off, footer: cur === off ? "current" : "" },
|
|
277
|
+
{ title: `default (${row.defaultLabel})`, value: "\u0000default", footer: !cur ? "current" : "" },
|
|
278
|
+
],
|
|
279
|
+
})
|
|
280
|
+
if (choice === "\u0000default") await removeAgentSetting(directory, agent, row.key)
|
|
281
|
+
else if (choice) await writeAgentSetting(directory, agent, row.key, choice)
|
|
282
|
+
continue
|
|
283
|
+
}
|
|
284
|
+
if (row.kind === "choice") {
|
|
285
|
+
let values = row.values ?? []
|
|
286
|
+
let title = row.key
|
|
287
|
+
if (row.key === "reasoning_effort") {
|
|
288
|
+
const levels = await probeReasoningEffort(agent)
|
|
289
|
+
if (levels) values = values.filter((v) => levels.includes(v))
|
|
290
|
+
else title = `${row.key} · supported values unknown`
|
|
291
|
+
}
|
|
292
|
+
const choice = await ctx.ui.dialog.select({
|
|
293
|
+
title,
|
|
294
|
+
current: keys[row.key],
|
|
295
|
+
options: [
|
|
296
|
+
...values.map((v) => ({ title: v, value: v, footer: keys[row.key] === v ? "current" : "" })),
|
|
297
|
+
{ title: row.offLabel ?? "off", value: "off", footer: !keys[row.key] ? "current" : "" },
|
|
298
|
+
],
|
|
299
|
+
})
|
|
300
|
+
if (choice === "off") await removeAgentSetting(directory, agent, row.key)
|
|
301
|
+
else if (choice) await writeAgentSetting(directory, agent, row.key, choice)
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
if (row.kind === "reminder") {
|
|
305
|
+
let pendingEdit = false
|
|
306
|
+
const choice = await ctx.ui.dialog.select({
|
|
307
|
+
title: "reminder",
|
|
308
|
+
options: [
|
|
309
|
+
...reminderPresets.map((p) => ({ title: p, value: p, footer: keys[row.key] === p ? "current" : "" })),
|
|
310
|
+
{ title: "edit…", value: "\u0000edit", footer: keys[row.key] && !reminderPresets.includes(keys[row.key]) && keys[row.key] !== "off" ? "current" : "" },
|
|
311
|
+
{ title: "off", value: "off", footer: keys[row.key] === "off" ? "current" : "" },
|
|
312
|
+
{ title: `default (${row.defaultLabel})`, value: "\u0000default", footer: !keys[row.key] ? "current" : "" },
|
|
313
|
+
],
|
|
314
|
+
actions: [
|
|
315
|
+
{
|
|
316
|
+
bind: "space",
|
|
317
|
+
title: "edit",
|
|
318
|
+
onTrigger: (v: string) => {
|
|
319
|
+
if (v !== "\u0000edit") return // space is inert on presets and off
|
|
320
|
+
pendingEdit = true
|
|
321
|
+
ctx.ui.dialog.clear() // closes this select; the edit prompt opens below
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
],
|
|
325
|
+
})
|
|
326
|
+
const editValue = () => {
|
|
327
|
+
const cur = keys[row.key] ?? ""
|
|
328
|
+
return cur && !reminderPresets.includes(cur) && cur !== "off" ? cur : ""
|
|
329
|
+
}
|
|
330
|
+
if (pendingEdit || choice === "\u0000edit") {
|
|
331
|
+
const typed = await ctx.ui.dialog.prompt({ title: "reminder", value: editValue() })
|
|
332
|
+
if (typed !== undefined && typed.trim()) await writeAgentSetting(directory, agent, row.key, typed.trim())
|
|
333
|
+
continue
|
|
334
|
+
}
|
|
335
|
+
if (!choice) continue
|
|
336
|
+
if (choice === "\u0000default") await removeAgentSetting(directory, agent, row.key)
|
|
337
|
+
else await writeAgentSetting(directory, agent, row.key, choice)
|
|
338
|
+
continue
|
|
339
|
+
}
|
|
340
|
+
const textChoice = await ctx.ui.dialog.select({
|
|
341
|
+
title: row.key,
|
|
342
|
+
options: [
|
|
343
|
+
{ title: "edit…", value: "\u0000edit", footer: keys[row.key] ? "current" : "" },
|
|
344
|
+
{ title: `default (${row.defaultLabel})`, value: "\u0000default", footer: !keys[row.key] ? "current" : "" },
|
|
345
|
+
],
|
|
346
|
+
})
|
|
347
|
+
if (textChoice === "\u0000default") await removeAgentSetting(directory, agent, row.key)
|
|
348
|
+
else if (textChoice === "\u0000edit") {
|
|
349
|
+
const typed = await ctx.ui.dialog.prompt({ title: row.key, value: keys[row.key] ?? "" })
|
|
350
|
+
if (typed === undefined) continue
|
|
351
|
+
if (typed.trim()) await writeAgentSetting(directory, agent, row.key, typed.trim())
|
|
352
|
+
else await removeAgentSetting(directory, agent, row.key)
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
ctx.keymap.layer(() => ({
|
|
357
|
+
mode: "global",
|
|
358
|
+
commands: [
|
|
359
|
+
{
|
|
360
|
+
id: "agent-plus.settings",
|
|
361
|
+
title: "Agent-plus settings",
|
|
362
|
+
group: "agent-plus",
|
|
363
|
+
slash: { name: "agent-plus" },
|
|
364
|
+
palette: true,
|
|
365
|
+
run: () => void openSettings(),
|
|
366
|
+
},
|
|
367
|
+
],
|
|
368
|
+
}))
|
|
369
|
+
|
|
122
370
|
return () => {
|
|
123
371
|
clearInterval(timer)
|
|
124
372
|
unwatchFile(statusFile, readStatus)
|
|
373
|
+
unwatchFile(verifierFile, readVerifier)
|
|
374
|
+
unwatchFile(probeStatusFile, readProbe)
|
|
125
375
|
stop()
|
|
126
376
|
}
|
|
127
377
|
},
|
package/src/verifier.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// `verifier: on` — after each finished turn, check the agent's last message
|
|
2
|
+
// against the rules. If it does not follow them, send a user-role message
|
|
3
|
+
// (like clockwork) asking the agent to correct it. Messages are never blocked;
|
|
4
|
+
// they always reach the user. Destructive tool-call blocking is a later phase.
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
7
|
+
import { folder, log } from "./log"
|
|
8
|
+
|
|
9
|
+
// Small file the TUI sidebar watches to show the last verifier verdict.
|
|
10
|
+
// Content is a JSON map: { sessionID: { verdict } }.
|
|
11
|
+
const statusFile = path.join(folder, "verifier.status")
|
|
12
|
+
function setVerdict(sessionID: string, verdict: string) {
|
|
13
|
+
try {
|
|
14
|
+
const map = JSON.parse(readFileSync(statusFile, "utf8")) as Record<string, { verdict: string }>
|
|
15
|
+
map[sessionID] = { verdict }
|
|
16
|
+
writeFileSync(statusFile, JSON.stringify(map))
|
|
17
|
+
} catch {
|
|
18
|
+
writeFileSync(statusFile, JSON.stringify({ [sessionID]: { verdict } }))
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Fixed prefix. Always the same. The judge fills in only the reason after it.
|
|
23
|
+
const PREFIX =
|
|
24
|
+
"=== Verifier ===\n" +
|
|
25
|
+
"This is not the user but a verifier is watching this session. " +
|
|
26
|
+
"Your last message isn't following the guidelines:\n"
|
|
27
|
+
|
|
28
|
+
const JUDGE_META =
|
|
29
|
+
"You are a verifier. Check the assistant's last message for any fact not " +
|
|
30
|
+
"checked or sourced this session (made-up numbers, paths, versions). If found, " +
|
|
31
|
+
"reply with one sentence naming it. If the message has no such fact, reply OK."
|
|
32
|
+
|
|
33
|
+
// How many times the verifier may correct one user turn before giving up.
|
|
34
|
+
// Without a cap, a correction re-fires session.execution.succeeded, the agent
|
|
35
|
+
// answers, the verifier flags again, and the session loops forever.
|
|
36
|
+
// Set per agent with `verifier_max_nags: n` (default 1).
|
|
37
|
+
|
|
38
|
+
export async function verifier(ctx: any, { settings }: { settings: (agent: string) => Promise<{ keys: Record<string, string> }> }) {
|
|
39
|
+
const shared = ((globalThis as any).__agentPlusVerifier ??= { running: new Set<string>(), corrections: new Map<string, number>(), lastEvent: undefined })
|
|
40
|
+
const running = shared.running as Set<string> // a check is in flight for this session
|
|
41
|
+
const corrections = shared.corrections as Map<string, number> // corrections sent for the current user turn
|
|
42
|
+
|
|
43
|
+
// After each finished turn, judge the agent's last message and correct if needed.
|
|
44
|
+
const controller = new AbortController()
|
|
45
|
+
log(`verifier: listener started`)
|
|
46
|
+
void (async () => {
|
|
47
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
48
|
+
if (event.id === shared.lastEvent) continue
|
|
49
|
+
shared.lastEvent = event.id
|
|
50
|
+
const sessionID: string | undefined = event.data?.sessionID
|
|
51
|
+
// A real user message re-arms the verifier. Our own steer message (which
|
|
52
|
+
// arrives as a user message too) must NOT reset the count, or the cap never bites.
|
|
53
|
+
if (event.type === "session.inbox.enqueued") {
|
|
54
|
+
const text = event.data?.item?.payload?.text
|
|
55
|
+
if (typeof text === "string" && text.startsWith(PREFIX)) continue
|
|
56
|
+
if (sessionID) corrections.delete(sessionID)
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
if (event.type !== "session.execution.succeeded") continue
|
|
60
|
+
if (!sessionID || running.has(sessionID)) continue
|
|
61
|
+
try {
|
|
62
|
+
const session = await ctx.session.get({ sessionID })
|
|
63
|
+
const { keys } = await settings(session.agent)
|
|
64
|
+
if (keys.verifier !== "on") continue
|
|
65
|
+
running.add(sessionID)
|
|
66
|
+
// Max nags for this agent's turn; default 1.
|
|
67
|
+
const maxCorrections = Number(keys.verifier_max_nags) || 1
|
|
68
|
+
|
|
69
|
+
// Read-only check: nothing saved. Reply is OK or "<rule> <reason>".
|
|
70
|
+
const verdict = String((await ctx.session.generate({ sessionID, prompt: JUDGE_META })).text).trim()
|
|
71
|
+
if (!verdict || /^ok\b/i.test(verdict)) {
|
|
72
|
+
setVerdict(sessionID, "ok")
|
|
73
|
+
log(`verifier: ok session=${sessionID} verdict=${verdict}`)
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Anti-loop: stop after maxCorrections for this user turn.
|
|
78
|
+
const sent = corrections.get(sessionID) ?? 0
|
|
79
|
+
if (sent >= maxCorrections) {
|
|
80
|
+
setVerdict(sessionID, "gave up")
|
|
81
|
+
log(`verifier: loop guard session=${sessionID} sent=${sent} verdict=${verdict}`)
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
setVerdict(sessionID, "flagged")
|
|
86
|
+
const text = `${PREFIX}${verdict}`
|
|
87
|
+
corrections.set(sessionID, sent + 1)
|
|
88
|
+
log(`verifier: correcting session=${sessionID} sent=${sent + 1} verdict=${verdict}`)
|
|
89
|
+
await ctx.session.prompt({ sessionID, text, delivery: "steer" })
|
|
90
|
+
} catch (error) {
|
|
91
|
+
log(`verifier: check failed session=${sessionID} error=${String(error)}`)
|
|
92
|
+
} finally {
|
|
93
|
+
running.delete(sessionID)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
})().catch((error) => log(`verifier: listener died error=${String(error)}`))
|
|
97
|
+
|
|
98
|
+
return () => controller.abort()
|
|
99
|
+
}
|