@opencode/plugin-browser 2.3.2 → 2.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/README.md CHANGED
@@ -13,7 +13,7 @@ return await tools.browser.snapshot({ tabID: tab.id })
13
13
  All page operations require a `tabID` returned by `browser.tabs.open/list`.
14
14
  Focus selects the visible Review tab, not an implicit command target. Discover
15
15
  current signatures with `search({ namespace: "browser" })`.
16
- Screenshots require a focused, visible tab; call `browser.tabs.focus` first.
16
+ Screenshots, clicks and hovers work while the tab is hidden; only a full-page screenshot needs the tab on screen in the Review pane.
17
17
 
18
18
  ## Tools
19
19
 
@@ -30,11 +30,21 @@ Screenshots require a focused, visible tab; call `browser.tabs.focus` first.
30
30
  The source of truth for inputs, descriptions, and outputs is
31
31
  `Browser.Operations` in `@opencode/plugin-browser/rpc`.
32
32
 
33
+ `tabs.open` and `navigate` take a web address in `url` or a workspace file in
34
+ `path`, never both. The server checks that a path is a readable file inside the
35
+ workspace, then sends the desktop a file action: `preview` for `tabs.open`
36
+ (older desktops and servers already exchange it under that name) and
37
+ `navigate.path` for `navigate`. No tool is named after either. The permission
38
+ check for a path names the called operation and `preview`, so a rule, policy or
39
+ hook that denies `browser: preview` still stops it.
40
+
33
41
  The built-in `browser` skill (`skill.ts`) teaches the workflow: explicit tab
34
42
  IDs, snapshots and refs, showing results to the user, recipes for debugging,
35
43
  performance and memory, and recovery after failures. It lists every operation
36
44
  from `Browser.Operations`. Like the tools, it is hidden until a desktop browser
37
- attaches to the session.
45
+ attaches to the session. An attached session lists both to every agent. An agent
46
+ whose configured rules deny the browser, or some of its operations, has each
47
+ such call refused; an `ask` makes each call prompt.
38
48
 
39
49
  The plugin entrypoint only composes its two owners: `connection.ts` manages
40
50
  desktop attachments and pending RPC requests; `tools.ts` runs the tool workflow.
@@ -4,9 +4,37 @@ import { Tool } from "@opencode/schema/tool";
4
4
  import { Effect, Scope } from "effect";
5
5
  import { Browser } from "./rpc.js";
6
6
  export type Connection = Effect.Success<ReturnType<typeof make>>;
