@adayacas/loopbreaker 0.3.0 → 0.4.1

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,7 +3,14 @@ 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";
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;
7
14
  /** Un repo no confiable puede poner symlinks en .opencode: nunca escribimos a través de ellos. */
8
15
  function isSymlink(f) {
9
16
  try {
@@ -13,17 +20,50 @@ function isSymlink(f) {
13
20
  return false;
14
21
  }
15
22
  }
16
- /** Núcleo del guardián: independiente de OpenCode para poder probarlo en aislamiento. */
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). */
17
27
  export class Guard {
18
28
  root;
19
29
  cfg;
20
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;
21
41
  constructor(root) {
22
42
  this.root = root;
23
43
  this.cfg = loadConfig(root);
24
44
  this.load();
25
45
  this.harden();
26
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
+ }
27
67
  /** Endurece archivos existentes de versiones anteriores (0644 -> 0600). */
28
68
  harden() {
29
69
  for (const f of [STATE_FILE, LOG_FILE]) {
@@ -33,8 +73,10 @@ export class Guard {
33
73
  try {
34
74
  fs.chmodSync(full, 0o600);
35
75
  }
36
- catch {
37
- /* el archivo todavía no existe */
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);
38
80
  }
39
81
  }
40
82
  }
@@ -42,48 +84,180 @@ export class Guard {
42
84
  reload() {
43
85
  this.cfg = loadConfig(this.root);
44
86
  }
45
- 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;
46
98
  try {
47
- const f = path.join(this.root, STATE_FILE);
48
- if (isSymlink(f))
49
- return;
50
- const raw = JSON.parse(fs.readFileSync(f, "utf8"));
51
- if (raw && typeof raw === "object" && raw.sessions) {
52
- this.state = raw;
53
- // Migración: versiones anteriores guardaban los primeros 120 caracteres de cada salida.
54
- let dirty = false;
55
- for (const s of Object.values(this.state.sessions)) {
56
- if (!s || !Array.isArray(s.entries))
57
- continue;
58
- for (const e of s.entries) {
59
- if (e && Object.prototype.hasOwnProperty.call(e, "snippet")) {
60
- delete e.snippet;
61
- dirty = true;
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;
62
113
  }
63
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));
64
121
  }
65
- if (dirty)
66
- this.save();
67
122
  }
68
123
  }
69
- catch {
70
- /* 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
+ }
71
148
  }
72
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;
210
+ }
211
+ this.state.sessions[id] = ds;
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
+ */
73
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`;
74
224
  try {
75
- const f = path.join(this.root, STATE_FILE);
76
- if (isSymlink(f))
77
- return;
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;
78
242
  fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
79
243
  // El snippet se usa solo en memoria para citar la salida en el mensaje de bloqueo.
80
244
  // Nunca se persiste: puede contener tokens, variables de entorno o credenciales.
81
245
  const data = JSON.stringify(this.state, (k, v) => (k === "snippet" ? undefined : v));
82
- fs.writeFileSync(f, data, { mode: 0o600 });
83
- fs.chmodSync(f, 0o600);
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);
84
252
  }
85
- catch {
86
- /* 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);
87
261
  }
88
262
  }
89
263
  log(event) {
@@ -100,20 +274,32 @@ export class Guard {
100
274
  fs.appendFileSync(f, JSON.stringify({ t: new Date().toISOString(), ...safe }) + "\n", { mode: 0o600 });
101
275
  fs.chmodSync(f, 0o600);
102
276
  }
103
- catch {
104
- /* 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++;
105
281
  }
106
282
  }
107
283
  session(id) {
108
- 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;
109
288
  }
110
289
  /**
111
290
  * Antes de ejecutar una herramienta. Devuelve el mensaje de bloqueo o undefined si puede seguir.
112
- * 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.
113
293
  */
114
- 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) {
115
298
  this.reload();
299
+ this.syncSession(sessionID);
116
300
  const s = this.session(sessionID);
301
+ if (callID && s.entries.some((e) => e.callID === callID))
302
+ return undefined; // invocación duplicada
117
303
  const sig = signature(tool, args, this.root);
118
304
  const fam = family(tool, args);
119
305
  // 1) alcance (solo escrituras)
@@ -145,28 +331,35 @@ export class Guard {
145
331
  // salvo los bloqueos por bucle, que sí deben seguir sumando para escalar.
146
332
  if (kind === "loop") {
147
333
  s.loopBlocks = (s.loopBlocks ?? 0) + 1;
148
- record(s, this.cfg, tool, sig, fam);
334
+ record(s, this.cfg, tool, sig, fam, callID);
149
335
  }
150
336
  this.save();
151
- return kind === "scope"
152
- ? `🛑 [LOOPBREAKER BLOQUEADO] ${reason}. Trabaja solo dentro del alcance de la fase activa o pide al usuario que cambie de fase.`
153
- : blockMessage(this.cfg, s, reason);
337
+ return kind === "scope" ? t("scope.message", { reason }, this.L) : blockMessage(this.cfg, s, reason);
154
338
  }
155
339
  }
156
- record(s, this.cfg, tool, sig, fam);
340
+ record(s, this.cfg, tool, sig, fam, callID);
157
341
  this.save();
158
342
  return undefined;
159
343
  }
160
- after(sessionID, tool, args, output, failed = false) {
161
- const s = this.session(sessionID);
162
- recordResult(s, tool, signature(tool, args, this.root), resultText(output), failed);
163
- 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
+ });
164
351
  }
165
352
  /** Red de seguridad fiable: archivos cambiados según git que violan el alcance. */
166
353
  gitCheck() {
167
354
  this.reload();
168
355
  try {
169
- 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
+ });
170
363
  const changed = out
171
364
  .split("\n")
172
365
  .filter(Boolean)
@@ -178,32 +371,47 @@ export class Guard {
178
371
  return bad;
179
372
  }
180
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.
181
375
  return [];
182
376
  }
183
377
  }
184
378
  reset(sessionID) {
185
- if (sessionID)
186
- delete this.state.sessions[sessionID];
187
- else
188
- this.state = { sessions: {} };
189
- 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
+ });
190
393
  }
191
394
  status(sessionID) {
192
395
  const c = this.cfg;
396
+ const L = this.L;
193
397
  const lines = [
194
- `modo: ${c.mode} | repeticiones: ${c.maxConsecutiveRepeats} | ciclos hasta periodo ${c.cycleMaxPeriod}`,
195
- `fase: ${c.specFile ?? "(ninguna)"}`,
196
- `allowOnly: ${c.scope.allowOnlyGlobs.join(", ") || "-"}`,
197
- `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),
198
402
  ];
