@omercnet/paseo-shared-browser 4.1.12-next.504.1 → 4.1.12-next.505.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/README.md CHANGED
@@ -157,6 +157,26 @@ The provider launches the stdio adapter on the Paseo daemon host, beside the dae
157
157
  runtime. Web, desktop, and mobile clients never own or host the adapter or Chromium, and a client
158
158
  disconnect does not close or reset either process.
159
159
 
160
+ ### Choosing which agents get the tool
161
+
162
+ By default every new agent gets the adapter. Settings, under Shared Browser, can restrict that:
163
+
164
+ - **Every new agent** (the default) injects the adapter into every new agent, as above.
165
+ - **Only the agents listed** injects it only into a new agent whose provider id is listed, or whose
166
+ workspace id or project id is listed. Separate entries with commas or new lines. An empty
167
+ configuration means no agent.
168
+
169
+ `agent.create` carries the provider and the working directory but no labels and no workspace id, so a
170
+ workspace or project is matched by directory: the workspace whose directory is the agent's directory or
171
+ the deepest one containing it. Both directories are normalized first (separators, `.` and `..` segments),
172
+ so a path that climbs out of a workspace does not match it. The lookup includes background workspaces. If
173
+ the list is longer than 20 pages of 200, or the lookup fails, those lists match nothing. Workspaces that
174
+ share a directory cannot be told apart, so listing any of them matches them all. Matching is lexical: nothing on disk is consulted, so symlinks are not resolved and letter case is not folded. The settings read has a 2 second deadline, and a read that is too slow is treated like an unreadable setting, so every new agent gets the tool. The workspace lookup has its own 2 second deadline, and a timeout there counts as no match. Either timeout logs one line, and a slow lookup never holds up agent creation. The check runs before the adapter, its credential or the supervisor are set up, so
175
+ an agent that is not allowed costs nothing. It applies to agents created after the setting is saved. A
176
+ setting that cannot be read or is invalid falls back to every new agent, and the plugin log gets one line
177
+ saying so. The settings screen reports an entry over 256 characters or a list over 200 entries instead of
178
+ cutting it off.
179
+
160
180
  ## Runtime environment overrides
161
181
 
162
182
  The plugin recognizes only these deployment overrides:
