@opencode/plugin-browser 2.3.2 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/files.d.ts CHANGED
@@ -2,13 +2,70 @@ export * as BrowserFiles from "./files.js";
2
2
  import { Browser } from "./rpc.js";
3
3
  import { Tool } from "@opencode/schema/tool";
4
4
  import { Effect } from "effect";
5
- export declare const read: (paths: readonly string[], directory: string) => Effect.Effect<{
6
- id: string & import("effect/Brand").Brand<"Browser.FileID">;
7
- name: string;
8
- mime: string;
9
- data: Uint8Array<ArrayBuffer>;
10
- }[], Tool.Error, never>;
11
- export declare const save: (files: readonly Browser.File[]) => Effect.Effect<{
5
+ import type { Context } from "@opencode/plugin/effect/plugin";
6
+ export declare const authorize: (ctx: Pick<Context, "location" | "permission">, tool: Tool.Context, action: "edit" | "read", paths: readonly string[]) => Effect.Effect<undefined, Tool.Error, never>;
7
+ export declare function uploadPath(directory: string, input: string): string;
8
+ export declare const physical: (paths: readonly string[]) => Effect.Effect<string[], Tool.Error, never>;
9
+ export declare const read: (paths: readonly string[], names: readonly string[]) => Effect.Effect<Browser.File[], Tool.Error, never>;
10
+ /**
11
+ * The workspace entry a path or `file:` address names, decided from its text alone, with no look at the disk: the
12
+ * address and its percent-encoding decoded, a line suffix dropped, `.` and `..` resolved. `entry` is the result
13
+ * relative to the workspace, with forward slashes. Undefined for an address that is no file. `unresolved` for text
14
+ * that is no path, `outside` for one that leaves the workspace, `invalid` for a name the desktop cannot open.
15
+ */
16
+ export declare function entry(path: string, directory: string): {
17
+ unresolved: true;
18
+ outside?: undefined;
19
+ invalid?: undefined;
20
+ absolute?: undefined;
21
+ entry?: undefined;
22
+ } | {
23
+ unresolved?: undefined;
24
+ absolute: string;
25
+ outside: true;
26
+ invalid?: undefined;
27
+ entry?: undefined;
28
+ } | {
29
+ unresolved?: undefined;
30
+ outside?: undefined;
31
+ absolute: string;
32
+ invalid: true;
33
+ entry?: undefined;
34
+ } | {
35
+ unresolved?: undefined;
36
+ outside?: undefined;
37
+ invalid?: undefined;
38
+ absolute: string;
39
+ entry: string;
40
+ } | undefined;
41
+ /** Resolve and authorize the exact entry. A missing agent path must not trigger a search of unapproved directories. */
42
+ export declare const locate: (path: string, directory: string, approve: (absolute: string) => Effect.Effect<void, Tool.Error>) => Effect.Effect<{
43
+ absolute: string;
44
+ found: boolean;
45
+ directory: boolean;
46
+ } | {
47
+ absolute: string;
48
+ found: boolean;
49
+ directory: boolean;
50
+ outside: boolean;
51
+ } | {
52
+ absolute: string;
53
+ found: boolean;
54
+ directory: boolean;
55
+ invalid: boolean;
56
+ } | undefined, Tool.Error, never>;
57
+ /** Whether a preview path is an address with a scheme, such as https:, skill: or file:. A drive letter is no scheme. */
58
+ export declare function address(path: string): boolean;
59
+ /** A session owns one private cache tree. Neither file names nor session IDs are interpreted as directory paths. */
60
+ export declare function exportRoot(sessionID: string): string;
61
+ export declare function exportPaths(files: readonly Browser.File[], root: string): {
62
+ directory: string;
63
+ paths: string[];
64
+ };
65
+ export declare const save: (files: readonly Browser.File[], plan: {
66
+ directory: string;
67
+ paths: string[];
68
+ }) => Effect.Effect<{
12
69
  id: string & import("effect/Brand").Brand<"Browser.FileID">;
13
70
  name: string;
14
71
  mime: string;
package/dist/files.js CHANGED
@@ -2,36 +2,141 @@ export * as BrowserFiles from "./files.js";
2
2
  import { Browser } from "./rpc.js";
3
3
  import { Tool } from "@opencode/schema/tool";
4
4
  import { Effect } from "effect";
5
+ import { FSUtil } from "@opencode/util/fs-util";
6
+ import { Global } from "@opencode/util/global";
7
+ import { workspaceTarget } from "./workspace.js";
8
+ import { previewPath } from "./preview-path.js";
9
+ import { open, realpath, stat } from "node:fs/promises";
10
+ import { basename, dirname, extname, join, parse, relative, resolve } from "node:path";
11
+ import { createHash } from "node:crypto";
12
+ import { fileURLToPath } from "node:url";
13
+ // Match core FileAccess's lexical resources; the plugin SDK exposes permission.assert, not FileAccess.Service.
14
+ export const authorize = Effect.fn("BrowserFiles.authorize")(function* (ctx, tool, action, paths) {
15
+ if (ctx.location.workspaceID)
16
+ return yield* new Tool.Error({ message: "Browser file transfers require a server-local workspace." });
17
+ const directory = ctx.location.directory;
18
+ const project = ctx.location.project.directory;
19
+ const outside = paths.filter((file) => !FSUtil.contains(directory, file) && (project === parse(project).root || !FSUtil.contains(project, file)));
20
+ const invocation = { sessionID: tool.sessionID, agent: tool.agent, source: { type: "tool", messageID: tool.messageID, id: tool.id }, metadata: { input: { paths } } };
21
+ if (outside.length)
22
+ yield* ctx.permission.assert({ ...invocation, action: "external_directory", resources: [...new Set(outside.map((file) => join(dirname(file), "*").replaceAll("\\", "/")))], save: [] });
23
+ const resources = paths.map((file) => (outside.includes(file) ? file : relative(directory, file) || ".").replaceAll("\\", "/"));
24
+ yield* ctx.permission.assert({ ...invocation, action, resources, save: outside.length || resources.some((r) => /[*?]/.test(r)) ? [] : resources });
25
+ });
26
+ export function uploadPath(directory, input) {
27
+ const path = FSUtil.windowsPath(input);
28
+ return resolve(directory, path === "~" ? Global.Path.home : /^~\//.test(path) || (process.platform === "win32" && path.startsWith("~\\")) ? join(Global.Path.home, path.slice(2)) : path);
29
+ }
30
+ export const physical = (paths) => Effect.tryPromise({ try: () => Promise.all(paths.map((path) => realpath(path))), catch: (error) => failure("read", error) });
5
31
  // Files cross machines as bytes. Only this endpoint interprets its local paths.
6
- export const read = Effect.fn("BrowserFiles.read")((paths, directory) => Effect.tryPromise({
32
+ export const read = Effect.fn("BrowserFiles.read")((paths, names) => Effect.tryPromise({
7
33
  try: async () => {
8
- const { open } = await import("node:fs/promises");
9
- const { resolve, basename, extname } = await import("node:path");
10
- const files = await Promise.all(paths.map(async (input) => {
11
- const file = await open(resolve(directory, input), "r");
34
+ const files = [];
35
+ let remaining = Browser.MAX_FILE_BYTES;
36
+ for (const [index, input] of paths.entries()) {
37
+ const file = await open(input, "r");
12
38
  try {
13
- const stat = await file.stat();
14
- if (!stat.isFile())
15
- throw new Error("Upload paths must name files, not directories. Select a server-local file.");
16
- if (stat.size > Browser.MAX_FILE_BYTES)
17
- throw new Error(`Upload is ${stat.size} bytes; the limit is ${Browser.MAX_FILE_BYTES} bytes (5 MiB). Select a smaller file; do not retry the same upload.`);
18
- return {
39
+ const info = await file.stat();
40
+ if (!info.isFile())
41
+ throw new Error("Upload paths must name regular files.");
42
+ if (info.size > remaining)
43
+ throw new Error("The selected upload files exceed 5 MiB in total.");
44
+ const data = Buffer.alloc(info.size);
45
+ let offset = 0;
46
+ while (offset < data.length) {
47
+ const { bytesRead } = await file.read(data, offset, data.length - offset, offset);
48
+ if (!bytesRead)
49
+ throw new Error("The upload file changed while it was being read.");
50
+ offset += bytesRead;
51
+ }
52
+ remaining -= data.length;
53
+ const name = basename(names[index] ?? input);
54
+ files.push({
19
55
  id: Browser.FileID.make(`file_${crypto.randomUUID()}`),
20
- name: basename(input),
21
- mime: types[extname(input).toLowerCase()] ?? "application/octet-stream",
22
- data: new Uint8Array(await file.readFile()),
23
- };
56
+ name,
57
+ mime: types[extname(name).toLowerCase()] ?? "application/octet-stream",
58
+ data,
59
+ });
24
60
  }
25
61
  finally {
26
62
  await file.close();
27
63
  }
28
- }));
29
- if (files.reduce((size, file) => size + file.data.byteLength, 0) > Browser.MAX_FILE_BYTES)
30
- throw new Error("The selected upload files exceed 5 MiB in total. Send fewer or smaller files; splitting them into one batch does not bypass the total limit.");
64
+ }
31
65
  return files;
32
66
  },
33
67
  catch: (error) => failure("read", error),
34
68
  }));
69
+ /**
70
+ * The workspace entry a path or `file:` address names, decided from its text alone, with no look at the disk: the
71
+ * address and its percent-encoding decoded, a line suffix dropped, `.` and `..` resolved. `entry` is the result
72
+ * relative to the workspace, with forward slashes. Undefined for an address that is no file. `unresolved` for text
73
+ * that is no path, `outside` for one that leaves the workspace, `invalid` for a name the desktop cannot open.
74
+ */
75
+ export function entry(path, directory) {
76
+ const value = path.trim();
77
+ if (address(value) && !/^file:/i.test(value))
78
+ return undefined;
79
+ const local = localPath(value);
80
+ if (local === undefined)
81
+ return { unresolved: true };
82
+ if (local === "")
83
+ return { absolute: value, outside: true };
84
+ const plain = local.replace(/(?:#L\d+(?:C\d+)?(?:-L?\d+(?:C\d+)?)?|:\d+(?::\d+)?(?:-\d+(?::\d+)?)?:?)$/i, "");
85
+ const absolute = resolve(directory, plain);
86
+ if (!FSUtil.contains(directory, absolute))
87
+ return { absolute, outside: true };
88
+ const name = relative(directory, absolute).replaceAll("\\", "/");
89
+ if (name && !previewPath(name, process.platform === "win32"))
90
+ return { absolute, invalid: true };
91
+ return { absolute, entry: name };
92
+ }
93
+ // A `file:` address as a local path, with forward slashes. Empty for one that names another host; undefined for text
94
+ // that is no address or path at all.
95
+ function localPath(value) {
96
+ try {
97
+ const url = /^file:/i.test(value) ? new URL(value) : undefined;
98
+ if (url?.hostname)
99
+ return "";
100
+ return (url ? fileURLToPath(url) : value).replaceAll("\\", "/");
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ }
106
+ /** Resolve and authorize the exact entry. A missing agent path must not trigger a search of unapproved directories. */
107
+ export const locate = Effect.fn("BrowserFiles.locate")(function* (path, directory, approve) {
108
+ const resolved = entry(path, directory);
109
+ if (!resolved)
110
+ return undefined;
111
+ const invalid = () => new Tool.Error({ metadata: { code: "unresolved_path" }, message: "This path does not resolve to a file inside the workspace." });
112
+ if ("unresolved" in resolved)
113
+ return yield* invalid();
114
+ const absolute = resolved.absolute;
115
+ const missing = { absolute, found: false, directory: false };
116
+ // Outside and invalid names can be refused lexically, without querying the filesystem or prompting to read them.
117
+ if ("outside" in resolved)
118
+ return { ...missing, outside: true };
119
+ if ("invalid" in resolved)
120
+ return { ...missing, invalid: true };
121
+ yield* approve(absolute);
122
+ const target = yield* Effect.tryPromise({ try: () => workspaceTarget(absolute, [directory]), catch: cause => cause instanceof Error && "code" in cause && (cause.code === "ENOENT" || cause.code === "ENOTDIR") ? "missing" : invalid() }).pipe(Effect.catchIf(error => error === "missing", () => Effect.succeed(null)));
123
+ if (target === null)
124
+ return missing;
125
+ if (!target)
126
+ return { ...missing, outside: true };
127
+ // The physical file, named under the workspace as the session spells it: a workspace reached through a symlink
128
+ // (macOS's /var is /private/var) keeps its own path, and only a link inside it to another entry needs approval.
129
+ const root = yield* Effect.tryPromise({ try: () => realpath(directory), catch: invalid });
130
+ const physical = resolve(directory, relative(root, target));
131
+ if (physical !== absolute)
132
+ yield* approve(physical);
133
+ const info = yield* Effect.tryPromise({ try: () => stat(target), catch: invalid });
134
+ return { absolute: physical, found: info.isFile(), directory: info.isDirectory() };
135
+ });
136
+ /** Whether a preview path is an address with a scheme, such as https:, skill: or file:. A drive letter is no scheme. */
137
+ export function address(path) {
138
+ return /^[a-z][a-z\d+.-]+:/i.test(path.trim());
139
+ }
35
140
  const types = {
36
141
  ".txt": "text/plain",
37
142
  ".csv": "text/csv",
@@ -47,21 +152,27 @@ const types = {
47
152
  ".zip": "application/zip",
48
153
  ".gz": "application/gzip",
49
154
  };
50
- export const save = Effect.fn("BrowserFiles.save")((files) => Effect.tryPromise({
155
+ /** A session owns one private cache tree. Neither file names nor session IDs are interpreted as directory paths. */
156
+ export function exportRoot(sessionID) {
157
+ return join(Global.Path.cache, "browser-exports", createHash("sha256").update(sessionID).digest("hex"));
158
+ }
159
+ export function exportPaths(files, root) {
160
+ const directory = join(root, crypto.randomUUID());
161
+ return { directory, paths: files.map((file, index) => join(directory, String(index), captureName(file.name))) };
162
+ }
163
+ export const save = Effect.fn("BrowserFiles.save")((files, plan) => Effect.tryPromise({
51
164
  try: async () => {
52
165
  if (files.length === 0)
53
166
  return [];
54
167
  if (files.reduce((size, file) => size + file.data.byteLength, 0) > Browser.MAX_FILE_BYTES)
55
168
  throw new Error("Capture files exceed the 5 MiB total transfer limit. Use a smaller screenshot, a shorter trace/profile, or a smaller page for heap capture; do not retry the identical capture.");
56
- const { mkdtemp, mkdir, writeFile } = await import("node:fs/promises");
57
- const { join } = await import("node:path");
58
- const { tmpdir } = await import("node:os");
59
- const directory = await mkdtemp(join(tmpdir(), "opencode-browser-"));
169
+ const { mkdir, writeFile } = await import("node:fs/promises");
170
+ await mkdir(dirname(plan.directory), { recursive: true, mode: 0o700 });
171
+ await mkdir(plan.directory, { mode: 0o700 });
60
172
  return Promise.all(files.map(async (file, index) => {
61
- const name = captureName(file.name);
62
- await mkdir(join(directory, String(index)));
63
- const path = join(directory, String(index), name);
64
- await writeFile(path, file.data, { flag: "wx" });
173
+ const path = plan.paths[index];
174
+ await mkdir(dirname(path), { mode: 0o700 });
175
+ await writeFile(path, file.data, { flag: "wx", mode: 0o600 });
65
176
  return { id: file.id, name: file.name, mime: file.mime, bytes: file.data.byteLength, path };
66
177
  }));
67
178
  },
package/dist/machine.d.ts CHANGED
@@ -181,18 +181,46 @@ export declare function transitionConnection(state: ConnectionState, event: Conn
181
181
  * Undefined when they already are, so a replace writes nothing.
182
182
  */
183
183
  export declare function reconcileBrowserPermissions(current: readonly Permission.Rule[] | undefined, allow: boolean): Permission.Rule[] | undefined;
184
+ /**
185
+ * One of the allows an attachment grants. A grant that holds only the browser allow, as some versions wrote it, is
186
+ * recognised too, so a revoke or the startup sweep removes it. A user rule of the same shape cannot be told apart
187
+ * from it.
188
+ */
189
+ export declare function isGrant(rule: Permission.Rule): boolean;
190
+ /**
191
+ * The rule that decides `browser` on `operation`, picked as core's `Permission.evaluate` picks it: the last rule whose
192
+ * action and resource patterns both match. Undefined when none matches.
193
+ */
194
+ export declare function selectBrowserRule(rules: readonly Permission.Rule[], operation: string): Permission.Rule | undefined;
184
195
  export declare function isConnectionDisposed(state: ConnectionState): state is {
185
196
  readonly status: "disposed";
186
197
  readonly nextAttempt: number;
187
198
  readonly sessions: ReadonlyMap<Session.ID, RevokingSession>;
188
199
  };
200
+ /** Whether the session has an attachment or a permission sync in flight, either of which owns its browser rules. */
201
+ export declare function hasSession(state: ConnectionState, sessionID: Session.ID): boolean;
189
202
  /** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
190
203
  export declare function selectNextAttempt(state: ConnectionState): number;
191
204
  /** The attempt of the session's attachment with `connectionID`, attaching or attached. */
192
205
  export declare function selectAttachment(state: ConnectionState, sessionID: Session.ID, connectionID: string): number | undefined;
193
206
  export declare function isAttachedConnection(state: ConnectionState, sessionID: Session.ID, connectionID: string): boolean;
194
207
  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. */
208
+ /**
209
+ * The session's attached connection, or the error a tool call returns while it has none. Reads nothing about its tabs,
210
+ * so it may answer before the call is authorized.
211
+ */
212
+ export declare function selectConnection(state: ConnectionState, sessionID: Session.ID): {
213
+ readonly ok: true;
214
+ readonly connectionID: string;
215
+ readonly tabs: readonly Browser.Tab[];
216
+ } | {
217
+ readonly ok: false;
218
+ readonly error: Tool.Error;
219
+ };
220
+ /**
221
+ * The attachment and tab a browser tool call targets, or the error the tool returns. The error for an unknown tab lists
222
+ * the session's tabs, so this runs only once the call is authorized.
223
+ */
196
224
  export declare function selectTarget(state: ConnectionState, sessionID: Session.ID, action: Browser.Action): {
197
225
  readonly ok: true;
198
226
  readonly connectionID: string;
package/dist/machine.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export * as BrowserMachine from "./machine.js";
2
2
  import { Tool } from "@opencode/schema/tool";
3
3
  import { BrowserSkill } from "./skill.js";
4
+ import { Wildcard } from "./wildcard.js";
4
5
  /** How long one permission sync (`session.get` and, when needed, `session.update`) may take. The desktop waits 15 s. */
5
6
  export const PERMISSION_SYNC_TIMEOUT_MS = 10_000;
6
7
  /** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */
@@ -271,7 +272,11 @@ function settleRequest(entry, event, command) {
271
272
  return [
272
273
  settle({
273
274
  ok: false,
274
- error: new Tool.Error({ message: `[browser.${event.outcome.code}] ${event.outcome.message}` }),
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
+ }),
275
280
  }),
276
281
  ];
277
282
  }
@@ -302,8 +307,7 @@ function syncWarning(event, sync) {
302
307
  */
303
308
  export function reconcileBrowserPermissions(current, allow) {
304
309
  const rules = current ?? [];
305
- const kept = rules.filter((rule) => rule.effect !== "allow" ||
306
- !ACCESS.some((access) => access.action === rule.action && access.resource === rule.resource));
310
+ const kept = rules.filter((rule) => !isGrant(rule));
307
311
  const next = allow ? [...kept, ...ACCESS.map((rule) => ({ ...rule, effect: "allow" }))] : kept;
308
312
  const unchanged = next.length === rules.length &&
309
313
  next.every((rule, index) => rule.action === rules[index]?.action &&
@@ -311,9 +315,29 @@ export function reconcileBrowserPermissions(current, allow) {
311
315
  rule.effect === rules[index]?.effect);
312
316
  return unchanged ? undefined : next;
313
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
+ }
314
334
  export function isConnectionDisposed(state) {
315
335
  return state.status === "disposed";
316
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
+ }
317
341
  /** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
318
342
  export function selectNextAttempt(state) {
319
343
  return state.nextAttempt;
@@ -341,41 +365,61 @@ export function selectPendingCommand(state, sessionID, connectionID, requestID)
341
365
  return undefined;
342
366
  return entry.pending.get(requestID);
343
367
  }
344
- /** The attachment and tab a browser tool call targets, or the error the tool returns. */
345
- export function selectTarget(state, sessionID, action) {
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) {
346
373
  const entry = state.status === "active" ? state.sessions.get(sessionID) : undefined;
347
374
  if (!entry || entry.status === "revoking")
348
375
  return {
349
376
  ok: false,
350
377
  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.",
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.",
352
379
  }),
353
380
  };
354
381
  if (entry.status === "attaching")
355
382
  return {
356
383
  ok: false,
357
384
  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.",
385
+ message: "The desktop browser is still connecting to this session. No action ran. Retry only after it attaches.",
359
386
  }),
360
387
  };
361
- const tab = "tabID" in action ? entry.browserState.tabs.find((tab) => tab.id === action.tabID) : undefined;
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;
362
399
  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 };
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
+ });
370
414
  }
371
415
  function disconnectedBeforeDispatch() {
372
416
  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({}).",
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.",
374
418
  });
375
419
  }
376
420
  function disconnectedAfterDispatch() {
377
421
  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.",
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.",
379
423
  });
380
424
  }
381
425
  function dispatchFailed(action, error) {
@@ -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
+ }