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/LICENSE +21 -0
- package/README.md +201 -2
- package/docs/analysis.md +458 -0
- package/package.json +29 -4
- package/src/actions.ts +321 -0
- package/src/detectors.ts +57 -0
- package/src/index.ts +102 -0
- package/src/normalize.ts +122 -0
- package/src/options.ts +176 -0
- package/src/runtime.ts +449 -0
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-agent-loop-breaker",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenCode V2 plugin that detects and breaks agent loops without compaction or rollback.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./src/index.ts",
|
|
10
|
+
"import": "./src/index.ts"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"docs",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"typecheck": "tsc --noEmit"
|
|
21
|
+
},
|
|
22
|
+
"peerDependencies": {
|
|
23
|
+
"@opencode/plugin": ">=2.4.3"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@opencode/plugin": "2.4.3",
|
|
27
|
+
"@types/node": "^24.0.0",
|
|
28
|
+
"typescript": "^5.8.0",
|
|
29
|
+
"vitest": "^4.0.0"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import {
|
|
2
|
+
normalizeCommand,
|
|
3
|
+
shortHash,
|
|
4
|
+
stableStringify,
|
|
5
|
+
} from "./normalize.js"
|
|
6
|
+
|
|
7
|
+
export type ActionFamily =
|
|
8
|
+
| "mutate"
|
|
9
|
+
| "test"
|
|
10
|
+
| "build"
|
|
11
|
+
| "investigate"
|
|
12
|
+
| "execute"
|
|
13
|
+
|
|
14
|
+
export interface ActionDescriptor {
|
|
15
|
+
readonly tool: string
|
|
16
|
+
readonly signature: string
|
|
17
|
+
readonly family: ActionFamily
|
|
18
|
+
readonly target?: string
|
|
19
|
+
readonly testKey?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const TEST_COMMAND =
|
|
23
|
+
/\b(?:vitest|jest|mocha|pytest|phpunit|rspec|ctest)\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|\b(?:cargo|go|dotnet)\s+test\b|\bmake\s+(?:test|check)\b/i
|
|
24
|
+
const BUILD_COMMAND =
|
|
25
|
+
/\b(?:tsc|eslint|biome|prettier|ruff|mypy|webpack)\b|\b(?:cargo\s+(?:build|check)|go\s+build|cmake|make|vite\s+build|next\s+build)\b|\b(?:npm|pnpm|yarn|bun)\s+run\s+(?:build|lint|check|typecheck)\b/i
|
|
26
|
+
const MUTATION_COMMAND =
|
|
27
|
+
/(?:^|[;&|]\s*)(?:sudo\s+)?(?:sed\s+-i|perl\s+-[a-z]*i|mv|cp|rm|mkdir|rmdir|touch|chmod|chown|ln|truncate)\b|(?:^|\s)>{1,2}\s*\S|(?:^|\s)tee\s+\S|\b(?:npm|pnpm|yarn|bun)\s+(?:install|add|remove|uninstall)\b|\b(?:pip|pip3)\s+install\b|\bcargo\s+(?:add|remove|install)\b|\bgo\s+(?:get|install)\b|\bgit\s+(?:apply|am|cherry-pick|revert|reset|checkout|switch)\b|\bapply_patch\b/i
|
|
28
|
+
const INVESTIGATION_COMMAND =
|
|
29
|
+
/\b(?:cat|head|tail|less|more|wc|stat|file|tree|ls|find|grep|rg|ag|ack|sed|awk|cut|sort|uniq|jq|git\s+(?:status|diff|log|show|blame|rev-parse)|(?:npm|pnpm|yarn|bun)\s+(?:ls|list))\b/i
|
|
30
|
+
|
|
31
|
+
const TARGET_VERBS = new Set([
|
|
32
|
+
"cat",
|
|
33
|
+
"head",
|
|
34
|
+
"tail",
|
|
35
|
+
"less",
|
|
36
|
+
"more",
|
|
37
|
+
"wc",
|
|
38
|
+
"stat",
|
|
39
|
+
"file",
|
|
40
|
+
"sed",
|
|
41
|
+
"awk",
|
|
42
|
+
"cut",
|
|
43
|
+
"sort",
|
|
44
|
+
"uniq",
|
|
45
|
+
"jq",
|
|
46
|
+
"grep",
|
|
47
|
+
"rg",
|
|
48
|
+
"ag",
|
|
49
|
+
"ack",
|
|
50
|
+
"find",
|
|
51
|
+
"ls",
|
|
52
|
+
"tree",
|
|
53
|
+
"vim",
|
|
54
|
+
"nano",
|
|
55
|
+
"diff",
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
const LAST_ARGUMENT_VERBS = new Set(["grep", "rg", "ag", "ack", "sed", "awk"])
|
|
59
|
+
|
|
60
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
61
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function firstString(
|
|
65
|
+
input: Record<string, unknown>,
|
|
66
|
+
keys: readonly string[],
|
|
67
|
+
): string | undefined {
|
|
68
|
+
for (const key of keys) {
|
|
69
|
+
const value = input[key]
|
|
70
|
+
if (typeof value === "string" && value.trim() !== "") return value
|
|
71
|
+
}
|
|
72
|
+
return undefined
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function toolName(tool: string): string {
|
|
76
|
+
return tool.trim().toLowerCase()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function matchesTool(tool: string, name: string): boolean {
|
|
80
|
+
const value = toolName(tool)
|
|
81
|
+
return (
|
|
82
|
+
value === name ||
|
|
83
|
+
value.startsWith(`${name}_`) ||
|
|
84
|
+
value.endsWith(`_${name}`) ||
|
|
85
|
+
value.endsWith(`.${name}`)
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function normalizePath(
|
|
90
|
+
value: string,
|
|
91
|
+
cwd?: string,
|
|
92
|
+
): string {
|
|
93
|
+
let path = value.trim().replaceAll("\\", "/")
|
|
94
|
+
if (path.startsWith("file://")) path = path.slice("file://".length)
|
|
95
|
+
if (cwd && cwd.length > 0) {
|
|
96
|
+
const prefix = cwd.endsWith("/") ? cwd : `${cwd}/`
|
|
97
|
+
if (path.startsWith(prefix)) path = path.slice(prefix.length)
|
|
98
|
+
}
|
|
99
|
+
return path.replace(/^\.\//, "")
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function pathSignature(value: string | undefined, cwd?: string): string {
|
|
103
|
+
return value ? normalizePath(value, cwd) : "<none>"
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function classifyBash(command: string): ActionFamily {
|
|
107
|
+
if (TEST_COMMAND.test(command)) return "test"
|
|
108
|
+
if (BUILD_COMMAND.test(command)) return "build"
|
|
109
|
+
if (MUTATION_COMMAND.test(command)) return "mutate"
|
|
110
|
+
if (INVESTIGATION_COMMAND.test(command)) return "investigate"
|
|
111
|
+
return "execute"
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function extractBashTarget(
|
|
115
|
+
command: string,
|
|
116
|
+
cwd?: string,
|
|
117
|
+
): string | undefined {
|
|
118
|
+
const tokens = command.split(/\s+/).filter(Boolean)
|
|
119
|
+
let index = 0
|
|
120
|
+
while (index < tokens.length) {
|
|
121
|
+
const token = tokens[index] ?? ""
|
|
122
|
+
if (
|
|
123
|
+
token === "sudo" ||
|
|
124
|
+
token === "time" ||
|
|
125
|
+
token === "env" ||
|
|
126
|
+
/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)
|
|
127
|
+
) {
|
|
128
|
+
index += 1
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
break
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const verb = tokens[index] ?? ""
|
|
135
|
+
if (verb === "git") {
|
|
136
|
+
const rest = tokens.slice(index + 1)
|
|
137
|
+
const subcommand = rest[0] ?? ""
|
|
138
|
+
const file = [...rest]
|
|
139
|
+
.reverse()
|
|
140
|
+
.find(
|
|
141
|
+
(token) =>
|
|
142
|
+
!token.startsWith("-") &&
|
|
143
|
+
!token.startsWith("'") &&
|
|
144
|
+
!token.startsWith('"'),
|
|
145
|
+
)
|
|
146
|
+
if (file && file !== subcommand) return normalizePath(file, cwd)
|
|
147
|
+
return subcommand ? `git:${subcommand}` : "git"
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (!TARGET_VERBS.has(verb)) return undefined
|
|
151
|
+
const rest = tokens.slice(index + 1)
|
|
152
|
+
const candidates = rest.filter(
|
|
153
|
+
(token) =>
|
|
154
|
+
!token.startsWith("-") &&
|
|
155
|
+
!token.startsWith("'") &&
|
|
156
|
+
!token.startsWith('"') &&
|
|
157
|
+
!/^\d+$/.test(token) &&
|
|
158
|
+
token !== "|" &&
|
|
159
|
+
token !== "&&" &&
|
|
160
|
+
token !== ";" &&
|
|
161
|
+
token !== ">" &&
|
|
162
|
+
token !== ">>",
|
|
163
|
+
)
|
|
164
|
+
if (candidates.length === 0) return undefined
|
|
165
|
+
const chosen = LAST_ARGUMENT_VERBS.has(verb)
|
|
166
|
+
? candidates[candidates.length - 1]
|
|
167
|
+
: candidates[0]
|
|
168
|
+
return chosen ? normalizePath(chosen, cwd) : undefined
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function describeAction(
|
|
172
|
+
tool: string,
|
|
173
|
+
input: unknown,
|
|
174
|
+
cwd?: string,
|
|
175
|
+
): ActionDescriptor {
|
|
176
|
+
const name = toolName(tool)
|
|
177
|
+
const args = isRecord(input) ? input : {}
|
|
178
|
+
|
|
179
|
+
if (matchesTool(name, "bash") || matchesTool(name, "shell")) {
|
|
180
|
+
const raw = firstString(args, ["command", "cmd", "script"]) ?? ""
|
|
181
|
+
const command = normalizeCommand(raw)
|
|
182
|
+
const family = classifyBash(command)
|
|
183
|
+
const target = extractBashTarget(command, cwd)
|
|
184
|
+
return {
|
|
185
|
+
tool: name,
|
|
186
|
+
signature: `${name}:${command}`,
|
|
187
|
+
family,
|
|
188
|
+
...(target ? { target } : {}),
|
|
189
|
+
...(family === "test" ? { testKey: command } : {}),
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (matchesTool(name, "write") || matchesTool(name, "edit")) {
|
|
194
|
+
const path = firstString(args, [
|
|
195
|
+
"filePath",
|
|
196
|
+
"file_path",
|
|
197
|
+
"path",
|
|
198
|
+
"filename",
|
|
199
|
+
"file",
|
|
200
|
+
])
|
|
201
|
+
const previous =
|
|
202
|
+
firstString(args, ["oldString", "old_string"]) ?? ""
|
|
203
|
+
const next =
|
|
204
|
+
firstString(args, ["content", "newString", "new_string", "text"]) ??
|
|
205
|
+
stableStringify(args)
|
|
206
|
+
const content = `${previous}\u0000${next}`
|
|
207
|
+
const target = path ? normalizePath(path, cwd) : undefined
|
|
208
|
+
return {
|
|
209
|
+
tool: name,
|
|
210
|
+
signature: `${name}:${pathSignature(target)}:${shortHash(content)}`,
|
|
211
|
+
family: "mutate",
|
|
212
|
+
...(target ? { target } : {}),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (matchesTool(name, "apply_patch") || matchesTool(name, "patch")) {
|
|
217
|
+
const path = firstString(args, [
|
|
218
|
+
"filePath",
|
|
219
|
+
"file_path",
|
|
220
|
+
"path",
|
|
221
|
+
"filename",
|
|
222
|
+
"file",
|
|
223
|
+
])
|
|
224
|
+
const target = path ? normalizePath(path, cwd) : undefined
|
|
225
|
+
const patch =
|
|
226
|
+
firstString(args, ["patch", "diff", "content", "text"]) ??
|
|
227
|
+
stableStringify(args)
|
|
228
|
+
return {
|
|
229
|
+
tool: name,
|
|
230
|
+
signature: `${name}:${pathSignature(target)}:${shortHash(patch)}`,
|
|
231
|
+
family: "mutate",
|
|
232
|
+
...(target ? { target } : {}),
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (matchesTool(name, "read")) {
|
|
237
|
+
const path = firstString(args, [
|
|
238
|
+
"filePath",
|
|
239
|
+
"file_path",
|
|
240
|
+
"path",
|
|
241
|
+
"filename",
|
|
242
|
+
"file",
|
|
243
|
+
])
|
|
244
|
+
const offset =
|
|
245
|
+
typeof args.offset === "number" ? String(args.offset) : ""
|
|
246
|
+
const limit = typeof args.limit === "number" ? String(args.limit) : ""
|
|
247
|
+
const target = path ? normalizePath(path, cwd) : undefined
|
|
248
|
+
return {
|
|
249
|
+
tool: name,
|
|
250
|
+
signature: `${name}:${pathSignature(target)}:${offset}:${limit}`,
|
|
251
|
+
family: "investigate",
|
|
252
|
+
...(target ? { target } : {}),
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (
|
|
257
|
+
matchesTool(name, "grep") ||
|
|
258
|
+
matchesTool(name, "glob") ||
|
|
259
|
+
matchesTool(name, "list")
|
|
260
|
+
) {
|
|
261
|
+
const pattern = firstString(args, ["pattern", "query", "glob"]) ?? ""
|
|
262
|
+
const path = firstString(args, [
|
|
263
|
+
"path",
|
|
264
|
+
"filePath",
|
|
265
|
+
"file_path",
|
|
266
|
+
"directory",
|
|
267
|
+
"dir",
|
|
268
|
+
])
|
|
269
|
+
const target = path ? normalizePath(path, cwd) : undefined
|
|
270
|
+
return {
|
|
271
|
+
tool: name,
|
|
272
|
+
signature: `${name}:${pattern}:${pathSignature(target)}`,
|
|
273
|
+
family: "investigate",
|
|
274
|
+
...(target ? { target } : {}),
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (matchesTool(name, "webfetch") || matchesTool(name, "fetch")) {
|
|
279
|
+
const url = firstString(args, ["url", "uri"]) ?? ""
|
|
280
|
+
let host = url
|
|
281
|
+
try {
|
|
282
|
+
host = new URL(url).host
|
|
283
|
+
} catch {
|
|
284
|
+
// Keep the raw value when the URL is not valid.
|
|
285
|
+
}
|
|
286
|
+
return {
|
|
287
|
+
tool: name,
|
|
288
|
+
signature: `${name}:${normalizeCommand(url)}`,
|
|
289
|
+
family: "investigate",
|
|
290
|
+
...(host ? { target: host } : {}),
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (matchesTool(name, "task")) {
|
|
295
|
+
const agent =
|
|
296
|
+
firstString(args, [
|
|
297
|
+
"subagent_type",
|
|
298
|
+
"subagentType",
|
|
299
|
+
"agent",
|
|
300
|
+
"agent_type",
|
|
301
|
+
"agentType",
|
|
302
|
+
]) ?? "task"
|
|
303
|
+
const description = firstString(args, ["description", "prompt"]) ?? ""
|
|
304
|
+
return {
|
|
305
|
+
tool: name,
|
|
306
|
+
signature: `${name}:${agent}:${shortHash(description)}`,
|
|
307
|
+
family: "execute",
|
|
308
|
+
target: agent,
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
tool: name,
|
|
314
|
+
signature: `${name}:${shortHash(stableStringify(args))}`,
|
|
315
|
+
family: "execute",
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function isExecutionFamily(family: ActionFamily): boolean {
|
|
320
|
+
return family === "execute" || family === "test" || family === "build"
|
|
321
|
+
}
|
package/src/detectors.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export interface CycleMatch {
|
|
2
|
+
readonly length: number
|
|
3
|
+
readonly repeats: number
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export function countTrailingSame(
|
|
7
|
+
signatures: readonly string[],
|
|
8
|
+
current: string,
|
|
9
|
+
): number {
|
|
10
|
+
let count = 0
|
|
11
|
+
for (let index = signatures.length - 1; index >= 0; index -= 1) {
|
|
12
|
+
if (signatures[index] !== current) break
|
|
13
|
+
count += 1
|
|
14
|
+
}
|
|
15
|
+
return count
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Detect a block of length L that repeats at least minRepeats times at the
|
|
20
|
+
* end of the signature list. The current prospective signature may be the
|
|
21
|
+
* last item, so the detector can block before the call runs.
|
|
22
|
+
*/
|
|
23
|
+
export function detectCycle(
|
|
24
|
+
signatures: readonly string[],
|
|
25
|
+
maxLength: number,
|
|
26
|
+
minRepeats: number,
|
|
27
|
+
minimumLength = 1,
|
|
28
|
+
): CycleMatch | null {
|
|
29
|
+
const start = Math.max(1, minimumLength)
|
|
30
|
+
const limit = Math.min(maxLength, Math.floor(signatures.length / minRepeats))
|
|
31
|
+
for (let length = start; length <= limit; length += 1) {
|
|
32
|
+
const pattern = signatures.slice(-length)
|
|
33
|
+
let repeats = 1
|
|
34
|
+
|
|
35
|
+
for (
|
|
36
|
+
let end = signatures.length - length;
|
|
37
|
+
end - length >= 0;
|
|
38
|
+
end -= length
|
|
39
|
+
) {
|
|
40
|
+
const block = signatures.slice(end - length, end)
|
|
41
|
+
if (!samePattern(block, pattern)) break
|
|
42
|
+
repeats += 1
|
|
43
|
+
if (repeats >= minRepeats) return { length, repeats }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function samePattern(left: readonly string[], right: readonly string[]): boolean {
|
|
50
|
+
if (left.length !== right.length) return false
|
|
51
|
+
return left.every((value, index) => value === right[index])
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function cycleReason(match: CycleMatch): string {
|
|
55
|
+
const actionWord = match.length === 1 ? "action" : "actions"
|
|
56
|
+
return `The last ${match.length} ${actionWord} repeated ${match.repeats} times without a successful change.`
|
|
57
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { resolveOptions } from "./options.js"
|
|
3
|
+
import { LoopBreakerRuntime } from "./runtime.js"
|
|
4
|
+
|
|
5
|
+
function resultText(result: unknown): string {
|
|
6
|
+
if (typeof result === "string") return result
|
|
7
|
+
if (!result || typeof result !== "object") return ""
|
|
8
|
+
|
|
9
|
+
const value = result as {
|
|
10
|
+
content?: unknown
|
|
11
|
+
output?: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (typeof value.content === "string") return value.content
|
|
15
|
+
if (Array.isArray(value.content)) {
|
|
16
|
+
return value.content
|
|
17
|
+
.map((part) => {
|
|
18
|
+
if (!part || typeof part !== "object") return ""
|
|
19
|
+
const piece = part as { type?: unknown; text?: unknown }
|
|
20
|
+
return piece.type === "text" && typeof piece.text === "string"
|
|
21
|
+
? piece.text
|
|
22
|
+
: ""
|
|
23
|
+
})
|
|
24
|
+
.filter(Boolean)
|
|
25
|
+
.join("\n")
|
|
26
|
+
}
|
|
27
|
+
if (typeof value.output === "string") return value.output
|
|
28
|
+
return ""
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export default Plugin.define({
|
|
32
|
+
id: "agent-loop-breaker",
|
|
33
|
+
async setup(ctx) {
|
|
34
|
+
const options = resolveOptions({ ...ctx.options })
|
|
35
|
+
const controller = new AbortController()
|
|
36
|
+
|
|
37
|
+
const runtime = new LoopBreakerRuntime(options, {
|
|
38
|
+
cwd: ctx.location.directory,
|
|
39
|
+
notify: async (sessionID, text) => {
|
|
40
|
+
await ctx.session.synthetic({
|
|
41
|
+
sessionID,
|
|
42
|
+
text,
|
|
43
|
+
description: "Loop Breaker",
|
|
44
|
+
})
|
|
45
|
+
},
|
|
46
|
+
debug: options.debug
|
|
47
|
+
? (message) => console.error(`[loop-breaker] ${message}`)
|
|
48
|
+
: undefined,
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
await ctx.tool.hook("execute.before", (event) => {
|
|
52
|
+
const decision = runtime.before({
|
|
53
|
+
sessionID: event.sessionID,
|
|
54
|
+
tool: event.tool,
|
|
55
|
+
callID: event.id,
|
|
56
|
+
input: event.input,
|
|
57
|
+
})
|
|
58
|
+
if (decision.block) throw new Error(decision.message)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
await ctx.tool.hook("execute.after", (event) => {
|
|
62
|
+
runtime.after({
|
|
63
|
+
sessionID: event.sessionID,
|
|
64
|
+
tool: event.tool,
|
|
65
|
+
callID: event.id,
|
|
66
|
+
input: event.input,
|
|
67
|
+
status: event.status,
|
|
68
|
+
text:
|
|
69
|
+
event.status === "completed"
|
|
70
|
+
? resultText(event.result)
|
|
71
|
+
: event.error.message,
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
void (async () => {
|
|
76
|
+
try {
|
|
77
|
+
for await (const event of ctx.event.subscribe({
|
|
78
|
+
types: ["session.step.ended", "session.idle"],
|
|
79
|
+
signal: controller.signal,
|
|
80
|
+
})) {
|
|
81
|
+
if (event.type === "session.step.ended") {
|
|
82
|
+
await runtime.onStepEnded({
|
|
83
|
+
sessionID: event.data.sessionID,
|
|
84
|
+
finish: event.data.finish,
|
|
85
|
+
})
|
|
86
|
+
} else {
|
|
87
|
+
runtime.onIdle(event.data.sessionID)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (!controller.signal.aborted) {
|
|
92
|
+
console.error("[loop-breaker] event stream stopped", error)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
})()
|
|
96
|
+
|
|
97
|
+
return () => {
|
|
98
|
+
controller.abort()
|
|
99
|
+
runtime.dispose()
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
})
|
package/src/normalize.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
|
|
3
|
+
const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g
|
|
4
|
+
const ISO_TIME =
|
|
5
|
+
/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g
|
|
6
|
+
const UUID =
|
|
7
|
+
/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi
|
|
8
|
+
const HEX = /\b0x[0-9a-f]+\b/gi
|
|
9
|
+
const TEMP =
|
|
10
|
+
/(?:\/private\/var\/folders|\/var\/folders|\/tmp)\/[^\s"'`),;]+/g
|
|
11
|
+
const DURATION =
|
|
12
|
+
/\b\d+(?:\.\d+)?\s*(?:ms|msec|milliseconds?|s|sec|secs|seconds?|m|min|mins|minutes?)\b/gi
|
|
13
|
+
const FILE_LINE =
|
|
14
|
+
/\b([\w./-]+\.(?:[cm]?[jt]sx?|py|go|rs|rb|java|kt|swift|cs|c|cc|cpp|h|hpp|md|json|ya?ml|toml|txt)):\d+(?::\d+)?\b/g
|
|
15
|
+
const PAREN_LOCATION = /\b([\w./-]+\.\w+)\(\d+,\d+\)/g
|
|
16
|
+
const COMPILER_GUTTER = /^\s*\d+\s*[|>]\s?/gm
|
|
17
|
+
|
|
18
|
+
export function stripAnsi(text: string): string {
|
|
19
|
+
return text.replace(ANSI, "")
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function sha256(text: string): string {
|
|
23
|
+
return createHash("sha256").update(text, "utf8").digest("hex")
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function shortHash(text: string): string {
|
|
27
|
+
return sha256(text).slice(0, 16)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function collapse(text: string): string {
|
|
31
|
+
return text.replace(/[ \t]+/g, " ").replace(/\n{2,}/g, "\n").trim()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Make a shell command stable enough for loop detection.
|
|
36
|
+
* It keeps the command meaning, but removes volatile paths and line numbers.
|
|
37
|
+
*/
|
|
38
|
+
export function normalizeCommand(command: string): string {
|
|
39
|
+
let text = stripAnsi(command).replace(/\r\n/g, "\n")
|
|
40
|
+
|
|
41
|
+
text = text.replace(
|
|
42
|
+
/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n([\s\S]*?)\n\s*\2\b/g,
|
|
43
|
+
(_match, _quote: string, tag: string, body: string) =>
|
|
44
|
+
`<<${tag}\n#${shortHash(body)}\n${tag}`,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
text = text.replace(/\s+/g, " ")
|
|
48
|
+
text = text.replace(TEMP, "<tmp>")
|
|
49
|
+
text = text.replace(ISO_TIME, "<time>")
|
|
50
|
+
text = text.replace(UUID, "<uuid>")
|
|
51
|
+
text = text.replace(HEX, "<hex>")
|
|
52
|
+
text = text.replace(/\b(line|col|column)\s+\d+\b/gi, "$1 #")
|
|
53
|
+
return collapse(text)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Remove values that change between runs but do not carry information.
|
|
58
|
+
* The result is hashed, so cosmetic changes do not reset a loop counter.
|
|
59
|
+
*/
|
|
60
|
+
export function normalizeOutput(output: string, cwd?: string): string {
|
|
61
|
+
let text = stripAnsi(output).replace(/\r\n/g, "\n")
|
|
62
|
+
|
|
63
|
+
if (cwd && cwd.length > 0) {
|
|
64
|
+
const prefix = cwd.endsWith("/") ? cwd : `${cwd}/`
|
|
65
|
+
text = text.split(prefix).join("")
|
|
66
|
+
if (text === cwd) text = "."
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
text = text.replace(COMPILER_GUTTER, "")
|
|
70
|
+
text = text.replace(FILE_LINE, "$1:#")
|
|
71
|
+
text = text.replace(PAREN_LOCATION, "$1(#,#)")
|
|
72
|
+
text = text.replace(TEMP, "<tmp>")
|
|
73
|
+
text = text.replace(ISO_TIME, "<time>")
|
|
74
|
+
text = text.replace(UUID, "<uuid>")
|
|
75
|
+
text = text.replace(HEX, "<hex>")
|
|
76
|
+
text = text.replace(DURATION, "<duration>")
|
|
77
|
+
text = text.replace(
|
|
78
|
+
/\b(?:line|col|column)\s+\d+\b/gi,
|
|
79
|
+
(match) => match.replace(/\d+$/, "#"),
|
|
80
|
+
)
|
|
81
|
+
text = collapse(text)
|
|
82
|
+
|
|
83
|
+
// Huge outputs are expensive to hash and add no more loop signal.
|
|
84
|
+
return text.length > 200_000 ? text.slice(0, 200_000) : text
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function outputFingerprint(
|
|
88
|
+
output: string,
|
|
89
|
+
cwd?: string,
|
|
90
|
+
): { hash: string; length: number } {
|
|
91
|
+
const normalized = normalizeOutput(output, cwd)
|
|
92
|
+
return { hash: shortHash(normalized), length: normalized.length }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Deterministic JSON for tool inputs whose shape is not known in advance.
|
|
97
|
+
*/
|
|
98
|
+
export function stableStringify(value: unknown, depth = 0): string {
|
|
99
|
+
if (value === null) return "null"
|
|
100
|
+
const kind = typeof value
|
|
101
|
+
if (kind === "string") return JSON.stringify(value)
|
|
102
|
+
if (kind === "number" || kind === "boolean") return String(value)
|
|
103
|
+
if (kind === "undefined") return "undefined"
|
|
104
|
+
if (kind === "bigint") return `${String(value)}n`
|
|
105
|
+
if (kind === "function") return "[function]"
|
|
106
|
+
if (kind === "symbol") return String(value)
|
|
107
|
+
if (kind !== "object") return String(value)
|
|
108
|
+
|
|
109
|
+
if (depth >= 6) return "[depth]"
|
|
110
|
+
if (Array.isArray(value)) {
|
|
111
|
+
return `[${value.map((item) => stableStringify(item, depth + 1)).join(",")}]`
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const record = value as Record<string, unknown>
|
|
115
|
+
const entries = Object.keys(record)
|
|
116
|
+
.sort()
|
|
117
|
+
.map(
|
|
118
|
+
(key) =>
|
|
119
|
+
`${JSON.stringify(key)}:${stableStringify(record[key], depth + 1)}`,
|
|
120
|
+
)
|
|
121
|
+
return `{${entries.join(",")}}`
|
|
122
|
+
}
|