@adayacas/loopbreaker 0.2.0 → 0.4.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.
@@ -1,7 +1,24 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { t } from "./messages.js";
4
6
  export const PLUGIN_NAME = "@adayacas/loopbreaker";
7
+ /** Versión del paquete que está ejecutando el instalador, para pinear el plugin. */
8
+ function packageVersion() {
9
+ try {
10
+ const here = path.dirname(fileURLToPath(import.meta.url));
11
+ const pkg = JSON.parse(fs.readFileSync(path.join(here, "../../package.json"), "utf8"));
12
+ return typeof pkg.version === "string" && pkg.version ? pkg.version : "latest";
13
+ }
14
+ catch {
15
+ return "latest";
16
+ }
17
+ }
18
+ export const PLUGIN_VERSION = packageVersion();
19
+ export const PINNED_PLUGIN = `${PLUGIN_NAME}@${PLUGIN_VERSION}`;
20
+ export const GITIGNORE_ENTRY = ".opencode/";
21
+ export const DEFAULT_INIT = { mode: "block", maxConsecutiveRepeats: 3, stagnationRepeats: 3 };
5
22
  /** Config global de OpenCode: $XDG_CONFIG_HOME/opencode o ~/.config/opencode. */
6
23
  export function globalConfigDir(env = process.env) {
7
24
  const base = env.XDG_CONFIG_HOME || path.join(env.HOME || env.USERPROFILE || os.homedir(), ".config");
@@ -50,7 +67,7 @@ function stripJsonc(text) {
50
67
  }
51
68
  return out.replace(/,(\s*[}\]])/g, "$1");
52
69
  }
53
- function read(file) {
70
+ export function readJsonFile(file) {
54
71
  if (!fs.existsSync(file))
55
72
  return { data: {}, hadComments: false };
56
73
  const raw = fs.readFileSync(file, "utf8");
@@ -66,58 +83,99 @@ function read(file) {
66
83
  }
67
84
  }
68
85
  }
