@adayacas/loopbreaker 0.4.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # loopbreaker
2
2
 
3
- Zero-dependency guard for coding agents. It **breaks tool-call loops** (identical repeats, A-B cycles, and "stagnation": the same command family returning the same output) and optionally **enforces a per-phase write scope**. Works with OpenCode, Claude Code, Codex CLI and Grok Build.
3
+ Zero-dependency guard for coding agents. It **breaks tool-call loops** (identical repeats, A-B cycles, and "stagnation": the same command family returning the same output) and optionally **enforces a per-phase write scope**. Works with OpenCode, Claude Code, Codex CLI, Grok Build and Pi.
4
4
 
5
5
  [Leer en español](#español)
6
6
 
@@ -8,7 +8,7 @@ Zero-dependency guard for coding agents. It **breaks tool-call loops** (identica
8
8
 
9
9
  ```bash
10
10
  npm install -g @adayacas/loopbreaker
11
- loopbreaker install --target auto # detects the tools you have; or: --target claude,codex,grok,opencode
11
+ loopbreaker install --target auto # detects the tools you have; or: --target claude,codex,grok,opencode,pi
12
12
  loopbreaker doctor # checks PATH, duplicates, config
13
13
  ```
14
14
 
@@ -18,6 +18,7 @@ loopbreaker doctor # checks PATH, duplicates, config
18
18
  | Claude Code | `PreToolUse` / `PostToolUse` / `PostToolUseFailure` command hooks | `~/.claude/settings.json` | follows official docs; automated tests with real payloads, live test pending |
19
19
  | Codex CLI | `PreToolUse` / `PostToolUse` command hooks | `~/.codex/hooks.json` (Codex asks you to review it with `/hooks`) | follows official docs; live test pending |
20
20
  | Grok Build | `PreToolUse` / `PostToolUse` command hooks | `~/.grok/hooks/loopbreaker.json` (project hooks need `/hooks-trust`) | follows official docs; live test pending; result field name of `PostToolUse` is not documented, several names are accepted |
21
+ | Pi | Pi extension (`~/.pi/agent/extensions/loopbreaker.ts`) | auto-discovered by Pi; calls `loopbreaker hook pi before/after` | extension generated by `install --target pi`; loopbreaker must be on PATH |
21
22
 
22
23
  Notes:
23
24
  - Hook-based tools call `loopbreaker` on every tool use, so it must be on your `PATH` (global install). `install` refuses otherwise.
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * Un solo parser tolerante cubre los tres: acepta ambos estilos de claves.
10
10
  */
11
- export type HookTarget = "claude" | "codex" | "grok";
11
+ export type HookTarget = "claude" | "codex" | "grok" | "pi";
12
12
  export type HookPhase = "before" | "after";
13
13
  export declare const HOOK_TARGETS: readonly HookTarget[];
14
14
  export interface HookEvent {
@@ -1,4 +1,4 @@
1
- export const HOOK_TARGETS = ["claude", "codex", "grok"];
1
+ export const HOOK_TARGETS = ["claude", "codex", "grok", "pi"];
2
2
  const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
3
3
  const str = (v) => (typeof v === "string" && v ? v : undefined);
4
4
  const first = (o, keys) => {
@@ -3,7 +3,7 @@ import * as path from "node:path";
3
3
  import { LOG_FILE, loadConfig } from "./config-loader.js";
4
4
  import { GITIGNORE_ENTRY, globalConfigDir, isInstalled } from "./installer.js";
5
5
  import { t } from "./messages.js";
6
- import { LABEL, TARGETS, hasHooks, hookFile, onPath } from "./targets.js";
6
+ import { LABEL, TARGETS, hasHooks, hookFile, isTargetInstalled, onPath } from "./targets.js";
7
7
  const ICON = { ok: "✓", warn: "⚠", fail: "✗" };
8
8
  export const formatCheck = (c) => `${ICON[c.level]} ${c.text}`;
9
9
  /** Revisa la instalación y la configuración. No modifica nada. */
@@ -30,6 +30,8 @@ export function doctor(root, e) {
30
30
  if (hasHooks(hookFile(tg, sc, { ...e, cwd: root })))
31
31
  mark(tg, sc);
32
32
  }
33
+ if (isTargetInstalled("pi", "user", e))
34
+ mark("pi", "user");
33
35
  for (const tg of TARGETS) {
34
36
  const w = where.get(tg);
35
37
  add(w ? "ok" : "warn", w ? t("doc.installed", { label: LABEL[tg], where: w.join(", ") }) : t("doc.notInstalled", { label: LABEL[tg] }));
@@ -281,6 +281,10 @@ declare const C: {
281
281
  en: string;
282
282
  es: string;
283
283
  };
284
+ "tgt.piManual": {
285
+ en: string;
286
+ es: string;
287
+ };
284
288
  "tgt.opencodeNote": {
285
289
  en: string;
286
290
  es: string;
@@ -127,6 +127,10 @@ const C = {
127
127
  "tgt.notObject": { en: '"hooks" in {file} is not an object.', es: '"hooks" en {file} no es un objeto.' },
128
128
  "tgt.unknown": { en: 'Unknown target "{name}". Valid: {valid}.', es: 'Destino desconocido "{name}". Válidos: {valid}.' },
129
129
  "tgt.none": { en: "No supported tools were detected. Use --target to choose.", es: "No se detectó ninguna herramienta compatible. Usa --target para elegir." },
130
+ "tgt.piManual": {
131
+ en: "Pi has no native hook API: use loopbreaker manually via `loopbreaker hook pi before/after` with a JSON payload, or wrap your commands. See README for details.",
132
+ es: "Pi no tiene API de hooks nativa: usá loopbreaker manualmente con `loopbreaker hook pi before/after` pasando un payload JSON, o envolvé tus comandos. Ver README para detalles.",
133
+ },
130
134
  "tgt.opencodeNote": { en: "OpenCode: {msg}", es: "OpenCode: {msg}" },
131
135
  // ---- doctor ----
132
136
  "doc.node": { en: "Node.js {v}", es: "Node.js {v}" },
@@ -166,7 +170,7 @@ const C = {
166
170
  // ---- CLI ----
167
171
  "cli.usage": {
168
172
  en: `usage: loopbreaker <command>
169
- install [--target opencode|claude|codex|grok|auto|all] [--project] [--yes] [--no-pin] [--no-gitignore] [--force]
173
+ install [--target opencode|claude|codex|grok|pi|auto|all] [--project] [--yes] [--no-pin] [--no-gitignore] [--force]
170
174
  set up loopbreaker (interactive wizard; --yes = defaults)
171
175
  uninstall [--target ...] [--project]
172
176
  remove it
@@ -175,12 +179,12 @@ const C = {
175
179
  status show phase, scope and blocks
176
180
  set-phase <id|path> change the active phase
177
181
  reset [sessionID] clear the block history
178
- hook <claude|codex|grok> <before|after> [--failed]
182
+ hook <claude|codex|grok|pi> <before|after> [--failed]
179
183
  (internal) entry point the tool hooks call
180
184
 
181
185
  Language: LOOPBREAKER_LOCALE=es or --lang es (default: en)`,
182
186
  es: `uso: loopbreaker <comando>
183
- install [--target opencode|claude|codex|grok|auto|all] [--project] [--yes] [--no-pin] [--no-gitignore] [--force]
187
+ install [--target opencode|claude|codex|grok|pi|auto|all] [--project] [--yes] [--no-pin] [--no-gitignore] [--force]
184
188
  instala loopbreaker (wizard interactivo; --yes = valores por defecto)
185
189
  uninstall [--target ...] [--project]
186
190
  lo quita
@@ -189,7 +193,7 @@ const C = {
189
193
  status muestra la fase, el alcance y los bloqueos
190
194
  set-phase <id|ruta> cambia la fase activa
191
195
  reset [sessionID] limpia el historial de bloqueos
192
- hook <claude|codex|grok> <before|after> [--failed]
196
+ hook <claude|codex|grok|pi> <before|after> [--failed]
193
197
  (interno) punto de entrada que llaman los hooks
194
198
 
195
199
  Idioma: LOOPBREAKER_LOCALE=es o --lang es (por defecto: en)`,
@@ -211,7 +215,7 @@ const C = {
211
215
  es: 'Ojo: {targets} también sigue instalado globalmente; usa "loopbreaker uninstall" para quitarlo.',
212
216
  },
213
217
  // ---- wizard ----
214
- "wiz.targets": { en: "Tools to protect (opencode, claude, codex, grok)", es: "Herramientas a proteger (opencode, claude, codex, grok)" },
218
+ "wiz.targets": { en: "Tools to protect (opencode, claude, codex, grok, pi)", es: "Herramientas a proteger (opencode, claude, codex, grok, pi)" },
215
219
  "wiz.scope": { en: "Install globally or only in this project? (global/project)", es: "¿Instalar global o solo en este proyecto? (global/proyecto)" },
216
220
  "wiz.pin": { en: "Pin the exact plugin version?", es: "¿Fijar la versión exacta del plugin?" },
217
221
  "wiz.createCfg": { en: "Create .loopbreaker.json with anti-loop settings?", es: "¿Crear .loopbreaker.json con ajustes del anti-bucles?" },
@@ -3,9 +3,9 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { globalConfigDir, install, isInstalled, manual, readJsonFile, uninstall } from "./installer.js";
5
5
  import { t } from "./messages.js";
6
- export const TARGETS = ["opencode", "claude", "codex", "grok"];
7
- export const LABEL = { opencode: "OpenCode", claude: "Claude Code", codex: "Codex CLI", grok: "Grok Build" };
8
- const BINARY = { opencode: "opencode", claude: "claude", codex: "codex", grok: "grok" };
6
+ export const TARGETS = ["opencode", "claude", "codex", "grok", "pi"];
7
+ export const LABEL = { opencode: "OpenCode", claude: "Claude Code", codex: "Codex CLI", grok: "Grok Build", pi: "Pi" };
8
+ const BINARY = { opencode: "opencode", claude: "claude", codex: "codex", grok: "grok", pi: "pi" };
9
9
  export function defaultEnv() {
10
10
  return { home: process.env.HOME || process.env.USERPROFILE || os.homedir(), cwd: process.cwd(), env: process.env };
11
11
  }
@@ -21,6 +21,8 @@ export function hookFile(target, scope, e) {
21
21
  return user ? path.join(codexHome(e), "hooks.json") : path.join(e.cwd, ".codex", "hooks.json");
22
22
  case "grok":
23
23
  return user ? path.join(e.home, ".grok", "hooks", "loopbreaker.json") : path.join(e.cwd, ".grok", "hooks", "loopbreaker.json");
24
+ case "pi":
25
+ return user ? path.join(e.home, ".pi", "agent", "extensions", "loopbreaker.ts") : path.join(e.cwd, ".pi", "extensions", "loopbreaker.ts");
24
26
  }
25
27
  }
26
28
  // ---------------------------------------------------------------- PATH
@@ -46,6 +48,7 @@ export function detectTargets(e) {
46
48
  claude: path.join(e.home, ".claude"),
47
49
  codex: codexHome(e),
48
50
  grok: path.join(e.home, ".grok"),
51
+ pi: path.join(e.home, ".pi"),
49
52
  };
50
53
  return TARGETS.filter((tg) => fs.existsSync(dirs[tg]) || onPath(BINARY[tg], e.env));
51
54
  }
@@ -66,7 +69,7 @@ export function parseTargets(spec, e) {
66
69
  return targets.length ? { targets } : { error: t("tgt.none") };
67
70
  }
68
71
  const command = (target, phase, failed = false) => `loopbreaker hook ${target} ${phase}${failed ? " --failed" : ""}`;
69
- export const isOurCommand = (c) => typeof c === "string" && /^loopbreaker hook (claude|codex|grok) /.test(c);
72
+ export const isOurCommand = (c) => typeof c === "string" && /^loopbreaker hook (claude|codex|grok|pi) /.test(c);
70
73
  const groupIsOurs = (g) => !!g && typeof g === "object" && Array.isArray(g.hooks) && g.hooks.some((h) => isOurCommand(h?.command));
71
74
  /** Grupos de hooks por evento. Codex y Grok solo documentan PreToolUse/PostToolUse; PostToolUseFailure solo en Claude Code. */
72
75
  function groupsFor(target) {
@@ -189,6 +192,38 @@ export function uninstallHooks(target, scope, e) {
189
192
  }
190
193
  // ---------------------------------------------------------------- orquestación
191
194
  export function installTarget(target, scope, e, opts = {}) {
195
+ if (target === "pi") {
196
+ const file = hookFile("pi", scope, e);
197
+ const ext = `import { execFileSync } from "node:child_process";
198
+
199
+ export default function (pi: any) {
200
+ const session = process.env.PI_SESSION_ID || "pi";
201
+ const cwd = process.cwd();
202
+ pi.on("tool_call", (event: any) => {
203
+ try {
204
+ const payload = JSON.stringify({ session_id: session, tool_name: event.toolName, tool_input: event.input, cwd });
205
+ execFileSync("loopbreaker", ["hook", "pi", "before"], { input: payload, stdio: ["pipe", "pipe", "pipe"] });
206
+ } catch (e: any) {
207
+ const stderr = e && e.stderr ? e.stderr.toString() : "";
208
+ if (stderr) return { block: true, reason: stderr };
209
+ }
210
+ return undefined;
211
+ });
212
+ pi.on("tool_result", (event: any) => {
213
+ try {
214
+ const content = Array.isArray(event.content) ? event.content.map((c: any) => (typeof c === "string" ? c : (c && c.text) || "")).join("\\n") : "";
215
+ const payload = JSON.stringify({ session_id: session, tool_name: event.toolName, tool_input: event.input, tool_response: { stdout: content, exit_code: event.isError ? 1 : 0 }, cwd });
216
+ execFileSync("loopbreaker", ["hook", "pi", "after"], { input: payload, stdio: ["pipe", "pipe", "pipe"] });
217
+ } catch {
218
+ /* fail open */
219
+ }
220
+ });
221
+ }
222
+ `;
223
+ fs.mkdirSync(path.dirname(file), { recursive: true });
224
+ fs.writeFileSync(file, ext);
225
+ return { ok: true, changed: true, file, message: `Pi: extension written to ${file}. Restart Pi to load it. loopbreaker must be on PATH.` };
226
+ }
192
227
  if (target === "opencode") {
193
228
  const r = install(scope === "project" ? e.cwd : globalConfigDir(e.env), opts.pin !== false);
194
229
  return { ...r, message: `${r.message}${r.changed ? `\n${t("cli.restartOpencode")}` : ""}` };
@@ -196,12 +231,22 @@ export function installTarget(target, scope, e, opts = {}) {
196
231
  return installHooks(target, scope, e, { force: opts.force });
197
232
  }
198
233
  export function uninstallTarget(target, scope, e) {
234
+ if (target === "pi") {
235
+ const file = hookFile("pi", scope, e);
236
+ try {
237
+ fs.rmSync(file, { force: true });
238
+ }
239
+ catch { /* ignore */ }
240
+ return { ok: true, changed: true, file, message: `Pi: extension removed (${file})` };
241
+ }
199
242
  if (target === "opencode")
200
243
  return uninstall(scope === "project" ? e.cwd : globalConfigDir(e.env));
201
244
  return uninstallHooks(target, scope, e);
202
245
  }
203
246
  /** ¿El destino sigue instalado en este scope? Sirve para avisar cuando queda activo en el otro. */
204
247
  export function isTargetInstalled(target, scope, e) {
248
+ if (target === "pi")
249
+ return fs.existsSync(hookFile("pi", scope, e));
205
250
  if (target === "opencode")
206
251
  return isInstalled(scope === "project" ? e.cwd : globalConfigDir(e.env));
207
252
  return hasHooks(hookFile(target, scope, e));
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "bugs": {
10
10
  "url": "https://github.com/adayacas/loopbreaker/issues"
11
11
  },
12
- "version": "0.4.0",
12
+ "version": "0.4.1",
13
13
  "description": "Its an Opencode loopbreaker tool to stop ai models when the context overload, to save tokens and guard the healt processes",
14
14
  "type": "module",
15
15
  "main": "dist/src/index.js",