199
- 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);
200
406
  for (const id of ids) {
201
- const s = this.state.sessions[id];
407
+ const s = sessions[id];
202
408
  if (s)
203
- 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));
204
410
  }
205
411
  for (const w of c.warnings)
206
412
  lines.push(`⚠ ${w}`);
413
+ if (this.lastError)
414
+ lines.push(t("status.lastError", { n: this.errorCount, msg: this.lastError }, L));
207
415
  return lines.join("\n");
208
416
  }
209
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
+ }
package/dist/src/index.js CHANGED
@@ -21,7 +21,7 @@ export const LoopbreakerPlugin = async (ctx = {}) => {
21
21
  "tool.execute.before": async (input, output) => {
22
22
  const args = output?.args ?? {};
23
23
  pending.set(input.callID, args);
24
- const msg = guard.before(input.sessionID, input.tool, args);
24
+ const msg = guard.before(input.sessionID, input.tool, args, input.callID);
25
25
  if (msg) {
26
26
  pending.delete(input.callID);
27
27
  throw new Error(msg);
@@ -32,7 +32,7 @@ export const LoopbreakerPlugin = async (ctx = {}) => {
32
32
  pending.delete(input.callID);
33
33
  if (!args)
34
34
  return;
35
- 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);
36
36
  },
37
37
  // Inyecta la tarjeta de fase en cada prompt y durante la compactación (no después).
38
38
  "experimental.chat.system.transform": async (_i, output) => {
@@ -14,12 +14,21 @@ export interface InstallResult {
14
14
  export declare function globalConfigDir(env?: NodeJS.ProcessEnv): string;
15
15
  /** Busca opencode.json (o .jsonc); si no existe ninguno, devuelve opencode.json como destino a crear. */
16
16
  export declare function configFile(dir: string): string;
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;
17
24
  /**
18
25
  * Añade el plugin a opencode.json de forma idempotente, con copia de seguridad.
19
26
  * Por defecto fija la versión exacta; una entrada sin versión se reemplaza.
20
27
  */
21
28
  export declare function install(dir: string, pin?: boolean): InstallResult;
22
29
  export declare function uninstall(dir: string): InstallResult;
30
+ /** ¿El opencode.json de este directorio registra loopbreaker? */
31
+ export declare function isInstalled(dir: string): boolean;
23
32
  /** Crea un .loopbreaker.json en el proyecto (no sobrescribe). */
24
33
  export declare function init(projectDir: string, config?: LoopbreakerConfig): InstallResult;
25
34
  /** Añade `.opencode/` al .gitignore del proyecto de forma idempotente. */