opencode-agent-plus 0.5.1 → 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 +21 -10
- package/package.json +4 -1
- package/src/context.ts +3 -9
- package/src/frontmatter.test.ts +2 -2
- package/src/frontmatter.ts +97 -9
- package/src/index.ts +12 -4
- package/src/presets.ts +6 -20
- package/src/probe.ts +156 -0
- package/src/repetition.ts +2 -2
- package/src/tui.tsx +260 -20
- package/src/verifier.ts +99 -0
package/README.md
CHANGED
|
@@ -78,26 +78,40 @@ You help the user write and edit text.
|
|
|
78
78
|
|
|
79
79
|
| Key | Value | Effect |
|
|
80
80
|
| --- | --- | --- |
|
|
81
|
-
| `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 |
|
|
82
82
|
| `on_error_command` | shell command, one line or a `\|` block | Run when a request fails with a connection error (server off), then retry |
|
|
83
|
-
| `safe_commands` | `
|
|
83
|
+
| `safe_commands` | `off` (default: on) | Turn safe-command auto-allow off for this agent |
|
|
84
84
|
| `max_word_repeat` | `on` or `off` (default: off) | Stop the reply when the model repeats the same text |
|
|
85
85
|
| `max_tool_repeat` | whole number | Max times the same tool call may repeat in a row |
|
|
86
86
|
| `manual_green_light` | `on` or `off` (default: off) | Tools run only when your message ends with an approval word |
|
|
87
87
|
| `manual_green_light_words` | comma-separated words | The approval words for `manual_green_light` |
|
|
88
88
|
| `auto_green_light` | `on` or `off` (default: off) | The model checks itself before the first tool call of each turn |
|
|
89
|
-
| `temperature` | number | Request body |
|
|
89
|
+
| `temperature` | number from `0` to `1` | Request body |
|
|
90
90
|
| `max_completion_tokens` | whole number | Request body |
|
|
91
91
|
| `reasoning_budget_tokens` | whole number | Request body |
|
|
92
|
-
| `reasoning_effort` | `
|
|
92
|
+
| `reasoning_effort` | `low`, `medium`, `high` or `xhigh` | Request body |
|
|
93
93
|
| `enable_thinking` | `true` or `false` | Request body, under `chat_template_kwargs` |
|
|
94
94
|
| `tools_override` | path to a JSON file (relative to the agent file) | Replace tool descriptions with your own |
|
|
95
95
|
| `pondering` | `on` or `off` (default: off) | Run a quiet thinking request when the session goes idle |
|
|
96
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 |
|
|
97
98
|
| `clockwork` | `on` or `off` (default: off) | Run the agent hands-off with auto-continue |
|
|
98
99
|
|
|
99
100
|
Names are sent as written. A setting with a wrong value is not sent.
|
|
100
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
|
+
|
|
101
115
|
## Reminders
|
|
102
116
|
|
|
103
117
|
### Why
|
|
@@ -109,12 +123,9 @@ the most.
|
|
|
109
123
|
|
|
110
124
|
### How
|
|
111
125
|
|
|
112
|
-
Before every model request, agent-plus adds one message at the end of the conversation with
|
|
113
|
-
|
|
114
|
-
1. the agent's `reminder`
|
|
115
|
-
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`.
|
|
116
127
|
|
|
117
|
-
`reminder` takes a preset name (`concise`, `
|
|
128
|
+
`reminder` takes a preset name (`concise`, `off`) for wording held in
|
|
118
129
|
the plugin, or your own text (more than 3 words). A short unknown value means
|
|
119
130
|
`off`.
|
|
120
131
|
|
|
@@ -182,7 +193,7 @@ It never overrides a configured `deny`, and only turns `ask` into `allow`. Doubt
|
|
|
182
193
|
Known unsafe flags are refused, e.g. `find -exec`, `env <cmd>`, `rg --pre`, `sort -o`, `git branch -D`,
|
|
183
194
|
`git log --output=`, `ssh -o ProxyCommand=`.
|
|
184
195
|
|
|
185
|
-
Turn it off for one agent with `safe_commands:
|
|
196
|
+
Turn it off for one agent with `safe_commands: off` in its frontmatter.
|
|
186
197
|
|
|
187
198
|
## Anti-repetition
|
|
188
199
|
|
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",
|
|
@@ -34,6 +34,9 @@
|
|
|
34
34
|
"qwen"
|
|
35
35
|
],
|
|
36
36
|
"type": "module",
|
|
37
|
+
"scripts": {
|
|
38
|
+
"test": "bun test ./src"
|
|
39
|
+
},
|
|
37
40
|
"exports": {
|
|
38
41
|
".": "./src/index.ts",
|
|
39
42
|
"./tui": "./src/tui.tsx"
|
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
|
@@ -9,7 +9,7 @@ test("parses keys and | blocks", () => {
|
|
|
9
9
|
|
|
10
10
|
test("validates request values", () => {
|
|
11
11
|
expect(requestValue("enable_thinking", "true")).toEqual({ value: true })
|
|
12
|
-
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" })
|
|
13
13
|
})
|
|
14
14
|
|
|
15
15
|
test("no frontmatter, empty, and unknown keys", () => {
|
|
@@ -19,7 +19,7 @@ test("no frontmatter, empty, and unknown keys", () => {
|
|
|
19
19
|
})
|
|
20
20
|
|
|
21
21
|
test("reports misspelled keys and wrong values", async () => {
|
|
22
|
-
const found = await problems(
|
|
22
|
+
const found = await problems({ temprature: "1", max_word_repeat: "maybe" })
|
|
23
23
|
expect(found).toContain("temprature → temperature")
|
|
24
24
|
expect(found).toContain("max_word_repeat: must be on or off")
|
|
25
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
|
|
|
@@ -17,13 +17,13 @@ export const TEMPLATE_KWARGS = ["enable_thinking"]
|
|
|
17
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", "tools_override", ...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,6 +251,10 @@ 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
|
+
: []
|
|
170
258
|
const toolOverrides =
|
|
171
259
|
keys.tools_override !== undefined && !keys.tools_override.trim()
|
|
172
260
|
? [`tools_override: must name a JSON file`]
|
|
@@ -177,5 +265,5 @@ export async function problems(file: string, keys: Record<string, string>) {
|
|
|
177
265
|
const result = requestValue(k, keys[k])
|
|
178
266
|
return "error" in result ? [result.error] : []
|
|
179
267
|
})
|
|
180
|
-
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering, ...misplacedTagFilter, ...clockwork, ...toolOverrides]
|
|
268
|
+
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering, ...misplacedTagFilter, ...clockwork, ...toolOverrides, ...showSettings]
|
|
181
269
|
}
|
package/src/index.ts
CHANGED
|
@@ -10,7 +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"
|
|
13
14
|
import { toolOverrides } from "./tooloverrides"
|
|
15
|
+
import { probe } from "./probe"
|
|
14
16
|
|
|
15
17
|
// Server half: adds the agent's reminders to every model request and its settings to the request body.
|
|
16
18
|
// The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
|
|
@@ -26,7 +28,7 @@ export default {
|
|
|
26
28
|
const keys = frontmatter(text)
|
|
27
29
|
if (!warned.has(file)) {
|
|
28
30
|
warned.add(file)
|
|
29
|
-
const found = await problems(
|
|
31
|
+
const found = await problems(keys)
|
|
30
32
|
if (found.length) log(`server: problems file=${file} found=${found.join("; ")}`)
|
|
31
33
|
}
|
|
32
34
|
return { file, keys }
|
|
@@ -37,13 +39,13 @@ export default {
|
|
|
37
39
|
// `on_error_command`: wake the server on a connection failure, then retry.
|
|
38
40
|
const allowWake = await onErrorCommand(ctx, { settings })
|
|
39
41
|
|
|
40
|
-
// 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`.
|
|
41
43
|
// It skips the ask window for read-only tool calls and safe shell commands.
|
|
42
44
|
// Configured `deny` rules are final and never reach this hook; anything unsafe passes through unchanged.
|
|
43
45
|
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
44
46
|
if (event.effect !== "ask" || !event.agent) return
|
|
45
47
|
const { keys } = await settings(event.agent)
|
|
46
|
-
if (keys.safe_commands === "
|
|
48
|
+
if (keys.safe_commands === "off") return
|
|
47
49
|
if (isSafeToolCall(event.action, event.resources ?? [])) event.effect = "allow"
|
|
48
50
|
})
|
|
49
51
|
|
|
@@ -69,13 +71,19 @@ export default {
|
|
|
69
71
|
// `clockwork: on` — deny all asks and keep the agent going on its own.
|
|
70
72
|
await clockwork(ctx, { settings })
|
|
71
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
|
+
|
|
72
80
|
await ctx.session.hook("context", async (event: any) => {
|
|
73
81
|
// A request got through: allow on_error_command to fire again next time.
|
|
74
82
|
allowWake(event.sessionID)
|
|
75
83
|
const { keys } = await settings(event.agent)
|
|
76
84
|
await httpRequest(event, { settings })
|
|
77
85
|
await toolOverrides(event, { settings })
|
|
78
|
-
const text = await reminderText(
|
|
86
|
+
const text = await reminderText(keys)
|
|
79
87
|
if (!text) return
|
|
80
88
|
appendBlock(event, "system-reminder", text)
|
|
81
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()
|
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,20 +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
|
-
|
|
29
|
-
|
|
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)}`)
|
|
30
36
|
if ("reasoning_effort" in keys && "value" in requestValue("reasoning_effort", keys.reasoning_effort))
|
|
31
37
|
lines.push(`reasoning_effort: ${keys.reasoning_effort}`)
|
|
32
38
|
for (const k of BODY) {
|
|
@@ -40,6 +46,28 @@ function sidebarLines(keys: Record<string, string>) {
|
|
|
40
46
|
return lines
|
|
41
47
|
}
|
|
42
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
|
+
|
|
43
71
|
export default {
|
|
44
72
|
id: "agent-plus",
|
|
45
73
|
async setup(ctx: any) {
|
|
@@ -47,7 +75,7 @@ export default {
|
|
|
47
75
|
log(`tui: setup directory=${directory} toast=${typeof ctx.ui?.toast?.show}`)
|
|
48
76
|
let warned = false
|
|
49
77
|
for (const file of await allAgentFiles(directory)) {
|
|
50
|
-
const found = await problems(
|
|
78
|
+
const found = await problems(frontmatter(await read(file)))
|
|
51
79
|
if (!found.length) continue
|
|
52
80
|
warned = true
|
|
53
81
|
log(`tui: toast warning file=${file} problems=${found.join("; ")}`)
|
|
@@ -75,6 +103,45 @@ export default {
|
|
|
75
103
|
} catch {}
|
|
76
104
|
}
|
|
77
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
|
+
}
|
|
78
145
|
const [frame, setFrame] = createSignal(0) // spinner frame counter
|
|
79
146
|
const timer = setInterval(() => setFrame((f) => f + 1), 80)
|
|
80
147
|
|
|
@@ -85,7 +152,10 @@ export default {
|
|
|
85
152
|
const agent = createMemo(() => ctx.data.session.get(props.sessionID)?.agent)
|
|
86
153
|
const [lines] = createResource(
|
|
87
154
|
() => agent() && { agent: agent()!, version: agentsVersion() },
|
|
88
|
-
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
|
+
},
|
|
89
159
|
)
|
|
90
160
|
// Live line: spinner while pondering, "on (idle)" when enabled and done, "off" when disabled.
|
|
91
161
|
const cacheLine = createMemo(() => {
|
|
@@ -98,7 +168,14 @@ export default {
|
|
|
98
168
|
return `cache: ${pct}% (cached: ${t.cache.read} token · new: ${t.input} token)`
|
|
99
169
|
})
|
|
100
170
|
const shown = createMemo(() => {
|
|
101
|
-
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
|
+
}
|
|
102
179
|
if (!ls.includes("pondering: on")) return ls
|
|
103
180
|
const st = statuses()[props.sessionID]
|
|
104
181
|
const busy = st?.state === "busy"
|
|
@@ -129,9 +206,172 @@ export default {
|
|
|
129
206
|
)
|
|
130
207
|
},
|
|
131
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
|
+
|
|
132
370
|
return () => {
|
|
133
371
|
clearInterval(timer)
|
|
134
372
|
unwatchFile(statusFile, readStatus)
|
|
373
|
+
unwatchFile(verifierFile, readVerifier)
|
|
374
|
+
unwatchFile(probeStatusFile, readProbe)
|
|
135
375
|
stop()
|
|
136
376
|
}
|
|
137
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
|
+
}
|