opencode-agent-plus 0.3.1 → 0.4.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/package.json +1 -1
- package/src/antiloop.ts +66 -0
- package/src/antirep/detect.ts +57 -0
- package/src/antirep/index.ts +29 -0
- package/src/antirep/stream.ts +94 -0
- package/src/frontmatter.ts +14 -19
- package/src/greenlight.ts +48 -0
- package/src/index.ts +15 -16
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-agent-plus",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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",
|
package/src/antiloop.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Anti-loop: denies a tool after `max_same_tool` calls in a row within ONE
|
|
2
|
+
// user message. The count resets when the user sends a new message, so a
|
|
3
|
+
// long multi-step task is never punished.
|
|
4
|
+
// The count lives in memory only; nothing is sent to the server.
|
|
5
|
+
export interface AntiLoopOptions {
|
|
6
|
+
/** Reads the agent's frontmatter keys. */
|
|
7
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
8
|
+
/** Optional debug logger. */
|
|
9
|
+
debug?: (line: string) => void
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Real user messages only: skips injections wrapped in <system-reminder>
|
|
13
|
+
// (ours and other plugins').
|
|
14
|
+
export function realUserTexts(messages: any[]): string[] {
|
|
15
|
+
const texts: string[] = []
|
|
16
|
+
for (const m of messages) {
|
|
17
|
+
if (m.role !== "user") continue
|
|
18
|
+
const parts = m.content ?? m.parts ?? []
|
|
19
|
+
const text = parts.map((p: any) => p.text ?? "").join("")
|
|
20
|
+
if (text.trimStart().startsWith("<system-reminder>")) continue
|
|
21
|
+
texts.push(text)
|
|
22
|
+
}
|
|
23
|
+
return texts
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function countUserTurns(messages: any[]): number {
|
|
27
|
+
return realUserTexts(messages).length
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function antiLoop(ctx: any, options: AntiLoopOptions) {
|
|
31
|
+
// Per session: the tool last called and how many times in a row.
|
|
32
|
+
const streaks = new Map<string, { action: string; count: number }>()
|
|
33
|
+
// Per session: how many real user messages were seen last time.
|
|
34
|
+
const turns = new Map<string, number>()
|
|
35
|
+
|
|
36
|
+
// The context hook runs before every model call: a new user message means
|
|
37
|
+
// the streak from the previous message no longer counts.
|
|
38
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
39
|
+
const key = String(event.sessionID)
|
|
40
|
+
const turn = countUserTurns(event.messages)
|
|
41
|
+
if (turns.get(key) !== turn) {
|
|
42
|
+
turns.set(key, turn)
|
|
43
|
+
streaks.delete(key)
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
48
|
+
if (!event.agent) return
|
|
49
|
+
// A call already denied (green light runs first) never ran: do not count it.
|
|
50
|
+
if (event.effect === "deny") return
|
|
51
|
+
const { keys } = await options.settings(event.agent)
|
|
52
|
+
const max = Number(keys.max_same_tool)
|
|
53
|
+
if (!Number.isInteger(max) || max < 1 || event.action === "task") return
|
|
54
|
+
const key = String(event.sessionID)
|
|
55
|
+
const prev = streaks.get(key)
|
|
56
|
+
const count = prev && prev.action === event.action ? prev.count + 1 : 1
|
|
57
|
+
streaks.set(key, { action: event.action, count })
|
|
58
|
+
if (count <= max) return
|
|
59
|
+
// Reset so the agent gets a fresh budget after being denied once.
|
|
60
|
+
streaks.set(key, { action: event.action, count: 0 })
|
|
61
|
+
event.effect = "deny"
|
|
62
|
+
event.message = `You already used '${event.action}' ${max} times in a row in this message. You are probably stuck in a doom loop. Try something else or report the issue to the user.`
|
|
63
|
+
options.debug?.(`anti-loop: denied ${event.action} session=${key} count=${count} max=${max}`)
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Pure repetition detection: finds a short piece of text repeated back-to-back
|
|
2
|
+
// many times, like "parameter=parameter=parameter=...".
|
|
3
|
+
// No streams, no state, no opencode types here — easy to test on its own.
|
|
4
|
+
|
|
5
|
+
export interface RepetitionHit {
|
|
6
|
+
/** The repeated piece, e.g. "parameter=". */
|
|
7
|
+
unit: string
|
|
8
|
+
/** How many times it appeared back-to-back. */
|
|
9
|
+
times: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface DetectOptions {
|
|
13
|
+
/** Longest repeated piece to look for. Default 64 characters. */
|
|
14
|
+
maxUnit?: number
|
|
15
|
+
/** Minimum back-to-back repeats to call it repetition. Default 5. */
|
|
16
|
+
minTimes?: number
|
|
17
|
+
/** Minimum total characters (unit x times) to call it repetition. Default 40. */
|
|
18
|
+
minTotal?: number
|
|
19
|
+
/** Only the last this-many characters are examined. Default 4096. */
|
|
20
|
+
window?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Looks at the tail of `text` for a block of length `unit` repeated `minTimes`
|
|
24
|
+
// or more times in a row. Returns the longest/most repeated block found.
|
|
25
|
+
export function findRepetition(text: string, options: DetectOptions = {}): RepetitionHit | undefined {
|
|
26
|
+
const maxUnit = options.maxUnit ?? 64
|
|
27
|
+
const minTimes = options.minTimes ?? 5
|
|
28
|
+
const minTotal = options.minTotal ?? 40
|
|
29
|
+
const window = options.window ?? 4096
|
|
30
|
+
|
|
31
|
+
const tail = text.length > window ? text.slice(-window) : text
|
|
32
|
+
let best: RepetitionHit | undefined
|
|
33
|
+
|
|
34
|
+
for (let unit = 1; unit <= maxUnit; unit++) {
|
|
35
|
+
// Need room for minTimes copies ending at (or near) the tail's end.
|
|
36
|
+
// Start scanning from every position where a run could reach the minimum.
|
|
37
|
+
const limit = tail.length - unit * minTimes
|
|
38
|
+
if (limit < 0) break
|
|
39
|
+
for (let start = 0; start <= limit; start++) {
|
|
40
|
+
const block = tail.slice(start, start + unit)
|
|
41
|
+
let times = 1
|
|
42
|
+
let at = start + unit
|
|
43
|
+
while (at + unit <= tail.length && tail.startsWith(block, at)) {
|
|
44
|
+
times++
|
|
45
|
+
at += unit
|
|
46
|
+
}
|
|
47
|
+
if (times >= minTimes && times * unit >= minTotal) {
|
|
48
|
+
const hit = { unit: block, times }
|
|
49
|
+
if (!best || times * unit > best.times * best.unit.length) best = hit
|
|
50
|
+
}
|
|
51
|
+
// Skip ahead: a run of `times` blocks cannot hide another qualifying
|
|
52
|
+
// run that starts inside it and ends later than `at`.
|
|
53
|
+
if (times > 1) start = at - unit
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return best
|
|
57
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Anti-repetition: watches the model's reply stream and interrupts the
|
|
2
|
+
// session when the text starts repeating itself (e.g. "parameter=parameter=...").
|
|
3
|
+
// Enabled per agent with `anti_repetition: on` in its frontmatter.
|
|
4
|
+
import { scanResponse } from "./stream"
|
|
5
|
+
import type { RepetitionHit } from "./detect"
|
|
6
|
+
|
|
7
|
+
export interface AntiRepetitionOptions {
|
|
8
|
+
/** Reads the agent's frontmatter keys. */
|
|
9
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
+
/** Optional debug logger. */
|
|
11
|
+
debug?: (line: string) => void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function antiRepetition(ctx: any, options: AntiRepetitionOptions) {
|
|
15
|
+
return ctx.session.hook("http.response", async (event: any) => {
|
|
16
|
+
const { keys } = await options.settings(event.agent)
|
|
17
|
+
if (keys.anti_repetition !== "on") return
|
|
18
|
+
options.debug?.(`anti-repetition: http.response fired session=${event.sessionID} agent=${event.agent}`)
|
|
19
|
+
const sessionID = event.sessionID
|
|
20
|
+
const stop = (hit: RepetitionHit) => {
|
|
21
|
+
options.debug?.(
|
|
22
|
+
`anti-repetition: session=${sessionID} unit=${JSON.stringify(hit.unit)} times=${hit.times} -> interrupt`,
|
|
23
|
+
)
|
|
24
|
+
// Fire once per reply; the interrupt ends the run.
|
|
25
|
+
ctx.session.interrupt({ sessionID }).catch(() => {})
|
|
26
|
+
}
|
|
27
|
+
event.response = scanResponse(event.response, { onHit: stop, debug: options.debug })
|
|
28
|
+
})
|
|
29
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Wraps a model reply stream so the model's words can be scanned as they
|
|
2
|
+
// arrive. The stream itself is protocol text (JSON chunks), so we pull the
|
|
3
|
+
// words out of it first, then scan only those.
|
|
4
|
+
// When the scanner says stop, onHit fires once; the stream itself keeps
|
|
5
|
+
// flowing (opencode's interrupt ends the run, not us).
|
|
6
|
+
import { findRepetition, type RepetitionHit } from "./detect"
|
|
7
|
+
|
|
8
|
+
export interface ScanOptions {
|
|
9
|
+
/** Called at most once, on the first repetition found. */
|
|
10
|
+
onHit: (hit: RepetitionHit) => void
|
|
11
|
+
/** Scan when at least this many new characters arrived since last scan. Default 256. */
|
|
12
|
+
scanEvery?: number
|
|
13
|
+
/** Optional debug logger. */
|
|
14
|
+
debug?: (line: string) => void
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Pulls model words out of protocol text: every `"content":"..."` value,
|
|
18
|
+
// with JSON escapes decoded. Unfinished tail (partial value) stays in `rest`.
|
|
19
|
+
export function extractText(chunk: string): { text: string; rest: string } {
|
|
20
|
+
let text = ""
|
|
21
|
+
let i = 0
|
|
22
|
+
for (;;) {
|
|
23
|
+
const key = chunk.indexOf('"content":"', i)
|
|
24
|
+
if (key < 0) return { text, rest: chunk.slice(i) }
|
|
25
|
+
let j = key + '"content":"'.length
|
|
26
|
+
let value = ""
|
|
27
|
+
let closed = false
|
|
28
|
+
while (j < chunk.length) {
|
|
29
|
+
const c = chunk[j]
|
|
30
|
+
if (c === "\\") {
|
|
31
|
+
if (j + 1 >= chunk.length) break // escape split across chunks: wait
|
|
32
|
+
const next = chunk[j + 1]
|
|
33
|
+
value += next === "n" ? "\n" : next === "t" ? "\t" : next
|
|
34
|
+
j += 2
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
if (c === '"') {
|
|
38
|
+
closed = true
|
|
39
|
+
j++
|
|
40
|
+
break
|
|
41
|
+
}
|
|
42
|
+
value += c
|
|
43
|
+
j++
|
|
44
|
+
}
|
|
45
|
+
if (!closed) return { text, rest: chunk.slice(key) }
|
|
46
|
+
text += value
|
|
47
|
+
i = j
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function scanResponse(response: Response, options: ScanOptions): Response {
|
|
52
|
+
if (!response.body) return response
|
|
53
|
+
const scanEvery = options.scanEvery ?? 256
|
|
54
|
+
const decoder = new TextDecoder()
|
|
55
|
+
let pending = "" // protocol text not yet parsed (ends mid-value)
|
|
56
|
+
let words = "" // model words, trimmed by findRepetition's window
|
|
57
|
+
let sinceScan = 0
|
|
58
|
+
let fired = false
|
|
59
|
+
|
|
60
|
+
// Throws inside transform/flush so the stream dies and the reader stops.
|
|
61
|
+
const check = (final: boolean) => {
|
|
62
|
+
if (fired) return
|
|
63
|
+
const hit = findRepetition(words)
|
|
64
|
+
if (!hit) return
|
|
65
|
+
fired = true
|
|
66
|
+
options.debug?.(`anti-repetition: HIT unit=${JSON.stringify(hit.unit)} times=${hit.times} final=${final}`)
|
|
67
|
+
options.onHit(hit)
|
|
68
|
+
throw new Error(`agent-plus: anti-repetition stopped the reply ("${hit.unit}" repeated ${hit.times} times)`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const checker = new TransformStream<Uint8Array, Uint8Array>({
|
|
72
|
+
transform(chunk, controller) {
|
|
73
|
+
if (sinceScan === 0 && words === "" && pending === "") options.debug?.(`anti-repetition: first chunk ${chunk.byteLength} bytes`)
|
|
74
|
+
if (fired) throw new Error("agent-plus: anti-repetition stopped the reply")
|
|
75
|
+
controller.enqueue(chunk)
|
|
76
|
+
const { text, rest } = extractText(pending + decoder.decode(chunk, { stream: true }))
|
|
77
|
+
pending = rest
|
|
78
|
+
if (!text) return
|
|
79
|
+
words += text
|
|
80
|
+
sinceScan += text.length
|
|
81
|
+
check(false)
|
|
82
|
+
},
|
|
83
|
+
flush() {
|
|
84
|
+
options.debug?.(`anti-repetition: stream end words=${words.length} fired=${fired}`)
|
|
85
|
+
check(true)
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
return new Response(response.body.pipeThrough(checker), {
|
|
90
|
+
status: response.status,
|
|
91
|
+
statusText: response.statusText,
|
|
92
|
+
headers: response.headers,
|
|
93
|
+
})
|
|
94
|
+
}
|
package/src/frontmatter.ts
CHANGED
|
@@ -13,24 +13,7 @@ export const BODY = [
|
|
|
13
13
|
"top_k",
|
|
14
14
|
"min_p",
|
|
15
15
|
"presence_penalty",
|
|
16
|
-
"frequency_penalty",
|
|
17
|
-
"repetition_penalty",
|
|
18
16
|
"repeat_penalty",
|
|
19
|
-
"repeat_last_n",
|
|
20
|
-
"penalty_last_n",
|
|
21
|
-
"dry_multiplier",
|
|
22
|
-
"dry_allowed_length",
|
|
23
|
-
"dry_penalty_last_n",
|
|
24
|
-
"dry_base",
|
|
25
|
-
"mirostat",
|
|
26
|
-
"mirostat_tau",
|
|
27
|
-
"mirostat_eta",
|
|
28
|
-
"typical_p",
|
|
29
|
-
"xtc_threshold",
|
|
30
|
-
"xtc_probability",
|
|
31
|
-
"min_keep",
|
|
32
|
-
"ignore_eos",
|
|
33
|
-
"seed",
|
|
34
17
|
"max_completion_tokens",
|
|
35
18
|
"reasoning_budget_tokens",
|
|
36
19
|
"reasoning_effort",
|
|
@@ -53,7 +36,7 @@ const OPENCODE_KEYS = [
|
|
|
53
36
|
"disabled",
|
|
54
37
|
"request",
|
|
55
38
|
]
|
|
56
|
-
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "reminder_file", "on_error_command", "safe_commands", ...BODY, ...TEMPLATE_KWARGS])
|
|
39
|
+
const KNOWN = new Set([...OPENCODE_KEYS, "reminder", "reminder_file", "on_error_command", "safe_commands", "anti_repetition", "max_same_tool", "green_light", "green_light_words", ...BODY, ...TEMPLATE_KWARGS])
|
|
57
40
|
|
|
58
41
|
export const read = (file: string) => readFile(file, "utf8").catch(() => "")
|
|
59
42
|
|
|
@@ -153,6 +136,18 @@ export async function problems(file: string, keys: Record<string, string>) {
|
|
|
153
136
|
keys.safe_commands && !["allow", "none"].includes(keys.safe_commands)
|
|
154
137
|
? [`safe_commands: must be allow or none`]
|
|
155
138
|
: []
|
|
139
|
+
const antiRepetition =
|
|
140
|
+
keys.anti_repetition && !["on", "off"].includes(keys.anti_repetition)
|
|
141
|
+
? [`anti_repetition: must be on or off`]
|
|
142
|
+
: []
|
|
143
|
+
const maxSameTool =
|
|
144
|
+
keys.max_same_tool && !/^\d+$/.test(keys.max_same_tool)
|
|
145
|
+
? [`max_same_tool: must be a whole number`]
|
|
146
|
+
: []
|
|
147
|
+
const greenLight =
|
|
148
|
+
keys.green_light && !["on", "off"].includes(keys.green_light)
|
|
149
|
+
? [`green_light: must be on or off`]
|
|
150
|
+
: []
|
|
156
151
|
const wrong = [...BODY, ...TEMPLATE_KWARGS]
|
|
157
152
|
.filter((k) => k in keys)
|
|
158
153
|
.flatMap((k) => {
|
|
@@ -163,5 +158,5 @@ export async function problems(file: string, keys: Record<string, string>) {
|
|
|
163
158
|
keys.reminder_file && !(await read(path.resolve(path.dirname(file), keys.reminder_file)))
|
|
164
159
|
? [`reminder_file: ${keys.reminder_file} not found or empty`]
|
|
165
160
|
: []
|
|
166
|
-
return [...misspelledKeys(keys), ...wrong, ...missing, ...safeCommands]
|
|
161
|
+
return [...misspelledKeys(keys), ...wrong, ...missing, ...safeCommands, ...antiRepetition, ...maxSameTool, ...greenLight]
|
|
167
162
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Green light: with `green_light: on`, every tool is denied unless the user's
|
|
2
|
+
// latest message ends with a green-light word (in its last 3 words), e.g.
|
|
3
|
+
// "fix the config, go". The agent must ask, the user must approve.
|
|
4
|
+
// Everything stays in memory; nothing is sent to the server.
|
|
5
|
+
import { realUserTexts } from "./antiloop"
|
|
6
|
+
|
|
7
|
+
export interface GreenLightOptions {
|
|
8
|
+
/** Reads the agent's frontmatter keys. */
|
|
9
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
+
/** Optional debug logger. */
|
|
11
|
+
debug?: (line: string) => void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Words that mean "you may act", checked in the last 3 words of the message.
|
|
15
|
+
// Agents replace the list with `green_light_words: yes, go, do`.
|
|
16
|
+
const DEFAULT_GREEN_LIGHT_WORDS = ["yes", "do", "go", "ok", "okay", "fine", "good", "fix", "try", "run"]
|
|
17
|
+
|
|
18
|
+
// Resolves `green_light_words` to the effective word list and its match test.
|
|
19
|
+
function greenLightWords(words: string | undefined): { list: string[]; test: RegExp } {
|
|
20
|
+
const list = words?.split(",").map((w) => w.trim().toLowerCase()).filter(Boolean)
|
|
21
|
+
const safe = list?.length ? list : DEFAULT_GREEN_LIGHT_WORDS
|
|
22
|
+
return { list: safe, test: new RegExp(`\\b(${safe.map((w) => w.replace(/[^\w-]/g, "")).join("|")})\\b`, "i") }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function greenLight(ctx: any, options: GreenLightOptions) {
|
|
26
|
+
// Per session: the user's latest real message text.
|
|
27
|
+
const lastUser = new Map<string, string>()
|
|
28
|
+
|
|
29
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
30
|
+
const texts = realUserTexts(event.messages)
|
|
31
|
+
lastUser.set(String(event.sessionID), texts[texts.length - 1] ?? "")
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
35
|
+
if (!event.agent) return
|
|
36
|
+
const { keys } = await options.settings(event.agent)
|
|
37
|
+
if (keys.green_light !== "on") return
|
|
38
|
+
// Reading files is always allowed; only acting needs the word.
|
|
39
|
+
if (event.action === "read") return
|
|
40
|
+
const text = lastUser.get(String(event.sessionID)) ?? ""
|
|
41
|
+
const tail = text.trim().split(/\s+/).slice(-3).join(" ")
|
|
42
|
+
const { list, test } = greenLightWords(keys.green_light_words)
|
|
43
|
+
if (test.test(tail)) return
|
|
44
|
+
event.effect = "deny"
|
|
45
|
+
event.message = `Green light is on: tools run only when the user's message ends with a green-light word (${list.join(", ")}). Ask the user to approve, or answer without tools.`
|
|
46
|
+
options.debug?.(`green-light: denied ${event.action} session=${String(event.sessionID)} tail=${JSON.stringify(tail)}`)
|
|
47
|
+
})
|
|
48
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,9 @@ import { spawn } from "node:child_process"
|
|
|
3
3
|
import { appendFileSync, existsSync } from "node:fs"
|
|
4
4
|
import { agentFile, BODY, frontmatter, problems, read, requestValue, TEMPLATE_KWARGS } from "./frontmatter"
|
|
5
5
|
import { isSafe } from "./safecommands"
|
|
6
|
+
import { antiRepetition } from "./antirep"
|
|
7
|
+
import { antiLoop } from "./antiloop"
|
|
8
|
+
import { greenLight } from "./greenlight"
|
|
6
9
|
|
|
7
10
|
// Runs a shell command (single or multi-line) and waits for it to finish.
|
|
8
11
|
// zsh so ~/.zshenv functions and aliases (like server-on) are available; falls back to sh.
|
|
@@ -40,6 +43,7 @@ export default {
|
|
|
40
43
|
const file = process.env.AGENT_PLUS_DEBUG
|
|
41
44
|
if (file) try { appendFileSync(file, `${new Date().toISOString()} ${line}\n`) } catch {}
|
|
42
45
|
}
|
|
46
|
+
debug(`plugin loaded directory=${directory}`)
|
|
43
47
|
|
|
44
48
|
// `on_error_command`: when a request fails because the server is unreachable,
|
|
45
49
|
// run the agent's command (e.g. wake it up) and ask for a quick retry.
|
|
@@ -60,28 +64,23 @@ export default {
|
|
|
60
64
|
// Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands: none`.
|
|
61
65
|
// It skips the ask window for read-only tool calls and safe shell commands.
|
|
62
66
|
// Configured `deny` rules are final and never reach this hook; anything unsafe passes through unchanged.
|
|
63
|
-
// `max_same_tool: n` denies a tool after n calls in a row without another tool in between.
|
|
64
|
-
// Varied work resets the count; only a streak trips it.
|
|
65
|
-
const streaks = new Map<string, { action: string; count: number }>()
|
|
66
67
|
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
67
|
-
if (!event.agent) return
|
|
68
|
+
if (event.effect !== "ask" || !event.agent) return
|
|
68
69
|
const { keys } = await settings(event.agent)
|
|
69
|
-
const max = Number(keys.max_same_tool)
|
|
70
|
-
if (Number.isInteger(max) && max >= 1 && event.action !== "task") {
|
|
71
|
-
const prev = streaks.get(event.sessionID)
|
|
72
|
-
const count = prev && prev.action === event.action ? prev.count + 1 : 1
|
|
73
|
-
streaks.set(event.sessionID, { action: event.action, count })
|
|
74
|
-
if (count > max) {
|
|
75
|
-
event.effect = "deny"
|
|
76
|
-
event.message = `You already used '${event.action}' more than the maximum allowed ${max} times in a row. You are probably stuck in a doom loop. Try something else or report the issue to user.`
|
|
77
|
-
return
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
if (event.effect !== "ask") return
|
|
81
70
|
if (keys.safe_commands === "none") return
|
|
82
71
|
if (isSafe(event.action, event.resources ?? [])) event.effect = "allow"
|
|
83
72
|
})
|
|
84
73
|
|
|
74
|
+
// `anti_repetition: on` — interrupt the run when the model's text repeats itself.
|
|
75
|
+
await antiRepetition(ctx, { settings, debug })
|
|
76
|
+
|
|
77
|
+
// `green_light: on` — deny tools unless the user's latest message ends with a go-ahead word.
|
|
78
|
+
// Registered first so its deny wins and the anti-loop below does not count a denied call.
|
|
79
|
+
await greenLight(ctx, { settings, debug })
|
|
80
|
+
|
|
81
|
+
// `max_same_tool: n` — deny a tool after n calls in a row within one user message.
|
|
82
|
+
await antiLoop(ctx, { settings, debug })
|
|
83
|
+
|
|
85
84
|
await ctx.session.hook("context", async (event: any) => {
|
|
86
85
|
// A request got through: allow on_error_command to fire again next time.
|
|
87
86
|
woken.delete(event.sessionID)
|