sinapse-ai 7.3.3 → 7.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.
Files changed (31) hide show
  1. package/.sinapse-ai/data/entity-registry.yaml +763 -765
  2. package/.sinapse-ai/development/templates/chrome-brain/knowledge-base/chrome-brain.md +161 -0
  3. package/.sinapse-ai/development/templates/chrome-brain/rules/chrome-brain-autoload.md +56 -0
  4. package/.sinapse-ai/development/templates/chrome-brain/scripts/chrome-brain-log.sh +67 -0
  5. package/.sinapse-ai/development/templates/chrome-brain/scripts/chrome-debug.sh +232 -0
  6. package/.sinapse-ai/development/templates/chrome-brain/scripts/chrome-ensure.sh +210 -0
  7. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-animations.md +50 -0
  8. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-brand.md +42 -0
  9. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-claude.md +49 -0
  10. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-cloning.md +50 -0
  11. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-commercial.md +41 -0
  12. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-content.md +45 -0
  13. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-copy.md +44 -0
  14. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-cybersecurity.md +42 -0
  15. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-design.md +50 -0
  16. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-growth.md +45 -0
  17. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-paidmedia.md +47 -0
  18. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-product.md +49 -0
  19. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-research.md +41 -0
  20. package/.sinapse-ai/development/templates/chrome-brain/squad-integrations/squad-storytelling.md +41 -0
  21. package/.sinapse-ai/install-manifest.yaml +81 -5
  22. package/CHROME-BRAIN-INSTALL.md +93 -0
  23. package/README.md +28 -1
  24. package/bin/modules/chrome-brain-installer.js +757 -0
  25. package/bin/sinapse.js +18 -0
  26. package/install-chrome-brain.sh +1328 -0
  27. package/package.json +3 -1
  28. package/packages/installer/src/wizard/index.js +24 -0
  29. package/packages/sinapse-install/src/capabilities/chrome-brain.js +962 -0
  30. package/packages/sinapse-install/src/installer.js +60 -2
  31. package/sinapse/agents/sinapse-orqx.md +27 -0
