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
|
@@ -1,28 +1,27 @@
|
|
|
1
|
-
// Green light: with `
|
|
1
|
+
// Green light: with `manual_green_light: on`, every tool is denied unless the user's
|
|
2
2
|
// latest message ends with a green-light word (in its last 3 words), e.g.
|
|
3
3
|
// "fix the config, go". The agent must ask, the user must approve.
|
|
4
4
|
// Everything stays in memory; nothing is sent to the server.
|
|
5
|
-
import { realUserTexts } from "./
|
|
5
|
+
import { realUserTexts } from "./context"
|
|
6
|
+
import { log } from "./log"
|
|
6
7
|
|
|
7
|
-
export interface
|
|
8
|
+
export interface ManualGreenLightOptions {
|
|
8
9
|
/** Reads the agent's frontmatter keys. */
|
|
9
10
|
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
-
/** Optional debug logger. */
|
|
11
|
-
debug?: (line: string) => void
|
|
12
11
|
}
|
|
13
12
|
|
|
14
13
|
// Words that mean "you may act", checked in the last 3 words of the message.
|
|
15
|
-
// Agents replace the list with `
|
|
14
|
+
// Agents replace the list with `manual_green_light_words: yes, go, do`.
|
|
16
15
|
const DEFAULT_GREEN_LIGHT_WORDS = ["yes", "do", "go", "ok", "okay", "fine", "good", "fix", "try", "run"]
|
|
17
16
|
|
|
18
|
-
// Resolves `
|
|
17
|
+
// Resolves `manual_green_light_words` to the effective word list and its match test.
|
|
19
18
|
function greenLightWords(words: string | undefined): { list: string[]; test: RegExp } {
|
|
20
19
|
const list = words?.split(",").map((w) => w.trim().toLowerCase()).filter(Boolean)
|
|
21
20
|
const safe = list?.length ? list : DEFAULT_GREEN_LIGHT_WORDS
|
|
22
21
|
return { list: safe, test: new RegExp(`\\b(${safe.map((w) => w.replace(/[^\w-]/g, "")).join("|")})\\b`, "i") }
|
|
23
22
|
}
|
|
24
23
|
|
|
25
|
-
export async function
|
|
24
|
+
export async function manualGreenLight(ctx: any, options: ManualGreenLightOptions) {
|
|
26
25
|
// Per session: the user's latest real message text.
|
|
27
26
|
const lastUser = new Map<string, string>()
|
|
28
27
|
|
|
@@ -34,15 +33,15 @@ export async function greenLight(ctx: any, options: GreenLightOptions) {
|
|
|
34
33
|
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
35
34
|
if (!event.agent) return
|
|
36
35
|
const { keys } = await options.settings(event.agent)
|
|
37
|
-
if (keys.
|
|
36
|
+
if (keys.manual_green_light !== "on") return
|
|
38
37
|
// Reading files is always allowed; only acting needs the word.
|
|
39
38
|
if (event.action === "read") return
|
|
40
39
|
const text = lastUser.get(String(event.sessionID)) ?? ""
|
|
41
40
|
const tail = text.trim().split(/\s+/).slice(-3).join(" ")
|
|
42
|
-
const { list, test } = greenLightWords(keys.
|
|
41
|
+
const { list, test } = greenLightWords(keys.manual_green_light_words)
|
|
43
42
|
if (test.test(tail)) return
|
|
44
43
|
event.effect = "deny"
|
|
45
44
|
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
|
-
|
|
45
|
+
log(`greenlight: denied action=${event.action} session=${String(event.sessionID)} tail=${JSON.stringify(tail)}`)
|
|
47
46
|
})
|
|
48
47
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// `on_error_command`: when a request fails because the server is unreachable,
|
|
2
|
+
// run the agent's command (e.g. wake it up) and ask for a quick retry.
|
|
3
|
+
import { spawn } from "node:child_process"
|
|
4
|
+
import { existsSync } from "node:fs"
|
|
5
|
+
import { log } from "./log"
|
|
6
|
+
|
|
7
|
+
export interface OnErrorCommandOptions {
|
|
8
|
+
/** Reads the agent's frontmatter keys. */
|
|
9
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Runs a shell command (single or multi-line) and waits for it to finish.
|
|
13
|
+
// zsh so ~/.zshenv functions and aliases (like server-on) are available; falls back to sh.
|
|
14
|
+
function runShell(command: string) {
|
|
15
|
+
const shell = existsSync("/bin/zsh") ? "/bin/zsh" : "/bin/sh"
|
|
16
|
+
return new Promise<void>((resolve) => {
|
|
17
|
+
const child = spawn(shell, ["-c", command], { stdio: "ignore" })
|
|
18
|
+
child.on("close", () => resolve())
|
|
19
|
+
child.on("error", () => resolve())
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function onErrorCommand(ctx: any, options: OnErrorCommandOptions) {
|
|
24
|
+
const woken = new Set<string>()
|
|
25
|
+
await ctx.session.hook("retry", async (event: any) => {
|
|
26
|
+
log(`onerrorcommand: retry fired session=${event.sessionID} attempt=${event.attempt} error=${JSON.stringify(event.error)}`)
|
|
27
|
+
const { keys } = await options.settings(event.agent)
|
|
28
|
+
const command = keys.on_error_command
|
|
29
|
+
if (!command) return
|
|
30
|
+
// Only connection failures: a real HTTP answer has a status code.
|
|
31
|
+
if (event.error?.status) return
|
|
32
|
+
if (woken.has(event.sessionID)) return
|
|
33
|
+
woken.add(event.sessionID)
|
|
34
|
+
await runShell(command)
|
|
35
|
+
event.decision = { retry: true, delay: 1_000 }
|
|
36
|
+
})
|
|
37
|
+
// Called from the context hook when a request got through: allow firing again.
|
|
38
|
+
return (sessionID: string) => woken.delete(sessionID)
|
|
39
|
+
}
|
package/src/pondering.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// `pondering: on` — when a session goes idle, run one transient generate
|
|
2
|
+
// request in it (opencode's own API: same context, not saved to history)
|
|
3
|
+
// asking the model to ponder where the conversation is going. The result is
|
|
4
|
+
// appended to the user's next message as a <pondering> block, used silently.
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
7
|
+
import { folder, log } from "./log"
|
|
8
|
+
import { appendBlock } from "./context"
|
|
9
|
+
|
|
10
|
+
// Small file the TUI sidebar watches to show pondering: busy/idle.
|
|
11
|
+
// Content is a JSON map: { sessionID: "busy" | "idle" }.
|
|
12
|
+
const statusFile = path.join(folder, "pondering.status")
|
|
13
|
+
function setStatus(sessionID: string, state: "busy" | "idle", note = "") {
|
|
14
|
+
try {
|
|
15
|
+
const map = JSON.parse(readFileSync(statusFile, "utf8")) as Record<string, { state: string; note: string }>
|
|
16
|
+
map[sessionID] = { state, note }
|
|
17
|
+
writeFileSync(statusFile, JSON.stringify(map))
|
|
18
|
+
} catch {
|
|
19
|
+
writeFileSync(statusFile, JSON.stringify({ [sessionID]: { state, note } }))
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const NOTE = [
|
|
24
|
+
"This is a pondering request (like a chess engine's permanent brain) to think ahead and improve future replies.",
|
|
25
|
+
"Read your last reply only. If there is nothing useful to note (a greeting, a yes/no answer), reply with exactly: SKIP",
|
|
26
|
+
"Otherwise write a short note, one line per point, only what applies.",
|
|
27
|
+
"1. Claims you did not verify: quote each one, if any.",
|
|
28
|
+
"2. Anything left unfinished.",
|
|
29
|
+
"3. What the user will likely ask next.",
|
|
30
|
+
"4. One thing to check first, and how.",
|
|
31
|
+
"5. Did you understand the user's intent, or miss something?",
|
|
32
|
+
"6. Anything you are stuck on, or want to ask the user.",
|
|
33
|
+
"7. Any other useful note.",
|
|
34
|
+
].join("\n")
|
|
35
|
+
|
|
36
|
+
export async function pondering(ctx: any, { settings }: { settings: (agent: string) => Promise<{ keys: Record<string, string> }> }) {
|
|
37
|
+
const shared = ((globalThis as any).__agentPlusPondering ??= { busy: new Set<string>(), done: new Set<string>() })
|
|
38
|
+
shared.ready ??= new Map<string, string>() // backfill when an older load created the object
|
|
39
|
+
const busy = shared.busy as Set<string> // a ponder is running for this session
|
|
40
|
+
const done = shared.done as Set<string> // this session already pondered this turn
|
|
41
|
+
const ready = shared.ready as Map<string, string> // shared: any copy's hook can inject the note
|
|
42
|
+
|
|
43
|
+
const controller = new AbortController()
|
|
44
|
+
log(`pondering: listener started`)
|
|
45
|
+
void (async () => {
|
|
46
|
+
// Events arrive as { type, data: {...} }; the session ID is in data.
|
|
47
|
+
// session.idle is never emitted by the server; the real "run finished"
|
|
48
|
+
// event is session.execution.succeeded (payload { sessionID }).
|
|
49
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
50
|
+
const sessionID: string | undefined = event.data?.sessionID
|
|
51
|
+
// Every plugin copy sees every event. Handle each event exactly once,
|
|
52
|
+
// in the first copy that gets to it; the rest skip.
|
|
53
|
+
if (event.id === shared.lastEvent) continue
|
|
54
|
+
shared.lastEvent = event.id
|
|
55
|
+
if (event.type === "session.inbox.enqueued") {
|
|
56
|
+
// The NOTE we sent via session.generate arrives as a user message.
|
|
57
|
+
// Ignore it so it does not clear `done` and re-arm pondering.
|
|
58
|
+
if (event.data?.item?.payload?.text === NOTE) {
|
|
59
|
+
log(`pondering: swallowed own NOTE session=${sessionID}`)
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
log(`pondering: enqueued session=${sessionID}`)
|
|
63
|
+
done.delete(sessionID) // the user sent a message, so done is cleared and the session can ponder again
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
if (event.type !== "session.execution.succeeded") continue
|
|
67
|
+
log(`pondering: event type=${event.type} session=${sessionID}`)
|
|
68
|
+
if (!sessionID || busy.has(sessionID) || done.has(sessionID)) continue
|
|
69
|
+
busy.add(sessionID) // claim now, before any await, so the other copies skip
|
|
70
|
+
try {
|
|
71
|
+
const session = await ctx.session.get({ sessionID })
|
|
72
|
+
const { keys } = await settings(session.agent)
|
|
73
|
+
if (keys.pondering !== "on") {
|
|
74
|
+
busy.delete(sessionID)
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
log(`pondering: start session=${sessionID} agent=${session.agent}`)
|
|
78
|
+
setStatus(sessionID, "busy")
|
|
79
|
+
const { text } = await ctx.session.generate({ sessionID, prompt: NOTE })
|
|
80
|
+
let trimmed = String(text).trim()
|
|
81
|
+
if (trimmed === "SKIP") trimmed = "" // the model found nothing worth noting
|
|
82
|
+
setStatus(sessionID, "idle", trimmed) // sidebar shows the raw note (troubleshooting)
|
|
83
|
+
if (trimmed) {
|
|
84
|
+
ready.set(sessionID, trimmed)
|
|
85
|
+
log(`pondering: done session=${sessionID} chars=${trimmed.length} text=${trimmed}`)
|
|
86
|
+
} else {
|
|
87
|
+
log(`pondering: discarded session=${sessionID} text=${trimmed}`)
|
|
88
|
+
}
|
|
89
|
+
busy.delete(sessionID)
|
|
90
|
+
done.add(sessionID) // one ponder per user message
|
|
91
|
+
} catch (error) {
|
|
92
|
+
setStatus(sessionID, "idle")
|
|
93
|
+
busy.delete(sessionID)
|
|
94
|
+
done.add(sessionID) // even a failed ponder counts for this turn
|
|
95
|
+
log(`pondering: failed session=${sessionID} error=${String(error)}`)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
})().catch((error) => log(`pondering: listener died error=${String(error)}`))
|
|
99
|
+
|
|
100
|
+
// Inject the stored pondering into the next real model request of the session
|
|
101
|
+
// (generate uses its own hook, so this only runs for real turns).
|
|
102
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
103
|
+
const text = ready.get(event.sessionID)
|
|
104
|
+
if (!text) return
|
|
105
|
+
ready.delete(event.sessionID)
|
|
106
|
+
setStatus(event.sessionID, "idle") // the sidebar note is consumed with this message
|
|
107
|
+
appendBlock(event, "pondering", text, "Automatic pondering note, not from the user. The assistant pondered during idle time; these are its notes. Do not reply to it, but use it silently when answering.")
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
return () => controller.abort()
|
|
111
|
+
}
|
package/src/presets.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Preset texts for `reminder:` values. Reading order: the agent file's
|
|
2
|
+
// `reminder:` first, then AGENTS.md's. A value that is a preset name gets
|
|
3
|
+
// the plugin's text; long text is used as written; a short unknown value
|
|
4
|
+
// means off (logged, never an error).
|
|
5
|
+
import { log } from "./log"
|
|
6
|
+
|
|
7
|
+
const PRESETS: Record<string, string> = {
|
|
8
|
+
concise: [
|
|
9
|
+
'You are "Concise" agents, a helpful assistant.',
|
|
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.",
|
|
16
|
+
].join("\n"),
|
|
17
|
+
"ultra-concise": [
|
|
18
|
+
'You are "Concise" agents, a helpful assistant.',
|
|
19
|
+
"Answer in one or two sentences. Only the requested fact or action, nothing else.",
|
|
20
|
+
"Plain simple English, no jargon, no headings, no lists.",
|
|
21
|
+
"Do not explain, summarize, or add details that are not asked.",
|
|
22
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
23
|
+
"NEVER use chained shell commands (; or &&). Run one command per call; chaining causes permission and execution issues.",
|
|
24
|
+
"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.",
|
|
25
|
+
"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.",
|
|
26
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
27
|
+
].join("\n"),
|
|
28
|
+
creative: [
|
|
29
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
30
|
+
"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.",
|
|
31
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
32
|
+
].join("\n"),
|
|
33
|
+
off: "",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Resolves one `reminder:` value to its text ("" = off).
|
|
37
|
+
// Returns null when the value is not set, so the caller reads the next source.
|
|
38
|
+
export function reminderPreset(value: string | undefined) {
|
|
39
|
+
const text = value?.trim() ?? ""
|
|
40
|
+
if (!text) return null
|
|
41
|
+
if (text in PRESETS) return PRESETS[text]
|
|
42
|
+
if (text.split(/\s+/).length > 3) return text
|
|
43
|
+
log(`presets: unknown value=${text} -> off`)
|
|
44
|
+
return ""
|
|
45
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// Repetition guards: stop the model when it repeats itself.
|
|
2
|
+
// `max_word_repeat` — interrupt the reply when its text repeats back-to-back.
|
|
3
|
+
// `max_tool_repeat` — deny a tool after it is called the same way N times in a row.
|
|
4
|
+
import { log } from "./log"
|
|
5
|
+
import { realUserTexts } from "./context"
|
|
6
|
+
|
|
7
|
+
export interface RepetitionOptions {
|
|
8
|
+
/** Reads the agent's frontmatter keys. */
|
|
9
|
+
settings: (agent: string) => Promise<{ keys: Record<string, string> }>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// --- max_word_repeat: text repetition ---
|
|
13
|
+
|
|
14
|
+
export interface RepetitionHit {
|
|
15
|
+
/** The repeated piece, e.g. "parameter=". */
|
|
16
|
+
unit: string
|
|
17
|
+
/** How many times it appeared back-to-back. */
|
|
18
|
+
times: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DetectOptions {
|
|
22
|
+
/** Longest repeated piece to look for. Default 64 characters. */
|
|
23
|
+
maxUnit?: number
|
|
24
|
+
/** Minimum back-to-back repeats to call it repetition. Default 5. */
|
|
25
|
+
minTimes?: number
|
|
26
|
+
/** Minimum total characters (unit x times) to call it repetition. Default 40. */
|
|
27
|
+
minTotal?: number
|
|
28
|
+
/** Only the last this-many characters are examined. Default 4096. */
|
|
29
|
+
window?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Looks at the tail of `text` for a block of length `unit` repeated `minTimes`
|
|
33
|
+
// or more times in a row. Returns the longest/most repeated block found.
|
|
34
|
+
export function findRepetition(text: string, options: DetectOptions = {}): RepetitionHit | undefined {
|
|
35
|
+
const maxUnit = options.maxUnit ?? 64
|
|
36
|
+
const minTimes = options.minTimes ?? 5
|
|
37
|
+
const minTotal = options.minTotal ?? 40
|
|
38
|
+
const window = options.window ?? 4096
|
|
39
|
+
|
|
40
|
+
const tail = text.length > window ? text.slice(-window) : text
|
|
41
|
+
let best: RepetitionHit | undefined
|
|
42
|
+
|
|
43
|
+
for (let unit = 1; unit <= maxUnit; unit++) {
|
|
44
|
+
const limit = tail.length - unit * minTimes
|
|
45
|
+
if (limit < 0) break
|
|
46
|
+
for (let start = 0; start <= limit; start++) {
|
|
47
|
+
const block = tail.slice(start, start + unit)
|
|
48
|
+
let times = 1
|
|
49
|
+
let at = start + unit
|
|
50
|
+
while (at + unit <= tail.length && tail.startsWith(block, at)) {
|
|
51
|
+
times++
|
|
52
|
+
at += unit
|
|
53
|
+
}
|
|
54
|
+
if (times >= minTimes && times * unit >= minTotal) {
|
|
55
|
+
const hit = { unit: block, times }
|
|
56
|
+
if (!best || times * unit > best.times * best.unit.length) best = hit
|
|
57
|
+
}
|
|
58
|
+
if (times > 1) start = at - unit
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return best
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Pulls model words out of protocol text: every `"content":"..."` value,
|
|
65
|
+
// with JSON escapes decoded. Unfinished tail (partial value) stays in `rest`.
|
|
66
|
+
export function extractText(chunk: string): { text: string; rest: string } {
|
|
67
|
+
let text = ""
|
|
68
|
+
let i = 0
|
|
69
|
+
for (;;) {
|
|
70
|
+
const key = chunk.indexOf('"content":"', i)
|
|
71
|
+
if (key < 0) return { text, rest: chunk.slice(i) }
|
|
72
|
+
let j = key + '"content":"'.length
|
|
73
|
+
let value = ""
|
|
74
|
+
let closed = false
|
|
75
|
+
while (j < chunk.length) {
|
|
76
|
+
const c = chunk[j]
|
|
77
|
+
if (c === "\\") {
|
|
78
|
+
if (j + 1 >= chunk.length) break
|
|
79
|
+
const next = chunk[j + 1]
|
|
80
|
+
value += next === "n" ? "\n" : next === "t" ? "\t" : next
|
|
81
|
+
j += 2
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
if (c === '"') {
|
|
85
|
+
closed = true
|
|
86
|
+
j++
|
|
87
|
+
break
|
|
88
|
+
}
|
|
89
|
+
value += c
|
|
90
|
+
j++
|
|
91
|
+
}
|
|
92
|
+
if (!closed) return { text, rest: chunk.slice(key) }
|
|
93
|
+
text += value
|
|
94
|
+
i = j
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface ScanOptions {
|
|
99
|
+
/** Called at most once, on the first repetition found. */
|
|
100
|
+
onHit: (hit: RepetitionHit) => void
|
|
101
|
+
/** Scan when at least this many new characters arrived since last scan. Default 256. */
|
|
102
|
+
scanEvery?: number
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Wraps a model reply stream so the model's words can be scanned as they
|
|
106
|
+
// arrive. When the scanner says stop, onHit fires once; the stream keeps
|
|
107
|
+
// flowing (opencode's interrupt ends the run, not us).
|
|
108
|
+
export function scanResponse(response: Response, options: ScanOptions): Response {
|
|
109
|
+
if (!response.body) return response
|
|
110
|
+
const scanEvery = options.scanEvery ?? 256
|
|
111
|
+
const decoder = new TextDecoder()
|
|
112
|
+
let pending = ""
|
|
113
|
+
let words = ""
|
|
114
|
+
let sinceScan = 0
|
|
115
|
+
let fired = false
|
|
116
|
+
|
|
117
|
+
const check = (final: boolean) => {
|
|
118
|
+
if (fired) return
|
|
119
|
+
const hit = findRepetition(words)
|
|
120
|
+
if (!hit) return
|
|
121
|
+
fired = true
|
|
122
|
+
log(`repetition: hit unit=${JSON.stringify(hit.unit)} times=${hit.times} final=${final}`)
|
|
123
|
+
options.onHit(hit)
|
|
124
|
+
throw new Error(`agent-plus: anti-repetition stopped the reply ("${hit.unit}" repeated ${hit.times} times)`)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const checker = new TransformStream<Uint8Array, Uint8Array>({
|
|
128
|
+
transform(chunk, controller) {
|
|
129
|
+
if (sinceScan === 0 && words === "" && pending === "") log(`repetition: first chunk bytes=${chunk.byteLength}`)
|
|
130
|
+
if (fired) throw new Error("agent-plus: anti-repetition stopped the reply")
|
|
131
|
+
controller.enqueue(chunk)
|
|
132
|
+
const { text, rest } = extractText(pending + decoder.decode(chunk, { stream: true }))
|
|
133
|
+
pending = rest
|
|
134
|
+
if (!text) return
|
|
135
|
+
words += text
|
|
136
|
+
sinceScan += text.length
|
|
137
|
+
check(false)
|
|
138
|
+
},
|
|
139
|
+
flush() {
|
|
140
|
+
log(`repetition: stream end words=${words.length} fired=${fired}`)
|
|
141
|
+
check(true)
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
return new Response(response.body.pipeThrough(checker), {
|
|
146
|
+
status: response.status,
|
|
147
|
+
statusText: response.statusText,
|
|
148
|
+
headers: response.headers,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function maxWordRepeat(ctx: any, options: RepetitionOptions) {
|
|
153
|
+
return ctx.session.hook("http.response", async (event: any) => {
|
|
154
|
+
const { keys } = await options.settings(event.agent)
|
|
155
|
+
if (keys.max_word_repeat !== "on") return
|
|
156
|
+
log(`repetition: http.response fired session=${event.sessionID} agent=${event.agent}`)
|
|
157
|
+
const sessionID = event.sessionID
|
|
158
|
+
const stop = (hit: RepetitionHit) => {
|
|
159
|
+
log(`repetition: interrupt session=${sessionID} unit=${JSON.stringify(hit.unit)} times=${hit.times}`)
|
|
160
|
+
ctx.session.interrupt({ sessionID }).catch(() => {})
|
|
161
|
+
}
|
|
162
|
+
event.response = scanResponse(event.response, { onHit: stop })
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// --- max_tool_repeat: same tool call repeated ---
|
|
167
|
+
|
|
168
|
+
function countUserTurns(messages: any[]): number {
|
|
169
|
+
return realUserTexts(messages).length
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function maxToolRepeat(ctx: any, options: RepetitionOptions) {
|
|
173
|
+
const streaks = new Map<string, { call: string; count: number }>()
|
|
174
|
+
const turns = new Map<string, number>()
|
|
175
|
+
|
|
176
|
+
await ctx.session.hook("context", async (event: any) => {
|
|
177
|
+
const key = String(event.sessionID)
|
|
178
|
+
const turn = countUserTurns(event.messages)
|
|
179
|
+
if (turns.get(key) !== turn) {
|
|
180
|
+
turns.set(key, turn)
|
|
181
|
+
streaks.delete(key)
|
|
182
|
+
}
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
186
|
+
if (!event.agent) return
|
|
187
|
+
if (event.effect === "deny") return
|
|
188
|
+
const { keys } = await options.settings(event.agent)
|
|
189
|
+
const max = Number(keys.max_tool_repeat)
|
|
190
|
+
if (!Number.isInteger(max) || max < 1 || event.action === "task") return
|
|
191
|
+
const key = String(event.sessionID)
|
|
192
|
+
// Same tool AND same arguments: only then it is a repeat.
|
|
193
|
+
const call = `${event.action}\u0000${(event.resources ?? []).join("\u0000")}`
|
|
194
|
+
const prev = streaks.get(key)
|
|
195
|
+
const count = prev && prev.call === call ? prev.count + 1 : 1
|
|
196
|
+
streaks.set(key, { call, count })
|
|
197
|
+
if (count <= max) return
|
|
198
|
+
streaks.set(key, { call, count: 0 })
|
|
199
|
+
event.effect = "deny"
|
|
200
|
+
event.message = `You already used '${event.action}' the same way ${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.`
|
|
201
|
+
log(`repetition: tool denied action=${event.action} session=${key} count=${count} max=${max}`)
|
|
202
|
+
})
|
|
203
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { isSafeToolCall } from "./safetoolcall"
|
|
3
|
+
|
|
4
|
+
const safe = (cmd: string) => isSafeToolCall("shell", [cmd])
|
|
5
|
+
|
|
6
|
+
test("read-only tools are safe", () => {
|
|
7
|
+
for (const a of ["read", "glob", "grep", "websearch"]) expect(isSafeToolCall(a, [])).toBe(true)
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
test("safe shell commands", () => {
|
|
11
|
+
for (const c of ["ls", "cat f", "git status", "git log --oneline", "docker compose ps", "npm ls", "node --version", "psql -c 'select 1'"])
|
|
12
|
+
expect(safe(c)).toBe(true)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
test("unsafe commands and flags", () => {
|
|
16
|
+
for (const c of ["rm -rf /", "git branch -D x", "find . -exec rm {} ;", "sort -o out f", "git log --output=f", "node script.js", "env rm x", "ssh -o ProxyCommand=x host"])
|
|
17
|
+
expect(safe(c)).toBe(false)
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
test("compound commands need every part safe", () => {
|
|
21
|
+
expect(isSafeToolCall("shell", ["ls", "cat f"])).toBe(true)
|
|
22
|
+
expect(isSafeToolCall("shell", ["ls", "rm x"])).toBe(false)
|
|
23
|
+
expect(safe("echo $(whoami)")).toBe(false)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test("corner cases", () => {
|
|
27
|
+
expect(isSafeToolCall("shell", [])).toBe(false) // no resources
|
|
28
|
+
expect(safe("")).toBe(false) // empty command
|
|
29
|
+
expect(safe("ls; rm x")).toBe(false) // semicolon hides a write
|
|
30
|
+
expect(safe("cat `whoami`")).toBe(false) // backtick substitution
|
|
31
|
+
expect(safe("git status --output=f")).toBe(false) // git write flag
|
|
32
|
+
expect(safe("docker compose down")).toBe(false) // not a read subcommand
|
|
33
|
+
expect(safe("sqlite3 db '.dump'")).toBe(false) // not a read-only dot
|
|
34
|
+
expect(safe("ssh host")).toBe(false) // bare ssh is a shell
|
|
35
|
+
expect(safe("ssh host ls")).toBe(true) // remote read command
|
|
36
|
+
})
|
|
@@ -139,7 +139,7 @@ function safeSsh(args: string[]): boolean {
|
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
// Is this permission event safe to allow? `action` and `resources` come from the hook event.
|
|
142
|
-
export function
|
|
142
|
+
export function isSafeToolCall(action: string, resources: readonly string[]): boolean {
|
|
143
143
|
if (SAFE_ACTIONS.has(action)) return true
|
|
144
144
|
if (action !== "shell") return false
|
|
145
145
|
// The scanner splits compound commands into several resources: every part must be safe.
|
package/src/tui.tsx
CHANGED
|
@@ -1,19 +1,39 @@
|
|
|
1
1
|
/** @jsxImportSource @opentui/solid */
|
|
2
2
|
import path from "node:path"
|
|
3
|
-
import {
|
|
3
|
+
import { readFileSync, unwatchFile, watchFile } from "node:fs"
|
|
4
|
+
import { createEffect, createMemo, createResource, createSignal, For, Show } from "solid-js"
|
|
4
5
|
import { agentFile, allAgentFiles, BODY, frontmatter, problems, read, requestValue } from "./frontmatter"
|
|
6
|
+
import { folder, log } from "./log"
|
|
7
|
+
import { reminderPreset } from "./presets"
|
|
5
8
|
|
|
6
9
|
// At start, shows a warning toast for every agent .md file with problems, or a "loaded" toast when there are none.
|
|
7
10
|
// Adds an "Agent-plus" section to the sidebar with the agent-plus settings of the session's agent.
|
|
8
11
|
// The sidebar reads the agent file again when the session's agent changes or opencode reports an agent file change.
|
|
12
|
+
const onOff = (v: string | undefined, on = "on") => (v === on ? "on" : "off")
|
|
13
|
+
|
|
9
14
|
function sidebarLines(keys: Record<string, string>) {
|
|
10
|
-
const lines
|
|
15
|
+
const lines: string[] = []
|
|
16
|
+
const reminder = reminderPreset(keys.reminder ?? "")
|
|
17
|
+
lines.push(reminder ? `reminder: ${keys.reminder}` : "reminder: off")
|
|
18
|
+
lines.push(`safe_commands: ${keys.safe_commands === "none" ? "off" : "on"}`)
|
|
19
|
+
lines.push(`max_word_repeat: ${onOff(keys.max_word_repeat)}`)
|
|
20
|
+
lines.push(`max_tool_repeat: ${keys.max_tool_repeat || "off"}`)
|
|
21
|
+
lines.push(
|
|
22
|
+
`on_error_command: ${keys.on_error_command ? keys.on_error_command.split("\n")[0].trim() + (keys.on_error_command.includes("\n") ? " …" : "") : "off"}`,
|
|
23
|
+
)
|
|
24
|
+
lines.push(`manual_green_light: ${onOff(keys.manual_green_light)}`)
|
|
25
|
+
lines.push(`auto_green_light: ${onOff(keys.auto_green_light)}`)
|
|
26
|
+
lines.push(`pondering: ${onOff(keys.pondering)}`)
|
|
27
|
+
if ("reasoning_effort" in keys && "value" in requestValue("reasoning_effort", keys.reasoning_effort))
|
|
28
|
+
lines.push(`reasoning_effort: ${keys.reasoning_effort}`)
|
|
29
|
+
for (const k of BODY) {
|
|
30
|
+
if (k === "reasoning_effort" || !(k in keys)) continue
|
|
31
|
+
const result = requestValue(k, keys[k])
|
|
32
|
+
if ("value" in result) lines.push(`${k}: ${keys[k]}`)
|
|
33
|
+
else lines.push(`${k}: ${keys[k]} (ERR: out of range!)`)
|
|
34
|
+
}
|
|
11
35
|
if (keys.enable_thinking === "true" || keys.enable_thinking === "false")
|
|
12
36
|
lines.push(`thinking: ${keys.enable_thinking === "true" ? "on" : "off"}`)
|
|
13
|
-
lines.push(`safe_commands: ${keys.safe_commands === "none" ? "off" : "on"}`)
|
|
14
|
-
if (keys.reminder || keys.reminder_file) lines.push("reminder: on")
|
|
15
|
-
if (keys.on_error_command)
|
|
16
|
-
lines.push(`on_error_command: ${keys.on_error_command.split("\n")[0].trim()}${keys.on_error_command.includes("\n") ? " …" : ""}`)
|
|
17
37
|
return lines
|
|
18
38
|
}
|
|
19
39
|
|
|
@@ -21,11 +41,13 @@ export default {
|
|
|
21
41
|
id: "agent-plus",
|
|
22
42
|
async setup(ctx: any) {
|
|
23
43
|
const directory = ctx.location?.directory ?? process.cwd()
|
|
44
|
+
log(`tui: setup directory=${directory} toast=${typeof ctx.ui?.toast?.show}`)
|
|
24
45
|
let warned = false
|
|
25
46
|
for (const file of await allAgentFiles(directory)) {
|
|
26
47
|
const found = await problems(file, frontmatter(await read(file)))
|
|
27
48
|
if (!found.length) continue
|
|
28
49
|
warned = true
|
|
50
|
+
log(`tui: toast warning file=${file} problems=${found.join("; ")}`)
|
|
29
51
|
ctx.ui.toast.show({
|
|
30
52
|
title: "agent-plus",
|
|
31
53
|
message: `Problems in ${path.basename(file)}:\n${found.join("\n")}`,
|
|
@@ -33,11 +55,26 @@ export default {
|
|
|
33
55
|
duration: 7000,
|
|
34
56
|
})
|
|
35
57
|
}
|
|
36
|
-
if (!warned)
|
|
58
|
+
if (!warned) {
|
|
59
|
+
log("tui: toast loaded")
|
|
60
|
+
ctx.ui.toast.show({ message: "agent-plus is loaded", variant: "info" })
|
|
61
|
+
}
|
|
37
62
|
|
|
38
63
|
const [agentsVersion, setAgentsVersion] = createSignal(0)
|
|
39
64
|
const stop = ctx.data.on("agent.updated", () => setAgentsVersion((v) => v + 1))
|
|
40
65
|
|
|
66
|
+
// Live pondering state written by the server plugin: { sessionID: "busy" | "idle" }
|
|
67
|
+
const statusFile = path.join(folder, "pondering.status")
|
|
68
|
+
const [statuses, setStatuses] = createSignal<Record<string, string>>({})
|
|
69
|
+
const readStatus = () => {
|
|
70
|
+
try {
|
|
71
|
+
setStatuses(JSON.parse(readFileSync(statusFile, "utf8")))
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
watchFile(statusFile, { interval: 300 }, readStatus)
|
|
75
|
+
const [frame, setFrame] = createSignal(0) // spinner frame counter
|
|
76
|
+
const timer = setInterval(() => setFrame((f) => f + 1), 80)
|
|
77
|
+
|
|
41
78
|
ctx.ui.slot({
|
|
42
79
|
append: "sidebar.content",
|
|
43
80
|
render: (props: { sessionID: string }) => {
|
|
@@ -47,18 +84,43 @@ export default {
|
|
|
47
84
|
() => agent() && { agent: agent()!, version: agentsVersion() },
|
|
48
85
|
async ({ agent }) => sidebarLines(frontmatter((await agentFile(directory, agent)).text)),
|
|
49
86
|
)
|
|
87
|
+
// Live line: spinner while pondering, "on (idle)" when enabled and done, "off" when disabled.
|
|
88
|
+
const shown = createMemo(() => {
|
|
89
|
+
const ls = lines() ?? []
|
|
90
|
+
if (!ls.includes("pondering: on")) return ls
|
|
91
|
+
const st = statuses()[props.sessionID]
|
|
92
|
+
const busy = st?.state === "busy"
|
|
93
|
+
const text = busy ? `pondering: ${"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"[frame() % 10]}` : "pondering: on (idle)"
|
|
94
|
+
const out = ls.map((l) => (l === "pondering: on" ? text : l))
|
|
95
|
+
if (!busy && st?.note) out.push("", "Pondering:", ...String(st.note).split("\n"))
|
|
96
|
+
return out
|
|
97
|
+
})
|
|
50
98
|
return (
|
|
51
|
-
<Show when={
|
|
99
|
+
<Show when={shown().length}>
|
|
52
100
|
<box>
|
|
53
101
|
<text fg={theme.text.base}>
|
|
54
102
|
<b>Agent-plus</b>
|
|
55
103
|
</text>
|
|
56
|
-
<For each={
|
|
104
|
+
<For each={shown()}>
|
|
105
|
+
{(line) =>
|
|
106
|
+
line === "Pondering:" ? (
|
|
107
|
+
<text fg={theme.text.base}>
|
|
108
|
+
<b>Pondering:</b>
|
|
109
|
+
</text>
|
|
110
|
+
) : (
|
|
111
|
+
<text fg={theme.text.muted}>{line}</text>
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
</For>
|
|
57
115
|
</box>
|
|
58
116
|
</Show>
|
|
59
117
|
)
|
|
60
118
|
},
|
|
61
119
|
})
|
|
62
|
-
return
|
|
120
|
+
return () => {
|
|
121
|
+
clearInterval(timer)
|
|
122
|
+
unwatchFile(statusFile, readStatus)
|
|
123
|
+
stop()
|
|
124
|
+
}
|
|
63
125
|
},
|
|
64
126
|
}
|