opencode-agent-plus 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -10
- package/package.json +1 -1
- package/src/antirepetition.test.ts +18 -0
- package/src/autogreenlight.ts +73 -0
- package/src/context.ts +55 -0
- package/src/frontmatter.test.ts +27 -0
- package/src/frontmatter.ts +27 -20
- package/src/httprequest.ts +21 -0
- package/src/index.ts +32 -79
- package/src/log.ts +23 -0
- package/src/{greenlight.ts → manualgreenlight.ts} +10 -11
- package/src/onerrorcommand.ts +39 -0
- package/src/pondering.ts +111 -0
- package/src/presets.ts +45 -0
- package/src/repetition.ts +203 -0
- package/src/safetoolcall.test.ts +36 -0
- package/src/{safecommands.ts → safetoolcall.ts} +1 -1
- package/src/tui.tsx +72 -10
- package/src/antiloop.ts +0 -66
- package/src/antirep/detect.ts +0 -57
- package/src/antirep/index.ts +0 -29
- package/src/antirep/stream.ts +0 -94
package/src/antiloop.ts
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
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
|
-
|
package/src/antirep/detect.ts
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
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
|
-
}
|
package/src/antirep/index.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
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
|
-
}
|
package/src/antirep/stream.ts
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
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
|
-
}
|