@@ -0,0 +1,161 @@
1
+ # Chrome Brain — Browser Automation Capability
2
+
3
+ > Cross-squad capability que da a TODOS os agents do SINAPSE o poder de
4
+ > navegar, clonar, preencher, auditar e scrape qualquer site via Chrome real.
5
+ > Auto-ativado. Sem comando manual. NSN Mode sempre ligado.
6
+
7
+ ---
8
+
9
+ ## Arquitetura
10
+
11
+ ```
12
+ Chrome (porta 9222, perfil ~/.chrome-debug-profile)
13
+ ├── Chrome DevTools MCP (29 tools) — acoes rapidas, screenshots, Lighthouse
14
+ ├── dev-browser (Playwright) — scraping complexo, batch, headless
15
+ └── claude-in-chrome (Extension) — fallback visual, coordenadas de tela
16
+ ```
17
+
18
+ **Prioridade de tooling:** CDP > dev-browser > claude-in-chrome
19
+
20
+ **Auto-launch:** Hook PreToolUse roda `chrome-ensure` antes de qualquer tool chrome.
21
+ Nao precisa rodar `chrome-debug` manualmente.
22
+
23
+ ---
24
+
25
+ ## Decisao de Tooling
26
+
27
+ | Cenario | Ferramenta |
28
+ |---------|-----------|
29
+ | Click, fill, navegar | Chrome DevTools MCP |
30
+ | Screenshot/snapshot | Chrome DevTools MCP |
31
+ | Performance/Lighthouse | Chrome DevTools MCP |
32
+ | Network/Console | Chrome DevTools MCP |
33
+ | Scraping com logica JS | dev-browser evaluate() |
34
+ | Batch/loops | dev-browser |
35
+ | Headless | dev-browser --headless |
36
+ | Iframe cross-origin | claude-in-chrome ou CDP Input.dispatchMouseEvent |
37
+ | CAPTCHA | CDP mouse events no iframe (funciona cross-origin) |
38
+
39
+ ---
40
+
41
+ ## Patterns Validados
42
+
43
+ ### Form Filling
44
+
45
+ **Multi-step forms (testado em 9 steps):**
46
+ 1. navigate_page → URL
47
+ 2. click → botao que abre form/modal
48
+ 3. wait_for → form renderizar
49
+ 4. Para cada step: take_snapshot → identificar tipo → fill/click → avancar
50
+ 5. Ultimo step: click enviar
51
+
52
+ **Gotchas:**
53
+ - Sempre take_snapshot ANTES de preencher (mapeia seletores)
54
+ - Email duplicado retorna erro inline — ter fallback
55
+ - `fill` aceita seletor CSS direto
56
+ - Dropdowns: click no dropdown → click na opcao (nao fill)
57
+
58
+ ### Site Cloning
59
+
60
+ **Fase 1 — Captura:**
61
+ 1. navigate_page → URL alvo
62
+ 2. take_screenshot (1 referencia)
63
+ 3. evaluate_script → document.documentElement.outerHTML
64
+ 4. evaluate_script → extrair fontes, cores, layout, breakpoints
65
+ 5. Scroll + screenshot nos pontos criticos (max 3-4)
66
+
67
+ **Fase 2 — Analise:**
68
+ - Identificar stack (Next.js? Vite? React? Vanilla?)
69
+ - Mapear componentes (hero, nav, sections, footer)
70
+ - Identificar animacoes (Three.js, GSAP, CSS, Framer Motion)
71
+ - Identificar assets (modelos 3D, texturas, SVGs, fontes)
72
+
73
+ **Fase 3 — Recriacao:**
74
+ 1. HTML single-file (inline CSS + JS)
75
+ 2. Clonar shaders se WebGL
76
+ 3. Testar em nova aba → comparar com original → iterar
77
+
78
+ **Casos validados:**
79
+ - itsoffbrand.com hero (orb WebGL, parallax, blend-mode) — 15min
80
+ - sinapse.club face 3D (Three.js r183, WaltHead.obj, bloom) — 20min
81
+
82
+ ### Animacoes 3D via AI
83
+
84
+ Workflow: navigate Gemini → prompt descritivo → aguardar geracao →
85
+ evaluate_script extrair HTML → salvar arquivo → abrir em nova aba → validar
86
+
87
+ ### CAPTCHA
88
+
89
+ | Estrategia | Resultado |
90
+ |-----------|----------|
91
+ | CDP Input.dispatchMouseEvent em iframe | FUNCIONA (bypassa cross-origin) |
92
+ | evaluate_script em iframe CAPTCHA | NAO FUNCIONA (same-origin policy) |
93
+ | Audio challenge reCAPTCHA | PENDENTE (promissor) |
94
+ | Continue with Google | PENDENTE (pula CAPTCHA se logado) |
95
+
96
+ **IMPORTANTE:** Apos 3-4 resolucoes corretas, Google detecta automacao e entra
97
+ em loop. Parar e mudar estrategia. Nao insistir.
98
+
99
+ ---
100
+
101
+ ## NSN Mode — Nunca Diga Nunca
102
+
103
+ **Protocolo ativo em TODOS os agents com Chrome Brain.**
104
+
105
+ Quando encontrar barreira:
106
+ 1. **Classificar** — permission? technical? knowledge? external?
107
+ 2. **Buscar** — WebSearch/WebFetch por workaround/solucao
108
+ 3. **Tentar alternativas** — minimo 3 abordagens diferentes
109
+ 4. **Configurar e testar** — instalar deps, ajustar permissoes, validar
110
+ 5. **Repetir** — voltar ao passo 2 com novo contexto (max 5 ciclos)
111
+ 6. **Escalar** — apos 5 falhas, reportar ao usuario com detalhes
112
+
113
+ **Anti-patterns:**
114
+ - NUNCA dizer "nao consigo" sem ter tentado alternativas
115
+ - NUNCA parar no primeiro erro
116
+ - NUNCA assumir que algo e impossivel sem pesquisar
117
+ - NUNCA pedir pro usuario fazer algo que o agent pode automatizar
118
+
119
+ **Excecoes:** acoes destrutivas, pagamentos, violacao de leis → pedir confirmacao
120
+
121
+ ---
122
+
123
+ ## Session Management
124
+
125
+ **Limites (prevencao de crash):**
126
+ - Max 15 screenshots por sessao
127
+ - Max 10 snapshots por sessao
128
+ - Preferir evaluate_script sobre take_snapshot (mais leve)
129
+ - Nunca screenshot + snapshot do mesmo estado
130
+ - Fechar tabs desnecessarias
131
+ - Salvar outputs em arquivo ANTES de acumular mais
132
+
133
+ **Rotacao:** A cada ~12 screenshots, salvar handoff e sugerir nova sessao.
134
+
135
+ ---
136
+
137
+ ## Learnings Log
138
+
139
+ > Secao atualizada automaticamente quando NSN Mode resolve problemas novos.
140
+ > Formato: data, barreira, tentativas, solucao, generalizavel, squad.
141
+
142
+ ### 2026-03-27 — CAPTCHA reCAPTCHA via CDP
143
+ **Barreira:** Iframe cross-origin do Google bloqueia evaluate_script
144
+ **Tentativas:** evaluate_script (falhou) → cliclick (precisa permissao) → AppleScript (precisa permissao)
145
+ **Solucao:** CDP Input.dispatchMouseEvent com coordenadas calculadas a partir da posicao do iframe
146
+ **Generalizavel:** Sim — qualquer iframe cross-origin pode ser interagido via CDP raw events
147
+ **Squad afetada:** Todas (form filling, signup flows)
148
+
149
+ ### 2026-03-27 — Chrome normal vs debug profile
150
+ **Barreira:** chrome-ensure matava o Chrome normal do usuario
151
+ **Tentativas:** pkill generico (matava tudo)
152
+ **Solucao:** pgrep -f "user-data-dir=$PROFILE" — mata apenas instancias do debug profile
153
+ **Generalizavel:** Sim — pattern para convivencia Chrome normal + debug
154
+ **Squad afetada:** Todas
155
+
156
+ ### 2026-03-27 — Session crash por acumulo de screenshots (65MB)
157
+ **Barreira:** 46 screenshots + 31 snapshots = 31.8 MB de imagens, request excedeu 20MB
158
+ **Tentativas:** N/A (crash irrecuperavel)
159
+ **Solucao:** Limitar a 15 screenshots/sessao, preferir evaluate_script, rotacionar sessoes
160
+ **Generalizavel:** Sim — regra universal para qualquer sessao com browser automation
161
+ **Squad afetada:** Todas
@@ -0,0 +1,56 @@
1
+ # Chrome Brain — Auto-Activation & Auto-Learning Rule
2
+
3
+ > CRITICAL: This capability auto-activates and auto-learns. No command needed.
4
+
5
+ ## Auto-Activation
6
+
7
+ When the user's prompt matches ANY of these patterns, Chrome Brain is active:
8
+
9
+ - **Browser**: abrir/navegar/acessar site, URL, pagina, chrome, aba
10
+ - **Cloning**: clonar/replicar/copiar site, pagina, hero, layout, animacao
11
+ - **Forms**: preencher/cadastrar/signup/login formulario, form, conta
12
+ - **Audit**: auditar/analisar/inspecionar site, performance, Lighthouse
13
+ - **Scraping**: extrair/scrape/coletar dados, conteudo, HTML, CSS
14
+ - **Animation**: animacao 3D, Three.js, WebGL, shader, canvas
15
+
16
+ ## Protocol
17
+
18
+ 1. Chrome connection is guaranteed by PreToolUse hook (chrome-ensure)
19
+ 2. Select tooling: CDP > dev-browser > claude-in-chrome
20
+ 3. Execute with NSN Mode enabled (never say "I can't" — try 3+ alternatives)
21
+ 4. Track screenshot count — max 15 per session
22
+ 5. Handoff results to domain squad when applicable
23
+
24
+ ## Auto-Learning — MANDATORY
25
+
26
+ After completing ANY browser automation task, evaluate:
27
+
28
+ 1. **Did something unexpected happen?** (error, workaround, new pattern)
29
+ 2. **Did NSN Mode activate?** (barrier encountered and resolved)
30
+ 3. **Is the solution generalizable?** (useful for future sessions)
31
+
32
+ If YES to any:
33
+ - Append the learning to the `## Learnings Log` section in:
34
+ `~/.sinapse/sinapse/knowledge-base/chrome-brain.md`
35
+ - Format:
36
+ ```
37
+ ### YYYY-MM-DD — [Summary]
38
+ **Barreira:** [description]
39
+ **Tentativas:** [what was tried]
40
+ **Solucao:** [what worked]
41
+ **Generalizavel:** sim/nao
42
+ **Squad afetada:** [which]
43
+ ```
44
+
45
+ This ensures every session makes the next session smarter.
46
+
47
+ ## Session Management
48
+
49
+ Track screenshots mentally. When approaching 12:
50
+ 1. Save current state to handoff file
51
+ 2. Suggest session rotation to user
52
+ 3. Never exceed 15 screenshots in a single session
53
+
54
+ ## Knowledge Base
55
+
56
+ Full reference: `~/.sinapse/sinapse/knowledge-base/chrome-brain.md`
@@ -0,0 +1,67 @@
1
+ #!/bin/bash
2
+ # ============================================================================
3
+ # chrome-brain-log — Session logger for Chrome Brain
4
+ # ============================================================================
5
+ # Called by PostToolUse hook. Logs tool usage and tracks screenshot count.
6
+ # Cross-platform: macOS, Linux, Windows (Git Bash / MSYS2).
7
+ #
8
+ # Environment:
9
+ # HOOK_TOOL_NAME — Name of the tool that was used (set by Claude Code)
10
+ #
11
+ # Behavior:
12
+ # - Logs tool name + timestamp to ~/.chrome-brain/session-YYYYMMDD.log
13
+ # - Tracks screenshot count in ~/.chrome-brain/.screenshot-count
14
+ # - WARNING at 12 screenshots, CRITICAL at 15
15
+ # - ALWAYS exits 0 (never blocks the tool pipeline)
16
+ #
17
+ # Usage: chrome-brain-log
18
+ # ============================================================================
19
+
20
+ # IMPORTANT: No set -e here. This script must NEVER fail or block the tool.
21
+
22
+ LOG_DIR="$HOME/.chrome-brain"
23
+ TODAY="$(date +%Y%m%d)"
24
+ LOG_FILE="$LOG_DIR/session-${TODAY}.log"
25
+ COUNTER_FILE="$LOG_DIR/.screenshot-count"
26
+
27
+ # Ensure log directory exists
28
+ mkdir -p "$LOG_DIR" 2>/dev/null || true
29
+
30
+ # ----------------------------------------------------------------------------
31
+ # Read tool name from environment
32
+ # ----------------------------------------------------------------------------
33
+ TOOL_NAME="${HOOK_TOOL_NAME:-unknown}"
34
+ TIMESTAMP="$(date +%H:%M:%S)"
35
+
36
+ # ----------------------------------------------------------------------------
37
+ # Append to session log
38
+ # ----------------------------------------------------------------------------
39
+ echo "$TIMESTAMP $TOOL_NAME" >> "$LOG_FILE" 2>/dev/null || true
40
+
41
+ # ----------------------------------------------------------------------------
42
+ # Track screenshot count and emit warnings
43
+ # ----------------------------------------------------------------------------
44
+ if echo "$TOOL_NAME" | grep -qE "take_screenshot|take_snapshot|screenshot"; then
45
+ # Read current count (default 0 if file missing or unreadable)
46
+ COUNT="$(cat "$COUNTER_FILE" 2>/dev/null)" || COUNT=0
47
+
48
+ # Validate that COUNT is numeric
49
+ case "$COUNT" in
50
+ ''|*[!0-9]*) COUNT=0 ;;
51
+ esac
52
+
53
+ COUNT=$((COUNT + 1))
54
+
55
+ # Write updated count
56
+ echo "$COUNT" > "$COUNTER_FILE" 2>/dev/null || true
57
+
58
+ # Emit warnings at thresholds
59
+ if [ "$COUNT" -ge 15 ]; then
60
+ echo "CRITICAL: ${COUNT} screenshots in this session. Session at risk of exceeding 20MB API limit. Save state NOW." >&2
61
+ elif [ "$COUNT" -ge 12 ]; then
62
+ echo "WARNING: ${COUNT} screenshots in this session. Consider saving state and rotating." >&2
63
+ fi
64
+ fi
65
+
66
+ # Always exit 0 — never block the tool pipeline
67
+ exit 0
@@ -0,0 +1,232 @@
1
+ #!/bin/bash
2
+ # ============================================================================
3
+ # chrome-debug — Manual Chrome debug launch
4
+ # ============================================================================
5
+ # For users to run directly when they want to start/restart the debug session.
6
+ # Cross-platform: macOS, Linux, Windows (Git Bash / MSYS2).
7
+ #
8
+ # Usage: chrome-debug [PORT]
9
+ # PORT defaults to 9222
10
+ #
11
+ # Behavior:
12
+ # 1. If Chrome debug is already running, exits early (no-op)
13
+ # 2. Kills only debug-profile Chrome instances (never the user's browser)
14
+ # 3. Launches Chrome with remote debugging flags
15
+ # 4. Waits for startup and reports result
16
+ #
17
+ # Exit codes:
18
+ # 0 — Chrome debug is running
19
+ # 1 — Failed to start Chrome debug
20
+ # ============================================================================
21
+ set -e
22
+
23
+ PORT="${1:-9222}"
24
+ CHROME_DEBUG_PROFILE="$HOME/.chrome-debug-profile"
25
+ CDP="http://127.0.0.1:$PORT/json/version"
26
+ MAX_WAIT=15 # seconds (more generous for manual use)
27
+
28
+ # Colors (only when stdout is a terminal)
29
+ if [ -t 1 ]; then
30
+ GREEN='\033[0;32m'
31
+ RED='\033[0;31m'
32
+ YELLOW='\033[1;33m'
33
+ CYAN='\033[0;36m'
34
+ NC='\033[0m'
35
+ else
36
+ GREEN='' RED='' YELLOW='' CYAN='' NC=''
37
+ fi
38
+
39
+ # ----------------------------------------------------------------------------
40
+ # Detect OS
41
+ # ----------------------------------------------------------------------------
42
+ UNAME="$(uname -s)"
43
+ case "$UNAME" in
44
+ Darwin) OS="macos" ;;
45
+ Linux) OS="linux" ;;
46
+ MINGW*|MSYS*|CYGWIN*) OS="windows" ;;
47
+ *)
48
+ echo -e "${RED}ERROR: Unsupported OS: $UNAME${NC}" >&2
49
+ exit 1
50
+ ;;
51
+ esac
52
+
53
+ # ----------------------------------------------------------------------------
54
+ # Locate Chrome binary
55
+ # ----------------------------------------------------------------------------
56
+ find_chrome() {
57
+ case "$OS" in
58
+ macos)
59
+ local chrome_path="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
60
+ if [ -x "$chrome_path" ]; then
61
+ echo "$chrome_path"
62
+ return 0
63
+ fi
64
+ ;;
65
+ linux)
66
+ for cmd in google-chrome google-chrome-stable chromium-browser chromium; do
67
+ if command -v "$cmd" &>/dev/null; then
68
+ command -v "$cmd"
69
+ return 0
70
+ fi
71
+ done
72
+ ;;
73
+ windows)
74
+ local local_app_data=""
75
+ if [ -n "$LOCALAPPDATA" ]; then
76
+ local_app_data="$(cygpath -u "$LOCALAPPDATA" 2>/dev/null || echo "")"
77
+ fi
78
+ for chrome_path in \
79
+ "/c/Program Files/Google/Chrome/Application/chrome.exe" \
80
+ "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" \
81
+ "${local_app_data:+$local_app_data/Google/Chrome/Application/chrome.exe}"; do
82
+ [ -z "$chrome_path" ] && continue
83
+ if [ -f "$chrome_path" ]; then
84
+ echo "$chrome_path"
85
+ return 0
86
+ fi
87
+ done
88
+ local win_path
89
+ win_path="$(cmd.exe /c "where chrome.exe" 2>/dev/null | tr -d '\r' | head -1)" || true
90
+ if [ -n "$win_path" ]; then
91
+ echo "$win_path"
92
+ return 0
93
+ fi
94
+ ;;
95
+ esac
96
+ return 1
97
+ }
98
+
99
+ # ----------------------------------------------------------------------------
100
+ # Check if Chrome debug is reachable via CDP
101
+ # ----------------------------------------------------------------------------
102
+ check_cdp() {
103
+ curl -sf "$CDP" -o /dev/null --max-time 1 2>/dev/null
104
+ }
105
+
106
+ # ----------------------------------------------------------------------------
107
+ # Kill only debug-profile Chrome instances
108
+ # ----------------------------------------------------------------------------
109
+ kill_debug_chrome() {
110
+ echo -e "${YELLOW}Stopping existing debug-profile Chrome instances...${NC}"
111
+ case "$OS" in
112
+ macos|linux)
113
+ local pids
114
+ pids="$(pgrep -f "user-data-dir=$CHROME_DEBUG_PROFILE" 2>/dev/null)" || true
115
+ if [ -n "$pids" ]; then
116
+ echo "$pids" | xargs kill 2>/dev/null || true
117
+ sleep 2
118
+ echo -e " ${GREEN}Stopped${NC}"
119
+ else
120
+ echo -e " ${CYAN}No debug instances found${NC}"
121
+ fi
122
+ ;;
123
+ windows)
124
+ local killed=0
125
+ powershell.exe -NoProfile -Command "
126
+ Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" |
127
+ Where-Object { \$_.CommandLine -like '*user-data-dir=*chrome-debug-profile*' } |
128
+ ForEach-Object { Stop-Process -Id \$_.ProcessId -Force -ErrorAction SilentlyContinue }
129
+ " &>/dev/null && killed=1 || true
130
+ if [ "$killed" -eq 1 ]; then
131
+ sleep 2
132
+ echo -e " ${GREEN}Stopped${NC}"
133
+ else
134
+ echo -e " ${CYAN}No debug instances found${NC}"
135
+ fi
136
+ ;;
137
+ esac
138
+ }
139
+
140
+ # ============================================================================
141
+ # Main
142
+ # ============================================================================
143
+
144
+ echo -e "${CYAN}Chrome Debug Launcher${NC}"
145
+ echo -e " Port: $PORT"
146
+ echo -e " Profile: $CHROME_DEBUG_PROFILE"
147
+ echo -e " OS: $OS"
148
+ echo ""
149
+
150
+ # Step 1: Check if already running
151
+ if check_cdp; then
152
+ echo -e "${GREEN}Chrome debug already running on port $PORT${NC}"
153
+ # Show version info
154
+ local_version="$(curl -sf "$CDP" --max-time 2 2>/dev/null)" || true
155
+ if [ -n "$local_version" ]; then
156
+ echo -e " $(echo "$local_version" | grep -o '"Browser":"[^"]*"' 2>/dev/null || true)"
157
+ fi
158
+ exit 0
159
+ fi
160
+
161
+ # Step 2: Find Chrome
162
+ CHROME_BIN="$(find_chrome)" || {
163
+ echo -e "${RED}ERROR: Google Chrome not found.${NC}" >&2
164
+ echo "" >&2
165
+ echo "Install Chrome from: https://www.google.com/chrome/" >&2
166
+ case "$OS" in
167
+ linux)
168
+ echo "Or try: sudo apt install google-chrome-stable" >&2
169
+ echo " or: sudo snap install chromium" >&2
170
+ ;;
171
+ esac
172
+ exit 1
173
+ }
174
+ echo -e " Chrome: $CHROME_BIN"
175
+
176
+ # Step 3: Kill stale debug-profile instances
177
+ kill_debug_chrome
178
+
179
+ # Step 4: Launch Chrome
180
+ echo -e "${CYAN}Launching Chrome with remote debugging on port $PORT...${NC}"
181
+
182
+ case "$OS" in
183
+ macos|linux)
184
+ "$CHROME_BIN" \
185
+ --remote-debugging-port="$PORT" \
186
+ --user-data-dir="$CHROME_DEBUG_PROFILE" \
187
+ --no-first-run \
188
+ &>/dev/null &
189
+ ;;
190
+ windows)
191
+ start "" "$CHROME_BIN" \
192
+ --remote-debugging-port="$PORT" \
193
+ --user-data-dir="$CHROME_DEBUG_PROFILE" \
194
+ --no-first-run \
195
+ &>/dev/null 2>&1 || \
196
+ "$CHROME_BIN" \
197
+ --remote-debugging-port="$PORT" \
198
+ --user-data-dir="$CHROME_DEBUG_PROFILE" \
199
+ --no-first-run \
200
+ &>/dev/null &
201
+ ;;
202
+ esac
203
+
204
+ # Step 5: Wait for Chrome to become reachable
205
+ echo -n " Waiting"
206
+ elapsed=0
207
+ while [ "$elapsed" -lt "$MAX_WAIT" ]; do
208
+ if check_cdp; then
209
+ echo ""
210
+ echo -e "${GREEN}Chrome debug ready on port $PORT${NC}"
211
+ local_version="$(curl -sf "$CDP" --max-time 2 2>/dev/null)" || true
212
+ if [ -n "$local_version" ]; then
213
+ echo -e " $(echo "$local_version" | grep -o '"Browser":"[^"]*"' 2>/dev/null || true)"
214
+ fi
215
+ echo ""
216
+ echo -e " CDP endpoint: $CDP"
217
+ echo -e " DevTools: http://127.0.0.1:$PORT"
218
+ exit 0
219
+ fi
220
+ echo -n "."
221
+ sleep 1
222
+ elapsed=$((elapsed + 1))
223
+ done
224
+
225
+ echo ""
226
+ echo -e "${RED}ERROR: Chrome failed to start with debugging after ${MAX_WAIT}s${NC}" >&2
227
+ echo "" >&2
228
+ echo "Troubleshooting:" >&2
229
+ echo " 1. Close all Chrome windows and try again" >&2
230
+ echo " 2. Delete the debug profile: rm -rf $CHROME_DEBUG_PROFILE" >&2
231
+ echo " 3. Check if port $PORT is in use by another process" >&2
232
+ exit 1