7
- export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" | "rpc" | "session">) => Effect.Effect<{
8
- target: (sessionID: string & import("effect/Brand").Brand<"SessionID">, action: {
7
+ /**
8
+ * A crash or SIGKILL skips the revokes, so a session keeps its grant with no attachment behind it. Revokes the grants
9
+ * this location's servers recorded, except those of a process that still runs: several servers can share one
10
+ * database, and another one's attachment may be live. Runs before the RPC registers, so no attach here can race it.
11
+ */
12
+ export declare const reconcileStaleGrants: (ctx: {
13
+ readonly session: Pick<Context["session"], "get" | "update">;
14
+ readonly storage: Pick<Context["storage"], "scan" | "remove">;
15
+ readonly location: Pick<Context["location"], "directory" | "workspaceID">;
16
+ }) => Effect.Effect<void, never, never>;
17
+ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" | "permission" | "rpc" | "session" | "storage">) => Effect.Effect<{
18
+ /**
19
+ * Refuses a call that config, the agent's definition or the session's own rules deny. It reads rules only and never
20
+ * prompts, so it runs before the tool reads a file, looks up a tab or says whether a desktop is attached: a denied
21
+ * call reveals nothing but the denial. Without a desktop the session has no grant, and core would deny the call
22
+ * with its own message before any hook ran.
23
+ */
24
+ refuse: (tool: Tool.Context, operations: readonly string[]) => Effect.Effect<undefined, Tool.Error, never>;
25
+ /**
26
+ * The permission check for one call, with the operation as its resource. Its `permission.evaluate` hooks decide it:
27
+ * this plugin's (configured denies win over the grant) and others such as `tool.use` policies.
28
+ */
29
+ authorize: (tool: Tool.Context, action: {
9
30
  readonly type: "tabs.list";
31
+ } | {
32
+ readonly type: "preview";
33
+ readonly path: string;
34
+ } | {
35
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
36
+ readonly type: "navigate.path";
37
+ readonly path: string;
10
38
  } | {
11
39
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
12
40
  readonly type: "back";
@@ -88,12 +116,258 @@ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" |
88
116
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
89
117
  readonly type: "press";
90
118
  readonly key: string;
119
+ } | {
120
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
121
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
122
+ readonly type: "select";
123
+ readonly values: readonly string[];
124
+ } | {
125
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
126
+ readonly type: "stop";
127
+ } | {
128
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
129
+ readonly type: "tabs.close";
130
+ } | {
131
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
132
+ readonly type: "tabs.focus";
133
+ } | {
134
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
135
+ readonly type: "trace.stop";
136
+ } | {
137
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
138
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
139
+ readonly type: "click";
140
+ readonly button?: "left" | "middle" | "right" | undefined;
141
+ readonly count?: 1 | 2 | undefined;
142
+ readonly modifiers?: readonly ("Alt" | "Control" | "Meta" | "Shift")[] | undefined;
143
+ } | {
144
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
145
+ readonly type: "console";
146
+ readonly level?: "debug" | "error" | "info" | "warning" | undefined;
147
+ readonly limit?: number | undefined;
148
+ } | {
149
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
150
+ readonly fileID: string & import("effect/Brand").Brand<"Browser.FileID">;
151
+ readonly type: "cpu.analyze";
152
+ readonly limit?: number | undefined;
153
+ } | {
154
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
155
+ readonly type: "dialog";
156
+ readonly action: "accept" | "dismiss" | "get";
157
+ readonly promptText?: string | undefined;
158
+ } | {
159
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
160
+ readonly frameID?: string | undefined;
161
+ readonly type: "evaluate";
162
+ readonly ref?: (string & import("effect/Brand").Brand<"Browser.Ref">) | undefined;
163
+ readonly script: string;
164
+ } | {
165
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
166
+ readonly frameID?: string | undefined;
167
+ readonly maxChars?: number | undefined;
168
+ readonly interactive?: boolean | undefined;
169
+ readonly maxLines?: number | undefined;
170
+ readonly type: "find";
171
+ readonly text: string;
172
+ } | {
173
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
174
+ readonly type: "heap.compare";
175
+ readonly before: string & import("effect/Brand").Brand<"Browser.FileID">;
176
+ readonly after: string & import("effect/Brand").Brand<"Browser.FileID">;
177
+ readonly limit?: number | undefined;
178
+ } | {
179
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
180
+ readonly fileID: string & import("effect/Brand").Brand<"Browser.FileID">;
181
+ readonly type: "heap.object";
182
+ readonly id: number;
183
+ readonly limit?: number | undefined;
184
+ } | {
185
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
186
+ readonly fileID: string & import("effect/Brand").Brand<"Browser.FileID">;
187
+ readonly type: "heap.query";
188
+ readonly name?: string | undefined;
189
+ readonly limit?: number | undefined;
190
+ } | {
191
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
192
+ readonly fileID: string & import("effect/Brand").Brand<"Browser.FileID">;
193
+ readonly type: "heap.summary";
194
+ readonly limit?: number | undefined;
195
+ } | {
196
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
197
+ readonly includeBody?: boolean | undefined;
198
+ readonly includeResponseBody?: boolean | undefined;
199
+ readonly maxBodyChars?: number | undefined;
200
+ readonly type: "network.get";
201
+ readonly id: string;
202
+ } | {
203
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
204
+ readonly type: "network.list";
205
+ readonly urlContains?: string | undefined;
206
+ readonly resourceType?: "document" | "eventsource" | "fetch" | "font" | "image" | "manifest" | "media" | "other" | "script" | "stylesheet" | "websocket" | "xhr" | undefined;
207
+ readonly limit?: number | undefined;
208
+ } | {
209
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
210
+ readonly type: "reload";
211
+ readonly ignoreCache?: boolean | undefined;
212
+ } | {
213
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
214
+ readonly type: "screenshot";
215
+ readonly ref?: (string & import("effect/Brand").Brand<"Browser.Ref">) | undefined;
216
+ readonly fullPage?: boolean | undefined;
217
+ readonly format?: "jpeg" | "png" | "webp" | undefined;
218
+ readonly quality?: number | undefined;
219
+ readonly maxWidth?: number | undefined;
220
+ } | {
221
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
222
+ readonly type: "scroll";
223
+ readonly deltaX?: number | undefined;
224
+ readonly deltaY: number;
225
+ } | {
226
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
227
+ readonly frameID?: string | undefined;
228
+ readonly maxChars?: number | undefined;
229
+ readonly interactive?: boolean | undefined;
230
+ readonly maxLines?: number | undefined;
231
+ readonly type: "snapshot";
232
+ readonly ref?: (string & import("effect/Brand").Brand<"Browser.Ref">) | undefined;
233
+ readonly depth?: number | undefined;
234
+ readonly boxes?: boolean | undefined;
235
+ } | {
236
+ readonly type: "tabs.open";
237
+ readonly url?: string | undefined;
238
+ readonly focus?: boolean | undefined;
239
+ } | {
240
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
241
+ readonly fileID: string & import("effect/Brand").Brand<"Browser.FileID">;
242
+ readonly type: "trace.analyze";
243
+ readonly limit?: number | undefined;
244
+ } | {
245
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
246
+ readonly type: "trace.start";
247
+ readonly durationMs?: number | undefined;
248
+ } | {
249
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
250
+ readonly frameID?: string | undefined;
251
+ readonly type: "wait";
252
+ readonly condition: "delay" | "load" | "text" | "textGone" | "url";
253
+ readonly text?: string | undefined;
254
+ readonly url?: string | undefined;
255
+ readonly timeoutMs?: number | undefined;
256
+ } | ({
257
+ readonly [x: string]: unknown;
258
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
259
+ readonly frameID?: string | undefined;
260
+ readonly condition?: "delay" | "element" | "elementGone" | "load" | "text" | "textGone" | "url" | undefined;
261
+ readonly text?: string | undefined;
262
+ readonly textGone?: string | undefined;
263
+ readonly selector?: string | undefined;
264
+ readonly ref?: (string & import("effect/Brand").Brand<"Browser.Ref">) | undefined;
265
+ readonly state?: "attached" | "detached" | "domcontentloaded" | "hidden" | "load" | "networkidle" | "visible" | undefined;
266
+ readonly url?: string | undefined;
267
+ readonly delayMs?: number | undefined;
268
+ readonly time?: number | undefined;
269
+ readonly ms?: number | undefined;
270
+ readonly timeoutMs?: number | undefined;
271
+ readonly timeout?: number | undefined;
272
+ } & {
273
+ readonly type: "wait";
274
+ }), operations?: readonly string[] | undefined) => Effect.Effect<{
275
+ connected: false;
276
+ message: string;
277
+ } | {
278
+ message?: undefined;
279
+ connected: true;
280
+ }, Tool.Error, never>;
281
+ target: (sessionID: string & import("effect/Brand").Brand<"SessionID">, action: {
282
+ readonly type: "tabs.list";
91
283
  } | {
92
284
  readonly type: "preview";
93
285
  readonly path: string;
94
286
  } | {
95
287
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
96
- readonly type: "reload";
288
+ readonly type: "navigate.path";
289
+ readonly path: string;
290
+ } | {
291
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
292
+ readonly type: "back";
293
+ } | {
294
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
295
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
296
+ readonly type: "check";
297
+ readonly checked: boolean;
298
+ } | {
299
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
300
+ readonly type: "cpu.start";
301
+ } | {
302
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
303
+ readonly type: "cpu.stop";
304
+ } | {
305
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
306
+ readonly type: "drag";
307
+ readonly from: string & import("effect/Brand").Brand<"Browser.Ref">;
308
+ readonly to: string & import("effect/Brand").Brand<"Browser.Ref">;
309
+ } | {
310
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
311
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
312
+ readonly type: "files.drop";
313
+ readonly paths: readonly string[];
314
+ } | {
315
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
316
+ readonly fileID: string & import("effect/Brand").Brand<"Browser.FileID">;
317
+ readonly type: "files.get";
318
+ } | {
319
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
320
+ readonly type: "files.list";
321
+ } | {
322
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
323
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
324
+ readonly type: "files.upload";
325
+ readonly paths: readonly string[];
326
+ } | {
327
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
328
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
329
+ readonly type: "fill";
330
+ readonly text: string;
331
+ } | {
332
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
333
+ readonly type: "fill_form";
334
+ readonly fields: readonly ({
335
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
336
+ readonly type: "text";
337
+ readonly value: string;
338
+ } | {
339
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
340
+ readonly type: "select";
341
+ readonly values: readonly string[];
342
+ } | {
343
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
344
+ readonly type: "check";
345
+ readonly checked: boolean;
346
+ })[];
347
+ } | {
348
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
349
+ readonly type: "forward";
350
+ } | {
351
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
352
+ readonly type: "frames";
353
+ } | {
354
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
355
+ readonly type: "heap.snapshot";
356
+ } | {
357
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
358
+ readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
359
+ readonly type: "hover";
360
+ } | {
361
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
362
+ readonly type: "lighthouse";
363
+ } | {
364
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
365
+ readonly type: "navigate";
366
+ readonly url: string;
367
+ } | {
368
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
369
+ readonly type: "press";
370
+ readonly key: string;
97
371
  } | {
98
372
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
99
373
  readonly ref: string & import("effect/Brand").Brand<"Browser.Ref">;
@@ -142,6 +416,9 @@ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" |
142
416
  } | {
143
417
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
144
418
  readonly frameID?: string | undefined;
419
+ readonly maxChars?: number | undefined;
420
+ readonly interactive?: boolean | undefined;
421
+ readonly maxLines?: number | undefined;
145
422
  readonly type: "find";
146
423
  readonly text: string;
147
424
  } | {
@@ -169,16 +446,21 @@ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" |
169
446
  readonly limit?: number | undefined;
170
447
  } | {
171
448
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
172
- readonly type: "network.get";
173
- readonly id: string;
174
449
  readonly includeBody?: boolean | undefined;
450
+ readonly includeResponseBody?: boolean | undefined;
175
451
  readonly maxBodyChars?: number | undefined;
452
+ readonly type: "network.get";
453
+ readonly id: string;
176
454
  } | {
177
455
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
178
456
  readonly type: "network.list";
179
457
  readonly urlContains?: string | undefined;
180
458
  readonly resourceType?: "document" | "eventsource" | "fetch" | "font" | "image" | "manifest" | "media" | "other" | "script" | "stylesheet" | "websocket" | "xhr" | undefined;
181
459
  readonly limit?: number | undefined;
460
+ } | {
461
+ readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
462
+ readonly type: "reload";
463
+ readonly ignoreCache?: boolean | undefined;
182
464
  } | {
183
465
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
184
466
  readonly type: "screenshot";
@@ -195,6 +477,9 @@ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" |
195
477
  } | {
196
478
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
197
479
  readonly frameID?: string | undefined;
480
+ readonly maxChars?: number | undefined;
481
+ readonly interactive?: boolean | undefined;
482
+ readonly maxLines?: number | undefined;
198
483
  readonly type: "snapshot";
199
484
  readonly ref?: (string & import("effect/Brand").Brand<"Browser.Ref">) | undefined;
200
485
  readonly depth?: number | undefined;
@@ -216,8 +501,9 @@ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" |
216
501
  readonly tabID: string & import("effect/Brand").Brand<"Browser.TabID">;
217
502
  readonly frameID?: string | undefined;
218
503
  readonly type: "wait";
219
- readonly condition: "load" | "text" | "textGone";
504
+ readonly condition: "delay" | "load" | "text" | "textGone" | "url";
220
505
  readonly text?: string | undefined;
506
+ readonly url?: string | undefined;
221
507
  readonly timeoutMs?: number | undefined;
222
508
  }) => Effect.Effect<{
223
509
  tab: Browser.Tab | undefined;
@@ -1,14 +1,74 @@
1
1
  export * as BrowserConnection from "./connection.js";
2
+ import { hostname } from "node:os";
3
+ import { rm } from "node:fs/promises";
4
+ import { BrowserFiles } from "./files.js";
5
+ import { Location } from "@opencode/schema/location";
6
+ import { Session } from "@opencode/schema/session";
2
7
  import { Tool } from "@opencode/schema/tool";
3
8
  import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect";
4
9
  import { BrowserMachine } from "./machine.js";
5
10
  import { Browser } from "./rpc.js";
6
11
  import { BrowserTunnel } from "./tunnel.js";
12
+ /** The server process that wrote a session's grant, stored as `grant:<sessionID>` until its revoke succeeds. */
13
+ const GrantOwner = Schema.Struct({ host: Schema.String, pid: Schema.Number, location: Location.Ref });
14
+ const GRANT_PREFIX = "grant:";
15
+ /**
16
+ * A crash or SIGKILL skips the revokes, so a session keeps its grant with no attachment behind it. Revokes the grants
17
+ * this location's servers recorded, except those of a process that still runs: several servers can share one
18
+ * database, and another one's attachment may be live. Runs before the RPC registers, so no attach here can race it.
19
+ */
20
+ export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleGrants")(function* (ctx) {
21
+ const revoke = (entry) => {
22
+ const owner = Schema.decodeUnknownOption(GrantOwner)(entry.value);
23
+ if (Option.isNone(owner) ||
24
+ owner.value.location.directory !== ctx.location.directory ||
25
+ owner.value.location.workspaceID !== ctx.location.workspaceID ||
26
+ running(owner.value))
27
+ return Effect.void;
28
+ return writePermissions(ctx, Session.ID.make(entry.key.slice(GRANT_PREFIX.length)), false).pipe(Effect.ignore, Effect.andThen(ctx.storage.remove(entry.key)));
29
+ };
30
+ const page = (after) => ctx.storage
31
+ .scan({ prefix: GRANT_PREFIX, after })
32
+ .pipe(Effect.flatMap((result) => Effect.forEach(result.entries, revoke, { discard: true }).pipe(Effect.andThen(result.next === undefined ? Effect.void : page(result.next)))));
33
+ yield* page();
34
+ });
7
35
  export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
8
- // Appended after config, so every agent hides the browser until an attachment allows it.
9
- yield* ctx.agent.transform((editor) => editor
10
- .list()
11
- .forEach((agent) => agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" })))));
36
+ // Each agent's rules from config and its definition, which an attachment's grant must not override.
37
+ const configured = new Map();
38
+ // Appended after config, so every agent hides the browser tools and their skill until an attachment allows them.
39
+ yield* ctx.agent.transform((editor) => {
40
+ configured.clear();
41
+ editor.list().forEach((agent) => {
42
+ configured.set(agent.id, [...agent.permissions]);
43
+ agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" })));
44
+ });
45
+ });
46
+ const rulesFor = (session, agent) => [
47
+ // Core denies everything to an agent it cannot resolve, such as a disabled or removed one; so does this.
48
+ ...(configured.get(agent ?? session.agent ?? "") ?? [{ action: "*", resource: "*", effect: "deny" }]),
49
+ ...(session.permissions ?? []).filter((rule) => !BrowserMachine.isGrant(rule)),
50
+ ];
51
+ // The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call to
52
+ // allow, and lists the browser tools and their skill to every agent of an attached session, one whose own rules
53
+ // deny the browser included. This hook alone refuses such an agent's calls, by the rules from config, the agent's
54
+ // definition and the session itself: a deny refuses the call. An ask rule is not applied in an attached session, as
55
+ // on dev, and no matching rule leaves the call allowed.
56
+ yield* ctx.permission.hook("evaluate", (event) => {
57
+ if (event.action !== "browser" || event.effect === "deny")
58
+ return Effect.void;
59
+ return ctx.session.get({ sessionID: event.sessionID }).pipe(Effect.map((session) => {
60
+ const denied = denial(rulesFor(session, event.agent), event.resources);
61
+ if (denied) {
62
+ event.effect = "deny";
63
+ event.message = denied;
64
+ }
65
+ }),
66
+ // Without the rules, the grant must not decide alone.
67
+ Effect.catchCause((cause) => Effect.logWarning("Browser permission evaluation failed", cause).pipe(Effect.andThen(Effect.sync(() => {
68
+ event.effect = "deny";
69
+ event.message = "Browser permissions could not be read; no action ran.";
70
+ })))));
71
+ });
12
72
  // Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes.
13
73
  const work = yield* Scope.make();
14
74
  yield* Effect.addFinalizer((exit) => Scope.close(work, exit));
@@ -56,10 +116,21 @@ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
56
116
  return Effect.logWarning(effect.message, effect.error);
57
117
  return Deferred.done(drained, Exit.void).pipe(Effect.asVoid);
58
118
  };
59
- const syncPermissions = (effect) => ctx.session.get({ sessionID: effect.sessionID }).pipe(Effect.flatMap((session) => {
60
- const permissions = BrowserMachine.reconcileBrowserPermissions(session.permissions, effect.allow);
61
- return permissions ? ctx.session.update({ sessionID: effect.sessionID, permissions }) : Effect.void;
62
- }), Effect.timeoutOption(Duration.millis(BrowserMachine.PERMISSION_SYNC_TIMEOUT_MS)), Effect.matchCauseEffect({
119
+ const owner = {
120
+ host: hostname(),
121
+ pid: process.pid,
122
+ location: {
123
+ directory: ctx.location.directory,
124
+ ...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }),
125
+ },
126
+ };
127
+ const syncPermissions = (effect) =>
128
+ // The owner is recorded before the grant and forgotten after the revoke, so a stored grant always has one.
129
+ (effect.allow
130
+ ? ctx.storage
131
+ .set(GRANT_PREFIX + effect.sessionID, owner)
132
+ .pipe(Effect.andThen(writePermissions(ctx, effect.sessionID, true)))
133
+ : writePermissions(ctx, effect.sessionID, false).pipe(Effect.andThen(ctx.storage.remove(GRANT_PREFIX + effect.sessionID)))).pipe(Effect.timeoutOption(Duration.millis(BrowserMachine.PERMISSION_SYNC_TIMEOUT_MS)), Effect.matchCauseEffect({
63
134
  onSuccess: (done) => dispatch({
64
135
  type: Option.isSome(done) ? "permissions.synced" : "permissions.timed-out",
65
136
  sessionID: effect.sessionID,
@@ -79,6 +150,7 @@ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
79
150
  ? Effect.succeed(attachment.tunnels)
80
151
  : Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed."));
81
152
  };
153
+ yield* reconcileStaleGrants(ctx);
82
154
  const rpc = yield* ctx.rpc
83
155
  .register(Browser.Definition, {
84
156
  attach: (input, call) => Effect.gen(function* () {
@@ -127,7 +199,23 @@ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
127
199
  yield* ctx.event.subscribe({ types: ["session.deleted", "session.moved"] }).pipe(Stream.runForEach((event) => dispatch({
128
200
  type: event.type === "session.deleted" ? "session.deleted" : "session.moved",
129
201
  sessionID: event.data.sessionID,
130
- })), Effect.forkScoped({ startImmediately: true }));
202
+ }).pipe(
203
+ // A deleted session's grant went with it, and no revoke will forget its owner record.
204
+ Effect.andThen(event.type === "session.deleted"
205
+ ? Effect.all([
206
+ ctx.storage.remove(GRANT_PREFIX + event.data.sessionID),
207
+ Effect.tryPromise(() => rm(BrowserFiles.exportRoot(event.data.sessionID), { recursive: true, force: true }))
208
+ .pipe(Effect.tapError((error) => Effect.logWarning("Could not remove deleted session's browser exports", error))),
209
+ ]).pipe(Effect.ignore)
210
+ : Effect.void))), Effect.forkScoped({ startImmediately: true }));
211
+ // A child copies its parent's permissions, browser grant included, but not the attachment. The grant is revoked while
212
+ // the child's prompt is admitted, so no step of the child lists browser tools. The lock keeps an attachment of the
213
+ // child's own from starting meanwhile; one that already exists keeps its grant.
214
+ yield* ctx.session.hook("prompt", (event) => ctx.session.get({ sessionID: event.sessionID }).pipe(Effect.flatMap((session) => session.parentID === undefined || !session.permissions?.some(BrowserMachine.isGrant)
215
+ ? Effect.void
216
+ : lock.withPermit(Effect.suspend(() => BrowserMachine.hasSession(machine.state, session.id)
217
+ ? Effect.void
218
+ : writePermissions(ctx, session.id, false)))), Effect.catchCause((cause) => Effect.logWarning("Browser permission revoke failed", cause))));
131
219
  // Registered last, so it runs first: attachments close and revokes drain while the RPC and `work` are still open.
132
220
  yield* Effect.addFinalizer(() => dispatch({ type: "disposed" }).pipe(Effect.andThen(Deferred.await(drained))));
133
221
  const request = Effect.fn("BrowserConnection.request")(function* (sessionID, connectionID, action, tab, files, inspection) {
@@ -149,6 +237,39 @@ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
149
237
  })))), Effect.onInterrupt(() => dispatch({ type: "request.cancelled", ...target })), Effect.ensuring(Effect.sync(() => requests.delete(requestID)))));
150
238
  });
