opencode-apex 0.2.0 → 0.2.2

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/docs/BROWSER.md CHANGED
@@ -1,226 +1,253 @@
1
- # Módulo browser — las tools `browser.*` contra un Chromium externo
1
+ # Browser module — drive an external Chromium with OpenCode's `browser` tools
2
2
 
3
- El plugin-browser del host ya registra 45 tools `browser.*` (`tabs.open`,
4
- `snapshot`, `click`, `evaluate`…). Su `connection.ts` mantiene un
5
- `Map<sessionID, Attachment>` que **solo se llena con un `attach`**. En un
6
- servidor sin la app de escritorio ese mapa está vacío y todas las tools fallan
7
- con:
3
+ > **OpenCode V2 only (2.1 or newer).** OpenCode V1 has a different plugin system and
4
+ > cannot load apex.
5
+
6
+ ## The problem it solves
7
+
8
+ OpenCode V2 ships a set of **browser tools** — open a tab, take a snapshot of the page,
9
+ click, fill a form, read the console, and so on (45 operations). The agent sees them as
10
+ `browser_tabs_open`, `browser_snapshot`, `browser_click`… (in Code Mode, as
11
+ `tools.browser.tabs.open(…)`, `tools.browser.snapshot(…)`…).
12
+
13
+ Out of the box those tools need a **browser attached to the session**, and only the
14
+ OpenCode **desktop app** attaches one: it has a built-in browser pane. On a headless
15
+ server, in the terminal UI, or when you simply want the agent to use *your* Chrome,
16
+ nothing is attached and every browser tool fails with:
8
17
 
9
18
  ```
10
19
  [browser.disconnected] No desktop browser is connected to this session.
11
20
  ```
12
21
 
13
- Este módulo llena ese mapa. No sustituye ninguna tool ni pisa ningún RPC: los
14
- nombres, schemas, permisos y descripciones siguen siendo los del host.
22
+ The browser module attaches a **Chromium-based browser of your choice** (Chrome,
23
+ Chromium, Edge, Brave…) instead. It talks to that browser over the **Chrome DevTools
24
+ Protocol (CDP)**: a WebSocket interface Chromium exposes when remote debugging is
25
+ enabled, the same one DevTools and Puppeteer use.
15
26
 
16
- ## Cómo funciona
27
+ It does not replace or wrap any OpenCode tool: names, input schemas, permissions and
28
+ descriptions are still OpenCode's own. apex only provides the browser behind them.
17
29
 
18
- Es el mismo cliente CDP que el proyecto `oc-browser-bridge` hacía por HTTP, pero
19
- las cuatro llamadas que allí eran cable ahora son funciones dentro del proceso:
30
+ ## Quick start
20
31
 
