@radheim/plugin-browser 0.0.0-stage → 2.4.3

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,435 @@
1
+ export * as BrowserMachine from "./machine.js";
2
+ import { Tool } from "@radheim/schema/tool";
3
+ import { BrowserSkill } from "./skill.js";
4
+ import { Wildcard } from "./wildcard.js";
5
+ /** How long one permission sync (`session.get` and, when needed, `session.update`) may take. The desktop waits 15 s. */
6
+ export const PERMISSION_SYNC_TIMEOUT_MS = 10_000;
7
+ /** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */
8
+ export const REQUEST_TIMEOUT_MS = 60_000;
9
+ /** The browser tools and their skill, which an attachment allows together. */
10
+ export const ACCESS = [
11
+ { action: "browser", resource: "*" },
12
+ { action: "skill", resource: BrowserSkill.id },
13
+ ];
14
+ export function createConnectionState() {
15
+ return { status: "active", nextAttempt: 1, sessions: new Map() };
16
+ }
17
+ export function transitionConnection(state, event) {
18
+ if (event.type === "disposed")
19
+ return dispose(state);
20
+ // A request whose attachment closed or was replaced after the tool picked it was never sent.
21
+ if (event.type === "request.started" && !isAttachedConnection(state, event.sessionID, event.connectionID))
22
+ return {
23
+ state,
24
+ effects: [
25
+ {
26
+ type: "settle-request",
27
+ requestID: event.requestID,
28
+ settlement: { ok: false, error: disconnectedBeforeDispatch() },
29
+ },
30
+ ],
31
+ };
32
+ const entry = state.sessions.get(event.sessionID);
33
+ if (state.status === "disposed") {
34
+ if (!entry || entry.status !== "revoking")
35
+ return { state, effects: [] };
36
+ const step = transitionRevoking(entry, event, state.nextAttempt);
37
+ if (!step)
38
+ return { state, effects: [] };
39
+ const sessions = new Map(state.sessions);
40
+ if (step.entry)
41
+ sessions.set(event.sessionID, step.entry);
42
+ if (!step.entry)
43
+ sessions.delete(event.sessionID);
44
+ return {
45
+ state: { status: "disposed", nextAttempt: step.nextAttempt, sessions },
46
+ effects: sessions.size ? step.effects : [...step.effects, { type: "notify-drained" }],
47
+ };
48
+ }
49
+ const step = transitionSession(entry, event, state.nextAttempt);
50
+ if (!step)
51
+ return { state, effects: [] };
52
+ const sessions = new Map(state.sessions);
53
+ if (step.entry)
54
+ sessions.set(event.sessionID, step.entry);
55
+ if (!step.entry)
56
+ sessions.delete(event.sessionID);
57
+ return { state: { status: "active", nextAttempt: step.nextAttempt, sessions }, effects: step.effects };
58
+ }
59
+ function transitionSession(entry, event, nextAttempt) {
60
+ if (event.type === "attach.started")
61
+ return attach(entry, event, nextAttempt);
62
+ if (!entry)
63
+ return undefined;
64
+ if (entry.status === "revoking")
65
+ return transitionRevoking(entry, event, nextAttempt);
66
+ if (entry.status === "attaching")
67
+ return transitionAttaching(entry, event, nextAttempt);
68
+ return transitionAttached(entry, event, nextAttempt);
69
+ }
70
+ function attach(entry, event, nextAttempt) {
71
+ if (event.attempt !== nextAttempt)
72
+ return undefined;
73
+ const attaching = (sync) => ({
74
+ status: "attaching",
75
+ attempt: event.attempt,
76
+ connectionID: event.connectionID,
77
+ sync,
78
+ });
79
+ // A sync already in flight finishes first; the grant waits for it, so two writes never interleave.
80
+ if (entry?.status === "attaching")
81
+ return {
82
+ entry: attaching(entry.sync),
83
+ nextAttempt: nextAttempt + 1,
84
+ effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }],
85
+ };
86
+ if (entry?.status === "revoking")
87
+ return { entry: attaching(entry.sync), nextAttempt: nextAttempt + 1, effects: [] };
88
+ const sync = { attempt: nextAttempt + 1, allow: true };
89
+ const effects = entry?.status === "attached"
90
+ ? [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }]
91
+ : [];
92
+ return {
93
+ entry: attaching(sync),
94
+ nextAttempt: nextAttempt + 2,
95
+ effects: [...effects, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
96
+ };
97
+ }
98
+ function transitionAttaching(entry, event, nextAttempt) {
99
+ if (event.type === "permissions.synced" ||
100
+ event.type === "permissions.failed" ||
101
+ event.type === "permissions.timed-out") {
102
+ if (event.attempt !== entry.sync.attempt)
103
+ return undefined;
104
+ const warning = syncWarning(event, entry.sync);
105
+ // The revoke that ran before this attachment settled; now grant.
106
+ if (!entry.sync.allow) {
107
+ const sync = { attempt: nextAttempt, allow: true };
108
+ return {
109
+ entry: { ...entry, sync },
110
+ nextAttempt: nextAttempt + 1,
111
+ effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
112
+ };
113
+ }
114
+ if (event.type === "permissions.synced")
115
+ return {
116
+ entry: {
117
+ status: "attached",
118
+ attempt: entry.attempt,
119
+ connectionID: entry.connectionID,
120
+ browserState: { tabs: [], focusedTabID: null },
121
+ pending: new Map(),
122
+ },
123
+ nextAttempt,
124
+ effects: [
125
+ { type: "emit-control", control: { type: "attached", connectionID: entry.connectionID, version: 4 } },
126
+ ],
127
+ };
128
+ // A grant that timed out may still have written its rules; revoke them.
129
+ const sync = { attempt: nextAttempt, allow: false };
130
+ return {
131
+ entry: { status: "revoking", sync, deleted: false },
132
+ nextAttempt: nextAttempt + 1,
133
+ effects: [
134
+ ...warning,
135
+ { type: "close-attachment", attempt: entry.attempt, outcome: "unavailable" },
136
+ { type: "sync-permissions", sessionID: event.sessionID, ...sync },
137
+ ],
138
+ };
139
+ }
140
+ if ((event.type === "attach.closed" && event.attempt === entry.attempt) ||
141
+ event.type === "session.moved" ||
142
+ event.type === "session.deleted")
143
+ return {
144
+ entry: { status: "revoking", sync: entry.sync, deleted: event.type === "session.deleted" },
145
+ nextAttempt,
146
+ effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
147
+ };
148
+ return undefined;
149
+ }
150
+ function transitionAttached(entry, event, nextAttempt) {
151
+ if (event.type === "state.updated")
152
+ return updateBrowserState(entry, event, nextAttempt);
153
+ if (event.type === "request.started") {
154
+ if (entry.pending.has(event.requestID))
155
+ return undefined;
156
+ return {
157
+ entry: { ...entry, pending: new Map(entry.pending).set(event.requestID, event.command) },
158
+ nextAttempt,
159
+ effects: [
160
+ {
161
+ type: "dispatch-command",
162
+ sessionID: event.sessionID,
163
+ connectionID: entry.connectionID,
164
+ requestID: event.requestID,
165
+ },
166
+ ],
167
+ };
168
+ }
169
+ if (event.type === "request.dispatch-failed" ||
170
+ event.type === "request.settled" ||
171
+ event.type === "request.timed-out" ||
172
+ event.type === "request.cancelled") {
173
+ const command = entry.connectionID === event.connectionID ? entry.pending.get(event.requestID) : undefined;
174
+ if (!command)
175
+ return undefined;
176
+ const pending = new Map(entry.pending);
177
+ pending.delete(event.requestID);
178
+ return { entry: { ...entry, pending }, nextAttempt, effects: settleRequest(entry, event, command) };
179
+ }
180
+ if (event.type === "session.deleted")
181
+ return {
182
+ entry: undefined,
183
+ nextAttempt,
184
+ effects: [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
185
+ };
186
+ if ((event.type === "attach.closed" && event.attempt === entry.attempt) || event.type === "session.moved")
187
+ return revokeAttached(entry, event.sessionID, nextAttempt);
188
+ return undefined;
189
+ }
190
+ function transitionRevoking(entry, event, nextAttempt) {
191
+ if (event.type === "session.deleted")
192
+ return entry.deleted ? undefined : { entry: { ...entry, deleted: true }, nextAttempt, effects: [] };
193
+ if (event.type !== "permissions.synced" &&
194
+ event.type !== "permissions.failed" &&
195
+ event.type !== "permissions.timed-out")
196
+ return undefined;
197
+ if (event.attempt !== entry.sync.attempt)
198
+ return undefined;
199
+ const warning = syncWarning(event, entry.sync);
200
+ // A grant settled after its attachment closed, or timed out and may still have written: revoke it.
201
+ if (entry.sync.allow && !entry.deleted) {
202
+ const sync = { attempt: nextAttempt, allow: false };
203
+ return {
204
+ entry: { status: "revoking", sync, deleted: false },
205
+ nextAttempt: nextAttempt + 1,
206
+ effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
207
+ };
208
+ }
209
+ return { entry: undefined, nextAttempt, effects: warning };
210
+ }
211
+ function dispose(state) {
212
+ if (state.status === "disposed")
213
+ return { state, effects: [] };
214
+ const effects = [];
215
+ const sessions = new Map();
216
+ const nextAttempt = Array.from(state.sessions).reduce((attempt, [sessionID, entry]) => {
217
+ if (entry.status === "revoking") {
218
+ sessions.set(sessionID, entry);
219
+ return attempt;
220
+ }
221
+ if (entry.status === "attaching") {
222
+ sessions.set(sessionID, { status: "revoking", sync: entry.sync, deleted: false });
223
+ effects.push({ type: "close-attachment", attempt: entry.attempt, outcome: "closed" });
224
+ return attempt;
225
+ }
226
+ const step = revokeAttached(entry, sessionID, attempt);
227
+ if (step.entry)
228
+ sessions.set(sessionID, step.entry);
229
+ effects.push(...step.effects);
230
+ return step.nextAttempt;
231
+ }, state.nextAttempt);
232
+ if (!sessions.size)
233
+ effects.push({ type: "notify-drained" });
234
+ return { state: { status: "disposed", nextAttempt, sessions }, effects };
235
+ }
236
+ function revokeAttached(entry, sessionID, nextAttempt) {
237
+ const sync = { attempt: nextAttempt, allow: false };
238
+ return {
239
+ entry: { status: "revoking", sync, deleted: false },
240
+ nextAttempt: nextAttempt + 1,
241
+ effects: [
242
+ ...failPending(entry),
243
+ { type: "close-attachment", attempt: entry.attempt, outcome: "closed" },
244
+ { type: "sync-permissions", sessionID, ...sync },
245
+ ],
246
+ };
247
+ }
248
+ function updateBrowserState(entry, event, nextAttempt) {
249
+ if (entry.connectionID !== event.connectionID || entry.browserState === event.browserState)
250
+ return undefined;
251
+ return { entry: { ...entry, browserState: event.browserState }, nextAttempt, effects: [] };
252
+ }
253
+ function settleRequest(entry, event, command) {
254
+ const cancel = {
255
+ type: "emit-control",
256
+ control: { type: "cancel", connectionID: entry.connectionID, requestID: event.requestID },
257
+ };
258
+ // The interrupted caller no longer waits; only the desktop needs to stop.
259
+ if (event.type === "request.cancelled")
260
+ return [cancel];
261
+ const settle = (settlement) => ({
262
+ type: "settle-request",
263
+ requestID: event.requestID,
264
+ settlement,
265
+ });
266
+ if (event.type === "request.timed-out")
267
+ return [settle({ ok: false, error: timedOut(command.action.type) }), cancel];
268
+ if (event.type === "request.dispatch-failed")
269
+ return [settle({ ok: false, error: dispatchFailed(command.action.type, event.error) })];
270
+ if (event.outcome.type === "success")
271
+ return [settle({ ok: true, result: event.outcome.result })];
272
+ return [
273
+ settle({
274
+ ok: false,
275
+ // The code stays readable apart from the message, so the server acts on it without parsing text.
276
+ error: new Tool.Error({
277
+ message: `[browser.${event.outcome.code}] ${event.outcome.message}`,
278
+ metadata: { code: event.outcome.code },
279
+ }),
280
+ }),
281
+ ];
282
+ }
283
+ function failPending(entry) {
284
+ return Array.from(entry.pending.keys(), (requestID) => ({
285
+ type: "settle-request",
286
+ requestID,
287
+ settlement: { ok: false, error: disconnectedAfterDispatch() },
288
+ }));
289
+ }
290
+ function syncWarning(event, sync) {
291
+ const action = sync.allow ? "grant" : "revoke";
292
+ if (event.type === "permissions.failed")
293
+ return [{ type: "warn", message: `Browser permission ${action} failed`, error: event.error }];
294
+ if (event.type === "permissions.timed-out")
295
+ return [
296
+ {
297
+ type: "warn",
298
+ message: `Browser permission ${action} timed out after ${PERMISSION_SYNC_TIMEOUT_MS} ms`,
299
+ error: undefined,
300
+ },
301
+ ];
302
+ return [];
303
+ }
304
+ /**
305
+ * The session's permissions with exactly one set of browser allows (`allow`) or none, every other rule kept in order.
306
+ * Undefined when they already are, so a replace writes nothing.
307
+ */
308
+ export function reconcileBrowserPermissions(current, allow) {
309
+ const rules = current ?? [];
310
+ const kept = rules.filter((rule) => !isGrant(rule));
311
+ const next = allow ? [...kept, ...ACCESS.map((rule) => ({ ...rule, effect: "allow" }))] : kept;
312
+ const unchanged = next.length === rules.length &&
313
+ next.every((rule, index) => rule.action === rules[index]?.action &&
314
+ rule.resource === rules[index]?.resource &&
315
+ rule.effect === rules[index]?.effect);
316
+ return unchanged ? undefined : next;
317
+ }
318
+ /**
319
+ * One of the allows an attachment grants. A grant that holds only the browser allow, as some versions wrote it, is
320
+ * recognised too, so a revoke or the startup sweep removes it. A user rule of the same shape cannot be told apart
321
+ * from it.
322
+ */
323
+ export function isGrant(rule) {
324
+ return rule.effect === "allow" && ACCESS.some((access) => access.action === rule.action && access.resource === rule.resource);
325
+ }
326
+ /**
327
+ * The rule that decides `browser` on `operation`, picked as core's `Permission.evaluate` picks it: the last rule whose
328
+ * action and resource patterns both match. Undefined when none matches.
329
+ */
330
+ export function selectBrowserRule(rules, operation) {
331
+ const ignoreCase = process.platform === "win32";
332
+ return rules.findLast((rule) => Wildcard.match("browser", rule.action, ignoreCase) && Wildcard.match(operation, rule.resource, ignoreCase));
333
+ }
334
+ export function isConnectionDisposed(state) {
335
+ return state.status === "disposed";
336
+ }
337
+ /** Whether the session has an attachment or a permission sync in flight, either of which owns its browser rules. */
338
+ export function hasSession(state, sessionID) {
339
+ return state.sessions.has(sessionID);
340
+ }
341
+ /** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
342
+ export function selectNextAttempt(state) {
343
+ return state.nextAttempt;
344
+ }
345
+ /** The attempt of the session's attachment with `connectionID`, attaching or attached. */
346
+ export function selectAttachment(state, sessionID, connectionID) {
347
+ if (state.status === "disposed")
348
+ return undefined;
349
+ const entry = state.sessions.get(sessionID);
350
+ if (entry?.status === "revoking" || entry?.connectionID !== connectionID)
351
+ return undefined;
352
+ return entry.attempt;
353
+ }
354
+ export function isAttachedConnection(state, sessionID, connectionID) {
355
+ if (state.status === "disposed")
356
+ return false;
357
+ const entry = state.sessions.get(sessionID);
358
+ return entry?.status === "attached" && entry.connectionID === connectionID;
359
+ }
360
+ export function selectPendingCommand(state, sessionID, connectionID, requestID) {
361
+ if (state.status === "disposed")
362
+ return undefined;
363
+ const entry = state.sessions.get(sessionID);
364
+ if (entry?.status !== "attached" || entry.connectionID !== connectionID)
365
+ return undefined;
366
+ return entry.pending.get(requestID);
367
+ }
368
+ /**
369
+ * The session's attached connection, or the error a tool call returns while it has none. Reads nothing about its tabs,
370
+ * so it may answer before the call is authorized.
371
+ */
372
+ export function selectConnection(state, sessionID) {
373
+ const entry = state.status === "active" ? state.sessions.get(sessionID) : undefined;
374
+ if (!entry || entry.status === "revoking")
375
+ return {
376
+ ok: false,
377
+ error: new Tool.Error({
378
+ message: "No browser is attached to this session. It attaches when the session is open in the OpenCode desktop app. No action ran. Continue without the browser; retry only after it attaches.",
379
+ }),
380
+ };
381
+ if (entry.status === "attaching")
382
+ return {
383
+ ok: false,
384
+ error: new Tool.Error({
385
+ message: "The desktop browser is still connecting to this session. No action ran. Retry only after it attaches.",
386
+ }),
387
+ };
388
+ return { ok: true, connectionID: entry.connectionID, tabs: entry.browserState.tabs };
389
+ }
390
+ /**
391
+ * The attachment and tab a browser tool call targets, or the error the tool returns. The error for an unknown tab lists
392
+ * the session's tabs, so this runs only once the call is authorized.
393
+ */
394
+ export function selectTarget(state, sessionID, action) {
395
+ const connection = selectConnection(state, sessionID);
396
+ if (!connection.ok)
397
+ return connection;
398
+ const tab = "tabID" in action ? connection.tabs.find((tab) => tab.id === action.tabID) : undefined;
399
+ if ("tabID" in action && !tab)
400
+ return { ok: false, error: tabUnavailable(action.tabID, connection.tabs) };
401
+ return { ok: true, connectionID: connection.connectionID, tab };
402
+ }
403
+ // Lists the session's open tabs, bounded, so the next call can use one directly.
404
+ function tabUnavailable(tabID, tabs) {
405
+ const listed = tabs
406
+ .slice(0, 10)
407
+ .map((tab) => `${tab.id} (${tab.url.length > 100 ? `${tab.url.slice(0, 100)}…` : tab.url})`);
408
+ const more = tabs.length > listed.length ? `, and ${tabs.length - listed.length} more from browser.tabs.list({})` : "";
409
+ return new Tool.Error({
410
+ message: `[browser.tab_unavailable] No open tab in this session has the ID ${tabID}; it was closed or came from another session. ${listed.length
411
+ ? `Open tabs: ${listed.join(", ")}${more}. Use one of these IDs`
412
+ : "This session has no open tabs. Open one with browser.tabs.open({ url })"}. Never use a request ID, file ID, or element ref as a tabID.`,
413
+ });
414
+ }
415
+ function disconnectedBeforeDispatch() {
416
+ return new Tool.Error({
417
+ message: "[browser.disconnected] The desktop app disconnected before this action was sent; no action ran. Call browser.tabs.list({}) to check whether it has reconnected before you try again.",
418
+ });
419
+ }
420
+ function disconnectedAfterDispatch() {
421
+ return new Tool.Error({
422
+ message: "[browser.disconnected] The desktop app disconnected while this action ran; the action may already have run. Once browser.tabs.list({}) succeeds again, inspect the tab with browser.snapshot({tabID}) before you repeat a click, submission, upload, or evaluation.",
423
+ });
424
+ }
425
+ function dispatchFailed(action, error) {
426
+ return new Tool.Error({
427
+ message: `Could not dispatch browser.${action}. Check the desktop connection and call browser.tabs.list({}) before deciding whether to retry.`,
428
+ error,
429
+ });
430
+ }
431
+ function timedOut(action) {
432
+ return new Tool.Error({
433
+ 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.`,
434
+ });
435
+ }
@@ -0,0 +1,7 @@
1
+ /** Remote preview requests use portable workspace-relative segments, never a server or OS address. */
2
+ export declare function previewPath(path: string, windows?: boolean): boolean;
3
+ export declare function windowsPreviewSegment(part: string): boolean;
4
+ /** A stable, session-scoped display address with the file tree's relative path, never the API endpoint. */
5
+ export declare function workspacePrefix(session: string): string;
6
+ /** Parse before URL normalization: reject alternate authorities, dot segments and encoded separators. */
7
+ export declare function remotePath(address: string, prefix: string, windows?: boolean): string | undefined;
@@ -0,0 +1,28 @@
1
+ /** Remote preview requests use portable workspace-relative segments, never a server or OS address. */
2
+ export function previewPath(path, windows = false) {
3
+ return !/^[a-z]:\//i.test(path) && path.split("/").every((part) => !!part && part !== "." && part !== ".." &&
4
+ !/[\\\u0000-\u001f]/.test(part) && (!windows || windowsPreviewSegment(part)));
5
+ }
6
+ export function windowsPreviewSegment(part) {
7
+ return !/[:\\]|[. ]$|^(?:con(?:in\$|out\$)?|nul|prn|aux|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part);
8
+ }
9
+ /** A stable, session-scoped display address with the file tree's relative path, never the API endpoint. */
10
+ export function workspacePrefix(session) {
11
+ return `workspace://${session.toLowerCase()}/`;
12
+ }
13
+ /** Parse before URL normalization: reject alternate authorities, dot segments and encoded separators. */
14
+ export function remotePath(address, prefix, windows = false) {
15
+ // A scheme and a session ID read the same in any case, and `workspacePrefix` writes them in lower case.
16
+ if (address.slice(0, prefix.length).toLowerCase() !== prefix)
17
+ return;
18
+ const encoded = address.slice(prefix.length).split(/[?#]/, 1)[0];
19
+ if (!encoded || /%(?:2f|5c)/i.test(encoded))
20
+ return;
21
+ try {
22
+ const path = decodeURIComponent(encoded);
23
+ return previewPath(path, windows) ? path : undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
@@ -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
+ }
@@ -0,0 +1,29 @@
1
+ export * as BrowserProxy from "./proxy.js";
2
+ import { Duplex } from "node:stream";
3
+ import { Browser } from "./rpc.js";
4
+ /** Legacy chunked RPC transport. */
5
+ export type Transport = {
6
+ open(target: Browser.TunnelTarget, signal: AbortSignal): Promise<string>;
7
+ read(id: string, signal: AbortSignal): Promise<Browser.TunnelRead>;
8
+ write(id: string, data: Uint8Array, end: boolean, signal: AbortSignal): Promise<void>;
9
+ close(id: string): Promise<void>;
10
+ };
11
+ /** Streaming duplex transport backed by the prewarmed binary WebSocket multiplexer. */
12
+ export type StreamTransport = {
13
+ openStream(target: Browser.TunnelTarget, signal: AbortSignal): Promise<Duplex>;
14
+ /** Optional hook invoked when the underlying tunnel disconnects so idle pooled sockets are evicted immediately. */
15
+ onReset?(listener: () => void): () => void;
16
+ };
17
+ export type ProxyTransport = Transport | StreamTransport;
18
+ export type Proxy = Awaited<ReturnType<typeof make>>;
19
+ export declare function make(transport: ProxyTransport): Promise<{
20
+ url: string;
21
+ host: string;
22
+ port: number;
23
+ credentials: {
24
+ username: string;
25
+ password: string;
26
+ };
27
+ resetPools: () => void;
28
+ close(): Promise<void>;
29
+ }>;