@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,127 @@
1
+ export * as BrowserTunnelMachine from "./tunnel-machine.js";
2
+ // The server end of one desktop attachment's TCP tunnels. A tunnel leaves the pool when the desktop
3
+ // closes it or once both directions are finished, so a lost `tunnel.close` cannot hold a slot forever.
4
+ export const MAX_TUNNELS = 64;
5
+ export const initial = () => ({ status: "active", entries: new Map() });
6
+ const DISPOSED = { status: "disposed" };
7
+ export function transition(state, event) {
8
+ if (state.status === "disposed") {
9
+ // A connect that lands after disposal still owns a socket.
10
+ if (event.type === "open.connected" || event.type === "open.failed")
11
+ return destroy(state, event.id);
12
+ return unchanged(state);
13
+ }
14
+ if (event.type === "disposed")
15
+ return { state: DISPOSED, effects: Array.from(state.entries.keys(), (id) => ({ type: "destroy-socket", id })) };
16
+ const entry = state.entries.get(event.id);
17
+ switch (event.type) {
18
+ case "open.started":
19
+ if (entry || state.entries.size >= MAX_TUNNELS)
20
+ return unchanged(state);
21
+ return { state: put(state, event.id, { status: "connecting" }), effects: [] };
22
+ case "open.connected":
23
+ // Closed while connecting: the socket has no slot to return to.
24
+ if (!entry)
25
+ return destroy(state, event.id);
26
+ if (entry.status !== "connecting")
27
+ return unchanged(state);
28
+ return {
29
+ state: put(state, event.id, {
30
+ status: "open",
31
+ reading: false,
32
+ writing: false,
33
+ readEnded: false,
34
+ writeEnded: false,
35
+ error: undefined,
36
+ }),
37
+ effects: [],
38
+ };
39
+ case "open.failed":
40
+ case "tunnel.closed":
41
+ return entry ? evict(state, event.id) : unchanged(state);
42
+ }
43
+ if (entry?.status !== "open")
44
+ return unchanged(state);
45
+ switch (event.type) {
46
+ case "socket.errored":
47
+ if (entry.error)
48
+ return unchanged(state);
49
+ return { state: put(state, event.id, { ...entry, error: event.error }), effects: [] };
50
+ case "socket.closed":
51
+ if (entry.reading || entry.writing || !entry.readEnded)
52
+ return unchanged(state);
53
+ return evict(state, event.id);
54
+ case "read.started":
55
+ if (entry.reading)
56
+ return unchanged(state);
57
+ return { state: put(state, event.id, { ...entry, reading: true }), effects: [] };
58
+ case "read.settled": {
59
+ if (!entry.reading)
60
+ return unchanged(state);
61
+ const readEnded = entry.readEnded || event.outcome === "eof";
62
+ if (event.outcome === "error" || (readEnded && (entry.writeEnded || event.socketClosed)))
63
+ return evict(state, event.id);
64
+ return { state: put(state, event.id, { ...entry, reading: false, readEnded }), effects: [] };
65
+ }
66
+ case "write.started":
67
+ if (entry.writing || entry.writeEnded || entry.error)
68
+ return unchanged(state);
69
+ return { state: put(state, event.id, { ...entry, writing: true }), effects: [] };
70
+ case "write.settled": {
71
+ if (!entry.writing)
72
+ return unchanged(state);
73
+ const writeEnded = entry.writeEnded || (event.outcome === "ok" && event.end);
74
+ if (event.outcome === "interrupted" || (entry.readEnded && (writeEnded || event.socketClosed)))
75
+ return evict(state, event.id);
76
+ return { state: put(state, event.id, { ...entry, writing: false, writeEnded }), effects: [] };
77
+ }
78
+ }
79
+ }
80
+ /** Why `open` cannot claim a slot, if it cannot. */
81
+ export function openError(state) {
82
+ if (state.status === "disposed")
83
+ return new Error("Browser attachment is closed.");
84
+ if (state.entries.size >= MAX_TUNNELS)
85
+ return new Error(`Browser attachment has reached its ${MAX_TUNNELS}-connection limit.`);
86
+ }
87
+ /** Whether `id` is connected and still in the pool. */
88
+ export function isOpen(state, id) {
89
+ return state.status === "active" && state.entries.get(id)?.status === "open";
90
+ }
91
+ /** Why `read` cannot start on `id`, if it cannot. */
92
+ export function readError(state, id) {
93
+ const entry = state.status === "active" ? state.entries.get(id) : undefined;
94
+ if (entry?.status !== "open")
95
+ return new Error("Browser tunnel is closed or unknown.");
96
+ if (entry.reading)
97
+ return new Error("Only one read may be pending per browser tunnel.");
98
+ }
99
+ /** Why `write` cannot start on `id`, if it cannot. */
100
+ export function writeError(state, id) {
101
+ const entry = state.status === "active" ? state.entries.get(id) : undefined;
102
+ if (entry?.status !== "open" || entry.writeEnded)
103
+ return new Error("Browser tunnel is not writable.");
104
+ if (entry.error)
105
+ return entry.error;
106
+ if (entry.writing)
107
+ return new Error("Only one write may be pending per browser tunnel.");
108
+ }
109
+ /** The socket error recorded for `id`. */
110
+ export function socketError(state, id) {
111
+ const entry = state.status === "active" ? state.entries.get(id) : undefined;
112
+ return entry?.status === "open" ? entry.error : undefined;
113
+ }
114
+ function put(state, id, entry) {
115
+ return { status: "active", entries: new Map(state.entries).set(id, entry) };
116
+ }
117
+ function evict(state, id) {
118
+ const entries = new Map(state.entries);
119
+ entries.delete(id);
120
+ return { state: { status: "active", entries }, effects: [{ type: "destroy-socket", id }] };
121
+ }
122
+ function destroy(state, id) {
123
+ return { state, effects: [{ type: "destroy-socket", id }] };
124
+ }
125
+ function unchanged(state) {
126
+ return { state, effects: [] };
127
+ }
@@ -0,0 +1,17 @@
1
+ export * as BrowserTunnel from "./tunnel.js";
2
+ import { Effect } from "effect";
3
+ import { EgressPolicy } from "./egress-policy.js";
4
+ export type Tunnels = ReturnType<typeof make>;
5
+ export declare function make(policy?: EgressPolicy.AttachmentPolicy): {
6
+ open: (target: {
7
+ readonly host: string;
8
+ readonly port: number;
9
+ }) => Effect.Effect<`${string}-${string}-${string}-${string}-${string}`, Error, never>;
10
+ read: (id: string) => Effect.Effect<{
11
+ readonly data: Uint8Array<ArrayBufferLike>;
12
+ readonly eof: boolean;
13
+ }, Error, never>;
14
+ write: (id: string, data: Uint8Array<ArrayBufferLike>, end?: boolean | undefined) => Effect.Effect<undefined, Error, never>;
15
+ close: (id: string) => Effect.Effect<void, never, never>;
16
+ dispose(): void;
17
+ };
package/dist/tunnel.js ADDED
@@ -0,0 +1,181 @@
1
+ export * as BrowserTunnel from "./tunnel.js";
2
+ import { Effect, Exit } from "effect";
3
+ import { EgressPolicy } from "./egress-policy.js";
4
+ import { Browser } from "./rpc.js";
5
+ import { BrowserTunnelMachine } from "./tunnel-machine.js";
6
+ // One instance belongs to one desktop attachment. Socket buffers provide
7
+ // backpressure; reads never collect an unbounded stream in application memory.
8
+ // When `policy` is omitted (experiment disabled or no tunnel host), preserves the
9
+ // exact pre-PR legacy `net.createConnection` DNS, socket, connect, and timeout behavior.
10
+ export function make(policy) {
11
+ let state = BrowserTunnelMachine.initial();
12
+ const sockets = new Map();
13
+ const connecting = new Map();
14
+ const dispatch = (event) => {
15
+ const next = BrowserTunnelMachine.transition(state, event);
16
+ state = next.state;
17
+ next.effects.forEach((effect) => {
18
+ connecting.get(effect.id)?.abort();
19
+ connecting.delete(effect.id);
20
+ sockets.get(effect.id)?.destroy();
21
+ sockets.delete(effect.id);
22
+ });
23
+ };
24
+ return {
25
+ open: Effect.fn("BrowserTunnel.open")(function* (target) {
26
+ const rejected = BrowserTunnelMachine.openError(state);
27
+ if (rejected)
28
+ return yield* Effect.fail(rejected);
29
+ const id = crypto.randomUUID();
30
+ dispatch({ type: "open.started", id });
31
+ if (!policy) {
32
+ return yield* Effect.gen(function* () {
33
+ const { createConnection } = yield* Effect.promise(() => import("node:net"));
34
+ const socket = yield* Effect.try({
35
+ try: () => createConnection({ ...target, allowHalfOpen: true }),
36
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
37
+ });
38
+ sockets.set(id, socket);
39
+ socket.on("error", (error) => dispatch({ type: "socket.errored", id, error }));
40
+ socket.once("close", () => dispatch({ type: "socket.closed", id }));
41
+ yield* Effect.callback((resume) => {
42
+ const connected = () => {
43
+ cleanup();
44
+ socket.setNoDelay(true);
45
+ resume(Effect.void);
46
+ };
47
+ const failed = (error) => {
48
+ cleanup();
49
+ resume(Effect.fail(error));
50
+ };
51
+ const closed = () => failed(new Error("Browser tunnel closed while connecting."));
52
+ const cleanup = () => {
53
+ socket.off("connect", connected);
54
+ socket.off("error", failed);
55
+ socket.off("close", closed);
56
+ };
57
+ socket.once("connect", connected);
58
+ socket.once("error", failed);
59
+ socket.once("close", closed);
60
+ if (socket.destroyed)
61
+ closed();
62
+ if (!socket.destroyed && !socket.connecting)
63
+ connected();
64
+ return Effect.sync(cleanup);
65
+ }).pipe(Effect.timeoutOrElse({
66
+ duration: "10 seconds",
67
+ orElse: () => Effect.fail(new Error("Browser tunnel target connection timed out.")),
68
+ }));
69
+ dispatch({ type: "open.connected", id });
70
+ // Disposal or `close(id)` can win the race with the connect.
71
+ if (!BrowserTunnelMachine.isOpen(state, id))
72
+ return yield* Effect.fail(new Error("Browser attachment is closed."));
73
+ return id;
74
+ }).pipe(Effect.onError(() => Effect.sync(() => dispatch({ type: "open.failed", id }))));
75
+ }
76
+ const abort = new AbortController();
77
+ connecting.set(id, abort);
78
+ return yield* Effect.gen(function* () {
79
+ // Resolve DNS once, enforce egress policy on every final IP, and connect directly to the checked IP.
80
+ const socket = yield* Effect.tryPromise({
81
+ try: (signal) => EgressPolicy.resolveAndConnect(target, policy, {
82
+ signal: AbortSignal.any([abort.signal, signal]),
83
+ timeoutMs: 10_000,
84
+ }),
85
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
86
+ });
87
+ connecting.delete(id);
88
+ sockets.set(id, socket);
89
+ socket.on("error", (error) => dispatch({ type: "socket.errored", id, error }));
90
+ socket.once("close", () => dispatch({ type: "socket.closed", id }));
91
+ dispatch({ type: "open.connected", id });
92
+ // Disposal or `close(id)` can win the race with the connect.
93
+ if (!BrowserTunnelMachine.isOpen(state, id)) {
94
+ socket.destroy();
95
+ sockets.delete(id);
96
+ return yield* Effect.fail(new Error("Browser attachment is closed."));
97
+ }
98
+ return id;
99
+ }).pipe(Effect.onError(() => Effect.sync(() => {
100
+ connecting.delete(id);
101
+ dispatch({ type: "open.failed", id });
102
+ })));
103
+ }),
104
+ read: Effect.fn("BrowserTunnel.read")(function* (id) {
105
+ const socket = sockets.get(id);
106
+ const rejected = BrowserTunnelMachine.readError(state, id);
107
+ if (rejected || !socket)
108
+ return yield* Effect.fail(rejected ?? new Error("Browser tunnel is closed or unknown."));
109
+ dispatch({ type: "read.started", id });
110
+ let outcome = "interrupted";
111
+ return yield* Effect.callback((resume) => {
112
+ const done = (value, result) => {
113
+ cleanup();
114
+ outcome = result;
115
+ resume(value);
116
+ };
117
+ const pull = () => {
118
+ const error = BrowserTunnelMachine.socketError(state, id);
119
+ if (error)
120
+ return done(Effect.fail(error), "error");
121
+ const size = Math.min(socket.readableLength, Browser.TUNNEL_CHUNK_BYTES);
122
+ if (size > 0) {
123
+ const data = socket.read(size);
124
+ return done(Effect.succeed({ data, eof: false }), "chunk");
125
+ }
126
+ if (socket.readableEnded || socket.destroyed)
127
+ done(Effect.succeed({ data: new Uint8Array(), eof: true }), "eof");
128
+ };
129
+ const cleanup = () => {
130
+ socket.off("readable", pull);
131
+ socket.off("end", pull);
132
+ socket.off("error", pull);
133
+ socket.off("close", pull);
134
+ };
135
+ socket.on("readable", pull);
136
+ socket.on("end", pull);
137
+ socket.on("error", pull);
138
+ socket.on("close", pull);
139
+ pull();
140
+ return Effect.sync(cleanup);
141
+ }).pipe(Effect.ensuring(Effect.sync(() => dispatch({ type: "read.settled", id, outcome, socketClosed: socket.destroyed }))));
142
+ }),
143
+ write: Effect.fn("BrowserTunnel.write")(function* (id, data, end = false) {
144
+ const socket = sockets.get(id);
145
+ const rejected = BrowserTunnelMachine.writeError(state, id);
146
+ if (rejected || !socket || socket.destroyed || socket.writableEnded)
147
+ return yield* Effect.fail(rejected ?? new Error("Browser tunnel is not writable."));
148
+ dispatch({ type: "write.started", id });
149
+ yield* Effect.callback((resume) => {
150
+ const done = (error) => {
151
+ cleanup();
152
+ resume(error ? Effect.fail(error) : Effect.void);
153
+ };
154
+ const failed = (error) => done(error);
155
+ // `destroy()` without an error emits neither "finish" nor "error", so a pending end would never settle.
156
+ const closed = () => done(BrowserTunnelMachine.socketError(state, id) ?? new Error("Browser tunnel closed while writing."));
157
+ const cleanup = () => {
158
+ socket.off("error", failed);
159
+ socket.off("close", closed);
160
+ };
161
+ socket.once("error", failed);
162
+ socket.once("close", closed);
163
+ if (end)
164
+ socket.end(data, done);
165
+ if (!end)
166
+ socket.write(data, done);
167
+ return Effect.sync(cleanup);
168
+ }).pipe(Effect.onExit((exit) => Effect.sync(() => dispatch({
169
+ type: "write.settled",
170
+ id,
171
+ end,
172
+ outcome: Exit.isSuccess(exit) ? "ok" : Exit.hasInterrupts(exit) ? "interrupted" : "error",
173
+ socketClosed: socket.destroyed,
174
+ }))));
175
+ }),
176
+ close: (id) => Effect.sync(() => dispatch({ type: "tunnel.closed", id })),
177
+ dispose() {
178
+ dispatch({ type: "disposed" });
179
+ },
180
+ };
181
+ }
@@ -0,0 +1,11 @@
1
+ export * as Wildcard from "./wildcard.js";
2
+ /**
3
+ * Whether `input` matches a permission pattern, as core matches the rules of a permission check. This is a private
4
+ * copy of `match` in `packages/core/src/util/wildcard.ts`: this package cannot import core, and the rule it picks for
5
+ * a browser call must be the rule core would pick. Port a change to that file here; `test/wildcard.test.ts` pins
6
+ * the cases.
7
+ *
8
+ * Core ignores case on Windows by reading the platform itself. Here the caller says so: pass `ignoreCase` as true
9
+ * when the server runs on Windows.
10
+ */
11
+ export declare function match(input: string, pattern: string, ignoreCase: boolean): boolean;
@@ -0,0 +1,21 @@
1
+ export * as Wildcard from "./wildcard.js";
2
+ /**
3
+ * Whether `input` matches a permission pattern, as core matches the rules of a permission check. This is a private
4
+ * copy of `match` in `packages/core/src/util/wildcard.ts`: this package cannot import core, and the rule it picks for
5
+ * a browser call must be the rule core would pick. Port a change to that file here; `test/wildcard.test.ts` pins
6
+ * the cases.
7
+ *
8
+ * Core ignores case on Windows by reading the platform itself. Here the caller says so: pass `ignoreCase` as true
9
+ * when the server runs on Windows.
10
+ */
11
+ export function match(input, pattern, ignoreCase) {
12
+ const normalized = input.replaceAll("\\", "/");
13
+ let escaped = pattern
14
+ .replaceAll("\\", "/")
15
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
16
+ .replace(/\*/g, ".*")
17
+ .replace(/\?/g, ".");
18
+ if (escaped.endsWith(" .*"))
19
+ escaped = escaped.slice(0, -3) + "( .*)?";
20
+ return new RegExp("^" + escaped + "$", ignoreCase ? "si" : "s").test(normalized);
21
+ }
@@ -0,0 +1,3 @@
1
+ /** Both the name and its resolved target must be within the same workspace. Compare physical names exactly,
2
+ * even on Windows: individual NTFS directories can be case sensitive. */
3
+ export declare function workspaceTarget(file: string, roots: readonly string[]): Promise<string | undefined>;
@@ -0,0 +1,19 @@
1
+ import { realpath } from "node:fs/promises";
2
+ import { isAbsolute, relative, sep } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ /** Both the name and its resolved target must be within the same workspace. Compare physical names exactly,
5
+ * even on Windows: individual NTFS directories can be case sensitive. */
6
+ export async function workspaceTarget(file, roots) {
7
+ const candidates = roots.filter((root) => {
8
+ const child = relative(root, file);
9
+ return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child);
10
+ });
11
+ if (!candidates.length)
12
+ return;
13
+ const [target, directories] = await Promise.all([realpath(file), Promise.all(candidates.map((root) => realpath(root)))]);
14
+ const href = pathToFileURL(target).href;
15
+ return directories.some((root) => {
16
+ const base = pathToFileURL(root).href;
17
+ return href === base || href.startsWith(`${base.replace(/\/$/, "")}/`);
18
+ }) ? target : undefined;
19
+ }
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package.json",
2
3
  "name": "@radheim/plugin-browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "2.4.3",