69
- const isAeg = (p) => typeof p === "string" && (p === PLUGIN_NAME || p.startsWith(PLUGIN_NAME + "@"));
70
- function manual(file, why, line) {
71
- return { ok: false, changed: false, file, message: `${why}\nNo toqué tu archivo. Añade a mano en ${file}:\n ${line}` };
86
+ const isLoopbreaker = (p) => typeof p === "string" && (p === PLUGIN_NAME || p.startsWith(PLUGIN_NAME + "@"));
87
+ export function manual(file, why, line) {
88
+ return { ok: false, changed: false, file, message: t("inst.manual", { why, file, line }) };
72
89
  }
73
- /** Añade el plugin a opencode.json de forma idempotente, con copia de seguridad. */
74
- export function install(dir, spec = PLUGIN_NAME) {
90
+ /**
91
+ * Añade el plugin a opencode.json de forma idempotente, con copia de seguridad.
92
+ * Por defecto fija la versión exacta; una entrada sin versión se reemplaza.
93
+ */
94
+ export function install(dir, pin = true) {
95
+ const spec = pin ? PINNED_PLUGIN : PLUGIN_NAME;
75
96
  const file = configFile(dir);
76
- const r = read(file);
97
+ const r = readJsonFile(file);
77
98
  if ("error" in r)
78
- return manual(file, `No pude leer ${file} (${r.error}).`, `"plugin": ["${spec}"]`);
99
+ return manual(file, t("inst.cantRead", { file, err: r.error }), `"plugin": ["${spec}"]`);
79
100
  if (r.hadComments) {
80
101
  // Reescribir perdería los comentarios del usuario: mejor no tocar nada.
81
- return manual(file, `${path.basename(file)} tiene comentarios y reescribirlo los borraría.`, `"plugin": [..., "${spec}"]`);
102
+ return manual(file, t("inst.hasComments", { name: path.basename(file) }), `"plugin": [..., "${spec}"]`);
82
103
  }
83
104
  const cur = r.data.plugin;
84
105
  if (cur !== undefined && !Array.isArray(cur))
85
- return manual(file, `"plugin" en ${file} no es una lista.`, `"plugin": ["${spec}"]`);
86
- const list = Array.isArray(cur) ? cur : [];
87
- if (list.some(isAeg))
88
- return { ok: true, changed: false, file, message: `Ya estaba instalado en ${file}.` };
106
+ return manual(file, t("inst.notList", { file }), `"plugin": ["${spec}"]`);
107
+ const list = Array.isArray(cur) ? [...cur] : [];
108
+ const idx = list.findIndex(isLoopbreaker);
109
+ if (idx !== -1 && list[idx] === spec)
110
+ return { ok: true, changed: false, file, message: t("inst.already", { file }) };
89
111
  if (fs.existsSync(file))
90
- fs.copyFileSync(file, file + ".aeg.bak");
91
- const next = { ...(fs.existsSync(file) ? r.data : { $schema: "https://opencode.ai/config.json" }), plugin: [...list, spec] };
112
+ fs.copyFileSync(file, file + ".loopbreaker.bak");
113
+ if (idx === -1)
114
+ list.push(spec);
115
+ else
116
+ list[idx] = spec;
117
+ const next = { ...(fs.existsSync(file) ? r.data : { $schema: "https://opencode.ai/config.json" }), plugin: list };
92
118
  fs.mkdirSync(dir, { recursive: true });
93
119
  fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
94
- return { ok: true, changed: true, file, message: `Plugin añadido a ${file}${fs.existsSync(file + ".aeg.bak") ? ` (copia: ${path.basename(file)}.aeg.bak)` : ""}.` };
120
+ return {
121
+ ok: true,
122
+ changed: true,
123
+ file,
124
+ message: t(idx === -1 ? "inst.added" : "inst.updated", {
125
+ spec,
126
+ file,
127
+ backup: fs.existsSync(file + ".loopbreaker.bak") ? t("inst.backup", { name: `${path.basename(file)}.loopbreaker.bak` }) : "",
128
+ }),
129
+ };
95
130
  }
96
131
  export function uninstall(dir) {
97
132
  const file = configFile(dir);
98
133
  if (!fs.existsSync(file))
99
- return { ok: true, changed: false, file, message: "No hay configuración que modificar." };
100
- const r = read(file);
134
+ return { ok: true, changed: false, file, message: t("inst.noConfig") };
135
+ const r = readJsonFile(file);
101
136
  if ("error" in r || r.hadComments)
102
- return manual(file, `No puedo editar ${file} automáticamente.`, `quita "${PLUGIN_NAME}" de "plugin"`);
137
+ return manual(file, t("inst.cantEdit", { file }), t("inst.removeLine", { name: PLUGIN_NAME }));
103
138
  const cur = r.data.plugin;
104
- if (!Array.isArray(cur) || !cur.some(isAeg))
105
- return { ok: true, changed: false, file, message: "El plugin no estaba registrado." };
106
- fs.copyFileSync(file, file + ".aeg.bak");
107
- const rest = cur.filter((p) => !isAeg(p));
139
+ if (!Array.isArray(cur) || !cur.some(isLoopbreaker))
140
+ return { ok: true, changed: false, file, message: t("inst.notRegistered") };
141
+ fs.copyFileSync(file, file + ".loopbreaker.bak");
142
+ const rest = cur.filter((p) => !isLoopbreaker(p));
108
143
  const next = { ...r.data };
109
144
  if (rest.length)
110
145
  next.plugin = rest;
111
146
  else
112
147
  delete next.plugin;
113
148
  fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
114
- return { ok: true, changed: true, file, message: `Plugin quitado de ${file}.` };
149
+ return { ok: true, changed: true, file, message: t("inst.removed", { file }) };
115
150
  }
116
- /** Crea un .aeg.json mínimo en el proyecto (no sobrescribe). */
117
- export function init(projectDir) {
118
- const file = path.join(projectDir, ".aeg.json");
151
+ /** ¿El opencode.json de este directorio registra loopbreaker? */
152
+ export function isInstalled(dir) {
153
+ const r = readJsonFile(configFile(dir));
154
+ return !("error" in r) && Array.isArray(r.data.plugin) && r.data.plugin.some(isLoopbreaker);
155
+ }
156
+ /** Crea un .loopbreaker.json en el proyecto (no sobrescribe). */
157
+ export function init(projectDir, config = DEFAULT_INIT) {
158
+ const file = path.join(projectDir, ".loopbreaker.json");
119
159
  if (fs.existsSync(file))
120
- return { ok: true, changed: false, file, message: `${file} ya existe.` };
121
- fs.writeFileSync(file, JSON.stringify({ mode: "block", maxConsecutiveRepeats: 3, stagnationRepeats: 3 }, null, 2) + "\n");
122
- return { ok: true, changed: true, file, message: `Creado ${file}.` };
160
+ return { ok: true, changed: false, file, message: t("inst.exists", { file }) };
161
+ fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\n");
162
+ return { ok: true, changed: true, file, message: t("inst.created", { file }) };
163
+ }
164
+ /** Añade `.opencode/` al .gitignore del proyecto de forma idempotente. */
165
+ export function ensureGitignore(projectDir) {
166
+ const file = path.join(projectDir, ".gitignore");
167
+ try {
168
+ const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
169
+ const has = current
170
+ .split(/\r?\n/)
171
+ .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === GITIGNORE_ENTRY.replace(/\/$/, ""));
172
+ if (has)
173
+ return { ok: true, changed: false, file, message: t("inst.giHas", { entry: GITIGNORE_ENTRY, file }) };
174
+ const prefix = current && !current.endsWith("\n") ? current + "\n" : current;
175
+ fs.writeFileSync(file, prefix + GITIGNORE_ENTRY + "\n");
176
+ return { ok: true, changed: true, file, message: t("inst.giAdded", { entry: GITIGNORE_ENTRY, file }) };
177
+ }
178
+ catch (e) {
179
+ return { ok: false, changed: false, file, message: t("inst.giFail", { file, err: e.message, entry: GITIGNORE_ENTRY }) };
180
+ }
123
181
  }
@@ -0,0 +1,4 @@
1
+ export { Guard } from "./guard.js";
2
+ export { loadConfig, phaseCard } from "./config-loader.js";
3
+ export { parseFrontmatter } from "./frontmatter.js";
4
+ export type { CallEntry, LoopbreakerConfig, Mode, PhaseSpec, ResolvedConfig, ScopeRules, SessionState, Verdict, } from "./types.js";
@@ -0,0 +1,7 @@
1
+ // API programática del paquete, separada de index.ts a propósito:
2
+ // OpenCode invoca como plugin CADA export de función/clase del módulo de entrada,
3
+ // así que index.ts no puede exponer nada más. Los consumidores de librería
4
+ // importan desde acá: `import { Guard, loadConfig } from "@adayacas/loopbreaker/lib"`.
5
+ export { Guard } from "./guard.js";
6
+ export { loadConfig, phaseCard } from "./config-loader.js";
7
+ export { parseFrontmatter } from "./frontmatter.js";
@@ -17,8 +17,8 @@ export declare const hashResult: (out: unknown) => string;
17
17
  * - Ciclo: un patrón de periodo 2..K repetido N veces (A-B-A-B-A-B).
18
18
  */
19
19
  export declare function check(state: SessionState, cfg: ResolvedConfig, tool: string, sig: string, fam?: string): Verdict;
20
- export declare function record(state: SessionState, cfg: ResolvedConfig, tool: string, sig: string, fam?: string): void;
20
+ export declare function record(state: SessionState, cfg: ResolvedConfig, tool: string, sig: string, fam?: string, callID?: string): void;
21
21
  /** Después de ejecutar: guarda el hash del resultado y sube la época si hubo escritura. */
22
- export declare function recordResult(state: SessionState, tool: string, sig: string, text: string, failed?: boolean): void;
22
+ export declare function recordResult(state: SessionState, tool: string, sig: string, text: string, failed?: boolean, callID?: string): void;
23
23
  /** Mensaje de bloqueo accionable; escala a "parada dura" tras varios bloqueos. */
24
24
  export declare function blockMessage(cfg: ResolvedConfig, state: SessionState, reason: string): string;
@@ -1,3 +1,4 @@
1
+ import { t } from "./messages.js";
1
2
  import { createHash } from "node:crypto";
2
3
  /** Herramientas que cambian el estado del proyecto: una escritura exitosa "da progreso". */
3
4
  export const WRITE_TOOLS = new Set(["edit", "write", "patch", "multiedit"]);
@@ -70,7 +71,7 @@ export function check(state, cfg, tool, sig, fam = tool) {
70
71
  if (streak + 1 >= n) {
71
72
  return {
72
73
  blocked: true,
73
- reason: `la llamada "${tool}" se repitió ${streak + 1} veces seguidas con los mismos argumentos y sin cambios en el proyecto ni en su salida`,
74
+ reason: t("loop.repeat", { tool, n: streak + 1 }, cfg.locale),
74
75
  };
75
76
  }
76
77
  // 2) estancamiento: la misma familia devuelve la misma salida (aunque cambien los argumentos)
@@ -86,7 +87,9 @@ export function check(state, cfg, tool, sig, fam = tool) {
86
87
  if (same >= cfg.stagnationRepeats) {
87
88
  return {
88
89
  blocked: true,
89
- reason: `las últimas ${same} llamadas de "${fam}" devolvieron EXACTAMENTE la misma salida («${(last.snippet ?? "").replace(/\s+/g, " ")}») aunque cambiaste los argumentos: el problema no está en el comando, algo se quedó pegado en la herramienta o el entorno`,
90
+ reason: last.snippet
91
+ ? t("loop.stagnation", { n: same, family: fam, snippet: last.snippet.replace(/\s+/g, " ") }, cfg.locale)
92
+ : t("loop.stagnationNoQuote", { n: same, family: fam }, cfg.locale),
90
93
  };
91
94
  }
92
95
  }
@@ -101,21 +104,44 @@ export function check(state, cfg, tool, sig, fam = tool) {
101
104
  if (new Set(pattern).size < 2)
102
105
  continue; // un patrón uniforme ya lo cubre la regla 1
103
106
  if (tail.every((s, i) => s === pattern[i % p])) {
104
- return { blocked: true, reason: `se detectó un ciclo de ${p} llamadas repetido ${n} veces sin progreso` };
107
+ // Salidas que cambian entre repeticiones del mismo elemento = progreso:
108
+ // el agente avanza aunque alterne, no es un bucle pegado.
109
+ let progress = false;
110
+ const firstHash = new Map();
111
+ for (const e of run.slice(-(need - 1))) {
112
+ if (!e.resultHash)
113
+ continue;
114
+ const first = firstHash.get(e.sig);
115
+ if (first === undefined)
116
+ firstHash.set(e.sig, e.resultHash);
117
+ else if (first !== e.resultHash) {
118
+ progress = true;
119
+ break;
120
+ }
121
+ }
122
+ if (!progress) {
123
+ return { blocked: true, reason: t("loop.cycle", { p, n }, cfg.locale) };
124
+ }
105
125
  }
106
126
  }
107
127
  return { blocked: false };
108
128
  }
109
- export function record(state, cfg, tool, sig, fam = tool) {
110
- state.entries.push({ sig, tool, family: fam, epoch: state.epoch });
129
+ export function record(state, cfg, tool, sig, fam = tool, callID) {
130
+ state.entries.push({ sig, tool, family: fam, epoch: state.epoch, ...(callID ? { callID } : {}) });
111
131
  if (state.entries.length > cfg.window)
112
132
  state.entries.splice(0, state.entries.length - cfg.window);
113
133
  }
114
134
  /** Después de ejecutar: guarda el hash del resultado y sube la época si hubo escritura. */
115
- export function recordResult(state, tool, sig, text, failed = false) {
135
+ export function recordResult(state, tool, sig, text, failed = false, callID) {
136
+ // Con id de llamada: si ese id ya tiene resultado, es una invocación duplicada (el mismo hook registrado dos veces).
137
+ if (callID) {
138
+ const dup = state.entries.find((e) => e.callID === callID);
139
+ if (dup?.resultHash !== undefined)
140
+ return;
141
+ }
116
142
  for (let i = state.entries.length - 1; i >= 0; i--) {
117
143
  const e = state.entries[i];
118
- if (e.sig === sig && e.resultHash === undefined) {
144
+ if (callID ? e.callID === callID : e.sig === sig && e.resultHash === undefined) {
119
145
  e.resultHash = hashResult(text);
120
146
  e.resultLen = text.length;
121
147
  e.snippet = text.slice(0, 120);
@@ -128,9 +154,8 @@ export function recordResult(state, tool, sig, text, failed = false) {
128
154
  /** Mensaje de bloqueo accionable; escala a "parada dura" tras varios bloqueos. */
129
155
  export function blockMessage(cfg, state, reason) {
130
156
  const hard = (state.loopBlocks ?? 0) >= cfg.hardStopAfter;
131
- const head = hard ? "🛑 [AEG PARADA DURA]" : "🛑 [AEG BLOQUEADO]";
132
- const todo = hard
133
- ? "Has insistido tras varios bloqueos. DETENTE ahora: explica al usuario qué intentas lograr, qué falla y pídele instrucciones. No sigas llamando herramientas."
134
- : "No repitas esta acción ni variantes de ella. Lee el error o la salida anterior, cambia de enfoque (otro comando, otro archivo, otra hipótesis) o pide ayuda al usuario.";
157
+ const L = cfg.locale;
158
+ const head = t(hard ? "loop.headHard" : "loop.headBlocked", {}, L);
159
+ const todo = t(hard ? "loop.todoHard" : "loop.todoBlocked", {}, L);
135
160
  return `${head} ${reason}. ${todo}`;
136
161
  }