@opencode/plugin-browser 2.2.4 → 2.2.6

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.
@@ -0,0 +1,391 @@
1
+ export * as BrowserMachine from "./machine.js";
2
+ import { Tool } from "@opencode/schema/tool";
3
+ import { BrowserSkill } from "./skill.js";
4
+ /** How long one permission sync (`session.get` and, when needed, `session.update`) may take. The desktop waits 15 s. */
5
+ export const PERMISSION_SYNC_TIMEOUT_MS = 10_000;
6
+ /** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */
7
+ export const REQUEST_TIMEOUT_MS = 60_000;
8
+ /** The browser tools and their skill, which an attachment allows together. */
9
+ export const ACCESS = [
10
+ { action: "browser", resource: "*" },
11
+ { action: "skill", resource: BrowserSkill.id },
12
+ ];
13
+ export function createConnectionState() {
14
+ return { status: "active", nextAttempt: 1, sessions: new Map() };
15
+ }
16
+ export function transitionConnection(state, event) {
17
+ if (event.type === "disposed")
18
+ return dispose(state);
19
+ // A request whose attachment closed or was replaced after the tool picked it was never sent.
20
+ if (event.type === "request.started" && !isAttachedConnection(state, event.sessionID, event.connectionID))
21
+ return {
22
+ state,
23
+ effects: [
24
+ {
25
+ type: "settle-request",
26
+ requestID: event.requestID,
27
+ settlement: { ok: false, error: disconnectedBeforeDispatch() },
28
+ },
29
+ ],
30
+ };
31
+ const entry = state.sessions.get(event.sessionID);
32
+ if (state.status === "disposed") {
33
+ if (!entry || entry.status !== "revoking")
34
+ return { state, effects: [] };
35
+ const step = transitionRevoking(entry, event, state.nextAttempt);
36
+ if (!step)
37
+ return { state, effects: [] };
38
+ const sessions = new Map(state.sessions);
39
+ if (step.entry)
40
+ sessions.set(event.sessionID, step.entry);
41
+ if (!step.entry)
42
+ sessions.delete(event.sessionID);
43
+ return {
44
+ state: { status: "disposed", nextAttempt: step.nextAttempt, sessions },
45
+ effects: sessions.size ? step.effects : [...step.effects, { type: "notify-drained" }],
46
+ };
47
+ }
48
+ const step = transitionSession(entry, event, state.nextAttempt);
49
+ if (!step)
50
+ return { state, effects: [] };
51
+ const sessions = new Map(state.sessions);
52
+ if (step.entry)
53
+ sessions.set(event.sessionID, step.entry);
54
+ if (!step.entry)
55
+ sessions.delete(event.sessionID);
56
+ return { state: { status: "active", nextAttempt: step.nextAttempt, sessions }, effects: step.effects };
57
+ }
58
+ function transitionSession(entry, event, nextAttempt) {
59
+ if (event.type === "attach.started")
60
+ return attach(entry, event, nextAttempt);
61
+ if (!entry)
62
+ return undefined;
63
+ if (entry.status === "revoking")
64
+ return transitionRevoking(entry, event, nextAttempt);
65
+ if (entry.status === "attaching")
66
+ return transitionAttaching(entry, event, nextAttempt);
67
+ return transitionAttached(entry, event, nextAttempt);
68
+ }
69
+ function attach(entry, event, nextAttempt) {
70
+ if (event.attempt !== nextAttempt)
71
+ return undefined;
72
+ const attaching = (sync) => ({
73
+ status: "attaching",
74
+ attempt: event.attempt,
75
+ connectionID: event.connectionID,
76
+ sync,
77
+ });
78
+ // A sync already in flight finishes first; the grant waits for it, so two writes never interleave.
79
+ if (entry?.status === "attaching")
80
+ return {
81
+ entry: attaching(entry.sync),
82
+ nextAttempt: nextAttempt + 1,
83
+ effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }],
84
+ };
85
+ if (entry?.status === "revoking")
86
+ return { entry: attaching(entry.sync), nextAttempt: nextAttempt + 1, effects: [] };
87
+ const sync = { attempt: nextAttempt + 1, allow: true };
88
+ const effects = entry?.status === "attached"
89
+ ? [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }]
90
+ : [];
91
+ return {
92
+ entry: attaching(sync),
93
+ nextAttempt: nextAttempt + 2,
94
+ effects: [...effects, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
95
+ };
96
+ }
97
+ function transitionAttaching(entry, event, nextAttempt) {
98
+ if (event.type === "permissions.synced" ||
99
+ event.type === "permissions.failed" ||
100
+ event.type === "permissions.timed-out") {
101
+ if (event.attempt !== entry.sync.attempt)
102
+ return undefined;
103
+ const warning = syncWarning(event, entry.sync);
104
+ // The revoke that ran before this attachment settled; now grant.
105
+ if (!entry.sync.allow) {
106
+ const sync = { attempt: nextAttempt, allow: true };
107
+ return {
108
+ entry: { ...entry, sync },
109
+ nextAttempt: nextAttempt + 1,
110
+ effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
111
+ };
112
+ }
113
+ if (event.type === "permissions.synced")
114
+ return {
115
+ entry: {
116
+ status: "attached",
117
+ attempt: entry.attempt,
118
+ connectionID: entry.connectionID,
119
+ browserState: { tabs: [], focusedTabID: null },
120
+ pending: new Map(),
121
+ },
122
+ nextAttempt,
123
+ effects: [
124
+ { type: "emit-control", control: { type: "attached", connectionID: entry.connectionID, version: 4 } },
125
+ ],
126
+ };
127
+ // A grant that timed out may still have written its rules; revoke them.
128
+ const sync = { attempt: nextAttempt, allow: false };
129
+ return {
130
+ entry: { status: "revoking", sync, deleted: false },
131
+ nextAttempt: nextAttempt + 1,
132
+ effects: [
133
+ ...warning,
134
+ { type: "close-attachment", attempt: entry.attempt, outcome: "unavailable" },
135
+ { type: "sync-permissions", sessionID: event.sessionID, ...sync },
136
+ ],
137
+ };
138
+ }
139
+ if ((event.type === "attach.closed" && event.attempt === entry.attempt) ||
140
+ event.type === "session.moved" ||
141
+ event.type === "session.deleted")
142
+ return {
143
+ entry: { status: "revoking", sync: entry.sync, deleted: event.type === "session.deleted" },
144
+ nextAttempt,
145
+ effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
146
+ };
147
+ return undefined;
148
+ }
149
+ function transitionAttached(entry, event, nextAttempt) {
150
+ if (event.type === "state.updated")
151
+ return updateBrowserState(entry, event, nextAttempt);
152
+ if (event.type === "request.started") {
153
+ if (entry.pending.has(event.requestID))
154
+ return undefined;
155
+ return {
156
+ entry: { ...entry, pending: new Map(entry.pending).set(event.requestID, event.command) },
157
+ nextAttempt,
158
+ effects: [
159
+ {
160
+ type: "dispatch-command",
161
+ sessionID: event.sessionID,
162
+ connectionID: entry.connectionID,
163
+ requestID: event.requestID,
164
+ },
165
+ ],
166
+ };
167
+ }
168
+ if (event.type === "request.dispatch-failed" ||
169
+ event.type === "request.settled" ||
170
+ event.type === "request.timed-out" ||
171
+ event.type === "request.cancelled") {
172
+ const command = entry.connectionID === event.connectionID ? entry.pending.get(event.requestID) : undefined;
173
+ if (!command)
174
+ return undefined;
175
+ const pending = new Map(entry.pending);
176
+ pending.delete(event.requestID);
177
+ return { entry: { ...entry, pending }, nextAttempt, effects: settleRequest(entry, event, command) };
178
+ }
179
+ if (event.type === "session.deleted")
180
+ return {
181
+ entry: undefined,
182
+ nextAttempt,
183
+ effects: [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
184
+ };
185
+ if ((event.type === "attach.closed" && event.attempt === entry.attempt) || event.type === "session.moved")
186
+ return revokeAttached(entry, event.sessionID, nextAttempt);
187
+ return undefined;
188
+ }
189
+ function transitionRevoking(entry, event, nextAttempt) {
190
+ if (event.type === "session.deleted")
191
+ return entry.deleted ? undefined : { entry: { ...entry, deleted: true }, nextAttempt, effects: [] };
192
+ if (event.type !== "permissions.synced" &&
193
+ event.type !== "permissions.failed" &&
194
+ event.type !== "permissions.timed-out")
195
+ return undefined;
196
+ if (event.attempt !== entry.sync.attempt)
197
+ return undefined;
198
+ const warning = syncWarning(event, entry.sync);
199
+ // A grant settled after its attachment closed, or timed out and may still have written: revoke it.
200
+ if (entry.sync.allow && !entry.deleted) {
201
+ const sync = { attempt: nextAttempt, allow: false };
202
+ return {
203
+ entry: { status: "revoking", sync, deleted: false },
204
+ nextAttempt: nextAttempt + 1,
205
+ effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
206
+ };
207
+ }
208
+ return { entry: undefined, nextAttempt, effects: warning };
209
+ }
210
+ function dispose(state) {
211
+ if (state.status === "disposed")
212
+ return { state, effects: [] };
213
+ const effects = [];
214
+ const sessions = new Map();
215
+ const nextAttempt = Array.from(state.sessions).reduce((attempt, [sessionID, entry]) => {
216
+ if (entry.status === "revoking") {
217
+ sessions.set(sessionID, entry);
218
+ return attempt;
219
+ }
220
+ if (entry.status === "attaching") {
221
+ sessions.set(sessionID, { status: "revoking", sync: entry.sync, deleted: false });
222
+ effects.push({ type: "close-attachment", attempt: entry.attempt, outcome: "closed" });
223
+ return attempt;
224
+ }
225
+ const step = revokeAttached(entry, sessionID, attempt);
226
+ if (step.entry)
227
+ sessions.set(sessionID, step.entry);
228
+ effects.push(...step.effects);
229
+ return step.nextAttempt;
230
+ }, state.nextAttempt);
231
+ if (!sessions.size)
232
+ effects.push({ type: "notify-drained" });
233
+ return { state: { status: "disposed", nextAttempt, sessions }, effects };
234
+ }
235
+ function revokeAttached(entry, sessionID, nextAttempt) {
236
+ const sync = { attempt: nextAttempt, allow: false };
237
+ return {
238
+ entry: { status: "revoking", sync, deleted: false },
239
+ nextAttempt: nextAttempt + 1,
240
+ effects: [
241
+ ...failPending(entry),
242
+ { type: "close-attachment", attempt: entry.attempt, outcome: "closed" },
243
+ { type: "sync-permissions", sessionID, ...sync },
244
+ ],
245
+ };
246
+ }
247
+ function updateBrowserState(entry, event, nextAttempt) {
248
+ if (entry.connectionID !== event.connectionID || entry.browserState === event.browserState)
249
+ return undefined;
250
+ return { entry: { ...entry, browserState: event.browserState }, nextAttempt, effects: [] };
251
+ }
252
+ function settleRequest(entry, event, command) {
253
+ const cancel = {
254
+ type: "emit-control",
255
+ control: { type: "cancel", connectionID: entry.connectionID, requestID: event.requestID },
256
+ };
257
+ // The interrupted caller no longer waits; only the desktop needs to stop.
258
+ if (event.type === "request.cancelled")
259
+ return [cancel];
260
+ const settle = (settlement) => ({
261
+ type: "settle-request",
262
+ requestID: event.requestID,
263
+ settlement,
264
+ });
265
+ if (event.type === "request.timed-out")
266
+ return [settle({ ok: false, error: timedOut(command.action.type) }), cancel];
267
+ if (event.type === "request.dispatch-failed")
268
+ return [settle({ ok: false, error: dispatchFailed(command.action.type, event.error) })];
269
+ if (event.outcome.type === "success")
270
+ return [settle({ ok: true, result: event.outcome.result })];
271
+ return [
272
+ settle({
273
+ ok: false,
274
+ error: new Tool.Error({ message: `[browser.${event.outcome.code}] ${event.outcome.message}` }),
275
+ }),
276
+ ];
277
+ }
278
+ function failPending(entry) {
279
+ return Array.from(entry.pending.keys(), (requestID) => ({
280
+ type: "settle-request",
281
+ requestID,
282
+ settlement: { ok: false, error: disconnectedAfterDispatch() },
283
+ }));
284
+ }
285
+ function syncWarning(event, sync) {
286
+ const action = sync.allow ? "grant" : "revoke";
287
+ if (event.type === "permissions.failed")
288
+ return [{ type: "warn", message: `Browser permission ${action} failed`, error: event.error }];
289
+ if (event.type === "permissions.timed-out")
290
+ return [
291
+ {
292
+ type: "warn",
293
+ message: `Browser permission ${action} timed out after ${PERMISSION_SYNC_TIMEOUT_MS} ms`,
294
+ error: undefined,
295
+ },
296
+ ];
297
+ return [];
298
+ }
299
+ /**
300
+ * The session's permissions with exactly one set of browser allows (`allow`) or none, every other rule kept in order.
301
+ * Undefined when they already are, so a replace writes nothing.
302
+ */
303
+ export function reconcileBrowserPermissions(current, allow) {
304
+ const rules = current ?? [];
305
+ const kept = rules.filter((rule) => rule.effect !== "allow" ||
306
+ !ACCESS.some((access) => access.action === rule.action && access.resource === rule.resource));
307
+ const next = allow ? [...kept, ...ACCESS.map((rule) => ({ ...rule, effect: "allow" }))] : kept;
308
+ const unchanged = next.length === rules.length &&
309
+ next.every((rule, index) => rule.action === rules[index]?.action &&
310
+ rule.resource === rules[index]?.resource &&
311
+ rule.effect === rules[index]?.effect);
312
+ return unchanged ? undefined : next;
313
+ }
314
+ export function isConnectionDisposed(state) {
315
+ return state.status === "disposed";
316
+ }
317
+ /** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
318
+ export function selectNextAttempt(state) {
319
+ return state.nextAttempt;
320
+ }
321
+ /** The attempt of the session's attachment with `connectionID`, attaching or attached. */
322
+ export function selectAttachment(state, sessionID, connectionID) {
323
+ if (state.status === "disposed")
324
+ return undefined;
325
+ const entry = state.sessions.get(sessionID);
326
+ if (entry?.status === "revoking" || entry?.connectionID !== connectionID)
327
+ return undefined;
328
+ return entry.attempt;
329
+ }
330
+ export function isAttachedConnection(state, sessionID, connectionID) {
331
+ if (state.status === "disposed")
332
+ return false;
333
+ const entry = state.sessions.get(sessionID);
334
+ return entry?.status === "attached" && entry.connectionID === connectionID;
335
+ }
336
+ export function selectPendingCommand(state, sessionID, connectionID, requestID) {
337
+ if (state.status === "disposed")
338
+ return undefined;
339
+ const entry = state.sessions.get(sessionID);
340
+ if (entry?.status !== "attached" || entry.connectionID !== connectionID)
341
+ return undefined;
342
+ return entry.pending.get(requestID);
343
+ }
344
+ /** The attachment and tab a browser tool call targets, or the error the tool returns. */
345
+ export function selectTarget(state, sessionID, action) {
346
+ const entry = state.status === "active" ? state.sessions.get(sessionID) : undefined;
347
+ if (!entry || entry.status === "revoking")
348
+ return {
349
+ ok: false,
350
+ error: new Tool.Error({
351
+ message: "[browser.disconnected] No desktop browser is connected to this session. Open this session in the desktop app and wait for it to connect. Then call browser.tabs.list({}). Repeating browser actions while disconnected will not help.",
352
+ }),
353
+ };
354
+ if (entry.status === "attaching")
355
+ return {
356
+ ok: false,
357
+ error: new Tool.Error({
358
+ message: "[browser.disconnected] The desktop browser is still connecting to this session; no action ran. Call browser.tabs.list({}) once it finishes connecting.",
359
+ }),
360
+ };
361
+ const tab = "tabID" in action ? entry.browserState.tabs.find((tab) => tab.id === action.tabID) : undefined;
362
+ if ("tabID" in action && !tab)
363
+ return {
364
+ ok: false,
365
+ error: new Tool.Error({
366
+ message: "[browser.tab_unavailable] This tab is closed or does not belong to the connected session. Call browser.tabs.list({}) and use an exact returned tabID. If no tabs exist, use browser.tabs.open({}). Never substitute a request ID, file ID, or element ref for tabID.",
367
+ }),
368
+ };
369
+ return { ok: true, connectionID: entry.connectionID, tab };
370
+ }
371
+ function disconnectedBeforeDispatch() {
372
+ return new Tool.Error({
373
+ message: "[browser.disconnected] The desktop browser disconnected before this action was sent; no action ran. Reconnect this session in the desktop app, then call browser.tabs.list({}).",
374
+ });
375
+ }
376
+ function disconnectedAfterDispatch() {
377
+ return new Tool.Error({
378
+ message: "[browser.disconnected] Browser connection closed; the action may already have run. Reconnect this session in the desktop app, call browser.tabs.list({}), and inspect the target tab with browser.snapshot({tabID}). Do not repeat clicks, submissions, uploads, or evaluations until their outcome is known.",
379
+ });
380
+ }
381
+ function dispatchFailed(action, error) {
382
+ return new Tool.Error({
383
+ message: `Could not dispatch browser.${action}. Check the desktop connection and call browser.tabs.list({}) before deciding whether to retry.`,
384
+ error,
385
+ });
386
+ }
387
+ function timedOut(action) {
388
+ return new Tool.Error({
389
+ message: `[browser.timeout] browser.${action} did not finish within ${REQUEST_TIMEOUT_MS / 1000} seconds; its outcome is unknown. Check the desktop connection, call browser.tabs.list({}), and inspect the tab or browser.files.list({tabID}) for completed work. Do not blindly repeat a mutating action or start another recording.`,
390
+ });
391
+ }
@@ -0,0 +1,33 @@
1
+ export * as BrowserProxyMachine from "./proxy-machine.js";
2
+ export type State = {
3
+ readonly status: "open";
4
+ } | {
5
+ readonly status: "closed";
6
+ };
7
+ export type Event = {
8
+ readonly type: "close";
9
+ };
10
+ /** `shutdown` aborts pending connects and destroys every tunnel and client socket, once. */
11
+ export type ProxyEffect = "shutdown";
12
+ export type Transition = {
13
+ readonly state: State;
14
+ readonly effects: readonly ProxyEffect[];
15
+ };
16
+ export declare const initial: State;
17
+ export declare function transition(state: State, event: Event): Transition;
18
+ /**
19
+ * Whether a client connection or a tunnel that just opened may join the proxy. One that arrives
20
+ * after `close` is destroyed instead, since shutdown already ran.
21
+ */
22
+ export declare function admits(state: State): state is {
23
+ readonly status: "open";
24
+ };
25
+ /**
26
+ * One tunnel socket's read side: at most one transport read in flight, and no reads after EOF or
27
+ * destruction.
28
+ */
29
+ export type ReadState = "idle" | "reading" | "ended" | "destroyed";
30
+ /** Chromium pulled, a transport read answered with data or EOF, or the socket was destroyed. */
31
+ export type ReadEvent = "pull" | "chunk" | "eof" | "destroyed";
32
+ /** Returns `state` itself when the event does not apply, so callers compare to see whether to act. */
33
+ export declare function transitionRead(state: ReadState, event: ReadEvent): ReadState;
@@ -0,0 +1,30 @@
1
+ export * as BrowserProxyMachine from "./proxy-machine.js";
2
+ export const initial = { status: "open" };
3
+ const CLOSED = { status: "closed" };
4
+ export function transition(state, event) {
5
+ if (state.status === "closed")
6
+ return { state, effects: [] };
7
+ switch (event.type) {
8
+ case "close":
9
+ return { state: CLOSED, effects: ["shutdown"] };
10
+ }
11
+ }
12
+ /**
13
+ * Whether a client connection or a tunnel that just opened may join the proxy. One that arrives
14
+ * after `close` is destroyed instead, since shutdown already ran.
15
+ */
16
+ export function admits(state) {
17
+ return state.status === "open";
18
+ }
19
+ /** Returns `state` itself when the event does not apply, so callers compare to see whether to act. */
20
+ export function transitionRead(state, event) {
21
+ if (state === "destroyed")
22
+ return state;
23
+ if (event === "destroyed")
24
+ return "destroyed";
25
+ if (event === "pull")
26
+ return state === "idle" ? "reading" : state;
27
+ if (state !== "reading")
28
+ return state;
29
+ return event === "eof" ? "ended" : "idle";
30
+ }
package/dist/proxy.js CHANGED
@@ -3,6 +3,7 @@ import { randomBytes, timingSafeEqual } from "node:crypto";
3
3
  import { Agent, createServer, request, } from "node:http";
4
4
  import { Duplex } from "node:stream";
5
5
  import { Schema } from "effect";
6
+ import { BrowserProxyMachine } from "./proxy-machine.js";
6
7
  import { Browser } from "./rpc.js";
7
8
  // Desktop-only leaf. This listener is never loaded by the server plugin.
8
9
  export async function make(transport) {
@@ -12,7 +13,8 @@ export async function make(transport) {
12
13
  const clients = new Set();
13
14
  const tunnels = new Set();
14
15
  const pending = new Set();
15
- let closed = false;
16
+ const closed = Promise.withResolvers();
17
+ let state = BrowserProxyMachine.initial;
16
18
  const authorized = (value) => {
17
19
  if (!value)
18
20
  return false;
@@ -20,7 +22,7 @@ export async function make(transport) {
20
22
  return actual.length === expected.length && timingSafeEqual(actual, expected);
21
23
  };
22
24
  const connect = async (target, signal) => {
23
- if (closed)
25
+ if (!BrowserProxyMachine.admits(state))
24
26
  throw new Error("Browser proxy is closed");
25
27
  const abort = new AbortController();
26
28
  const cancel = () => abort.abort();
@@ -31,7 +33,7 @@ export async function make(transport) {
31
33
  try {
32
34
  const id = await transport.open(target, abort.signal);
33
35
  const socket = new TunnelSocket(transport, id);
34
- if (closed || abort.signal.aborted) {
36
+ if (!BrowserProxyMachine.admits(state) || abort.signal.aborted) {
35
37
  socket.destroy();
36
38
  throw new Error("Browser proxy connection was cancelled");
37
39
  }
@@ -57,11 +59,18 @@ export async function make(transport) {
57
59
  server.requestTimeout = 30_000;
58
60
  server.headersTimeout = 10_000;
59
61
  server.on("connection", (socket) => {
62
+ // A backlog connection can surface while the server drains after `close()`.
63
+ if (!BrowserProxyMachine.admits(state)) {
64
+ socket.destroy();
65
+ return;
66
+ }
60
67
  clients.add(socket);
61
68
  socket.on("error", () => socket.destroy());
62
69
  socket.once("close", () => clients.delete(socket));
63
70
  });
64
71
  const upgrade = (incoming, socket, head, connectMethod) => {
72
+ // Setup can throw before the close listeners pair the tunnel with the client socket.
73
+ let opened;
65
74
  void (async () => {
66
75
  if (!authorized(incoming.headers["proxy-authorization"])) {
67
76
  socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="OpenCode Browser Proxy"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
@@ -78,6 +87,7 @@ export async function make(transport) {
78
87
  socket.pause();
79
88
  try {
80
89
  const tunnel = await connect(target(url), abort.signal);
90
+ opened = tunnel;
81
91
  if (socket.destroyed) {
82
92
  tunnel.destroy();
83
93
  return;
@@ -107,6 +117,7 @@ export async function make(transport) {
107
117
  socket.off("close", cancel);
108
118
  }
109
119
  })().catch(() => {
120
+ opened?.destroy();
110
121
  if (!socket.destroyed)
111
122
  socket.end("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
112
123
  });
@@ -127,21 +138,21 @@ export async function make(transport) {
127
138
  const address = server.address();
128
139
  if (!address || typeof address === "string")
129
140
  throw new Error("Browser proxy did not bind a TCP address");
130
- let closing;
131
141
  return {
132
142
  url: `http://127.0.0.1:${address.port}`,
133
143
  host: "127.0.0.1",
134
144
  port: address.port,
135
145
  credentials: { username, password },
136
146
  close() {
137
- if (closing)
138
- return closing;
139
- closed = true;
140
- pending.forEach((abort) => abort.abort());
141
- tunnels.forEach((socket) => socket.destroy());
142
- clients.forEach((socket) => socket.destroy());
143
- closing = new Promise((resolve) => server.close(() => resolve()));
144
- return closing;
147
+ const next = BrowserProxyMachine.transition(state, { type: "close" });
148
+ state = next.state;
149
+ next.effects.forEach(() => {
150
+ pending.forEach((abort) => abort.abort());
151
+ tunnels.forEach((socket) => socket.destroy());
152
+ clients.forEach((socket) => socket.destroy());
153
+ server.close(() => closed.resolve());
154
+ });
155
+ return closed.promise;
145
156
  },
146
157
  };
147
158
  }
@@ -162,8 +173,11 @@ async function forward(incoming, response, connect, authorized) {
162
173
  incoming.once("aborted", cancel);
163
174
  response.once("close", cancel);
164
175
  const agent = new Agent({ keepAlive: false, maxSockets: 1 });
176
+ // An abort before the request adopts the tunnel leaves it out of `agent.destroy()`.
177
+ let opened;
165
178
  try {
166
179
  const tunnel = await connect(target(url), abort.signal);
180
+ opened = tunnel;
167
181
  agent.createConnection = () => tunnel;
168
182
  const headers = forwardedHeaders(incoming.headers);
169
183
  headers.host = url.host;
@@ -194,6 +208,7 @@ async function forward(incoming, response, connect, authorized) {
194
208
  incoming.off("aborted", cancel);
195
209
  response.off("close", cancel);
196
210
  agent.destroy();
211
+ opened?.destroy();
197
212
  }
198
213
  }
199
214
  function forwardedHeaders(input) {
@@ -231,7 +246,7 @@ class TunnelSocket extends Duplex {
231
246
  id;
232
247
  connecting = false;
233
248
  abort = new AbortController();
234
- pending = false;
249
+ reads = "idle";
235
250
  constructor(transport, id) {
236
251
  super({ highWaterMark: Browser.TUNNEL_CHUNK_BYTES, allowHalfOpen: true });
237
252
  this.transport = transport;
@@ -239,12 +254,10 @@ class TunnelSocket extends Duplex {
239
254
  this.on("error", () => this.destroy());
240
255
  }
241
256
  _read() {
242
- if (this.pending || this.destroyed)
257
+ if (!this.advance("pull"))
243
258
  return;
244
- this.pending = true;
245
259
  void this.transport.read(this.id, this.abort.signal).then((result) => {
246
- this.pending = false;
247
- if (this.destroyed)
260
+ if (!this.advance(result.eof ? "eof" : "chunk"))
248
261
  return;
249
262
  if (result.eof) {
250
263
  this.push(null);
@@ -254,6 +267,13 @@ class TunnelSocket extends Duplex {
254
267
  this._read();
255
268
  }, (error) => this.destroy(asError(error)));
256
269
  }
270
+ advance(event) {
271
+ const next = BrowserProxyMachine.transitionRead(this.reads, event);
272
+ if (next === this.reads)
273
+ return false;
274
+ this.reads = next;
275
+ return true;
276
+ }
257
277
  _write(chunk, encoding, callback) {
258
278
  const data = typeof chunk === "string" ? Buffer.from(chunk, encoding) : chunk;
259
279
  void (async () => {
@@ -265,6 +285,7 @@ class TunnelSocket extends Duplex {
265
285
  void this.transport.write(this.id, new Uint8Array(), true, this.abort.signal).then(() => callback(), (error) => callback(asError(error)));
266
286
  }
267
287
  _destroy(error, callback) {
288
+ this.advance("destroyed");
268
289
  this.abort.abort();
269
290
  void this.transport
270
291
  .close(this.id)
package/dist/skill.js CHANGED
@@ -8,7 +8,7 @@ export const info = Skill.Info.make({
8
8
  id,
9
9
  name: Skill.Name.make("Browser"),
10
10
  description: "Use the in-app browser: open and read pages, click and fill forms, take screenshots, check console and network logs, and profile performance and memory. Load it before your first browser tool call.",
11
- path: AbsolutePath.make("/builtin/browser.md"),
11
+ path: AbsolutePath.make("skill://browser/SKILL.md"),
12
12
  content: [
13
13
  "# In-app browser",
14
14
  "",
package/dist/tools.d.ts CHANGED
@@ -219,16 +219,7 @@ export declare const register: (ctx: Pick<Context, "location" | "skill" | "tool"
219
219
  readonly text?: string | undefined;
220
220
  readonly timeoutMs?: number | undefined;
221
221
  }) => Effect.Effect<{
222
- tab: {
223
- readonly id: string & import("effect/Brand").Brand<"Browser.TabID">;
224
- readonly url: string;
225
- readonly title: string;
226
- readonly loading: boolean;
227
- readonly loadError?: string | undefined;
228
- readonly canGoBack: boolean;
229
- readonly canGoForward: boolean;
230
- readonly generation: number;
231
- } | undefined;
222
+ tab: Browser.Tab | undefined;
232
223
  inspect: () => Effect.Effect<{
233
224
  readonly resources: readonly string[];
234
225
  readonly key: string;