@omercnet/paseo-shared-browser 4.1.11 → 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.
@@ -5,16 +5,18 @@ import { createServer, type Socket } from "node:net";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import type { ZodType } from "zod";
8
- import type { BrowserFrame, BrowserState } from "../shared/browser";
8
+ import type { BrowserFrame, BrowserState, BrowserVideoSettings } from "../shared/browser";
9
9
  import {
10
10
  beginBrowserGestureRpc,
11
11
  captureBrowserRpc,
12
12
  closeBrowserRpc,
13
13
  endBrowserGestureRpc,
14
+ keepAliveBrowserGestureRpc,
14
15
  MAX_BROWSER_TABS,
15
16
  navigateBrowserRpc,
16
17
  resizeBrowserRpc,
17
18
  sendBrowserInputRpc,
19
+ setBrowserVideoSettingsRpc,
18
20
  setCaptureDensityRpc,
19
21
  updateBrowserGestureRpc,
20
22
  } from "../shared/browser";
@@ -65,6 +67,12 @@ export interface RuntimeOwner<Runtime extends RuntimeInstance = RuntimeInstance>
65
67
  create(workspaceId: string): Promise<Runtime>;
66
68
  request(runtime: Runtime, operation: string, input: JsonValue): Promise<JsonValue>;
67
69
  stop(runtime: Runtime): Promise<void>;
70
+ /** Effective host-wide encoded-video launch option, read fresh on every call. */
71
+ videoSettings?(): Promise<BrowserVideoSettings>;
72
+ /** Persist the choice; it applies to runtimes created afterwards. */
73
+ setVideoEnabled?(enabled: boolean): Promise<void>;
74
+ /** Encoded-video option this runtime was launched with. */
75
+ videoLaunched?(runtime: Runtime): boolean;
68
76
  }
69
77
 
70
78
  export interface RuntimeSupervisorOptions<Runtime extends RuntimeInstance> {
@@ -406,6 +414,14 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
406
414
  throw new RuntimeProtocolError("RUNTIME_FAILURE", "Browser runtime was replaced");
407
415
  this.invalidateAgentObservations(workspaceId);
408
416
  this.revokeAgentControl(workspaceId);
417
+ // The runtime's viewers and targets die with it. Agents reattach to the next runtime's
418
+ // default page; advancing the revision rejects completions begun on the old tab.
419
+ for (const binding of this.agentBindings.values()) {
420
+ if (binding.workspaceId !== workspaceId) continue;
421
+ binding.viewerToken = null;
422
+ binding.tabId = null;
423
+ binding.selectionRevision++;
424
+ }
409
425
  await this.owner.stop(entry.runtime);
410
426
  if (this.workspaces.get(workspaceId) === entry) this.workspaces.delete(workspaceId);
411
427
  });
@@ -495,6 +511,11 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
495
511
  result = await this.browserPolicy.endGesture(endBrowserGestureRpc.input.parse(data));
496
512
  this.invalidateAgentObservationsForState(result);
497
513
  break;
514
+ case "gesture.keepalive":
515
+ result = await this.browserPolicy.keepAliveGesture(
516
+ keepAliveBrowserGestureRpc.input.parse(data),
517
+ );
518
+ break;
498
519
  case "list":
499
520
  result = { workspaceIds: await this.browserPolicy.listOpenWorkspaceIds() };
500
521
  break;
@@ -524,6 +545,25 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
524
545
  result = { archived: true };
525
546
  break;
526
547
  }
548
+ case "video.settings":
549
+ result = await this.videoSettings();
550
+ break;
551
+ case "video.set": {
552
+ const input = setBrowserVideoSettingsRpc.input.parse(data);
553
+ const setVideoEnabled = this.owner.setVideoEnabled?.bind(this.owner);
554
+ if (!setVideoEnabled)
555
+ throw new RuntimeProtocolError(
556
+ "INVALID_REQUEST",
557
+ "Encoded video settings are unavailable",
558
+ );
559
+ await this.browserPolicy.relaunchOpenBrowsers(
560
+ input.viewerToken,
561
+ () => setVideoEnabled(input.enabled),
562
+ () => this.staleVideoRuntimes(),
563
+ );
564
+ result = await this.videoSettings();
565
+ break;
566
+ }
527
567
  default:
528
568
  throw new RuntimeProtocolError(
529
569
  "INVALID_REQUEST",
@@ -534,6 +574,20 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
534
574
  return result as JsonValue;
535
575
  }
