opencode-agent-plus 0.4.2 → 0.5.1
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 +50 -15
- package/package.json +30 -7
- package/src/clockwork.ts +125 -0
- package/src/frontmatter.test.ts +0 -2
- package/src/frontmatter.ts +15 -3
- package/src/httprequest.ts +8 -1
- package/src/index.ts +10 -0
- package/src/misplacedtag.test.ts +47 -0
- package/src/misplacedtag.ts +116 -0
- package/src/presets.ts +1 -7
- package/src/tooloverrides.ts +48 -0
- package/src/tui.tsx +13 -1
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
|
|
@@ -83,22 +81,20 @@ You help the user write and edit text.
|
|
|
83
81
|
| `reminder` | `concise`, `ultra-concise`, `creative`, `off`, or text (one line or a `\|` block) | Preset or custom reminder, added as the last message of every model request |
|
|
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
83
|
| `safe_commands` | `none` (default: on) | Turn safe-command auto-allow off for this agent |
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
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
89
|
| `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) |
|
|
98
90
|
| `max_completion_tokens` | whole number | Request body |
|
|
99
|
-
| `reasoning_budget_tokens` | whole number | Request body
|
|
91
|
+
| `reasoning_budget_tokens` | whole number | Request body |
|
|
100
92
|
| `reasoning_effort` | `none`, `minimal`, `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
|
+
| `clockwork` | `on` or `off` (default: off) | Run the agent hands-off with auto-continue |
|
|
102
98
|
|
|
103
99
|
Names are sent as written. A setting with a wrong value is not sent.
|
|
104
100
|
|
|
@@ -145,7 +141,7 @@ chunks, like llama.cpp with `--cache-reuse`, may recover part of it.
|
|
|
145
141
|
At start, a toast lists problems in agent files:
|
|
146
142
|
|
|
147
143
|
- misspelled keys, like `temprature → temperature`
|
|
148
|
-
- wrong values, like `
|
|
144
|
+
- wrong values, like `max_completion_tokens: must be a whole number`
|
|
149
145
|
|
|
150
146
|
Unknown keys that don't look like a misspelling are left alone, so other plugins can add their own keys.
|
|
151
147
|
With no problems, the toast says "agent-plus is loaded".
|
|
@@ -190,12 +186,12 @@ Turn it off for one agent with `safe_commands: none` in its frontmatter.
|
|
|
190
186
|
|
|
191
187
|
## Anti-repetition
|
|
192
188
|
|
|
193
|
-
With `
|
|
189
|
+
With `max_word_repeat: on`, agent-plus watches the model's reply as it streams. When the same stretch of text
|
|
194
190
|
repeats 5 or more times, the reply is cut and the session is interrupted, instead of filling up with garbage.
|
|
195
191
|
|
|
196
192
|
## Anti-loop
|
|
197
193
|
|
|
198
|
-
With `
|
|
194
|
+
With `max_tool_repeat: 5`, the same tool call (same tool, same arguments) may repeat at most 5 times in a row.
|
|
199
195
|
The 6th is denied with a message telling the model to stop. The count resets when you send a new message.
|
|
200
196
|
|
|
201
197
|
## Pondering
|
|
@@ -206,6 +202,13 @@ saved to history). The model ponders where the conversation is going. The
|
|
|
206
202
|
result rides into your next message as a `<pondering>` block, which the model
|
|
207
203
|
uses silently — like the reminder, it never replies to it.
|
|
208
204
|
|
|
205
|
+
## Misplaced tag filter
|
|
206
|
+
|
|
207
|
+
With `misplaced_tag_filter: on`, tag signs (`<`, `>`, `|`) that leak into the
|
|
208
|
+
thinking or message text are swapped for safe look-alikes, so they cannot break
|
|
209
|
+
the next turn. Tool calls are not touched. When a message was changed, a short
|
|
210
|
+
note is added so you do not copy broken code from it.
|
|
211
|
+
|
|
209
212
|
## Green light
|
|
210
213
|
|
|
211
214
|
With `manual_green_light: on`, tool calls are denied unless your latest message ends with an approval word (in its last
|
|
@@ -215,6 +218,38 @@ is always allowed. Set your own words with `manual_green_light_words: yes, do, g
|
|
|
215
218
|
With `auto_green_light: on`, the model checks itself before the first tool call of each turn: it must allow the call
|
|
216
219
|
and state its plan, or explain why it cannot. The check fires once per turn and is not saved in the chat history.
|
|
217
220
|
|
|
221
|
+
## Tool overrides
|
|
222
|
+
|
|
223
|
+
With `tools_override: <file>.json` (relative to the agent file), tool
|
|
224
|
+
descriptions are replaced with the ones from that file. The file maps tool
|
|
225
|
+
names to replacement descriptions:
|
|
226
|
+
|
|
227
|
+
```json
|
|
228
|
+
{
|
|
229
|
+
"bash": "Run a shell command.",
|
|
230
|
+
"read": "Read a file."
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Tools not listed keep their original description. The file is re-read only when
|
|
235
|
+
it changes on disk, so the prompt cache stays warm.
|
|
236
|
+
|
|
237
|
+
## Clockwork
|
|
238
|
+
|
|
239
|
+
With `clockwork: on`, the agent runs hands-off. Every permission ask is denied.
|
|
240
|
+
After each finished turn a judge request reads the plan and the work so far and
|
|
241
|
+
replies with one word:
|
|
242
|
+
|
|
243
|
+
- `CONTINUE` — the plugin sends a fresh "keep going" message. Every 7–10 turns
|
|
244
|
+
it instead nudges the agent to re-read its plan document (PLAN.md, TODO.md,
|
|
245
|
+
etc.) and list remaining work.
|
|
246
|
+
- `WAIT` — the agent is waiting on a background job, so the plugin waits 30s
|
|
247
|
+
and judges again.
|
|
248
|
+
- `DONE` — the plugin sends a wrap-up message. The next `DONE` sends a final
|
|
249
|
+
"JOB COMPLETED" line and stops the loop.
|
|
250
|
+
|
|
251
|
+
Only agents with `clockwork: on` are affected.
|
|
252
|
+
|
|
218
253
|
## Notes
|
|
219
254
|
|
|
220
255
|
- Use `max_completion_tokens`, not `max_tokens`: OpenCode already sends `max_completion_tokens`, and servers use that one.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-agent-plus",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "OpenCode plugin: safe-command auto-allow (no prompt for read-only calls), per-agent chat_template_kwargs (enable_thinking), sampling settings and system reminders from agent frontmatter. For llama.cpp, LiteLLM and OpenAI-compatible providers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Anoosh Ahmadi",
|
|
@@ -9,21 +9,44 @@
|
|
|
9
9
|
"url": "git+https://github.com/Anooshiravan/opencode-agent-plus.git"
|
|
10
10
|
},
|
|
11
11
|
"keywords": [
|
|
12
|
-
"opencode",
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
12
|
+
"opencode",
|
|
13
|
+
"opencode-plugin",
|
|
14
|
+
"opencode-agent",
|
|
15
|
+
"agent",
|
|
16
|
+
"agents",
|
|
17
|
+
"frontmatter",
|
|
18
|
+
"llama.cpp",
|
|
19
|
+
"llama-cpp",
|
|
20
|
+
"litellm",
|
|
21
|
+
"openai-compatible",
|
|
22
|
+
"local-llm",
|
|
23
|
+
"chat_template_kwargs",
|
|
24
|
+
"chat-template-kwargs",
|
|
25
|
+
"enable_thinking",
|
|
26
|
+
"thinking",
|
|
27
|
+
"reasoning",
|
|
28
|
+
"temperature",
|
|
29
|
+
"sampling",
|
|
30
|
+
"top_p",
|
|
31
|
+
"min_p",
|
|
32
|
+
"system-reminder",
|
|
33
|
+
"reminder",
|
|
34
|
+
"qwen"
|
|
17
35
|
],
|
|
18
36
|
"type": "module",
|
|
19
37
|
"exports": {
|
|
20
38
|
".": "./src/index.ts",
|
|
21
39
|
"./tui": "./src/tui.tsx"
|
|
22
40
|
},
|
|
23
|
-
"files": [
|
|
41
|
+
"files": [
|
|
42
|
+
"src"
|
|
43
|
+
],
|
|
24
44
|
"peerDependencies": {
|
|
25
45
|
"@opentui/core": ">=0.7.0",
|
|
26
46
|
"@opentui/solid": ">=0.7.0",
|
|
27
47
|
"solid-js": ">=1.9.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"tsx": "^4.23.15"
|
|
28
51
|
}
|
|
29
52
|
}
|
package/src/clockwork.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// `clockwork: on` — hands-off loop. Denies every permission ask, and after the
|
|
2
|
+
// agent finishes a turn it asks the LLM endpoint to write a fresh proactive
|
|
3
|
+
// message, then sends it so the agent keeps going. Only agents with
|
|
4
|
+
// `clockwork: on` are affected.
|
|
5
|
+
import { log } from "./log"
|
|
6
|
+
|
|
7
|
+
const FALLBACK =
|
|
8
|
+
"Work autonomously. Decide for yourself, pick the option that best fits " +
|
|
9
|
+
"the task and the surrounding code, and keep going. If the situation is " +
|
|
10
|
+
"ambiguous, trust your feeling. Use all available tools to solve the task."
|
|
11
|
+
|
|
12
|
+
const META =
|
|
13
|
+
"You are nudging an autonomous coding agent that just stopped. Write ONE " +
|
|
14
|
+
"short imperative sentence telling it what to do next to keep making " +
|
|
15
|
+
"progress. Do not greet, do not ask questions, do not repeat prior work. " +
|
|
16
|
+
"Reply with that one sentence only."
|
|
17
|
+
|
|
18
|
+
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
|
+
|
|
38
|
+
export async function clockwork(ctx: any, { settings }: { settings: (agent: string) => Promise<{ keys: Record<string, 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>() })
|
|
40
|
+
const running = shared.running as Set<string> // a keep-going prompt is in flight
|
|
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
|
|
46
|
+
|
|
47
|
+
// Deny every permission ask for clockwork agents.
|
|
48
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
49
|
+
if (!event.agent) return
|
|
50
|
+
const { keys } = await settings(event.agent)
|
|
51
|
+
if (keys.clockwork !== "on") return
|
|
52
|
+
if (event.effect !== "ask") return
|
|
53
|
+
event.effect = "deny"
|
|
54
|
+
event.message = "Clockwork: permission denied. Pick a different approach."
|
|
55
|
+
denied.add(String(event.sessionID))
|
|
56
|
+
log(`clockwork: denied ask session=${event.sessionID} action=${event.action}`)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
// After each finished turn, ask the endpoint for a fresh nudge and send it.
|
|
60
|
+
const controller = new AbortController()
|
|
61
|
+
log(`clockwork: listener started`)
|
|
62
|
+
void (async () => {
|
|
63
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
64
|
+
if (event.id === shared.lastEvent) continue
|
|
65
|
+
shared.lastEvent = event.id
|
|
66
|
+
if (event.type !== "session.execution.succeeded") continue
|
|
67
|
+
const sessionID: string | undefined = event.data?.sessionID
|
|
68
|
+
if (!sessionID || running.has(sessionID)) continue
|
|
69
|
+
try {
|
|
70
|
+
const session = await ctx.session.get({ sessionID })
|
|
71
|
+
const { keys } = await settings(session.agent)
|
|
72
|
+
if (keys.clockwork !== "on") continue
|
|
73
|
+
if (stopped.has(sessionID)) continue
|
|
74
|
+
running.add(sessionID)
|
|
75
|
+
const wasDenied = denied.delete(sessionID)
|
|
76
|
+
|
|
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 })
|
|
111
|
+
const text = String(next).trim() || FALLBACK
|
|
112
|
+
|
|
113
|
+
const final = wasDenied ? `Request is rejected. ${text}` : text
|
|
114
|
+
log(`clockwork: continuing session=${sessionID} denied=${wasDenied} text=${final}`)
|
|
115
|
+
await ctx.session.prompt({ sessionID, text: final, delivery: "steer" })
|
|
116
|
+
} catch (error) {
|
|
117
|
+
log(`clockwork: prompt failed session=${sessionID} error=${String(error)}`)
|
|
118
|
+
} finally {
|
|
119
|
+
running.delete(sessionID)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
})().catch((error) => log(`clockwork: listener died error=${String(error)}`))
|
|
123
|
+
|
|
124
|
+
return () => controller.abort()
|
|
125
|
+
}
|
package/src/frontmatter.test.ts
CHANGED
|
@@ -8,8 +8,6 @@ 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
12
|
expect(requestValue("reasoning_effort", "bad")).toEqual({ error: "reasoning_effort: must be one of none, minimal, low, medium, high, xhigh" })
|
|
15
13
|
})
|
package/src/frontmatter.ts
CHANGED
|
@@ -14,7 +14,7 @@ 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
20
|
temperature: [0.2, 1.4],
|
|
@@ -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", ...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", "tools_override", ...BODY, ...TEMPLATE_KWARGS])
|
|
41
41
|
|
|
42
42
|
export const read = (file: string) => readFile(file, "utf8").catch(() => "")
|
|
43
43
|
|
|
@@ -159,11 +159,23 @@ export async function problems(file: string, keys: Record<string, string>) {
|
|
|
159
159
|
keys.pondering && !["on", "off"].includes(keys.pondering)
|
|
160
160
|
? [`pondering: must be on or off`]
|
|
161
161
|
: []
|
|
162
|
+
const misplacedTagFilter =
|
|
163
|
+
keys.misplaced_tag_filter && !["on", "off"].includes(keys.misplaced_tag_filter)
|
|
164
|
+
? [`misplaced_tag_filter: must be on or off`]
|
|
165
|
+
: []
|
|
166
|
+
const clockwork =
|
|
167
|
+
keys.clockwork && !["on", "off"].includes(keys.clockwork)
|
|
168
|
+
? [`clockwork: must be on or off`]
|
|
169
|
+
: []
|
|
170
|
+
const toolOverrides =
|
|
171
|
+
keys.tools_override !== undefined && !keys.tools_override.trim()
|
|
172
|
+
? [`tools_override: must name a JSON file`]
|
|
173
|
+
: []
|
|
162
174
|
const wrong = [...BODY, ...TEMPLATE_KWARGS]
|
|
163
175
|
.filter((k) => k in keys)
|
|
164
176
|
.flatMap((k) => {
|
|
165
177
|
const result = requestValue(k, keys[k])
|
|
166
178
|
return "error" in result ? [result.error] : []
|
|
167
179
|
})
|
|
168
|
-
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering]
|
|
180
|
+
return [...misspelledKeys(keys), ...wrong, ...safeCommands, ...maxWordRepeat, ...maxToolRepeat, ...greenLight, ...autoGreenLight, ...pondering, ...misplacedTagFilter, ...clockwork, ...toolOverrides]
|
|
169
181
|
}
|
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
|
@@ -8,6 +8,9 @@ import { autoGreenLight } from "./autogreenlight"
|
|
|
8
8
|
import { onErrorCommand } from "./onerrorcommand"
|
|
9
9
|
import { httpRequest } from "./httprequest"
|
|
10
10
|
import { pondering } from "./pondering"
|
|
11
|
+
import { misplacedTagFilter } from "./misplacedtag"
|
|
12
|
+
import { clockwork } from "./clockwork"
|
|
13
|
+
import { toolOverrides } from "./tooloverrides"
|
|
11
14
|
|
|
12
15
|
// Server half: adds the agent's reminders to every model request and its settings to the request body.
|
|
13
16
|
// The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
|
|
@@ -60,11 +63,18 @@ export default {
|
|
|
60
63
|
// `pondering: on` — think during idle time; the result rides into the next user message.
|
|
61
64
|
await pondering(ctx, { settings })
|
|
62
65
|
|
|
66
|
+
// `misplaced_tag_filter: on` — swap stray tag signs in thinking/message text for safe look-alikes.
|
|
67
|
+
await misplacedTagFilter(ctx, { settings })
|
|
68
|
+
|
|
69
|
+
// `clockwork: on` — deny all asks and keep the agent going on its own.
|
|
70
|
+
await clockwork(ctx, { settings })
|
|
71
|
+
|
|
63
72
|
await ctx.session.hook("context", async (event: any) => {
|
|
64
73
|
// A request got through: allow on_error_command to fire again next time.
|
|
65
74
|
allowWake(event.sessionID)
|
|
66
75
|
const { keys } = await settings(event.agent)
|
|
67
76
|
await httpRequest(event, { settings })
|
|
77
|
+
await toolOverrides(event, { settings })
|
|
68
78
|
const text = await reminderText(directory, keys)
|
|
69
79
|
if (!text) return
|
|
70
80
|
appendBlock(event, "system-reminder", text)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { filterResponse } from "./misplacedtag"
|
|
3
|
+
|
|
4
|
+
// Runs the filter over fake SSE chunks and returns the output text.
|
|
5
|
+
async function run(chunks: string[]) {
|
|
6
|
+
const body = new ReadableStream({
|
|
7
|
+
start(controller) {
|
|
8
|
+
for (const c of chunks) controller.enqueue(new TextEncoder().encode(c))
|
|
9
|
+
controller.close()
|
|
10
|
+
},
|
|
11
|
+
})
|
|
12
|
+
const out = await filterResponse(new Response(body)).text()
|
|
13
|
+
return out
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const chunk = (field: string, value: string) =>
|
|
17
|
+
`data: {"choices":[{"index":0,"delta":{"${field}":"${value}"}}]}\n\n`
|
|
18
|
+
|
|
19
|
+
test("swaps tag signs in content", async () => {
|
|
20
|
+
const out = await run([chunk("content", "a <|end|> b")])
|
|
21
|
+
expect(out).toContain("a <|end|> b")
|
|
22
|
+
expect(out).toContain("safe look-alikes")
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
test("swaps tag signs in reasoning_content, no note", async () => {
|
|
26
|
+
const out = await run([chunk("reasoning_content", "x <|think|> y")])
|
|
27
|
+
expect(out).toContain("x <|think|> y")
|
|
28
|
+
expect(out).not.toContain("safe look-alikes")
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test("leaves tool_calls alone", async () => {
|
|
32
|
+
const out = await run([`data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"{\\"a\\": 1<2}"}}]}}]}\n\n`])
|
|
33
|
+
expect(out).toContain("1<2")
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test("handles a field split across chunks", async () => {
|
|
37
|
+
const full = chunk("content", "a <|end|> b")
|
|
38
|
+
const cut = full.indexOf("<|")
|
|
39
|
+
const out = await run([full.slice(0, cut), full.slice(cut)])
|
|
40
|
+
expect(out).toContain("a <|end|> b")
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test("clean text passes through unchanged", async () => {
|
|
44
|
+
const out = await run([chunk("content", "plain text")])
|
|
45
|
+
expect(out).toContain("plain text")
|
|
46
|
+
expect(out).not.toContain("safe look-alikes")
|
|
47
|
+
})
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// `misplaced_tag_filter: on` — the server already splits the reply into
|
|
2
|
+
// `reasoning_content` (thinking) and `content` (message). Any tag sign that
|
|
3
|
+
// still shows up inside those fields is misplaced, so we swap it for a safe
|
|
4
|
+
// look-alike. Tool calls are left alone. When the message part was changed, a
|
|
5
|
+
// short note is appended so the user does not copy broken code.
|
|
6
|
+
import { log } from "./log"
|
|
7
|
+
|
|
8
|
+
export interface TagFilterOptions {
|
|
9
|
+
/** Reads the agent's frontmatter keys. */
|
|
10
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const NOTE = "\n\n[Note: some tag characters in this message were replaced with safe look-alikes. Do not copy/paste code from it.]"
|
|
14
|
+
|
|
15
|
+
// Sign → safe look-alike.
|
|
16
|
+
const SWAP: Record<string, string> = { "<": "<", ">": ">", "|": "|" }
|
|
17
|
+
|
|
18
|
+
const swap = (value: string) => value.replace(/[<>|]/g, (c) => SWAP[c])
|
|
19
|
+
|
|
20
|
+
// The two fields we filter, by their JSON key.
|
|
21
|
+
const KEYS = ['"content":"', '"reasoning_content":"']
|
|
22
|
+
|
|
23
|
+
// Rewrites complete `"<key>":"<value>"` fields in `text`. Returns the processed
|
|
24
|
+
// part, the unfinished tail, and whether the message part was changed.
|
|
25
|
+
function filter(text: string): { out: string; rest: string; messageChanged: boolean } {
|
|
26
|
+
let out = ""
|
|
27
|
+
let messageChanged = false
|
|
28
|
+
let i = 0
|
|
29
|
+
for (;;) {
|
|
30
|
+
// Find the nearest field key ahead.
|
|
31
|
+
let at = -1
|
|
32
|
+
let key = ""
|
|
33
|
+
for (const k of KEYS) {
|
|
34
|
+
const p = text.indexOf(k, i)
|
|
35
|
+
if (p >= 0 && (at < 0 || p < at)) {
|
|
36
|
+
at = p
|
|
37
|
+
key = k
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (at < 0) {
|
|
41
|
+
// No key left; keep a tail so a key split across chunks is not missed.
|
|
42
|
+
const keep = 24
|
|
43
|
+
out += text.slice(i, Math.max(i, text.length - keep))
|
|
44
|
+
return { out, rest: text.slice(Math.max(i, text.length - keep)), messageChanged }
|
|
45
|
+
}
|
|
46
|
+
out += text.slice(i, at)
|
|
47
|
+
let j = at + key.length
|
|
48
|
+
let value = ""
|
|
49
|
+
let closed = false
|
|
50
|
+
while (j < text.length) {
|
|
51
|
+
const c = text[j]
|
|
52
|
+
if (c === "\\") {
|
|
53
|
+
if (j + 1 >= text.length) break
|
|
54
|
+
value += c + text[j + 1]
|
|
55
|
+
j += 2
|
|
56
|
+
continue
|
|
57
|
+
}
|
|
58
|
+
if (c === '"') {
|
|
59
|
+
closed = true
|
|
60
|
+
j++
|
|
61
|
+
break
|
|
62
|
+
}
|
|
63
|
+
value += c
|
|
64
|
+
j++
|
|
65
|
+
}
|
|
66
|
+
if (!closed) return { out, rest: text.slice(at), messageChanged }
|
|
67
|
+
const swapped = swap(value)
|
|
68
|
+
if (key === '"content":"' && swapped !== value) messageChanged = true
|
|
69
|
+
out += key + swapped + '"'
|
|
70
|
+
i = j
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function filterResponse(response: Response): Response {
|
|
75
|
+
if (!response.body) return response
|
|
76
|
+
const decoder = new TextDecoder()
|
|
77
|
+
const encoder = new TextEncoder()
|
|
78
|
+
let pending = ""
|
|
79
|
+
let messageChanged = false
|
|
80
|
+
|
|
81
|
+
const stream = new TransformStream<Uint8Array, Uint8Array>({
|
|
82
|
+
transform(chunk, controller) {
|
|
83
|
+
const { out, rest, messageChanged: changed } = filter(pending + decoder.decode(chunk, { stream: true }))
|
|
84
|
+
pending = rest
|
|
85
|
+
messageChanged = messageChanged || changed
|
|
86
|
+
if (out) controller.enqueue(encoder.encode(out))
|
|
87
|
+
},
|
|
88
|
+
flush(controller) {
|
|
89
|
+
// Process whatever is left; emit the held tail as-is (stream is over).
|
|
90
|
+
const { out, rest, messageChanged: changed } = filter(pending + decoder.decode())
|
|
91
|
+
messageChanged = messageChanged || changed
|
|
92
|
+
const final = out + rest
|
|
93
|
+
if (final) controller.enqueue(encoder.encode(final))
|
|
94
|
+
if (messageChanged) {
|
|
95
|
+
const note = `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: NOTE } }] })}\n\n`
|
|
96
|
+
controller.enqueue(encoder.encode(note))
|
|
97
|
+
log("misplaced_tag_filter: note appended")
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
return new Response(response.body.pipeThrough(stream), {
|
|
103
|
+
status: response.status,
|
|
104
|
+
statusText: response.statusText,
|
|
105
|
+
headers: response.headers,
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function misplacedTagFilter(ctx: any, options: TagFilterOptions) {
|
|
110
|
+
return ctx.session.hook("http.response", async (event: any) => {
|
|
111
|
+
const { keys } = await options.settings(event.agent)
|
|
112
|
+
if (keys.misplaced_tag_filter !== "on") return
|
|
113
|
+
log(`misplaced_tag_filter: http.response fired session=${event.sessionID} agent=${event.agent}`)
|
|
114
|
+
event.response = filterResponse(event.response)
|
|
115
|
+
})
|
|
116
|
+
}
|
package/src/presets.ts
CHANGED
|
@@ -6,13 +6,7 @@ import { log } from "./log"
|
|
|
6
6
|
|
|
7
7
|
const PRESETS: Record<string, string> = {
|
|
8
8
|
concise: [
|
|
9
|
-
|
|
10
|
-
"Be concise in chat: short simple answers covering only the requested task. When request is unclear, say it so instead of guessing.",
|
|
11
|
-
"Always answer in plain simple English, no jargon.",
|
|
12
|
-
"Do NOT over-explain. Do not add details that are not asked. You are required to be short and quickly readable, NOT complete and comprehensive.",
|
|
13
|
-
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
14
|
-
"Never use chained shell commands (; or &&). Run one command per call; chaining causes permission and execution issues.",
|
|
15
|
-
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
9
|
+
"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.",
|
|
16
10
|
].join("\n"),
|
|
17
11
|
"ultra-concise": [
|
|
18
12
|
'You are "Concise" agents, a helpful assistant.',
|
|
@@ -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
|
@@ -24,6 +24,9 @@ function sidebarLines(keys: Record<string, string>) {
|
|
|
24
24
|
lines.push(`manual_green_light: ${onOff(keys.manual_green_light)}`)
|
|
25
25
|
lines.push(`auto_green_light: ${onOff(keys.auto_green_light)}`)
|
|
26
26
|
lines.push(`pondering: ${onOff(keys.pondering)}`)
|
|
27
|
+
lines.push(`misplaced_tag_filter: ${onOff(keys.misplaced_tag_filter)}`)
|
|
28
|
+
lines.push(`clockwork: ${onOff(keys.clockwork)}`)
|
|
29
|
+
lines.push(`tools_override: ${keys.tools_override ? "on" : "off"}`)
|
|
27
30
|
if ("reasoning_effort" in keys && "value" in requestValue("reasoning_effort", keys.reasoning_effort))
|
|
28
31
|
lines.push(`reasoning_effort: ${keys.reasoning_effort}`)
|
|
29
32
|
for (const k of BODY) {
|
|
@@ -85,8 +88,17 @@ export default {
|
|
|
85
88
|
async ({ agent }) => sidebarLines(frontmatter((await agentFile(directory, agent)).text)),
|
|
86
89
|
)
|
|
87
90
|
// Live line: spinner while pondering, "on (idle)" when enabled and done, "off" when disabled.
|
|
91
|
+
const cacheLine = createMemo(() => {
|
|
92
|
+
const msgs = ctx.data.session.message.list(props.sessionID) ?? []
|
|
93
|
+
const last = [...msgs].reverse().find((m: any) => m.type === "assistant" && m.tokens)
|
|
94
|
+
if (!last) return "cache: -"
|
|
95
|
+
const t = last.tokens
|
|
96
|
+
const total = t.input + t.cache.read
|
|
97
|
+
const pct = total > 0 ? ((t.cache.read / total) * 100).toFixed(1) : "0.0"
|
|
98
|
+
return `cache: ${pct}% (cached: ${t.cache.read} token · new: ${t.input} token)`
|
|
99
|
+
})
|
|
88
100
|
const shown = createMemo(() => {
|
|
89
|
-
const ls = lines() ?? []
|
|
101
|
+
const ls = [...(lines() ?? []), cacheLine()]
|
|
90
102
|
if (!ls.includes("pondering: on")) return ls
|
|
91
103
|
const st = statuses()[props.sessionID]
|
|
92
104
|
const busy = st?.state === "busy"
|