@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.
@@ -1,7 +1,7 @@
1
1
  export * as BrowserConnection from "./connection.js";
2
2
  import type { Context } from "@opencode/plugin/effect/plugin";
3
3
  import { Tool } from "@opencode/schema/tool";
4
- import { Effect } from "effect";
4
+ import { Effect, Scope } from "effect";
5
5
  import { Browser } from "./rpc.js";
6
6
  export type Connection = Effect.Success<ReturnType<typeof make>>;
7
7
  export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" | "rpc" | "session">) => Effect.Effect<{
@@ -220,20 +220,11 @@ export declare const make: (ctx: Pick<Context, "agent" | "event" | "location" |
220
220
  readonly text?: string | undefined;
221
221
  readonly timeoutMs?: number | undefined;
222
222
  }) => Effect.Effect<{
223
- tab: {
224
- readonly id: string & import("effect/Brand").Brand<"Browser.TabID">;
225
- readonly url: string;
226
- readonly title: string;
227
- readonly loading: boolean;
228
- readonly loadError?: string | undefined;
229
- readonly canGoBack: boolean;
230
- readonly canGoForward: boolean;
231
- readonly generation: number;
232
- } | undefined;
223
+ tab: Browser.Tab | undefined;
233
224
  inspect: () => Effect.Effect<{
234
225
  readonly resources: readonly string[];
235
226
  readonly key: string;
236
227
  }, Tool.Error, never>;
237
228
  request: (files: readonly Browser.File[], target?: Browser.Target) => Effect.Effect<Browser.Result, Tool.Error, never>;
238
229
  }, Tool.Error, never>;
239
- }, never, import("effect/Scope").Scope>;
230
+ }, never, Scope.Scope>;
@@ -1,54 +1,82 @@
1
1
  export * as BrowserConnection from "./connection.js";
2
2
  import { Tool } from "@opencode/schema/tool";
3
- import { Deferred, Effect, Schema, Stream } from "effect";
3
+ import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect";
4
+ import { BrowserMachine } from "./machine.js";
4
5
  import { Browser } from "./rpc.js";
5
- import { BrowserSkill } from "./skill.js";
6
6
  import { BrowserTunnel } from "./tunnel.js";
7
7
  export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
8
- const browsers = new Map();
9
- // The browser tools and their skill, which an attachment allows together.
10
- const access = [
11
- { action: "browser", resource: "*" },
12
- { action: "skill", resource: BrowserSkill.id },
13
- ];
14
8
  // Appended after config, so every agent hides the browser until an attachment allows it.