536
576
 
577
+ private async videoSettings(): Promise<BrowserVideoSettings> {
578
+ return (await this.owner.videoSettings?.()) ?? { enabled: false, forcedByHost: false };
579
+ }
580
+
581
+ /** Live runtimes launched with an encoded-video option that differs from the effective one. */
582
+ private async staleVideoRuntimes(): Promise<{ workspaceId: string; runtimeId: string }[]> {
583
+ const launched = this.owner.videoLaunched?.bind(this.owner);
584
+ if (!launched) return [];
585
+ const { enabled } = await this.videoSettings();
586
+ return [...this.workspaces]
587
+ .filter(([, entry]) => !entry.lost && launched(entry.runtime) !== enabled)
588
+ .map(([workspaceId, entry]) => ({ workspaceId, runtimeId: entry.runtime.runtimeId }));
589
+ }
590
+
537
591
  private issueAgentTicket(bridgeId: string, epoch: number, ticket: string): JsonValue {
538
592
  this.assertActiveBridge(bridgeId, epoch);
539
593
  this.expireUnboundTickets();
@@ -0,0 +1,331 @@
1
+ import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+ import { SessionManager } from "./browser-policy";
6
+ import { readVideoSettings, VIDEO_PREFERENCE_FILE, writeVideoEnabled } from "./video-preference";
7
+
8
+ const roots: string[] = [];
9
+ async function root() {
10
+ const path = await mkdtemp(join(tmpdir(), "psb-video-"));
11
+ roots.push(path);
12
+ return join(path, "shared-browser");
13
+ }
14
+ afterEach(async () => {
15
+ await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true })));
16
+ });
17
+
18
+ describe("host encoded-video preference", () => {
19
+ it("is disabled when missing or corrupt and persists an atomic choice", async () => {
20
+ const dir = await root();
21
+ expect(await readVideoSettings(dir, {})).toEqual({ enabled: false, forcedByHost: false });
22
+ await writeVideoEnabled(dir, true);
23
+ expect(await readVideoSettings(dir, {})).toEqual({ enabled: true, forcedByHost: false });
24
+ expect(await readdir(dir)).toEqual([VIDEO_PREFERENCE_FILE]);
25
+ expect(JSON.parse(await readFile(join(dir, VIDEO_PREFERENCE_FILE), "utf8"))).toEqual({
26
+ enabled: true,
27
+ });
28
+ await writeFile(join(dir, VIDEO_PREFERENCE_FILE), "{not json");
29
+ expect((await readVideoSettings(dir, {})).enabled).toBe(false);
30
+ await writeFile(join(dir, VIDEO_PREFERENCE_FILE), JSON.stringify({ enabled: "yes" }));
31
+ expect((await readVideoSettings(dir, {})).enabled).toBe(false);
32
+ });
33
+
34
+ it("the daemon environment forces video on over a persisted off", async () => {
35
+ const dir = await root();
36
+ await writeVideoEnabled(dir, false);
37
+ expect(await readVideoSettings(dir, { PASEO_SHARED_BROWSER_VIDEO: "1" })).toEqual({
38
+ enabled: true,
39
+ forcedByHost: true,
40
+ });
41
+ expect(await readVideoSettings(dir, { PASEO_SHARED_BROWSER_VIDEO: "0" })).toEqual({
42
+ enabled: false,
43
+ forcedByHost: false,
44
+ });
45
+ });
46
+ });
47
+
48
+ describe("launch-option relaunch", () => {
49
+ async function fixture() {
50
+ let runtime = 0;
51
+ const closed: string[] = [];
52
+ const control = {
53
+ failClose: false,
54
+ ensureGate: null as Promise<void> | null,
55
+ };
56
+ let counter = 0;
57
+ const manager = new SessionManager({
58
+ validateWorkspace: async () => true,
59
+ issueToken: () => (++counter).toString().padStart(32, "0"),
60
+ client: {
61
+ connect: async () => ({ epoch: 1 }),
62
+ ensureWorkspace: async (workspaceId) => {
63
+ if (control.ensureGate) await control.ensureGate;
64
+ return {
65
+ workspaceId,
66
+ runtimeId: String(++runtime).padStart(32, "r"),
67
+ createdAt: 1,
68
+ };
69
+ },
70
+ requestWorkspace: async (_workspace, operation) => {
71
+ if (operation === "identity") return { userAgent: "Fixture", targetId: "t" };
72
+ if (operation === "state")
73
+ return {
74
+ url: "https://fixture.invalid/",
75
+ title: "",
76
+ canGoBack: false,
77
+ canGoForward: false,
78
+ };
79
+ return null;
80
+ },
81
+ archiveWorkspace: async () => {},
82
+ closeWorkspace: async (_workspace, runtimeId) => {
83
+ if (control.failClose) throw new Error("stop failed");
84
+ closed.push(runtimeId);
85
+ },
86
+ disconnect: () => {},
87
+ },
88
+ });
89
+ await manager.connect();
90
+ return { manager, closed, control };
91
+ }
92
+
93
+ it("relaunches open browsers on change; old tokens read as expired, not closed", async () => {
94
+ const { manager, closed } = await fixture();
95
+ const first = await manager.attach("workspace", "Viewer");
96
+ await manager.relaunchOpenBrowsers(
97
+ first.viewerToken,
98
+ async () => {},
99
+ async () => [{ workspaceId: "workspace", runtimeId: first.state.runtimeId! }],
100
+ );
101
+ expect(closed).toEqual([first.state.runtimeId]);
102
+ await expect(manager.status(first.viewerToken)).rejects.toThrow(
103
+ "Viewer token is invalid or expired",
104
+ );
105
+ const second = await manager.attach("workspace", "Viewer");
106
+ expect(second.state.runtimeId).not.toBe(first.state.runtimeId);
107
+ manager.disconnect();
108
+ });
109
+
110
+ it("does nothing without a stale runtime and refuses an invalid viewer", async () => {
111
+ const { manager, closed } = await fixture();
112
+ const viewer = await manager.attach("workspace", "Viewer");
113
+ let applied = 0;
114
+ await manager.relaunchOpenBrowsers(
115
+ viewer.viewerToken,
116
+ async () => {
117
+ applied += 1;
118
+ },
119
+ async () => [],
120
+ );
121
+ expect(closed).toEqual([]);
122
+ await expect(
123
+ manager.relaunchOpenBrowsers(
124
+ "x".repeat(32),
125
+ async () => {
126
+ applied += 1;
127
+ },
128
+ async () => [{ workspaceId: "workspace", runtimeId: viewer.state.runtimeId! }],
129
+ ),
130
+ ).rejects.toThrow("Viewer token is invalid or expired");
131
+ expect(applied).toBe(1);
132
+ manager.disconnect();
133
+ });
134
+
135
+ it("reports a failed stop and retries the same stale runtime on the next call", async () => {
136
+ const { manager, closed, control } = await fixture();
137
+ const viewer = await manager.attach("workspace", "Viewer");
138
+ const stale = [{ workspaceId: "workspace", runtimeId: viewer.state.runtimeId! }];
139
+ control.failClose = true;
140
+ await expect(
141
+ manager.relaunchOpenBrowsers(
142
+ viewer.viewerToken,
143
+ async () => {},
144
+ async () => stale,
145
+ ),
146
+ ).rejects.toThrow("Some browsers could not be restarted");
147
+ expect(closed).toEqual([]);
148
+ // The failed stop dropped the policy session; the registry still lists the runtime.
149
+ control.failClose = false;
150
+ const retry = await manager.attach("other", "Viewer");
151
+ await manager.relaunchOpenBrowsers(
152
+ retry.viewerToken,
153
+ async () => {},
154
+ async () => stale,
155
+ );
156
+ expect(closed).toEqual([viewer.state.runtimeId]);
157
+ manager.disconnect();
158
+ });
159
+
160
+ it("waits for a first attachment in flight before reading stale runtimes", async () => {
161
+ const { manager, control } = await fixture();
162
+ const viewer = await manager.attach("workspace", "Viewer");
163
+ let release!: () => void;
164
+ control.ensureGate = new Promise<void>((resolve) => {
165
+ release = resolve;
166
+ });
167
+ const pending = manager.attach("late", "Viewer");
168
+ let read = false;
169
+ const relaunch = manager.relaunchOpenBrowsers(
170
+ viewer.viewerToken,
171
+ async () => {},
172
+ async () => {
173
+ read = true;
174
+ return [];
175
+ },
176
+ );
177
+ await new Promise((resolve) => setTimeout(resolve, 10));
178
+ expect(read).toBe(false);
179
+ control.ensureGate = null;
180
+ release();
181
+ await pending;
182
+ await relaunch;
183
+ expect(read).toBe(true);
184
+ manager.disconnect();
185
+ });
186
+ });
187
+
188
+ describe("launch-option relaunch against a live runtime registry", () => {
189
+ /** One current runtime per workspace, like the supervisor; identity can be gated. */
190
+ async function registry() {
191
+ let next = 0;
192
+ const current = new Map<string, string>();
193
+ const stopped: string[] = [];
194
+ const gate = { identity: null as Promise<void> | null, failEnsure: false };
195
+ let counter = 0;
196
+ const manager = new SessionManager({
197
+ validateWorkspace: async () => true,
198
+ issueToken: () => (++counter).toString().padStart(32, "0"),
199
+ client: {
200
+ connect: async () => ({ epoch: 1 }),
201
+ ensureWorkspace: async (workspaceId) => {
202
+ if (gate.failEnsure) throw new Error("launch failed");
203
+ let runtimeId = current.get(workspaceId);
204
+ if (!runtimeId) {
205
+ runtimeId = String(++next).padStart(32, "r");
206
+ current.set(workspaceId, runtimeId);
207
+ }
208
+ return { workspaceId, runtimeId, createdAt: 1 };
209
+ },
210
+ requestWorkspace: async (_workspace, operation, input) => {
211
+ if (operation === "identity") {
212
+ if (gate.identity) await gate.identity;
213
+ const data = (input ?? {}) as { targetId?: string };
214
+ return { userAgent: "Fixture", targetId: data.targetId ?? "root" };
215
+ }
216
+ if (operation === "state")
217
+ return {
218
+ url: "https://fixture.invalid/",
219
+ title: "",
220
+ canGoBack: false,
221
+ canGoForward: false,
222
+ };
223
+ return null;
224
+ },
225
+ archiveWorkspace: async () => {},
226
+ closeWorkspace: async (workspaceId, runtimeId) => {
227
+ if (current.get(workspaceId) === runtimeId) current.delete(workspaceId);
228
+ stopped.push(runtimeId);
229
+ },
230
+ disconnect: () => {},
231
+ },
232
+ });
233
+ await manager.connect();
234
+ return { manager, current, stopped, gate };
235
+ }
236
+
237
+ it("never publishes a page whose creation overlapped the restart of its runtime", async () => {
238
+ const { manager, current, stopped, gate } = await registry();
239
+ const viewer = await manager.attach("workspace", "Viewer");
240
+ const oldRuntime = viewer.state.runtimeId!;
241
+ let release!: () => void;
242
+ let late!: ReturnType<typeof manager.attach>;
243
+ await manager.relaunchOpenBrowsers(
244
+ viewer.viewerToken,
245
+ async () => {},
246
+ async () => {
247
+ // A second-tab attachment starts after the relaunch drained pending creations.
248
+ gate.identity = new Promise<void>((resolve) => {
249
+ release = resolve;
250
+ });
251
+ late = manager.attach("workspace", "Late", "second");
252
+ await new Promise((resolve) => setTimeout(resolve, 0));
253
+ gate.identity = null;
254
+ setTimeout(release, 5);
255
+ return [{ workspaceId: "workspace", runtimeId: oldRuntime }];
256
+ },
257
+ );
258
+ const attached = await late;
259
+ expect(stopped).toEqual([oldRuntime]);
260
+ expect(attached.state.runtimeId).toBe(current.get("workspace"));
261
+ expect(attached.state.runtimeId).not.toBe(oldRuntime);
262
+ manager.disconnect();
263
+ });
264
+
265
+ it("reports a restart whose replacement browser fails to launch", async () => {
266
+ const { manager, gate } = await registry();
267
+ const viewer = await manager.attach("workspace", "Viewer");
268
+ const other = await manager.attach("other", "Viewer");
269
+ await expect(
270
+ manager.relaunchOpenBrowsers(
271
+ other.viewerToken,
272
+ async () => {
273
+ gate.failEnsure = true;
274
+ },
275
+ async () => [{ workspaceId: "workspace", runtimeId: viewer.state.runtimeId! }],
276
+ ),
277
+ ).rejects.toThrow("Some browsers could not be restarted");
278
+ manager.disconnect();
279
+ });
280
+
281
+ it("serializes concurrent identical toggles so the second sees nothing stale", async () => {
282
+ const { manager, current, stopped } = await registry();
283
+ const viewer = await manager.attach("workspace", "Viewer");
284
+ const launchedWith = new Map<string, boolean>([[viewer.state.runtimeId!, false]]);
285
+ let setting = false;
286
+ const stale = async () =>
287
+ [...current].flatMap(([workspaceId, runtimeId]) =>
288
+ (launchedWith.get(runtimeId) ?? setting) !== setting ? [{ workspaceId, runtimeId }] : [],
289
+ );
290
+ const toggle = () =>
291
+ manager.relaunchOpenBrowsers(
292
+ viewer.viewerToken,
293
+ async () => {
294
+ setting = true;
295
+ },
296
+ stale,
297
+ );
298
+ await expect(Promise.all([toggle(), toggle()])).resolves.toBeDefined();
299
+ expect(stopped).toEqual([viewer.state.runtimeId]);
300
+ manager.disconnect();
301
+ });
302
+
303
+ it("drops a queued relaunch when the manager resets while it waits", async () => {
304
+ const { manager } = await registry();
305
+ const viewer = await manager.attach("workspace", "Viewer");
306
+ let release!: () => void;
307
+ const first = manager.relaunchOpenBrowsers(
308
+ viewer.viewerToken,
309
+ () =>
310
+ new Promise<void>((resolve) => {
311
+ release = resolve;
312
+ }),
313
+ async () => [],
314
+ );
315
+ let applied = false;
316
+ const queued = manager.relaunchOpenBrowsers(
317
+ viewer.viewerToken,
318
+ async () => {
319
+ applied = true;
320
+ },
321
+ async () => [],
322
+ );
323
+ await new Promise((resolve) => setTimeout(resolve, 0));
324
+ manager.reset();
325
+ release();
326
+ await first;
327
+ await expect(queued).rejects.toThrow("Shared browser manager was reset");
328
+ expect(applied).toBe(false);
329
+ manager.disconnect();
330
+ });
331
+ });
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Host-wide encoded-video launch option. The capture extension loads only at Chromium
3
+ * launch, so every runtime creation reads the current value instead of a value
4
+ * captured at process start. The daemon environment can force video on; the
5
+ * persisted choice only ever adds it. A missing or corrupt file means disabled.
6
+ */
7
+ import { randomUUID } from "node:crypto";
8
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { z } from "zod";
11
+ import type { BrowserVideoSettings } from "../shared/browser";
12
+
13
+ export const VIDEO_PREFERENCE_FILE = "video-preference.json";
14
+ const VIDEO_ENV = "PASEO_SHARED_BROWSER_VIDEO";
15
+ const videoPreferenceSchema = z.object({ enabled: z.boolean() });
16
+
17
+ export function isVideoForcedByHost(env: NodeJS.ProcessEnv = process.env): boolean {
18
+ return env[VIDEO_ENV] === "1";
19
+ }
20
+
21
+ async function readPersistedVideoEnabled(root: string): Promise<boolean> {
22
+ try {
23
+ const raw = await readFile(join(root, VIDEO_PREFERENCE_FILE), "utf8");
24
+ const parsed = videoPreferenceSchema.safeParse(JSON.parse(raw));
25
+ return parsed.success && parsed.data.enabled;
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+
31
+ export async function readVideoSettings(
32
+ root: string,
33
+ env: NodeJS.ProcessEnv = process.env,
34
+ ): Promise<BrowserVideoSettings> {
35
+ const forcedByHost = isVideoForcedByHost(env);
36
+ return { enabled: forcedByHost || (await readPersistedVideoEnabled(root)), forcedByHost };
37
+ }
38
+
39
+ /** Atomic replace: a reader sees the previous or the next document, never a partial one. */
40
+ export async function writeVideoEnabled(root: string, enabled: boolean): Promise<void> {
41
+ await mkdir(root, { recursive: true, mode: 0o700 });
42
+ const target = join(root, VIDEO_PREFERENCE_FILE);
43
+ const temporary = `${target}.${randomUUID()}.tmp`;
44
+ try {
45
+ await writeFile(temporary, `${JSON.stringify({ enabled })}\n`, { mode: 0o600 });
46
+ await rename(temporary, target);
47
+ } catch (error) {
48
+ await rm(temporary, { force: true });
49
+ throw error;
50
+ }
51
+ }
@@ -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
+ }