151
239
  return {
240
+ /**
241
+ * Refuses a call that config, the agent's definition or the session's own rules deny. It reads rules only and never
242
+ * prompts, so it runs before the tool reads a file, looks up a tab or says whether a desktop is attached: a denied
243
+ * call reveals nothing but the denial. Without a desktop the session has no grant, and core would deny the call
244
+ * with its own message before any hook ran.
245
+ */
246
+ refuse: Effect.fn("BrowserConnection.refuse")(function* (tool, operations) {
247
+ const session = yield* ctx.session
248
+ .get({ sessionID: tool.sessionID })
249
+ .pipe(Effect.mapError((error) => new Tool.Error({ message: `Session not found: ${tool.sessionID}`, error })));
250
+ const denied = denial(rulesFor(session, tool.agent), operations);
251
+ if (denied)
252
+ return yield* new Tool.Error({ message: denied });
253
+ }),
254
+ /**
255
+ * The permission check for one call, with the operation as its resource. Its `permission.evaluate` hooks decide it:
256
+ * this plugin's (configured denies win over the grant) and others such as `tool.use` policies.
257
+ */
258
+ authorize: Effect.fn("BrowserConnection.authorize")(function* (tool, action, operations) {
259
+ const connection = BrowserMachine.selectConnection(machine.state, tool.sessionID);
260
+ if (!connection.ok)
261
+ return { connected: false, message: connection.error.message };
262
+ yield* ctx.permission.assert({
263
+ sessionID: tool.sessionID,
264
+ agent: tool.agent,
265
+ action: "browser",
266
+ // Keep exact operation resources for existing permission rules and tool.use policies. A call that stands for
267
+ // more than one operation names each, and a deny of any of them refuses it.
268
+ resources: operations ?? [action.type],
269
+ source: { type: "tool", messageID: tool.messageID, id: tool.id },
270
+ });
271
+ return { connected: true };
272
+ }),
152
273
  target: Effect.fn("BrowserConnection.target")(function* (sessionID, action) {
153
274
  const selected = BrowserMachine.selectTarget(machine.state, sessionID, action);
154
275
  if (!selected.ok)
@@ -167,3 +288,36 @@ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
167
288
  }),
168
289
  };