@@ -0,0 +1,143 @@
1
+ import { type PluginSurfaceProps, useSettings } from "@getpaseo/plugin/client";
2
+ import {
3
+ SettingsAction,
4
+ SettingsCard,
5
+ SettingsInput,
6
+ type SettingsInputHandle,
7
+ SettingsSection,
8
+ SettingsSelect,
9
+ } from "@getpaseo/plugin/client/ui";
10
+ import { useRef, useState } from "react";
11
+ import { Text } from "react-native";
12
+ import { type AgentAccessMode, agentAccessSettings, parseEntries } from "../shared/agent-access";
13
+
14
+ const MODE_OPTIONS: readonly { label: string; value: AgentAccessMode }[] = [
15
+ { label: "Every new agent", value: "all" },
16
+ { label: "Only the agents listed below", value: "listed" },
17
+ ];
18
+
19
+ type ListName = "providers" | "workspaces" | "projects";
20
+ const NO_ERRORS: Record<ListName, string | null> = {
21
+ providers: null,
22
+ workspaces: null,
23
+ projects: null,
24
+ };
25
+
26
+ /** Settings screen: which new agents get the browser tool. */
27
+ export function AgentAccessSettings({ theme }: PluginSurfaceProps) {
28
+ const settings = useSettings(agentAccessSettings);
29
+ const providers = useRef<SettingsInputHandle>(null);
30
+ const workspaces = useRef<SettingsInputHandle>(null);
31
+ const projects = useRef<SettingsInputHandle>(null);
32
+ // Errors belong to the revision they were found on; a newer revision (another client saved) clears them.
33
+ const [found, setFound] = useState<{
34
+ revision: string | null;
35
+ errors: Record<ListName, string | null>;
36
+ }>({ revision: null, errors: NO_ERRORS });
37
+ const muted = { color: theme.colors.foregroundMuted, fontSize: 13, lineHeight: 19 };
38
+
39
+ if (settings.status === "loading") {
40
+ return (
41
+ <SettingsSection title="Shared Browser: agent access">
42
+ <Text style={muted}>Loading</Text>
43
+ </SettingsSection>
44
+ );
45
+ }
46
+ if (settings.status !== "ready") {
47
+ return (
48
+ <SettingsSection title="Shared Browser: agent access">
49
+ <Text style={muted}>{settings.error}</Text>
50
+ <SettingsCard>
51
+ <SettingsAction label="Try again" actionLabel="Reload" onPress={settings.reload} />
52
+ {settings.status === "invalid" ? (
53
+ <SettingsAction
54
+ label="Back to the default"
55
+ actionLabel="Reset"
56
+ onPress={settings.reset}
57
+ />
58
+ ) : null}
59
+ </SettingsCard>
60
+ </SettingsSection>
61
+ );
62
+ }
63
+
64
+ const { values } = settings;
65
+ const listErrors = found.revision === settings.revision ? found.errors : NO_ERRORS;
66
+ const save = (next: typeof values) => void settings.save(next, settings.revision);
67
+ // The lists as typed, parsed the same way for Save and for a mode change, so unsaved text is never
68
+ // lost to the revision remount. A list that does not parse shows its error and nothing is saved.
69
+ const typedLists = () => {
70
+ const parsed = {
71
+ providers: parseEntries(providers.current?.getText() ?? ""),
72
+ workspaces: parseEntries(workspaces.current?.getText() ?? ""),
73
+ projects: parseEntries(projects.current?.getText() ?? ""),
74
+ };
75
+ const errors = {
76
+ providers: parsed.providers.error,
77
+ workspaces: parsed.workspaces.error,
78
+ projects: parsed.projects.error,
79
+ };
80
+ setFound({ revision: settings.revision, errors });
81
+ if (errors.providers || errors.workspaces || errors.projects) return null;
82
+ return {
83
+ providers: parsed.providers.entries,
84
+ workspaces: parsed.workspaces.entries,
85
+ projects: parsed.projects.entries,
86
+ };
87
+ };
88
+ return (
89
+ <SettingsSection title="Shared Browser: agent access">
90
+ {/* Keyed on the revision, so the text inputs start over from the saved lists when another client changes them. */}
91
+ <SettingsCard key={settings.revision}>
92
+ <SettingsSelect
93
+ label="Browser tool for"
94
+ hint="Applies to agents created from now on. With the lists empty, no agent gets the tool."
95
+ error={settings.saveError}
96
+ value={values.mode}
97
+ options={MODE_OPTIONS}
98
+ disabled={settings.saving}
99
+ onValueChange={(mode) => {
100
+ const lists = typedLists();
101
+ if (lists) save({ ...values, ...lists, mode });
102
+ }}
103
+ />
104
+ <SettingsInput
105
+ ref={providers}
106
+ label="Provider ids"
107
+ hint="Separated by commas or new lines. An agent whose provider is listed gets the tool."
108
+ initialValue={values.providers.join(", ")}
109
+ error={listErrors.providers}
110
+ onChangeText={() => {}}
111
+ disabled={settings.saving}
112
+ />
113
+ <SettingsInput
114
+ ref={workspaces}
115
+ label="Workspace ids"
116
+ hint="Every new agent in a listed workspace gets the tool."
117
+ initialValue={values.workspaces.join(", ")}
118
+ error={listErrors.workspaces}
119
+ onChangeText={() => {}}
120
+ disabled={settings.saving}
121
+ />
122
+ <SettingsInput
123
+ ref={projects}
124
+ label="Project ids"
125
+ hint="Every new agent in a workspace of a listed project gets the tool."
126
+ initialValue={values.projects.join(", ")}
127
+ error={listErrors.projects}
128
+ onChangeText={() => {}}
129
+ disabled={settings.saving}
130
+ />
131
+ <SettingsAction
132
+ label="Save the lists"
133
+ actionLabel="Save"
134
+ disabled={settings.saving}
135
+ onPress={() => {
136
+ const lists = typedLists();
137
+ if (lists) save({ ...values, ...lists });
138
+ }}
139
+ />
140
+ </SettingsCard>
141
+ </SettingsSection>
142
+ );
143
+ }
package/index.client.tsx CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { AgentAccessSettings } from "./client/agent-access-settings";
2
3
  import { contributeSharedBrowserClient, SharedBrowserPanel } from "./client/browser";
