opencode-agent-loop-breaker 0.0.0-stage → 0.1.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/src/options.ts ADDED
@@ -0,0 +1,176 @@
1
+ export interface LoopBreakerOptions {
2
+ /**
3
+ * Turn the plugin off without removing it from the config.
4
+ * Default: true.
5
+ */
6
+ enabled?: boolean
7
+ /**
8
+ * Block a call when the same action signature repeats this many times.
9
+ * Set 0 to disable. Default: 4.
10
+ */
11
+ maxIdenticalActions?: number
12
+ /**
13
+ * Block a repeated action cycle after this many repeats.
14
+ * Set 0 to disable. Default: 3.
15
+ */
16
+ maxCycleRepeats?: number
17
+ /**
18
+ * Longest action cycle to detect. Set 0 to disable.
19
+ * Minimum active value: 2. Default: 4.
20
+ */
21
+ maxCycleLength?: number
22
+ /**
23
+ * Block when the same action returns the same output this many times.
24
+ * Set 0 to disable. Default: 3.
25
+ */
26
+ maxIdenticalOutputs?: number
27
+ /**
28
+ * Block new commands when different commands return the same output this
29
+ * many times. Default: 6. Set 0 to disable.
30
+ */
31
+ maxRepeatedOutputs?: number
32
+ /**
33
+ * Block more command runs after this many failures in a row.
34
+ * Default: 3. Set 0 to disable.
35
+ */
36
+ maxFailureStreak?: number
37
+ /**
38
+ * Block the same test command after this many runs without a successful
39
+ * change. Default: 3. Set 0 to disable.
40
+ */
41
+ maxTestRuns?: number
42
+ /**
43
+ * Block more inspections of one file or target. Default: 10.
44
+ * Set 0 to disable.
45
+ */
46
+ maxFileInvestigations?: number
47
+ /**
48
+ * Block more inspections across all targets. Default: 30.
49
+ * Set 0 to disable.
50
+ */
51
+ maxTotalInvestigations?: number
52
+ /**
53
+ * Send one synthetic message when model output hits the token limit.
54
+ * Default: "notify".
55
+ */
56
+ onTruncation?: "notify" | "off"
57
+ /**
58
+ * Number of truncated steps in a row before the notice.
59
+ * Default: 2.
60
+ */
61
+ maxTruncatedSteps?: number
62
+ /**
63
+ * Minimum time between truncation notices. Default: 60000.
64
+ */
65
+ truncationCooldownMs?: number
66
+ /**
67
+ * Tools that the plugin must not observe. Default: skill, todowrite,
68
+ * todoread, todo_write, todo_read, write_todos, read_todos, question.
69
+ */
70
+ ignoreTools?: string[]
71
+ /**
72
+ * Clear all state when the session becomes idle. Default: true.
73
+ */
74
+ resetOnIdle?: boolean
75
+ /**
76
+ * Log blocked calls to stderr. Default: false.
77
+ */
78
+ debug?: boolean
79
+ }
80
+
81
+ export interface ResolvedOptions {
82
+ readonly enabled: boolean
83
+ readonly maxIdenticalActions: number
84
+ readonly maxCycleRepeats: number
85
+ readonly maxCycleLength: number
86
+ readonly maxIdenticalOutputs: number
87
+ readonly maxRepeatedOutputs: number
88
+ readonly maxFailureStreak: number
89
+ readonly maxTestRuns: number
90
+ readonly maxFileInvestigations: number
91
+ readonly maxTotalInvestigations: number
92
+ readonly onTruncation: "notify" | "off"
93
+ readonly maxTruncatedSteps: number
94
+ readonly truncationCooldownMs: number
95
+ readonly ignoreTools: ReadonlySet<string>
96
+ readonly resetOnIdle: boolean
97
+ readonly debug: boolean
98
+ }
99
+
100
+ const DEFAULT_IGNORE_TOOLS = [
101
+ "skill",
102
+ "todowrite",
103
+ "todoread",
104
+ "todo_write",
105
+ "todo_read",
106
+ "write_todos",
107
+ "read_todos",
108
+ "question",
109
+ ]
110
+
111
+ function integer(
112
+ value: unknown,
113
+ fallback: number,
114
+ minimum: number,
115
+ ): number {
116
+ const parsed =
117
+ typeof value === "number"
118
+ ? value
119
+ : typeof value === "string" && value.trim() !== ""
120
+ ? Number(value)
121
+ : Number.NaN
122
+ if (!Number.isFinite(parsed)) return fallback
123
+ return Math.max(minimum, Math.floor(parsed))
124
+ }
125
+
126
+ function toolNames(value: unknown): ReadonlySet<string> {
127
+ if (!Array.isArray(value)) {
128
+ return new Set(DEFAULT_IGNORE_TOOLS)
129
+ }
130
+ const names = value
131
+ .filter((item): item is string => typeof item === "string")
132
+ .map((item) => item.trim().toLowerCase())
133
+ .filter(Boolean)
134
+ return new Set(names)
135
+ }
136
+
137
+ function threshold(
138
+ value: unknown,
139
+ fallback: number,
140
+ minimumWhenEnabled: number,
141
+ ): number {
142
+ const parsed = integer(value, fallback, 0)
143
+ if (parsed === 0) return 0
144
+ return Math.max(minimumWhenEnabled, parsed)
145
+ }
146
+
147
+ export function resolveOptions(
148
+ raw: Record<string, unknown> | undefined,
149
+ ): ResolvedOptions {
150
+ const value = raw ?? {}
151
+ return {
152
+ enabled: value.enabled !== false,
153
+ maxIdenticalActions: threshold(value.maxIdenticalActions, 4, 2),
154
+ maxCycleRepeats: threshold(value.maxCycleRepeats, 3, 2),
155
+ maxCycleLength: threshold(value.maxCycleLength, 4, 2),
156
+ maxIdenticalOutputs: threshold(value.maxIdenticalOutputs, 3, 2),
157
+ maxRepeatedOutputs: integer(value.maxRepeatedOutputs, 6, 0),
158
+ maxFailureStreak: integer(value.maxFailureStreak, 3, 0),
159
+ maxTestRuns: integer(value.maxTestRuns, 3, 0),
160
+ maxFileInvestigations: integer(value.maxFileInvestigations, 10, 0),
161
+ maxTotalInvestigations: integer(value.maxTotalInvestigations, 30, 0),
162
+ onTruncation: value.onTruncation === "off" ? "off" : "notify",
163
+ maxTruncatedSteps: integer(value.maxTruncatedSteps, 2, 1),
164
+ truncationCooldownMs: integer(value.truncationCooldownMs, 60_000, 0),
165
+ ignoreTools: toolNames(value.ignoreTools),
166
+ resetOnIdle: value.resetOnIdle !== false,
167
+ debug: value.debug === true,
168
+ }
169
+ }
170
+
171
+ export function isIgnoredTool(
172
+ tool: string,
173
+ options: ResolvedOptions,
174
+ ): boolean {
175
+ return options.ignoreTools.has(tool.toLowerCase())
176
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,449 @@
1
+ import {
2
+ describeAction,
3
+ isExecutionFamily,
4
+ type ActionDescriptor,
5
+ } from "./actions.js"
6
+ import { countTrailingSame, cycleReason, detectCycle } from "./detectors.js"
7
+ import { outputFingerprint } from "./normalize.js"
8
+ import type { ResolvedOptions } from "./options.js"
9
+ import { isIgnoredTool } from "./options.js"
10
+
11
+ const MAX_SESSIONS = 200
12
+ const MAX_ACTIONS = 40
13
+ const MAX_PENDING = 20
14
+ const MAX_OUTPUT_KEYS = 100
15
+ const MAX_TARGET_KEYS = 100
16
+ const MAX_TEST_KEYS = 100
17
+ const MIN_OUTPUT_LENGTH = 20
18
+
19
+ export const TRUNCATION_NOTICE =
20
+ "Loop Breaker: the last model steps hit the output limit. Stop reasoning now. Make one small tool call, or give a short answer."
21
+
22
+ export interface RuntimeDeps {
23
+ readonly cwd: string
24
+ readonly now?: () => number
25
+ readonly notify?: ((sessionID: string, text: string) => Promise<void>) | undefined
26
+ readonly debug?: ((message: string) => void) | undefined
27
+ }
28
+
29
+ export interface ToolBefore {
30
+ readonly sessionID: string
31
+ readonly tool: string
32
+ readonly callID: string
33
+ readonly input: unknown
34
+ }
35
+
36
+ export interface ToolAfter extends ToolBefore {
37
+ readonly status: "completed" | "error"
38
+ readonly text?: string
39
+ }
40
+
41
+ export interface StepEnded {
42
+ readonly sessionID: string
43
+ readonly finish: string
44
+ }
45
+
46
+ export type Decision =
47
+ | { readonly block: false }
48
+ | { readonly block: true; readonly reason: string; readonly message: string }
49
+
50
+ interface OutputRecord {
51
+ hash: string
52
+ count: number
53
+ }
54
+
55
+ interface SessionState {
56
+ actions: ActionDescriptor[]
57
+ pending: Map<string, ActionDescriptor>
58
+ investigations: number
59
+ targetInvestigations: Map<string, number>
60
+ testRuns: Map<string, number>
61
+ commandOutputs: Map<string, OutputRecord>
62
+ outputCounts: Map<string, number>
63
+ outputTrip: string | undefined
64
+ failures: number
65
+ blocks: number
66
+ truncatedSteps: number
67
+ lastTruncationNotice: number
68
+ seenAt: number
69
+ }
70
+
71
+ function emptyState(now: number): SessionState {
72
+ return {
73
+ actions: [],
74
+ pending: new Map(),
75
+ investigations: 0,
76
+ targetInvestigations: new Map(),
77
+ testRuns: new Map(),
78
+ commandOutputs: new Map(),
79
+ outputCounts: new Map(),
80
+ outputTrip: undefined,
81
+ failures: 0,
82
+ blocks: 0,
83
+ truncatedSteps: 0,
84
+ lastTruncationNotice: 0,
85
+ seenAt: now,
86
+ }
87
+ }
88
+
89
+ export class LoopBreakerRuntime {
90
+ readonly #options: ResolvedOptions
91
+ readonly #deps: RuntimeDeps
92
+ readonly #sessions = new Map<string, SessionState>()
93
+
94
+ constructor(options: ResolvedOptions, deps: RuntimeDeps) {
95
+ this.#options = options
96
+ this.#deps = deps
97
+ }
98
+
99
+ get size(): number {
100
+ return this.#sessions.size
101
+ }
102
+
103
+ before(event: ToolBefore): Decision {
104
+ if (!this.#options.enabled) return { block: false }
105
+ if (isIgnoredTool(event.tool, this.#options)) return { block: false }
106
+
107
+ const state = this.#state(event.sessionID)
108
+ const action = describeAction(event.tool, event.input, this.#deps.cwd)
109
+ const signatures = state.actions.map((record) => record.signature)
110
+
111
+ if (
112
+ this.#options.maxFailureStreak > 0 &&
113
+ state.failures >= this.#options.maxFailureStreak &&
114
+ isExecutionFamily(action.family)
115
+ ) {
116
+ return this.#block(
117
+ state,
118
+ "failure-streak",
119
+ `${state.failures} command runs failed in a row.`,
120
+ "Stop running this type of command. Read the last error and make one concrete change with write or edit.",
121
+ )
122
+ }
123
+
124
+ if (
125
+ state.outputTrip !== undefined &&
126
+ action.family !== "mutate" &&
127
+ action.family !== "investigate"
128
+ ) {
129
+ return this.#block(
130
+ state,
131
+ "repeated-output",
132
+ "Different commands returned the same output several times.",
133
+ "The output gave no new information. Change the code or the approach before you run another command.",
134
+ )
135
+ }
136
+
137
+ if (action.family === "investigate") {
138
+ const target = action.target
139
+ if (target) {
140
+ const targetCount = state.targetInvestigations.get(target) ?? 0
141
+ if (
142
+ this.#options.maxFileInvestigations > 0 &&
143
+ targetCount >= this.#options.maxFileInvestigations
144
+ ) {
145
+ return this.#block(
146
+ state,
147
+ "file-investigation",
148
+ `The target ${target} was inspected ${targetCount} times without a successful change.`,
149
+ "You have enough information from this target. Change the code or inspect a different target.",
150
+ )
151
+ }
152
+ }
153
+
154
+ if (
155
+ this.#options.maxTotalInvestigations > 0 &&
156
+ state.investigations >= this.#options.maxTotalInvestigations
157
+ ) {
158
+ return this.#block(
159
+ state,
160
+ "total-investigations",
161
+ `${state.investigations} inspections ran without a successful change.`,
162
+ "Stop collecting context. Make the smallest correct change with write or edit.",
163
+ )
164
+ }
165
+ }
166
+
167
+ if (
168
+ action.family === "test" &&
169
+ action.testKey !== undefined &&
170
+ this.#options.maxTestRuns > 0
171
+ ) {
172
+ const runs = state.testRuns.get(action.testKey) ?? 0
173
+ if (runs >= this.#options.maxTestRuns) {
174
+ return this.#block(
175
+ state,
176
+ "test-repeat",
177
+ `The same test command ran ${runs} times without a successful change.`,
178
+ "Change the code before you run this test again.",
179
+ )
180
+ }
181
+ }
182
+
183
+ const previousOutput = state.commandOutputs.get(action.signature)
184
+ if (
185
+ previousOutput &&
186
+ this.#options.maxIdenticalOutputs > 0 &&
187
+ previousOutput.count >= this.#options.maxIdenticalOutputs
188
+ ) {
189
+ return this.#block(
190
+ state,
191
+ "identical-output",
192
+ `This action returned the same output ${previousOutput.count} times.`,
193
+ "A further run cannot add information. Read the output you have and change the code.",
194
+ )
195
+ }
196
+
197
+ const same = countTrailingSame(signatures, action.signature)
198
+ if (
199
+ this.#options.maxIdenticalActions > 0 &&
200
+ same + 1 >= this.#options.maxIdenticalActions
201
+ ) {
202
+ return this.#block(
203
+ state,
204
+ "identical-action",
205
+ `The same ${action.tool} call repeated ${same + 1} times without a successful change.`,
206
+ "Do not repeat this call. Use the last result and take a different action.",
207
+ )
208
+ }
209
+
210
+ const cycle =
211
+ this.#options.maxCycleRepeats > 0 && this.#options.maxCycleLength > 0
212
+ ? detectCycle(
213
+ [...signatures, action.signature],
214
+ this.#options.maxCycleLength,
215
+ this.#options.maxCycleRepeats,
216
+ 2,
217
+ )
218
+ : null
219
+ if (cycle) {
220
+ return this.#block(
221
+ state,
222
+ "action-cycle",
223
+ cycleReason(cycle),
224
+ "The cycle adds no new information. Break it with a different action or a concrete code change.",
225
+ )
226
+ }
227
+
228
+ state.pending.set(event.callID, action)
229
+ if (state.pending.size > MAX_PENDING) {
230
+ const oldest = state.pending.keys().next().value
231
+ if (oldest !== undefined) state.pending.delete(oldest)
232
+ }
233
+
234
+ if (
235
+ action.family === "test" &&
236
+ action.testKey !== undefined &&
237
+ this.#options.maxTestRuns > 0
238
+ ) {
239
+ state.testRuns.set(
240
+ action.testKey,
241
+ (state.testRuns.get(action.testKey) ?? 0) + 1,
242
+ )
243
+ if (state.testRuns.size > MAX_TEST_KEYS) {
244
+ const oldest = state.testRuns.keys().next().value
245
+ if (oldest !== undefined) state.testRuns.delete(oldest)
246
+ }
247
+ }
248
+
249
+ if (action.family === "investigate") {
250
+ if (this.#options.maxTotalInvestigations > 0) {
251
+ state.investigations += 1
252
+ }
253
+ if (action.target && this.#options.maxFileInvestigations > 0) {
254
+ state.targetInvestigations.set(
255
+ action.target,
256
+ (state.targetInvestigations.get(action.target) ?? 0) + 1,
257
+ )
258
+ if (state.targetInvestigations.size > MAX_TARGET_KEYS) {
259
+ const oldest = state.targetInvestigations.keys().next().value
260
+ if (oldest !== undefined) state.targetInvestigations.delete(oldest)
261
+ }
262
+ }
263
+ }
264
+
265
+ return { block: false }
266
+ }
267
+
268
+ after(event: ToolAfter): void {
269
+ if (!this.#options.enabled) return
270
+ if (isIgnoredTool(event.tool, this.#options)) return
271
+
272
+ const state = this.#state(event.sessionID)
273
+ const action =
274
+ state.pending.get(event.callID) ??
275
+ describeAction(event.tool, event.input, this.#deps.cwd)
276
+ state.pending.delete(event.callID)
277
+
278
+ const failed = event.status === "error"
279
+ const fingerprint = event.text
280
+ ? outputFingerprint(event.text, this.#deps.cwd)
281
+ : undefined
282
+
283
+ state.actions.push(action)
284
+ if (state.actions.length > MAX_ACTIONS) {
285
+ state.actions.splice(0, state.actions.length - MAX_ACTIONS)
286
+ }
287
+
288
+ if (
289
+ fingerprint &&
290
+ fingerprint.length >= MIN_OUTPUT_LENGTH &&
291
+ (this.#options.maxIdenticalOutputs > 0 ||
292
+ this.#options.maxRepeatedOutputs > 0)
293
+ ) {
294
+ if (this.#options.maxIdenticalOutputs > 0) {
295
+ const previous = state.commandOutputs.get(action.signature)
296
+ if (previous && previous.hash === fingerprint.hash) {
297
+ previous.count += 1
298
+ } else {
299
+ state.commandOutputs.set(action.signature, {
300
+ hash: fingerprint.hash,
301
+ count: 1,
302
+ })
303
+ }
304
+ if (state.commandOutputs.size > MAX_OUTPUT_KEYS) {
305
+ const oldest = state.commandOutputs.keys().next().value
306
+ if (oldest !== undefined) state.commandOutputs.delete(oldest)
307
+ }
308
+ }
309
+
310
+ if (this.#options.maxRepeatedOutputs > 0) {
311
+ const globalCount =
312
+ (state.outputCounts.get(fingerprint.hash) ?? 0) + 1
313
+ state.outputCounts.set(fingerprint.hash, globalCount)
314
+ if (globalCount >= this.#options.maxRepeatedOutputs) {
315
+ state.outputTrip = fingerprint.hash
316
+ }
317
+ if (
318
+ state.outputTrip !== undefined &&
319
+ state.outputTrip !== fingerprint.hash &&
320
+ !failed
321
+ ) {
322
+ state.outputTrip = undefined
323
+ }
324
+ if (state.outputCounts.size > MAX_OUTPUT_KEYS) {
325
+ const oldest = state.outputCounts.keys().next().value
326
+ if (oldest !== undefined) state.outputCounts.delete(oldest)
327
+ }
328
+ }
329
+ }
330
+
331
+ if (failed) {
332
+ if (isExecutionFamily(action.family)) state.failures += 1
333
+ return
334
+ }
335
+
336
+ if (isExecutionFamily(action.family)) state.failures = 0
337
+ if (action.family === "mutate") this.#resetForMutation(state)
338
+ }
339
+
340
+ async onStepEnded(event: StepEnded): Promise<void> {
341
+ if (!this.#options.enabled) return
342
+ if (this.#options.onTruncation === "off") return
343
+ const state = this.#state(event.sessionID)
344
+
345
+ if (event.finish !== "length") {
346
+ state.truncatedSteps = 0
347
+ return
348
+ }
349
+
350
+ state.truncatedSteps += 1
351
+ if (state.truncatedSteps < this.#options.maxTruncatedSteps) return
352
+
353
+ const now = this.#now()
354
+ if (
355
+ state.lastTruncationNotice !== 0 &&
356
+ now - state.lastTruncationNotice < this.#options.truncationCooldownMs
357
+ ) {
358
+ return
359
+ }
360
+
361
+ state.truncatedSteps = 0
362
+ state.lastTruncationNotice = now
363
+ if (!this.#deps.notify) return
364
+
365
+ try {
366
+ await this.#deps.notify(event.sessionID, TRUNCATION_NOTICE)
367
+ } catch (error) {
368
+ this.#log(`truncation notice failed: ${String(error)}`)
369
+ }
370
+ }
371
+
372
+ onIdle(sessionID: string): void {
373
+ if (this.#options.resetOnIdle) this.#sessions.delete(sessionID)
374
+ }
375
+
376
+ dispose(): void {
377
+ this.#sessions.clear()
378
+ }
379
+
380
+ #state(sessionID: string): SessionState {
381
+ const now = this.#now()
382
+ const existing = this.#sessions.get(sessionID)
383
+ if (existing) {
384
+ existing.seenAt = now
385
+ return existing
386
+ }
387
+
388
+ if (this.#sessions.size >= MAX_SESSIONS) {
389
+ let oldestID: string | undefined
390
+ let oldestSeen = Number.POSITIVE_INFINITY
391
+ for (const [id, state] of this.#sessions) {
392
+ if (state.seenAt < oldestSeen) {
393
+ oldestSeen = state.seenAt
394
+ oldestID = id
395
+ }
396
+ }
397
+ if (oldestID !== undefined) this.#sessions.delete(oldestID)
398
+ }
399
+
400
+ const created = emptyState(now)
401
+ this.#sessions.set(sessionID, created)
402
+ return created
403
+ }
404
+
405
+ #block(
406
+ state: SessionState,
407
+ reason: string,
408
+ detail: string,
409
+ advice: string,
410
+ ): Decision {
411
+ state.blocks += 1
412
+ this.#log(`blocked: ${reason}: ${detail}`)
413
+
414
+ const escalation =
415
+ state.blocks >= 4
416
+ ? "\nThis is a repeated block. Stop and explain the blocker to the user."
417
+ : ""
418
+ return {
419
+ block: true,
420
+ reason,
421
+ message: `Loop Breaker blocked this tool call.\nReason: ${detail}\n${advice}${escalation}`,
422
+ }
423
+ }
424
+
425
+ #resetForMutation(state: SessionState): void {
426
+ state.actions.length = 0
427
+ state.investigations = 0
428
+ state.targetInvestigations.clear()
429
+ state.testRuns.clear()
430
+ state.commandOutputs.clear()
431
+ state.outputCounts.clear()
432
+ state.outputTrip = undefined
433
+ state.failures = 0
434
+ state.blocks = 0
435
+ }
436
+
437
+ #now(): number {
438
+ return this.#deps.now?.() ?? Date.now()
439
+ }
440
+
441
+ #log(message: string): void {
442
+ if (!this.#options.debug && !this.#deps.debug) return
443
+ if (this.#deps.debug) {
444
+ this.#deps.debug(message)
445
+ return
446
+ }
447
+ console.error(`[loop-breaker] ${message}`)
448
+ }
449
+ }