opencode-loop-guard 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (2026-11-22)
4
+
5
+ - README: the install example used `"plugin"`; OpenCode 2.x reads `"plugins"`.
6
+
7
+ ## 0.1.0 (2026-11-22)
8
+
9
+ - Blocks a tool call repeated with the same input and the same result (twice in a row, or in an A, B, A, B, A loop).
10
+ - Polling commands are never blocked, and a file edit starts the count over.
11
+ - After 3 blocked calls in a row, ends the turn so a stuck model waits for the user.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the opencode-loop-guard authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # opencode-loop-guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [OpenCode](https://opencode.ai) 2.x plugin that stops a model from running
4
+ the same tool call over and over.
5
+
6
+ Local models in long sessions sometimes get stuck re-running one command and
7
+ re-reading the same result. OpenCode's built-in `doom_loop` check only catches
8
+ repeated *failures*, so a call that keeps succeeding with the same output can
9
+ loop a hundred times.
10
+
11
+ ## What it blocks
12
+
13
+ A tool call is refused when the same tool with the same input already returned
14
+ the same result:
15
+
16
+ - in each of the last two calls (a straight repeat), or
17
+ - twice more among the last 10 calls (an A, B, A, B, A loop).
18
+
19
+ The model gets an error telling it to use the result it already has, take a
20
+ different step, or ask the user. If it sends a blocked call 3 times in a row
21
+ anyway, the guard ends the turn (OpenCode's `session.interrupt`), so a stuck
22
+ model stops and waits for you instead of retrying for half an hour. Any call
23
+ that runs resets that count. It's never blocked when:
24
+
25
+ - the result changes between runs (polling until something finishes works), or
26
+ - a file was edited since (`edit`, `write`, `patch` and similar tools start the
27
+ count over, so "edit, re-run the tests, same failure, edit again" keeps
28
+ working), or
29
+ - the shell command waits or polls (`sleep`, `wait`, `watch`, `*_status`,
30
+ `unity … status`).
31
+
32
+ Fields that don't change what a call does (`description`, `timeout`, `title`,
33
+ `reason`) and key order are ignored when comparing inputs.
34
+
35
+ ## Install
36
+
37
+ Add it to `opencode.json`:
38
+
39
+ ```json
40
+ { "plugins": ["opencode-loop-guard"] }
41
+ ```
42
+
43
+ or copy `index.js` to `~/.config/opencode/plugins/loop-guard.js`. Restart
44
+ OpenCode.
45
+
46
+ ## Limits
47
+
48
+ - It remembers the last 10 calls of up to 200 sessions, in memory only.
49
+ - It relies on OpenCode 2.x's `tool.hook("execute.before" | "execute.after")`
50
+ plugin API. Tested with OpenCode 2.1.4 and 2.3.2.
51
+
52
+ ## Development
53
+
54
+ ```bash
55
+ npm test
56
+ ```
package/index.js ADDED
@@ -0,0 +1,147 @@
1
+ // opencode-loop-guard (OpenCode 2.x plugin): stops a model that keeps repeating itself.
2
+ //
3
+ // Blocks a tool call when the exact same call (same tool, same input) already
4
+ // returned the same result
5
+ // - in each of the last two calls (a straight repeat), or
6
+ // - twice more among the last 10 calls (an A, B, A, B, A loop).
7
+ // A repeat whose result changes is allowed, so polling until something is done
8
+ // still works, and shell commands that wait or poll a status are never blocked.
9
+ // A file edit starts the count over for every other call, so "edit, re-run the
10
+ // tests, same failure, edit again, re-run" is never blocked.
11
+ // The model gets an error telling it to change approach or ask the user. If it
12
+ // keeps sending blocked calls (3 in a row), the guard ends the turn, so a stuck
13
+ // model stops and waits for the user instead of retrying for half an hour.
14
+ // Remove it from your plugin list (or delete the file) to turn it off.
15
+
16
+ import { createHash } from "node:crypto"
17
+
18
+ const WINDOW = 10 // calls remembered per session
19
+ const STOP_AFTER = 3 // blocked calls in a row before the turn is ended
20
+ const MAX_SESSIONS = 200 // sessions remembered at once (least recently active dropped first)
21
+ // Shell commands that may legitimately repeat with the same output while waiting:
22
+ // sleep/wait/watch, *_status commands, and `unity ... status` (Editor, test, job).
23
+ const POLL = /(^|[\s;&|(])(sleep|wait|watch)\b|_status\b|\bunity\b.*\bstatus\b/i
24
+
25
+ function text(value) {
26
+ try {
27
+ return typeof value === "string" ? value : JSON.stringify(value)
28
+ } catch {
29
+ return String(value)
30
+ }
31
+ }
32
+
33
+ function hash(value) {
34
+ return createHash("sha1")
35
+ .update(text(value) ?? "")
36
+ .digest("hex")
37
+ }
38
+
39
+ // Fields a model may vary between otherwise identical calls (a reworded
40
+ // description, a different timeout); they don't change what the call does.
41
+ const IGNORED_FIELDS = new Set(["description", "timeout", "title", "reason"])
42
+
43
+ function signature(call) {
44
+ let input = call.input
45
+ if (input && typeof input === "object" && !Array.isArray(input)) {
46
+ input = Object.fromEntries(
47
+ Object.entries(input)
48
+ .filter(([key]) => !IGNORED_FIELDS.has(key))
49
+ .sort(([a], [b]) => (a < b ? -1 : 1)),
50
+ )
51
+ }
52
+ return hash(call.tool + "\u0000" + text(input))
53
+ }
54
+
55
+ // Tools that change files. After one runs, earlier results of other calls may be stale.
56
+ const WRITE_TOOL = /(^|[_.-])(edit|multiedit|write|patch|apply_patch)$/i
57
+
58
+ function isWrite(call) {
59
+ return typeof call.tool === "string" && WRITE_TOOL.test(call.tool)
60
+ }
61
+
62
+ function isPoll(call) {
63
+ const command = call.input && typeof call.input === "object" ? call.input.command : undefined
64
+ return typeof command === "string" && POLL.test(command)
65
+ }
66
+
67
+ function resultKey(call) {
68
+ if (call.status === "error") return hash("error\u0000" + text(call.error?.message ?? call.error))
69
+ return hash(call.result?.content ?? call.result?.output ?? call.result)
70
+ }
71
+
72
+ export function createPlugin() {
73
+ const runs = new Map() // sessionID -> [{ sig, out }]
74
+ const blocked = new Set() // ids of calls this guard refused
75
+ const strikes = new Map() // sessionID -> blocked calls in a row
76
+
77
+ function remember(sessionID, entry) {
78
+ let recent = runs.get(sessionID) ?? []
79
+ // Files changed: forget the other calls, but keep earlier edits so an edit
80
+ // repeated with the same result can still be caught.
81
+ if (entry.write) recent = recent.filter((r) => r.write)
82
+ runs.delete(sessionID) // re-insert so the most recently active session is last
83
+ recent.push(entry)
84
+ if (recent.length > WINDOW) recent.shift()
85
+ runs.set(sessionID, recent)
86
+ if (runs.size > MAX_SESSIONS) runs.delete(runs.keys().next().value)
87
+ }
88
+
89
+ return {
90
+ id: "loop-guard",
91
+ async setup(ctx) {
92
+ // Ends the session's current turn, after the refused call has been reported.
93
+ const interrupt = typeof ctx.session?.interrupt === "function"
94
+ ? (sessionID) => setTimeout(() => {
95
+ try {
96
+ Promise.resolve(ctx.session.interrupt({ sessionID })).catch(() => {})
97
+ } catch {}
98
+ }, 0)
99
+ : undefined
100
+
101
+ await ctx.tool.hook("execute.before", (call) => {
102
+ if (isPoll(call)) return
103
+ const sig = signature(call)
104
+ const recent = runs.get(call.sessionID) ?? []
105
+ const last = recent.slice(-2)
106
+ const twiceInARow = last.length === 2 && last.every((r) => r.sig === sig) && last[0].out === last[1].out
107
+ const same = recent.filter((r) => r.sig === sig)
108
+ const loop = same.length >= 2 && same.every((r) => r.out === same[0].out)
109
+ if (!twiceInARow && !loop) return
110
+ // opencode 2.1 doesn't run execute.after for a call refused here; keep the set from growing anyway.
111
+ if (blocked.size > 1000) blocked.clear()
112
+ blocked.add(call.id)
113
+ const strike = (strikes.get(call.sessionID) ?? 0) + 1
114
+ strikes.set(call.sessionID, strike)
115
+ if (strikes.size > MAX_SESSIONS) strikes.delete(strikes.keys().next().value)
116
+ if (strike >= STOP_AFTER && interrupt) {
117
+ strikes.delete(call.sessionID)
118
+ interrupt(call.sessionID)
119
+ throw new Error(
120
+ "loop-guard stopped this turn: you sent a call it had already blocked " +
121
+ strike +
122
+ " times in a row (" +
123
+ call.tool +
124
+ " with the same input and the same result). Don't run it again. " +
125
+ "When the user writes next, say what you were trying to do, what the repeated call returned, and ask one short question.",
126
+ )
127
+ }
128
+ throw new Error(
129
+ "loop-guard blocked this call: you already ran this exact " +
130
+ call.tool +
131
+ " call with the same input " +
132
+ (twiceInARow ? "twice in a row" : same.length + " times in your last few steps") +
133
+ " and got the same result each time. Running it again will not change anything. " +
134
+ "Use the result you already have, take a different next step, or stop and ask the user one short question.",
135
+ )
136
+ })
137
+
138
+ await ctx.tool.hook("execute.after", (call) => {
139
+ if (blocked.delete(call.id)) return
140
+ strikes.delete(call.sessionID)
141
+ remember(call.sessionID, { sig: signature(call), out: resultKey(call), write: isWrite(call) })
142
+ })
143
+ },
144
+ }
145
+ }
146
+
147
+ export default createPlugin()
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "opencode-loop-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "OpenCode plugin that stops a model from repeating the same tool call over and over",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": { ".": "./index.js" },
8
+ "files": ["index.js", "README.md", "LICENSE", "CHANGELOG.md"],
9
+ "scripts": { "test": "node --test" },
10
+ "keywords": ["opencode", "opencode-plugin", "agent", "loop"],
11
+ "engines": { "node": ">=20" },
12
+ "license": "MIT",
13
+ "repository": { "type": "git", "url": "git+https://github.com/amirhakimnejad/opencode-loop-guard.git" }
14
+ }