3
4
  import { contributeSharedBrowserSidebar } from "./client/sidebar";
4
5
 
@@ -21,9 +22,16 @@ export default function contribute(client: PluginClientContext) {
21
22
  },
22
23
  });
23
24
 
25
+ const removeSettings = client.addSettingsScreen({
26
+ id: "agent-access",
27
+ title: "Shared Browser",
28
+ icon: "PanelsTopLeft",
29
+ Component: AgentAccessSettings,
30
+ });
24
31
  const removeSidebar = contributeSharedBrowserSidebar(client);
25
32
  const cleanup = contributeSharedBrowserClient(client);
26
33
  return () => {
34
+ removeSettings();
27
35
  removeSidebar();
28
36
  return cleanup();
29
37
  };
package/index.server.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
- import type { PluginServerContext } from "@getpaseo/plugin/server";
4
+ import type { PluginHookContext, PluginServerContext } from "@getpaseo/plugin/server";
5
5
  import {
6
6
  bindAgentTicket,
7
7
  cleanupBrowserServer,
@@ -33,6 +33,13 @@ import {
33
33
  revokeAgentBrowserAccess,
34
34
  } from "./server/browser";
35
35
  import { resolveBrowserRuntimeRoot } from "./server/runtime-path";
36
+ import { listAllWorkspaces } from "./server/workspace-list";
37
+ import {
38
+ accessFromState,
39
+ agentAccessSettings,
40
+ agentGetsBrowser,
41
+ DEFAULT_AGENT_ACCESS,
42
+ } from "./shared/agent-access";
36
43
  import {
37
44
  acquireControlRpc,
38
45
  applyDevicePresetRpc,
@@ -63,25 +70,34 @@ import { readBrowserVideoRpc } from "./shared/browser-video";
63
70
  const TICKET_ENV = "PASEO_SHARED_BROWSER_TICKET";
64
71
  const MCP_SERVER_ID = "shared-browser";
65
72
  const TICKET_ISSUE_TIMEOUT_MS = 2_000;
73
+ const ACCESS_DECISION_TIMEOUT_MS = 2_000;
66
74
 
67
- async function issueTicketWithinDeadline(ticket: string): Promise<boolean> {
75
+ /** The result of `work`, or a rejection when it has not settled within `ms`. */
76
+ async function withinDeadline<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
68
77
  let timer: NodeJS.Timeout | undefined;
69
78
  try {
70
- await Promise.race([
71
- issueAgentTicket(ticket),
79
+ return await Promise.race([
80
+ work,
72
81
  new Promise<never>((_, reject) => {
73
- timer = setTimeout(
74
- () => reject(new Error("Shared Browser ticket issuance timed out")),
75
- TICKET_ISSUE_TIMEOUT_MS,
76
- );
82
+ timer = setTimeout(() => reject(new Error(message)), ms);
77
83
  timer.unref();
78
84
  }),
79
85
  ]);
86
+ } finally {
87
+ clearTimeout(timer);
88
+ }
89
+ }
90
+
91
+ async function issueTicketWithinDeadline(ticket: string): Promise<boolean> {
92
+ try {
93
+ await withinDeadline(
94
+ issueAgentTicket(ticket),
95
+ TICKET_ISSUE_TIMEOUT_MS,
96
+ "Shared Browser ticket issuance timed out",
97
+ );
80
98
  return true;
81
99
  } catch {
82
100
  return false;
83
- } finally {
84
- clearTimeout(timer);
85
101
  }
86
102
  }
87
103
 
@@ -95,6 +111,45 @@ function mcpBundlePath(): string {
95
111
 
96
112
  export default function contribute(server: PluginServerContext) {
97
113
  server.registerSettings(browserDisplayPreferences);
114
+ const agentAccess = server.registerSettings(agentAccessSettings);
115
+ // The deadline covers the settings read alone: a setting that cannot be read in time is an unreadable
116
+ // setting, and that falls back to the default (every new agent).
117
+ const readAccess = async () => {
118
+ try {
119
+ const state = await withinDeadline(
120
+ Promise.resolve(agentAccess.read()),
121
+ ACCESS_DECISION_TIMEOUT_MS,
122
+ "the read timed out",
123
+ );
124
+ const access = accessFromState(state);
125
+ if (access === DEFAULT_AGENT_ACCESS) {
126
+ console.warn(
127
+ `shared-browser: the agent-access setting is ${state?.status ?? "missing"}; every new agent gets the browser tool`,
128
+ );
129
+ }
130
+ return access;
131
+ } catch (error) {
132
+ console.warn(
133
+ `shared-browser: the agent-access setting could not be read (${error instanceof Error ? error.message : "error"}); every new agent gets the browser tool`,
134
+ );
135
+ return DEFAULT_AGENT_ACCESS;
136
+ }
137
+ };
138
+ // The workspace lookup has its own deadline; a timeout or any other failure there is no match.
139
+ const lookupWorkspaces = async (paseo: PluginHookContext["paseo"]) => {
140
+ try {
141
+ return await withinDeadline(
142
+ listAllWorkspaces(paseo),
143
+ ACCESS_DECISION_TIMEOUT_MS,
144
+ "the workspace lookup timed out",
145
+ );
146
+ } catch (error) {
147
+ console.warn(
148
+ `shared-browser: the workspace lookup failed (${error instanceof Error ? error.message : "error"}); the agent is not matched to a workspace or project`,
149
+ );
150
+ throw error;
151
+ }
152
+ };
98
153
  server.handle(attachBrowserRpc, handleAttachBrowser);
99
154
  server.handle(detachBrowserRpc, handleDetachBrowser);
100
155
  server.handle(closeBrowserRpc, handleCloseBrowser);
@@ -118,8 +173,13 @@ export default function contribute(server: PluginServerContext) {
118
173
  server.handle(resizeBrowserRpc, handleResizeBrowser);
119
174
  server.handle(applyDevicePresetRpc, handleApplyDevicePreset);
120
175
  server.handle(sendBrowserInputRpc, handleSendBrowserInput);
121
- server.before("agent.create", async ({ request }) => {
176
+ server.before("agent.create", async ({ request }, context) => {
122
177
  if (request.config.internal) return request;
178
+ // Decide before any ticket or supervisor work, so an agent that is not allowed costs nothing.
179
+ const allowed = await agentGetsBrowser(await readAccess(), request.config, () =>
180
+ lookupWorkspaces(context.paseo),
181
+ );
182
+ if (!allowed) return request;
123
183
  const ticket = randomBytes(32).toString("base64url");
124
184
  if (!(await issueTicketWithinDeadline(ticket))) return request;
125
185
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-shared-browser",
3
- "version": "4.1.12-next.504.1",
3
+ "version": "4.1.12-next.505.1",
4
4
  "description": "One real Chromium session per Paseo workspace, shared live across every connected client.",
5
5
  "keywords": [
6
6
  "browser",
@@ -50,8 +50,8 @@
50
50
  "check:write": "biome check --write .",
51
51
  "typecheck": "tsc --noEmit",
52
52
  "prepare:runtime": "node scripts/prepare-runtime.mjs",
53
- "test": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
54
- "test:unit": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
53
+ "test": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-filter.test.ts tests/workspace-list.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
54
+ "test:unit": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-filter.test.ts tests/workspace-list.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared",
55
55
  "test:smoke": "vitest run tests/browser.smoke.test.ts tests/browser.drag-cancel.smoke.test.ts tests/xvfb.smoke.test.ts tests/browser.failed-open.smoke.test.ts tests/browser.background-tab.smoke.test.ts --testTimeout=30000",
56
56
  "test:tabs": "vitest run tests/browser-tabs.smoke.test.ts --testTimeout=30000",
57
57
  "test:video": "vitest run tests/video.smoke.test.ts --testTimeout=30000"
@@ -0,0 +1,42 @@
1
+ import type { WorkspaceRef } from "../shared/agent-access";
2
+
3
+ export const WORKSPACE_PAGE_SIZE = 200;
4
+ export const WORKSPACE_PAGE_LIMIT = 20;
5
+
6
+ interface WorkspacePage {
7
+ entries: readonly WorkspaceRef[];
8
+ pageInfo: { nextCursor?: string | null; hasMore: boolean };
9
+ }
10
+
11
+ export interface WorkspaceLister {
12
+ workspaces: {
13
+ list(options: {
14
+ filter: { includeBackground: true };
15
+ page: { limit: number; cursor?: string };
16
+ }): Promise<WorkspacePage>;
17
+ };
18
+ }
19
+
20
+ /**
21
+ * Every workspace the daemon knows, background ones included. An access decision made from a partial
22
+ * list could match a shallower workspace than the agent is really in, so a list that is still
23
+ * incomplete after the page limit is an error, and the caller counts it as a failed lookup.
24
+ */
25
+ export async function listAllWorkspaces(
26
+ paseo: WorkspaceLister,
27
+ pageLimit: number = WORKSPACE_PAGE_LIMIT,
28
+ ): Promise<WorkspaceRef[]> {
29
+ const workspaces: WorkspaceRef[] = [];
30
+ let cursor: string | undefined;
31
+ for (let page = 0; page < pageLimit; page += 1) {
32
+ const result = await paseo.workspaces.list({
33
+ filter: { includeBackground: true },
34
+ page: { limit: WORKSPACE_PAGE_SIZE, ...(cursor ? { cursor } : {}) },
35
+ });
36
+ workspaces.push(...result.entries);
37
+ if (!result.pageInfo.hasMore) return workspaces;
38
+ cursor = result.pageInfo.nextCursor ?? undefined;
39
+ if (!cursor) throw new Error("Workspace list reports more pages but gave no cursor");
40
+ }
41
+ throw new Error(`Workspace list is longer than ${pageLimit} pages`);
42
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Which new agents get the Shared Browser tool.
3
+ *
4
+ * "all" injects the adapter into every new agent (the behaviour before this setting existed, and the
5
+ * default). "listed" injects it only when the new agent matches an entry of one of three lists: its
6
+ * provider id, the id of its workspace, or the id of its workspace's project. An empty configuration
7
+ * means no agent. Agents that already exist are never changed.
8
+ *
9
+ * `agent.create` carries the provider and the working directory but no labels and no workspace id, so
10
+ * the workspace is found by matching the directory against the daemon's workspaces.
11
+ */
12
+ import { defineSettings } from "@getpaseo/plugin";
13
+ import { z } from "zod";
14
+
15
+ export const AGENT_ACCESS_MODES = ["all", "listed"] as const;
16
+ export type AgentAccessMode = (typeof AGENT_ACCESS_MODES)[number];
17
+
18
+ const MAX_ENTRIES = 200;
19
+ const MAX_ENTRY_LENGTH = 256;
20
+ const entries = z.array(z.string().min(1).max(MAX_ENTRY_LENGTH)).max(MAX_ENTRIES).default([]);
21
+
22
+ export const agentAccessSchema = z.object({
23
+ mode: z.enum(AGENT_ACCESS_MODES).default("all"),
24
+ providers: entries,
25
+ workspaces: entries,
26
+ projects: entries,
27
+ });
28
+
29
+ export type AgentAccess = z.output<typeof agentAccessSchema>;
30
+
31
+ export const agentAccessSettings = defineSettings({
32
+ id: "agent-access",
33
+ scope: "host",
34
+ version: 1,
35
+ schema: agentAccessSchema,
36
+ });
37
+
38
+ /** Used when the setting cannot be read or fails validation. */
39
+ export const DEFAULT_AGENT_ACCESS: AgentAccess = {
40
+ mode: "all",
41
+ providers: [],
42
+ workspaces: [],
43
+ projects: [],
44
+ };
45
+
46
+ export function accessFromState(
47
+ state: { status: "ready"; values: AgentAccess } | { status: string } | undefined,
48
+ ): AgentAccess {
49
+ return state?.status === "ready" && "values" in state ? state.values : DEFAULT_AGENT_ACCESS;
50
+ }
51
+
52
+ export interface NewAgent {
53
+ provider: string;
54
+ cwd: string;
55
+ }
56
+
57
+ export interface WorkspaceRef {
58
+ id: string;
59
+ projectId: string;
60
+ workspaceDirectory?: string | undefined;
61
+ }
62
+
63
+ /**
64
+ * A directory in one lexical canonical form: backslashes become slashes, repeated slashes collapse, and
65
+ * `.` and `..` segments resolve. An absolute path (a leading slash, or a drive such as `C:`) cannot
66
+ * climb above its root, which is `/` or `C:/`. It is the same idea as posix normalize, written out because
67
+ * shared code does not import Node modules. Nothing on disk is consulted: symlinks are not resolved and
68
+ * letter case is not folded.
69
+ */
70
+ export function normalizeDirectory(path: string): string {
71
+ const slashed = path.replace(/\\/g, "/");
72
+ const drive = /^[A-Za-z]:(?=\/|$)/.exec(slashed)?.[0] ?? "";
73
+ const rest = slashed.slice(drive.length);
74
+ const absolute = drive !== "" || rest.startsWith("/");
75
+ const kept: string[] = [];
76
+ for (const segment of rest.split("/")) {
77
+ if (segment === "" || segment === ".") continue;
78
+ if (segment !== "..") {
79
+ kept.push(segment);
80
+ } else if (kept.length > 0 && kept[kept.length - 1] !== "..") {
81
+ kept.pop();
82
+ } else if (!absolute) {
83
+ kept.push("..");
84
+ }
85
+ }
86
+ const joined = kept.join("/");
87
+ return absolute ? `${drive}/${joined}` : joined;
88
+ }
89
+
90
+ /**
91
+ * The workspaces whose directory is the agent's directory, or the deepest directory that contains it.
92
+ * Several workspaces can share one directory, so this returns all of them.
93
+ */
94
+ export function workspacesForDirectory(
95
+ cwd: string,
96
+ workspaces: readonly WorkspaceRef[],
97
+ ): WorkspaceRef[] {
98
+ const target = normalizeDirectory(cwd);
99
+ let depth = -1;
100
+ let found: WorkspaceRef[] = [];
101
+ for (const workspace of workspaces) {
102
+ if (!workspace.workspaceDirectory) continue;
103
+ const directory = normalizeDirectory(workspace.workspaceDirectory);
104
+ const prefix = directory.endsWith("/") ? directory : `${directory}/`;
105
+ if (target !== directory && !target.startsWith(prefix)) continue;
106
+ if (directory.length > depth) {
107
+ depth = directory.length;
108
+ found = [workspace];
109
+ } else if (directory.length === depth) {
110
+ found.push(workspace);
111
+ }
112
+ }
113
+ return found;
114
+ }
115
+
116
+ /**
117
+ * True when a new agent gets the browser tool. `listWorkspaces` is called only when a workspace or
118
+ * project is listed and the provider did not already match; if it throws, those lists do not match.
119
+ */
120
+ export async function agentGetsBrowser(
121
+ access: AgentAccess,
122
+ agent: NewAgent,
123
+ listWorkspaces: () => Promise<readonly WorkspaceRef[]>,
124
+ ): Promise<boolean> {
125
+ if (access.mode === "all") return true;
126
+ if (access.providers.includes(agent.provider)) return true;
127
+ if (access.workspaces.length === 0 && access.projects.length === 0) return false;
128
+ try {
129
+ return workspacesForDirectory(agent.cwd, await listWorkspaces()).some(
130
+ (workspace) =>
131
+ access.workspaces.includes(workspace.id) || access.projects.includes(workspace.projectId),
132
+ );
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ export const MAX_LIST_ENTRIES = MAX_ENTRIES;
139
+ export const MAX_LIST_ENTRY_LENGTH = MAX_ENTRY_LENGTH;
140
+
141
+ /**
142
+ * The comma or line separated names typed in the settings screen. Repeats are dropped. A name over the
143
+ * length limit or a list over the entry limit is reported in `error` instead of being cut off.
144
+ */
145
+ export function parseEntries(text: string): { entries: string[]; error: string | null } {
146
+ const entries: string[] = [];
147
+ for (const piece of text.split(/[,\n]/)) {
148
+ const name = piece.trim();
149
+ if (name === "") continue;
150
+ if (name.length > MAX_ENTRY_LENGTH) {
151
+ return {
152
+ entries: [],
153
+ error: `An entry is longer than ${MAX_ENTRY_LENGTH} characters: ${name.slice(0, 24)}...`,
154
+ };
155
+ }
156
+ if (!entries.includes(name)) entries.push(name);
157
+ }
158
+ if (entries.length > MAX_ENTRIES) {
159
+ return {
160
+ entries: [],
161
+ error: `A list can hold ${MAX_ENTRIES} entries; this one has ${entries.length}.`,
162
+ };
163
+ }
164
+ return { entries, error: null };
165
+ }