169
290
  });
291
+ /** The refusal for the first operation the rules deny, or undefined when they deny none. */
292
+ function denial(rules, operations) {
293
+ const denied = operations
294
+ .map((operation) => ({ operation, rule: BrowserMachine.selectBrowserRule(rules, operation) }))
295
+ .find((item) => item.rule?.effect === "deny");
296
+ if (!denied)
297
+ return undefined;
298
+ return denied.rule?.resource === "*"
299
+ ? "[browser.denied] Browser tools are denied for this agent by configuration; no action ran. Do not retry browser tools."
300
+ : denied.operation === "preview"
301
+ ? // No tool has this name any more: it is the permission that covers showing a workspace file.
302
+ "[browser.denied] Showing a workspace file in the browser (permission browser.preview) is denied for this agent by configuration; no action ran. Do not retry it."
303
+ : `[browser.denied] browser.${denied.operation} is denied for this agent by configuration; no action ran. Do not retry it.`;
304
+ }
305
+ function writePermissions(ctx, sessionID, allow) {
306
+ return ctx.session.get({ sessionID }).pipe(Effect.flatMap((session) => {
307
+ const permissions = BrowserMachine.reconcileBrowserPermissions(session.permissions, allow);
308
+ return permissions ? ctx.session.update({ sessionID, permissions }) : Effect.void;
309
+ }));
310
+ }
311
+ // A process on another host, such as another container on a shared volume, cannot be checked; its grants count as live.
312
+ // A reused process ID also counts as live, which only leaves a stale grant in place.
313
+ function running(owner) {
314
+ if (owner.host !== hostname())
315
+ return true;
316
+ try {
317
+ process.kill(owner.pid, 0);
318
+ return true;
319
+ }
320
+ catch (error) {
321
+ return error instanceof Error && "code" in error && error.code === "EPERM";
322
+ }
323
+ }