15
9
  yield* ctx.agent.transform((editor) => editor
16
10
  .list()
17
- .forEach((agent) => agent.permissions.push(...access.map((rule) => ({ ...rule, effect: "deny" })))));
18
- // Each attachment adds and removes its own allows, so a replaced attachment keeps the new one's.
19
- const grant = (sessionID) => Effect.acquireRelease(ctx.session.get({ sessionID }).pipe(Effect.flatMap((session) => ctx.session.update({
20
- sessionID,
21
- permissions: [
22
- ...(session.permissions ?? []),
23
- ...access.map((rule) => ({ ...rule, effect: "allow" })),
24
- ],
25
- })), Effect.orDie), () => ctx.session.get({ sessionID }).pipe(Effect.flatMap((session) => {
26
- const current = session.permissions ?? [];
27
- const permissions = access.reduce((rules, allow) => {
28
- const index = rules.findIndex((rule) => rule.action === allow.action && rule.resource === allow.resource && rule.effect === "allow");
29
- return index === -1 ? rules : rules.toSpliced(index, 1);
30
- }, current);
31
- if (permissions.length === current.length)
32
- return Effect.void;
33
- return ctx.session.update({ sessionID, permissions });
34
- }), Effect.ignore));
35
- let active = true;
36
- const close = (sessionID, reason = "closed") => Effect.gen(function* () {
37
- const browser = browsers.get(sessionID);
38
- if (!browser)
39
- return;
40
- browsers.delete(sessionID);
41
- browser.tunnels.dispose();
42
- yield* Deferred.succeed(browser.closed, reason);
43
- });
44
- yield* Effect.addFinalizer(() => {
45
- active = false;
46
- return Effect.forEach(browsers.keys(), (id) => close(id), { discard: true });
11
+ .forEach((agent) => agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" })))));
12
+ // Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes.
13
+ const work = yield* Scope.make();
14
+ yield* Effect.addFinalizer((exit) => Scope.close(work, exit));
15
+ const machine = { state: BrowserMachine.createConnectionState() };
16
+ const attachments = new Map();
17
+ const requests = new Map();
18
+ const drained = Deferred.makeUnsafe();
19
+ // One event at a time, effects included, so controls reach the bus in transition order: `attached` before any
20
+ // `command` of that attachment.
21
+ const lock = Semaphore.makeUnsafe(1);
22
+ const step = (event) => Effect.suspend(() => {
23
+ const next = BrowserMachine.transitionConnection(machine.state, event);
24
+ machine.state = next.state;
25
+ return Effect.forEach(next.effects, (effect) => perform(effect).pipe(Effect.catchCause((cause) => Effect.logWarning("Browser effect failed", cause))), { discard: true });
47
26
  });
27
+ const dispatch = (event) => lock.withPermit(step(event));
28
+ const perform = (effect) => {
29
+ if (effect.type === "sync-permissions")
30
+ return Effect.asVoid(Effect.forkIn(syncPermissions(effect), work));
31
+ if (effect.type === "close-attachment")
32
+ return Effect.suspend(() => {
33
+ const attachment = attachments.get(effect.attempt);
34
+ if (!attachment)
35
+ return Effect.void;
36
+ attachments.delete(effect.attempt);
37
+ attachment.tunnels.dispose();
38
+ return Deferred.done(attachment.closed, effect.outcome === "unavailable" ? Exit.fail(effect.outcome) : Exit.succeed(effect.outcome)).pipe(Effect.asVoid);
39
+ });
40
+ if (effect.type === "emit-control")
41
+ return rpc.events.emit("control", effect.control);
42
+ if (effect.type === "dispatch-command")
43
+ return (rpc.events
44
+ .emit("control", { type: "command", connectionID: effect.connectionID, requestID: effect.requestID })
45
+ // Already inside the lock, so the failure steps directly.
46
+ .pipe(Effect.catch((error) => step({ ...effect, type: "request.dispatch-failed", error }))));
47
+ if (effect.type === "settle-request")
48
+ return Effect.suspend(() => {
49
+ const result = requests.get(effect.requestID);
50
+ if (!result)
51
+ return Effect.void;
52
+ requests.delete(effect.requestID);
53
+ return Deferred.done(result, effect.settlement.ok ? Exit.succeed(effect.settlement.result) : Exit.fail(effect.settlement.error)).pipe(Effect.asVoid);
54
+ });
55
+ if (effect.type === "warn")
56
+ return Effect.logWarning(effect.message, effect.error);
57
+ return Deferred.done(drained, Exit.void).pipe(Effect.asVoid);
58
+ };
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({
63
+ onSuccess: (done) => dispatch({
64
+ type: Option.isSome(done) ? "permissions.synced" : "permissions.timed-out",
65
+ sessionID: effect.sessionID,
66
+ attempt: effect.attempt,
67
+ }),
68
+ onFailure: (cause) => dispatch({
69
+ type: "permissions.failed",
70
+ sessionID: effect.sessionID,
71
+ attempt: effect.attempt,
72
+ error: Cause.squash(cause),
73
+ }),
74
+ }));
48
75
  const tunnels = (input) => {
49
- const browser = browsers.get(input.sessionID);
50
- return browser?.connectionID === input.connectionID
51
- ? Effect.succeed(browser.tunnels)
76
+ const attempt = BrowserMachine.selectAttachment(machine.state, input.sessionID, input.connectionID);
77
+ const attachment = attempt === undefined ? undefined : attachments.get(attempt);
78
+ return attachment
79
+ ? Effect.succeed(attachment.tunnels)
52
80
  : Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed."));
53
81
  };
54
82
  const rpc = yield* ctx.rpc
@@ -59,102 +87,83 @@ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
59
87
  .pipe(Effect.mapError(() => call.error("unavailable", "Session not found.", {})));
60
88
  if (session.location.directory !== ctx.location.directory)
61
89
  return yield* Effect.fail(call.error("unavailable", "Session belongs to another location.", {}));
62
- const browser = yield* Effect.acquireRelease(Effect.gen(function* () {
63
- if (!active)
64
- return yield* Effect.fail(call.error("unavailable", "Browser is unavailable.", {}));
65
- yield* close(input.sessionID, "replaced");
66
- const browser = {
90
+ return yield* Effect.acquireUseRelease(lock.withPermit(Effect.suspend(() => {
91
+ if (BrowserMachine.isConnectionDisposed(machine.state))
92
+ return Effect.fail(call.error("unavailable", "Browser is unavailable.", {}));
93
+ const attempt = BrowserMachine.selectNextAttempt(machine.state);
94
+ const attachment = { closed: Deferred.makeUnsafe(), tunnels: BrowserTunnel.make() };
95
+ attachments.set(attempt, attachment);
96
+ return step({
97
+ type: "attach.started",
98
+ sessionID: input.sessionID,
99
+ attempt,
67
100
  connectionID: input.connectionID,
68
- state: { tabs: [], focusedTabID: null },
69
- closed: yield* Deferred.make(),
70
- pending: new Map(),
71
- tunnels: BrowserTunnel.make(),
72
- };
73
- browsers.set(input.sessionID, browser);
74
- return browser;
75
- }), (browser) => (browsers.get(input.sessionID) === browser ? close(input.sessionID) : Effect.void));
76
- yield* grant(input.sessionID);
77
- yield* rpc.events
78
- .emit("control", { type: "attached", connectionID: input.connectionID, version: 4 })
79
- .pipe(Effect.orDie);
80
- return yield* Deferred.await(browser.closed);
81
- }).pipe(Effect.scoped),
82
- state: (input, call) => Effect.gen(function* () {
83
- const browser = browsers.get(input.sessionID);
84
- if (!browser || browser.connectionID !== input.connectionID)
85
- return yield* Effect.fail(call.error("unavailable", "Browser is unavailable.", {}));
86
- browser.state = input.state;
101
+ }).pipe(Effect.as({ attempt, attachment }));
102
+ })), (attached) => Deferred.await(attached.attachment.closed).pipe(Effect.mapError(() => call.error("unavailable", "Browser permissions could not be granted.", {}))), (attached) => dispatch({ type: "attach.closed", sessionID: input.sessionID, attempt: attached.attempt }));
87
103
  }),
