opencode-apex 0.1.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/browser.ts ADDED
@@ -0,0 +1,556 @@
1
+ /**
2
+ * Módulo `browser` de opencode-apex.
3
+ *
4
+ * QUÉ HACE Y POR QUÉ NO SUSTITUYE NADA
5
+ *
6
+ * El plugin-browser del host publica el RPC `experimental.browser` y sus tools
7
+ * `browser.*`; su `connection.ts` mantiene un `Map<sessionID, Attachment>` que
8
+ * solo se llena con un `attach`. En un servidor sin la app de escritorio ese
9
+ * mapa está vacío y todas las tools fallan con "browser is disconnected".
10
+ *
11
+ * Este módulo llena ese mapa. Es el mismo cliente CDP que `oc-browser-bridge`
12
+ * hacía por HTTP, pero las cuatro llamadas que allí eran cable ahora son
13
+ * funciones dentro del proceso:
14
+ *
15
+ * POST /api/rpc/…/attach → ctx.rpc(Browser.Definition).attach(…)
16
+ * SSE /api/event → ctx.event.subscribe()
17
+ * POST …/command → ctx.rpc(…).command(…)
18
+ * POST …/result → ctx.rpc(…).result(…)
19
+ * WebSocket CDP → IGUAL (lo único que no cambia)
20
+ *
21
+ * No se sustituye el `execute` de las tools ni se pisa el RPC: los nombres,
22
+ * schemas, permisos y descripciones siguen siendo los del host.
23
+ *
24
+ * EL LÍMITE DEL PROTOCOLO
25
+ *
26
+ * `connection.ts:59` hace `close(sessionID, "replaced")` en cada attach, así que
27
+ * solo hay un attachment por sesión y el plugin y la app Electron nunca
28
+ * coexisten en la misma. Por eso "elegir navegador" es elegir QUIÉN se engancha,
29
+ * y de ahí los tres modos: `in-app` no se engancha (y suelta el que haya);
30
+ * `external` y `auto` enganchan solo cuando alguien lo pide — `browser.target`
31
+ * (agente) o `/browser-target` (usuario) —, nunca en cada tool call.
32
+ */
33
+
34
+ import { Cause, Effect, Fiber, Result, Scope as ScopeService, Stream } from "effect"
35
+ import type { Plugin } from "@opencode/plugin/effect"
36
+ import { Browser } from "@opencode/plugin-browser/rpc"
37
+ import { readFileSync } from "node:fs"
38
+ import { CdpClient, CdpError, EventCollector, TabRegistry, type TlsOptions } from "./browser/cdp.js"
39
+ import { executeAction } from "./browser/actions.js"
40
+
41
+ const PROTOCOL_VERSION = 4
42
+ /** Mismo límite que browser-chromium.ts:451. */
43
+ const MAX_RESULT_CHARS = 512_000
44
+
45
+ type Scope = import("effect").Scope.Scope
46
+
47
+ export type BrowserMode = "in-app" | "external" | "auto"
48
+
49
+ export interface BrowserConfigShape {
50
+ enabled: boolean
51
+ mode: BrowserMode
52
+ cdpUrl: string
53
+ profile: string
54
+ connectTimeoutMs: number
55
+ reconnectSeconds: number
56
+ headers: Record<string, string>
57
+ caFile: string
58
+ insecureSkipVerify: boolean
59
+ }
60
+
61
+ export function createDefaultBrowserConfig(): BrowserConfigShape {
62
+ return {
63
+ enabled: true,
64
+ mode: "auto",
65
+ cdpUrl: "auto",
66
+ profile: "",
67
+ connectTimeoutMs: 90_000,
68
+ reconnectSeconds: 15,
69
+ headers: {},
70
+ caFile: "",
71
+ insecureSkipVerify: false,
72
+ }
73
+ }
74
+
75
+ /** El estado del enlace, en los cuatro modos. */
76
+ interface Link {
77
+ cdp: CdpClient | undefined
78
+ error: string | undefined
79
+ pending: Promise<CdpClient> | undefined
80
+ }
81
+
82
+ interface Session {
83
+ connectionID: string
84
+ tabs: TabRegistry
85
+ collectors: EventCollector
86
+ /**
87
+ * La fibra del `attach`. Hace falta para soltarla de verdad: el attachment del
88
+ * servidor vive dentro del scope de esa llamada (connection.ts:76), así que
89
+ * solo se cierra al INTERRUMPIRLA, no con un return.
90
+ */
91
+ fiber: import("effect").Fiber.Fiber<unknown, unknown> | undefined
92
+ }
93
+
94
+ export function register(ctx: Plugin.Context, config: BrowserConfigShape): Effect.Effect<void, never, Scope> {
95
+ return Effect.gen(function* () {
96
+ const rpc = ctx.rpc(Browser.Definition)
97
+ // El scope del plugin, no el de quien llame: la fibra que sostiene el
98
+ // `attach` (un long-poll) debe sobrevivir al comando que la dispara y
99
+ // morir solo cuando el plugin se descarga.
100
+ const pluginScope = yield* Effect.scope
101
+
102
+ // El modo efectivo lo cambia el comando del usuario o la tool del agente;
103
+ // la config es solo el punto de partida.
104
+ const modeState: { current: BrowserMode; source: string } = { current: config.mode, source: "config" }
105
+
106
+ // El destino CDP arranca en la config y lo puede cambiar browser.target en
107
+ // caliente. Se guarda aparte de `config` porque reconectar exige cerrar el
108
+ // socket viejo: si leyéramos `config` en cada intento, un destino distinto
109
+ // no se notaría y seguiríamos hablando con el navegador anterior.
110
+ const target: { cdpUrl: string; profile: string } = { cdpUrl: config.cdpUrl, profile: config.profile }
111
+
112
+ // El CDP se conecta UNA vez y se mantiene vivo. En el modo toggle de Chrome
113
+ // cada conexión abre un popup "Allow remote debugging?", así que reconectar
114
+ // por comando es exactamente lo que hay que evitar.
115
+ const link: Link = { cdp: undefined, error: undefined, pending: undefined }
116
+
117
+ // sessionID → recursos vivos. El TabRegistry mantiene el cache de sessionId
118
+ // por tab y los colectores los buffers de console/red: si se recrearan por
119
+ // comando, cada lectura perdería justo lo que venía a leer.
120
+ const sessions = new Map<string, Session>()
121
+
122
+ const connect: Effect.Effect<CdpClient, Error> = Effect.gen(function* () {
123
+ if (link.cdp) return link.cdp
124
+ // Dos llamadas concurrentes comparten el mismo intento: sin esto, el hook
125
+ // y un comando simultáneo abrirían dos sockets y dos popups.
126
+ if (link.pending) return yield* Effect.promise(() => link.pending as Promise<CdpClient>)
127
+
128
+ const attempt = CdpClient.connect({
129
+ cdpUrl: target.cdpUrl,
130
+ profileDir: target.profile || undefined,
131
+ headers: config.headers,
132
+ tls: tlsOptions(target.cdpUrl, config),
133
+ timeoutMs: config.connectTimeoutMs,
134
+ }).then(
135
+ (client) => {
136
+ link.cdp = client
137
+ link.error = undefined
138
+ link.pending = undefined
139
+ return client
140
+ },
141
+ (error: Error) => {
142
+ link.error = error.message
143
+ link.pending = undefined
144
+ throw error
145
+ },
146
+ )
147
+ link.pending = attempt
148
+ return yield* Effect.promise(() => attempt)
149
+ })
150
+
151
+ /**
152
+ * Suelta el navegador: cierra los attachments y el socket CDP.
153
+ *
154
+ * Necesario al cambiar de destino. Los recursos de cada sesión están atados
155
+ * al socket viejo (TabRegistry con sus sessionIds, colectores con sus
156
+ * buffers), así que reconectar sin tirarlos dejaría un TabRegistry hablando
157
+ * con un socket que ya no existe.
158
+ *
159
+ * Va al final porque se llama desde el `hold`, que se reencamina a sí mismo
160
+ * al reconectar; cerrarlo antes dejaría al `hold` viejo reconectando.
161
+ */
162
+ const disconnect = (sessionID?: string) =>
163
+ Effect.gen(function* () {
164
+ // Hay que interrumpir la fibra del attach, no solo olvidarla: el
165
+ // attachment del servidor se cierra con el scope de esa llamada
166
+ // (connection.ts:76), y sin interrupción el servidor seguiría creyendo
167
+ // que tenemos el navegador —y cualquier tool browser.* seguiría yendo a
168
+ // un Chromium que ya no controlamos.
169
+ const drop = function* (session: Session) {
170
+ session.collectors.dispose()
171
+ if (session.fiber) yield* Fiber.interrupt(session.fiber)
172
+ }
173
+ if (sessionID) {
174
+ const session = sessions.get(sessionID)
175
+ if (!session) return
176
+ yield* drop(session)
177
+ sessions.delete(sessionID)
178
+ return
179
+ }
180
+ for (const session of sessions.values()) yield* drop(session)
181
+ sessions.clear()
182
+ link.cdp?.close()
183
+ link.cdp = undefined
184
+ link.pending = undefined
185
+ link.error = undefined
186
+ })
187
+
188
+ const describe = () => ({
189
+ mode: modeState.current,
190
+ source: modeState.source,
191
+ target: { cdpUrl: target.cdpUrl, profile: target.profile || null },
192
+ connected: link.cdp
193
+ ? {
194
+ profile: link.cdp.endpoint?.profileDir ?? null,
195
+ cdp: link.cdp.endpoint?.webSocketDebuggerUrl ?? null,
196
+ how: link.cdp.endpoint?.how ?? null,
197
+ }
198
+ : null,
199
+ attached: [...sessions.keys()],
200
+ error: link.error ?? null,
201
+ })
202
+
203
+ const stateOf = (tabs: Awaited<ReturnType<TabRegistry["list"]>>): Browser.State => ({
204
+ tabs: tabs.map((t) => ({
205
+ id: t.id as Browser.TabID,
206
+ url: t.url,
207
+ title: t.title,
208
+ loading: false,
209
+ canGoBack: false,
210
+ canGoForward: false,
211
+ generation: t.generation,
212
+ })),
213
+ focusedTabID: (tabs[0]?.id ?? null) as Browser.TabID | null,
214
+ })
215
+
216
+ const runCommand = Effect.fn("apex.browser.command")(function* (
217
+ sessionID: string,
218
+ connectionID: string,
219
+ requestID: string,
220
+ ) {
221
+ const cdp = yield* connect
222
+ // Reutilizamos los recursos del attachment: un TabRegistry nuevo perdería
223
+ // el cache de sessionId por tab y los colectores recargarían sus buffers.
224
+ const live = sessions.get(sessionID)
225
+ const tabs = live?.tabs ?? new TabRegistry(cdp)
226
+ const collectors = live?.collectors ?? new EventCollector(cdp)
227
+
228
+ // Effect.result y no try/catch: un DEFECTO (un throw de JS dentro de
229
+ // Effect.promise) no lo captura el try/catch del generador, se propaga y
230
+ // aquí se lo tragaría la fibra. Con result todo vuelve por el mismo
231
+ // camino y siempre se responde, que es lo que espera el servidor.
232
+ const outcome = yield* Effect.result(
233
+ Effect.gen(function* () {
234
+ const command = yield* rpc.command({ sessionID: sessionID as never, connectionID, requestID })
235
+ const { __file, ...value } = yield* Effect.promise(() =>
236
+ executeAction(command.action, { cdp, tabs, collectors, command }),
237
+ )
238
+ if (JSON.stringify(value).length > MAX_RESULT_CHARS) {
239
+ throw new CdpError(
240
+ `Browser result exceeds ${MAX_RESULT_CHARS} JSON characters. ` +
241
+ `Ask for fewer items, a shallower snapshot, or only the fields you need.`,
242
+ { code: "result_too_large" },
243
+ )
244
+ }
245
+ // El estado se publica ANTES de responder: el servidor acaba de validar
246
+ // el tabID contra su copia del inventario, y abrir una pestaña la
247
+ // devuelve con un id que todavía no conoce. El cliente Electron hace
248
+ // lo mismo (browser-pane.ts:161-173).
249
+ yield* publishState(sessionID, connectionID)
250
+ return {
251
+ type: "success" as const,
252
+ result: {
253
+ value: value as never,
254
+ // `data` entra como base64: Schema.Uint8ArrayFromBase64 lo
255
+ // decodifica al pasar por el RPC, así que aquí van los bytes en b64.
256
+ files: __file
257
+ ? [
258
+ {
259
+ id: `file_${crypto.randomUUID()}` as Browser.FileID,
260
+ name: __file.name,
261
+ mime: __file.mime,
262
+ data: Buffer.from(__file.data).toString("base64"),
263
+ },
264
+ ]
265
+ : [],
266
+ },
267
+ }
268
+ }).pipe(Effect.catchDefect((defect) => Effect.fail(causeOf(defect)))),
269
+ )
270
+
271
+ const failure = Result.isSuccess(outcome)
272
+ ? outcome.success
273
+ : {
274
+ type: "failure" as const,
275
+ code: outcome.failure instanceof CdpError ? outcome.failure.code : "bridge_error",
276
+ message: outcome.failure.message,
277
+ }
278
+
279
+ if (failure.type === "failure") {
280
+ yield* Effect.logWarning(`[apex.browser] comando fallido ${requestID}: ${failure.code} ${failure.message}`)
281
+ }
282
+ yield* rpc
283
+ .result({ sessionID: sessionID as never, connectionID, requestID, outcome: failure as never })
284
+ .pipe(Effect.catch(() => Effect.void))
285
+ })
286
+
287
+ /**
288
+ * Publica el inventario hasta que el servidor lo acepte.
289
+ *
290
+ * `state` exige que el attachment ya exista (connection.ts:80), y el
291
+ * attachment solo se crea dentro de `attach`, que además no retorna hasta
292
+ * que se cierre. Como `attach` va en background, el primer `state` siempre
293
+ * llega antes: hay que reintentarlo hasta que cuaje.
294
+ */
295
+ const publishState = Effect.fn("apex.browser.state")(function* (
296
+ sessionID: string,
297
+ connectionID: string,
298
+ attempts = 5,
299
+ ) {
300
+ for (let attempt = 0; attempt < attempts; attempt++) {
301
+ // El TabRegistry de la sesión, NUNCA uno nuevo: los tabID opencode los
302
+ // genera él y se los recuerda. Un registro distinto inventaría ids
303
+ // distintos para la misma pestaña y el servidor no coincidiría.
304
+ const tabs = sessions.get(sessionID)?.tabs
305
+ if (!tabs) return false
306
+ const list = yield* Effect.promise(() => tabs.list())
307
+ const ok = yield* Effect.result(
308
+ rpc.state({ sessionID: sessionID as never, connectionID, state: stateOf(list) }),
309
+ ).pipe(Effect.map((result) => result._tag === "Success"), Effect.catch(() => Effect.succeed(false)))
310
+ if (ok) return true
311
+ yield* Effect.sleep(`${Math.min(2_000, 100 * 2 ** attempt)} millis`)
312
+ }
313
+ return false
314
+ })
315
+
316
+ // `attach` es un long-poll: no retorna hasta "closed"/"replaced". Se declara
317
+ // aparte de attachSession porque se llama a sí misma al reconectar, y una
318
+ // función recursiva necesita su tipo anotado.
319
+ const hold = (sessionID: string, connectionID: string): Effect.Effect<void, never, Scope> =>
320
+ Effect.gen(function* () {
321
+ const outcome = yield* rpc
322
+ .attach({ sessionID: sessionID as never, connectionID, version: PROTOCOL_VERSION })
323
+ .pipe(Effect.catch((error) => Effect.succeed(`error: ${error.message}`)))
324
+ yield* Effect.logInfo(`[apex.browser] ${sessionID} desenganchado (${outcome})`)
325
+ // Si `disconnect` ya se llevó esta sesión (destino cambiado), sus
326
+ // recursos ya no sirven: no hay nada que reconectar.
327
+ if (sessions.get(sessionID)?.connectionID !== connectionID) return
328
+ // El `replaced` de connection.ts:59 dejó fuera a la app Electron, así
329
+ // que reconectar nosotros es lo que restaura el navegador de la sesión.
330
+ if (modeState.current === "in-app") return
331
+ if (config.reconnectSeconds > 0) yield* Effect.sleep(`${config.reconnectSeconds} second`)
332
+ yield* attachSession(sessionID).pipe(Effect.catch(() => Effect.void))
333
+ })
334
+
335
+ const attachSession = Effect.fn("apex.browser.attach")(function* (sessionID: string) {
336
+ if (modeState.current === "in-app" || sessions.has(sessionID)) return
337
+ const cdp = yield* connect
338
+ const tabs = new TabRegistry(cdp)
339
+ const collectors = new EventCollector(cdp)
340
+ const connectionID = crypto.randomUUID()
341
+
342
+ const session: Session = { connectionID, tabs, collectors, fiber: undefined }
343
+ sessions.set(sessionID, session)
344
+ // El attach va primero (registra el attachment) y el estado detrás, con
345
+ // reintentos hasta que el servidor lo acepte: al revés, `state` siempre
346
+ // fallaría con "unavailable" porque el mapa todavía no tiene la sesión.
347
+ session.fiber = yield* Effect.forkScoped(hold(sessionID, connectionID), { startImmediately: true })
348
+ const ok = yield* publishState(sessionID, connectionID)
349
+ yield* Effect.logInfo(
350
+ `[apex.browser] ${sessionID} ${ok ? "enganchado" : "enganchado sin inventario"} a ${cdp.endpoint?.profileDir ?? cdp.endpoint?.how}`,
351
+ )
352
+ })
353
+
354
+ /**
355
+ * Enganche a petición: solo lo llaman `browser.target` (el agente) y
356
+ * `/browser-target` (el usuario). Antes iba en un hook `execute.before`,
357
+ * que reintentaba el connect en CADA tool call: con el destino caído eran
358
+ * hasta 90 s de bloqueo por invocación, y con el toggle de Chrome un popup
359
+ * en la primera tool que no era ni del navegador.
360
+ */
361
+ const attachFor = Effect.fn("apex.browser.attachFor")(function* (sessionID: string | undefined) {
362
+ if (!sessionID) return
363
+ // in-app no solo no engancha: suelta lo que esta sesión tuviera para que
364
+ // la app de escritorio pueda servirla.
365
+ if (modeState.current === "in-app") {
366
+ yield* disconnect(sessionID)
367
+ return
368
+ }
369
+ // Ya enganchada → nada que hacer: pedirla otra vez NO reinicia el socket.
370
+ if (sessions.has(sessionID)) return
371
+ // Se provee el scope del plugin para que la fibra del `attach` no muera
372
+ // con la llamada que la disparó. El connect falla como DEFECTO (un throw
373
+ // dentro de Effect.promise), así que hacen falta las dos capturas: sin
374
+ // catchDefect el destino caído mata la tool en vez de dejar el error en
375
+ // describe().
376
+ yield* attachSession(sessionID).pipe(
377
+ Effect.provideService(ScopeService.Scope, pluginScope),
378
+ Effect.catch((error: Error) =>
379
+ Effect.logWarning(`[apex.browser] no se pudo conectar al CDP: ${error.message}`).pipe(
380
+ Effect.andThen(Effect.void),
381
+ ),
382
+ ),
383
+ Effect.catchDefect((defect) =>
384
+ Effect.logWarning(`[apex.browser] no se pudo conectar al CDP: ${causeOf(defect).message}`).pipe(
385
+ Effect.andThen(Effect.void),
386
+ ),
387
+ ),
388
+ )
389
+ })
390
+
391
+ // --- control: aquí llegan los comandos -----------------------------------
392
+ yield* ctx.event
393
+ .subscribe()
394
+ .pipe(
395
+ Stream.filter((event) => event.type === "rpc.experimental.browser.control"),
396
+ // El comando se lanza en su propia fibra y el effect del stream termina
397
+ // al instante. Con un mapEffect normal (que espera a que el efecto
398
+ // termine), el segundo comando se queda en el buffer hasta que el
399
+ // primero acaba: el stream es secuencial.
400
+ Stream.mapEffect((event) =>
401
+ Effect.gen(function* () {
402
+ const control = event.data as Browser.Control
403
+ if (control.type !== "command") return
404
+ // El evento `command` no lleva sessionID, solo connectionID: por eso
405
+ // el índice es sobre connectionID.
406
+ const owner = [...sessions].find(([, session]) => session.connectionID === control.connectionID)
407
+ if (!owner) return
408
+ yield* Effect.forkDetach(runCommand(owner[0], control.connectionID, control.requestID))
409
+ }),
410
+ ),
411
+ Stream.runDrain,
412
+ Effect.forkScoped,
413
+ )
414
+
415
+ // --- tool para que el AGENTE elija ---------------------------------------
416
+ yield* ctx.tool
417
+ .transform((editor) => {
418
+ editor.namespace({
419
+ name: "browser",
420
+ description: "Browser control. browser.target chooses between an external Chromium over CDP and the desktop app.",
421
+ })
422
+ editor.add({
423
+ name: "target",
424
+ description:
425
+ "Choose which browser serves this session's browser.* tools, and optionally where to reach it. " +
426
+ "`mode: external` drives a Chromium over CDP and takes the session's attachment, so an opencode desktop " +
427
+ "app on the same session steps aside. `in-app` releases it and lets the desktop app serve. `external` " +
428
+ "and `auto` attach only when asked — by this tool or /browser-target — never on their own. Only one " +
429
+ "client can hold a session's browser at a time; the other has no browser until this changes.\n\n" +
430
+ "Destination (`cdpUrl`, `profile`) is optional and only applies to `external`. Changing it closes the " +
431
+ "current CDP connection and reconnects this session to the new destination; sessions that were " +
432
+ "attached drop and must ask again with this tool. Calling it is also what attaches: a session's " +
433
+ "browser.* only work after this tool or /browser-target has asked for a browser. " +
434
+ "`cdpUrl` is `auto` (read DevToolsActivePort from known profiles), a port like `9222`, or a full " +
435
+ "`ws://`/`wss://` websocket URL for a remote browser behind a tunnel. `profile` is a Chromium user-data " +
436
+ "directory; it wins over `cdpUrl` and requires no remote debugging toggle. Using `external` may raise " +
437
+ "an \"Allow remote debugging?\" prompt in the browser: approve it once, the connection is then kept open.",
438
+ input: {
439
+ mode: {
440
+ type: "string",
441
+ enum: ["external", "in-app", "auto"],
442
+ description: "Which browser should serve browser.* for this session.",
443
+ },
444
+ cdpUrl: {
445
+ type: "string",
446
+ description:
447
+ "Where to reach the external Chromium: `auto`, a port (`9222`), or a full `ws://host:port/path` / " +
448
+ "`wss://…` URL. Omit to keep the current one.",
449
+ },
450
+ profile: {
451
+ type: "string",
452
+ description:
453
+ "Chromium user-data directory to control, e.g. `~/.config/google-chrome`. Wins over cdpUrl. Omit to " +
454
+ "keep the current one; pass an empty string to go back to cdpUrl discovery.",
455
+ },
456
+ },
457
+ options: { namespace: "browser", permission: "browser", codemode: true },
458
+ execute: (input, context) =>
459
+ Effect.gen(function* () {
460
+ const { mode: requestedMode, cdpUrl, profile } = input as {
461
+ mode?: unknown
462
+ cdpUrl?: unknown
463
+ profile?: unknown
464
+ }
465
+ if (requestedMode === "external" || requestedMode === "in-app" || requestedMode === "auto") {
466
+ modeState.current = requestedMode
467
+ modeState.source = "browser.target"
468
+ }
469
+
470
+ // Destino explícito → cerrar y reencolar. Sin esto seguiríamos
471
+ // hablando con el navegador anterior, que es lo confuso: la tool
472
+ // aceptaría el cambio y no cambiaría nada.
473
+ if (typeof cdpUrl === "string" || typeof profile === "string") {
474
+ const nextUrl = typeof cdpUrl === "string" ? cdpUrl : target.cdpUrl
475
+ const nextProfile = typeof profile === "string" ? profile : target.profile
476
+ if (nextUrl !== target.cdpUrl || nextProfile !== target.profile) {
477
+ yield* disconnect()
478
+ target.cdpUrl = nextUrl || "auto"
479
+ target.profile = nextProfile
480
+ yield* Effect.logInfo(
481
+ `[apex.browser] destino → ${target.profile || target.cdpUrl} · esta sesión se reengancha`,
482
+ )
483
+ }
484
+ }
485
+
486
+ // El enganche ocurre AQUÍ y solo aquí: pedir navegador para esta
487
+ // sesión. Un hook execute.before lo hacía en cada tool call y con
488
+ // el destino caído eso eran hasta 90 s de bloqueo por invocación.
489
+ yield* attachFor(context.sessionID)
490
+
491
+ return { output: describe() }
492
+ }),
493
+ })
494
+ })
495
+ .pipe(Effect.orDie)
496
+
497
+ // --- comando para que lo elija el USUARIO --------------------------------
498
+ yield* ctx.command
499
+ .transform((editor) => {
500
+ editor.add({
501
+ name: "browser-target",
502
+ description:
503
+ "Choose the browser that serves browser.*: external (CDP), in-app (desktop app), or auto. Optional " +
504
+ "destination: `/browser-target external 9333`, `/browser-target external ws://host:port/path`, or " +
505
+ "`/browser-target external ~/.config/google-chrome`.",
506
+ execute: (input) =>
507
+ Effect.gen(function* () {
508
+ // El prompt llega como texto libre: `external 9333`, o solo
509
+ // `external` para no cambiar el destino.
510
+ const [arg, destination] = String(input.prompt ?? "").trim().split(/\s+/)
511
+ if (arg !== "external" && arg !== "in-app" && arg !== "auto") return
512
+ modeState.current = arg
513
+ modeState.source = "/browser-target"
514
+ if (destination) {
515
+ // Un destino que empieza por / o ~ es un perfil; el resto, una
516
+ // URL o un puerto. Igual que la tool: si cambia, cerrar el
517
+ // socket; si no, tocar nada (reconectar contra un destino
518
+ // caído es un popup perdido o 90 s de bloqueo).
519
+ const isProfile = destination.startsWith("/") || destination.startsWith("~")
520
+ const nextProfile = isProfile ? destination : ""
521
+ const nextUrl = isProfile ? target.cdpUrl : destination
522
+ if (nextUrl !== target.cdpUrl || nextProfile !== target.profile) {
523
+ yield* disconnect()
524
+ target.cdpUrl = nextUrl || "auto"
525
+ target.profile = nextProfile
526
+ yield* Effect.logInfo(
527
+ `[apex.browser] destino → ${target.profile || target.cdpUrl} · esta sesión se reengancha`,
528
+ )
529
+ }
530
+ }
531
+ // El usuario lo pide aquí: engancha (o suelta, en in-app) la
532
+ // sesión que ejecuta el comando.
533
+ yield* attachFor(input.sessionID)
534
+ }),
535
+ })
536
+ })
537
+ .pipe(Effect.orDie)
538
+
539
+ yield* Effect.logInfo(
540
+ `[apex.browser] listo · modo=${modeState.current} (${modeState.source}) · destino=${target.profile || target.cdpUrl}`,
541
+ )
542
+ })
543
+ }
544
+
545
+ /** Cause de Effect a Error legible: los defectos llegan envueltos. */
546
+ const causeOf = (defect: unknown) =>
547
+ Cause.isCause(defect) ? new Error(Cause.pretty(defect)) : defect instanceof Error ? defect : new Error(String(defect))
548
+
549
+ /** Opciones TLS para un endpoint wss:// remoto (detrás de un proxy inverso). */
550
+ function tlsOptions(cdpUrl: string, config: BrowserConfigShape): TlsOptions | undefined {
551
+ if (!cdpUrl.startsWith("wss://")) return undefined
552
+ const tls: { ca?: Buffer; rejectUnauthorized?: boolean } = {}
553
+ if (config.caFile) tls.ca = readFileSync(config.caFile)
554
+ if (config.insecureSkipVerify) tls.rejectUnauthorized = false
555
+ return Object.keys(tls).length > 0 ? tls : { rejectUnauthorized: true }
556
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Apex Advisor — definición del agente dedicado y su protocolo.
3
+ *
4
+ * El plugin define (upsert) un agente `apex-advisor` oculto, de modo `subagent`,
5
+ * con su propio `model` (barato/rápido) y un ruleset de permisos que le permite
6
+ * EXCLUSIVAMENTE la herramienta de decisión.
7
+ *
8
+ * El agente editor de v2 hace upsert: `update(id, fn)` sobre un id inexistente
9
+ * lo crea partiendo de `Agent.Info.default(id)`.
10
+ */
11
+
12
+ import { Effect } from "effect"
13
+ import type { Scope } from "effect"
14
+ import type { Plugin } from "@opencode/plugin/effect"
15
+
16
+ /** ID del agente advisor. */
17
+ export const ADVISOR_AGENT_ID = "apex-advisor"
18
+
19
+ /** Nombre de la única herramienta que expone el advisor. */
20
+ export const ADVISOR_TOOL_NAME = "apex_advisor_decide"
21
+
22
+ /** Instrucciones del agente: protocolo de decisión allow/deny. */
23
+ export function advisorSystemPrompt(decisive: boolean): string {
24
+ const enforcement = decisive
25
+ ? "Tu decisión se APLICA automáticamente: allow autoriza la ejecución, deny la bloquea."
26
+ : "Tu decisión se muestra al usuario, que decide en última instancia."
27
+
28
+ return `Eres el advisor de permisos de opencode-apex. Evaluás si se permite o se deniega
29
+ la ejecución de una herramienta solicitada por otra sesión de agente.
30
+
31
+ ${enforcement}
32
+
33
+ Para responder debés llamar SIEMPRE a la herramienta \`${ADVISOR_TOOL_NAME}\` con:
34
+ - requestID: el identificador de la solicitud (te lo damos en cada petición)
35
+ - decision: "allow" para APROBAR la ejecución
36
+ - reason: motivo breve — OBLIGATORIO cuando decision="deny", opcional si allow
37
+
38
+ Criterios:
39
+ - "allow" si la acción es segura y apropiada en el contexto dado.
40
+ - "deny" si puede causar daño, pérdida de datos, exfiltración de secretos,
41
+ destrucción de recursos o es claramente inapropiada.
42
+
43
+ No ejecutes ninguna otra herramienta. No respondas con texto libre: usá la herramienta.`
44
+ }
45
+
46
+ /**
47
+ * Define/actualiza el agente advisor en el runtime.
48
+ * Se re-ejecuta en cada carga del plugin (upsert idempotente).
49
+ */
50
+ export function ensureAdvisorAgent(
51
+ ctx: Plugin.Context,
52
+ options: { model?: string; system?: string; decisive: boolean },
53
+ ): Effect.Effect<void, never, Scope.Scope> {
54
+ return Effect.gen(function* () {
55
+ const model = parseModelRef(options.model)
56
+
57
+ yield* ctx.agent.transform((editor) => {
58
+ editor.update(ADVISOR_AGENT_ID, (agent) => {
59
+ agent.name = ADVISOR_AGENT_ID as never
60
+ agent.description = "Advisor de permisos de apex: decide allow/deny sobre herramientas de otras sesiones"
61
+ agent.mode = "subagent"
62
+ agent.hidden = true
63
+ agent.system = options.system ?? advisorSystemPrompt(options.decisive)
64
+ if (model) agent.model = model as never
65
+
66
+ // Toolset = la herramienta de decisión y `execute`. El resto denegado, así
67
+ // el advisor no puede tocar el workspace.
68
+ //
69
+ // `execute` es imprescindible, no un extra: en opencode v2 el modelo no
70
+ // invoca las herramientas como function calls, las llama desde el sandbox
71
+ // JS (`return await tools.apex_advisor_decide({…})`). Con `execute`
72
+ // denegado el advisor decidía correctamente y su llamada quedaba en
73
+ // `executed: false`, de modo que la decisión nunca llegaba y cada
74
+ // evaluación terminaba en timeout. El sandbox no amplía privilegios:
75
+ // toda herramienta que invoque vuelve a pasar por estos permisos.
76
+ agent.permissions = [
77
+ { action: "*", resource: "*", effect: "deny" },
78
+ { action: "execute", resource: "*", effect: "allow" },
79
+ { action: ADVISOR_TOOL_NAME, resource: "*", effect: "allow" },
80
+ ] as never
81
+ })
82
+ })
83
+ })
84
+ }
85
+
86
+ /** "providerID/modelID" → Model.Ref. Devuelve null si el formato no es válido. */
87
+ export function parseModelRef(spec: string | undefined): { providerID: string; id: string } | null {
88
+ const raw = (spec ?? "").trim()
89
+ if (!raw) return null
90
+ const slash = raw.indexOf("/")
91
+ if (slash <= 0 || slash === raw.length - 1) return null
92
+ return { providerID: raw.slice(0, slash), id: raw.slice(slash + 1) }
93
+ }