@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/CHANGELOG.md ADDED
@@ -0,0 +1,63 @@
1
+ # Changelog
2
+
3
+ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). Versionado semántico (en 0.x, un cambio incompatible sube la versión menor).
4
+
5
+ ## [0.4.0] - 2026-11-25
6
+
7
+ ### Añadido
8
+ - **Multi-arnés.** Además de OpenCode, funciona con **Claude Code, Codex CLI y Grok Build** mediante hooks de comando (`loopbreaker hook <arnés> <before|after>`). Los hooks fallan en abierto.
9
+ - `loopbreaker install --target opencode|claude|codex|grok|auto|all` (idempotente, con copia de seguridad `*.loopbreaker.bak`, snippet manual si el archivo tiene comentarios o no se puede leer; Grok se omite si ya hay hooks de Claude Code, `--force` lo permite).
10
+ - `loopbreaker uninstall --target ...` y `loopbreaker doctor` (PATH, duplicados, configuración, `.gitignore`, errores internos).
11
+ - Wizard con selección de herramientas.
12
+ - Mensajes en **inglés por defecto**; español con `"locale": "es"`, `LOOPBREAKER_LOCALE=es` o `--lang es`.
13
+ - Estado seguro entre procesos: archivo de bloqueo, deduplicación por id de llamada (un mismo hook ejecutado dos veces no cuenta doble).
14
+ - Adaptadores tolerantes a claves snake_case y camelCase.
15
+ - **API programática.** `@adayacas/loopbreaker/lib` expone `Guard`, `loadConfig`, `phaseCard` y `parseFrontmatter` sin agregar exports al módulo del plugin de OpenCode.
16
+
17
+ ### Cambiado
18
+ - Los textos de bloqueo ahora salen del catálogo `messages.ts`. Sin configurar idioma verás inglés (antes español).
19
+ - README en inglés con sección en español.
20
+
21
+ ### Corregido
22
+ - **Frontmatter con claves dedent.** Un archivo de fase con la primera clave indentada y las siguientes a nivel raíz descartaba estas últimas en silencio (el `scope` dejaba de aplicarse). Ahora falla con un error explícito.
23
+ - **Falsos positivos de ciclo.** Alternar dos llamadas cuyas salidas cambian ya no se bloquea como ciclo: la salida distinta cuenta como progreso.
24
+ - **`git` colgado.** La red de seguridad usa un timeout de 5 s: un `index.lock` viejo o un filesystem de red no congela al agente.
25
+ - **Desinstalación incompleta silenciosa.** Quitar un scope avisa si el mismo destino sigue instalado en el otro (`--project` o global).
26
+
27
+ ### Pendiente
28
+ - Verificación en vivo con Claude Code, Codex y Grok (cubiertos por pruebas automáticas con payloads documentados).
29
+
30
+ ## [0.3.1] - 2026-11-25
31
+
32
+ ### Corregido
33
+ - **Pérdida de sesiones con procesos en paralelo.** Cada proceso reescribía todo el archivo de estado desde su copia en memoria, así que dos sesiones de OpenCode sobre el mismo proyecto se borraban el historial entre sí. Ahora cada proceso solo sobrescribe las sesiones que ha usado y mezcla con lo que hay en disco.
34
+ - **Escritura no atómica del estado.** Un fallo a mitad de escritura podía dejar un JSON truncado, que se descartaba en silencio. Ahora se escribe a un archivo temporal y se renombra, sin seguir symlinks previos, y el temporal se limpia si algo falla.
35
+
36
+ ### Cambiado
37
+ - **Los fallos internos ya no se ocultan.** Antes, 6 bloques `catch` vacíos ignoraban cualquier error al leer, guardar o endurecer permisos. Ahora el agente sigue trabajando igual, pero el fallo queda registrado una vez por tipo en el log (`internal-error`) y aparece en `loopbreaker status`. Que el archivo de estado no exista todavía no cuenta como error.
38
+ - Los errores de lectura de JSON no copian el contenido del archivo al log.
39
+
40
+ ### Documentación
41
+ - README: texto neutral, nota sobre errores internos y versión fijada actualizada.
42
+ - Se añade este changelog.
43
+
44
+ ## [0.3.0] - 2026-11-17
45
+
46
+ ### Cambiado (incompatible con 0.2.x)
47
+ - Todo lo que decía `aeg` pasa a `loopbreaker`: `.loopbreaker.json`, `.opencode/loopbreaker-state.json`, `.opencode/loopbreaker.log.jsonl`, la herramienta `loopbreaker_status`, el comando `loopbreaker` y el export `LoopbreakerPlugin`. Guía de migración en el README.
48
+ - El instalador fija la versión exacta por defecto (`--no-pin` para dejar `latest`).
49
+
50
+ ### Seguridad y privacidad
51
+ - El estado y el log ya no guardan fragmentos de la salida de las herramientas; los archivos se crean con permisos `0600` y los estados antiguos se sanean al cargar.
52
+ - No se escribe a través de symlinks en `.opencode/`.
53
+ - La ruta de la fase activa no puede salir de la raíz del proyecto.
54
+ - La tarjeta de fase se sanea, se limita en longitud y se marca como datos del repositorio, no como instrucciones.
55
+
56
+ ### Añadido
57
+ - Asistente de instalación con valores seguros por defecto y `--yes` para uso no interactivo.
58
+ - `loopbreaker_status` funciona sin `@opencode-ai/plugin`.
59
+
60
+ ## [0.2.0] - 2026-11-17
61
+
62
+ ### Añadido
63
+ - Primera versión publicada: detector de bucles (repeticiones idénticas y ciclos), detección de estancamiento por salida idéntica, control de alcance por fases, tarjeta de fase en el prompt y en la compactación, red de seguridad con `git` y CLI (`install`, `init`, `status`, `set-phase`, `reset`).
package/LICENSE CHANGED
@@ -1,9 +1,21 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 AEG contributors
3
+ Copyright (c) 2026 Adrián Ayala Castrillón
4
4
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
6
11
 
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
8
14
 
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,24 +1,73 @@
1
1
  # loopbreaker