88
- command: (input, call) => Effect.gen(function* () {
89
- const browser = browsers.get(input.sessionID);
90
- const pending = browser?.connectionID === input.connectionID ? browser.pending.get(input.requestID) : undefined;
91
- if (!pending)
92
- return yield* Effect.fail(call.error("unavailable", "Browser request is no longer available.", {}));
93
- return pending.command;
104
+ state: (input, call) => Effect.suspend(() => BrowserMachine.isAttachedConnection(machine.state, input.sessionID, input.connectionID)
105
+ ? dispatch({
106
+ type: "state.updated",
107
+ sessionID: input.sessionID,
108
+ connectionID: input.connectionID,
109
+ browserState: input.state,
110
+ })
111
+ : Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))),
112
+ command: (input, call) => Effect.suspend(() => {
113
+ const command = BrowserMachine.selectPendingCommand(machine.state, input.sessionID, input.connectionID, input.requestID);
114
+ return command
115
+ ? Effect.succeed(command)
116
+ : Effect.fail(call.error("unavailable", "Browser request is no longer available.", {}));
94
117
  }),
95
- result: (input, call) => Effect.gen(function* () {
96
- const browser = browsers.get(input.sessionID);
97
- if (!browser || browser.connectionID !== input.connectionID)
98
- return yield* Effect.fail(call.error("unavailable", "Browser is unavailable.", {}));
99
- const pending = browser.pending.get(input.requestID);
100
- if (!pending)
101
- return;
102
- if (input.outcome.type === "failure")
103
- return yield* Deferred.fail(pending.result, new Tool.Error({ message: `[browser.${input.outcome.code}] ${input.outcome.message}` })).pipe(Effect.asVoid);
104
- yield* Deferred.succeed(pending.result, input.outcome.result);
105
- }).pipe(Effect.asVoid),
118
+ result: (input, call) => Effect.suspend(() => BrowserMachine.isAttachedConnection(machine.state, input.sessionID, input.connectionID)
119
+ ? dispatch({ type: "request.settled", ...input })
120
+ : Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))),
106
121
  "tunnel.open": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.open(input.target)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
