opencode-agent-plus 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -10
- package/package.json +31 -7
- package/src/antirepetition.test.ts +18 -0
- package/src/autogreenlight.ts +73 -0
- package/src/clockwork.ts +67 -0
- package/src/context.ts +55 -0
- package/src/frontmatter.test.ts +27 -0
- package/src/frontmatter.ts +35 -20
- package/src/httprequest.ts +21 -0
- package/src/index.ts +40 -79
- package/src/log.ts +23 -0
- package/src/{greenlight.ts → manualgreenlight.ts} +10 -11
- package/src/misplacedtag.test.ts +47 -0
- package/src/misplacedtag.ts +116 -0
- package/src/onerrorcommand.ts +39 -0
- package/src/pondering.ts +111 -0
- package/src/presets.ts +39 -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 +74 -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/index.ts
CHANGED
|
@@ -1,22 +1,15 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const shell = existsSync("/bin/zsh") ? "/bin/zsh" : "/bin/sh"
|
|
14
|
-
return new Promise<void>((resolve) => {
|
|
15
|
-
const child = spawn(shell, ["-c", command], { stdio: "ignore" })
|
|
16
|
-
child.on("close", () => resolve())
|
|
17
|
-
child.on("error", () => resolve())
|
|
18
|
-
})
|
|
19
|
-
}
|
|
1
|
+
import { agentFile, frontmatter, problems } from "./frontmatter"
|
|
2
|
+
import { appendBlock, reminderText } from "./context"
|
|
3
|
+
import { log } from "./log"
|
|
4
|
+
import { isSafeToolCall } from "./safetoolcall"
|
|
5
|
+
import { maxWordRepeat, maxToolRepeat } from "./repetition"
|
|
6
|
+
import { manualGreenLight } from "./manualgreenlight"
|
|
7
|
+
import { autoGreenLight } from "./autogreenlight"
|
|
8
|
+
import { onErrorCommand } from "./onerrorcommand"
|
|
9
|
+
import { httpRequest } from "./httprequest"
|
|
10
|
+
import { pondering } from "./pondering"
|
|
11
|
+
import { misplacedTagFilter } from "./misplacedtag"
|
|
12
|
+
import { clockwork } from "./clockwork"
|
|
20
13
|
|
|
21
14
|
// Server half: adds the agent's reminders to every model request and its settings to the request body.
|
|
22
15
|
// The supported frontmatter keys are listed in frontmatter.ts and explained in README.md.
|
|
@@ -33,33 +26,15 @@ export default {
|
|
|
33
26
|
if (!warned.has(file)) {
|
|
34
27
|
warned.add(file)
|
|
35
28
|
const found = await problems(file, keys)
|
|
36
|
-
if (found.length)
|
|
29
|
+
if (found.length) log(`server: problems file=${file} found=${found.join("; ")}`)
|
|
37
30
|
}
|
|
38
31
|
return { file, keys }
|
|
39
32
|
}
|
|
40
33
|
|
|
41
|
-
|
|
42
|
-
const debug = (line: string) => {
|
|
43
|
-
const file = process.env.AGENT_PLUS_DEBUG
|
|
44
|
-
if (file) try { appendFileSync(file, `${new Date().toISOString()} ${line}\n`) } catch {}
|
|
45
|
-
}
|
|
46
|
-
debug(`plugin loaded directory=${directory}`)
|
|
34
|
+
log(`server: plugin loaded directory=${directory} pid=${process.pid} module=${import.meta.url}`)
|
|
47
35
|
|
|
48
|
-
// `on_error_command`:
|
|
49
|
-
|
|
50
|
-
const woken = new Set<string>()
|
|
51
|
-
await ctx.session.hook("retry", async (event: any) => {
|
|
52
|
-
debug(`retry fired session=${event.sessionID} attempt=${event.attempt} error=${JSON.stringify(event.error)}`)
|
|
53
|
-
const { keys } = await settings(event.agent)
|
|
54
|
-
const command = keys.on_error_command
|
|
55
|
-
if (!command) return
|
|
56
|
-
// Only connection failures: a real HTTP answer has a status code.
|
|
57
|
-
if (event.error?.status) return
|
|
58
|
-
if (woken.has(event.sessionID)) return
|
|
59
|
-
woken.add(event.sessionID)
|
|
60
|
-
await runShell(command)
|
|
61
|
-
event.decision = { retry: true, delay: 1_000 }
|
|
62
|
-
})
|
|
36
|
+
// `on_error_command`: wake the server on a connection failure, then retry.
|
|
37
|
+
const allowWake = await onErrorCommand(ctx, { settings })
|
|
63
38
|
|
|
64
39
|
// Safe-command auto-allow is on for every agent; an agent turns it off with `safe_commands: none`.
|
|
65
40
|
// It skips the ask window for read-only tool calls and safe shell commands.
|
|
@@ -68,53 +43,39 @@ export default {
|
|
|
68
43
|
if (event.effect !== "ask" || !event.agent) return
|
|
69
44
|
const { keys } = await settings(event.agent)
|
|
70
45
|
if (keys.safe_commands === "none") return
|
|
71
|
-
if (
|
|
46
|
+
if (isSafeToolCall(event.action, event.resources ?? [])) event.effect = "allow"
|
|
72
47
|
})
|
|
73
48
|
|
|
74
|
-
// `
|
|
75
|
-
await
|
|
49
|
+
// `max_word_repeat: on` — interrupt the run when the model's text repeats itself.
|
|
50
|
+
await maxWordRepeat(ctx, { settings })
|
|
76
51
|
|
|
77
|
-
// `
|
|
52
|
+
// `manual_green_light: on` — deny tools unless the user's latest message ends with a go-ahead word.
|
|
78
53
|
// Registered first so its deny wins and the anti-loop below does not count a denied call.
|
|
79
|
-
await
|
|
54
|
+
await manualGreenLight(ctx, { settings })
|
|
55
|
+
|
|
56
|
+
// `auto_green_light: on` — the model checks itself before the first tool call of each turn.
|
|
57
|
+
await autoGreenLight(ctx, { settings })
|
|
58
|
+
|
|
59
|
+
// `max_tool_repeat: n` — deny a tool after n calls in a row within one user message.
|
|
60
|
+
await maxToolRepeat(ctx, { settings })
|
|
80
61
|
|
|
81
|
-
// `
|
|
82
|
-
await
|
|
62
|
+
// `pondering: on` — think during idle time; the result rides into the next user message.
|
|
63
|
+
await pondering(ctx, { settings })
|
|
64
|
+
|
|
65
|
+
// `misplaced_tag_filter: on` — swap stray tag signs in thinking/message text for safe look-alikes.
|
|
66
|
+
await misplacedTagFilter(ctx, { settings })
|
|
67
|
+
|
|
68
|
+
// `clockwork: on` — deny all asks and keep the agent going on its own.
|
|
69
|
+
await clockwork(ctx, { settings })
|
|
83
70
|
|
|
84
71
|
await ctx.session.hook("context", async (event: any) => {
|
|
85
72
|
// A request got through: allow on_error_command to fire again next time.
|
|
86
|
-
|
|
87
|
-
const { file, keys } = await settings(event.agent)
|
|
88
|
-
const parts = [
|
|
89
|
-
keys.reminder ?? "",
|
|
90
|
-
keys.reminder_file ? await read(path.resolve(path.dirname(file), keys.reminder_file)) : "",
|
|
91
|
-
await read(path.join(directory, "reminder.txt")),
|
|
92
|
-
]
|
|
93
|
-
const text = parts.map((t) => t.trim()).filter(Boolean).join("\n\n")
|
|
94
|
-
if (!text) return
|
|
95
|
-
// Wrapped so the model does not take the reminder as a user message and reply to it.
|
|
96
|
-
const wrapped = `<system-reminder>\nAutomatic note, not from the user. Do not reply to it.\n\n${text}\n</system-reminder>`
|
|
97
|
-
// Plugins cannot import opencode's Message class (@opencode/ai), so borrow it from an existing message.
|
|
98
|
-
const Message = event.messages[0].constructor
|
|
99
|
-
event.messages.push(new Message({ role: "user", content: [{ type: "text", text: wrapped }] }))
|
|
100
|
-
})
|
|
101
|
-
|
|
102
|
-
await ctx.session.hook("http.request", async (event: any) => {
|
|
73
|
+
allowWake(event.sessionID)
|
|
103
74
|
const { keys } = await settings(event.agent)
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const result = requestValue(k, keys[k])
|
|
109
|
-
return "value" in result ? [[k, result.value]] : []
|
|
110
|
-
}),
|
|
111
|
-
)
|
|
112
|
-
const extra = pick(BODY)
|
|
113
|
-
const kwargs = pick(TEMPLATE_KWARGS)
|
|
114
|
-
if (!Object.keys(extra).length && !Object.keys(kwargs).length) return
|
|
115
|
-
const body = await event.request.clone().json()
|
|
116
|
-
if (Object.keys(kwargs).length) extra.chat_template_kwargs = { ...body.chat_template_kwargs, ...kwargs }
|
|
117
|
-
event.request = new Request(event.request, { body: JSON.stringify({ ...body, ...extra }) })
|
|
75
|
+
await httpRequest(event, { settings })
|
|
76
|
+
const text = await reminderText(directory, keys)
|
|
77
|
+
if (!text) return
|
|
78
|
+
appendBlock(event, "system-reminder", text)
|
|
118
79
|
})
|
|
119
80
|
},
|
|
120
81
|
}
|
package/src/log.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// The plugin's single log function. Lines are appended to `debug.log`
|
|
2
|
+
// next to the plugin's folder. Debug lines are on only while a `debug`
|
|
3
|
+
// file exists in the plugin's folder (touch/rm, no restart needed).
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
import { appendFileSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
|
6
|
+
import { fileURLToPath } from "node:url"
|
|
7
|
+
|
|
8
|
+
export const folder = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
|
|
9
|
+
const marker = path.join(folder, "debug")
|
|
10
|
+
const file = path.join(folder, "debug.log")
|
|
11
|
+
const MAX_BYTES = 500_000 // cheap size check per line; on pass, rewrite with the last KEEP_LINES
|
|
12
|
+
const KEEP_LINES = 2000
|
|
13
|
+
|
|
14
|
+
export function log(line: string) {
|
|
15
|
+
if (!existsSync(marker)) return
|
|
16
|
+
try {
|
|
17
|
+
if (existsSync(file) && statSync(file).size > MAX_BYTES) {
|
|
18
|
+
const lines = readFileSync(file, "utf8").split("\n")
|
|
19
|
+
writeFileSync(file, lines.slice(-KEEP_LINES).join("\n"))
|
|
20
|
+
}
|
|
21
|
+
appendFileSync(file, `${new Date().toISOString()} ${line}\n`)
|
|
22
|
+
} catch {}
|
|
23
|
+
}
|
|
@@ -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,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
|
+
}
|
|
@@ -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,39 @@
|
|
|
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
|
+
"Be concise and straight to the point. Cut the crap and jargon, and talk plain English. Do only what the user asked, and nothing else.",
|
|
10
|
+
].join("\n"),
|
|
11
|
+
"ultra-concise": [
|
|
12
|
+
'You are "Concise" agents, a helpful assistant.',
|
|
13
|
+
"Answer in one or two sentences. Only the requested fact or action, nothing else.",
|
|
14
|
+
"Plain simple English, no jargon, no headings, no lists.",
|
|
15
|
+
"Do not explain, summarize, or add details that are not asked.",
|
|
16
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
17
|
+
"NEVER use chained shell commands (; or &&). Run one command per call; chaining causes permission and execution issues.",
|
|
18
|
+
"NEVER ask 'want me to?' or 'shall I?' or offer to do something. When the user wants an action, just do it. Only ask questions that are technical and block you from proceeding.",
|
|
19
|
+
"NEVER ask 'what do you want?' or tell the user what to do. NEVER push the user to act. Say nothing to the user except precise technical content.",
|
|
20
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
21
|
+
].join("\n"),
|
|
22
|
+
creative: [
|
|
23
|
+
"Do not use system folders like /tmp /opt. Use ./local/tmp for your temp files.",
|
|
24
|
+
"Keep the user's meaning, facts and voice. Change only what the user asks for. When asked to write or rewrite, give the full text. Use plain, clear language unless the user asks for another style.",
|
|
25
|
+
"Reasoning effort is set to low. Keep your thinking brief and focused.",
|
|
26
|
+
].join("\n"),
|
|
27
|
+
off: "",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Resolves one `reminder:` value to its text ("" = off).
|
|
31
|
+
// Returns null when the value is not set, so the caller reads the next source.
|
|
32
|
+
export function reminderPreset(value: string | undefined) {
|
|
33
|
+
const text = value?.trim() ?? ""
|
|
34
|
+
if (!text) return null
|
|
35
|
+
if (text in PRESETS) return PRESETS[text]
|
|
36
|
+
if (text.split(/\s+/).length > 3) return text
|
|
37
|
+
log(`presets: unknown value=${text} -> off`)
|
|
38
|
+
return ""
|
|
39
|
+
}
|