2
2
 
3
- Loop breaker para agentes de OpenCode: frena bucles de herramientas y limita el alcance de escritura por fase.
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.
4
+
5
+ [Leer en español](#español)
6
+
7
+ ## Install
4
8
 
5
- ## Instalación
6
9
  ```bash
7
- npx @adayacas/loopbreaker install # registra el plugin en ~/.config/opencode/opencode.json
10
+ npm install -g @adayacas/loopbreaker
11
+ loopbreaker install --target auto # detects the tools you have; or: --target claude,codex,grok,opencode
12
+ loopbreaker doctor # checks PATH, duplicates, config
13
+ ```
14
+
15
+ | Tool | How it hooks in | Where | Status |
16
+ |---|---|---|---|
17
+ | OpenCode | npm plugin (`opencode.json`) | `~/.config/opencode/opencode.json` | tested live |
18
+ | Claude Code | `PreToolUse` / `PostToolUse` / `PostToolUseFailure` command hooks | `~/.claude/settings.json` | follows official docs; automated tests with real payloads, live test pending |
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
+ | 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
+
22
+ Notes:
23
+ - Hook-based tools call `loopbreaker` on every tool use, so it must be on your `PATH` (global install). `install` refuses otherwise.
24
+ - Grok Build also reads Claude Code hooks. If Claude hooks are present, `install --target grok` is skipped (each call would be counted twice); use `--force` to override.
25
+ - Hooks **fail open**: any internal error lets the call through. A guard that breaks the agent is worse than none.
26
+ - Each hook call is a new process. State lives on disk (`.opencode/loopbreaker-state.json`), guarded by a lock file and de-duplicated by tool-call id.
27
+ - Existing config files are backed up (`*.loopbreaker.bak`). If a file has comments or cannot be parsed, the installer prints the snippet to add manually instead of touching it.
28
+ - Options: `--project` (this project only), `--yes` (no wizard), `--no-pin`, `--no-gitignore`, `--force`, `--lang es`. Uninstall: `loopbreaker uninstall --target <...>`; removing one scope warns if the same tool is still installed in the other.
29
+ - Messages are English by default; set `"locale": "es"` in `.loopbreaker.json` or `LOOPBREAKER_LOCALE=es` for Spanish.
30
+
31
+ Commands: `install`, `uninstall`, `doctor`, `init`, `status`, `set-phase <id|path>`, `reset [sessionID]`. The agent only gets the read-only `loopbreaker_status` tool (OpenCode).
32
+
33
+ ## What it does
34
+ - **Loops**: blocks N identical calls and A-B-A-B cycles; after `hardStopAfter` loop blocks it escalates to a hard stop.
35
+ - **Stagnation**: the same command family returning identical output (≥ 40 chars) `stagnationRepeats` times in a row is blocked even if arguments change. A successful write resets it.
36
+ - **Scope**: validates `edit`/`write`/`patch` (exact, symlink-aware) and `bash` (best effort) against `allowOnlyGlobs`/`denyGlobs`. **A deterrent, not a sandbox.**
37
+ - **Git safety net** (OpenCode): on `session.idle` it compares `git status` with the scope and only logs.
38
+ - **Privacy**: state and log store hashes, lengths and metadata, never tool output. Files are `0600`.
39
+
40
+ Configuration lives in `.loopbreaker.json` (all optional); see the Spanish section for the full reference. Add `.opencode/` to `.gitignore`.
41
+
42
+ ## Known limits
43
+ - Scope enforcement is not a security boundary (shell variables, `node -e`, subshells, `git checkout`, `npm install`…).
44
+ - Only tool calls the harness routes through hooks can be seen. Hook payload shapes of Codex and Grok may change; run `loopbreaker doctor` after upgrading them.
45
+ - Windows is not tested.
46
+
47
+ ---
48
+
49
+ ## Español
50
+
51
+ ### Instalación
52
+ ```bash
53
+ npx @adayacas/loopbreaker install # wizard: global o proyecto, versión y ajustes opcionales
8
54
  ```
9
55
  Reinicia OpenCode: descarga el paquete de npm por sí mismo al arrancar. No hay build ni copia de archivos.
10
- Para un solo proyecto: `npx @adayacas/loopbreaker install --project`. Para quitarlo: `npx @adayacas/loopbreaker uninstall`.
56
+ El instalador fija la versión exacta (`@adayacas/loopbreaker@0.4.0`) por defecto. Usa `--no-pin` para dejar `latest`; para actualizar, vuelve a ejecutar `install`.
57
+ Para CI o instalación no interactiva: `install --yes` usa los defaults sin preguntar.
58
+ Para un solo proyecto: `npx @adayacas/loopbreaker install --project`. Para quitarlo: `npx @adayacas/loopbreaker uninstall [--project]` — sin `--project` quita la instalación global y te avisa si este proyecto también la tiene.
11
59
 
12
- Instalación manual equivalente, en `opencode.json`: `{ "plugin": ["@adayacas/loopbreaker"] }`.
13
- Sin `.aeg.json` funciona solo el anti-bucles. `npx @adayacas/loopbreaker init` crea uno mínimo.
60
+ El wizard puede crear `.loopbreaker.json` con los ajustes del anti-bucles y añadir `.opencode/` al `.gitignore` del proyecto.
61
+ Instalación manual equivalente, en `opencode.json`: `{ "plugin": ["@adayacas/loopbreaker@0.4.0"] }`.
62
+ Sin `.loopbreaker.json` funciona solo el anti-bucles. `npx @adayacas/loopbreaker init` crea uno mínimo.
14
63
 
15
- ## Publicar (mantenedor)
64
+ ### Publicar (mantenedor)
16
65
  ```bash
17
66
  npm login
18
67
  npm publish # prepublishOnly: limpia, compila, corre los tests y compila solo src
19
68
  ```
20
69
 
21
- ## Configuración (`.aeg.json`, todo opcional)
70
+ ### Configuración (`.loopbreaker.json`, todo opcional)
22
71
  ```json
23
72
  {
24
73
  "mode": "block",
@@ -31,10 +80,10 @@ npm publish # prepublishOnly: limpia, compila, corre los tests y compila solo
31
80
  "protectedGlobs": []
32
81
  }
33
82
  ```
34
- `mode: "warn"` solo registra en `.opencode/aeg.log.jsonl` (útil para calibrar umbrales).
83
+ `mode: "warn"` solo registra en `.opencode/loopbreaker.log.jsonl` (útil para calibrar umbrales).
35
84
 
36
- ## Fases
37
- `.engram/current_phase.lock` contiene un id (`2`, `phase-02`) o una ruta. El frontmatter de la spec manda sobre `.aeg.json`:
85
+ ### Fases
86
+ `.engram/current_phase.lock` contiene un id (`2`, `phase-02`) o una ruta **dentro del proyecto**. Si la ruta apunta afuera (o pasa por un symlink que sale), se ignora con un aviso. El frontmatter de la spec manda sobre `.loopbreaker.json`:
38
87
  ```yaml
39
88
  ---
40
89
  id: phase-02
@@ -47,19 +96,41 @@ exitCriteria:
47
96
  ---
48
97
  ```
49
98
 
50
- ## Qué hace
99
+ La spec es contenido del repositorio, no una fuente de instrucciones confiable. `goal` y `exitCriteria` se aplanan, se recortan y se marcan como datos antes de inyectarse, pero la defensa real es no instalar el plugin en repos que no controlás.
100
+
101
+ ### Qué hace
51
102
  - **Bucles**: vigila todas las herramientas. Bloquea repeticiones idénticas (N veces) y ciclos A-B-A-B.
52
103
  - **Estancamiento**: si la misma familia de comando (herramienta, y en bash el programa: `rtk`, `npx`, `psql`...) devuelve EXACTAMENTE la misma salida `stagnationRepeats` veces seguidas, bloquea aunque los argumentos cambien. Ignora salidas cortas (< 40 caracteres) y se reinicia con una escritura exitosa. Cubre el caso en que una herramienta se queda pegada y el agente prueba variantes. Una escritura exitosa o una salida distinta cuentan como progreso. Tras `hardStopAfter` bloqueos escala a "parada dura".
53
- - **Alcance**: valida `edit`/`write`/`patch` (exacto, con `realpath`) y `bash` (mejor esfuerzo). `deny` gana a `allowOnly`. Los archivos del guardián están protegidos.
54
- - **Red de seguridad**: en `session.idle` compara `git status` con el alcance y registra violaciones.
104
+ - **Alcance**: valida `edit`/`write`/`patch` (exacto, con `realpath`) y `bash` (mejor esfuerzo). `deny` gana a `allowOnly`. Los archivos del guardián están protegidos. **Es un recordatorio disuasorio, no un sandbox.**
105
+ - **Red de seguridad**: en `session.idle` compara `git status` con el alcance y **solo registra** las violaciones; no bloquea.
55
106
  - **Contexto**: inyecta una tarjeta de fase en el prompt y en la compactación.
107
+ - **Privacidad**: el estado y el log no guardan la salida de las herramientas; solo hashes, longitudes y metadatos. Se crean con permisos de dueño (`0600`).
56
108
 
57
- ## Gestión (solo humanos, el agente no la tiene)
109
+ ### Archivos que genera
110
+ Añade a tu `.gitignore`: `.opencode/` (el wizard lo hace por ti en una instalación de proyecto).
111
+ El estado se guarda de forma atómica y sin pisar las sesiones de otros procesos. Si algo interno falla (disco lleno, permisos), el agente sigue trabajando y el fallo queda en el log (`internal-error`) y en `loopbreaker status`.
112
+ El estado y el log se crean con permisos `0600`. Las versiones viejas con snippets se sanean al cargar, pero conviene borrar `.opencode/loopbreaker-state.json` y `.opencode/loopbreaker.log.jsonl` una vez migrado.
113
+
114
+ ### Gestión (solo humanos, el agente no la tiene)
58
115
  ```
59
116
  npx @adayacas/loopbreaker status | npx @adayacas/loopbreaker set-phase 2 | npx @adayacas/loopbreaker reset [sessionID]
60
117
  ```
61
- El agente solo dispone de la herramienta de lectura `aeg_status`.
118
+ El agente solo dispone de la herramienta de lectura `loopbreaker_status`, que ahora se expone siempre sin depender de `@opencode-ai/plugin`.
119
+
120
+ ### Migrar desde 0.2.x
121
+ La 0.3.0 renombra todo lo que antes decía `aeg`:
122
+
123
+ | Antes | Ahora |
124
+ |---|---|
125
+ | `.aeg.json` | `.loopbreaker.json` |
126
+ | `.opencode/.aeg-state.json` | `.opencode/loopbreaker-state.json` |
127
+ | `.opencode/aeg.log.jsonl` | `.opencode/loopbreaker.log.jsonl` |
128
+ | herramienta `aeg_status` | `loopbreaker_status` |
129
+ | comando `aeg` | `loopbreaker` |
130
+
131
+ En cada proyecto: `mv .aeg.json .loopbreaker.json`. El estado y el log antiguos se pueden borrar.
62
132
 
63
- ## Límites conocidos
64
- - `bash` no se puede validar al 100 % (variables, scripts, subshells): por eso existe la comprobación con git.
133
+ ### Límites conocidos
134
+ - El guardián de alcance es disuasorio, no un control de seguridad: `bash` se evade con variables, `node -e`, subshells, `git checkout`, `npm install`, etc., y la red de git solo registra.
65
135
  - Los nombres de hooks `experimental.*` y la forma de `output.args` dependen de la versión de OpenCode; verifícalos al instalar.
136
+ - La spec de fase se considera contenido del repo, no instrucciones. Un repo malicioso puede intentar inyectar texto por `goal`/`exitCriteria`; se aplana y se recorta, pero no uses el plugin como frontera de confianza.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Adaptadores: traducen lo que envía cada herramienta a un evento común.
3
+ *
4
+ * Formatos documentados (verificados contra la documentación oficial, noviembre 2026):
5
+ * - Claude Code y Codex CLI: JSON por stdin en snake_case (session_id, tool_name, tool_input, tool_use_id, tool_response, cwd).
6
+ * - Grok Build: JSON por stdin en camelCase (sessionId, toolName, toolInput, cwd, workspaceRoot).
7
+ * La documentación de Grok no detalla el campo de resultado de PostToolUse: se aceptan varios nombres.
8
+ *
9
+ * Un solo parser tolerante cubre los tres: acepta ambos estilos de claves.
10
+ */
11
+ export type HookTarget = "claude" | "codex" | "grok";
12
+ export type HookPhase = "before" | "after";
13
+ export declare const HOOK_TARGETS: readonly HookTarget[];
14
+ export interface HookEvent {
15
+ sessionID: string;
16
+ callID?: string;
17
+ tool: string;
18
+ args: Record<string, unknown>;
19
+ /** Solo en "after": lo que devolvió la herramienta (o el error, si falló). */
20
+ output?: unknown;
21
+ cwd?: string;
22
+ /** Raíz del proyecto si la herramienta la informa (Grok: workspaceRoot). */
23
+ root?: string;
24
+ }
25
+ /**
26
+ * Convierte (nombre, entrada) de cualquier herramienta al par interno que entiende el guardián.
27
+ * Para nombres desconocidos aplica una heurística conservadora: un `command` de texto es un shell;
28
+ * una ruta junto con contenido a escribir es una edición. Lo demás pasa tal cual.
29
+ */
30
+ export declare function normalizeTool(rawName: string, input: Record<string, unknown>): {
31
+ tool: string;
32
+ args: Record<string, unknown>;
33
+ };
34
+ /** Texto estable de lo que devolvió una herramienta, para comparar salidas entre llamadas. */
35
+ export declare function responseText(v: unknown): string;
36
+ /** Devuelve undefined si el evento no es de una herramienta (el hook no tiene nada que hacer). */
37
+ export declare function parseHookInput(raw: unknown, phase: HookPhase): HookEvent | undefined;
@@ -0,0 +1,96 @@
1
+ export const HOOK_TARGETS = ["claude", "codex", "grok"];
2
+ const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
3
+ const str = (v) => (typeof v === "string" && v ? v : undefined);
4
+ const first = (o, keys) => {
5
+ for (const k of keys)
6
+ if (o[k] !== undefined && o[k] !== null)
7
+ return o[k];
8
+ return undefined;
9
+ };
10
+ /** Nombres de herramienta conocidos -> nombre interno (en minúsculas, como en OpenCode). */
11
+ const NAME_MAP = {
12
+ bash: "bash",
13
+ edit: "edit",
14
+ multiedit: "multiedit",
15
+ write: "write",
16
+ notebookedit: "edit",
17
+ read: "read",
18
+ grep: "grep",
19
+ glob: "glob",
20
+ apply_patch: "patch",
21
+ applypatch: "patch",
22
+ patch: "patch",
23
+ };
24
+ const FILE_KEYS = ["file_path", "filePath", "path", "notebook_path"];
25
+ const CONTENT_KEYS = ["content", "old_string", "new_string", "oldString", "newString", "text", "new_source"];
26
+ /**
27
+ * Convierte (nombre, entrada) de cualquier herramienta al par interno que entiende el guardián.
28
+ * Para nombres desconocidos aplica una heurística conservadora: un `command` de texto es un shell;
29
+ * una ruta junto con contenido a escribir es una edición. Lo demás pasa tal cual.
30
+ */
31
+ export function normalizeTool(rawName, input) {
32
+ const n = rawName.toLowerCase();
33
+ const mapped = NAME_MAP[n];
34
+ if (mapped === "patch") {
35
+ // Codex: el parche completo viaja en tool_input.command
36
+ const patchText = str(first(input, ["command", "patch", "patchText", "input", "diff"])) ?? "";
37
+ return { tool: "patch", args: { patchText } };
38
+ }
39
+ if (mapped) {
40
+ const args = { ...input };
41
+ if (n === "notebookedit" && !args.filePath && !args.file_path)
42
+ args.filePath = input.notebook_path;
43
+ return { tool: mapped, args };
44
+ }
45
+ if (n.startsWith("mcp__") || n.startsWith("mcp."))
46
+ return { tool: n, args: input };
47
+ if (typeof input.command === "string")
48
+ return { tool: "bash", args: input };
49
+ const hasPath = FILE_KEYS.some((k) => typeof input[k] === "string");
50
+ const hasContent = CONTENT_KEYS.some((k) => typeof input[k] === "string");
51
+ if (hasPath && hasContent)
52
+ return { tool: "edit", args: input };
53
+ return { tool: n, args: input };
54
+ }
55
+ /** Texto estable de lo que devolvió una herramienta, para comparar salidas entre llamadas. */
56
+ export function responseText(v) {
57
+ if (v === undefined || v === null)
58
+ return "";
59
+ if (typeof v === "string")
60
+ return v;
61
+ if (Array.isArray(v)) {
62
+ return v
63
+ .map((x) => (typeof x === "string" ? x : str(obj(x).text) ?? JSON.stringify(x)))
64
+ .join("\n");
65
+ }
66
+ const o = obj(v);
67
+ const parts = ["stdout", "stderr", "output", "content", "text", "error", "result"]
68
+ .map((k) => o[k])
69
+ .filter((x) => typeof x === "string" && x !== "");
70
+ if (parts.length)
71
+ return parts.join("\n");
72
+ const nested = first(o, ["content", "result"]);
73
+ if (Array.isArray(nested))
74
+ return responseText(nested);
75
+ return JSON.stringify(v);
76
+ }
77
+ /** Devuelve undefined si el evento no es de una herramienta (el hook no tiene nada que hacer). */
78
+ export function parseHookInput(raw, phase) {
79
+ const o = obj(raw);
80
+ const name = str(first(o, ["tool_name", "toolName"]));
81
+ if (!name)
82
+ return undefined;
83
+ const input = obj(first(o, ["tool_input", "toolInput", "input", "arguments", "args"]));
84
+ const { tool, args } = normalizeTool(name, input);
85
+ const ev = {
86
+ sessionID: str(first(o, ["session_id", "sessionId"])) ?? "default",
87
+ callID: str(first(o, ["tool_use_id", "toolUseId", "tool_call_id", "toolCallId", "call_id", "callId"])),
88
+ tool,
89
+ args,
90
+ cwd: str(o.cwd),
91
+ root: str(first(o, ["workspaceRoot", "workspace_root", "projectDir", "project_dir"])),
92
+ };
93
+ if (phase === "after")
94
+ ev.output = first(o, ["tool_response", "toolResponse", "tool_result", "toolResult", "tool_output", "toolOutput", "output", "error"]);
95
+ return ev;
96
+ }
@@ -0,0 +1,7 @@
1
+ export interface ParsedArgs {
2
+ positional: string[];
3
+ flags: Set<string>;
4
+ values: Record<string, string>;
5
+ }
6
+ /** `--target x`, `--target=x`, y banderas booleanas. */
7
+ export declare function parseArgs(argv: string[]): ParsedArgs;
@@ -0,0 +1,32 @@
1
+ const VALUE_FLAGS = new Set(["--target", "--lang"]);
2
+ /** `--target x`, `--target=x`, y banderas booleanas. */
3
+ export function parseArgs(argv) {
4
+ const positional = [];
5
+ const flags = new Set();
6
+ const values = {};
7
+ for (let i = 0; i < argv.length; i++) {
8
+ const a = argv[i];
9
+ if (!a.startsWith("--")) {
10
+ positional.push(a);
11
+ continue;
12
+ }
13
+ const eq = a.indexOf("=");
14
+ if (eq !== -1) {
15
+ values[a.slice(0, eq)] = a.slice(eq + 1);
16
+ }
17
+ else if (VALUE_FLAGS.has(a)) {
18
+ const next = argv[i + 1];
19
+ if (next !== undefined && !next.startsWith("--")) {
20
+ values[a] = next;
21
+ i++;
22
+ }
23
+ else {
24
+ values[a] = "";
25
+ }
26
+ }
27
+ else {
28
+ flags.add(a);
29
+ }
30
+ }
31
+ return { positional, flags, values };
32
+ }
package/dist/src/cli.js CHANGED
@@ -1,62 +1,173 @@
1
1
  #!/usr/bin/env node
2
- // CLI SOLO PARA HUMANOS. El agente no tiene acceso a estas operaciones como herramientas.
2
+ // CLI para humanos (más el punto de entrada interno `hook`). El agente no tiene estas operaciones como herramientas.
3
3
  import * as fs from "node:fs";
4
4
  import * as path from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { HOOK_TARGETS } from "./adapters.js";
5
7
  import { PHASE_LOCK } from "./config-loader.js";
8
+ import { doctor, formatCheck } from "./doctor.js";
6
9
  import { Guard } from "./guard.js";
7
- import { globalConfigDir, init, install, uninstall } from "./installer.js";
8
- const args = process.argv.slice(2);
9
- const flags = new Set(args.filter((a) => a.startsWith("--")));
10
- const [cmd, arg] = args.filter((a) => !a.startsWith("--"));
11
- const root = process.cwd();
12
- const USAGE = `uso: loopbreaker <comando> (alias corto: aeg)
13
- install [--project] registra el plugin en OpenCode (global; --project = ./opencode.json)
14
- uninstall [--project] lo quita
15
- init crea .aeg.json en este proyecto
16
- status muestra la fase, el alcance y los bloqueos
17
- set-phase <id|ruta> cambia la fase activa
18
- reset [sessionID] limpia el historial de bloqueos`;
19
- function out(r) {
20
- (r.ok ? console.log : console.error)(r.message);
21
- process.exit(r.ok ? 0 : 1);
10
+ import { readStdin, runHook } from "./hook.js";
11
+ import { ensureGitignore, init } from "./installer.js";
12
+ import { asLocale, setLocale, t } from "./messages.js";
13
+ import { defaultEnv, detectTargets, installTarget, isTargetInstalled, LABEL, parseTargets, uninstallTarget } from "./targets.js";
14
+ import { parseArgs } from "./args.js";
15
+ import { runWizard } from "./wizard.js";
16
+ function fail(msg, code = 1) {
17
+ console.error(msg);
18
+ process.exit(code);
22
19
  }
23
- const configDir = () => (flags.has("--project") ? root : globalConfigDir());
24
- switch (cmd) {
25
- case "install": {
26
- const r = install(configDir());
27
- if (r.ok && r.changed)
28
- console.log("Reinicia OpenCode para cargarlo. Opcional: `npx @adayacas/loopbreaker init` en tu proyecto.");
29
- out(r);
30
- break;
20
+ async function main() {
21
+ const { positional, flags, values } = parseArgs(process.argv.slice(2));
22
+ const [cmd, arg, arg2] = positional;
23
+ if (values["--lang"]) {
24
+ const l = asLocale(values["--lang"]);
25
+ if (l)
26
+ setLocale(l);
31
27
  }
32
- case "uninstall":
33
- out(uninstall(configDir()));
34
- break;
35
- case "init":
36
- out(init(root));
37
- break;
38
- case "status":
39
- console.log(new Guard(root).status());
40
- break;
41
- case "set-phase": {
42
- if (!arg) {
43
- console.error("uso: aeg set-phase <id|ruta> (p. ej. aeg set-phase 2)");
44
- process.exit(2);
28
+ // Hot path de los hooks: no cargar nada más de lo necesario y no escribir en stdout.
29
+ if (cmd === "hook") {
30
+ const target = arg;
31
+ const phase = arg2;
32
+ if (!HOOK_TARGETS.includes(target) || (phase !== "before" && phase !== "after"))
33
+ process.exit(0); // fail-open
34
+ const res = runHook(target, phase, await readStdin(), { failed: flags.has("--failed") });
35
+ if (res.stderr)
36
+ process.stderr.write(res.stderr + "\n", () => process.exit(res.exitCode));
37
+ else
38
+ process.exit(res.exitCode);
39
+ return;
40
+ }
41
+ const root = process.cwd();
42
+ const e = defaultEnv();
43
+ const scope = flags.has("--project") ? "project" : "user";
44
+ switch (cmd) {
45
+ case "install": {
46
+ const specGiven = values["--target"] !== undefined;
47
+ let tools;
48
+ if (specGiven) {
49
+ const p = parseTargets(values["--target"], e);
50
+ if ("error" in p)
51
+ fail(p.error);
52
+ tools = p.targets;
53
+ }
54
+ else {
55
+ const det = detectTargets(e);
56
+ tools = det.length ? det : ["opencode"];
57
+ }
58
+ let choices = {
59
+ target: scope === "project" ? "project" : "global",
60
+ pin: !flags.has("--no-pin"),
61
+ gitignore: scope === "project" && !flags.has("--no-gitignore"),
62
+ tools,
63
+ };
64
+ if (!flags.has("--yes") && process.stdin.isTTY) {
65
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
66
+ try {
67
+ const answer = await runWizard(root, { question: (q) => rl.question(q) }, flags.has("--project") ? "project" : undefined, {
68
+ askTools: !specGiven,
69
+ detected: tools,
70
+ });
71
+ if (!answer) {
72
+ console.log(t("cli.cancelled"));
73
+ return;
74
+ }
75
+ choices = { ...answer, tools: answer.tools ?? tools };
76
+ }
77
+ catch {
78
+ console.log("\n" + t("cli.cancelled"));
79
+ return;
80
+ }
81
+ finally {
82
+ rl.close();
83
+ }
84
+ if (flags.has("--no-pin"))
85
+ choices.pin = false;
86
+ if (flags.has("--no-gitignore"))
87
+ choices.gitignore = false;
88
+ }
89
+ const sc = choices.target === "project" ? "project" : "user";
90
+ let anyFail = false;
91
+ for (const tg of choices.tools ?? tools) {
92
+ const r = installTarget(tg, sc, e, { pin: choices.pin, force: flags.has("--force") });
93
+ (r.ok ? console.log : console.error)(r.message);
94
+ if (!r.ok)
95
+ anyFail = true;
96
+ }
97
+ if (choices.config)
98
+ console.log(init(root, choices.config).message);
99
+ if (choices.gitignore)
100
+ console.log(ensureGitignore(root).message);
101
+ if (anyFail)
102
+ process.exit(1);
103
+ break;
104
+ }
105
+ case "uninstall": {
106
+ let tools = ["opencode"];
107
+ if (values["--target"] !== undefined) {
108
+ const p = parseTargets(values["--target"], e);
109
+ if ("error" in p)
110
+ fail(p.error);
111
+ tools = p.targets;
112
+ }
113
+ let anyFail = false;
114
+ for (const tg of tools) {
115
+ const r = uninstallTarget(tg, scope, e);
116
+ (r.ok ? console.log : console.error)(r.message);
117
+ if (!r.ok)
118
+ anyFail = true;
119
+ }
120
+ // Quitar un scope no toca el otro: avisar si el mismo destino sigue activo.
121
+ const other = scope === "user" ? "project" : "user";
122
+ const remains = tools.filter((tg) => isTargetInstalled(tg, other, e));
123
+ if (remains.length) {
124
+ console.log(t(scope === "user" ? "cli.projectRemains" : "cli.userRemains", {
125
+ targets: remains.map((tg) => LABEL[tg]).join(", "),
126
+ }));
127
+ }
128
+ process.exit(anyFail ? 1 : 0);
129
+ break;
130
+ }
131
+ case "doctor": {
132
+ const checks = doctor(root, e);
133
+ for (const c of checks)
134
+ (c.level === "fail" ? console.error : console.log)(formatCheck(c));
135
+ const problems = checks.filter((c) => c.level !== "ok").length;
136
+ console.log(problems ? t("doc.summary", { n: problems }) : t("doc.allGood"));
137
+ process.exit(checks.some((c) => c.level === "fail") ? 1 : 0);
138
+ break;
139
+ }
140
+ case "init": {
141
+ const r = init(root);
142
+ (r.ok ? console.log : console.error)(r.message);
143
+ process.exit(r.ok ? 0 : 1);
144
+ break;
145
+ }
146
+ case "status":
147
+ console.log(new Guard(root).status());
148
+ break;
149
+ case "set-phase": {
150
+ if (!arg)
151
+ fail(t("cli.setPhaseUsage"), 2);
152
+ const guard = new Guard(root);
153
+ const lock = path.join(root, PHASE_LOCK);
154
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
155
+ fs.writeFileSync(lock, arg + "\n");
156
+ guard.reset();
157
+ guard.reload();
158
+ console.log(guard.status());
159
+ break;
45
160
  }
46
- const guard = new Guard(root);
47
- const lock = path.join(root, PHASE_LOCK);
48
- fs.mkdirSync(path.dirname(lock), { recursive: true });
49
- fs.writeFileSync(lock, arg + "\n");
50
- guard.reset();
51
- guard.reload();
52
- console.log(guard.status());
53
- break;
161
+ case "reset":
162
+ new Guard(root).reset(arg);
163
+ console.log(arg ? t("cli.resetOne", { id: arg }) : t("cli.resetAll"));
164
+ break;
165
+ default:
166
+ console.error(t("cli.usage"));
167
+ process.exit(cmd ? 2 : 0);
54
168
  }
55
- case "reset":
56
- new Guard(root).reset(arg);
57
- console.log(arg ? `historial de ${arg} limpiado` : "historial limpiado");
58
- break;
59
- default:
60
- console.error(USAGE);
61
- process.exit(cmd ? 2 : 0);
62
169
  }
170
+ main().catch((err) => {
171
+ console.error(err.message);
172
+ process.exit(1);
173
+ });