5
+ "description": "OpenCode's desktop browser plugin",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/anomalyco/opencode.git",
11
+ "directory": "packages/plugin-browser"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ },
24
+ "./rpc": {
25
+ "types": "./dist/rpc.d.ts",
26
+ "import": "./dist/rpc.js"
27
+ },
28
+ "./workspace": {
29
+ "types": "./dist/workspace.d.ts",
30
+ "import": "./dist/workspace.js"
31
+ },
32
+ "./preview-path": {
33
+ "types": "./dist/preview-path.d.ts",
34
+ "import": "./dist/preview-path.js"
35
+ },
36
+ "./proxy": {
37
+ "types": "./dist/proxy.d.ts",
38
+ "import": "./dist/proxy.js"
39
+ },
40
+ "./experimental/stream": {
41
+ "types": "./dist/stream.d.ts",
42
+ "import": "./dist/stream.js"
43
+ },
44
+ "./experimental/tunnel-host": {
45
+ "types": "./dist/tunnel-host.d.ts",
46
+ "import": "./dist/tunnel-host.js"
47
+ }
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json",
51
+ "pack": "bun run script/pack.ts",
52
+ "typecheck": "bun check --no-script -p tsconfig.test.json",
53
+ "typecheck:tsc": "tsc --noEmit -p tsconfig.test.json",
54
+ "test": "bun test"
55
+ },
56
+ "dependencies": {
57
+ "@radheim/plugin": "2.4.3",
58
+ "@radheim/schema": "2.4.3",
59
+ "@radheim/util": "2.4.3",
60
+ "effect": "4.1.0"
61
+ },
62
+ "devDependencies": {
63
+ "@tsconfig/bun": "1.0.9",
64
+ "@types/bun": "1.4.3",
65
+ "@typescript/native": "npm:typescript@7.1.0-beta",
66
+ "typescript": "npm:@typescript/typescript6@6.0.2"
67
+ }
68
+ }