107
122
  "tunnel.read": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.read(input.tunnelID)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
108
123
  "tunnel.write": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.write(input.tunnelID, input.data, input.end)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
109
124
  "tunnel.close": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.close(input.tunnelID)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
110
125
  })
111
126
  .pipe(Effect.orDie);
112
- yield* ctx.event.subscribe({ types: ["session.deleted", "session.moved"] }).pipe(Stream.runForEach((event) => close(event.data.sessionID)), Effect.forkScoped({ startImmediately: true }));
127
+ yield* ctx.event.subscribe({ types: ["session.deleted", "session.moved"] }).pipe(Stream.runForEach((event) => dispatch({
128
+ type: event.type === "session.deleted" ? "session.deleted" : "session.moved",
129
+ sessionID: event.data.sessionID,
130
+ })), Effect.forkScoped({ startImmediately: true }));
131
+ // Registered last, so it runs first: attachments close and revokes drain while the RPC and `work` are still open.
132
+ yield* Effect.addFinalizer(() => dispatch({ type: "disposed" }).pipe(Effect.andThen(Deferred.await(drained))));
133
+ const request = Effect.fn("BrowserConnection.request")(function* (sessionID, connectionID, action, tab, files, inspection) {
134
+ const requestID = crypto.randomUUID();
135
+ const target = { sessionID, connectionID, requestID };
136
+ const result = yield* Deferred.make();
137
+ const command = {
138
+ action: (action.type === "files.upload" || action.type === "files.drop") && !inspection.inspect
139
+ ? { ...action, paths: files.map((file) => file.name) }
140
+ : action,
141
+ ...(tab ? { generation: tab.generation } : {}),
142
+ files,
143
+ ...inspection,
144
+ };
145
+ // Once started, the request always reaches the machine's exit: a settlement, a timeout or a cancel.
146
+ return yield* Effect.uninterruptibleMask((restore) => Effect.sync(() => requests.set(requestID, result)).pipe(Effect.andThen(dispatch({ type: "request.started", ...target, command })), Effect.andThen(restore(Deferred.await(result).pipe(Effect.timeoutOrElse({
147
+ duration: Duration.millis(BrowserMachine.REQUEST_TIMEOUT_MS),
148
+ orElse: () => dispatch({ type: "request.timed-out", ...target }).pipe(Effect.andThen(Deferred.await(result))),
149
+ })))), Effect.onInterrupt(() => dispatch({ type: "request.cancelled", ...target })), Effect.ensuring(Effect.sync(() => requests.delete(requestID)))));
150
+ });
113
151
  return {
114
152
  target: Effect.fn("BrowserConnection.target")(function* (sessionID, action) {
115
- const browser = browsers.get(sessionID);
116
- if (!browser)
117
- return yield* new Tool.Error({
118
- 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.",
119
- });
120
- const tab = "tabID" in action ? browser.state.tabs.find((tab) => tab.id === action.tabID) : undefined;
121
- if ("tabID" in action && !tab)
122
- return yield* new Tool.Error({
123
- 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.",
124
- });
125
- // Keep the selected attachment and document, even while permissions or file IO wait.
153
+ const selected = BrowserMachine.selectTarget(machine.state, sessionID, action);
154
+ if (!selected.ok)
155
+ return yield* selected.error;
156
+ // Requests go to the attachment selected here. One that closes first, even while file IO waits, runs nothing.
126
157
  return {
127
- tab,
128
- inspect: () => request(rpc, browser, action, tab, [], { inspect: true }).pipe(Effect.flatMap((result) => Schema.decodeUnknownEffect(Browser.Target)(result.value)), Effect.mapError((error) => new Tool.Error({
158
+ tab: selected.tab,
159
+ inspect: () => request(sessionID, selected.connectionID, action, selected.tab, [], { inspect: true }).pipe(Effect.flatMap((result) => Schema.decodeUnknownEffect(Browser.Target)(result.value)), Effect.mapError((error) => new Tool.Error({
129
160
  message: error instanceof Tool.Error
130
161
  ? error.message
131
162
  : "Browser returned invalid target metadata. Check desktop/plugin versions; no action was authorized.",
132
163
  error,
133
164
  }))),
134
- request: (files, target) => request(rpc, browser, action, tab, files, { target }),
165
+ request: (files, target) => request(sessionID, selected.connectionID, action, selected.tab, files, { target }),
135
166
  };
136
167
  }),
137
168
  };
138
169
  });
139
- const request = Effect.fn("BrowserConnection.request")(function* (rpc, browser, action, tab, files, inspection) {
140
- const requestID = crypto.randomUUID();
141
- const pending = yield* Deferred.make();
142
- const command = (action.type === "files.upload" || action.type === "files.drop") && !inspection.inspect
143
- ? { ...action, paths: files.map((file) => file.name) }
144
- : action;
145
- browser.pending.set(requestID, {
146
- command: { action: command, ...(tab ? { generation: tab.generation } : {}), files, ...inspection },
147
- result: pending,
148
- });
149
- return yield* rpc.events.emit("control", { type: "command", connectionID: browser.connectionID, requestID }).pipe(Effect.mapError((error) => new Tool.Error({
150
- message: `Could not dispatch browser.${action.type}. Check the desktop connection and call browser.tabs.list({}) before deciding whether to retry.`,
151
- error,
152
- })), Effect.andThen(Deferred.await(pending)), Effect.raceFirst(Deferred.await(browser.closed).pipe(Effect.andThen(new Tool.Error({
153
- 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.",
154
- })))), Effect.onInterrupt(() => rpc.events.emit("control", { type: "cancel", connectionID: browser.connectionID, requestID }).pipe(Effect.ignore)), Effect.timeoutOrElse({
155
- duration: "60 seconds",
156
- orElse: () => new Tool.Error({
157
- message: `[browser.timeout] browser.${action.type} did not finish within 60 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.`,
158
- }),
159
- }), Effect.ensuring(Effect.sync(() => browser.pending.delete(requestID))));
160
- });
@@ -0,0 +1,203 @@
1
+ export * as BrowserMachine from "./machine.js";
2
+ import type { Permission } from "@opencode/schema/permission";
3
+ import type { Session } from "@opencode/schema/session";
4
+ import { Tool } from "@opencode/schema/tool";
5
+ import type { Browser } from "./rpc.js";
6
+ /** How long one permission sync (`session.get` and, when needed, `session.update`) may take. The desktop waits 15 s. */
7
+ export declare const PERMISSION_SYNC_TIMEOUT_MS = 10000;
8
+ /** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */
9
+ export declare const REQUEST_TIMEOUT_MS = 60000;
10
+ /** The browser tools and their skill, which an attachment allows together. */
11
+ export declare const ACCESS: readonly [{
12
+ readonly action: "browser";
13
+ readonly resource: "*";
14
+ }, {
15
+ readonly action: "skill";
16
+ readonly resource: string & import("effect/Brand").Brand<"Skill.ID">;
17
+ }];
18
+ /** The one `session.permissions` sync in flight for a session: grant (`allow`) or revoke the browser rules. */
19
+ export type PermissionSync = {
20
+ readonly attempt: number;
21
+ readonly allow: boolean;
22
+ };
23
+ /**
24
+ * One session's attachment. A session absent from `sessions` has no attachment and no sync in flight.
25
+ *
26
+ * - `attaching`: the desktop called `attach` as `attempt`. Its grant runs after any revoke in flight (`sync`); until it
27
+ * succeeds, no `attached` handshake is sent and no command is dispatched.
28
+ * - `attached`: the session allows the browser and the desktop received `attached`; commands run.
29
+ * - `revoking`: no attachment; `sync` settles, then a revoke follows unless the session was `deleted`.
30
+ */
31
+ export type SessionState = {
32
+ readonly status: "attaching";
33
+ readonly attempt: number;
34
+ readonly connectionID: string;
35
+ readonly sync: PermissionSync;
36
+ } | {
37
+ readonly status: "attached";
38
+ readonly attempt: number;
39
+ readonly connectionID: string;
40
+ readonly browserState: Browser.State;
41
+ readonly pending: ReadonlyMap<string, Browser.Command>;
42
+ } | {
43
+ readonly status: "revoking";
44
+ readonly sync: PermissionSync;
45
+ readonly deleted: boolean;
46
+ };
47
+ export type RevokingSession = Extract<SessionState, {
48
+ readonly status: "revoking";
49
+ }>;
50
+ /** Every attachment of the plugin. Once `disposed`, only revokes still draining remain. */
51
+ export type ConnectionState = {
52
+ readonly status: "active";
53
+ readonly nextAttempt: number;
54
+ readonly sessions: ReadonlyMap<Session.ID, SessionState>;
55
+ } | {
56
+ readonly status: "disposed";
57
+ readonly nextAttempt: number;
58
+ readonly sessions: ReadonlyMap<Session.ID, RevokingSession>;
59
+ };
60
+ /** How an `attach` call ends: its result, or `unavailable` when the grant failed. */
61
+ export type AttachmentOutcome = "closed" | "replaced" | "unavailable";
62
+ export type RequestSettlement = {
63
+ readonly ok: true;
64
+ readonly result: Browser.Result;
65
+ } | {
66
+ readonly ok: false;
67
+ readonly error: Tool.Error;
68
+ };
69
+ export type ConnectionEvent =
70
+ /** `attempt` is the state's `nextAttempt`, read when the driver registered the attachment's handle. */
71
+ {
72
+ readonly type: "attach.started";
73
+ readonly sessionID: Session.ID;
74
+ readonly attempt: number;
75
+ readonly connectionID: string;
76
+ }
77
+ /** The `attach` call ended on the desktop's side (disconnect or interrupt). */
78
+ | {
79
+ readonly type: "attach.closed";
80
+ readonly sessionID: Session.ID;
81
+ readonly attempt: number;
82
+ } | {
83
+ readonly type: "permissions.synced";
84
+ readonly sessionID: Session.ID;
85
+ readonly attempt: number;
86
+ } | {
87
+ readonly type: "permissions.failed";
88
+ readonly sessionID: Session.ID;
89
+ readonly attempt: number;
90
+ readonly error: unknown;
91
+ } | {
92
+ readonly type: "permissions.timed-out";
93
+ readonly sessionID: Session.ID;
94
+ readonly attempt: number;
95
+ } | {
96
+ readonly type: "state.updated";
97
+ readonly sessionID: Session.ID;
98
+ readonly connectionID: string;
99
+ readonly browserState: Browser.State;
100
+ } | {
101
+ readonly type: "request.started";
102
+ readonly sessionID: Session.ID;
103
+ readonly connectionID: string;
104
+ readonly requestID: string;
105
+ readonly command: Browser.Command;
106
+ } | {
107
+ readonly type: "request.dispatch-failed";
108
+ readonly sessionID: Session.ID;
109
+ readonly connectionID: string;
110
+ readonly requestID: string;
111
+ readonly error: unknown;
112
+ } | {
113
+ readonly type: "request.settled";
114
+ readonly sessionID: Session.ID;
115
+ readonly connectionID: string;
116
+ readonly requestID: string;
117
+ readonly outcome: Browser.Outcome;
118
+ } | {
119
+ readonly type: "request.timed-out";
120
+ readonly sessionID: Session.ID;
121
+ readonly connectionID: string;
122
+ readonly requestID: string;
123
+ }
124
+ /** The tool call that started the request was interrupted. */
125
+ | {
126
+ readonly type: "request.cancelled";
127
+ readonly sessionID: Session.ID;
128
+ readonly connectionID: string;
129
+ readonly requestID: string;
130
+ } | {
131
+ readonly type: "session.moved";
132
+ readonly sessionID: Session.ID;
133
+ } | {
134
+ readonly type: "session.deleted";
135
+ readonly sessionID: Session.ID;
136
+ } | {
137
+ readonly type: "disposed";
138
+ };
139
+ export type ConnectionEffect = {
140
+ readonly type: "sync-permissions";
141
+ readonly sessionID: Session.ID;
142
+ readonly attempt: number;
143
+ readonly allow: boolean;
144
+ }
145
+ /** Disposes the attachment's tunnels and ends its `attach` call with `outcome`. */
146
+ | {
147
+ readonly type: "close-attachment";
148
+ readonly attempt: number;
149
+ readonly outcome: AttachmentOutcome;
150
+ } | {
151
+ readonly type: "emit-control";
152
+ readonly control: Browser.Control;
153
+ }
154
+ /** Emits the `command` control; a failure comes back as `request.dispatch-failed`. */
155
+ | {
156
+ readonly type: "dispatch-command";
157
+ readonly sessionID: Session.ID;
158
+ readonly connectionID: string;
159
+ readonly requestID: string;
160
+ } | {
161
+ readonly type: "settle-request";
162
+ readonly requestID: string;
163
+ readonly settlement: RequestSettlement;
164
+ } | {
165
+ readonly type: "warn";
166
+ readonly message: string;
167
+ readonly error: unknown;
168
+ }
169
+ /** The disposed plugin has no revoke left in flight. */
170
+ | {
171
+ readonly type: "notify-drained";
172
+ };
173
+ export type ConnectionTransition = {
174
+ readonly state: ConnectionState;
175
+ readonly effects: readonly ConnectionEffect[];
176
+ };
177
+ export declare function createConnectionState(): ConnectionState;
178
+ export declare function transitionConnection(state: ConnectionState, event: ConnectionEvent): ConnectionTransition;
179
+ /**
180
+ * The session's permissions with exactly one set of browser allows (`allow`) or none, every other rule kept in order.
181
+ * Undefined when they already are, so a replace writes nothing.
182
+ */
183
+ export declare function reconcileBrowserPermissions(current: readonly Permission.Rule[] | undefined, allow: boolean): Permission.Rule[] | undefined;
184
+ export declare function isConnectionDisposed(state: ConnectionState): state is {
185
+ readonly status: "disposed";
186
+ readonly nextAttempt: number;
187
+ readonly sessions: ReadonlyMap<Session.ID, RevokingSession>;
188
+ };
189
+ /** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
190
+ export declare function selectNextAttempt(state: ConnectionState): number;
191
+ /** The attempt of the session's attachment with `connectionID`, attaching or attached. */
192
+ export declare function selectAttachment(state: ConnectionState, sessionID: Session.ID, connectionID: string): number | undefined;
193
+ export declare function isAttachedConnection(state: ConnectionState, sessionID: Session.ID, connectionID: string): boolean;
194
+ export declare function selectPendingCommand(state: ConnectionState, sessionID: Session.ID, connectionID: string, requestID: string): Browser.Command | undefined;
195
+ /** The attachment and tab a browser tool call targets, or the error the tool returns. */
196
+ export declare function selectTarget(state: ConnectionState, sessionID: Session.ID, action: Browser.Action): {
197
+ readonly ok: true;
198
+ readonly connectionID: string;
199
+ readonly tab: Browser.Tab | undefined;
200
+ } | {
201
+ readonly ok: false;
202
+ readonly error: Tool.Error;
203
+ };