@adayacas/loopbreaker 0.0.0-stage → 0.3.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 +88 -2
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +109 -0
- package/dist/src/config-loader.d.ts +10 -0
- package/dist/src/config-loader.js +143 -0
- package/dist/src/frontmatter.d.ts +2 -0
- package/dist/src/frontmatter.js +132 -0
- package/dist/src/glob.d.ts +3 -0
- package/dist/src/glob.js +75 -0
- package/dist/src/guard.d.ts +26 -0
- package/dist/src/guard.js +209 -0
- package/dist/src/index.d.ts +45 -0
- package/dist/src/index.js +56 -0
- package/dist/src/installer.d.ts +26 -0
- package/dist/src/installer.js +171 -0
- package/dist/src/loop-detector.d.ts +24 -0
- package/dist/src/loop-detector.js +136 -0
- package/dist/src/scope-validator.d.ts +16 -0
- package/dist/src/scope-validator.js +114 -0
- package/dist/src/types.d.ts +72 -0
- package/dist/src/types.js +1 -0
- package/dist/src/wizard.d.ts +23 -0
- package/dist/src/wizard.js +58 -0
- package/package.json +50 -3
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ResolvedConfig, Verdict } from "./types.js";
|
|
2
|
+
/** Normaliza a ruta relativa al proyecto con "/". Devuelve null si queda fuera de la raíz. */
|
|
3
|
+
export declare function toRel(root: string, p: string): string | null;
|
|
4
|
+
/** Valida UNA ruta que se va a escribir. */
|
|
5
|
+
export declare function checkPath(cfg: ResolvedConfig, p: string): Verdict;
|
|
6
|
+
export declare function checkPaths(cfg: ResolvedConfig, paths: string[]): Verdict;
|
|
7
|
+
/** Rutas que toca una llamada de escritura. Para edit/write/patch es exacto. */
|
|
8
|
+
export declare function writtenPaths(tool: string, args: Record<string, unknown>): string[];
|
|
9
|
+
/**
|
|
10
|
+
* Mejor esfuerzo sobre bash: redirecciones y comandos de escritura obvios.
|
|
11
|
+
* NO es una garantía (variables, scripts, subshells lo evaden): la red de seguridad
|
|
12
|
+
* fiable es `git diff` al terminar el turno (ver gitViolations).
|
|
13
|
+
*/
|
|
14
|
+
export declare function bashWrites(command: string): string[];
|
|
15
|
+
/** Archivos modificados según git, fuera del alcance de la fase. */
|
|
16
|
+
export declare function gitViolations(cfg: ResolvedConfig, changed: string[]): string[];
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { matchAny } from "./glob.js";
|
|
4
|
+
/** realpath del ancestro existente más profundo (resuelve symlinks aunque el archivo aún no exista). */
|
|
5
|
+
function realish(abs) {
|
|
6
|
+
let cur = abs;
|
|
7
|
+
const tail = [];
|
|
8
|
+
for (;;) {
|
|
9
|
+
try {
|
|
10
|
+
return path.join(fs.realpathSync(cur), ...tail);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
const parent = path.dirname(cur);
|
|
14
|
+
if (parent === cur)
|
|
15
|
+
return abs;
|
|
16
|
+
tail.unshift(path.basename(cur));
|
|
17
|
+
cur = parent;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Normaliza a ruta relativa al proyecto con "/". Devuelve null si queda fuera de la raíz. */
|
|
22
|
+
export function toRel(root, p) {
|
|
23
|
+
const realRoot = realish(root);
|
|
24
|
+
const abs = realish(path.resolve(root, p));
|
|
25
|
+
const rel = path.relative(realRoot, abs);
|
|
26
|
+
if (rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel))
|
|
27
|
+
return null;
|
|
28
|
+
return rel.split(path.sep).join("/");
|
|
29
|
+
}
|
|
30
|
+
/** Valida UNA ruta que se va a escribir. */
|
|
31
|
+
export function checkPath(cfg, p) {
|
|
32
|
+
const rel = toRel(cfg.root, p);
|
|
33
|
+
if (rel === null)
|
|
34
|
+
return { blocked: true, reason: `"${p}" está fuera del proyecto` };
|
|
35
|
+
if (matchAny(rel, cfg.protectedGlobs))
|
|
36
|
+
return { blocked: true, reason: `"${rel}" es un archivo protegido del guardián` };
|
|
37
|
+
if (matchAny(rel, cfg.scope.denyGlobs))
|
|
38
|
+
return { blocked: true, reason: `"${rel}" está prohibido en esta fase (denyGlobs)` };
|
|
39
|
+
const allow = cfg.scope.allowOnlyGlobs;
|
|
40
|
+
if (allow.length && !matchAny(rel, allow)) {
|
|
41
|
+
return { blocked: true, reason: `"${rel}" no está en el alcance de esta fase (allowOnlyGlobs: ${allow.join(", ")})` };
|
|
42
|
+
}
|
|
43
|
+
return { blocked: false };
|
|
44
|
+
}
|
|
45
|
+
export function checkPaths(cfg, paths) {
|
|
46
|
+
for (const p of paths) {
|
|
47
|
+
const v = checkPath(cfg, p);
|
|
48
|
+
if (v.blocked)
|
|
49
|
+
return v;
|
|
50
|
+
}
|
|
51
|
+
return { blocked: false };
|
|
52
|
+
}
|
|
53
|
+
/** Rutas que toca una llamada de escritura. Para edit/write/patch es exacto. */
|
|
54
|
+
export function writtenPaths(tool, args) {
|
|
55
|
+
const out = [];
|
|
56
|
+
const f = args.filePath ?? args.file_path ?? args.path;
|
|
57
|
+
if (typeof f === "string")
|
|
58
|
+
out.push(f);
|
|
59
|
+
if (tool === "patch") {
|
|
60
|
+
const text = String(args.patchText ?? args.patch ?? args.diff ?? "");
|
|
61
|
+
// formato "*** Update/Add/Delete File: x" y diff unificado (--- a/x / +++ b/x)
|
|
62
|
+
for (const m of text.matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*(.+)$/gm))
|
|
63
|
+
out.push(m[1].trim());
|
|
64
|
+
for (const m of text.matchAll(/^\+\+\+ (?:b\/)?(\S+)/gm))
|
|
65
|
+
if (m[1] !== "/dev/null")
|
|
66
|
+
out.push(m[1]);
|
|
67
|
+
for (const m of text.matchAll(/^--- (?:a\/)?(\S+)/gm))
|
|
68
|
+
if (m[1] !== "/dev/null")
|
|
69
|
+
out.push(m[1]);
|
|
70
|
+
}
|
|
71
|
+
return [...new Set(out)];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Mejor esfuerzo sobre bash: redirecciones y comandos de escritura obvios.
|
|
75
|
+
* NO es una garantía (variables, scripts, subshells lo evaden): la red de seguridad
|
|
76
|
+
* fiable es `git diff` al terminar el turno (ver gitViolations).
|
|
77
|
+
*/
|
|
78
|
+
export function bashWrites(command) {
|
|
79
|
+
const out = [];
|
|
80
|
+
const clean = (s) => s.replace(/^["']|["']$/g, "");
|
|
81
|
+
for (const m of command.matchAll(/(?:^|[^>&0-9])>>?\s*(?!&)([^\s;|&<>()]+)/g))
|
|
82
|
+
out.push(clean(m[1]));
|
|
83
|
+
for (const m of command.matchAll(/\btee\s+(?:-[a-z]+\s+)*([^\s;|&<>]+)/g))
|
|
84
|
+
out.push(clean(m[1]));
|
|
85
|
+
for (const m of command.matchAll(/\bsed\s+(?:-[A-Za-z]*i[A-Za-z]*(?:\.\w+)?\s+)(?:-e\s+)?(?:'[^']*'|"[^"]*"|\S+)\s+([^\s;|&]+)/g))
|
|
86
|
+
out.push(clean(m[1]));
|
|
87
|
+
for (const m of command.matchAll(/\b(?:rm|touch|mkdir|rmdir|truncate)\s+((?:-\S+\s+)*)([^;|&<>]+)/g)) {
|
|
88
|
+
for (const t of m[2].trim().split(/\s+/))
|
|
89
|
+
if (!t.startsWith("-"))
|
|
90
|
+
out.push(clean(t));
|
|
91
|
+
}
|
|
92
|
+
for (const m of command.matchAll(/\b(?:mv|cp)\s+((?:-\S+\s+)*)([^;|&<>]+)/g)) {
|
|
93
|
+
const toks = m[2].trim().split(/\s+/).filter((t) => !t.startsWith("-"));
|
|
94
|
+
if (toks.length)
|
|
95
|
+
out.push(clean(toks[toks.length - 1])); // destino
|
|
96
|
+
if (/^\s*mv/.test(m[0]))
|
|
97
|
+
toks.slice(0, -1).forEach((t) => out.push(clean(t))); // origen desaparece
|
|
98
|
+
}
|
|
99
|
+
return [...new Set(out.filter((p) => p && !p.startsWith("/dev/") && !/^\$/.test(p)))];
|
|
100
|
+
}
|
|
101
|
+
/** Archivos modificados según git, fuera del alcance de la fase. */
|
|
102
|
+
export function gitViolations(cfg, changed) {
|
|
103
|
+
return changed.filter((p) => {
|
|
104
|
+
const rel = toRel(cfg.root, p);
|
|
105
|
+
if (rel === null)
|
|
106
|
+
return true;
|
|
107
|
+
if (matchAny(rel, cfg.protectedGlobs))
|
|
108
|
+
return false; // archivos del guardián: los edita el humano
|
|
109
|
+
if (matchAny(rel, cfg.scope.denyGlobs))
|
|
110
|
+
return true;
|
|
111
|
+
const allow = cfg.scope.allowOnlyGlobs;
|
|
112
|
+
return allow.length > 0 && !matchAny(rel, allow);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export type Mode = "block" | "warn";
|
|
2
|
+
export interface ScopeRules {
|
|
3
|
+
denyGlobs: string[];
|
|
4
|
+
allowOnlyGlobs: string[];
|
|
5
|
+
}
|
|
6
|
+
/** Contenido de .loopbreaker.json (todo opcional: sin archivo, solo corre el anti-bucles). */
|
|
7
|
+
export interface LoopbreakerConfig {
|
|
8
|
+
mode?: Mode;
|
|
9
|
+
/** Repeticiones consecutivas idénticas (sin progreso) que disparan el bloqueo. */
|
|
10
|
+
maxConsecutiveRepeats?: number;
|
|
11
|
+
/** Umbrales por herramienta, p. ej. { "read": 4, "bash": 3 }. */
|
|
12
|
+
toolThresholds?: Record<string, number>;
|
|
13
|
+
/** Periodo máximo de ciclo a detectar (2 = A-B-A-B, 3 = A-B-C-A-B-C). */
|
|
14
|
+
cycleMaxPeriod?: number;
|
|
15
|
+
/** Salidas idénticas seguidas (misma familia de comando) que indican estancamiento. */
|
|
16
|
+
stagnationRepeats?: number;
|
|
17
|
+
/** Tamaño de la ventana deslizante de historial por sesión. */
|
|
18
|
+
window?: number;
|
|
19
|
+
/** Bloqueos acumulados en una sesión tras los cuales el mensaje pasa a "parada dura". */
|
|
20
|
+
hardStopAfter?: number;
|
|
21
|
+
activeSpecFile?: string;
|
|
22
|
+
scope?: Partial<ScopeRules>;
|
|
23
|
+
/** Globs adicionales que el agente nunca puede escribir. */
|
|
24
|
+
protectedGlobs?: string[];
|
|
25
|
+
}
|
|
26
|
+
/** Frontmatter de .engram/specs/phase-XX.md */
|
|
27
|
+
export interface PhaseSpec {
|
|
28
|
+
id?: string;
|
|
29
|
+
goal?: string;
|
|
30
|
+
scope?: Partial<ScopeRules>;
|
|
31
|
+
exitCriteria?: string[];
|
|
32
|
+
}
|
|
33
|
+
export interface ResolvedConfig {
|
|
34
|
+
root: string;
|
|
35
|
+
mode: Mode;
|
|
36
|
+
maxConsecutiveRepeats: number;
|
|
37
|
+
toolThresholds: Record<string, number>;
|
|
38
|
+
cycleMaxPeriod: number;
|
|
39
|
+
stagnationRepeats: number;
|
|
40
|
+
window: number;
|
|
41
|
+
hardStopAfter: number;
|
|
42
|
+
scope: ScopeRules;
|
|
43
|
+
protectedGlobs: string[];
|
|
44
|
+
specFile?: string;
|
|
45
|
+
phase?: PhaseSpec;
|
|
46
|
+
/** Errores de configuración: el guardián sigue activo y los reporta. */
|
|
47
|
+
warnings: string[];
|
|
48
|
+
}
|
|
49
|
+
export interface CallEntry {
|
|
50
|
+
sig: string;
|
|
51
|
+
tool: string;
|
|
52
|
+
/** Época de escritura: sube cada vez que una herramienta de escritura termina bien. */
|
|
53
|
+
epoch: number;
|
|
54
|
+
/** Familia del comando: tool, y para bash el primer programa (p. ej. "bash:rtk"). */
|
|
55
|
+
family?: string;
|
|
56
|
+
resultHash?: string;
|
|
57
|
+
resultLen?: number;
|
|
58
|
+
/** Primeros caracteres de la salida, para citarla en el mensaje de bloqueo. */
|
|
59
|
+
snippet?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface SessionState {
|
|
62
|
+
epoch: number;
|
|
63
|
+
/** Bloqueos totales (informativo). */
|
|
64
|
+
blocks: number;
|
|
65
|
+
/** Bloqueos por bucle: solo estos escalan a parada dura. */
|
|
66
|
+
loopBlocks?: number;
|
|
67
|
+
entries: CallEntry[];
|
|
68
|
+
}
|
|
69
|
+
export interface Verdict {
|
|
70
|
+
blocked: boolean;
|
|
71
|
+
reason?: string;
|
|
72
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { LoopbreakerConfig, Mode } from "./types.js";
|
|
2
|
+
export interface InstallChoices {
|
|
3
|
+
target: "global" | "project";
|
|
4
|
+
pin: boolean;
|
|
5
|
+
config?: LoopbreakerConfig;
|
|
6
|
+
gitignore: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface WizardIo {
|
|
9
|
+
question(prompt: string): Promise<string>;
|
|
10
|
+
}
|
|
11
|
+
export declare function parsePositive(text: string, def: number, min?: number): number;
|
|
12
|
+
export declare function parseGlobs(text: string): string[];
|
|
13
|
+
/** Respuestas ya normalizadas -> archivo .loopbreaker.json. Separado para poder testearlo. */
|
|
14
|
+
export declare function buildConfig(a: {
|
|
15
|
+
mode: Mode;
|
|
16
|
+
maxConsecutiveRepeats: number;
|
|
17
|
+
stagnationRepeats: number;
|
|
18
|
+
hardStopAfter: number;
|
|
19
|
+
allowOnlyGlobs?: string[];
|
|
20
|
+
denyGlobs?: string[];
|
|
21
|
+
}): LoopbreakerConfig;
|
|
22
|
+
/** Wizard de instalación. Sin TTY el CLI no lo llama y usa los mismos defaults. */
|
|
23
|
+
export declare function runWizard(projectRoot: string, io: WizardIo, fixedTarget?: "global" | "project"): Promise<InstallChoices | undefined>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { DEFAULT_INIT } from "./installer.js";
|
|
2
|
+
export function parsePositive(text, def, min = 2) {
|
|
3
|
+
const n = Number(text.trim());
|
|
4
|
+
return Number.isInteger(n) && n >= min ? n : def;
|
|
5
|
+
}
|
|
6
|
+
export function parseGlobs(text) {
|
|
7
|
+
return text
|
|
8
|
+
.split(",")
|
|
9
|
+
.map((s) => s.trim())
|
|
10
|
+
.filter(Boolean);
|
|
11
|
+
}
|
|
12
|
+
/** Respuestas ya normalizadas -> archivo .loopbreaker.json. Separado para poder testearlo. */
|
|
13
|
+
export function buildConfig(a) {
|
|
14
|
+
const cfg = {
|
|
15
|
+
mode: a.mode,
|
|
16
|
+
maxConsecutiveRepeats: a.maxConsecutiveRepeats,
|
|
17
|
+
stagnationRepeats: a.stagnationRepeats,
|
|
18
|
+
hardStopAfter: a.hardStopAfter,
|
|
19
|
+
};
|
|
20
|
+
const allowOnlyGlobs = a.allowOnlyGlobs ?? [];
|
|
21
|
+
const denyGlobs = a.denyGlobs ?? [];
|
|
22
|
+
if (allowOnlyGlobs.length || denyGlobs.length)
|
|
23
|
+
cfg.scope = { allowOnlyGlobs, denyGlobs };
|
|
24
|
+
return cfg;
|
|
25
|
+
}
|
|
26
|
+
/** Wizard de instalación. Sin TTY el CLI no lo llama y usa los mismos defaults. */
|
|
27
|
+
export async function runWizard(projectRoot, io, fixedTarget) {
|
|
28
|
+
const text = async (q) => (await io.question(`${q}: `)).trim();
|
|
29
|
+
const ask = async (q, def) => (await text(`${q} [${def}]`)) || def;
|
|
30
|
+
const yes = async (q, def) => {
|
|
31
|
+
const a = (await text(`${q} (${def ? "S/n" : "s/N"})`)).toLowerCase();
|
|
32
|
+
if (!a)
|
|
33
|
+
return def;
|
|
34
|
+
return ["s", "si", "sí", "y", "yes"].includes(a);
|
|
35
|
+
};
|
|
36
|
+
const num = async (q, def, min = 2) => parsePositive(await text(`${q} [${def}]`), def, min);
|
|
37
|
+
const target = fixedTarget ?? ((await ask("¿Instalar global o solo en este proyecto? (global/proyecto)", "global")).toLowerCase().startsWith("p") ? "project" : "global");
|
|
38
|
+
const pin = await yes("¿Fijar la versión exacta del plugin?", true);
|
|
39
|
+
let config;
|
|
40
|
+
if (await yes("¿Crear .loopbreaker.json con ajustes del anti-bucles?", false)) {
|
|
41
|
+
const mode = (await ask("Modo (block/warn)", "block")).toLowerCase() === "warn" ? "warn" : "block";
|
|
42
|
+
const maxConsecutiveRepeats = await num("Repeticiones idénticas antes de bloquear", DEFAULT_INIT.maxConsecutiveRepeats ?? 3, 2);
|
|
43
|
+
const stagnationRepeats = await num("Salidas idénticas para estancamiento", DEFAULT_INIT.stagnationRepeats ?? 3, 2);
|
|
44
|
+
const hardStopAfter = await num("Bloqueos antes de parada dura", DEFAULT_INIT.hardStopAfter ?? 3, 1);
|
|
45
|
+
let allowOnlyGlobs = [];
|
|
46
|
+
let denyGlobs = [];
|
|
47
|
+
if (await yes("¿Configurar alcance por globs? (disuasorio, no sandbox)", false)) {
|
|
48
|
+
allowOnlyGlobs = parseGlobs(await text("allowOnlyGlobs separados por coma (vacío = sin límite)"));
|
|
49
|
+
denyGlobs = parseGlobs(await text("denyGlobs separados por coma (vacío = ninguno)"));
|
|
50
|
+
}
|
|
51
|
+
config = buildConfig({ mode, maxConsecutiveRepeats, stagnationRepeats, hardStopAfter, allowOnlyGlobs, denyGlobs });
|
|
52
|
+
}
|
|
53
|
+
const gitignore = await yes("¿Añadir .opencode/ al .gitignore de este proyecto?", true);
|
|
54
|
+
console.log(`\nResumen: ${target === "project" ? `proyecto (${projectRoot})` : "global"} | versión ${pin ? "fija" : "latest"} | .loopbreaker.json ${config ? "sí" : "no"} | .gitignore ${gitignore ? "sí" : "no"}`);
|
|
55
|
+
if (!(await yes("¿Aplicar estos cambios?", true)))
|
|
56
|
+
return undefined;
|
|
57
|
+
return { target, pin, config, gitignore };
|
|
58
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adayacas/loopbreaker",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
3
|
+
"author": "Adrián Ayala Castrillón <adayacas@gmail.com>",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "git+https://github.com/adayacas/loopbreaker.git"
|
|
7
|
+
},
|
|
8
|
+
"homepage": "https://github.com/adayacas/loopbreaker#readme",
|
|
9
|
+
"bugs": {
|
|
10
|
+
"url": "https://github.com/adayacas/loopbreaker/issues"
|
|
11
|
+
},
|
|
12
|
+
"version": "0.3.0",
|
|
13
|
+
"description": "Its an Opencode loopbreaker tool to stop ai models when the context overload, to save tokens and guard the healt processes",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "dist/src/index.js",
|
|
16
|
+
"types": "dist/src/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": "./dist/src/index.js"
|
|
19
|
+
},
|
|
20
|
+
"bin": {
|
|
21
|
+
"loopbreaker": "dist/src/cli.js"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist/src",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.json",
|
|
30
|
+
"test": "tsc -p tsconfig.json && node --test \"dist/test/*.test.js\"",
|
|
31
|
+
"prepublishOnly": "rm -rf dist && npm test && tsc -p tsconfig.build.json"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"typescript": "^5.6.0",
|
|
35
|
+
"@types/node": "^22.0.0"
|
|
36
|
+
},
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"opencode",
|
|
43
|
+
"opencode-plugin",
|
|
44
|
+
"agent",
|
|
45
|
+
"loop-detection",
|
|
46
|
+
"circuit-breaker",
|
|
47
|
+
"guardrails",
|
|
48
|
+
"scope"
|
|
49
|
+
],
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
}
|
|
6
53
|
}
|