21
- | Fuera del proceso (bridge) | Dentro (este módulo) |
22
- | ----------------------------------------- | ----------------------------------------------- |
23
- | `POST /api/rpc/…/attach` | `ctx.rpc(Browser.Definition).attach(…)` |
24
- | `GET /api/event` (SSE) | `ctx.event.subscribe()` |
25
- | `POST …/command` | `ctx.rpc(…).command(…)` |
26
- | `POST …/result` | `ctx.rpc(…).result(…)` |
27
- | WebSocket CDP | **igual** (lo único que no cambia) |
32
+ 1. Start a Chromium with remote debugging on a port, using its **own** profile directory
33
+ (see [Chrome's two remote-debugging modes](#chromes-two-remote-debugging-modes) for
34
+ why):
28
35
 
29
- El CDP se conecta **una vez** y se mantiene abierto. Eso importa: el modo toggle
30
- de Chrome abre un popup de consentimiento *por conexión*, así que reconectar
31
- por comando es justo lo que hay que evitar.
36
+ ```bash
37
+ google-chrome --remote-debugging-port=9333 --user-data-dir="$HOME/.cache/apex-chrome"
38
+ ```
32
39
 
33
- Y el enganche solo ocurre **a petición**: con `browser.target` (el agente) o
34
- `/browser-target` (el usuario). Antes iba en un hook `execute.before`, que
35
- reintentaba el connect en *cada* tool call: con el destino caído eran hasta 90 s
36
- de bloqueo por invocación, y con el toggle de Chrome un popup en la primera tool
37
- que no era ni del navegador. Pedirlo otra vez no reinicia la conexión: si la
38
- sesión ya está enganchada, no hace nada.
40
+ Port 9333 rather than the usual 9222: a stale `DevToolsActivePort` file from your
41
+ everyday Chrome often still claims 9222.
39
42
 
40
- ## Elegir navegador: la tool y el comando
43
+ 2. Make sure the module is on (it is by default) and point it at that port:
41
44
 
42
- El protocolo admite **un attachment por sesión**:
45
+ ```jsonc
46
+ // in the apex options (see docs/CONFIG.md)
47
+ {
48
+ "modules": { "browser": true },
49
+ "browser": { "mode": "external", "cdpUrl": "9333" }
50
+ }
51
+ ```
43
52
 
44
- ```typescript
45
- // packages/plugin-browser/src/connection.ts:59
46
- yield* close(input.sessionID, "replaced")
47
- ```
53
+ 3. In a session, **ask for the browser once**:
54
+ - the agent calls the `browser_target` tool, for example `browser_target({ mode: "external" })`;
55
+ - or you type the command `/browser-target external`.
48
56
 
49
- El plugin y la app Electron **nunca** sirven la misma sesión a la vez. Por eso
50
- "cambiar de navegador" no es cambiar de transporte: es decidir **quién se
51
- engancha**.
57
+ From then on that session's browser tools run against your Chromium.
52
58
 
53
- | Modo | El plugin hace `attach` | Quién sirve `browser.*` |
54
- | ---------- | ----------------------- | ------------------------------------------------ |
55
- | `in-app` | no, y suelta el que haya | la app de escritorio |
56
- | `external` | sí, al pedirlo | este plugin; la app recibe `browser.pane.replaced` |
57
- | `auto` | sí, al pedirlo | el que llegue primero |
59
+ Nothing attaches until step 3. Loading the plugin never opens a connection by itself,
60
+ so it never triggers an unexpected "Allow remote debugging?" prompt.
58
61
 
59
- Se cambia en caliente, sin recargar:
62
+ ## Choosing who serves the browser
60
63
 
61
- - **Agente**: `browser.target({ mode: "external" \| "in-app" \| "auto" })`
62
- - **Usuario**: `/browser-target external` (o `in-app`, `auto`)
64
+ OpenCode allows **one browser attachment per session**: a new attachment replaces the
65
+ previous one. So apex and the desktop app never serve the same session at the same
66
+ time, and "choosing a browser" really means choosing **who attaches**:
63
67
 
64
- Precedencia: tool/comando > config > `auto`.
68
+ | Mode | What apex does | Who serves the browser tools |
69
+ | --- | --- | --- |
70
+ | `in-app` | never attaches, and releases any attachment it holds in that session | the desktop app's built-in browser |
71
+ | `external` | attaches when asked (tool or command) | apex, with your Chromium; the desktop app is told its pane was replaced |
72
+ | `auto` (default) | nothing until asked; once asked, the same as `external` | apex, after the first request |
65
73
 
66
- `auto` es el default a propósito: no hace nada hasta que alguien lo pide, así
67
- que cargar el plugin no abre un popup de Chrome sin avisar.
74
+ You can switch at any time without reloading anything:
68
75
 
69
- ## Definir la URL de destino
76
+ - **Agent:** `browser_target({ mode: "external" | "in-app" | "auto" })`
77
+ - **You:** `/browser-target external` (or `in-app`, `auto`)
70
78
 
71
- Las dos vías, con la tool por encima de la config.
79
+ The mode set by the tool or the command wins over the config value, until the plugin
80
+ reloads.
72
81
 
73
- **En la config** (el destino por defecto):
82
+ Asking again in a session that is already attached does nothing: the connection is
83
+ **not** restarted. After an attachment is replaced (for example the desktop app took the
84
+ session), apex re-attaches by itself after `reconnectSeconds` unless the mode is `in-app`.
85
+
86
+ ## Choosing where the browser is
87
+
88
+ The destination can come from the config (the default) or from the tool or command at
89
+ run time; run-time values win.
90
+
91
+ **Config:**
74
92
 
75
93
  ```jsonc
76
94
  "browser": {
77
95
  "mode": "external",
78
- "cdpUrl": "auto", // "auto" | "9222" | "ws://host:puerto/ruta" | "wss://…"
79
- "profile": "", // ruta del user-data dir; gana sobre cdpUrl
80
- "headers": {}, // auth para un proxy delante de un wss://
81
- "caFile": "", "insecureSkipVerify": false
96
+ "cdpUrl": "auto", // "auto" | a port like "9222" | "ws://host:port/path" | "wss://…"
97
+ "profile": "", // a Chromium user-data directory; wins over cdpUrl
98
+ "headers": {}, // extra headers for a wss:// endpoint behind a proxy
99
+ "caFile": "", // CA certificate for that proxy
100
+ "insecureSkipVerify": false
82
101
  }
83
102
  ```
84
103
 
85
- **En caliente**, con la tool o el comando:
104
+ **At run time:**
86
105
 
87
106
  ```
88
- browser.target({ mode: "external", cdpUrl: "9333" })
89
- browser.target({ mode: "external", cdpUrl: "wss://tunnel.example/devtools" })
90
- browser.target({ mode: "external", profile: "~/.config/google-chrome" })
107
+ browser_target({ mode: "external", cdpUrl: "9333" })
108
+ browser_target({ mode: "external", cdpUrl: "wss://tunnel.example/devtools" })
109
+ browser_target({ mode: "external", profile: "/home/you/.config/google-chrome" })
91
110
 
92
111
  /browser-target external 9333
93
112
  /browser-target external wss://tunnel.example/devtools
94
- /browser-target external ~/.config/google-chrome
113
+ /browser-target external /home/you/.config/google-chrome
95
114
  ```
96
115
 
97
- - Un destino que empieza por `/` o `~` se interpreta como **perfil**; el resto,
98
- como **URL o puerto**.
99
- - Omitir el destino no lo cambia: hay que pasarlo explícitamente.
100
- - `profile: ""` (o un destino de tipo URL) vuelve a la detección por `cdpUrl`.
116
+ - In the command, a destination starting with `/` or `~` is read as a **profile
117
+ directory**; anything else as a **URL or port**.
118
+ - Leaving the destination out keeps the current one.
119
+ - `profile: ""` goes back to discovery through `cdpUrl`.
120
+ - Profile paths may start with `~/` (your home directory), e.g. `~/.config/google-chrome`.
101
121
 
102
- Cambiar el destino **cierra el socket CDP y suelta los attachments**; la sesión
103
- que lo cambió se reengancha en la misma llamada y las demás tienen que pedirlo
104
- de nuevo con `browser.target`. Hace falta porque los recursos de cada sesión (el
105
- `TabRegistry` con sus sessionIds, los colectores con sus buffers) están atados al
106
- socket viejo.
122
+ **How `cdpUrl` is resolved:**
107
123
 
108
- Un detalle que no es obvio: soltar el attachment exige **interrumpir la fibra** del
109
- `attach`, no solo olvidarla. El attachment vive en el scope de esa llamada
110
- (`connection.ts:76`); si solo se limpia el estado local, el servidor sigue creyendo
111
- que tenemos el navegador y manda comandos a un Chromium que ya no controlamos.
124
+ | Value | What happens |
125
+ | --- | --- |
126
+ | `ws://…` / `wss://…` | used as is (a remote browser, usually behind a tunnel or proxy) |
127
+ | `profile` set | reads that profile's `DevToolsActivePort` file (written by Chrome while remote debugging is on) |
128
+ | `auto` | reads `DevToolsActivePort` from known Linux profiles under `~/.config` (Chrome, Chromium, Edge, Brave, BrowserOS, the OpenCode desktop app), preferring port 9222 |
129
+ | a port (`9222`) or `http://host:port` | finds the profile that declares that port, or falls back to asking `http://host:port/json/version` |
112
130
 
113
- ### Cuál usar
131
+ When several candidates match, they are tried **in order** and the first one that really
132
+ answers wins. When Chrome closes, it leaves its `DevToolsActivePort` file behind, so
133
+ several profiles can claim the same port while only one is listening.
114
134
 
115
- | Destino | Cómo |
116
- | --- | --- |
117
- | Tu Chrome con el toggle de `chrome://inspect/#remote-debugging` | `profile: "~/.config/google-chrome"` — pide un popup por conexión |
118
- | Un Chromium propio: sin popup y sin depender de nada abierto | `--remote-debugging-port=9222 --user-data-dir=…` y `cdpUrl: "9222"` |
119
- | Otra máquina | `cdpUrl: "wss://…"` detrás de un túnel, más `headers` con su auth |
135
+ Changing the destination **closes the CDP connection and drops every attachment**. The
136
+ session that made the change re-attaches in the same call; other sessions must ask
137
+ again with `browser_target`. This is unavoidable: each session's tab registry and
138
+ console/network buffers are tied to the old connection.
120
139
 
121
- ## Configuración
140
+ ### Which destination to use
122
141
 
123
- ```jsonc
124
- {
125
- "modules": { "browser": true },
126
- "browser": {
127
- "mode": "auto", // in-app | external | auto
128
- "cdpUrl": "auto", // "auto" | "9222" | "ws://…" | "wss://…"
129
- "profile": "", // "" = deducir de DevToolsActivePort
130
- "connectTimeoutMs": 90000,
131
- "reconnectSeconds": 15,
132
- "headers": {}, // para wss:// detrás de un proxy
133
- "caFile": "",
134
- "insecureSkipVerify": false
135
- }
136
- }
137
- ```
142
+ | You want | Do this |
143
+ | --- | --- |
144
+ | A browser just for the agent, no prompts | Start Chromium with `--remote-debugging-port=9333 --user-data-dir=<its own dir>` and set `cdpUrl: "9333"` |
145
+ | Your everyday Chrome, with its logins | Turn on the toggle at `chrome://inspect/#remote-debugging`, then `profile: "/home/you/.config/google-chrome"`. Chrome shows a consent prompt **for every new connection**. |
146
+ | A browser on another machine | Put a tunnel or reverse proxy in front of it and use `cdpUrl: "wss://…"`, with `headers` for its auth |
138
147
 
139
- ## Los dos modos de Chrome (y por qué importan)
148
+ ## Chrome's two remote-debugging modes
140
149
 
141
- | Modo | `/json/version` | Popup | Notas |
142
- | ----------------------------------------- | --------------- | ----- | ----- |
143
- | `--remote-debugging-port` (flag) | 200 | no | **Inerte** sobre el user-data-dir por defecto desde Chrome 136; necesita perfil propio |
144
- | `chrome://inspect/#remote-debugging` (toggle) | **404 por diseño** | **sí, por conexión** | La URL sale de `DevToolsActivePort` |
150
+ | How it is enabled | `GET /json/version` | Consent prompt | Notes |
151
+ | --- | --- | --- | --- |
152
+ | `--remote-debugging-port` flag | 200 | no | Ignored on Chrome's **default** profile since Chrome 136: use a separate `--user-data-dir` |
153
+ | Toggle at `chrome://inspect/#remote-debugging` | **404, by design** | **yes, per connection** | The WebSocket address is read from `DevToolsActivePort` |
145
154
 
146
- Un 404 en `/json/version` no es un error de configuración: es la ruta del toggle.
155
+ A 404 from `/json/version` is not a misconfiguration: it is how the toggle mode works.
147
156
 
148
- **Perfiles stale**: al cerrar Chrome, el `DevToolsActivePort` no se borra. Medido
149
- en esta máquina: `google-chrome`, `chromium` y `browser-os` declaran los tres el
150
- puerto 9222 y solo uno escucha. Por eso los candidatos se prueban **en orden** y
151
- gana el primero que responde de verdad; elegir el primero a ciegas acaba en un
152
- perfil muerto.
157
+ Because the toggle asks for consent **per connection**, apex opens the CDP connection
158
+ **once** and keeps it open. It never reconnects per command.
153
159
 
154
- ## Navegador en otra máquina
160
+ ## A browser on another machine
155
161
 
156
- El CDP nativo de Chrome no habla TLS ni pide cabeceras: expone un websocket en
157
- claro y sin autenticación. Un navegador remoto necesita un túnel o proxy
158
- inverso delante (ssh -L, tailscale, cloudflared, nginx) y aquí apuntar al
159
- `wss://` que publica ese proxy:
162
+ Chrome's native CDP endpoint speaks neither TLS nor authentication: it is a plain,
163
+ unauthenticated WebSocket, and anyone who reaches it controls the browser. **Never
164
+ expose it directly.** Put a tunnel or reverse proxy in front of it (`ssh -L`, Tailscale,
165
+ cloudflared, nginx) and point apex at the `wss://` URL it publishes:
160
166
 
161
167
  ```jsonc
162
- { "browser": { "cdpUrl": "wss://tunnel.example/devtools", "headers": { "Authorization": "Bearer …" } } }
168
+ {
169
+ "browser": {
170
+ "cdpUrl": "wss://tunnel.example/devtools",
171
+ "headers": { "Authorization": "Bearer …" },
172
+ "caFile": "/path/to/ca.pem" // only for a private CA
173
+ }
174
+ }
163
175
  ```
164
176
 
165
- ## Sobre `ai.opencode.desktop`
177
+ `insecureSkipVerify: true` disables certificate checks. Use it only for a quick test.
166
178
 
167
- Los panes del navegador de la app de escritorio usan **particiones efímeras**
168
- (`opencode-browser-<uuid>`), así que no hay un perfil de navegación persistente
169
- que heredar: lo que persiste es el *data dir*.
179
+ ## About the OpenCode desktop app's own profile
170
180
 
171
- Apuntar `profile` a `~/.config/ai.opencode.desktop` **exige que la app Electron
172
- esté cerrada**. Mientras está corriendo mantiene el `SingletonLock` de ese
173
- directorio, y dos procesos sobre el mismo `user-data-dir` corrompen el SQLite de
174
- cookies.
181
+ The desktop app's browser panes use **ephemeral partitions**: there is no persistent
182
+ browsing profile to reuse. Pointing `profile` at the app's data directory
183
+ (`~/.config/ai.opencode.desktop` on Linux) only works with the app **closed**. While it
184
+ runs it holds that directory's lock, and two processes on one user-data directory
185
+ corrupt its cookie database. For daily use, prefer a dedicated profile started with
186
+ `--remote-debugging-port`.
175
187
 
176
- Para uso diario conviene un perfil dedicado con el flag
177
- `--remote-debugging-port`: sin popup y sin depender de que nada más esté abierto.
188
+ ## What is supported
178
189
 
179
- ## Cobertura
190
+ 37 of the 45 browser operations. The other 8 return an `unsupported` error that says
191
+ why, instead of hanging until OpenCode's 60-second command timeout:
180
192
 
181
- 37 de las 45 operaciones. Las 8 restantes devuelven `unsupported` con el motivo,
182
- en vez de colgarse hasta el timeout de 60 s del servidor:
193
+ | Operation | Why not |
194
+ | --- | --- |
195
+ | `preview` | needs the desktop app's Review pane |
196
+ | `trace.analyze`, `cpu.analyze` | they analyze a capture's contents; apex returns the capture file, not an analyzer |
197
+ | `heap.summary`, `heap.query`, `heap.object`, `heap.compare` | same: the heap snapshot file is returned, not analyzed |
198
+ | `lighthouse` | needs a Lighthouse runtime, not just CDP |
183
199
 
184
- | Operación | Por qué no |
185
- | -------------------------------------------- | ------------------------------------------------- |
186
- | `preview` | necesita el panel de review de una app de escritorio |
187
- | `trace.analyze`, `cpu.analyze` | analizan el contenido de una captura |
188
- | `heap.summary`, `heap.query`, `heap.object`, `heap.compare` | ídem: el módulo entrega el fichero, no un analizador |
189
- | `lighthouse` | requiere el runtime de Lighthouse |
200
+ Results are capped at **512,000 characters of JSON**, the same limit the desktop app's
201
+ browser applies. A bigger result fails with a message telling the agent what to reduce:
202
+ fewer items, a shallower snapshot, or only the needed fields.
190
203
 
191
- ## Límites del resultado
204
+ ## Configuration reference
192
205
 
193
- El servidor rechaza un resultado de más de **512 000 caracteres JSON**
194
- (`browser-chromium.ts:451`). El módulo lo comprueba antes de responder y, si se
195
- pasa, devuelve un error que dice qué reducir en vez de un fallo opaco.
206
+ ```jsonc
207
+ {
208
+ "modules": { "browser": true }, // on by default
209
+ "browser": {
210
+ "mode": "auto", // in-app | external | auto
211
+ "cdpUrl": "auto", // "auto" | "9222" | "ws://…" | "wss://…"
212
+ "profile": "", // "" = discover through cdpUrl
213
+ "connectTimeoutMs": 90000, // how long one connection attempt may take
214
+ "reconnectSeconds": 15, // wait before re-attaching after being replaced (0 = at once)
215
+ "headers": {}, // for wss:// behind a proxy
216
+ "caFile": "",
217
+ "insecureSkipVerify": false
218
+ }
219
+ }
220
+ ```
196
221
 
197
- ## Probarlo
222
+ ## Testing it
198
223
 
199
224
  ```bash
200
- # Sin popup: un Chromium propio con flag
225
+ # No prompts: a throwaway headless Chromium with the flag
201
226
  chromium --headless=new --remote-debugging-port=9333 --user-data-dir=/tmp/cdp-probe about:blank &
202
227
  TEST_CDP_URL=9333 bun test test/browser.test.ts
203
228
  ```
204
229
 
205
- Con el toggle de Chrome, `TEST_CDP_URL=auto` y hay que aprobar el popup.
206
-
207
- ## Details que-importan (medidos, no deducidos)
208
-
209
- - **El estado se publica antes de responder cada comando**, no por sondeo. El
210
- servidor valida `tabID` contra *su* copia del inventario; sin esto,
211
- `tabs.open` devuelve un id que el servidor todavía no conoce y la siguiente
212
- llamada falla con `tab_unavailable`. El cliente Electron hace lo mismo
213
- (`browser-pane.ts:161-173`).
214
- - **`attach` va antes que `state`**, y `state` se reintenta. `state` exige que el
215
- attachment ya exista (`connection.ts:80`), y el attachment solo se crea dentro
216
- de `attach`, que además no retorna hasta que se cierra.
217
- - **El `sessionId` de tab se cachea.** `Target.attachToTarget` devuelve uno
218
- nuevo en cada llamada; sin cache, cada comando abría una sesión distinta y los
219
- buffers de console/red salían siempre vacíos (medido: 0 mensajes, 0
220
- peticiones).
221
- - **El evento `command` no lleva `sessionID`**, solo `connectionID`. El índice
222
- para mapear un comando a su sesión es sobre `connectionID`.
223
- - **`data` de los ficheros entra como base64** y se decodifica al pasar por el
224
- RPC (`Schema.Uint8ArrayFromBase64`).
225
- - **`evaluate` con `ref` es una función, no una expresión**: se ejecuta con
226
- `Runtime.callFunctionOn` sobre el nodo resuelto.
230
+ With the Chrome toggle instead, use `TEST_CDP_URL=auto` and approve the prompt.
231
+
232
+ ## Implementation notes (measured, not assumed)
233
+
234
+ For contributors. These are the non-obvious details that make the bridge work:
235
+
236
+ - **The tab inventory is published before each command is answered.** OpenCode validates
237
+ `tabID` against *its* copy of the inventory. Without this, `tabs.open` returns an id
238
+ OpenCode does not know yet and the next call fails with `tab_unavailable`. The desktop
239
+ app does the same.
240
+ - **`attach` comes before `state`, and `state` is retried.** OpenCode only accepts
241
+ `state` once the attachment exists, and the attachment is created inside `attach`,
242
+ which does not return until it is closed (it is a long poll).
243
+ - **Releasing an attachment means interrupting the `attach` fiber**, not just forgetting
244
+ it. The attachment lives in that call's scope. Clearing local state alone would leave
245
+ OpenCode sending commands to a browser apex no longer controls.
246
+ - **Tab `sessionId`s are cached.** `Target.attachToTarget` returns a new one on every call.
247
+ Without the cache each command opened a new CDP session, and the console and network
248
+ buffers always came back empty.
249
+ - **The `command` event carries no `sessionID`**, only a `connectionID`, so commands are
250
+ routed by `connectionID`.
251
+ - **File `data` travels as base64** and is decoded by the RPC layer.
252
+ - **`evaluate` with a `ref` is a function, not an expression.** It runs through
253
+ `Runtime.callFunctionOn` on the resolved node.