@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.
package/dist/src/guard.js CHANGED
@@ -3,61 +3,303 @@ import * as path from "node:path";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { LOG_FILE, STATE_FILE, loadConfig } from "./config-loader.js";
5
5
  import { blockMessage, check, family, newSession, record, recordResult, resultText, signature, WRITE_TOOLS } from "./loop-detector.js";
6
+ import { t } from "./messages.js";
6
7
  import { bashWrites, checkPaths, gitViolations, writtenPaths } from "./scope-validator.js";
7
- /** Núcleo del guardián: independiente de OpenCode para poder probarlo en aislamiento. */
8
+ /** Sesiones que se conservan en disco: las más recientes. Evita que el estado crezca sin límite. */
9
+ const MAX_SESSIONS = 50;
10
+ /** Un bloqueo de archivo más viejo que esto se considera de un proceso muerto y se retira. */
11
+ const LOCK_STALE_MS = 5000;
12
+ /** Tiempo máximo esperando el bloqueo; pasado esto se sigue sin él (nunca se frena al agente por esto). */
13
+ const LOCK_WAIT_MS = 1500;
14
+ /** Un repo no confiable puede poner symlinks en .opencode: nunca escribimos a través de ellos. */
15
+ function isSymlink(f) {
16
+ try {
17
+ return fs.lstatSync(f).isSymbolicLink();
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ function sleep(ms) {
24
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
25
+ }
26
+ /** Núcleo del guardián: independiente de la herramienta que lo llame (plugin de OpenCode o hooks por CLI). */
8
27
  export class Guard {
9
28
  root;
10
29
  cfg;
11
30
  state = { sessions: {} };
31
+ /** Sesiones que ESTE proceso ha tocado: al guardar solo se sobrescriben estas, no las de otros procesos. */
32
+ touched = new Set();
33
+ /** Sesiones que este proceso ya guardó con éxito: si luego desaparecen del disco, se reseteó desde fuera. */
34
+ savedOk = new Set();
35
+ clearAll = false;
36
+ lockDepth = 0;
37
+ /** Errores internos ya registrados (evita llenar el log con el mismo fallo repetido). */
38
+ reported = new Set();
39
+ lastError;
40
+ errorCount = 0;
12
41
  constructor(root) {
13
42
  this.root = root;
14
43
  this.cfg = loadConfig(root);
15
44
  this.load();
45
+ this.harden();
46
+ }
47
+ get L() {
48
+ return this.cfg.locale;
49
+ }
50
+ /**
51
+ * Un fallo interno nunca rompe la sesión del agente, pero tampoco se esconde:
52
+ * queda en el log (una vez por tipo) y en `status`.
53
+ */
54
+ fail(where, e) {
55
+ // Los errores de JSON.parse citan un trozo del contenido: no se reenvían al log.
56
+ const detail = e instanceof SyntaxError ? t("err.json", {}, this.L) : (e?.message ?? String(e));
57
+ const msg = `${t(where, {}, this.L)}: ${detail}`.replace(/\s+/g, " ").slice(0, 300);
58
+ this.lastError = msg;
59
+ this.errorCount++;
60
+ // Se deduplica por tipo de fallo, no por texto: el mensaje incluye rutas con nombres de temporales aleatorios.
61
+ const kind = `${where}|${e?.code ?? e?.name ?? "error"}`;
62
+ if (this.reported.has(kind))
63
+ return;
64
+ this.reported.add(kind);
65
+ this.log({ event: "internal-error", where, message: msg });
66
+ }
67
+ /** Endurece archivos existentes de versiones anteriores (0644 -> 0600). */
68
+ harden() {
69
+ for (const f of [STATE_FILE, LOG_FILE]) {
70
+ const full = path.join(this.root, f);
71
+ if (isSymlink(full))
72
+ continue;
73
+ try {
74
+ fs.chmodSync(full, 0o600);
75
+ }
76
+ catch (e) {
77
+ // ENOENT es lo normal (el archivo aún no existe); cualquier otro fallo sí se reporta.
78
+ if (e.code !== "ENOENT")
79
+ this.fail("err.harden", e);
80
+ }
81
+ }
16
82
  }
17
83
  /** La configuración se relee en cada llamada: cambiar de fase surte efecto sin reiniciar. */
18
84
  reload() {
19
85
  this.cfg = loadConfig(this.root);
20
86
  }
21
- load() {
87
+ /**
88
+ * Exclusión mutua entre procesos con un archivo creado con O_EXCL ("wx").
89
+ * Cada hook de una herramienta es un proceso nuevo y puede haber llamadas en paralelo:
90
+ * sin esto, dos procesos leen el mismo estado y el último en escribir borra el cambio del otro.
91
+ * Si no se consigue el bloqueo a tiempo, se sigue sin él: el guardián nunca frena al agente por esto.
92
+ */
93
+ withLock(fn) {
94
+ if (this.lockDepth > 0)
95
+ return fn();
96
+ const lockFile = path.join(this.root, STATE_FILE) + ".lock";
97
+ let fd;
22
98
  try {
23
- const raw = JSON.parse(fs.readFileSync(path.join(this.root, STATE_FILE), "utf8"));
24
- if (raw && typeof raw === "object" && raw.sessions)
25
- this.state = raw;
99
+ fs.mkdirSync(path.dirname(lockFile), { recursive: true, mode: 0o700 });
100
+ const deadline = Date.now() + LOCK_WAIT_MS;
101
+ for (;;) {
102
+ try {
103
+ fd = fs.openSync(lockFile, "wx", 0o600);
104
+ break;
105
+ }
106
+ catch (e) {
107
+ if (e.code !== "EEXIST")
108
+ throw e;
109
+ try {
110
+ if (Date.now() - fs.statSync(lockFile).mtimeMs > LOCK_STALE_MS) {
111
+ fs.rmSync(lockFile, { force: true });
112
+ continue;
113
+ }
114
+ }
115
+ catch {
116
+ continue; // el bloqueo desapareció entre medias: reintentar ya
117
+ }
118
+ if (Date.now() > deadline)
119
+ throw new Error("timeout");
120
+ sleep(3 + Math.floor(Math.random() * 12));
121
+ }
122
+ }
26
123
  }
27
- catch {
28
- /* sin estado previo o corrupto: empezamos limpio */
124
+ catch (e) {
125
+ fd = undefined;
126
+ this.fail("err.lock", e);
127
+ }
128
+ this.lockDepth++;
129
+ try {
130
+ return fn();
131
+ }
132
+ finally {
133
+ this.lockDepth--;
134
+ if (fd !== undefined) {
135
+ try {
136
+ fs.closeSync(fd);
137
+ }
138
+ catch {
139
+ /* ya cerrado */
140
+ }
141
+ try {
142
+ fs.rmSync(lockFile, { force: true });
143
+ }
144
+ catch {
145
+ /* ya retirado */
146
+ }
147
+ }
148
+ }
149
+ }
150
+ /** Lee el estado del disco. Sin archivo = undefined sin error; archivo ilegible = undefined y se reporta. */
151
+ readDisk() {
152
+ const f = path.join(this.root, STATE_FILE);
153
+ if (isSymlink(f))
154
+ return undefined;
155
+ try {
156
+ const raw = JSON.parse(fs.readFileSync(f, "utf8"));
157
+ return raw && typeof raw === "object" && raw.sessions && typeof raw.sessions === "object" ? raw : undefined;
158
+ }
159
+ catch (e) {
160
+ if (e.code !== "ENOENT")
161
+ this.fail("err.read", e);
162
+ return undefined;
163
+ }
164
+ }
165
+ load() {
166
+ const disk = this.readDisk();
167
+ if (!disk)
168
+ return; // sin estado previo o corrupto (ya reportado): empezamos limpio
169
+ this.state = disk;
170
+ // Migración: versiones anteriores guardaban los primeros 120 caracteres de cada salida.
171
+ let dirty = false;
172
+ for (const s of Object.values(this.state.sessions)) {
173
+ if (!s || !Array.isArray(s.entries))
174
+ continue;
175
+ for (const e of s.entries) {
176
+ if (e && Object.prototype.hasOwnProperty.call(e, "snippet")) {
177
+ delete e.snippet;
178
+ dirty = true;
179
+ }
180
+ }
181
+ }
182
+ if (dirty)
183
+ this.save();
184
+ }
185
+ /**
186
+ * Trae la sesión del disco, que es la verdad cuando hay varios procesos.
187
+ * El fragmento de salida solo vive en memoria (nunca se persiste), así que se conserva al recargar.
188
+ */
189
+ syncSession(id) {
190
+ const disk = this.readDisk();
191
+ if (!disk)
192
+ return;
193
+ const ds = disk.sessions[id];
194
+ if (!ds) {
195
+ // Desapareció del disco después de que este proceso la guardara: alguien la reseteó desde fuera.
196
+ if (this.savedOk.has(id)) {
197
+ delete this.state.sessions[id];
198
+ this.savedOk.delete(id);
199
+ }
200
+ return;
201
+ }
202
+ const keep = new Map();
203
+ for (const e of this.state.sessions[id]?.entries ?? [])
204
+ if (e.resultHash && e.snippet)
205
+ keep.set(e.resultHash, e.snippet);
206
+ for (const e of ds.entries ?? []) {
207
+ const sn = e.resultHash ? keep.get(e.resultHash) : undefined;
208
+ if (sn)
209
+ e.snippet = sn;
29
210
  }
211
+ this.state.sessions[id] = ds;
30
212
  }
213
+ /**
214
+ * Guarda el estado sin corromperlo ni pisar a otros procesos:
215
+ * - mezcla con lo que haya en disco y solo sobrescribe las sesiones que este proceso tocó;
216
+ * - escribe a un archivo temporal (flag "wx": nunca sigue un symlink previo) y lo renombra,
217
+ * así un lector o un fallo a mitad de escritura nunca ve JSON a medias.
218
+ */
31
219
  save() {
220
+ const f = path.join(this.root, STATE_FILE);
221
+ if (isSymlink(f))
222
+ return;
223
+ const tmp = `${f}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
32
224
  try {
33
- const f = path.join(this.root, STATE_FILE);
34
- fs.mkdirSync(path.dirname(f), { recursive: true });
35
- fs.writeFileSync(f, JSON.stringify(this.state));
225
+ const disk = this.clearAll ? undefined : this.readDisk();
226
+ const sessions = { ...(disk?.sessions ?? {}) };
227
+ for (const id of this.touched) {
228
+ const s = this.state.sessions[id];
229
+ if (s)
230
+ sessions[id] = s;
231
+ else
232
+ delete sessions[id];
233
+ }
234
+ // Poda: se conservan las sesiones más recientes (y siempre las que este proceso está usando).
235
+ const ids = Object.keys(sessions);
236
+ if (ids.length > MAX_SESSIONS) {
237
+ const droppable = ids.filter((id) => !this.touched.has(id)).sort((a, b) => (sessions[a]?.updated ?? 0) - (sessions[b]?.updated ?? 0));
238
+ for (const id of droppable.slice(0, ids.length - MAX_SESSIONS))
239
+ delete sessions[id];
240
+ }
241
+ this.state.sessions = sessions;
242
+ fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
243
+ // El snippet se usa solo en memoria para citar la salida en el mensaje de bloqueo.
244
+ // Nunca se persiste: puede contener tokens, variables de entorno o credenciales.
245
+ const data = JSON.stringify(this.state, (k, v) => (k === "snippet" ? undefined : v));
246
+ fs.writeFileSync(tmp, data, { mode: 0o600, flag: "wx" });
247
+ fs.renameSync(tmp, f);
248
+ this.clearAll = false;
249
+ for (const id of this.touched)
250
+ if (this.state.sessions[id])
251
+ this.savedOk.add(id);
36
252
  }
37
- catch {
38
- /* el guardián nunca debe romper la sesión por no poder persistir */
253
+ catch (e) {
254
+ try {
255
+ fs.rmSync(tmp, { force: true });
256
+ }
257
+ catch {
258
+ /* nada que limpiar */
259
+ }
260
+ this.fail("err.save", e);
39
261
  }
40
262
  }
41
263
  log(event) {
42
264
  try {
43
265
  const f = path.join(this.root, LOG_FILE);
44
- fs.mkdirSync(path.dirname(f), { recursive: true });
45
- fs.appendFileSync(f, JSON.stringify({ t: new Date().toISOString(), ...event }) + "\n");
266
+ if (isSymlink(f))
267
+ return;
268
+ fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
269
+ // El motivo de estancamiento cita la salida: se redacta antes de tocar el disco.
270
+ const safe = Object.fromEntries(Object.entries(event).map(([k, v]) => [
271
+ k,
272
+ typeof v === "string" ? v.replace(/«[^»]*»/g, "«…»").slice(0, 500) : v,
273
+ ]));
274
+ fs.appendFileSync(f, JSON.stringify({ t: new Date().toISOString(), ...safe }) + "\n", { mode: 0o600 });
275
+ fs.chmodSync(f, 0o600);
46
276
  }
47
- catch {
48
- /* idem */
277
+ catch (e) {
278
+ // Si ni el log funciona no hay dónde registrarlo: queda solo en `status` (y no se reintenta, para no entrar en bucle).
279
+ this.lastError = `${t("err.writeLog", {}, this.L)}: ${e?.message ?? String(e)}`.replace(/\s+/g, " ").slice(0, 300);
280
+ this.errorCount++;
49
281
  }
50
282
  }
51
283
  session(id) {
52
- return (this.state.sessions[id] ??= newSession());
284
+ this.touched.add(id);
285
+ const s = (this.state.sessions[id] ??= newSession());
286
+ s.updated = Date.now();
287
+ return s;
53
288
  }
54
289
  /**
55
290
  * Antes de ejecutar una herramienta. Devuelve el mensaje de bloqueo o undefined si puede seguir.
56
- * En modo "warn" solo registra en el log.
291
+ * En modo "warn" solo registra en el log. `callID` (si la herramienta lo da) evita contar dos veces
292
+ * una misma llamada cuando el hook está registrado más de una vez.
57
293
  */
58
- before(sessionID, tool, args = {}) {
294
+ before(sessionID, tool, args = {}, callID) {
295
+ return this.withLock(() => this.beforeLocked(sessionID, tool, args, callID));
296
+ }
297
+ beforeLocked(sessionID, tool, args, callID) {
59
298
  this.reload();
299
+ this.syncSession(sessionID);
60
300
  const s = this.session(sessionID);
301
+ if (callID && s.entries.some((e) => e.callID === callID))
302
+ return undefined; // invocación duplicada
61
303
  const sig = signature(tool, args, this.root);
62
304
  const fam = family(tool, args);
63
305
  // 1) alcance (solo escrituras)
@@ -89,28 +331,35 @@ export class Guard {
89
331
  // salvo los bloqueos por bucle, que sí deben seguir sumando para escalar.
90
332
  if (kind === "loop") {
91
333
  s.loopBlocks = (s.loopBlocks ?? 0) + 1;
92
- record(s, this.cfg, tool, sig, fam);
334
+ record(s, this.cfg, tool, sig, fam, callID);
93
335
  }
94
336
  this.save();
95
- return kind === "scope"
96
- ? `🛑 [AEG BLOQUEADO] ${reason}. Trabaja solo dentro del alcance de la fase activa o pide al usuario que cambie de fase.`
97
- : blockMessage(this.cfg, s, reason);
337
+ return kind === "scope" ? t("scope.message", { reason }, this.L) : blockMessage(this.cfg, s, reason);
98
338
  }
99
339
  }
100
- record(s, this.cfg, tool, sig, fam);
340
+ record(s, this.cfg, tool, sig, fam, callID);
101
341
  this.save();
102
342
  return undefined;
103
343
  }
104
- after(sessionID, tool, args, output, failed = false) {
105
- const s = this.session(sessionID);
106
- recordResult(s, tool, signature(tool, args, this.root), resultText(output), failed);
107
- this.save();
344
+ after(sessionID, tool, args, output, failed = false, callID) {
345
+ this.withLock(() => {
346
+ this.syncSession(sessionID);
347
+ const s = this.session(sessionID);
348
+ recordResult(s, tool, signature(tool, args, this.root), resultText(output), failed, callID);
349
+ this.save();
350
+ });
108
351
  }
109
352
  /** Red de seguridad fiable: archivos cambiados según git que violan el alcance. */
110
353
  gitCheck() {
111
354
  this.reload();
112
355
  try {
113
- const out = execFileSync("git", ["status", "--porcelain", "-uall"], { cwd: this.root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
356
+ // Un git colgado (index.lock viejo, FS de red) no debe congelar al agente.
357
+ const out = execFileSync("git", ["status", "--porcelain", "-uall"], {
358
+ cwd: this.root,
359
+ encoding: "utf8",
360
+ stdio: ["ignore", "pipe", "ignore"],
361
+ timeout: 5000,
362
+ });
114
363
  const changed = out
115
364
  .split("\n")
116
365
  .filter(Boolean)
@@ -122,32 +371,47 @@ export class Guard {
122
371
  return bad;
123
372
  }
124
373
  catch {
374
+ // Sin git instalado o fuera de un repositorio: no hay red de seguridad que aplicar, y no es un error del plugin.
125
375
  return [];
126
376
  }
127
377
  }
128
378
  reset(sessionID) {
129
- if (sessionID)
130
- delete this.state.sessions[sessionID];
131
- else
132
- this.state = { sessions: {} };
133
- this.save();
379
+ this.withLock(() => {
380
+ if (sessionID) {
381
+ delete this.state.sessions[sessionID];
382
+ this.touched.add(sessionID); // sin sesión en memoria, save() la borra también del disco
383
+ this.savedOk.delete(sessionID);
384
+ }
385
+ else {
386
+ this.state = { sessions: {} };
387
+ this.touched.clear();
388
+ this.savedOk.clear();
389
+ this.clearAll = true; // limpiar todo, incluidas las sesiones de otros procesos
390
+ }
391
+ this.save();
392
+ });
134
393
  }
135
394
  status(sessionID) {
136
395
  const c = this.cfg;
396
+ const L = this.L;
137
397
  const lines = [
138
- `modo: ${c.mode} | repeticiones: ${c.maxConsecutiveRepeats} | ciclos hasta periodo ${c.cycleMaxPeriod}`,
139
- `fase: ${c.specFile ?? "(ninguna)"}`,
140
- `allowOnly: ${c.scope.allowOnlyGlobs.join(", ") || "-"}`,
141
- `deny: ${c.scope.denyGlobs.join(", ") || "-"}`,
398
+ t("status.line1", { mode: c.mode, repeats: c.maxConsecutiveRepeats, period: c.cycleMaxPeriod }, L),
399
+ t("status.phase", { v: c.specFile ?? t("status.none", {}, L) }, L),
400
+ t("status.allow", { v: c.scope.allowOnlyGlobs.join(", ") || "-" }, L),
401
+ t("status.deny", { v: c.scope.denyGlobs.join(", ") || "-" }, L),
142
402
  ];
143
- const ids = sessionID ? [sessionID] : Object.keys(this.state.sessions);
403
+ const disk = this.readDisk();
404
+ const sessions = { ...this.state.sessions, ...(disk?.sessions ?? {}) };
405
+ const ids = sessionID ? [sessionID] : Object.keys(sessions);
144
406
  for (const id of ids) {
145
- const s = this.state.sessions[id];
407
+ const s = sessions[id];
146
408
  if (s)
147
- lines.push(`sesión ${id}: ${s.entries.length} llamadas, ${s.blocks} bloqueos`);
409
+ lines.push(t("status.session", { id, calls: s.entries.length, blocks: s.blocks }, L));
148
410
  }
149
411
  for (const w of c.warnings)
150
412
  lines.push(`⚠ ${w}`);
413
+ if (this.lastError)
414
+ lines.push(t("status.lastError", { n: this.errorCount, msg: this.lastError }, L));
151
415
  return lines.join("\n");
152
416
  }
153
417
  }
@@ -0,0 +1,21 @@
1
+ import type { HookPhase, HookTarget } from "./adapters.js";
2
+ export interface HookResult {
3
+ /** 0 = la llamada sigue; 2 = bloqueada (Claude Code, Codex y Grok leen el motivo de stderr). */
4
+ exitCode: 0 | 2;
5
+ stderr?: string;
6
+ }
7
+ /**
8
+ * Raíz del proyecto para el estado y la configuración.
9
+ * No se usa `.claude`/`.codex`/`.grok` como marcador: también existen en el HOME del usuario.
10
+ */
11
+ export declare function findRoot(cwd: string, env?: NodeJS.ProcessEnv): string;
12
+ /**
13
+ * Punto de entrada de los hooks. Falla EN ABIERTO: cualquier error interno (JSON ilegible, disco lleno,
14
+ * un bug) deja pasar la llamada. Un guardián que rompe al agente es peor que ninguno.
15
+ */
16
+ export declare function runHook(_target: HookTarget, phase: HookPhase, stdinText: string, opts?: {
17
+ failed?: boolean;
18
+ env?: NodeJS.ProcessEnv;
19
+ cwd?: string;
20
+ }): HookResult;
21
+ export declare function readStdin(): Promise<string>;
@@ -0,0 +1,57 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { parseHookInput, responseText } from "./adapters.js";
4
+ import { Guard } from "./guard.js";
5
+ /**
6
+ * Raíz del proyecto para el estado y la configuración.
7
+ * No se usa `.claude`/`.codex`/`.grok` como marcador: también existen en el HOME del usuario.
8
+ */
9
+ export function findRoot(cwd, env = process.env) {
10
+ if (env.CLAUDE_PROJECT_DIR && fs.existsSync(env.CLAUDE_PROJECT_DIR))
11
+ return env.CLAUDE_PROJECT_DIR;
12
+ let dir = path.resolve(cwd);
13
+ for (;;) {
14
+ if (fs.existsSync(path.join(dir, ".loopbreaker.json")) || fs.existsSync(path.join(dir, ".git")))
15
+ return dir;
16
+ const parent = path.dirname(dir);
17
+ if (parent === dir)
18
+ return path.resolve(cwd);
19
+ dir = parent;
20
+ }
21
+ }
22
+ /**
23
+ * Punto de entrada de los hooks. Falla EN ABIERTO: cualquier error interno (JSON ilegible, disco lleno,
24
+ * un bug) deja pasar la llamada. Un guardián que rompe al agente es peor que ninguno.
25
+ */
26
+ export function runHook(_target, phase, stdinText, opts = {}) {
27
+ const env = opts.env ?? process.env;
28
+ try {
29
+ const ev = parseHookInput(JSON.parse(stdinText), phase);
30
+ if (!ev)
31
+ return { exitCode: 0 };
32
+ const root = ev.root ?? findRoot(ev.cwd ?? opts.cwd ?? process.cwd(), env);
33
+ const guard = new Guard(root);
34
+ if (phase === "before") {
35
+ const msg = guard.before(ev.sessionID, ev.tool, ev.args, ev.callID);
36
+ return msg ? { exitCode: 2, stderr: msg } : { exitCode: 0 };
37
+ }
38
+ guard.after(ev.sessionID, ev.tool, ev.args, responseText(ev.output), Boolean(opts.failed), ev.callID);
39
+ return { exitCode: 0 };
40
+ }
41
+ catch (e) {
42
+ if (env.LOOPBREAKER_DEBUG)
43
+ return { exitCode: 0, stderr: `loopbreaker: ${e.message}` };
44
+ return { exitCode: 0 };
45
+ }
46
+ }
47
+ export function readStdin() {
48
+ return new Promise((resolve) => {
49
+ if (process.stdin.isTTY)
50
+ return resolve("");
51
+ let data = "";
52
+ process.stdin.setEncoding("utf8");
53
+ process.stdin.on("data", (c) => (data += c));
54
+ process.stdin.on("end", () => resolve(data));
55
+ process.stdin.on("error", () => resolve(data));
56
+ });
57
+ }
@@ -3,7 +3,16 @@ type PluginCtx = {
3
3
  directory?: string;
4
4
  worktree?: string;
5
5
  };
6
- export declare const AegPlugin: (ctx?: PluginCtx) => Promise<{
6
+ export declare const LoopbreakerPlugin: (ctx?: PluginCtx) => Promise<{
7
+ tool: {
8
+ loopbreaker_status: {
9
+ description: string;
10
+ args: {};
11
+ execute(_a: unknown, c: {
12
+ sessionID?: string;
13
+ }): Promise<string>;
14
+ };
15
+ };
7
16
  "tool.execute.before": (input: {
8
17
  tool: string;
9
18
  sessionID: string;
@@ -32,6 +41,5 @@ export declare const AegPlugin: (ctx?: PluginCtx) => Promise<{
32
41
  type: string;
33
42
  };
34
43
  }) => Promise<void>;
35
- tool?: Record<string, unknown> | undefined;
36
44
  }>;
37
45
  export {};
package/dist/src/index.js CHANGED
@@ -1,35 +1,27 @@
1
1
  import { Guard } from "./guard.js";
2
2
  import { phaseCard } from "./config-loader.js";
3
- export const AegPlugin = async (ctx = {}) => {
3
+ export const LoopbreakerPlugin = async (ctx = {}) => {
4
4
  const root = ctx.worktree || ctx.directory || process.cwd();
5
5
  const guard = new Guard(root);
6
6
  // Las args se guardan entre before y after por callID (el hook after no las recibe).
7
7
  const pending = new Map();
8
- // aeg_status es de solo lectura. Si el paquete de plugin no está, el guardián funciona igual.
9
- let tools;
10
- try {
11
- const mod = await import("@opencode-ai/plugin");
12
- if (mod?.tool) {
13
- tools = {
14
- aeg_status: mod.tool({
15
- description: "Muestra el estado del guardián de ejecución (fase activa, alcance, bloqueos).",
16
- args: {},
17
- async execute(_a, c) {
18
- return guard.status(c?.sessionID);
19
- },
20
- }),
21
- };
22
- }
23
- }
24
- catch {
25
- /* paquete no disponible */
26
- }
8
+ // loopbreaker_status es de solo lectura. No depende de @opencode-ai/plugin:
9
+ // su helper tool() es una identidad (verificado en 1.19.5 y 0.15.31), así que
10
+ // devolver el objeto directamente evita el peer y el fallo silencioso.
27
11
  return {
28
- ...(tools ? { tool: tools } : {}),
12
+ tool: {
13
+ loopbreaker_status: {
14
+ description: "Muestra el estado del guardián de ejecución (fase activa, alcance, bloqueos).",
15
+ args: {},
16
+ async execute(_a, c) {
17
+ return guard.status(c?.sessionID);
18
+ },
19
+ },
20
+ },
29
21
  "tool.execute.before": async (input, output) => {
30
22
  const args = output?.args ?? {};
31
23
  pending.set(input.callID, args);
32
- const msg = guard.before(input.sessionID, input.tool, args);
24
+ const msg = guard.before(input.sessionID, input.tool, args, input.callID);
33
25
  if (msg) {
34
26
  pending.delete(input.callID);
35
27
  throw new Error(msg);
@@ -40,7 +32,7 @@ export const AegPlugin = async (ctx = {}) => {
40
32
  pending.delete(input.callID);
41
33
  if (!args)
42
34
  return;
43
- guard.after(input.sessionID, input.tool, args, output?.output, Boolean(output?.metadata?.error));
35
+ guard.after(input.sessionID, input.tool, args, output?.output, Boolean(output?.metadata?.error), input.callID);
44
36
  },
45
37
  // Inyecta la tarjeta de fase en cada prompt y durante la compactación (no después).
46
38
  "experimental.chat.system.transform": async (_i, output) => {
@@ -61,4 +53,4 @@ export const AegPlugin = async (ctx = {}) => {
61
53
  },
62
54
  };
63
55
  };
64
- // Solo se exporta AegPlugin: OpenCode invoca como plugin CADA export de función/clase del módulo.
56
+ // Solo se exporta LoopbreakerPlugin: OpenCode invoca como plugin CADA export de función/clase del módulo.
@@ -1,4 +1,9 @@
1
+ import type { LoopbreakerConfig } from "./types.js";
1
2
  export declare const PLUGIN_NAME = "@adayacas/loopbreaker";
3
+ export declare const PLUGIN_VERSION: string;
4
+ export declare const PINNED_PLUGIN: string;
5
+ export declare const GITIGNORE_ENTRY = ".opencode/";
6
+ export declare const DEFAULT_INIT: LoopbreakerConfig;
2
7
  export interface InstallResult {
3
8
  ok: boolean;
4
9
  changed: boolean;
@@ -9,8 +14,22 @@ export interface InstallResult {
9
14
  export declare function globalConfigDir(env?: NodeJS.ProcessEnv): string;
10
15
  /** Busca opencode.json (o .jsonc); si no existe ninguno, devuelve opencode.json como destino a crear. */
11
16
  export declare function configFile(dir: string): string;
12
- /** Añade el plugin a opencode.json de forma idempotente, con copia de seguridad. */
13
- export declare function install(dir: string, spec?: string): InstallResult;
17
+ export declare function readJsonFile(file: string): {
18
+ data: Record<string, unknown>;
19
+ hadComments: boolean;
20
+ } | {
21
+ error: string;
22
+ };
23
+ export declare function manual(file: string, why: string, line: string): InstallResult;
24
+ /**
25
+ * Añade el plugin a opencode.json de forma idempotente, con copia de seguridad.
26
+ * Por defecto fija la versión exacta; una entrada sin versión se reemplaza.
27
+ */
28
+ export declare function install(dir: string, pin?: boolean): InstallResult;
14
29
  export declare function uninstall(dir: string): InstallResult;
15
- /** Crea un .aeg.json mínimo en el proyecto (no sobrescribe). */
16
- export declare function init(projectDir: string): InstallResult;
30
+ /** ¿El opencode.json de este directorio registra loopbreaker? */
31
+ export declare function isInstalled(dir: string): boolean;
32
+ /** Crea un .loopbreaker.json en el proyecto (no sobrescribe). */
33
+ export declare function init(projectDir: string, config?: LoopbreakerConfig): InstallResult;
34
+ /** Añade `.opencode/` al .gitignore del proyecto de forma idempotente. */
35
+ export declare function ensureGitignore(projectDir: string): InstallResult;