@kealthas-dev/opencode-loop-guard 0.0.0-stage → 1.1.3

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.
Files changed (3) hide show
  1. package/README.md +21 -2
  2. package/loop-guard.ts +84 -0
  3. package/package.json +20 -4
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # 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
+ Stops a model calling the same tool with the same arguments over and over, which is the commonest way a small local model gets stuck. Why this is a hook and not a prompt line: [docs/design-philosophy.md](../../docs/design-philosophy.md). Where the idea comes from: [docs/multi-agent-prior-art.md](../../docs/multi-agent-prior-art.md).
4
+
5
+ - Package: `@kealthas-dev/opencode-loop-guard`, source `loop-guard.ts`.
6
+ - Not yet published and not in `deploy/opencode.json.example`; see `TODO.md`. Until then it works as a hand-copied file in a plugins directory.
7
+
8
+ ## Behavior
9
+
10
+ Per session, it tracks the last call (tool name plus arguments, key order ignored) and how many calls in a row repeated it.
11
+
12
+ - From the 3rd consecutive identical call whose output is also identical, a notice is appended to the tool output telling the model to stop and make a different call or answer.
13
+ - The 6th identical call to `read`, `grep` or `glob` is refused with an error, and stays refused until the model does something different. Tools with side effects (`bash`, `edit`, ...) only ever get the notice, since repeating them can be deliberate.
14
+ - A call that returns a different output restarts the run, so reading a file again after it changed is never counted.
15
+ - Failing calls count too: a tool that throws never reaches `tool.execute.after`, so the run is counted in `tool.execute.before` and a read of a missing file repeated forever is refused like any other loop. The notice cannot be appended for them, because there is no output to append it to.
16
+ - A new user message resets the session. `task` is exempt.
17
+
18
+ The thresholds (3 and 5) and the tool lists are constants at the top of `loop-guard.ts`.
19
+
20
+ ## Tests
21
+
22
+ `tests/unit/loop-guard.test.mjs` drives the hooks with plain objects: the notice at the 3rd call, the notice not disturbing the next comparison, a changed result and changed arguments restarting the run, the refusal at the 6th read-only call, failing calls, side-effect tools only warned, per-session state and the reset on a new user message. `tests/integration/guard-plugins.test.mjs` runs it in a real opencode against a fake model: the notice reaches the model on the 3rd identical `read` and the 6th is refused.
package/loop-guard.ts ADDED
@@ -0,0 +1,84 @@
1
+ import type { Plugin } from "@opencode-ai/plugin";
2
+
3
+ // A small model's commonest failure is calling the same tool with the same
4
+ // arguments over and over. This counts consecutive identical calls per session
5
+ // and, once the result is also unchanged, tells the model to stop; for the
6
+ // read-only search tools it eventually refuses the call.
7
+
8
+ // Consecutive identical calls (same tool, same arguments) after which the
9
+ // tool output gets a notice appended. Only counted while the output is
10
+ // unchanged: a call that returns something new is progress and restarts the run.
11
+ const WARN_AT = 3;
12
+ // Identical calls after which the next identical call to a BLOCKABLE tool is refused.
13
+ const BLOCK_AT = 5;
14
+ // Only tools with no side effects are ever refused; repeating `bash` or `edit` may be deliberate.
15
+ const BLOCKABLE = new Set(["read", "grep", "glob"]);
16
+ // `task` starts subagents, whose own sessions have their own loop state.
17
+ const EXEMPT = new Set(["task"]);
18
+ const MAX_SESSIONS = 256;
19
+ const MARKER = "[REPEATED TOOL CALL - STOP]";
20
+
21
+ const WARNING = `\n\n${MARKER}\nYou have made the exact same call with identical arguments ${WARN_AT} times in a row and got the same result each time, so you are making no progress. Do not repeat it. Either make a different call (another path, pattern or tool), or, if the task is done, give your final answer now.`;
22
+
23
+ // Key order must not matter: {a, b} and {b, a} are the same call.
24
+ function stable(value: unknown): string {
25
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "undefined";
26
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
27
+ const rec = value as Record<string, unknown>;
28
+ return `{${Object.keys(rec).sort().map((k) => `${JSON.stringify(k)}:${stable(rec[k])}`).join(",")}}`;
29
+ }
30
+
31
+ type Run = {
32
+ key: string;
33
+ // Calls in the current run, counting the one in flight.
34
+ runs: number;
35
+ // Output of the most recent completed call of this run; undefined until one completes (a failing tool never reaches tool.execute.after).
36
+ output?: string;
37
+ };
38
+
39
+ export const LoopGuard: Plugin = async () => {
40
+ const sessions = new Map<string, Run>();
41
+
42
+ const remember = (sessionID: string, run: Run) => {
43
+ sessions.delete(sessionID); // re-insert so the oldest session is evicted first
44
+ sessions.set(sessionID, run);
45
+ if (sessions.size > MAX_SESSIONS) sessions.delete(sessions.keys().next().value as string);
46
+ };
47
+
48
+ return {
49
+ // A new user message is a new turn; repeating a call after the user spoke is not a loop.
50
+ "chat.message": async (input) => {
51
+ sessions.delete(input.sessionID);
52
+ },
53
+ "tool.execute.before": async (input, output) => {
54
+ if (EXEMPT.has(input.tool)) return;
55
+ const key = `${input.tool}:${stable(output.args)}`;
56
+ const last = sessions.get(input.sessionID);
57
+ if (!last || last.key !== key) {
58
+ remember(input.sessionID, { key, runs: 1 });
59
+ return;
60
+ }
61
+ // Failing calls never reach the after hook, so they can only be counted here: a read of a file that does not exist repeated forever is still a loop.
62
+ if (last.runs >= BLOCK_AT && BLOCKABLE.has(input.tool)) {
63
+ throw new Error(
64
+ `Refusing to run "${input.tool}": this exact call has been made ${last.runs} times in a row without a different result, which is a loop. Stop repeating it: make a different call, or give your final answer.`,
65
+ );
66
+ }
67
+ last.runs += 1;
68
+ },
69
+ "tool.execute.after": async (input, output) => {
70
+ if (EXEMPT.has(input.tool) || typeof output.output !== "string") return;
71
+ const run = sessions.get(input.sessionID);
72
+ // The session moved on (or was reset) while this call ran: nothing to compare against.
73
+ if (!run || run.key !== `${input.tool}:${stable(input.args)}`) return;
74
+ // Compare and remember the raw output, never the one with the notice appended, or the next identical result would look like a change.
75
+ const raw = output.output;
76
+ if (run.output !== undefined && run.output === raw) {
77
+ if (run.runs >= WARN_AT && !raw.includes(MARKER)) output.output += WARNING;
78
+ } else {
79
+ run.runs = 1; // first result, or a different one: progress
80
+ }
81
+ run.output = raw;
82
+ },
83
+ };
84
+ };
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "@kealthas-dev/opencode-loop-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.3",
4
+ "type": "module",
5
+ "description": "loop-guard.ts opencode plugin: stops a model from calling the same tool with the same arguments over and over - warns after 3 identical calls with identical results and refuses a 6th identical read/grep/glob call. Written in TypeScript against @opencode-ai/plugin's Plugin type (type-only). Independently installable - not bundled with the other plugins.",
6
+ "main": "loop-guard.ts",
7
+ "files": [
8
+ "loop-guard.ts"
9
+ ],
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/Keal-thas/opencode-toolkit.git",
16
+ "directory": "plugins/loop-guard"
17
+ },
18
+ "devDependencies": {
19
+ "@opencode-ai/plugin": "^1.0.0",
20
+ "@types/node": "^22.0.0"
21
+ }
22
+ }